/**
  * Tear down test case
  */
 public function tearDown()
 {
     foreach ($this->testFilesToDelete as $absoluteFileName) {
         \TYPO3\CMS\Core\Utility\GeneralUtility::unlink_tempfile($absoluteFileName);
     }
     parent::tearDown();
 }
Ejemplo n.º 2
0
 /**
  * @param string $fileref
  */
 public function download($fileref)
 {
     $extensionConfiguration = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['sharepoint_connector']);
     $extensionConfiguration = \TYPO3\CMS\Core\Utility\GeneralUtility::removeDotsFromTS($extensionConfiguration);
     $filePath = explode(';#', $fileref);
     $urlInfo = parse_url($extensionConfiguration['sharepointServer']['url']);
     $downloadLink = $urlInfo['scheme'] . '://' . $urlInfo['host'] . '/' . $filePath[1];
     $destinationFile = \TYPO3\CMS\Core\Utility\GeneralUtility::tempnam('spdownload_');
     $fp = fopen($destinationFile, 'w+');
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $downloadLink);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
     curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
     curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_NTLM);
     curl_setopt($ch, CURLOPT_USERPWD, $extensionConfiguration['sharepointServer']['username'] . ':' . $extensionConfiguration['sharepointServer']['password']);
     curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
     # increase timeout to download big file
     curl_setopt($ch, CURLOPT_FILE, $fp);
     curl_exec($ch);
     curl_close($ch);
     fclose($fp);
     if (file_exists($destinationFile)) {
         header("Content-Type: application/force-download");
         header("Content-Disposition: attachment; filename=" . basename($downloadLink));
         header("Content-Transfer-Encoding: binary");
         header('Content-Length: ' . filesize($destinationFile));
         ob_clean();
         flush();
         readfile($destinationFile);
     }
     \TYPO3\CMS\Core\Utility\GeneralUtility::unlink_tempfile($destinationFile);
 }
Ejemplo n.º 3
0
 public function tearDown()
 {
     \TYPO3\CMS\Core\Extension\ExtensionManager::clearExtensionKeyMap();
     foreach ($this->globals as $key => $value) {
         $GLOBALS[$key] = unserialize($value);
     }
     foreach ($this->testFilesToDelete as $absoluteFileName) {
         \TYPO3\CMS\Core\Utility\GeneralUtility::unlink_tempfile($absoluteFileName);
     }
     \TYPO3\CMS\Core\Utility\GeneralUtility::purgeInstances();
 }
 public function tearDown()
 {
     ExtensionManagementUtility::clearExtensionKeyMap();
     foreach ($this->testFilesToDelete as $absoluteFileName) {
         \TYPO3\CMS\Core\Utility\GeneralUtility::unlink_tempfile($absoluteFileName);
     }
     if (file_exists(PATH_site . 'typo3temp/test_ext/')) {
         \TYPO3\CMS\Core\Utility\GeneralUtility::rmdir(PATH_site . 'typo3temp/test_ext/', TRUE);
     }
     ExtensionManagementUtilityAccessibleProxy::setPackageManager($this->backUpPackageManager);
     ExtensionManagementUtilityAccessibleProxy::setCacheManager(NULL);
     $GLOBALS['TYPO3_LOADED_EXT'] = new \TYPO3\CMS\Core\Compatibility\LoadedExtensionsArray($this->backUpPackageManager);
     \TYPO3\CMS\Core\Utility\GeneralUtility::resetSingletonInstances($this->singletonInstances);
     parent::tearDown();
 }
Ejemplo n.º 5
0
 /**
  * Main function. Called from TypoScript.
  * This
  * - initializes internal variables,
  * - fills in the markerArray with default substitution string
  * - saves/emails if such commands are sent
  * - calls functions for display of the screen for editing/creation/deletion etc.
  *
  * @param string $content Empty string, ignore.
  * @param array $conf TypoScript properties following the USER_INT object which uses this library
  *
  * @return string HTML content
  */
 public function init($content, $conf)
 {
     $this->conf = $conf;
     // template file is fetched.
     $this->templateCode = $this->conf['templateContent'] ? $this->conf['templateContent'] : $this->cObj->fileResource($this->conf['templateFile']);
     // Getting the cmd var
     $this->cmd = (string) GeneralUtility::_GP('cmd');
     // Getting the preview var
     $this->preview = (string) GeneralUtility::_GP('preview');
     // backURL is a given URL to return to when login is performed
     $this->backURL = GeneralUtility::_GP('backURL');
     if (strstr($this->backURL, '"') || strstr($this->backURL, "'") || preg_match('/(javascript|vbscript):/i', $this->backURL) || stristr($this->backURL, "fromcharcode") || strstr($this->backURL, "<") || strstr($this->backURL, ">")) {
         $this->backURL = '';
         // Clear backURL if it seems to contain XSS code - only URLs are allowed
     }
     // Remove host from URL: Make sure that $this->backURL maps to the current site
     $this->backURL = preg_replace('|[A-Za-z]+://[^/]+|', '', $this->backURL);
     // Uid to edit:
     $this->recUid = GeneralUtility::_GP('rU');
     // Authentication code:
     $this->authCode = GeneralUtility::_GP('aC');
     // get table
     $this->theTable = $this->conf['table'];
     // link configuration
     $linkConf = is_array($this->conf['formurl.']) ? $this->conf['formurl.'] : [];
     // pid
     $this->thePid = intval($this->conf['pid']) ? intval($this->conf['pid']) : $this->getTypoScriptFrontendController()->id;
     //
     $this->codeLength = intval($this->conf['authcodeFields.']['codeLength']) ? intval($this->conf['authcodeFields.']['codeLength']) : 8;
     // Setting the hardcoded lists of fields allowed for editing and creation.
     $this->fieldList = implode(',', GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$this->theTable]['feInterface']['fe_admin_fieldList'], 1));
     // globally substituted markers, fonts and colors.
     $splitMark = md5(microtime());
     list($this->markerArray['###GW1B###'], $this->markerArray['###GW1E###']) = explode($splitMark, $this->cObj->stdWrap($splitMark, $this->conf['wrap1.']));
     list($this->markerArray['###GW2B###'], $this->markerArray['###GW2E###']) = explode($splitMark, $this->cObj->stdWrap($splitMark, $this->conf['wrap2.']));
     $this->markerArray['###GC1###'] = $this->cObj->stdWrap($this->conf['color1'], $this->conf['color1.']);
     $this->markerArray['###GC2###'] = $this->cObj->stdWrap($this->conf['color2'], $this->conf['color2.']);
     $this->markerArray['###GC3###'] = $this->cObj->stdWrap($this->conf['color3'], $this->conf['color3.']);
     if (intval($this->conf['no_cache']) && !isset($linkConf['no_cache'])) {
         // needed for backwards compatibility
         $linkConf['no_cache'] = 1;
     }
     if (!$linkConf['parameter']) {
         $linkConf['parameter'] = $this->getTypoScriptFrontendController()->id;
     }
     if (!$linkConf['additionalParams']) {
         // needed for backwards compatibility
         $linkConf['additionalParams'] = $this->conf['addParams'];
     }
     $formURL = $this->cObj->typoLink_URL($linkConf);
     if (!strstr($formURL, '?')) {
         $formURL .= '?';
     }
     // Initialize markerArray, setting FORM_URL and HIDDENFIELDS
     $this->markerArray['###FORM_URL###'] = $formURL;
     $this->markerArray['###FORM_URL_ENC###'] = rawurlencode($this->markerArray['###FORM_URL###']);
     $this->markerArray['###FORM_URL_HSC###'] = htmlspecialchars($this->markerArray['###FORM_URL###']);
     $this->markerArray['###BACK_URL###'] = $this->backURL;
     $this->markerArray['###BACK_URL_ENC###'] = rawurlencode($this->markerArray['###BACK_URL###']);
     $this->markerArray['###BACK_URL_HSC###'] = htmlspecialchars($this->markerArray['###BACK_URL###']);
     $this->markerArray['###THE_PID###'] = $this->thePid;
     $this->markerArray['###REC_UID###'] = $this->recUid;
     $this->markerArray['###AUTH_CODE###'] = $this->authCode;
     $this->markerArray['###THIS_ID###'] = $this->getTypoScriptFrontendController()->id;
     $this->markerArray['###THIS_URL###'] = htmlspecialchars(GeneralUtility::getIndpEnv('TYPO3_SITE_URL'));
     $this->markerArray['###HIDDENFIELDS###'] = ($this->cmd ? '<input type="hidden" name="cmd" value="' . htmlspecialchars($this->cmd) . '" />' : '') . ($this->authCode ? '<input type="hidden" name="aC" value="' . htmlspecialchars($this->authCode) . '" />' : '') . ($this->backURL ? '<input type="hidden" name="backURL" value="' . htmlspecialchars($this->backURL) . '" />' : '');
     // Setting cmdKey which is either 'edit' or 'create'
     switch ($this->cmd) {
         case 'edit':
             $this->cmdKey = 'edit';
             break;
         default:
             $this->cmdKey = 'create';
             break;
     }
     // Setting requiredArr to the fields in 'required' intersected field the total field list in order to remove invalid fields.
     $this->requiredArr = array_intersect(GeneralUtility::trimExplode(',', $this->conf[$this->cmdKey . '.']['required'], 1), GeneralUtility::trimExplode(',', $this->conf[$this->cmdKey . '.']['fields'], 1));
     // Setting incoming data. Non-stripped
     $fe = GeneralUtility::_GP('FE');
     $this->dataArr = $fe[$this->theTable];
     // Incoming data.
     // Checking template file and table value
     if (!$this->templateCode) {
         $content = 'No template file found: ' . $this->conf['templateFile'];
         return $content;
     }
     if (!$this->theTable || !$this->fieldList) {
         $content = 'Wrong table: ' . $this->theTable;
         return $content;
         // Not listed or editable table!
     }
     // *****************
     // If data is submitted, we take care of it here.
     // *******************
     if ($this->cmd == 'delete' && !$this->preview && !GeneralUtility::_GP('doNotSave')) {
         // Delete record if delete command is sent + the preview flag is NOT set.
         $this->deleteRecord();
     }
     // If incoming data is seen...
     if (is_array($this->dataArr) && count(ArrayUtility::removeArrayEntryByValue(array_keys($this->dataArr), 'captcha'))) {
         // Evaluation of data:
         $this->parseValues();
         $this->overrideValues();
         $this->evalValues();
         if ($this->conf['evalFunc']) {
             $this->dataArr = $this->userProcess('evalFunc', $this->dataArr);
         }
         /*
         debug($this->dataArr);
         debug($this->failure);
         debug($this->preview);
         */
         // if not preview and no failures, then set data...
         if (!$this->failure && !$this->preview && !GeneralUtility::_GP('doNotSave')) {
             // doNotSave is a global var (eg a 'Cancel' submit button) that prevents the data from being processed
             $this->save();
         } else {
             if ($this->conf['debug']) {
                 debug($this->failure);
             }
         }
     } else {
         $this->defaultValues();
         // If no incoming data, this will set the default values.
         $this->preview = 0;
         // No preview if data is not received
     }
     if ($this->failure) {
         $this->preview = 0;
     }
     // No preview flag if a evaluation failure has occured
     $this->previewLabel = $this->preview ? '_PREVIEW' : '';
     // Setting preview label prefix.
     // *********************
     // DISPLAY FORMS:
     // ***********************
     if ($this->saved) {
         // Clear page cache
         $this->clearCacheIfSet();
         $this->setNoCacheHeader();
         // Displaying the page here that says, the record has been saved. You're able to include the saved values by markers.
         switch ($this->cmd) {
             case 'delete':
                 $key = 'DELETE';
                 break;
             case 'edit':
                 $key = 'EDIT';
                 break;
             default:
                 $key = 'CREATE';
                 break;
         }
         // Output message
         $templateCode = $this->cObj->getSubpart($this->templateCode, '###TEMPLATE_' . $key . '_SAVED###');
         $this->setCObjects($templateCode, $this->currentArr);
         $markerArray = $this->cObj->fillInMarkerArray($this->markerArray, $this->currentArr, '', true, 'FIELD_', $this->recInMarkersHSC);
         $content = $this->cObj->substituteMarkerArray($templateCode, $markerArray);
         // email message:
         $this->compileMail($key . '_SAVED', [$this->currentArr], $this->currentArr[$this->conf['email.']['field']], $this->conf['setfixed.']);
     } elseif ($this->error) {
         // If there was an error, we return the template-subpart with the error message
         $templateCode = $this->cObj->getSubpart($this->templateCode, $this->error);
         $this->setCObjects($templateCode);
         $content = $this->cObj->substituteMarkerArray($templateCode, $this->markerArray);
     } else {
         // Finally, if there has been no attempt to save. That is either preview or just displaying and empty or not correctly filled form:
         if (!$this->cmd) {
             $this->cmd = $this->conf['defaultCmd'];
         }
         if ($this->conf['debug']) {
             debug('Display form: ' . $this->cmd, 1);
         }
         switch ($this->cmd) {
             case 'setfixed':
                 $content = $this->procesSetFixed();
                 break;
             case 'infomail':
                 $content = $this->sendInfoMail();
                 break;
             case 'delete':
                 $content = $this->displayDeleteScreen();
                 break;
             case 'edit':
                 $content = $this->displayEditScreen();
                 break;
             case 'create':
                 $content = $this->displayCreateScreen();
                 break;
         }
     }
     // Delete temp files:
     foreach ($this->unlinkTempFiles as $tempFileName) {
         GeneralUtility::unlink_tempfile($tempFileName);
     }
     // Return content:
     return $content;
 }
 /**
  * Do some cleanup at the end (deleting attachment files)
  */
 public function __destruct()
 {
     foreach ($this->temporaryFiles as $file) {
         if (\TYPO3\CMS\Core\Utility\GeneralUtility::isAllowedAbsPath($file) && \TYPO3\CMS\Core\Utility\GeneralUtility::isFirstPartOfStr($file, PATH_site . 'typo3temp/upload_temp_')) {
             \TYPO3\CMS\Core\Utility\GeneralUtility::unlink_tempfile($file);
         }
     }
 }
Ejemplo n.º 7
0
 /**
  * Handler for the content of a tag
  */
 public function spellCheckHandler($xml_parser, $string)
 {
     $incurrent = array();
     $stringText = $string;
     $words = preg_split($this->parserCharset == 'utf-8' ? '/\\P{L}+/u' : '/\\W+/', $stringText);
     foreach ($words as $word) {
         $word = preg_replace('/ /' . ($this->parserCharset == 'utf-8' ? 'u' : ''), '', $word);
         if ($word && !is_numeric($word)) {
             if ($this->pspell_is_available && !$this->forceCommandMode) {
                 if (!pspell_check($this->pspell_link, $word)) {
                     if (!in_array($word, $this->misspelled)) {
                         if (sizeof($this->misspelled) != 0) {
                             $this->suggestedWords .= ',';
                         }
                         $suggest = array();
                         $suggest = pspell_suggest($this->pspell_link, $word);
                         if (sizeof($suggest) != 0) {
                             $this->suggestionCount++;
                             $this->suggestedWordCount += sizeof($suggest);
                         }
                         $this->suggestedWords .= '"' . $word . '":"' . implode(',', $suggest) . '"';
                         $this->misspelled[] = $word;
                         unset($suggest);
                     }
                     if (!in_array($word, $incurrent)) {
                         $stringText = preg_replace('/\\b' . $word . '\\b/' . ($this->parserCharset == 'utf-8' ? 'u' : ''), '<span class="htmlarea-spellcheck-error">' . $word . '</span>', $stringText);
                         $incurrent[] = $word;
                     }
                 }
             } else {
                 $tmpFileName = GeneralUtility::tempnam($this->filePrefix);
                 if (!($filehandle = fopen($tmpFileName, 'wb'))) {
                     echo 'SpellChecker tempfile open error';
                 }
                 if (!fwrite($filehandle, $word)) {
                     echo 'SpellChecker tempfile write error';
                 }
                 if (!fclose($filehandle)) {
                     echo 'SpellChecker tempfile close error';
                 }
                 $catCommand = TYPO3_OS === 'WIN' ? 'type' : 'cat';
                 $AspellCommand = $catCommand . ' ' . escapeshellarg($tmpFileName) . ' | ' . $this->AspellDirectory . ' -a check' . ' --mode=none' . ' --sug-mode=' . escapeshellarg($this->pspellMode) . ($this->personalDictionaryPath ? ' --home-dir=' . escapeshellarg($this->personalDictionaryPath) : '') . ' --lang=' . escapeshellarg($this->dictionary) . ' --encoding=' . escapeshellarg($this->aspellEncoding) . ' 2>&1';
                 $AspellAnswer = shell_exec($AspellCommand);
                 $AspellResultLines = array();
                 $AspellResultLines = GeneralUtility::trimExplode(LF, $AspellAnswer, TRUE);
                 if (substr($AspellResultLines[0], 0, 6) == 'Error:') {
                     echo '{' . $AspellAnswer . '}';
                 }
                 GeneralUtility::unlink_tempfile($tmpFileName);
                 if ($AspellResultLines['1'][0] !== '*') {
                     if (!in_array($word, $this->misspelled)) {
                         if (sizeof($this->misspelled) != 0) {
                             $this->suggestedWords .= ',';
                         }
                         $suggest = array();
                         $suggestions = array();
                         if ($AspellResultLines['1'][0] === '&') {
                             $suggestions = GeneralUtility::trimExplode(':', $AspellResultLines['1'], TRUE);
                             $suggest = GeneralUtility::trimExplode(',', $suggestions['1'], TRUE);
                         }
                         if (sizeof($suggest) != 0) {
                             $this->suggestionCount++;
                             $this->suggestedWordCount += sizeof($suggest);
                         }
                         $this->suggestedWords .= '"' . $word . '":"' . implode(',', $suggest) . '"';
                         $this->misspelled[] = $word;
                         unset($suggest);
                         unset($suggestions);
                     }
                     if (!in_array($word, $incurrent)) {
                         $stringText = preg_replace('/\\b' . $word . '\\b/' . ($this->parserCharset == 'utf-8' ? 'u' : ''), '<span class="htmlarea-spellcheck-error">' . $word . '</span>', $stringText);
                         $incurrent[] = $word;
                     }
                 }
                 unset($AspellResultLines);
             }
             $this->wordCount++;
         }
     }
     $this->text .= $stringText;
     unset($incurrent);
 }
 /**
  * This method actually does the processing of files locally
  *
  * Takes the original file (for remote storages this will be fetched from the remote server),
  * does the IM magic on the local server by creating a temporary typo3temp/ file,
  * copies the typo3temp/ file to the processing folder of the target storage and
  * removes the typo3temp/ file.
  *
  * The returned array has the following structure:
  *   width => 100
  *   height => 200
  *   filePath => /some/path
  *
  * If filePath isn't set but width and height are the original file is used as ProcessedFile
  * with the returned width and height. This is for example useful for SVG images.
  *
  * @param TaskInterface $task
  * @return array|NULL
  */
 public function process(TaskInterface $task)
 {
     $result = null;
     $targetFile = $task->getTargetFile();
     $sourceFile = $task->getSourceFile();
     $originalFileName = $sourceFile->getForLocalProcessing(false);
     /** @var $gifBuilder GifBuilder */
     $gifBuilder = GeneralUtility::makeInstance(GifBuilder::class);
     $gifBuilder->init();
     $gifBuilder->absPrefix = PATH_site;
     $configuration = $targetFile->getProcessingConfiguration();
     $configuration['additionalParameters'] = $this->modifyImageMagickStripProfileParameters($configuration['additionalParameters'], $configuration);
     if (empty($configuration['fileExtension'])) {
         $configuration['fileExtension'] = $task->getTargetFileExtension();
     }
     $options = $this->getConfigurationForImageCropScaleMask($targetFile, $gifBuilder);
     $croppedImage = null;
     if (!empty($configuration['crop'])) {
         // check if it is a json object
         $cropData = json_decode($configuration['crop']);
         if ($cropData) {
             $crop = implode(',', array((int) $cropData->x, (int) $cropData->y, (int) $cropData->width, (int) $cropData->height));
         } else {
             $crop = $configuration['crop'];
         }
         list($offsetLeft, $offsetTop, $newWidth, $newHeight) = explode(',', $crop, 4);
         $backupPrefix = $gifBuilder->filenamePrefix;
         $gifBuilder->filenamePrefix = 'crop_';
         // the result info is an array with 0=width,1=height,2=extension,3=filename
         $result = $gifBuilder->imageMagickConvert($originalFileName, '', '', '', sprintf('-crop %dx%d+%d+%d', $newWidth, $newHeight, $offsetLeft, $offsetTop), '', ['noScale' => true], true);
         $gifBuilder->filenamePrefix = $backupPrefix;
         if ($result !== null) {
             $originalFileName = $croppedImage = $result[3];
         }
     }
     // Normal situation (no masking)
     if (!(is_array($configuration['maskImages']) && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im'])) {
         // SVG
         if ($croppedImage === null && $sourceFile->getExtension() === 'svg') {
             $newDimensions = $this->getNewSvgDimensions($sourceFile, $configuration, $options, $gifBuilder);
             $result = array(0 => $newDimensions['width'], 1 => $newDimensions['height'], 3 => '');
             // all other images
         } else {
             // the result info is an array with 0=width,1=height,2=extension,3=filename
             $result = $gifBuilder->imageMagickConvert($originalFileName, $configuration['fileExtension'], $configuration['width'], $configuration['height'], $configuration['additionalParameters'], $configuration['frame'], $options);
         }
     } else {
         $targetFileName = $this->getFilenameForImageCropScaleMask($task);
         $temporaryFileName = $gifBuilder->tempPath . $targetFileName;
         $maskImage = $configuration['maskImages']['maskImage'];
         $maskBackgroundImage = $configuration['maskImages']['backgroundImage'];
         if ($maskImage instanceof Resource\FileInterface && $maskBackgroundImage instanceof Resource\FileInterface) {
             $temporaryExtension = 'png';
             if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['im_mask_temp_ext_gif']) {
                 // If ImageMagick version 5+
                 $temporaryExtension = $gifBuilder->gifExtension;
             }
             $tempFileInfo = $gifBuilder->imageMagickConvert($originalFileName, $temporaryExtension, $configuration['width'], $configuration['height'], $configuration['additionalParameters'], $configuration['frame'], $options);
             if (is_array($tempFileInfo)) {
                 $maskBottomImage = $configuration['maskImages']['maskBottomImage'];
                 if ($maskBottomImage instanceof Resource\FileInterface) {
                     $maskBottomImageMask = $configuration['maskImages']['maskBottomImageMask'];
                 } else {
                     $maskBottomImageMask = null;
                 }
                 //	Scaling:	****
                 $tempScale = array();
                 $command = '-geometry ' . $tempFileInfo[0] . 'x' . $tempFileInfo[1] . '!';
                 $command = $this->modifyImageMagickStripProfileParameters($command, $configuration);
                 $tmpStr = $gifBuilder->randomName();
                 //	m_mask
                 $tempScale['m_mask'] = $tmpStr . '_mask.' . $temporaryExtension;
                 $gifBuilder->imageMagickExec($maskImage->getForLocalProcessing(true), $tempScale['m_mask'], $command);
                 //	m_bgImg
                 $tempScale['m_bgImg'] = $tmpStr . '_bgImg.miff';
                 $gifBuilder->imageMagickExec($maskBackgroundImage->getForLocalProcessing(), $tempScale['m_bgImg'], $command);
                 //	m_bottomImg / m_bottomImg_mask
                 if ($maskBottomImage instanceof Resource\FileInterface && $maskBottomImageMask instanceof Resource\FileInterface) {
                     $tempScale['m_bottomImg'] = $tmpStr . '_bottomImg.' . $temporaryExtension;
                     $gifBuilder->imageMagickExec($maskBottomImage->getForLocalProcessing(), $tempScale['m_bottomImg'], $command);
                     $tempScale['m_bottomImg_mask'] = $tmpStr . '_bottomImg_mask.' . $temporaryExtension;
                     $gifBuilder->imageMagickExec($maskBottomImageMask->getForLocalProcessing(), $tempScale['m_bottomImg_mask'], $command);
                     // BEGIN combining:
                     // The image onto the background
                     $gifBuilder->combineExec($tempScale['m_bgImg'], $tempScale['m_bottomImg'], $tempScale['m_bottomImg_mask'], $tempScale['m_bgImg']);
                 }
                 // The image onto the background
                 $gifBuilder->combineExec($tempScale['m_bgImg'], $tempFileInfo[3], $tempScale['m_mask'], $temporaryFileName);
                 $tempFileInfo[3] = $temporaryFileName;
                 // Unlink the temp-images...
                 foreach ($tempScale as $tempFile) {
                     if (@is_file($tempFile)) {
                         unlink($tempFile);
                     }
                 }
             }
             $result = $tempFileInfo;
         }
     }
     // check if the processing really generated a new file (scaled and/or cropped)
     if ($result !== null) {
         if ($result[3] !== $originalFileName || $originalFileName === $croppedImage) {
             $result = array('width' => $result[0], 'height' => $result[1], 'filePath' => $result[3]);
         } else {
             // No file was generated
             $result = null;
         }
     }
     // Cleanup temp file if it isn't used as result
     if ($croppedImage && ($result === null || $croppedImage !== $result['filePath'])) {
         GeneralUtility::unlink_tempfile($croppedImage);
     }
     return $result;
 }
Ejemplo n.º 9
0
 /**
  * @test
  */
 public function unlink_tempfileReturnsNullIfFileIsNowWithinTypo3temp()
 {
     $returnValue = GeneralUtility::unlink_tempfile('/tmp/typo3-unit-test-unlink_tempfile');
     $this->assertNull($returnValue);
 }
 /**
  * @test
  */
 public function filelinkCreatesCorrectUrlForFileWithUrlEncodedSpecialChars()
 {
     $fileNameAndPath = PATH_site . 'typo3temp/var/tests/phpunitJumpUrlTestFile with spaces & amps.txt';
     file_put_contents($fileNameAndPath, 'Some test data');
     $relativeFileNameAndPath = substr($fileNameAndPath, strlen(PATH_site));
     $fileName = substr($fileNameAndPath, strlen(PATH_site . 'typo3temp/var/tests/'));
     $expectedLink = str_replace('%2F', '/', rawurlencode($relativeFileNameAndPath));
     $result = $this->subject->filelink($fileName, array('path' => 'typo3temp/var/tests/'));
     $this->assertEquals('<a href="' . $expectedLink . '">' . $fileName . '</a>', $result);
     \TYPO3\CMS\Core\Utility\GeneralUtility::unlink_tempfile($fileNameAndPath);
 }
Ejemplo n.º 11
0
 /**
  * Process file
  * Create static image preview for Online Media item when possible
  *
  * @param FileProcessingService $fileProcessingService
  * @param AbstractDriver $driver
  * @param ProcessedFile $processedFile
  * @param File $file
  * @param string $taskType
  * @param array $configuration
  */
 public function processFile(FileProcessingService $fileProcessingService, AbstractDriver $driver, ProcessedFile $processedFile, File $file, $taskType, array $configuration)
 {
     if ($taskType !== 'Image.Preview' && $taskType !== 'Image.CropScaleMask') {
         return;
     }
     // Check if processing is needed
     if (!$this->needsReprocessing($processedFile)) {
         return;
     }
     // Check if there is a OnlineMediaHelper registered for this file type
     $helper = OnlineMediaHelperRegistry::getInstance()->getOnlineMediaHelper($file);
     if ($helper === false) {
         return;
     }
     // Check if helper provides a preview image
     $temporaryFileName = $helper->getPreviewImage($file);
     if (empty($temporaryFileName) || !file_exists($temporaryFileName)) {
         return;
     }
     $temporaryFileNameForResizedThumb = uniqid(PATH_site . 'typo3temp/var/transient/online_media_' . $file->getHashedIdentifier()) . '.jpg';
     switch ($taskType) {
         case 'Image.Preview':
             // Merge custom configuration with default configuration
             $configuration = array_merge(array('width' => 64, 'height' => 64), $configuration);
             $configuration['width'] = MathUtility::forceIntegerInRange($configuration['width'], 1, 1000);
             $configuration['height'] = MathUtility::forceIntegerInRange($configuration['height'], 1, 1000);
             $this->resizeImage($temporaryFileName, $temporaryFileNameForResizedThumb, $configuration);
             break;
         case 'Image.CropScaleMask':
             $this->cropScaleImage($temporaryFileName, $temporaryFileNameForResizedThumb, $configuration);
             break;
     }
     GeneralUtility::unlink_tempfile($temporaryFileName);
     if (is_file($temporaryFileNameForResizedThumb)) {
         $processedFile->setName($this->getTargetFileName($processedFile));
         list($width, $height) = getimagesize($temporaryFileNameForResizedThumb);
         $processedFile->updateProperties(array('width' => $width, 'height' => $height, 'size' => filesize($temporaryFileNameForResizedThumb), 'checksum' => $processedFile->getTask()->getConfigurationChecksum()));
         $processedFile->updateWithLocalFile($temporaryFileNameForResizedThumb);
         GeneralUtility::unlink_tempfile($temporaryFileNameForResizedThumb);
         /** @var ProcessedFileRepository $processedFileRepository */
         $processedFileRepository = GeneralUtility::makeInstance(ProcessedFileRepository::class);
         $processedFileRepository->add($processedFile);
     }
 }
Ejemplo n.º 12
0
 protected function handleUpload($property, $uploadDir, $filename, &$path, $maxSize = '2097152', $filetypes = "jpg,png")
 {
     $data = $_FILES['tx_' . strtolower($this->request->getControllerExtensionName()) . '_' . strtolower($this->request->getPluginName())];
     if (is_array($data) && count($data) > 0) {
         $propertyPath = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode('.', $property);
         $namePath = $data['name'];
         $tmpPath = $data['tmp_name'];
         $sizePath = $data['size'];
         foreach ($propertyPath as $segment) {
             $namePath = $namePath[$segment];
             $tmpPath = $tmpPath[$segment];
             $sizePath = $sizePath[$segment];
         }
         if ($namePath !== NULL && $namePath !== '') {
             $fileArray = array('name' => $namePath, 'tmp' => $tmpPath, 'size' => $sizePath);
         } else {
             return 1;
         }
     } else {
         return 0;
     }
     if ($fileArray['size'] > $maxSize) {
         return 2;
     }
     $fileInfo = pathinfo($fileArray['name']);
     if (!\TYPO3\CMS\Core\Utility\GeneralUtility::inList($filetypes, strtolower($fileInfo['extension']))) {
         return 3;
     }
     if (file_exists(PATH_site . $uploadDir . $filename)) {
         $filename = $filename . '-' . time() . '.' . $fileInfo['extension'];
     }
     if (\TYPO3\CMS\Core\Utility\GeneralUtility::upload_copy_move($fileArray['tmp'], PATH_site . $uploadDir . $filename . '.' . $fileInfo['extension'])) {
         $path = $filename . '.' . $fileInfo['extension'];
         return 0;
     } else {
         \TYPO3\CMS\Core\Utility\GeneralUtility::unlink_tempfile($fileArray['tmp']);
         return 4;
     }
 }
Ejemplo n.º 13
0
 /**
  * Remove uploaded files from the typo3temp
  *
  * @return void
  */
 protected function removeFiles()
 {
     $sessionData = $this->getSessionData();
     if (is_array($sessionData)) {
         foreach ($sessionData as $fieldName => $values) {
             if (is_array($values)) {
                 foreach ($values as $file) {
                     if (isset($file['tempFilename'])) {
                         GeneralUtility::unlink_tempfile($file['tempFilename']);
                     }
                 }
             }
         }
     }
 }
Ejemplo n.º 14
0
 public static function removePublicTempFile($temp)
 {
     GeneralUtility::unlink_tempfile($temp['name']);
 }
 /**
  * Create new OnlineMedia item container file.
  * This is created inside typo3temp/ and then moved from FAL to the proper storage.
  *
  * @param Folder $targetFolder
  * @param string $fileName
  * @param string $onlineMediaId
  * @return File
  */
 protected function createNewFile(Folder $targetFolder, $fileName, $onlineMediaId)
 {
     $temporaryFile = GeneralUtility::tempnam('online_media');
     GeneralUtility::writeFileToTypo3tempDir($temporaryFile, $onlineMediaId);
     $file = $targetFolder->addFile($temporaryFile, $fileName, DuplicationBehavior::RENAME);
     GeneralUtility::unlink_tempfile($temporaryFile);
     return $file;
 }
Ejemplo n.º 16
0
 /**
  * @test
  */
 public function typoLinkCreatesCorrectSecureJumpUrlForFile()
 {
     $testData = $this->initializeJumpUrlTestEnvironment();
     $fileNameAndPath = PATH_site . 'typo3temp/phpunitJumpUrlTestFile.txt';
     file_put_contents($fileNameAndPath, 'Some test data');
     $relativeFileNameAndPath = substr($fileNameAndPath, strlen(PATH_site));
     $testAddress = $relativeFileNameAndPath;
     $expectedHash = '1933f3c181db8940acfcd4d16c74643947179948';
     $expectedUrl = $testData['absRefPrefix'] . $testData['mainScript'] . '?id=' . $testData['pageId'] . '&type=' . $testData['pageType'] . '&jumpurl=' . rawurlencode($testAddress) . '&juSecure=1&locationData=' . rawurlencode($testData['locationData']) . '&juHash=' . $expectedHash;
     $generatedUrl = $this->subject->typoLink_URL(array('parameter' => $testAddress, 'jumpurl.' => array('secure' => 1)));
     $this->assertEquals($expectedUrl, $generatedUrl);
     GeneralUtility::unlink_tempfile($fileNameAndPath);
 }
    /**
     * Import part of module
     *
     * @param array $inData Content of POST VAR tx_impexp[]..
     * @return void Setting content in $this->content
     * @todo Define visibility
     */
    public function importData($inData)
    {
        global $LANG;
        $access = is_array($this->pageinfo) ? 1 : 0;
        if ($this->id && $access || $GLOBALS['BE_USER']->user['admin'] && !$this->id) {
            if ($GLOBALS['BE_USER']->user['admin'] && !$this->id) {
                $this->pageinfo = array('title' => '[root-level]', 'uid' => 0, 'pid' => 0);
            }
            if ($inData['new_import']) {
                unset($inData['import_mode']);
            }
            /** @var $import \TYPO3\CMS\Impexp\ImportExport */
            $import = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Impexp\\ImportExport');
            $import->init(0, 'import');
            $import->update = $inData['do_update'];
            $import->import_mode = $inData['import_mode'];
            $import->enableLogging = $inData['enableLogging'];
            $import->global_ignore_pid = $inData['global_ignore_pid'];
            $import->force_all_UIDS = $inData['force_all_UIDS'];
            $import->showDiff = !$inData['notShowDiff'];
            $import->allowPHPScripts = $inData['allowPHPScripts'];
            $import->softrefInputValues = $inData['softrefInputValues'];
            // OUTPUT creation:
            $menuItems = array();
            // Make input selector:
            // must have trailing slash.
            $path = $GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'];
            $filesInDir = \TYPO3\CMS\Core\Utility\GeneralUtility::getFilesInDir(PATH_site . $path, 't3d,xml', 1, 1);
            $userPath = $this->userSaveFolder();
            //Files from User-Dir
            $filesInUserDir = \TYPO3\CMS\Core\Utility\GeneralUtility::getFilesInDir($userPath, 't3d,xml', 1, 1);
            $filesInDir = array_merge($filesInUserDir, $filesInDir);
            if (is_dir(PATH_site . $path . 'export/')) {
                $filesInDir = array_merge($filesInDir, \TYPO3\CMS\Core\Utility\GeneralUtility::getFilesInDir(PATH_site . $path . 'export/', 't3d,xml', 1, 1));
            }
            $tempFolder = $this->userTempFolder();
            if ($tempFolder) {
                $temp_filesInDir = \TYPO3\CMS\Core\Utility\GeneralUtility::getFilesInDir($tempFolder, 't3d,xml', 1, 1);
                $filesInDir = array_merge($filesInDir, $temp_filesInDir);
            }
            // Configuration
            $row = array();
            $opt = array('');
            foreach ($filesInDir as $file) {
                $opt[$file] = substr($file, strlen(PATH_site));
            }
            $row[] = '<tr class="bgColor5">
					<td colspan="2"><strong>' . $LANG->getLL('importdata_selectFileToImport', 1) . '</strong></td>
				</tr>';
            $row[] = '<tr class="bgColor4">
				<td><strong>' . $LANG->getLL('importdata_file', 1) . '</strong>' . \TYPO3\CMS\Backend\Utility\BackendUtility::cshItem('xMOD_tx_impexp', 'importFile', $GLOBALS['BACK_PATH'], '') . '</td>
				<td>' . $this->renderSelectBox('tx_impexp[file]', $inData['file'], $opt) . '<br />' . sprintf($LANG->getLL('importdata_fromPathS', 1), $path) . (!$import->compress ? '<br /><span class="typo3-red">' . $LANG->getLL('importdata_noteNoDecompressorAvailable', 1) . '</span>' : '') . '</td>
				</tr>';
            $row[] = '<tr class="bgColor5">
					<td colspan="2"><strong>' . $LANG->getLL('importdata_importOptions', 1) . '</strong></td>
				</tr>';
            $row[] = '<tr class="bgColor4">
				<td><strong>' . $LANG->getLL('importdata_update', 1) . '</strong>' . \TYPO3\CMS\Backend\Utility\BackendUtility::cshItem('xMOD_tx_impexp', 'update', $GLOBALS['BACK_PATH'], '') . '</td>
				<td>
					<input type="checkbox" name="tx_impexp[do_update]" id="checkDo_update" value="1"' . ($inData['do_update'] ? ' checked="checked"' : '') . ' />
					<label for="checkDo_update">' . $LANG->getLL('importdata_updateRecords', 1) . '</label><br/>
				<em>(' . $LANG->getLL('importdata_thisOptionRequiresThat', 1) . ')</em>' . ($inData['do_update'] ? '	<hr/>
					<input type="checkbox" name="tx_impexp[global_ignore_pid]" id="checkGlobal_ignore_pid" value="1"' . ($inData['global_ignore_pid'] ? ' checked="checked"' : '') . ' />
					<label for="checkGlobal_ignore_pid">' . $LANG->getLL('importdata_ignorePidDifferencesGlobally', 1) . '</label><br/>
					<em>(' . $LANG->getLL('importdata_ifYouSetThis', 1) . ')</em>
					' : '') . '</td>
				</tr>';
            $row[] = '<tr class="bgColor4">
				<td><strong>' . $LANG->getLL('importdata_options', 1) . '</strong>' . \TYPO3\CMS\Backend\Utility\BackendUtility::cshItem('xMOD_tx_impexp', 'options', $GLOBALS['BACK_PATH'], '') . '</td>
				<td>
					<input type="checkbox" name="tx_impexp[notShowDiff]" id="checkNotShowDiff" value="1"' . ($inData['notShowDiff'] ? ' checked="checked"' : '') . ' />
					<label for="checkNotShowDiff">' . $LANG->getLL('importdata_doNotShowDifferences', 1) . '</label><br/>
					<em>(' . $LANG->getLL('importdata_greenValuesAreFrom', 1) . ')</em>
					<br/><br/>

					' . ($GLOBALS['BE_USER']->isAdmin() ? '
					<input type="checkbox" name="tx_impexp[allowPHPScripts]" id="checkAllowPHPScripts" value="1"' . ($inData['allowPHPScripts'] ? ' checked="checked"' : '') . ' />
					<label for="checkAllowPHPScripts">' . $LANG->getLL('importdata_allowToWriteBanned', 1) . '</label><br/>' : '') . (!$inData['do_update'] && $GLOBALS['BE_USER']->isAdmin() ? '
					<br/>
					<input type="checkbox" name="tx_impexp[force_all_UIDS]" id="checkForce_all_UIDS" value="1"' . ($inData['force_all_UIDS'] ? ' checked="checked"' : '') . ' />
					<label for="checkForce_all_UIDS"><span class="typo3-red">' . $LANG->getLL('importdata_force_all_UIDS', 1) . '</span></label><br/>
					<em>(' . $LANG->getLL('importdata_force_all_UIDS_descr', 1) . ')</em>' : '') . '
				</td>
				</tr>';
            $row[] = '<tr class="bgColor4">
				<td><strong>' . $LANG->getLL('importdata_action', 1) . '</strong>' . \TYPO3\CMS\Backend\Utility\BackendUtility::cshItem('xMOD_tx_impexp', 'action', $GLOBALS['BACK_PATH'], '') . '</td>
				<td>' . (!$inData['import_file'] ? '<input type="submit" value="' . $LANG->getLL('importdata_preview', 1) . '" />' . ($inData['file'] ? ' - <input type="submit" value="' . ($inData['do_update'] ? $LANG->getLL('importdata_update_299e', 1) : $LANG->getLL('importdata_import', 1)) . '" name="tx_impexp[import_file]" onclick="return confirm(\'' . $LANG->getLL('importdata_areYouSure', 1) . '\');" />' : '') : '<input type="submit" name="tx_impexp[new_import]" value="' . $LANG->getLL('importdata_newImport', 1) . '" />') . '
					<input type="hidden" name="tx_impexp[action]" value="import" /></td>
				</tr>';
            $row[] = '<tr class="bgColor4">
				<td><strong>' . $LANG->getLL('importdata_enableLogging', 1) . '</strong>' . \TYPO3\CMS\Backend\Utility\BackendUtility::cshItem('xMOD_tx_impexp', 'enableLogging', $GLOBALS['BACK_PATH'], '') . '</td>
				<td>
					<input type="checkbox" name="tx_impexp[enableLogging]" id="checkEnableLogging" value="1"' . ($inData['enableLogging'] ? ' checked="checked"' : '') . ' />
					<label for="checkEnableLogging">' . $LANG->getLL('importdata_writeIndividualDbActions', 1) . '</label><br/>
					<em>(' . $LANG->getLL('importdata_thisIsDisabledBy', 1) . ')</em>
				</td>
				</tr>';
            $menuItems[] = array('label' => $LANG->getLL('importdata_import', 1), 'content' => '
					<table border="0" cellpadding="1" cellspacing="1">
						' . implode('
						', $row) . '
					</table>
				');
            // Upload file:
            $tempFolder = $this->userTempFolder();
            if ($tempFolder) {
                $row = array();
                $row[] = '<tr class="bgColor5">
						<td colspan="2"><strong>' . $LANG->getLL('importdata_uploadFileFromLocal', 1) . '</strong></td>
					</tr>';
                $row[] = '<tr class="bgColor4">
						<td>' . $LANG->getLL('importdata_browse', 1) . \TYPO3\CMS\Backend\Utility\BackendUtility::cshItem('xMOD_tx_impexp', 'upload', $GLOBALS['BACK_PATH'], '') . '</td>
						<td>

								<input type="file" name="upload_1"' . $this->doc->formWidth(35) . ' size="40" />
								<input type="hidden" name="file[upload][1][target]" value="' . htmlspecialchars($tempFolder) . '" />
								<input type="hidden" name="file[upload][1][data]" value="1" /><br />

								<input type="submit" name="_upload" value="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:file_upload.php.submit', 1) . '" />
								<input type="checkbox" name="overwriteExistingFiles" id="checkOverwriteExistingFiles" value="1" checked="checked" /> <label for="checkOverwriteExistingFiles">' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_misc.php:overwriteExistingFiles', 1) . '</label>
						</td>
					</tr>';
                if (\TYPO3\CMS\Core\Utility\GeneralUtility::_POST('_upload')) {
                    $row[] = '<tr class="bgColor4">
							<td>' . $LANG->getLL('importdata_uploadStatus', 1) . '</td>
							<td>' . ($this->fileProcessor->internalUploadMap[1] ? $LANG->getLL('importdata_success', 1) . ' ' . substr($this->fileProcessor->internalUploadMap[1], strlen(PATH_site)) : '<span class="typo3-red">' . $LANG->getLL('importdata_failureNoFileUploaded', 1) . '</span>') . '</td>
						</tr>';
                }
                $menuItems[] = array('label' => $LANG->getLL('importdata_upload'), 'content' => '
						<table border="0" cellpadding="1" cellspacing="1">
							' . implode('
							', $row) . '
						</table>
					');
            }
            // Perform import or preview depending:
            $overviewContent = '';
            $extensionInstallationMessage = '';
            $emURL = '';
            $inFile = \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName($inData['file']);
            if ($inFile && @is_file($inFile)) {
                $trow = array();
                if ($import->loadFile($inFile, 1)) {
                    // Check extension dependencies:
                    $extKeysToInstall = array();
                    if (is_array($import->dat['header']['extensionDependencies'])) {
                        foreach ($import->dat['header']['extensionDependencies'] as $extKey) {
                            if (!\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded($extKey)) {
                                $extKeysToInstall[] = $extKey;
                            }
                        }
                    }
                    if (count($extKeysToInstall)) {
                        $passParams = \TYPO3\CMS\Core\Utility\GeneralUtility::_POST('tx_impexp');
                        unset($passParams['import_mode']);
                        unset($passParams['import_file']);
                        $thisScriptUrl = \TYPO3\CMS\Core\Utility\GeneralUtility::getIndpEnv('REQUEST_URI') . '?M=xMOD_tximpexp&id=' . $this->id . \TYPO3\CMS\Core\Utility\GeneralUtility::implodeArrayForUrl('tx_impexp', $passParams);
                        $emURL = $this->doc->backPath . \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extRelPath('em') . 'classes/index.php?CMD[requestInstallExtensions]=' . implode(',', $extKeysToInstall) . '&returnUrl=' . rawurlencode($thisScriptUrl);
                        $extensionInstallationMessage = 'Before you can install this T3D file you need to install the extensions "' . implode('", "', $extKeysToInstall) . '". Clicking Import will first take you to the Extension Manager so these dependencies can be resolved.';
                    }
                    if ($inData['import_file']) {
                        if (!count($extKeysToInstall)) {
                            $import->importData($this->id);
                            \TYPO3\CMS\Backend\Utility\BackendUtility::setUpdateSignal('updatePageTree');
                        } else {
                            \TYPO3\CMS\Core\Utility\HttpUtility::redirect($emURL);
                        }
                    }
                    $import->display_import_pid_record = $this->pageinfo;
                    $overviewContent = $import->displayContentOverview();
                }
                // Meta data output:
                $trow[] = '<tr class="bgColor5">
						<td colspan="2"><strong>' . $LANG->getLL('importdata_metaData', 1) . '</strong></td>
					</tr>';
                $opt = array('');
                foreach ($filesInDir as $file) {
                    $opt[$file] = substr($file, strlen(PATH_site));
                }
                $trow[] = '<tr class="bgColor4">
					<td><strong>' . $LANG->getLL('importdata_title', 1) . '</strong></td>
					<td width="95%">' . nl2br(htmlspecialchars($import->dat['header']['meta']['title'])) . '</td>
					</tr>';
                $trow[] = '<tr class="bgColor4">
					<td><strong>' . $LANG->getLL('importdata_description', 1) . '</strong></td>
					<td width="95%">' . nl2br(htmlspecialchars($import->dat['header']['meta']['description'])) . '</td>
					</tr>';
                $trow[] = '<tr class="bgColor4">
					<td><strong>' . $LANG->getLL('importdata_notes', 1) . '</strong></td>
					<td width="95%">' . nl2br(htmlspecialchars($import->dat['header']['meta']['notes'])) . '</td>
					</tr>';
                $trow[] = '<tr class="bgColor4">
					<td><strong>' . $LANG->getLL('importdata_packager', 1) . '</strong></td>
					<td width="95%">' . nl2br(htmlspecialchars($import->dat['header']['meta']['packager_name'] . ' (' . $import->dat['header']['meta']['packager_username'] . ')')) . '<br/>
						' . $LANG->getLL('importdata_email', 1) . ' ' . $import->dat['header']['meta']['packager_email'] . '</td>
					</tr>';
                // Thumbnail icon:
                if (is_array($import->dat['header']['thumbnail'])) {
                    $pI = pathinfo($import->dat['header']['thumbnail']['filename']);
                    if (\TYPO3\CMS\Core\Utility\GeneralUtility::inList('gif,jpg,png,jpeg', strtolower($pI['extension']))) {
                        // Construct filename and write it:
                        $fileName = PATH_site . 'typo3temp/importthumb.' . $pI['extension'];
                        \TYPO3\CMS\Core\Utility\GeneralUtility::writeFile($fileName, $import->dat['header']['thumbnail']['content']);
                        // Check that the image really is an image and not a malicious PHP script...
                        if (getimagesize($fileName)) {
                            // Create icon tag:
                            $iconTag = '<img src="' . $this->doc->backPath . '../' . substr($fileName, strlen(PATH_site)) . '" ' . $import->dat['header']['thumbnail']['imgInfo'][3] . ' vspace="5" style="border: solid black 1px;" alt="" />';
                            $trow[] = '<tr class="bgColor4">
								<td><strong>' . $LANG->getLL('importdata_icon', 1) . '</strong></td>
								<td>' . $iconTag . '</td>
								</tr>';
                        } else {
                            \TYPO3\CMS\Core\Utility\GeneralUtility::unlink_tempfile($fileName);
                        }
                    }
                }
                $menuItems[] = array('label' => $LANG->getLL('importdata_metaData_1387'), 'content' => '
						<table border="0" cellpadding="1" cellspacing="1">
							' . implode('
							', $trow) . '
						</table>
					');
            }
            // Print errors that might be:
            $errors = $import->printErrorLog();
            $menuItems[] = array('label' => $LANG->getLL('importdata_messages'), 'content' => $errors, 'stateIcon' => $errors ? 2 : 0);
            // Output tabs:
            $content = $this->doc->getDynTabMenu($menuItems, 'tx_impexp_import', -1);
            if ($extensionInstallationMessage) {
                $content = '<div style="border: 1px black solid; margin: 10px 10px 10px 10px; padding: 10px 10px 10px 10px;">' . $this->doc->icons(1) . htmlspecialchars($extensionInstallationMessage) . '</div>' . $content;
            }
            $this->content .= $this->doc->section('', $content, 0, 1);
            // Print overview:
            if ($overviewContent) {
                $this->content .= $this->doc->section($inData['import_file'] ? $LANG->getLL('importdata_structureHasBeenImported', 1) : $LANG->getLL('filterpage_structureToBeImported', 1), $overviewContent, 0, 1);
            }
        }
    }
Ejemplo n.º 18
0
 /**
  * Remove uploaded files from the typo3temp
  *
  * @return void
  */
 protected function removeFiles()
 {
     $values = $this->getByMethod();
     if (is_array($values)) {
         foreach ($values as $value) {
             if (is_array($value) && isset($value['tempFilename'])) {
                 GeneralUtility::unlink_tempfile($value['tempFilename']);
             }
         }
     }
 }
Ejemplo n.º 19
0
 /**
  * The actual sprite generator, renders the command for IM/GM and executes
  *
  * @return void
  */
 protected function generateHighDensityGraphic()
 {
     $tempSprite = GeneralUtility::tempnam($this->spriteName . '@x2', '.png');
     $filePath = PATH_site . $this->spriteFolder . $this->spriteName . '@x2.png';
     // Create black true color image with given size
     $newSprite = imagecreatetruecolor($this->spriteWidth * 2, $this->spriteHeight * 2);
     imagesavealpha($newSprite, TRUE);
     // Make it transparent
     imagefill($newSprite, 0, 0, imagecolorallocatealpha($newSprite, 0, 255, 255, 127));
     foreach ($this->iconsData as $icon) {
         $function = 'imagecreatefrom' . strtolower($icon['fileExtension']);
         if (function_exists($function)) {
             if ($icon['fileNameHighDensity'] !== FALSE) {
                 // copy HighDensity file
                 $currentIcon = $function($icon['fileNameHighDensity']);
                 imagecopy($newSprite, $currentIcon, $icon['left'] * 2, $icon['top'] * 2, 0, 0, $icon['width'] * 2, $icon['height'] * 2);
             } else {
                 // scale up normal file
                 $currentIcon = $function($icon['fileName']);
                 imagecopyresized($newSprite, $currentIcon, $icon['left'] * 2, $icon['top'] * 2, 0, 0, $icon['width'] * 2, $icon['height'] * 2, $icon['width'], $icon['height']);
             }
         }
     }
     imagepng($newSprite, $tempSprite);
     GeneralUtility::upload_copy_move($tempSprite, $filePath);
     GeneralUtility::unlink_tempfile($tempSprite);
 }
Ejemplo n.º 20
0
 /**
  * This method actually does the processing of files locally
  *
  * takes the original file (on remote storages this will be fetched from the remote server)
  * does the IM magic on the local server by creating a temporary typo3temp/ file
  * copies the typo3temp/ file to the processingfolder of the target storage
  * removes the typo3temp/ file
  *
  * @param \TYPO3\CMS\Core\Resource\ProcessedFile $processedFile
  * @param \TYPO3\CMS\Core\Resource\FileInterface $file
  * @param array $configuration
  * @return void
  */
 protected function processImageCropResizeMask(\TYPO3\CMS\Core\Resource\ProcessedFile $processedFile, \TYPO3\CMS\Core\Resource\FileInterface $file, array $configuration)
 {
     // checks to see if m (the mask array) is defined
     $doMasking = is_array($configuration['maskImages']) && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im'];
     // @todo: is it ok that we use tslib (=FE) here?
     /** @var $gifBuilder tslib_gifbuilder */
     $gifBuilder = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('tslib_gifbuilder');
     $gifBuilder->init();
     // @todo: this is not clean yet
     if (!trim($configuration['fileExtension'])) {
         $configuration['fileExtension'] = 'web';
         $targetFileExtension = $file->getExtension();
     } elseif ($doMasking) {
         $targetFileExtension = $file->getExtension() == $gifBuilder->gifExtension ? $gifBuilder->gifExtension : 'jpg';
     } else {
         $targetFileExtension = $configuration['fileExtension'];
     }
     $originalFileName = $file->getForLocalProcessing(FALSE);
     $targetFolder = $this->storage->getProcessingFolder();
     $targetFileName = 'previewcrm_' . $processedFile->calculateChecksum() . '.' . $targetFileExtension;
     // @todo: implement meaningful TempFileIndex
     if ($configuration['useSample']) {
         $gifBuilder->scalecmd = '-sample';
     }
     $options = array();
     if ($configuration['maxWidth']) {
         $options['maxW'] = $configuration['maxWidth'];
     }
     if ($configuration['maxHeight']) {
         $options['maxH'] = $configuration['maxHeight'];
     }
     if ($configuration['minWidth']) {
         $options['minW'] = $configuration['minWidth'];
     }
     if ($configuration['minHeight']) {
         $options['minH'] = $configuration['minHeight'];
     }
     $options['noScale'] = $configuration['noScale'];
     $configuration['additionalParameters'] = $this->modifyImageMagickStripProfileParameters($configuration['additionalParameters'], $configuration);
     // Do the actual processing
     if (!$targetFolder->hasFile($targetFileName)) {
         if (!$doMasking) {
             // Normal situation (no masking)
             // the result info is an array with 0=width,1=height,2=extension,3=filename
             list($targetWidth, $targetHeight, $targetExtension, $temporaryFileName) = $gifBuilder->imageMagickConvert($originalFileName, $configuration['fileExtension'], $configuration['width'], $configuration['height'], $configuration['additionalParameters'], $configuration['frame'], $options);
         } else {
             $temporaryFileName = $gifBuilder->tempPath . $targetFileName;
             $maskImage = $configuration['maskImages']['maskImage'];
             $maskBackgroundImage = $configuration['maskImages']['backgroundImage'];
             if ($maskImage instanceof \TYPO3\CMS\Core\Resource\FileInterface && $maskBackgroundImage instanceof \TYPO3\CMS\Core\Resource\FileInterface) {
                 $negate = $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_negate_mask'] ? ' -negate' : '';
                 $temporaryExtension = 'png';
                 if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['im_mask_temp_ext_gif']) {
                     // If ImageMagick version 5+
                     $temporaryExtension = $gifBuilder->gifExtension;
                 }
                 $tempFileInfo = $gifBuilder->imageMagickConvert($originalFileName, $temporaryExtension, $configuration['width'], $configuration['height'], $configuration['additionalParameters'], $configuration['frame'], $options);
                 if (is_array($tempFileInfo)) {
                     $maskBottomImage = $configuration['maskImages']['maskBottomImage'];
                     if ($maskBottomImage instanceof $maskBottomImage) {
                         $maskBottomImageMask = $configuration['maskImages']['maskBottomImageMask'];
                     }
                     //	Scaling:	****
                     $tempScale = array();
                     $command = '-geometry ' . $tempFileInfo[0] . 'x' . $tempFileInfo[1] . '!';
                     $command = $this->modifyImageMagickStripProfileParameters($command, $configuration);
                     $tmpStr = $gifBuilder->randomName();
                     //	m_mask
                     $tempScale['m_mask'] = $tmpStr . '_mask.' . $temporaryExtension;
                     $gifBuilder->imageMagickExec($maskImage->getForLocalProcessing(TRUE), $tempScale['m_mask'], $command . $negate);
                     //	m_bgImg
                     $tempScale['m_bgImg'] = $tmpStr . '_bgImg.' . trim($GLOBALS['TYPO3_CONF_VARS']['GFX']['im_mask_temp_ext_noloss']);
                     $gifBuilder->imageMagickExec($maskBackgroundImage->getForLocalProcessing(), $tempScale['m_bgImg'], $command);
                     //	m_bottomImg / m_bottomImg_mask
                     if ($maskBottomImage instanceof \TYPO3\CMS\Core\Resource\FileInterface && $maskBottomImageMask instanceof \TYPO3\CMS\Core\Resource\FileInterface) {
                         $tempScale['m_bottomImg'] = $tmpStr . '_bottomImg.' . $temporaryExtension;
                         $gifBuilder->imageMagickExec($maskBottomImage->getForLocalProcessing(), $tempScale['m_bottomImg'], $command);
                         $tempScale['m_bottomImg_mask'] = $tmpStr . '_bottomImg_mask.' . $temporaryExtension;
                         $gifBuilder->imageMagickExec($maskBottomImageMask->getForLocalProcessing(), $tempScale['m_bottomImg_mask'], $command . $negate);
                         // BEGIN combining:
                         // The image onto the background
                         $gifBuilder->combineExec($tempScale['m_bgImg'], $tempScale['m_bottomImg'], $tempScale['m_bottomImg_mask'], $tempScale['m_bgImg']);
                     }
                     // The image onto the background
                     $gifBuilder->combineExec($tempScale['m_bgImg'], $tempFileInfo[3], $tempScale['m_mask'], $temporaryFileName);
                     // Unlink the temp-images...
                     foreach ($tempScale as $file) {
                         if (@is_file($file)) {
                             unlink($file);
                         }
                     }
                 }
             }
             // Finish off
             list($targetWidth, $targetHeight) = $gifBuilder->getImageDimensions($temporaryFileName);
         }
         // Temporary image was created
         if (file_exists($temporaryFileName)) {
             $updatedProperties = array('width' => $targetWidth, 'height' => $targetHeight);
             // ImageMagick did not have to do anything, as it is already there...
             if ($originalFileName !== $temporaryFileName) {
                 \TYPO3\CMS\Core\Utility\GeneralUtility::fixPermissions($temporaryFileName);
                 // Copy the temporary file to the processedFolder
                 // this is done here, as the driver can do this without worrying
                 // about existing ProcessedFile objects
                 // or permissions in the storage
                 // for "remote" storages this means "uploading" the file to the storage again
                 // for the virtual storage, it is merely a thing of "copying a file from typo3temp/ to typo3temp/_processed_"
                 $this->driver->addFile($temporaryFileName, $targetFolder, $targetFileName, $processedFile);
                 // Remove the temporary file as it's not needed anymore
                 \TYPO3\CMS\Core\Utility\GeneralUtility::unlink_tempfile($temporaryFileName);
             } else {
             }
             $processedFile->updateProperties($updatedProperties);
             $processedFile->setProcessed(TRUE);
         }
     }
 }
Ejemplo n.º 21
0
 /**
  * Delete registered temporary files.
  *
  * @return 	void
  * @todo Define visibility
  */
 public function unlinkTempFiles()
 {
     foreach ($this->tempFiles as $absFile) {
         \TYPO3\CMS\Core\Utility\GeneralUtility::unlink_tempfile($absFile);
     }
     $this->tempFiles = array();
 }
Ejemplo n.º 22
0
 /**
  * @test
  */
 public function imagemakeFixesPermissionsOnNewFiles()
 {
     if (TYPO3_OS == 'WIN') {
         $this->markTestSkipped('imagemakeFixesPermissionsOnNewFiles() test not available on Windows.');
     }
     $fixtureGifFile = __DIR__ . '/Fixtures/clear.gif';
     // Create image resource, determine target filename, fake target permission, run method and clean up
     $fixtureGifRessource = imagecreatefromgif($fixtureGifFile);
     $targetFilename = PATH_site . 'typo3temp/' . $this->getUniqueId('test_') . '.gif';
     $GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'] = '0777';
     $subject = $this->subject;
     $subject::imagemake($fixtureGifRessource, $targetFilename);
     clearstatcache();
     $resultFilePermissions = substr(decoct(fileperms($targetFilename)), 2);
     \TYPO3\CMS\Core\Utility\GeneralUtility::unlink_tempfile($targetFilename);
     $this->assertEquals($resultFilePermissions, '0777');
 }
Ejemplo n.º 23
0
 /**
  * The actual sprite generator, renders the command for Im/GM and executes
  *
  * @return void
  */
 protected function generateGraphic()
 {
     $tempSprite = \TYPO3\CMS\Core\Utility\GeneralUtility::tempnam($this->spriteName);
     $filePath = array('mainFile' => PATH_site . $this->spriteFolder . $this->spriteName . '.png');
     // Create black true color image with given size
     $newSprite = imagecreatetruecolor($this->spriteWidth, $this->spriteHeight);
     imagesavealpha($newSprite, TRUE);
     // Make it transparent
     imagefill($newSprite, 0, 0, imagecolorallocatealpha($newSprite, 0, 255, 255, 127));
     foreach ($this->iconsData as $icon) {
         $function = 'imagecreatefrom' . strtolower($icon['fileExtension']);
         if (function_exists($function)) {
             $currentIcon = $function($icon['fileName']);
             imagecopy($newSprite, $currentIcon, $icon['left'], $icon['top'], 0, 0, $icon['width'], $icon['height']);
         }
     }
     imagepng($newSprite, $tempSprite . '.png');
     \TYPO3\CMS\Core\Utility\GeneralUtility::upload_copy_move($tempSprite . '.png', $filePath['mainFile']);
     \TYPO3\CMS\Core\Utility\GeneralUtility::unlink_tempfile($tempSprite . '.png');
 }
Ejemplo n.º 24
0
 /**
  * @param $zipArchivePath
  * @throws Exception
  * @return void
  */
 private function extractDownloadedPiwik($zipArchivePath)
 {
     //make dir for extraction
     \TYPO3\CMS\Core\Utility\GeneralUtility::mkdir_deep(PATH_site, $this->installPath);
     if (!is_writeable(PATH_site . $this->installPath)) {
         throw new \Exception($this->installPath . ' must be writeable');
     }
     //extract archive
     switch ($this->checkUnzip()) {
         case 'clsZipArchive':
             $zip = new \ZipArchive();
             $zip->open($zipArchivePath);
             $zip->extractTo($this->getAbsInstallPath());
             $zip->close();
             unset($zip);
             break;
         case 'cmd':
             $cmd = $GLOBALS['TYPO3_CONF_VARS']['BE']['unzip_path'] . 'unzip -qq "' . $zipArchivePath . '" -d "' . $this->getAbsInstallPath() . '"';
             exec($cmd);
             break;
         case 'zlib':
             try {
                 //up to 4.4.4
                 $emUnzipFile = PATH_typo3 . '/mod/tools/em/class.em_unzip.php';
                 if (file_exists($emUnzipFile)) {
                     require_once $emUnzipFile;
                 }
                 $zlibObj = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('em_unzip', $zipArchivePath);
             } catch (\Exception $e) {
                 //from 4.5.0b2
                 $zlibObj = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('tx_em_Tools_Unzip', $zipArchivePath);
             }
             $zlibObj->extract(array('add_path' => $this->getAbsInstallPath()));
             break;
         default:
             throw new \Exception('There is no valid unzip wrapper, i need either the class ZipArchiv from php or a *nix system with unzip path set.');
             break;
     }
     //unlink archiv to save space in typo3temp ;)
     \TYPO3\CMS\Core\Utility\GeneralUtility::unlink_tempfile($zipArchivePath);
     if (!$this->checkInstallation()) {
         $buffer = 'No files has been extracted!';
         if (!class_exists('ZipArchive')) {
             $buffer .= ' -> Please enable the phpextensions Zip or Zlib!';
         }
         if (!(TYPO3_OS == 'WIN' || $GLOBALS['TYPO3_CONF_VARS']['BE']['disable_exec_function'])) {
             $buffer .= ' -> used TYPO3 cmd line function to extract files, if you use solaris this may be the problem.';
             $buffer .= ' -> please manually extract piwik and copy it to typo3conf/piwik/piwik and use the extmgm update script to patch and configure piwik';
             $buffer .= ' -> take a look in your manual for more information or use an environment with a working zip class';
         }
         throw new \Exception($buffer);
     }
 }
    /**
     * Import part of module
     *
     * @param array $inData Content of POST VAR tx_impexp[]..
     * @throws \BadFunctionCallException
     * @throws \InvalidArgumentException
     * @throws \RuntimeException
     * @return void Setting content in $this->content
     */
    public function importData($inData)
    {
        $access = is_array($this->pageinfo) ? 1 : 0;
        $beUser = $this->getBackendUser();
        if ($this->id && $access || $beUser->user['admin'] && !$this->id) {
            if ($beUser->user['admin'] && !$this->id) {
                $this->pageinfo = array('title' => '[root-level]', 'uid' => 0, 'pid' => 0);
            }
            if ($inData['new_import']) {
                unset($inData['import_mode']);
            }
            /** @var $import \TYPO3\CMS\Impexp\ImportExport */
            $import = GeneralUtility::makeInstance(\TYPO3\CMS\Impexp\ImportExport::class);
            $import->init(0, 'import');
            $import->update = $inData['do_update'];
            $import->import_mode = $inData['import_mode'];
            $import->enableLogging = $inData['enableLogging'];
            $import->global_ignore_pid = $inData['global_ignore_pid'];
            $import->force_all_UIDS = $inData['force_all_UIDS'];
            $import->showDiff = !$inData['notShowDiff'];
            $import->allowPHPScripts = $inData['allowPHPScripts'];
            $import->softrefInputValues = $inData['softrefInputValues'];
            // OUTPUT creation:
            $menuItems = array();
            // Make input selector:
            // must have trailing slash.
            $path = $this->getDefaultImportExportFolder();
            $exportFiles = $this->getExportFiles();
            $this->shortcutName .= ' (' . $this->pageinfo['title'] . ')';
            // Configuration
            $row = array();
            $selectOptions = array('');
            foreach ($exportFiles as $file) {
                $selectOptions[$file->getCombinedIdentifier()] = $file->getPublicUrl();
            }
            $row[] = '
				<tr>
					<th colspan="2">' . $this->lang->getLL('importdata_selectFileToImport', true) . '</th>
				</tr>';
            $noCompressorAvailable = !$import->compress ? '<br /><span class="text-danger">' . $this->lang->getLL('importdata_noteNoDecompressorAvailable', true) . '</span>' : '';
            $row[] = '
				<tr>
					<td valign="top">
						' . $this->lang->getLL('importdata_file', true) . '' . BackendUtility::cshItem('xMOD_tx_impexp', 'importFile') . '
					</td>
					<td>
						' . $this->renderSelectBox('tx_impexp[file]', $inData['file'], $selectOptions) . '<br />' . sprintf($this->lang->getLL('importdata_fromPathS', true), $path ? $path->getCombinedIdentifier() : $this->lang->getLL('importdata_no_accessible_file_mount', true)) . $noCompressorAvailable . '
					</td>
				</tr>';
            $row[] = '
				<tr>
					<th colspan="2">
						' . $this->lang->getLL('importdata_importOptions', true) . '
					</th>
				</tr>';
            $row[] = '
				<tr>
					<td valign="top">
						' . $this->lang->getLL('importdata_update', true) . BackendUtility::cshItem('xMOD_tx_impexp', 'update') . '
					</td>
					<td>
						<input type="checkbox" name="tx_impexp[do_update]" id="checkDo_update" value="1"' . ($inData['do_update'] ? ' checked="checked"' : '') . ' />
						<label for="checkDo_update">' . $this->lang->getLL('importdata_updateRecords', true) . '</label>
						<br/>
						<em>(' . $this->lang->getLL('importdata_thisOptionRequiresThat', true) . ')</em>' . ($inData['do_update'] ? '	<hr/>
						<input type="checkbox" name="tx_impexp[global_ignore_pid]" id="checkGlobal_ignore_pid" value="1"' . ($inData['global_ignore_pid'] ? ' checked="checked"' : '') . ' />
						<label for="checkGlobal_ignore_pid">' . $this->lang->getLL('importdata_ignorePidDifferencesGlobally', true) . '</label><br/>
						<em>(' . $this->lang->getLL('importdata_ifYouSetThis', true) . ')</em>
						' : '') . '
					</td>
				</tr>';
            $allowPhpScripts = $beUser->isAdmin() ? '
					<input type="checkbox" name="tx_impexp[allowPHPScripts]" id="checkAllowPHPScripts" value="1"' . ($inData['allowPHPScripts'] ? ' checked="checked"' : '') . ' />
					<label for="checkAllowPHPScripts">' . $this->lang->getLL('importdata_allowToWriteBanned', true) . '</label><br/>' : '';
            $doUpdate = !$inData['do_update'] && $beUser->isAdmin() ? '
					<br/>
					<input type="checkbox" name="tx_impexp[force_all_UIDS]" id="checkForce_all_UIDS" value="1"' . ($inData['force_all_UIDS'] ? ' checked="checked"' : '') . ' />
					<label for="checkForce_all_UIDS"><span class="text-danger">' . $this->lang->getLL('importdata_force_all_UIDS', true) . '</span></label><br/>
					<em>(' . $this->lang->getLL('importdata_force_all_UIDS_descr', true) . ')</em>' : '';
            $row[] = '<tr>
					<td valign="top">
						' . $this->lang->getLL('importdata_options', true) . BackendUtility::cshItem('xMOD_tx_impexp', 'options') . '
					</td>
					<td>
						<input type="checkbox" name="tx_impexp[notShowDiff]" id="checkNotShowDiff" value="1"' . ($inData['notShowDiff'] ? ' checked="checked"' : '') . ' />
						<label for="checkNotShowDiff">' . $this->lang->getLL('importdata_doNotShowDifferences', true) . '</label><br/>
						<em>(' . $this->lang->getLL('importdata_greenValuesAreFrom', true) . ')</em>
						<br/><br/>

						' . $allowPhpScripts . $doUpdate . '
					</td>
				</tr>';
            $newImport = !$inData['import_file'] ? '<input class="btn btn-default" type="submit" value="' . $this->lang->getLL('importdata_preview', true) . '" />' . ($inData['file'] ? ' - <input type="hidden" name="not-set" value="1" id="t3js-submit-field" /><input class="btn btn-default t3js-confirm-trigger" type="button" value="' . ($inData['do_update'] ? $this->lang->getLL('importdata_update_299e', true) : $this->lang->getLL('importdata_import', true)) . '" name="tx_impexp[import_file]" data-title="' . $this->lang->getLL('pleaseConfirm', true) . '" data-message="' . $this->lang->getLL('importdata_areYouSure', true) . '" />' : '') : '<input class="btn btn-default" type="submit" name="tx_impexp[new_import]" value="' . $this->lang->getLL('importdata_newImport', true) . '" />';
            $row[] = '<tr>
					<td valign="top">
						' . $this->lang->getLL('importdata_action', true) . BackendUtility::cshItem('xMOD_tx_impexp', 'action') . '
					</td>
					<td>
						' . $newImport . '
						<input type="hidden" name="tx_impexp[action]" value="import" />
					</td>
				</tr>';
            $row[] = '<tr>
				<td valign="top">
					' . $this->lang->getLL('importdata_enableLogging', true) . BackendUtility::cshItem('xMOD_tx_impexp', 'enableLogging') . '
				</td>
				<td>
					<input type="checkbox" name="tx_impexp[enableLogging]" id="checkEnableLogging" value="1"' . ($inData['enableLogging'] ? ' checked="checked"' : '') . ' />
					<label for="checkEnableLogging">' . $this->lang->getLL('importdata_writeIndividualDbActions', true) . '</label><br/>
					<em>(' . $this->lang->getLL('importdata_thisIsDisabledBy', true) . ')</em>
				</td>
				</tr>';
            $menuItems[] = array('label' => $this->lang->getLL('importdata_import', true), 'content' => '
					<table border="0" cellpadding="1" cellspacing="1">
						' . implode('
						', $row) . '
					</table>
				');
            // Upload file:
            $tempFolder = $this->getDefaultImportExportFolder();
            if ($tempFolder) {
                $row = array();
                $row[] = '
					<tr>
						<th colspan="2">' . $this->lang->getLL('importdata_uploadFileFromLocal', true) . '</th>
					</tr>';
                $row[] = '
					<tr>
						<td valign="top">
							' . $this->lang->getLL('importdata_browse', true) . BackendUtility::cshItem('xMOD_tx_impexp', 'upload') . '
						</td>
						<td>
							<input type="file" name="upload_1" size="40" />
							<input type="hidden" name="file[upload][1][target]" value="' . htmlspecialchars($tempFolder->getCombinedIdentifier()) . '" />
							<input type="hidden" name="file[upload][1][data]" value="1" />
							<br />
							<input class="btn btn-default" type="submit" name="_upload" value="' . $this->lang->sL('LLL:EXT:lang/locallang_core.xlf:file_upload.php.submit', true) . '" />
							<input type="checkbox" name="overwriteExistingFiles" id="checkOverwriteExistingFiles" value="1" checked="checked" />
							<label for="checkOverwriteExistingFiles">' . $this->lang->sL('LLL:EXT:lang/locallang_misc.xlf:overwriteExistingFiles', true) . '</label>
						</td>
					</tr>';
                if (GeneralUtility::_POST('_upload')) {
                    $noFileUploaded = $this->fileProcessor->internalUploadMap[1] ? $this->lang->getLL('importdata_success', true) . ' ' . $this->uploadedFiles[0]->getName() : '<span class="text-danger">' . $this->lang->getLL('importdata_failureNoFileUploaded', true) . '</span>';
                    $row[] = '<tr class="bgColor4">
							<td>' . $this->lang->getLL('importdata_uploadStatus', true) . '</td>
							<td>' . $noFileUploaded . '</td>
						</tr>';
                }
                $menuItems[] = array('label' => $this->lang->getLL('importdata_upload'), 'content' => '
						<table border="0" cellpadding="1" cellspacing="1">
							' . implode('
							', $row) . '
						</table>
					');
            }
            // Perform import or preview depending:
            $overviewContent = '';
            $extensionInstallationMessage = '';
            $inFile = $this->getFile($inData['file']);
            if ($inFile !== null && $inFile->exists()) {
                $trow = array();
                if ($import->loadFile($inFile->getForLocalProcessing(false), 1)) {
                    // Check extension dependencies:
                    $extKeysToInstall = array();
                    if (is_array($import->dat['header']['extensionDependencies'])) {
                        foreach ($import->dat['header']['extensionDependencies'] as $extKey) {
                            if (!\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded($extKey)) {
                                $extKeysToInstall[] = $extKey;
                            }
                        }
                    }
                    if (!empty($extKeysToInstall)) {
                        $extensionInstallationMessage = 'Before you can install this T3D file you need to install the extensions "' . implode('", "', $extKeysToInstall) . '".';
                    }
                    if ($inData['import_file']) {
                        if (empty($extKeysToInstall)) {
                            $import->importData($this->id);
                            BackendUtility::setUpdateSignal('updatePageTree');
                        }
                    }
                    $import->display_import_pid_record = $this->pageinfo;
                    $overviewContent = $import->displayContentOverview();
                }
                // Meta data output:
                $trow[] = '<tr class="bgColor5">
						<td colspan="2"><strong>' . $this->lang->getLL('importdata_metaData', true) . '</strong></td>
					</tr>';
                $trow[] = '<tr class="bgColor4">
					<td><strong>' . $this->lang->getLL('importdata_title', true) . '</strong></td>
					<td width="95%">' . nl2br(htmlspecialchars($import->dat['header']['meta']['title'])) . '</td>
					</tr>';
                $trow[] = '<tr class="bgColor4">
					<td><strong>' . $this->lang->getLL('importdata_description', true) . '</strong></td>
					<td width="95%">' . nl2br(htmlspecialchars($import->dat['header']['meta']['description'])) . '</td>
					</tr>';
                $trow[] = '<tr class="bgColor4">
					<td><strong>' . $this->lang->getLL('importdata_notes', true) . '</strong></td>
					<td width="95%">' . nl2br(htmlspecialchars($import->dat['header']['meta']['notes'])) . '</td>
					</tr>';
                $trow[] = '<tr class="bgColor4">
					<td><strong>' . $this->lang->getLL('importdata_packager', true) . '</strong></td>
					<td width="95%">' . nl2br(htmlspecialchars($import->dat['header']['meta']['packager_name'] . ' (' . $import->dat['header']['meta']['packager_username'] . ')')) . '<br/>
						' . $this->lang->getLL('importdata_email', true) . ' ' . $import->dat['header']['meta']['packager_email'] . '</td>
					</tr>';
                // Thumbnail icon:
                if (is_array($import->dat['header']['thumbnail'])) {
                    $pI = pathinfo($import->dat['header']['thumbnail']['filename']);
                    if (GeneralUtility::inList('gif,jpg,png,jpeg', strtolower($pI['extension']))) {
                        // Construct filename and write it:
                        $fileName = PATH_site . 'typo3temp/importthumb.' . $pI['extension'];
                        GeneralUtility::writeFile($fileName, $import->dat['header']['thumbnail']['content']);
                        // Check that the image really is an image and not a malicious PHP script...
                        if (getimagesize($fileName)) {
                            // Create icon tag:
                            $iconTag = '<img src="../' . PathUtility::stripPathSitePrefix($fileName) . '" ' . $import->dat['header']['thumbnail']['imgInfo'][3] . ' vspace="5" style="border: solid black 1px;" alt="" />';
                            $trow[] = '<tr class="bgColor4">
								<td><strong>' . $this->lang->getLL('importdata_icon', true) . '</strong></td>
								<td>' . $iconTag . '</td>
								</tr>';
                        } else {
                            GeneralUtility::unlink_tempfile($fileName);
                        }
                    }
                }
                $menuItems[] = array('label' => $this->lang->getLL('importdata_metaData_1387'), 'content' => '
						<table border="0" cellpadding="1" cellspacing="1">
							' . implode('
							', $trow) . '
						</table>
					');
            }
            // Print errors that might be:
            $errors = $import->printErrorLog();
            $menuItems[] = array('label' => $this->lang->getLL('importdata_messages'), 'content' => $errors, 'stateIcon' => $errors ? 2 : 0);
            // Output tabs:
            $content = $this->moduleTemplate->getDynamicTabMenu($menuItems, 'tx_impexp_import', 1, false, true, false);
            if ($extensionInstallationMessage) {
                $content = '<div style="border: 1px black solid; margin: 10px 10px 10px 10px; padding: 10px 10px 10px 10px;">' . $this->moduleTemplate->icons(1) . htmlspecialchars($extensionInstallationMessage) . '</div>' . $content;
            }
            $this->content .= $this->moduleTemplate->section('', $content, 0, 1);
            // Print overview:
            if ($overviewContent) {
                $this->content .= $this->moduleTemplate->section($inData['import_file'] ? $this->lang->getLL('importdata_structureHasBeenImported', true) : $this->lang->getLL('filterpage_structureToBeImported', true), $overviewContent, 0, 1);
            }
        }
    }
Ejemplo n.º 26
0
    function catXMLExportImportAction($l10ncfgObj)
    {
        global $LANG, $BACK_PATH, $BE_USER;
        $allowedSettingFiles = array('across' => 'acrossL10nmgrConfig.dst', 'dejaVu' => 'dejaVuL10nmgrConfig.dvflt', 'memoq' => 'memoQ.mqres', 'memoq2013-2014' => 'XMLConverter_TYPO3_l10nmgr_v3.6.mqres', 'transit' => 'StarTransit_XML_UTF_TYPO3.FFD', 'sdltrados2007' => 'SDLTradosTagEditor.ini', 'sdltrados2009' => 'TYPO3_l10nmgr.sdlfiletype', 'sdltrados2011-2014' => 'TYPO3_LocalizationManager_v3.6.free.sdlftsettings', 'sdlpassolo' => 'SDLPassolo.xfg');
        /** @var $service L10nBaseService */
        $service = GeneralUtility::makeInstance(L10nBaseService::class);
        $info = '<br/>';
        $info .= '<input type="submit" value="' . $GLOBALS['LANG']->getLL('general.action.refresh.button.title') . '" name="_" /><br /><br/>';
        $info .= '<div id="ddtabs" class="basictab" style="border:0px solid gray;margin:0px;">
					<ul style="border:0px solid #999999; ">
					<li><a onClick="expandcontent(\'sc1\', this)" style="margin:0px;">' . $GLOBALS['LANG']->getLL('export.xml.headline.title') . '</a></li>
					<li><a onClick="expandcontent(\'sc2\', this)" style="margin:0px;">' . $GLOBALS['LANG']->getLL('import.xml.headline.title') . '</a></li>
					<li><a onClick="expandcontent(\'sc3\', this)" style="margin:0px;">' . $GLOBALS['LANG']->getLL('file.settings.downloads.title') . '</a></li>
					<li><a onClick="expandcontent(\'sc4\', this)" style="margin:0px;">' . $GLOBALS['LANG']->getLL('l10nmgr.documentation.title') . '</a></li>
				</ul></div>';
        $info .= '<div id="tabcontentcontainer" style="height:190px;border:1px solid gray;padding-right:5px;width:100%;">';
        $info .= '<div id="sc1" class="tabcontent">';
        //$info .= '<div id="sc1" class="tabcontent">';
        $_selectOptions = array('0' => '-default-');
        $_selectOptions = $_selectOptions + $this->MOD_MENU["lang"];
        $info .= '<input type="checkbox" value="1" name="check_exports" /> ' . $GLOBALS['LANG']->getLL('export.xml.check_exports.title') . '<br />';
        $info .= '<input type="checkbox" value="1" checked="checked" name="no_check_xml" /> ' . $GLOBALS['LANG']->getLL('export.xml.no_check_xml.title') . '<br />';
        $info .= '<input type="checkbox" value="1" name="check_utf8" /> ' . $GLOBALS['LANG']->getLL('export.xml.checkUtf8.title') . '<br />';
        $info .= $GLOBALS['LANG']->getLL('export.xml.source-language.title') . $this->_getSelectField("export_xml_forcepreviewlanguage", '0', $_selectOptions) . '<br />';
        // Add the option to send to FTP server, if FTP information is defined
        if (!empty($this->lConf['ftp_server']) && !empty($this->lConf['ftp_server_username']) && !empty($this->lConf['ftp_server_password'])) {
            $info .= '<input type="checkbox" value="1" name="ftp_upload" id="tx_l10nmgr_ftp_upload" /> <label for="tx_l10nmgr_ftp_upload">' . $GLOBALS['LANG']->getLL('export.xml.ftp.title') . '</label>';
        }
        $info .= '<br /><br/>';
        $info .= '<input type="submit" value="Export" name="export_xml" /><br /><br /><br/>';
        $info .= '</div>';
        $info .= '<div id="sc2" class="tabcontent">';
        $info .= '<input type="checkbox" value="1" name="make_preview_link" /> ' . $GLOBALS['LANG']->getLL('import.xml.make_preview_link.title') . '<br />';
        $info .= '<input type="checkbox" value="1" name="import_delL10N" /> ' . $GLOBALS['LANG']->getLL('import.xml.delL10N.title') . '<br />';
        $info .= '<input type="checkbox" value="1" name="import_asdefaultlanguage" /> ' . $GLOBALS['LANG']->getLL('import.xml.asdefaultlanguage.title') . '<br />';
        $info .= '<br />';
        $info .= '<input type="file" size="60" name="uploaded_import_file" /><br /><br /><input type="submit" value="Import" name="import_xml" /><br /><br /> ';
        $info .= '</div>';
        $info .= '<div id="sc3" class="tabcontent">';
        $info .= $this->doc->icons(1) . $GLOBALS['LANG']->getLL('file.settings.available.title');
        for (reset($allowedSettingFiles); list($settingId, $settingFileName) = each($allowedSettingFiles);) {
            $currentFile = GeneralUtility::resolveBackPath($BACK_PATH . \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extRelPath('l10nmgr') . 'settings/' . $settingFileName);
            if (is_file($currentFile) && is_readable($currentFile)) {
                $size = GeneralUtility::formatSize((int) filesize($currentFile), ' Bytes| KB| MB| GB');
                $info .= '<br/><a href="' . GeneralUtility::rawUrlEncodeFP($currentFile) . '" title="' . $GLOBALS['LANG']->getLL('file.settings.download.title') . '" target="_blank">' . $GLOBALS['LANG']->getLL('file.settings.' . $settingId . '.title') . ' (' . $size . ')' . '</a> ';
            }
        }
        $info .= '</div>';
        $info .= '<div id="sc4" class="tabcontent">';
        $info .= '<a href="/' . \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::siteRelPath('l10nmgr') . 'doc/manual.sxw" target="_new">Download</a>';
        $info .= '</div>';
        $info .= '</div>';
        $actionInfo = '';
        // Read uploaded file:
        if (GeneralUtility::_POST('import_xml') && $_FILES['uploaded_import_file']['tmp_name'] && is_uploaded_file($_FILES['uploaded_import_file']['tmp_name'])) {
            $uploadedTempFile = GeneralUtility::upload_to_tempfile($_FILES['uploaded_import_file']['tmp_name']);
            /** @var $factory TranslationDataFactory */
            $factory = GeneralUtility::makeInstance(TranslationDataFactory::class);
            //print "<pre>";
            //var_dump($GLOBALS['BE_USER']->user);
            //print "</pre>";
            if (GeneralUtility::_POST('import_asdefaultlanguage') == '1') {
                $service->setImportAsDefaultLanguage(true);
            }
            if (GeneralUtility::_POST('import_oldformat') == '1') {
                //Support for the old Format of XML Import (without pageGrp element)
                $actionInfo .= $GLOBALS['LANG']->getLL('import.xml.old-format.message');
                $translationData = $factory->getTranslationDataFromOldFormatCATXMLFile($uploadedTempFile);
                $translationData->setLanguage($this->sysLanguage);
                $service->saveTranslation($l10ncfgObj, $translationData);
                $actionInfo .= '<br/><br/>' . $this->doc->icons(1) . 'Import done<br/><br/>(Command count:' . $service->lastTCEMAINCommandsCount . ')';
            } else {
                // Relevant processing of XML Import with the help of the Importmanager
                /** @var $importManager CatXmlImportManager */
                $importManager = GeneralUtility::makeInstance(CatXmlImportManager::class, $uploadedTempFile, $this->sysLanguage, $xmlString = "");
                if ($importManager->parseAndCheckXMLFile() === false) {
                    $actionInfo .= '<br/><br/>' . $this->doc->header($GLOBALS['LANG']->getLL('import.error.title')) . $importManager->getErrorMessages();
                } else {
                    if (GeneralUtility::_POST('import_delL10N') == '1') {
                        $actionInfo .= $GLOBALS['LANG']->getLL('import.xml.delL10N.message') . '<br/>';
                        $delCount = $importManager->delL10N($importManager->getDelL10NDataFromCATXMLNodes($importManager->xmlNodes));
                        $actionInfo .= sprintf($GLOBALS['LANG']->getLL('import.xml.delL10N.count.message'), $delCount) . '<br/><br/>';
                    }
                    if (GeneralUtility::_POST('make_preview_link') == '1') {
                        $pageIds = $importManager->getPidsFromCATXMLNodes($importManager->xmlNodes);
                        $actionInfo .= '<b>' . $GLOBALS['LANG']->getLL('import.xml.preview_links.title') . '</b><br/>';
                        /** @var $mkPreviewLinks MkPreviewLinkService */
                        $mkPreviewLinks = GeneralUtility::makeInstance(MkPreviewLinkService::class, $t3_workspaceId = $importManager->headerData['t3_workspaceId'], $t3_sysLang = $importManager->headerData['t3_sysLang'], $pageIds);
                        $actionInfo .= $mkPreviewLinks->renderPreviewLinks($mkPreviewLinks->mkPreviewLinks());
                    }
                    $translationData = $factory->getTranslationDataFromCATXMLNodes($importManager->getXMLNodes());
                    $translationData->setLanguage($this->sysLanguage);
                    //$actionInfo.="<pre>".var_export($GLOBALS['BE_USER'],true)."</pre>";
                    unset($importManager);
                    $service->saveTranslation($l10ncfgObj, $translationData);
                    $actionInfo .= '<br/>' . $this->doc->icons(-1) . $GLOBALS['LANG']->getLL('import.xml.done.message') . '<br/><br/>(Command count:' . $service->lastTCEMAINCommandsCount . ')';
                }
            }
            GeneralUtility::unlink_tempfile($uploadedTempFile);
        }
        // If export of XML is asked for, do that (this will exit and push a file for download, or upload to FTP is option is checked)
        if (GeneralUtility::_POST('export_xml')) {
            // Save user prefs
            $BE_USER->pushModuleData('l10nmgr/cm1/checkUTF8', GeneralUtility::_POST('check_utf8'));
            // Render the XML
            /** @var $viewClass CatXmlView */
            $viewClass = GeneralUtility::makeInstance(CatXmlView::class, $l10ncfgObj, $this->sysLanguage);
            $export_xml_forcepreviewlanguage = (int) GeneralUtility::_POST('export_xml_forcepreviewlanguage');
            if ($export_xml_forcepreviewlanguage > 0) {
                $viewClass->setForcedSourceLanguage($export_xml_forcepreviewlanguage);
            }
            if ($this->MOD_SETTINGS['onlyChangedContent']) {
                $viewClass->setModeOnlyChanged();
            }
            if ($this->MOD_SETTINGS['noHidden']) {
                $viewClass->setModeNoHidden();
            }
            // Check the export
            if (GeneralUtility::_POST('check_exports') == '1' && $viewClass->checkExports() == false) {
                /** @var $flashMessage FlashMessage */
                $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $GLOBALS['LANG']->getLL('export.process.duplicate.message'), $GLOBALS['LANG']->getLL('export.process.duplicate.title'), FlashMessage::INFO);
                $actionInfo .= $flashMessage->render();
                $actionInfo .= $viewClass->renderExports();
            } else {
                // Upload to FTP
                if (GeneralUtility::_POST('ftp_upload') == '1') {
                    try {
                        $filename = $this->uploadToFtp($viewClass);
                        // Send a mail notification
                        $this->emailNotification($filename, $l10ncfgObj, $this->sysLanguage);
                        // Prepare a success message for display
                        $title = $GLOBALS['LANG']->getLL('export.ftp.success');
                        $message = sprintf($GLOBALS['LANG']->getLL('export.ftp.success.detail'), $this->lConf['ftp_server_path'] . $filename);
                        $status = FlashMessage::OK;
                    } catch (Exception $e) {
                        // Prepare an error message for display
                        $title = $GLOBALS['LANG']->getLL('export.ftp.error');
                        $message = $e->getMessage() . ' (' . $e->getCode() . ')';
                        $status = FlashMessage::ERROR;
                    }
                    /** @var $flashMessage FlashMessage */
                    $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $message, $title, $status);
                    $actionInfo .= $flashMessage->render();
                    $actionInfo .= $viewClass->renderInternalMessagesAsFlashMessage($status);
                    // Download the XML file
                } else {
                    try {
                        $filename = $this->downloadXML($viewClass);
                        // Prepare a success message for display
                        $link = sprintf('<a href="%s" target="_blank">%s</a>', GeneralUtility::getIndpEnv('TYPO3_SITE_URL') . $filename, $filename);
                        $title = $GLOBALS['LANG']->getLL('export.download.success');
                        $message = sprintf($GLOBALS['LANG']->getLL('export.download.success.detail'), $link);
                        $status = FlashMessage::OK;
                    } catch (Exception $e) {
                        // Prepare an error message for display
                        $title = $GLOBALS['LANG']->getLL('export.download.error');
                        $message = $e->getMessage() . ' (' . $e->getCode() . ')';
                        $status = FlashMessage::ERROR;
                    }
                    /** @var $flashMessage FlashMessage */
                    $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $message, $title, $status);
                    $actionInfo .= $flashMessage->render();
                    $actionInfo .= $viewClass->renderInternalMessagesAsFlashMessage($status);
                }
                $viewClass->saveExportInformation();
            }
        }
        if (!empty($actionInfo)) {
            $info .= $this->doc->header($GLOBALS['LANG']->getLL('misc.messages.title'));
            $info .= $actionInfo;
        }
        $info .= '</div>';
        return $info;
    }
Ejemplo n.º 27
0
 /**
  * @test
  */
 public function syslogFixesPermissionsOnFileIfUsingFileLogging()
 {
     if (TYPO3_OS == 'WIN') {
         $this->markTestSkipped('syslogFixesPermissionsOnFileIfUsingFileLogging() test not available on Windows.');
     }
     // Fake all required settings
     $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLogLevel'] = 0;
     $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogInit'] = TRUE;
     unset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog']);
     $testLogFilename = PATH_site . 'typo3temp/' . uniqid('test_') . '.txt';
     $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLog'] = 'file,' . $testLogFilename . ',0';
     $GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'] = '0777';
     // Call method, get actual permissions and clean up
     Utility\GeneralUtility::syslog('testLog', 'test', Utility\GeneralUtility::SYSLOG_SEVERITY_NOTICE);
     clearstatcache();
     $resultFilePermissions = substr(decoct(fileperms($testLogFilename)), 2);
     Utility\GeneralUtility::unlink_tempfile($testLogFilename);
     $this->assertEquals($resultFilePermissions, '0777');
 }
Ejemplo n.º 28
0
 /**
  * Remove temporary file.
  *
  * @param string $filePath
  */
 protected function removeTemporaryFile($filePath)
 {
     if (!GeneralUtility::unlink_tempfile($filePath)) {
         $this->logger->error('Failed to remove file', array('filepath' => $filePath));
     }
 }
Ejemplo n.º 29
0
 /**
  * Cleaning up all the temporary files stored in typo3temp/ folder
  *
  * @return void
  */
 public function unlinkTempFiles()
 {
     foreach ($this->unlinkFiles as $fileName) {
         if (GeneralUtility::isFirstPartOfStr($fileName, PATH_site . 'typo3temp/')) {
             GeneralUtility::unlink_tempfile($fileName);
             clearstatcache();
             if (is_file($fileName)) {
                 $this->error('Error: ' . $fileName . ' was NOT unlinked as it should have been!');
             }
         } else {
             $this->error('Error: ' . $fileName . ' was not in temp-path. Not removed!');
         }
     }
     $this->unlinkFiles = array();
 }
Ejemplo n.º 30
0
 /**
  * @param  $filePath
  * @param  $language
  * @return void
  */
 private function deleteSystemCache($filePath, $language)
 {
     // Delete Cached Language File
     $cacheFileName = self::getCacheFileName($filePath, $language);
     GeneralUtility::unlink_tempfile($cacheFileName);
     // Delete 'default'
     if ($language != 'default') {
         $cacheFileNameDefault = self::getCacheFileName($filePath);
         GeneralUtility::unlink_tempfile($cacheFileNameDefault);
     }
 }