Ejemplo n.º 1
0
 /**
  * Unset all additional properties of test classes to help PHP
  * garbage collection. This reduces memory footprint with lots
  * of tests.
  *
  * If owerwriting tearDown() in test classes, please call
  * parent::tearDown() at the end. Unsetting of own properties
  * is not needed this way.
  *
  * @throws \RuntimeException
  * @return void
  */
 protected function tearDown()
 {
     // Unset properties of test classes to safe memory
     $reflection = new \ReflectionObject($this);
     foreach ($reflection->getProperties() as $property) {
         $declaringClass = $property->getDeclaringClass()->getName();
         if (!$property->isStatic() && $declaringClass !== \TYPO3\CMS\Core\Tests\UnitTestCase::class && $declaringClass !== \TYPO3\CMS\Core\Tests\BaseTestCase::class && strpos($property->getDeclaringClass()->getName(), 'PHPUnit_') !== 0) {
             $propertyName = $property->getName();
             unset($this->{$propertyName});
         }
     }
     unset($reflection);
     // Delete registered test files and directories
     foreach ($this->testFilesToDelete as $absoluteFileName) {
         $absoluteFileName = GeneralUtility::fixWindowsFilePath(PathUtility::getCanonicalPath($absoluteFileName));
         if (!GeneralUtility::validPathStr($absoluteFileName)) {
             throw new \RuntimeException('tearDown() cleanup: Filename contains illegal characters', 1410633087);
         }
         if (!StringUtility::beginsWith($absoluteFileName, PATH_site . 'typo3temp/')) {
             throw new \RuntimeException('tearDown() cleanup:  Files to delete must be within typo3temp/', 1410633412);
         }
         // file_exists returns false for links pointing to not existing targets, so handle links before next check.
         if (@is_link($absoluteFileName) || @is_file($absoluteFileName)) {
             unlink($absoluteFileName);
         } elseif (@is_dir($absoluteFileName)) {
             GeneralUtility::rmdir($absoluteFileName, true);
         } else {
             throw new \RuntimeException('tearDown() cleanup: File, link or directory does not exist', 1410633510);
         }
     }
     $this->testFilesToDelete = array();
 }
 /**
  * @return FlashMessage
  */
 public function execute()
 {
     $this->controller->headerMessage(LocalizationUtility::translate('moveDamRecordsToStorageCommand', 'dam_falmigration', array($this->storageObject->getName())));
     if (!$this->isTableAvailable('tx_dam')) {
         return $this->getResultMessage('damTableNotFound');
     }
     $this->fileIndexRepository = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\Index\\FileIndexRepository');
     $result = $this->execSelectNotMigratedDamRecordsQuery();
     $counter = 0;
     $total = $this->database->sql_num_rows($result);
     $this->controller->infoMessage('Found ' . $total . ' DAM records without a connection to a sys_file storage');
     $relativeTargetFolderBasePath = $this->storageBasePath . $this->targetFolderBasePath;
     while ($damRecord = $this->database->sql_fetch_assoc($result)) {
         $counter++;
         try {
             $relativeSourceFilePath = GeneralUtility::fixWindowsFilePath($this->getFullFileName($damRecord));
             $absoluteSourceFilePath = PATH_site . $relativeSourceFilePath;
             if (!file_exists($absoluteSourceFilePath)) {
                 throw new \RuntimeException('No file found for DAM record. DAM uid: ' . $damRecord['uid'] . ': "' . $relativeSourceFilePath . '"', 1441110613);
             }
             list($_, $directory) = explode('/', dirname($relativeSourceFilePath), 2);
             $relativeTargetFolder = $relativeTargetFolderBasePath . rtrim($directory, '/') . '/';
             $absoluteTargetFolder = PATH_site . $relativeTargetFolder;
             if (!is_dir($absoluteTargetFolder)) {
                 GeneralUtility::mkdir_deep($absoluteTargetFolder);
             }
             $basename = basename($relativeSourceFilePath);
             $absoluteTargetFilePath = $absoluteTargetFolder . $basename;
             if (!file_exists($absoluteTargetFilePath)) {
                 GeneralUtility::upload_copy_move($absoluteSourceFilePath, $absoluteTargetFilePath);
             } elseif (filesize($absoluteSourceFilePath) !== filesize($absoluteTargetFilePath)) {
                 throw new \RuntimeException('File already exists. DAM uid: ' . $damRecord['uid'] . ': "' . $relativeSourceFilePath . '"', 1441112138);
             }
             $fileIdentifier = substr($relativeTargetFolder, strlen($this->storageBasePath)) . $basename;
             $fileObject = $this->storageObject->getFile($fileIdentifier);
             $this->fileIndexRepository->add($fileObject);
             $this->updateDamFilePath($damRecord['uid'], $relativeTargetFolder);
             $this->amountOfMigratedRecords++;
         } catch (\Exception $e) {
             $this->setDamFileMissingByUid($damRecord['uid']);
             $this->controller->warningMessage($e->getMessage());
             $this->amountOfFilesNotFound++;
             continue;
         }
     }
     $this->database->sql_free_result($result);
     $this->controller->message('Not migrated dam records at start of task: ' . $total . '. Migrated files after task: ' . $this->amountOfMigratedRecords . '. Files not found: ' . $this->amountOfFilesNotFound . '.');
     return $this->getResultMessage();
 }
Ejemplo n.º 3
0
 /**
  * Translates an array of paths or single path into absolute paths/path
  *
  * @param mixed $path
  * @return mixed
  */
 public static function translatePath($path)
 {
     if (is_array($path) == FALSE) {
         $path = 0 === strpos($path, '/') ? $path : GeneralUtility::getFileAbsFileName($path);
         if (is_dir($path)) {
             $path = realpath($path) . '/';
         }
         $path = GeneralUtility::fixWindowsFilePath($path);
     } else {
         foreach ($path as $key => $subPath) {
             if (TRUE === in_array($key, self::$knownPathNames)) {
                 $path[$key] = self::translatePath($subPath);
             }
         }
     }
     return $path;
 }
Ejemplo n.º 4
0
 /**
  * Consolidate between Windows and Unix and add trailing slash im missing
  *
  * @param string $path Given path
  * @return string Cleaned up path
  */
 protected function cleanUpPath($path)
 {
     $path = \TYPO3\CMS\Core\Utility\GeneralUtility::fixWindowsFilePath($path);
     // Add trailing slash if missing
     if (!preg_match('/[\\/]$/', $path)) {
         $path .= '/';
     }
     return $path;
 }
Ejemplo n.º 5
0
    /**
     * This method assembles a list of all defined executables search paths
     *
     * @return string HTML to display
     */
    protected function renderExecutablesSearchPathList()
    {
        $searchPaths = \TYPO3\CMS\Core\Utility\CommandUtility::getPaths(TRUE);
        $content = '<br /><h3 class="divider">' . $GLOBALS['LANG']->getLL('search_paths') . '</h3>';
        if (count($searchPaths) == 0) {
            $content .= '<p>' . $GLOBALS['LANG']->getLL('no_search_paths') . '</p>';
        } else {
            $content .= '
			<table cellspacing="1" cellpadding="2" border="0" class="tx_sv_reportlist paths">
				<thead>
					<tr class="t3-row-header">
						<td>' . $GLOBALS['LANG']->getLL('path') . '</td>
						<td>' . $GLOBALS['LANG']->getLL('valid') . '</td>
					</tr>
				</thead>
				<tbody>';
            foreach ($searchPaths as $path => $isValid) {
                $pathAccessibleClass = 'typo3-message message-error';
                $pathAccessible = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:no');
                if ($isValid) {
                    $pathAccessibleClass = 'typo3-message message-ok';
                    $pathAccessible = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:yes');
                }
                $content .= '
					<tr>
						<td class="first-cell ' . $pathAccessibleClass . '">' . \TYPO3\CMS\Core\Utility\GeneralUtility::fixWindowsFilePath($path) . '</td>
						<td class="last-cell ' . $pathAccessibleClass . '">' . $pathAccessible . '</td>
					</tr>';
            }
            $content .= '
				</tbody>
			</table>';
        }
        return $content;
    }
Ejemplo n.º 6
0
 /**
  * Expands the given $patterns by adding an array element for each $replacement
  * replacing occurrences of $search.
  *
  * @param array $patterns
  * @param string $search
  * @param array $replacements
  * @return void
  */
 protected function expandPatterns(array &$patterns, $search, array $replacements)
 {
     $patternsWithReplacements = array();
     foreach ($patterns as $pattern) {
         foreach ($replacements as $replacement) {
             $patternsWithReplacements[] = GeneralUtility::fixWindowsFilePath(str_replace($search, $replacement, $pattern));
         }
     }
     $patterns = $patternsWithReplacements;
 }
Ejemplo n.º 7
0
 /**
  * Resolve the partial path and filename based on $this->getPartialRootPath() and request format
  *
  * @param string $partialName The name of the partial
  * @return string the full path which should be used. The path definitely exists.
  * @throws \TYPO3\CMS\Fluid\View\Exception\InvalidTemplateResourceException
  */
 protected function getPartialPathAndFilename($partialName)
 {
     $partialRootPath = $this->getPartialRootPath();
     if (!is_dir($partialRootPath)) {
         throw new \TYPO3\CMS\Fluid\View\Exception\InvalidTemplateResourceException('Partial root path "' . $partialRootPath . '" does not exist.', 1288094648);
     }
     $possiblePartialPaths = array();
     $possiblePartialPaths[] = \TYPO3\CMS\Core\Utility\GeneralUtility::fixWindowsFilePath($partialRootPath . '/' . $partialName . '.' . $this->getRequest()->getFormat());
     $possiblePartialPaths[] = \TYPO3\CMS\Core\Utility\GeneralUtility::fixWindowsFilePath($partialRootPath . '/' . $partialName);
     foreach ($possiblePartialPaths as $partialPathAndFilename) {
         if (is_file($partialPathAndFilename)) {
             return $partialPathAndFilename;
         }
     }
     throw new \TYPO3\CMS\Fluid\View\Exception\InvalidTemplateResourceException('Could not load partial file. Tried following paths: "' . implode('", "', $possiblePartialPaths) . '".', 1288092556);
 }
Ejemplo n.º 8
0
 /**
  * Renames a file in this storage.
  *
  * @param string $fileIdentifier
  * @param string $newName The target path (including the file name!)
  * @return string The identifier of the file after renaming
  * @throws Exception\ExistingTargetFileNameException
  * @throws \RuntimeException
  */
 public function renameFile($fileIdentifier, $newName)
 {
     // Makes sure the Path given as parameter is valid
     $newName = $this->sanitizeFileName($newName);
     $newIdentifier = rtrim(GeneralUtility::fixWindowsFilePath(PathUtility::dirname($fileIdentifier)), '/') . '/' . $newName;
     $newIdentifier = $this->canonicalizeAndCheckFileIdentifier($newIdentifier);
     // The target should not exist already
     if ($this->fileExists($newIdentifier)) {
         throw new Exception\ExistingTargetFileNameException('The target file "' . $newIdentifier . '" already exists.', 1320291063);
     }
     $sourcePath = $this->getAbsolutePath($fileIdentifier);
     $targetPath = $this->getAbsolutePath($newIdentifier);
     $result = rename($sourcePath, $targetPath);
     if ($result === false) {
         throw new \RuntimeException('Renaming file ' . $sourcePath . ' to ' . $targetPath . ' failed.', 1320375115);
     }
     return $newIdentifier;
 }
 /**
  * Generate a relative path string from an absolute path within a give package path
  *
  * @param string $packagePath
  * @param string $realPathOfClassFile
  * @return string
  */
 protected static function makePathRelative($packagePath, $realPathOfClassFile)
 {
     $realPathOfClassFile = GeneralUtility::fixWindowsFilePath($realPathOfClassFile);
     $classesRealPath = GeneralUtility::fixWindowsFilePath(realpath($packagePath));
     $relativeClassesPath = rtrim(PathUtility::stripPathSitePrefix($packagePath), '/');
     $relativePathToClassFile = $relativeClassesPath . '/' . ltrim(substr($realPathOfClassFile, strlen($classesRealPath)), '/');
     return $relativePathToClassFile;
 }
Ejemplo n.º 10
0
 /**
  * Resolve the partial path and filename based on $this->getPartialRootPaths() and request format
  *
  * @param string $partialName The name of the partial
  * @return string The full path which should be used. The path definitely exists.
  * @throws InvalidTemplateResourceException
  */
 protected function getPartialPathAndFilename($partialName)
 {
     $upperCasedPartialName = ucfirst($partialName);
     $paths = ArrayUtility::sortArrayWithIntegerKeys($this->getPartialRootPaths());
     $paths = array_reverse($paths, TRUE);
     $possiblePartialPaths = array();
     foreach ($paths as $partialRootPath) {
         $possiblePartialPaths[] = GeneralUtility::fixWindowsFilePath($partialRootPath . '/' . $upperCasedPartialName . '.' . $this->getRequest()->getFormat());
         $possiblePartialPaths[] = GeneralUtility::fixWindowsFilePath($partialRootPath . '/' . $upperCasedPartialName);
         if ($upperCasedPartialName !== $partialName) {
             $possiblePartialPaths[] = GeneralUtility::fixWindowsFilePath($partialRootPath . '/' . $partialName . '.' . $this->getRequest()->getFormat());
             $possiblePartialPaths[] = GeneralUtility::fixWindowsFilePath($partialRootPath . '/' . $partialName);
         }
     }
     foreach ($possiblePartialPaths as $partialPathAndFilename) {
         if ($this->testFileExistence($partialPathAndFilename)) {
             return $partialPathAndFilename;
         }
     }
     throw new InvalidTemplateResourceException('Could not load partial file. Tried following paths: "' . implode('", "', $possiblePartialPaths) . '".', 1288092556);
 }
Ejemplo n.º 11
0
 /**
  * Handling files for group/select function
  *
  * @param array $valueArray Array of incoming file references. Keys are numeric, values are files (basically, this is the exploded list of incoming files)
  * @param array $tcaFieldConf Configuration array from TCA of the field
  * @param string $curValue Current value of the field
  * @param array $uploadedFileArray Array of uploaded files, if any
  * @param string $status 'update' or 'new' flag
  * @param string $table tablename of record
  * @param int $id UID of record
  * @param string $recFID Field identifier [table:uid:field] for flexforms
  * @return array Modified value array
  *
  * @throws \RuntimeException
  * @see checkValue_group_select()
  */
 public function checkValue_group_select_file($valueArray, $tcaFieldConf, $curValue, $uploadedFileArray, $status, $table, $id, $recFID)
 {
     // If file handling should NOT be bypassed, do processing:
     if (!$this->bypassFileHandling) {
         // If any files are uploaded, add them to value array
         // Numeric index means that there are multiple files
         if (isset($uploadedFileArray[0])) {
             $uploadedFiles = $uploadedFileArray;
         } else {
             // There is only one file
             $uploadedFiles = array($uploadedFileArray);
         }
         foreach ($uploadedFiles as $uploadedFileArray) {
             if (!empty($uploadedFileArray['name']) && $uploadedFileArray['tmp_name'] !== 'none') {
                 $valueArray[] = $uploadedFileArray['tmp_name'];
                 $this->alternativeFileName[$uploadedFileArray['tmp_name']] = $uploadedFileArray['name'];
             }
         }
         // Creating fileFunc object.
         if (!$this->fileFunc) {
             $this->fileFunc = GeneralUtility::makeInstance(BasicFileUtility::class);
             $this->include_filefunctions = 1;
         }
         // Setting permitted extensions.
         $all_files = array();
         $all_files['webspace']['allow'] = $tcaFieldConf['allowed'];
         $all_files['webspace']['deny'] = $tcaFieldConf['disallowed'] ?: '*';
         $all_files['ftpspace'] = $all_files['webspace'];
         $this->fileFunc->init('', $all_files);
     }
     // If there is an upload folder defined:
     if ($tcaFieldConf['uploadfolder'] && $tcaFieldConf['internal_type'] == 'file') {
         $currentFilesForHistory = null;
         // If filehandling should NOT be bypassed, do processing:
         if (!$this->bypassFileHandling) {
             // For logging..
             $propArr = $this->getRecordProperties($table, $id);
             // Get destrination path:
             $dest = $this->destPathFromUploadFolder($tcaFieldConf['uploadfolder']);
             // If we are updating:
             if ($status == 'update') {
                 // Traverse the input values and convert to absolute filenames in case the update happens to an autoVersionized record.
                 // Background: This is a horrible workaround! The problem is that when a record is auto-versionized the files of the record get copied and therefore get new names which is overridden with the names from the original record in the incoming data meaning both lost files and double-references!
                 // The only solution I could come up with (except removing support for managing files when autoversioning) was to convert all relative files to absolute names so they are copied again (and existing files deleted). This should keep references intact but means that some files are copied, then deleted after being copied _again_.
                 // Actually, the same problem applies to database references in case auto-versioning would include sub-records since in such a case references are remapped - and they would be overridden due to the same principle then.
                 // Illustration of the problem comes here:
                 // We have a record 123 with a file logo.gif. We open and edit the files header in a workspace. So a new version is automatically made.
                 // The versions uid is 456 and the file is copied to "logo_01.gif". But the form data that we sent was based on uid 123 and hence contains the filename "logo.gif" from the original.
                 // The file management code below will do two things: First it will blindly accept "logo.gif" as a file attached to the record (thus creating a double reference) and secondly it will find that "logo_01.gif" was not in the incoming filelist and therefore should be deleted.
                 // If we prefix the incoming file "logo.gif" with its absolute path it will be seen as a new file added. Thus it will be copied to "logo_02.gif". "logo_01.gif" will still be deleted but since the files are the same the difference is zero - only more processing and file copying for no reason. But it will work.
                 if ($this->autoVersioningUpdate === true) {
                     foreach ($valueArray as $key => $theFile) {
                         // If it is an already attached file...
                         if ($theFile === basename($theFile)) {
                             $valueArray[$key] = PATH_site . $tcaFieldConf['uploadfolder'] . '/' . $theFile;
                         }
                     }
                 }
                 // Finding the CURRENT files listed, either from MM or from the current record.
                 $theFileValues = array();
                 // If MM relations for the files also!
                 if ($tcaFieldConf['MM']) {
                     $dbAnalysis = $this->createRelationHandlerInstance();
                     /** @var $dbAnalysis RelationHandler */
                     $dbAnalysis->start('', 'files', $tcaFieldConf['MM'], $id);
                     foreach ($dbAnalysis->itemArray as $item) {
                         if ($item['id']) {
                             $theFileValues[] = $item['id'];
                         }
                     }
                 } else {
                     $theFileValues = GeneralUtility::trimExplode(',', $curValue, true);
                 }
                 $currentFilesForHistory = implode(',', $theFileValues);
                 // DELETE files: If existing files were found, traverse those and register files for deletion which has been removed:
                 if (!empty($theFileValues)) {
                     // Traverse the input values and for all input values which match an EXISTING value, remove the existing from $theFileValues array (this will result in an array of all the existing files which should be deleted!)
                     foreach ($valueArray as $key => $theFile) {
                         if ($theFile && !strstr(GeneralUtility::fixWindowsFilePath($theFile), '/')) {
                             $theFileValues = ArrayUtility::removeArrayEntryByValue($theFileValues, $theFile);
                         }
                     }
                     // This array contains the filenames in the uploadfolder that should be deleted:
                     foreach ($theFileValues as $key => $theFile) {
                         $theFile = trim($theFile);
                         if (@is_file($dest . '/' . $theFile)) {
                             $this->removeFilesStore[] = $dest . '/' . $theFile;
                         } elseif ($this->enableLogging && $theFile) {
                             $this->log($table, $id, 5, 0, 1, 'Could not delete file \'%s\' (does not exist). (%s)', 10, array($dest . '/' . $theFile, $recFID), $propArr['event_pid']);
                         }
                     }
                 }
             }
             // Traverse the submitted values:
             foreach ($valueArray as $key => $theFile) {
                 // Init:
                 $maxSize = (int) $tcaFieldConf['max_size'];
                 // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!
                 $theDestFile = '';
                 // a FAL file was added, now resolve the file object and get the absolute path
                 // @todo in future versions this needs to be modified to handle FAL objects natively
                 if (!empty($theFile) && MathUtility::canBeInterpretedAsInteger($theFile)) {
                     $fileObject = ResourceFactory::getInstance()->getFileObject($theFile);
                     $theFile = $fileObject->getForLocalProcessing(false);
                 }
                 // NEW FILES? If the value contains '/' it indicates, that the file
                 // is new and should be added to the uploadsdir (whether its absolute or relative does not matter here)
                 if (strstr(GeneralUtility::fixWindowsFilePath($theFile), '/')) {
                     // Check various things before copying file:
                     // File and destination must exist
                     if (@is_dir($dest) && (@is_file($theFile) || @is_uploaded_file($theFile))) {
                         // Finding size.
                         if (is_uploaded_file($theFile) && $theFile == $uploadedFileArray['tmp_name']) {
                             $fileSize = $uploadedFileArray['size'];
                         } else {
                             $fileSize = filesize($theFile);
                         }
                         // Check file size:
                         if (!$maxSize || $fileSize <= $maxSize * 1024) {
                             // Prepare filename:
                             $theEndFileName = isset($this->alternativeFileName[$theFile]) ? $this->alternativeFileName[$theFile] : $theFile;
                             $fI = GeneralUtility::split_fileref($theEndFileName);
                             // Check for allowed extension:
                             if ($this->fileFunc->checkIfAllowed($fI['fileext'], $dest, $theEndFileName)) {
                                 $theDestFile = $this->fileFunc->getUniqueName($this->fileFunc->cleanFileName($fI['file']), $dest);
                                 // If we have a unique destination filename, then write the file:
                                 if ($theDestFile) {
                                     GeneralUtility::upload_copy_move($theFile, $theDestFile);
                                     // Hook for post-processing the upload action
                                     if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processUpload'])) {
                                         foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processUpload'] as $classRef) {
                                             $hookObject = GeneralUtility::getUserObj($classRef);
                                             if (!$hookObject instanceof DataHandlerProcessUploadHookInterface) {
                                                 throw new \UnexpectedValueException('$hookObject must implement interface TYPO3\\CMS\\Core\\DataHandling\\DataHandlerProcessUploadHookInterface', 1279962349);
                                             }
                                             $hookObject->processUpload_postProcessAction($theDestFile, $this);
                                         }
                                     }
                                     $this->copiedFileMap[$theFile] = $theDestFile;
                                     clearstatcache();
                                     if ($this->enableLogging && !@is_file($theDestFile)) {
                                         $this->log($table, $id, 5, 0, 1, 'Copying file \'%s\' failed!: The destination path (%s) may be write protected. Please make it write enabled!. (%s)', 16, array($theFile, dirname($theDestFile), $recFID), $propArr['event_pid']);
                                     }
                                 } elseif ($this->enableLogging) {
                                     $this->log($table, $id, 5, 0, 1, 'Copying file \'%s\' failed!: No destination file (%s) possible!. (%s)', 11, array($theFile, $theDestFile, $recFID), $propArr['event_pid']);
                                 }
                             } elseif ($this->enableLogging) {
                                 $this->log($table, $id, 5, 0, 1, 'File extension \'%s\' not allowed. (%s)', 12, array($fI['fileext'], $recFID), $propArr['event_pid']);
                             }
                         } elseif ($this->enableLogging) {
                             $this->log($table, $id, 5, 0, 1, 'Filesize (%s) of file \'%s\' exceeds limit (%s). (%s)', 13, array(GeneralUtility::formatSize($fileSize), $theFile, GeneralUtility::formatSize($maxSize * 1024), $recFID), $propArr['event_pid']);
                         }
                     } elseif ($this->enableLogging) {
                         $this->log($table, $id, 5, 0, 1, 'The destination (%s) or the source file (%s) does not exist. (%s)', 14, array($dest, $theFile, $recFID), $propArr['event_pid']);
                     }
                     // If the destination file was created, we will set the new filename in the value array, otherwise unset the entry in the value array!
                     if (@is_file($theDestFile)) {
                         $info = GeneralUtility::split_fileref($theDestFile);
                         // The value is set to the new filename
                         $valueArray[$key] = $info['file'];
                     } else {
                         // The value is set to the new filename
                         unset($valueArray[$key]);
                     }
                 }
             }
         }
         // If MM relations for the files, we will set the relations as MM records and change the valuearray to contain a single entry with a count of the number of files!
         if ($tcaFieldConf['MM']) {
             /** @var $dbAnalysis RelationHandler */
             $dbAnalysis = $this->createRelationHandlerInstance();
             // Dummy
             $dbAnalysis->tableArray['files'] = array();
             foreach ($valueArray as $key => $theFile) {
                 // Explode files
                 $dbAnalysis->itemArray[]['id'] = $theFile;
             }
             if ($status == 'update') {
                 $dbAnalysis->writeMM($tcaFieldConf['MM'], $id, 0);
                 $newFiles = implode(',', $dbAnalysis->getValueArray());
                 list(, , $recFieldName) = explode(':', $recFID);
                 if ($currentFilesForHistory != $newFiles) {
                     $this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$recFieldName] = $currentFilesForHistory;
                     $this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$recFieldName] = $newFiles;
                 } else {
                     $this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$recFieldName] = '';
                     $this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$recFieldName] = '';
                 }
             } else {
                 $this->dbAnalysisStore[] = array($dbAnalysis, $tcaFieldConf['MM'], $id, 0);
             }
             $valueArray = $dbAnalysis->countItems();
         }
     } else {
         if (!empty($valueArray)) {
             // If filehandling should NOT be bypassed, do processing:
             if (!$this->bypassFileHandling) {
                 // For logging..
                 $propArr = $this->getRecordProperties($table, $id);
                 foreach ($valueArray as &$theFile) {
                     // FAL handling: it's a UID, thus it is resolved to the absolute path
                     if (!empty($theFile) && MathUtility::canBeInterpretedAsInteger($theFile)) {
                         $fileObject = ResourceFactory::getInstance()->getFileObject($theFile);
                         $theFile = $fileObject->getForLocalProcessing(false);
                     }
                     if ($this->alternativeFilePath[$theFile]) {
                         // If alternative File Path is set for the file, then it was an import
                         // don't import the file if it already exists
                         if (@is_file(PATH_site . $this->alternativeFilePath[$theFile])) {
                             $theFile = PATH_site . $this->alternativeFilePath[$theFile];
                         } elseif (@is_file($theFile)) {
                             $dest = dirname(PATH_site . $this->alternativeFilePath[$theFile]);
                             if (!@is_dir($dest)) {
                                 GeneralUtility::mkdir_deep(PATH_site, dirname($this->alternativeFilePath[$theFile]) . '/');
                             }
                             // Init:
                             $maxSize = (int) $tcaFieldConf['max_size'];
                             // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!
                             $theDestFile = '';
                             $fileSize = filesize($theFile);
                             // Check file size:
                             if (!$maxSize || $fileSize <= $maxSize * 1024) {
                                 // Prepare filename:
                                 $theEndFileName = isset($this->alternativeFileName[$theFile]) ? $this->alternativeFileName[$theFile] : $theFile;
                                 $fI = GeneralUtility::split_fileref($theEndFileName);
                                 // Check for allowed extension:
                                 if ($this->fileFunc->checkIfAllowed($fI['fileext'], $dest, $theEndFileName)) {
                                     $theDestFile = PATH_site . $this->alternativeFilePath[$theFile];
                                     // Write the file:
                                     if ($theDestFile) {
                                         GeneralUtility::upload_copy_move($theFile, $theDestFile);
                                         $this->copiedFileMap[$theFile] = $theDestFile;
                                         clearstatcache();
                                         if ($this->enableLogging && !@is_file($theDestFile)) {
                                             $this->log($table, $id, 5, 0, 1, 'Copying file \'%s\' failed!: The destination path (%s) may be write protected. Please make it write enabled!. (%s)', 16, array($theFile, dirname($theDestFile), $recFID), $propArr['event_pid']);
                                         }
                                     } elseif ($this->enableLogging) {
                                         $this->log($table, $id, 5, 0, 1, 'Copying file \'%s\' failed!: No destination file (%s) possible!. (%s)', 11, array($theFile, $theDestFile, $recFID), $propArr['event_pid']);
                                     }
                                 } elseif ($this->enableLogging) {
                                     $this->log($table, $id, 5, 0, 1, 'File extension \'%s\' not allowed. (%s)', 12, array($fI['fileext'], $recFID), $propArr['event_pid']);
                                 }
                             } elseif ($this->enableLogging) {
                                 $this->log($table, $id, 5, 0, 1, 'Filesize (%s) of file \'%s\' exceeds limit (%s). (%s)', 13, array(GeneralUtility::formatSize($fileSize), $theFile, GeneralUtility::formatSize($maxSize * 1024), $recFID), $propArr['event_pid']);
                             }
                             // If the destination file was created, we will set the new filename in the value array, otherwise unset the entry in the value array!
                             if (@is_file($theDestFile)) {
                                 // The value is set to the new filename
                                 $theFile = $theDestFile;
                             } else {
                                 // The value is set to the new filename
                                 unset($theFile);
                             }
                         }
                     }
                     if (!empty($theFile)) {
                         $theFile = GeneralUtility::fixWindowsFilePath($theFile);
                         if (GeneralUtility::isFirstPartOfStr($theFile, PATH_site)) {
                             $theFile = PathUtility::stripPathSitePrefix($theFile);
                         }
                     }
                 }
                 unset($theFile);
             }
         }
     }
     return $valueArray;
 }
Ejemplo n.º 12
0
 /**
  * @test
  */
 public function setCacheDirectoryAllowsRelativeDottedPathWithTrailingSlash()
 {
     $backend = $this->getAccessibleMock(\TYPO3\CMS\Core\Cache\Backend\FileBackend::class, array('dummy'), array(), '', false);
     $backend->_set('cacheIdentifier', 'test');
     $backend->setCacheDirectory('../tmp/foo/');
     // get PATH_site without trailing slash
     $path = GeneralUtility::fixWindowsFilePath(realpath(PATH_site));
     $this->assertEquals($path . '/../tmp/foo/test/', $backend->_get('temporaryCacheDirectory'));
 }
Ejemplo n.º 13
0
 /**
  * Save a uploaded file
  *
  * @param string $uploadedFile
  * @return NULL|string
  */
 public function saveUploadedFile($uploadedFile)
 {
     if (is_uploaded_file($uploadedFile)) {
         $tempFilename = GeneralUtility::upload_to_tempfile($uploadedFile);
         if (TYPO3_OS === 'WIN') {
             $tempFilename = GeneralUtility::fixWindowsFilePath($tempFilename);
         }
         if ($tempFilename !== '') {
             return $tempFilename;
         }
     }
     return null;
 }
Ejemplo n.º 14
0
 /**
  * Store uploaded files in the typo3temp and return the information of those
  * files
  *
  * @return void
  */
 public function storeFiles()
 {
     $formData = $this->getByMethod();
     if (isset($_FILES[$this->prefix]) && is_array($_FILES[$this->prefix])) {
         foreach ($_FILES[$this->prefix]['tmp_name'] as $fieldName => $uploadedFile) {
             if (is_uploaded_file($uploadedFile)) {
                 $tempFilename = GeneralUtility::upload_to_tempfile($uploadedFile);
                 if (TYPO3_OS === 'WIN') {
                     $tempFilename = GeneralUtility::fixWindowsFilePath($tempFilename);
                 }
                 if ($tempFilename !== '') {
                     $fileInfo = GeneralUtility::makeInstance(FileInfo::class, $tempFilename);
                     $formData[$fieldName] = array('tempFilename' => $tempFilename, 'originalFilename' => $_FILES[$this->prefix]['name'][$fieldName], 'type' => $fileInfo->getMimeType(), 'size' => (int) $_FILES[$this->prefix]['size'][$fieldName]);
                 }
             }
         }
     }
     switch ($this->getMethod()) {
         case 'post':
             $_POST[$this->prefix] = $formData;
             break;
         case 'get':
             $_GET[$this->prefix] = $formData;
             break;
         case 'session':
             $this->sessionData = $formData;
             break;
     }
 }
Ejemplo n.º 15
0
 /**
  * Store uploaded files in the typo3temp and return the information of those
  * files
  *
  * @return void
  */
 public function storeFiles()
 {
     $formData = $this->getByMethod();
     if (isset($_FILES[$this->prefix]) && is_array($_FILES[$this->prefix])) {
         foreach ($_FILES[$this->prefix]['tmp_name'] as $fieldName => $uploadedFile) {
             if (is_uploaded_file($uploadedFile)) {
                 $tempFilename = \TYPO3\CMS\Core\Utility\GeneralUtility::upload_to_tempfile($uploadedFile);
                 if (TYPO3_OS === 'WIN') {
                     $tempFilename = \TYPO3\CMS\Core\Utility\GeneralUtility::fixWindowsFilePath($tempFilename);
                 }
                 if ($tempFilename !== '') {
                     // Use finfo to get the mime type
                     $finfo = finfo_open(FILEINFO_MIME_TYPE);
                     $mimeType = finfo_file($finfo, $tempFilename);
                     finfo_close($finfo);
                     $formData[$fieldName] = array('tempFilename' => $tempFilename, 'originalFilename' => $_FILES[$this->prefix]['name'][$fieldName], 'type' => $mimeType, 'size' => (int) $_FILES[$this->prefix]['size'][$fieldName]);
                 }
             }
         }
     }
     switch ($this->getMethod()) {
         case 'post':
             $_POST[$this->prefix] = $formData;
             break;
         case 'get':
             $_GET[$this->prefix] = $formData;
             break;
         case 'session':
             $this->sessionData = $formData;
             break;
     }
 }
Ejemplo n.º 16
0
 /**
  * Create and return the armor fields for this validator
  * 
  * @return \string                 Armor fields
  */
 protected function _armor()
 {
     $now = null;
     // Add the HMAC hidden field
     $armor = '<input type="hidden" name="' . htmlspecialchars($this->_token) . '[hmac]" value="' . htmlspecialchars($this->_hmac($now)) . '"/>';
     // Add the timestamp field
     if ($now !== null) {
         $armor .= '<input type="hidden" name="' . htmlspecialchars($this->_token) . '[ts]" value="' . intval($now) . '"/>';
     }
     // Add the honeypot field
     if ($this->_honeypotEnabled()) {
         $viewSettings = $this->_setup('view.');
         /* @var $standaloneView \TYPO3\CMS\Fluid\View\StandaloneView */
         $standaloneView = $this->_objectManager->get('TYPO3\\CMS\\Fluid\\View\\StandaloneView');
         if (version_compare(TYPO3_version, '7.3.0', '>=')) {
             $standaloneView->setTemplateRootPaths($viewSettings['templateRootPaths.']);
             $standaloneView->setTemplate('Armor/Honeypot.html');
         } else {
             $templateRootPaths = \TYPO3\CMS\Extbase\Utility\ArrayUtility::sortArrayWithIntegerKeys($viewSettings['templateRootPaths.']);
             foreach (array_reverse($templateRootPaths) as $templateRootPath) {
                 $templateRootPathAndFileName = \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName(\TYPO3\CMS\Core\Utility\GeneralUtility::fixWindowsFilePath($templateRootPath . '/Armor/Honeypot.html'), FALSE);
                 if (@file_exists($templateRootPathAndFileName) && @is_readable($templateRootPathAndFileName)) {
                     $standaloneView->setTemplatePathAndFilename($templateRootPathAndFileName);
                     break;
                 }
             }
         }
         $standaloneView->setPartialRootPaths($viewSettings['partialRootPaths.']);
         $standaloneView->setLayoutRootPaths($viewSettings['layoutRootPaths.']);
         $standaloneView->assign('honeypots', array_keys($this->_honeypotFields()));
         $armor .= $standaloneView->render();
     }
     return $armor;
 }
Ejemplo n.º 17
0
    /**
     * This method assembles a list of all defined executables search paths
     *
     * @return string HTML to display
     */
    protected function renderExecutablesSearchPathList()
    {
        $searchPaths = CommandUtility::getPaths(TRUE);
        $content = '<h3>' . $this->getLanguageService()->getLL('search_paths') . '</h3>';
        if (empty($searchPaths)) {
            $content .= '<p>' . $this->getLanguageService()->getLL('no_search_paths') . '</p>';
        } else {
            $content .= '
			<table class="table table-striped table-hover tx_sv_reportlist">
				<thead>
					<tr>
						<td>' . $this->getLanguageService()->getLL('path') . '</td>
						<td>' . $this->getLanguageService()->getLL('valid') . '</td>
					</tr>
				</thead>
				<tbody>';
            foreach ($searchPaths as $path => $isValid) {
                $pathAccessibleClass = 'danger';
                $pathAccessible = $this->getLanguageService()->sL('LLL:EXT:lang/locallang_common.xlf:no');
                if ($isValid) {
                    $pathAccessibleClass = 'success';
                    $pathAccessible = $this->getLanguageService()->sL('LLL:EXT:lang/locallang_common.xlf:yes');
                }
                $content .= '
					<tr class="' . $pathAccessibleClass . '">
						<td class="first-cell">' . GeneralUtility::fixWindowsFilePath($path) . '</td>
						<td class="last-cell">' . $pathAccessible . '</td>
					</tr>';
            }
            $content .= '
				</tbody>
			</table>';
        }
        return $content;
    }
Ejemplo n.º 18
0
 protected function getViewFileName(\TYPO3\CMS\Extbase\Mvc\Controller\ControllerContext $controllerContext)
 {
     // try to get the view name based upon the controller/action
     $controller = $controllerContext->getRequest()->getControllerName();
     $action = $controllerContext->getRequest()->getControllerActionName();
     $file = $controller . '/' . ucfirst($action) . '.tpl';
     $paths = $this->getTemplateRootPaths();
     $paths = \TYPO3\CMS\Extbase\Utility\ArrayUtility::sortArrayWithIntegerKeys($paths);
     $paths = array_reverse($paths, true);
     foreach ($paths as $rootPath) {
         $fileName = GeneralUtility::fixWindowsFilePath($rootPath . '/' . $file);
         $fileName = GeneralUtility::getFileAbsFileName($fileName);
         if (file_exists($fileName)) {
             return $fileName;
         }
     }
     // no view found
     throw new \Exception('Template not found for ' . $controller . '->' . $action);
 }
 /**
  * Remove specified directory
  *
  * @param string $extDirPath
  * @throws ExtensionManagerException
  * @return void
  */
 public function removeDirectory($extDirPath)
 {
     $extDirPath = GeneralUtility::fixWindowsFilePath($extDirPath);
     $extensionPathWithoutTrailingSlash = rtrim($extDirPath, '/');
     if (is_link($extensionPathWithoutTrailingSlash) && TYPO3_OS !== 'WIN') {
         $result = unlink($extensionPathWithoutTrailingSlash);
     } else {
         $result = GeneralUtility::rmdir($extDirPath, TRUE);
     }
     if ($result === FALSE) {
         throw new ExtensionManagerException(sprintf($this->getLanguageService()->getLL('clearMakeExtDir_could_not_remove_dir'), $this->getRelativePath($extDirPath)), 1337280415);
     }
 }
Ejemplo n.º 20
0
	/**
	 * Wrapper method to make the static call to GeneralUtility mockable in tests
	 *
	 * @param string $pathAndFilename
	 *
	 * @return string absolute pathAndFilename
	 */
	protected function resolveFileNamePath($pathAndFilename) {
		return GeneralUtility::getFileAbsFileName(GeneralUtility::fixWindowsFilePath($pathAndFilename), TRUE);
	}
Ejemplo n.º 21
0
 /**
  * @test
  */
 public function getLayoutSourceReturnsContentOfDefaultLayoutFileIfNoLayoutExistsForTheSpecifiedFormat()
 {
     $layoutRootPath = GeneralUtility::fixWindowsFilePath(__DIR__) . '/Fixtures';
     $this->view->setLayoutRootPath($layoutRootPath);
     $this->mockRequest->expects($this->once())->method('getFormat')->will($this->returnValue('foo'));
     $this->view->expects($this->at(0))->method('testFileExistence')->with($layoutRootPath . '/LayoutFixture.foo')->will($this->returnValue(false));
     $this->view->expects($this->at(1))->method('testFileExistence')->with($layoutRootPath . '/LayoutFixture')->will($this->returnValue(true));
     $expectedResult = file_get_contents($layoutRootPath . '/LayoutFixture');
     $actualResult = $this->view->_call('getLayoutSource', 'LayoutFixture');
     $this->assertEquals($expectedResult, $actualResult);
 }
Ejemplo n.º 22
0
 /**
  * Remove specified directory
  *
  * @param string $extDirPath
  * @throws ExtensionManagerException
  * @return void
  */
 public function removeDirectory($extDirPath)
 {
     $extDirPath = GeneralUtility::fixWindowsFilePath($extDirPath);
     $extensionPathWithoutTrailingSlash = rtrim($extDirPath, '/');
     if (is_link($extensionPathWithoutTrailingSlash) && TYPO3_OS !== 'WIN') {
         $result = unlink($extensionPathWithoutTrailingSlash);
     } else {
         $result = GeneralUtility::rmdir($extDirPath, true);
     }
     if ($result === false) {
         throw new ExtensionManagerException(sprintf($this->languageService->getLL('fileHandling.couldNotRemoveDirectory'), $this->getRelativePath($extDirPath)), 1337280415);
     }
 }
Ejemplo n.º 23
0
 /**
  * Renames a folder in this storage.
  *
  * @param \TYPO3\CMS\Core\Resource\Folder $folder
  * @param string $newName The target path (including the file name!)
  * @return array A map of old to new file identifiers
  * @throws \RuntimeException if renaming the folder failed
  */
 public function renameFolder(\TYPO3\CMS\Core\Resource\Folder $folder, $newName)
 {
     // Makes sure the path given as parameter is valid
     $newName = $this->sanitizeFileName($newName);
     $relativeSourcePath = $folder->getIdentifier();
     $sourcePath = $this->getAbsolutePath($relativeSourcePath);
     $relativeTargetPath = rtrim(GeneralUtility::fixWindowsFilePath(dirname($relativeSourcePath)), '/') . '/' . $newName . '/';
     $targetPath = $this->getAbsolutePath($relativeTargetPath);
     // get all files and folders we are going to move, to have a map for updating later.
     $filesAndFolders = $this->getFileAndFoldernamesInPath($sourcePath, TRUE);
     $result = rename($sourcePath, $targetPath);
     if ($result === FALSE) {
         throw new \RuntimeException(sprintf('Renaming folder "%1$s" to "%2$s" failed."', $sourcePath, $targetPath), 1320375116);
     }
     try {
         // Create a mapping from old to new identifiers
         $identifierMap = $this->createIdentifierMap($filesAndFolders, $relativeSourcePath, $relativeTargetPath);
     } catch (\Exception $e) {
         rename($targetPath, $sourcePath);
         throw new \RuntimeException(sprintf('Creating filename mapping after renaming "%1$s" to "%2$s" failed. Reverted rename operation.\\n\\nOriginal error: %3$s"', $sourcePath, $targetPath, $e->getMessage()), 1334160746);
     }
     return $identifierMap;
 }
 /**
  * Resolve the partial path and filename
  * 		based on $this->getPartialRootPaths() and request format
  *
  * @param string $partialName The name of the partial
  * @return string the full path which should be used. The path definitely exists.
  * @throws InvalidTemplateResourceException
  */
 protected function getPartialPathAndFilename($partialName)
 {
     $partialRootPaths = $this->getPartialRootPaths();
     foreach ($partialRootPaths as $pathIndex => $partialRootPath) {
         if (!is_dir($partialRootPath)) {
             unset($partialRootPaths[$pathIndex]);
         }
     }
     if (empty($partialRootPaths)) {
         throw new InvalidTemplateResourceException('Partial root paths do not exist.', 1410653918);
     }
     $possiblePartialPaths = array();
     foreach ($partialRootPaths as $partialRootPath) {
         $possiblePartialPaths[] = GeneralUtility::fixWindowsFilePath($partialRootPath . '/' . $partialName . '.' . $this->getRequest()->getFormat());
         $possiblePartialPaths[] = GeneralUtility::fixWindowsFilePath($partialRootPath . '/' . $partialName);
     }
     foreach ($possiblePartialPaths as $pathAndFilename) {
         if (is_file($pathAndFilename)) {
             return $pathAndFilename;
         }
     }
     throw new InvalidTemplateResourceException('Could not load partial file. Tried following paths: "' . implode('", "', $possiblePartialPaths) . '".', 1288092556);
     return '';
 }
Ejemplo n.º 25
0
 /**
  * Compile the command for running ImageMagick/GraphicsMagick.
  *
  * @param string $command Command to be run: identify, convert or combine/composite
  * @param string $parameters The parameters string
  * @param string $path Override the default path (e.g. used by the install tool)
  * @return string Compiled command that deals with IM6 & GraphicsMagick
  */
 public static function imageMagickCommand($command, $parameters, $path = '')
 {
     $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
     $isExt = TYPO3_OS == 'WIN' ? '.exe' : '';
     $switchCompositeParameters = FALSE;
     if (!$path) {
         $path = $gfxConf['im_path'];
     }
     $path = \TYPO3\CMS\Core\Utility\GeneralUtility::fixWindowsFilePath($path);
     $im_version = strtolower($gfxConf['im_version_5']);
     $combineScript = $gfxConf['im_combine_filename'] ? trim($gfxConf['im_combine_filename']) : 'combine';
     // This is only used internally, has no effect outside
     if ($command === 'combine') {
         $command = 'composite';
     }
     // Compile the path & command
     if ($im_version === 'gm') {
         $switchCompositeParameters = TRUE;
         $path = escapeshellarg($path . 'gm' . $isExt) . ' ' . $command;
     } else {
         if ($im_version === 'im6') {
             $switchCompositeParameters = TRUE;
         }
         $path = escapeshellarg($path . ($command == 'composite' ? $combineScript : $command) . $isExt);
     }
     // strip profile information for thumbnails and reduce their size
     if ($parameters && $command != 'identify' && $gfxConf['im_useStripProfileByDefault'] && $gfxConf['im_stripProfileCommand'] != '') {
         if (strpos($parameters, $gfxConf['im_stripProfileCommand']) === FALSE) {
             // Determine whether the strip profile action has be disabled by TypoScript:
             if ($parameters !== '-version' && strpos($parameters, '###SkipStripProfile###') === FALSE) {
                 $parameters = $gfxConf['im_stripProfileCommand'] . ' ' . $parameters;
             } else {
                 $parameters = str_replace('###SkipStripProfile###', '', $parameters);
             }
         }
     }
     $cmdLine = $path . ' ' . $parameters;
     // Because of some weird incompatibilities between ImageMagick 4 and 6 (plus GraphicsMagick),
     // it is needed to change the parameters order under some preconditions
     if ($command == 'composite' && $switchCompositeParameters) {
         $paramsArr = \TYPO3\CMS\Core\Utility\GeneralUtility::unQuoteFilenames($parameters);
         // The mask image has been specified => swap the parameters
         if (count($paramsArr) > 5) {
             $tmp = $paramsArr[count($paramsArr) - 3];
             $paramsArr[count($paramsArr) - 3] = $paramsArr[count($paramsArr) - 4];
             $paramsArr[count($paramsArr) - 4] = $tmp;
         }
         $cmdLine = $path . ' ' . implode(' ', $paramsArr);
     }
     return $cmdLine;
 }
Ejemplo n.º 26
0
<?php

defined('TYPO3_MODE') or die('Access denied.');
$composerAutoloadFile = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('phpunit') . 'Composer/vendor/autoload.php';
/** @var $extensionSettingsService Tx_Phpunit_Service_ExtensionSettingsService */
$extensionSettingsService = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('Tx_Phpunit_Service_ExtensionSettingsService');
$composerPhpUnitPath = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('phpunit') . 'Composer/vendor/phpunit/phpunit/';
if ($extensionSettingsService->hasString('composerpath')) {
    $userComposerPath = rtrim(\TYPO3\CMS\Core\Utility\GeneralUtility::fixWindowsFilePath($extensionSettingsService->getAsString('composerpath')), '/');
    if (is_dir($userComposerPath . '/vendor/') && is_file($userComposerPath . '/vendor/autoload.php')) {
        if (set_include_path($userComposerPath . PATH_SEPARATOR . get_include_path()) !== FALSE) {
            $composerAutoloadFile = $userComposerPath . '/vendor/autoload.php';
        }
    }
}
unset($extensionSettingsService);
require_once $composerAutoloadFile;
require_once \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('phpunit') . 'Migrations/vfsStream.php';
$GLOBALS['TYPO3_CONF_VARS']['BE']['AJAX']['Tx_Phpunit_BackEnd_Ajax'] = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('phpunit') . 'Classes/BackEnd/Ajax.php:Tx_Phpunit_BackEnd_Ajax->ajaxBroker';
if (TYPO3_MODE === 'BE') {
    $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['cliKeys']['phpunit'] = array('EXT:' . $_EXTKEY . '/Scripts/ManualCliTestRunner.php', '_CLI_phpunit');
    $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['cliKeys']['phpunit_ide_testrunner'] = array('EXT:' . $_EXTKEY . '/Scripts/IdeTestRunner.php', '_CLI_phpunit');
}
Ejemplo n.º 27
0
 /**
  * Returns the first trace information which is not caused by the PHPUnit file
  * "Framework/Assert.php".
  *
  * @param array[] $traceData the trace data
  *
  * @return array trace information
  */
 protected function getFirstNonPhpUnitTrace(array $traceData)
 {
     $testCaseTraceData = array();
     foreach ($traceData as $singleTraceArr) {
         if (!stristr(GeneralUtility::fixWindowsFilePath($singleTraceArr['file']), 'Framework/Assert.php')) {
             $testCaseTraceData = $singleTraceArr;
             break;
         }
     }
     return $testCaseTraceData;
 }
Ejemplo n.º 28
0
 /**
  * @test
  */
 public function filesCanBeCopiedToATemporaryPath()
 {
     $fileContents = 'asdfgh';
     $this->addToMount(array('someDir' => array('someFile' => $fileContents)));
     $fixture = $this->createDriverFixture(array('basePath' => $this->getMountRootUrl()));
     $mockedFile = $this->getSimpleFileMock('/someDir/someFile');
     $filePath = GeneralUtility::fixWindowsFilePath($fixture->copyFileToTemporaryPath($mockedFile));
     $this->assertContains('/typo3temp/', $filePath);
     $this->assertEquals($fileContents, file_get_contents($filePath));
 }
Ejemplo n.º 29
0
 /**
  * @test
  */
 public function filesCanBeCopiedToATemporaryPath()
 {
     $fileContents = 'asdfgh';
     $this->addToMount(array('someDir' => array('someFile' => $fileContents)));
     $fixture = $this->createDriverFixture();
     $filePath = GeneralUtility::fixWindowsFilePath($fixture->_call('copyFileToTemporaryPath', '/someDir/someFile'));
     $this->testFilesToDelete[] = $filePath;
     $this->assertContains('/typo3temp/', $filePath);
     $this->assertEquals($fileContents, file_get_contents($filePath));
 }
 /**
  * Generate a relative path string from an absolute path within a give package path
  *
  * @param string $packagePath
  * @param string $realPathOfClassFile
  * @param bool $relativeToRoot
  * @return string
  */
 protected function makePathRelative($packagePath, $realPathOfClassFile, $relativeToRoot = true)
 {
     $realPathOfClassFile = GeneralUtility::fixWindowsFilePath($realPathOfClassFile);
     $packageRealPath = GeneralUtility::fixWindowsFilePath(realpath($packagePath));
     $relativePackagePath = rtrim(substr($packagePath, strlen($this->installationRoot)), '/');
     if ($relativeToRoot) {
         if ($realPathOfClassFile === $packageRealPath) {
             $relativePathToClassFile = $relativePackagePath;
         } else {
             $relativePathToClassFile = $relativePackagePath . '/' . ltrim(substr($realPathOfClassFile, strlen($packageRealPath)), '/');
         }
     } else {
         $relativePathToClassFile = ltrim(substr($realPathOfClassFile, strlen($packageRealPath)), '/');
     }
     return $relativePathToClassFile;
 }