/**
  * This test creates an extension based on a JSON file, generated
  * with version 1.0 of the ExtensionBuilder and compares all
  * generated files with the originally created ones
  * This test should help, to find compatibility breaking changes
  *
  * @test
  */
 function generateExtensionFromVersion1Configuration()
 {
     $this->configurationManager = $this->getMock($this->buildAccessibleProxy('Tx_ExtensionBuilder_Configuration_ConfigurationManager'), array('dummy'));
     $this->extensionSchemaBuilder = $this->objectManager->get('Tx_ExtensionBuilder_Service_ExtensionSchemaBuilder');
     $testExtensionDir = PATH_typo3conf . 'ext/extension_builder/Tests/Examples/TestExtensions/test_extension_v1/';
     $jsonFile = $testExtensionDir . Tx_ExtensionBuilder_Configuration_ConfigurationManager::EXTENSION_BUILDER_SETTINGS_FILE;
     if (file_exists($jsonFile)) {
         // compatibility adaptions for configurations from older versions
         $extensionConfigurationJSON = json_decode(file_get_contents($jsonFile), TRUE);
         $extensionConfigurationJSON = $this->configurationManager->fixExtensionBuilderJSON($extensionConfigurationJSON);
     } else {
         $this->fail('JSON file not found');
     }
     $this->extension = $this->extensionSchemaBuilder->build($extensionConfigurationJSON);
     $this->codeGenerator->setSettings(array('codeTemplateRootPath' => PATH_typo3conf . 'ext/extension_builder/Resources/Private/CodeTemplates/Extbase/', 'extConf' => array('enableRoundtrip' => '0')));
     $newExtensionDir = vfsStream::url('testDir') . '/';
     $this->extension->setExtensionDir($newExtensionDir . 'test_extension/');
     $this->codeGenerator->build($this->extension);
     $referenceFiles = t3lib_div::getAllFilesAndFoldersInPath(array(), $testExtensionDir);
     foreach ($referenceFiles as $referenceFile) {
         $createdFile = str_replace($testExtensionDir, $this->extension->getExtensionDir(), $referenceFile);
         if (!in_array(basename($createdFile), array('ExtensionBuilder.json'))) {
             // json file is generated by controller
             $referenceFileContent = str_replace(array('2011-08-11', '###YEAR###'), array(date('Y-m-d'), date('Y')), file_get_contents($referenceFile));
             //t3lib_div::writeFile(PATH_site.'fileadmin/'.basename($createdFile), file_get_contents($createdFile));
             $this->assertFileExists($createdFile, 'File ' . $createdFile . ' was not created!');
             $this->assertEquals(t3lib_div::trimExplode("\n", $referenceFileContent, TRUE), t3lib_div::trimExplode("\n", file_get_contents($createdFile), TRUE), 'File ' . $createdFile . ' was not equal to original file.');
         }
     }
 }
Ejemplo n.º 2
0
 /**
  * Recursively gather all files and folders of a path.
  * Usage: 5
  *
  * @param	array		$fileArr: Empty input array (will have files added to it)
  * @param	string		$path: The path to read recursively from (absolute) (include trailing slash!)
  * @param	string		$extList: Comma list of file extensions: Only files with extensions in this list (if applicable) will be selected.
  * @param	boolean		$regDirs: If set, directories are also included in output.
  * @param	integer		$recursivityLevels: The number of levels to dig down...
  * @return	array		An array with the found files/directories.
  */
 function getAllFilesAndFoldersInPath($fileArr, $path, $extList = '', $regDirs = 0, $recursivityLevels = 99)
 {
     if ($regDirs) {
         $fileArr[] = $path;
     }
     $fileArr = array_merge($fileArr, t3lib_div::getFilesInDir($path, $extList, 1, 1));
     $dirs = t3lib_div::get_dirs($path);
     if (is_array($dirs) && $recursivityLevels > 0) {
         foreach ($dirs as $subdirs) {
             if ((string) $subdirs != '') {
                 $fileArr = t3lib_div::getAllFilesAndFoldersInPath($fileArr, $path . $subdirs . '/', $extList, $regDirs, $recursivityLevels - 1);
             }
         }
     }
     return $fileArr;
 }
 /**
  * Make upload array out of extension
  *
  * @param	string		Extension key
  * @param	array		Extension information array
  * @return	mixed		Returns array with extension upload array on success, otherwise an error string.
  */
 function makeUploadarray($extKey, $conf)
 {
     $extPath = tx_em_Tools::getExtPath($extKey, $conf['type']);
     if ($extPath) {
         // Get files for extension:
         $fileArr = array();
         $fileArr = t3lib_div::getAllFilesAndFoldersInPath($fileArr, $extPath, '', 0, 99, $GLOBALS['TYPO3_CONF_VARS']['EXT']['excludeForPackaging']);
         // Calculate the total size of those files:
         $totalSize = 0;
         foreach ($fileArr as $file) {
             $totalSize += filesize($file);
         }
         // If the total size is less than the upper limit, proceed:
         if ($totalSize < $this->maxUploadSize) {
             // Initialize output array:
             $uploadArray = array();
             $uploadArray['extKey'] = $extKey;
             $uploadArray['EM_CONF'] = $conf['EM_CONF'];
             $uploadArray['misc']['codelines'] = 0;
             $uploadArray['misc']['codebytes'] = 0;
             $uploadArray['techInfo'] = $this->install->makeDetailedExtensionAnalysis($extKey, $conf, 1);
             // Read all files:
             foreach ($fileArr as $file) {
                 $relFileName = substr($file, strlen($extPath));
                 $fI = pathinfo($relFileName);
                 if ($relFileName != 'ext_emconf.php') {
                     // This file should be dynamically written...
                     $uploadArray['FILES'][$relFileName] = array('name' => $relFileName, 'size' => filesize($file), 'mtime' => filemtime($file), 'is_executable' => TYPO3_OS == 'WIN' ? 0 : is_executable($file), 'content' => t3lib_div::getUrl($file));
                     if (t3lib_div::inList('php,inc', strtolower($fI['extension']))) {
                         $uploadArray['FILES'][$relFileName]['codelines'] = count(explode(LF, $uploadArray['FILES'][$relFileName]['content']));
                         $uploadArray['misc']['codelines'] += $uploadArray['FILES'][$relFileName]['codelines'];
                         $uploadArray['misc']['codebytes'] += $uploadArray['FILES'][$relFileName]['size'];
                         // locallang*.php files:
                         if (substr($fI['basename'], 0, 9) == 'locallang' && strstr($uploadArray['FILES'][$relFileName]['content'], '$LOCAL_LANG')) {
                             $uploadArray['FILES'][$relFileName]['LOCAL_LANG'] = tx_em_Tools::getSerializedLocalLang($file, $uploadArray['FILES'][$relFileName]['content']);
                         }
                     }
                     $uploadArray['FILES'][$relFileName]['content_md5'] = md5($uploadArray['FILES'][$relFileName]['content']);
                 }
             }
             // Return upload-array:
             return $uploadArray;
         } else {
             return sprintf($GLOBALS['LANG']->getLL('makeUploadArray_error_size'), $totalSize, t3lib_div::formatSize($this->maxUploadSize));
         }
     } else {
         return sprintf($GLOBALS['LANG']->getLL('makeUploadArray_error_path'), $extKey);
     }
 }
 /**
  * Add selector box items of more exotic kinds.
  *
  * @param	array		The array of items (label,value,icon)
  * @param	array		The "columns" array for the field (from TCA)
  * @param	array		TSconfig for the table/row
  * @param	string		The fieldname
  * @return	array		The $items array modified.
  */
 function addSelectOptionsToItemArray($items, $fieldValue, $TSconfig, $field)
 {
     global $TCA;
     // Values from foreign tables:
     if ($fieldValue['config']['foreign_table']) {
         $items = $this->foreignTable($items, $fieldValue, $TSconfig, $field);
         if ($fieldValue['config']['neg_foreign_table']) {
             $items = $this->foreignTable($items, $fieldValue, $TSconfig, $field, 1);
         }
     }
     // Values from a file folder:
     if ($fieldValue['config']['fileFolder']) {
         $fileFolder = t3lib_div::getFileAbsFileName($fieldValue['config']['fileFolder']);
         if (@is_dir($fileFolder)) {
             // Configurations:
             $extList = $fieldValue['config']['fileFolder_extList'];
             $recursivityLevels = isset($fieldValue['config']['fileFolder_recursions']) ? t3lib_div::intInRange($fieldValue['config']['fileFolder_recursions'], 0, 99) : 99;
             // Get files:
             $fileFolder = rtrim($fileFolder, '/') . '/';
             $fileArr = t3lib_div::getAllFilesAndFoldersInPath(array(), $fileFolder, $extList, 0, $recursivityLevels);
             $fileArr = t3lib_div::removePrefixPathFromList($fileArr, $fileFolder);
             foreach ($fileArr as $fileRef) {
                 $fI = pathinfo($fileRef);
                 $icon = t3lib_div::inList('gif,png,jpeg,jpg', strtolower($fI['extension'])) ? '../' . substr($fileFolder, strlen(PATH_site)) . $fileRef : '';
                 $items[] = array($fileRef, $fileRef, $icon);
             }
         }
     }
     // If 'special' is configured:
     if ($fieldValue['config']['special']) {
         switch ($fieldValue['config']['special']) {
             case 'tables':
                 $temp_tc = array_keys($TCA);
                 $descr = '';
                 foreach ($temp_tc as $theTableNames) {
                     if (!$TCA[$theTableNames]['ctrl']['adminOnly']) {
                         // Icon:
                         $icon = t3lib_iconWorks::mapRecordTypeToSpriteIconName($theTableNames, array());
                         // Add help text
                         $helpText = array();
                         $GLOBALS['LANG']->loadSingleTableDescription($theTableNames);
                         $helpTextArray = $GLOBALS['TCA_DESCR'][$theTableNames]['columns'][''];
                         if (!empty($helpTextArray['description'])) {
                             $helpText['description'] = $helpTextArray['description'];
                         }
                         // Item configuration:
                         $items[] = array($this->sL($TCA[$theTableNames]['ctrl']['title']), $theTableNames, $icon, $helpText);
                     }
                 }
                 break;
             case 'pagetypes':
                 $theTypes = $TCA['pages']['columns']['doktype']['config']['items'];
                 foreach ($theTypes as $theTypeArrays) {
                     // Icon:
                     $icon = t3lib_iconWorks::mapRecordTypeToSpriteIconName('pages', array('doktype' => $theTypeArrays[1]));
                     // Item configuration:
                     $items[] = array($this->sL($theTypeArrays[0]), $theTypeArrays[1], $icon);
                 }
                 break;
             case 'exclude':
                 $theTypes = t3lib_BEfunc::getExcludeFields();
                 $descr = '';
                 foreach ($theTypes as $theTypeArrays) {
                     list($theTable, $theField) = explode(':', $theTypeArrays[1]);
                     // Add help text
                     $helpText = array();
                     $GLOBALS['LANG']->loadSingleTableDescription($theTable);
                     $helpTextArray = $GLOBALS['TCA_DESCR'][$theTable]['columns'][$theField];
                     if (!empty($helpTextArray['description'])) {
                         $helpText['description'] = $helpTextArray['description'];
                     }
                     // Item configuration:
                     $items[] = array(rtrim($theTypeArrays[0], ':'), $theTypeArrays[1], 'empty-empty', $helpText);
                 }
                 break;
             case 'explicitValues':
                 $theTypes = t3lib_BEfunc::getExplicitAuthFieldValues();
                 // Icons:
                 $icons = array('ALLOW' => 'status-status-permission-granted', 'DENY' => 'status-status-permission-denied');
                 // Traverse types:
                 foreach ($theTypes as $tableFieldKey => $theTypeArrays) {
                     if (is_array($theTypeArrays['items'])) {
                         // Add header:
                         $items[] = array($theTypeArrays['tableFieldLabel'], '--div--');
                         // Traverse options for this field:
                         foreach ($theTypeArrays['items'] as $itemValue => $itemContent) {
                             // Add item to be selected:
                             $items[] = array('[' . $itemContent[2] . '] ' . $itemContent[1], $tableFieldKey . ':' . preg_replace('/[:|,]/', '', $itemValue) . ':' . $itemContent[0], $icons[$itemContent[0]]);
                         }
                     }
                 }
                 break;
             case 'languages':
                 $items = array_merge($items, t3lib_BEfunc::getSystemLanguages());
                 break;
             case 'custom':
                 // Initialize:
                 $customOptions = $GLOBALS['TYPO3_CONF_VARS']['BE']['customPermOptions'];
                 if (is_array($customOptions)) {
                     foreach ($customOptions as $coKey => $coValue) {
                         if (is_array($coValue['items'])) {
                             // Add header:
                             $items[] = array($GLOBALS['LANG']->sl($coValue['header']), '--div--');
                             // Traverse items:
                             foreach ($coValue['items'] as $itemKey => $itemCfg) {
                                 // Icon:
                                 if ($itemCfg[1]) {
                                     list($icon) = $this->getIcon($itemCfg[1]);
                                 } else {
                                     $icon = 'empty-empty';
                                 }
                                 // Add help text
                                 $helpText = array();
                                 if (!empty($itemCfg[2])) {
                                     $helpText['description'] = $GLOBALS['LANG']->sl($itemCfg[2]);
                                 }
                                 // Add item to be selected:
                                 $items[] = array($GLOBALS['LANG']->sl($itemCfg[0]), $coKey . ':' . preg_replace('/[:|,]/', '', $itemKey), $icon, $helpText);
                             }
                         }
                     }
                 }
                 break;
             case 'modListGroup':
             case 'modListUser':
                 $loadModules = t3lib_div::makeInstance('t3lib_loadModules');
                 $loadModules->load($GLOBALS['TBE_MODULES']);
                 $modList = $fieldValue['config']['special'] == 'modListUser' ? $loadModules->modListUser : $loadModules->modListGroup;
                 if (is_array($modList)) {
                     $descr = '';
                     foreach ($modList as $theMod) {
                         // Icon:
                         $icon = $GLOBALS['LANG']->moduleLabels['tabs_images'][$theMod . '_tab'];
                         if ($icon) {
                             $icon = '../' . substr($icon, strlen(PATH_site));
                         }
                         // Add help text
                         $helpText = array('title' => $GLOBALS['LANG']->moduleLabels['labels'][$theMod . '_tablabel'], 'description' => $GLOBALS['LANG']->moduleLabels['labels'][$theMod . '_tabdescr']);
                         // Item configuration:
                         $items[] = array($this->addSelectOptionsToItemArray_makeModuleData($theMod), $theMod, $icon, $helpText);
                     }
                 }
                 break;
         }
     }
     // Return the items:
     return $items;
 }
Ejemplo n.º 5
0
 /**
  * generate the folder structure for reST documentation
  */
 protected function generateDocumentationFiles()
 {
     $this->mkdir_deep($this->extensionDirectory, 'Documentation');
     $docFiles = array();
     $docFiles = t3lib_div::getAllFilesAndFoldersInPath($docFiles, t3lib_extMgm::extPath('extension_builder') . 'Resources/Private/CodeTemplates/Extbase/Documentation/', '', TRUE, 5, '/.*rstt/');
     foreach ($docFiles as $docFile) {
         if (is_dir($docFile)) {
             $this->mkdir_deep($this->extensionDirectory, 'Documentation/' . str_replace($this->codeTemplateRootPath . 'Documentation/', '', $docFile));
         } else {
             if (strpos($docFile, '.rstt') === FALSE) {
                 $this->upload_copy_move($docFile, str_replace(t3lib_extMgm::extPath('extension_builder') . 'Resources/Private/CodeTemplates/Extbase/', $this->extensionDirectory, $docFile));
             }
         }
     }
     $this->upload_copy_move(t3lib_extMgm::extPath('extension_builder') . 'Resources/Private/CodeTemplates/Extbase/Readme.rst', $this->extensionDirectory . 'Readme.rst');
     $fileContents = $this->renderTemplate('Documentation/Index.rstt', array('extension' => $this->extension));
     $this->writeFile($this->extensionDirectory . 'Documentation/Index.rst', $fileContents);
 }
Ejemplo n.º 6
0
 /**
  * Analyses the php-scripts of an available extension on server
  *
  * @param	string		Absolute path to extension
  * @param	string		Prefix for tables/classes.
  * @param	string		Extension key
  * @return	array		Information array.
  * @see makeDetailedExtensionAnalysis()
  */
 public static function getClassIndexLocallangFiles($absPath, $table_class_prefix, $extKey)
 {
     $excludeForPackaging = $GLOBALS['TYPO3_CONF_VARS']['EXT']['excludeForPackaging'];
     $filesInside = t3lib_div::removePrefixPathFromList(t3lib_div::getAllFilesAndFoldersInPath(array(), $absPath, 'php,inc', 0, 99, $excludeForPackaging), $absPath);
     $out = array();
     $reg = array();
     foreach ($filesInside as $fileName) {
         if (substr($fileName, 0, 4) != 'ext_' && substr($fileName, 0, 6) != 'tests/') {
             // ignore supposed-to-be unit tests as well
             $baseName = basename($fileName);
             if (substr($baseName, 0, 9) == 'locallang' && substr($baseName, -4) == '.php') {
                 $out['locallang'][] = $fileName;
             } elseif ($baseName != 'conf.php') {
                 if (filesize($absPath . $fileName) < 500 * 1024) {
                     $fContent = t3lib_div::getUrl($absPath . $fileName);
                     unset($reg);
                     if (preg_match('/\\n[[:space:]]*class[[:space:]]*([[:alnum:]_]+)([[:alnum:][:space:]_]*)/', $fContent, $reg)) {
                         // Find classes:
                         $lines = explode(LF, $fContent);
                         foreach ($lines as $l) {
                             $line = trim($l);
                             unset($reg);
                             if (preg_match('/^class[[:space:]]*([[:alnum:]_]+)([[:alnum:][:space:]_]*)/', $line, $reg)) {
                                 $out['classes'][] = $reg[1];
                                 $out['files'][$fileName]['classes'][] = $reg[1];
                                 if ($reg[1] !== 'ext_update' && substr($reg[1], 0, 3) != 'ux_' && !t3lib_div::isFirstPartOfStr($reg[1], $table_class_prefix) && strcmp(substr($table_class_prefix, 0, -1), $reg[1])) {
                                     $out['NSerrors']['classname'][] = $reg[1];
                                 } else {
                                     $out['NSok']['classname'][] = $reg[1];
                                 }
                             }
                         }
                         // If class file prefixed 'class.'....
                         if (substr($baseName, 0, 6) == 'class.') {
                             $fI = pathinfo($baseName);
                             $testName = substr($baseName, 6, -(1 + strlen($fI['extension'])));
                             if ($testName !== 'ext_update' && substr($testName, 0, 3) != 'ux_' && !t3lib_div::isFirstPartOfStr($testName, $table_class_prefix) && strcmp(substr($table_class_prefix, 0, -1), $testName)) {
                                 $out['NSerrors']['classfilename'][] = $baseName;
                             } else {
                                 $out['NSok']['classfilename'][] = $baseName;
                                 if (is_array($out['files'][$fileName]['classes']) && tx_em_Tools::first_in_array($testName, $out['files'][$fileName]['classes'], 1)) {
                                     $out['msg'][] = sprintf($GLOBALS['LANG']->getLL('detailedExtAnalysis_class_ok'), $fileName, $testName);
                                 } else {
                                     $out['errors'][] = sprintf($GLOBALS['LANG']->getLL('detailedExtAnalysis_class_not_ok'), $fileName, $testName);
                                 }
                             }
                         }
                         // Check for proper XCLASS definition
                         // Match $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS'] with single or doublequotes
                         $XclassSearch = '\\$TYPO3_CONF_VARS\\[TYPO3_MODE\\]\\[[\'"]XCLASS[\'"]\\]';
                         $XclassParts = preg_split('/if \\(defined\\([\'"]TYPO3_MODE[\'"]\\)(.*)' . $XclassSearch . '/', $fContent, 2);
                         if (count($XclassParts) !== 2) {
                             // Match $GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS'] with single or doublequotes
                             $XclassSearch = '\\$GLOBALS\\[[\'"]TYPO3_CONF_VARS[\'"]\\]\\[TYPO3_MODE\\]\\[[\'"]XCLASS[\'"]\\]';
                             $XclassParts = preg_split('/if \\(defined\\([\'"]TYPO3_MODE[\'"]\\)(.*)' . $XclassSearch . '/', $fContent, 2);
                         }
                         if (count($XclassParts) == 2) {
                             unset($reg);
                             preg_match('/^\\[[\'"]([[:alnum:]_\\/\\.]*)[\'"]\\]/', $XclassParts[1], $reg);
                             if ($reg[1]) {
                                 $cmpF = 'ext/' . $extKey . '/' . $fileName;
                                 if (!strcmp($reg[1], $cmpF)) {
                                     if (preg_match('/_once[[:space:]]*\\(' . $XclassSearch . '\\[[\'"]' . preg_quote($cmpF, '/') . '[\'"]\\]\\);/', $XclassParts[1])) {
                                         $out['msg'][] = sprintf($GLOBALS['LANG']->getLL('detailedExtAnalysis_xclass_ok'), $fileName);
                                     } else {
                                         $out['errors'][] = $GLOBALS['LANG']->getLL('detailedExtAnalysis_xclass_no_include');
                                     }
                                 } else {
                                     $out['errors'][] = sprintf($GLOBALS['LANG']->getLL('detailedExtAnalysis_xclass_incorrect'), $reg[1], $cmpF);
                                 }
                             } else {
                                 $out['errors'][] = sprintf($GLOBALS['LANG']->getLL('detailedExtAnalysis_no_xclass_filename'), $fileName);
                             }
                         } elseif (!tx_em_Tools::first_in_array('ux_', $out['files'][$fileName]['classes'])) {
                             // No Xclass definition required if classname starts with 'ux_'
                             $out['errors'][] = sprintf($GLOBALS['LANG']->getLL('detailedExtAnalysis_no_xclass_found'), $fileName);
                         }
                     }
                 }
             }
         }
     }
     return $out;
 }
 /**
  * get files from given relative directory path array
  *
  * @param array $directoryArray
  * @return array An Array containing all files of all valid directories
  */
 public function getFilesFromDirectories(array $directoryArray)
 {
     $directoryArray = $this->getAbsoluteDirectoryPath($directoryArray);
     if (is_array($directoryArray) && count($directoryArray)) {
         foreach ($directoryArray as $directory) {
             if (TYPO3_VERSION_INTEGER >= 7000000) {
                 $foundFiles = TYPO3\CMS\Core\Utility\GeneralUtility::getAllFilesAndFoldersInPath(array(), $directory, $this->indexerConfig['fileext']);
             } else {
                 $foundFiles = t3lib_div::getAllFilesAndFoldersInPath(array(), $directory, $this->indexerConfig['fileext']);
             }
             if (is_array($foundFiles) && count($foundFiles)) {
                 foreach ($foundFiles as $file) {
                     $files[] = $file;
                 }
             }
         }
         return $files;
     } else {
         return array();
     }
 }
Ejemplo n.º 8
0
 /**
  * Find lost files in uploads/ folder
  * FIX METHOD: Simply delete the file...
  *
  * TODO: Add parameter to exclude filepath
  * TODO: Add parameter to list more file names/patterns to ignore
  * TODO: Add parameter to include RTEmagic images
  *
  * @return	array
  */
 function main()
 {
     global $TYPO3_DB;
     // Initialize result array:
     $resultArray = array('message' => $this->cli_help['name'] . LF . LF . $this->cli_help['description'], 'headers' => array('managedFiles' => array('Files related to TYPO3 records and managed by TCEmain', 'These files you definitely want to keep.', 0), 'ignoredFiles' => array('Ignored files (index.html, .htaccess etc.)', 'These files are allowed in uploads/ folder', 0), 'RTEmagicFiles' => array('RTE magic images - those found (and ignored)', 'These files are also allowed in some uploads/ folders as RTEmagic images.', 0), 'lostFiles' => array('Lost files - those you can delete', 'You can delete these files!', 3), 'warnings' => array('Warnings picked up', '', 2)), 'managedFiles' => array(), 'ignoredFiles' => array(), 'RTEmagicFiles' => array(), 'lostFiles' => array(), 'warnings' => array());
     // Get all files:
     $fileArr = array();
     $fileArr = t3lib_div::getAllFilesAndFoldersInPath($fileArr, PATH_site . 'uploads/');
     $fileArr = t3lib_div::removePrefixPathFromList($fileArr, PATH_site);
     $excludePaths = t3lib_div::trimExplode(',', $this->cli_argValue('--excludePath', 0), 1);
     // Traverse files and for each, look up if its found in the reference index.
     foreach ($fileArr as $key => $value) {
         $include = TRUE;
         foreach ($excludePaths as $exclPath) {
             if (t3lib_div::isFirstPartOfStr($value, $exclPath)) {
                 $include = FALSE;
             }
         }
         $shortKey = t3lib_div::shortmd5($value);
         if ($include) {
             // First, allow "index.html", ".htaccess" files since they are often used for good reasons
             if (substr($value, -11) == '/index.html' || substr($value, -10) == '/.htaccess') {
                 unset($fileArr[$key]);
                 $resultArray['ignoredFiles'][$shortKey] = $value;
             } else {
                 // Looking for a reference from a field which is NOT a soft reference (thus, only fields with a proper TCA/Flexform configuration)
                 $recs = $TYPO3_DB->exec_SELECTgetRows('*', 'sys_refindex', 'ref_table=' . $TYPO3_DB->fullQuoteStr('_FILE', 'sys_refindex') . ' AND ref_string=' . $TYPO3_DB->fullQuoteStr($value, 'sys_refindex') . ' AND softref_key=' . $TYPO3_DB->fullQuoteStr('', 'sys_refindex'), '', 'sorting DESC');
                 // If found, unset entry:
                 if (count($recs)) {
                     unset($fileArr[$key]);
                     $resultArray['managedFiles'][$shortKey] = $value;
                     if (count($recs) > 1) {
                         $resultArray['warnings'][$shortKey] = 'Warning: File "' . $value . '" had ' . count($recs) . ' references from group-fields, should have only one!';
                     }
                 } else {
                     // When here it means the file was not found. So we test if it has a RTEmagic-image name and if so, we allow it:
                     if (preg_match('/^RTEmagic[P|C]_/', basename($value))) {
                         unset($fileArr[$key]);
                         $resultArray['RTEmagicFiles'][$shortKey] = $value;
                     } else {
                         // We conclude that the file is lost...:
                         unset($fileArr[$key]);
                         $resultArray['lostFiles'][$shortKey] = $value;
                     }
                 }
             }
         }
     }
     asort($resultArray['ignoredFiles']);
     asort($resultArray['managedFiles']);
     asort($resultArray['RTEmagicFiles']);
     asort($resultArray['lostFiles']);
     asort($resultArray['warnings']);
     // $fileArr variable should now be empty with all contents transferred to the result array keys.
     return $resultArray;
 }
Ejemplo n.º 9
0
    /**
     * Returns file-listing of an extension
     *
     * @param	string		Extension key
     * @param	array		Extension information array
     * @return	string		HTML table.
     */
    function getFileListOfExtension($extKey, $conf)
    {
        $content = '';
        $extPath = tx_em_Tools::getExtPath($extKey, $conf['type']);
        if ($extPath) {
            // Read files:
            $fileArr = array();
            $fileArr = t3lib_div::getAllFilesAndFoldersInPath($fileArr, $extPath, '', 0, 99, $this->excludeForPackaging);
            // Start table:
            $lines = array();
            $totalSize = 0;
            // Header:
            $lines[] = '
				<tr class="t3-row-header">
					<td>' . $GLOBALS['LANG']->getLL('extFileList_file') . '</td>
					<td>' . $GLOBALS['LANG']->getLL('extFileList_size') . '</td>
					<td>' . $GLOBALS['LANG']->getLL('extFileList_edit') . '</td>
				</tr>';
            foreach ($fileArr as $file) {
                $fI = t3lib_div::split_fileref($file);
                $lines[] = '
				<tr class="bgColor4">
					<td><a href="' . htmlspecialchars(t3lib_div::linkThisScript(array('CMD[showExt]' => $extKey, 'CMD[downloadFile]' => rawurlencode($file)))) . '" title="' . $GLOBALS['LANG']->getLL('extFileList_download') . '">' . substr($file, strlen($extPath)) . '</a></td>
					<td>' . t3lib_div::formatSize(filesize($file)) . '</td>
					<td>' . (!in_array($extKey, $this->requiredExt) && t3lib_div::inList($this->editTextExtensions, $fI['fileext'] ? $fI['fileext'] : $fI['filebody']) ? '<a href="' . htmlspecialchars(t3lib_div::linkThisScript(array('CMD[showExt]' => $extKey, 'CMD[editFile]' => rawurlencode($file)))) . '">' . $GLOBALS['LANG']->getLL('extFileList_edit_file') . '</a>' : '') . '</td>
				</tr>';
                $totalSize += filesize($file);
            }
            $lines[] = '
				<tr class="bgColor6">
					<td><strong>' . $GLOBALS['LANG']->getLL('extFileList_total') . '</strong></td>
					<td><strong>' . t3lib_div::formatSize($totalSize) . '</strong></td>
					<td>&nbsp;</td>
				</tr>';
            $content = '
			Path: ' . $extPath . '<br /><br />
			<table border="0" cellpadding="1" cellspacing="2">' . implode('', $lines) . '</table>';
        }
        return $content;
    }
Ejemplo n.º 10
0
 function folderChange($startpath)
 {
     // config
     $subfolder = '';
     // let's go
     $folderArray = $newArray = array();
     // init empty array
     $folderArray = t3lib_div::getAllFilesAndFoldersInPath($folderArray, t3lib_div::getFileAbsFileName($startpath), 'wt_gallery', 1);
     // get all folders of the startpath in an array
     $folderArray = array_flip($folderArray);
     // flip array
     foreach ((array) $folderArray as $key => $value) {
         // one loop for every array content
         if (substr($key, -1) === '/') {
             // if last sign is '/'
             $key = substr($key, 0, -1);
             // delete last sign
         }
         if (t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST') . '/' != t3lib_div::getIndpEnv('TYPO3_SITE_URL')) {
             // if request_host is different to site_url (TYPO3 runs in a subfolder)
             $subfolder = str_replace(t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST') . '/', '', t3lib_div::getIndpEnv('TYPO3_SITE_URL'));
             // get the folder (like "subfolder/")
         }
         $newArray[str_replace(t3lib_div::getIndpEnv('TYPO3_DOCUMENT_ROOT') . '/' . $subfolder, '', $key)] = $this->hashCode(str_replace(t3lib_div::getIndpEnv('TYPO3_DOCUMENT_ROOT') . '/' . $subfolder, '', $key));
         // rewrite array like 12345 => fileadmin/pics
     }
     if (!empty($newArray)) {
         return $newArray;
     }
 }
 /**
  * Generate the $classNameToFileMapping for a given filePath.
  *
  * @param	array	$classNameToFileMapping	(Reference to array) All values are appended to this array.
  * @param	string	$path	Path which should be crawled
  * @param	string	$excludeRegularExpression	Exclude regular expression, to exclude certain files from being processed
  * @param	string	$valueWrap	Wrap for the file name
  * @param	boolean $includeSubFolders Whether to include sub folders
  * @param	string $fileExtensionList List of file extensions to consider
  * @return void
  */
 protected function buildAutoloadRegistryForSinglePath(&$classNameToFileMapping, $path, $excludeRegularExpression = '', $valueWrap = '\'|\'', $includeSubFolders = TRUE, $fileExtensionList = 'php')
 {
     $recursivityLevels = $includeSubFolders ? 99 : 0;
     $extensionFileNames = t3lib_div::removePrefixPathFromList(t3lib_div::getAllFilesAndFoldersInPath(array(), $path, $fileExtensionList, FALSE, $recursivityLevels, $excludeRegularExpression), $path);
     foreach ($extensionFileNames as $extensionFileName) {
         $classNamesInFile = $this->extractClassNames($path . $extensionFileName);
         if (!count($classNamesInFile)) {
             continue;
         }
         foreach ($classNamesInFile as $className) {
             // Register processed classes and the accordant file name:
             if (!isset($this->processedClasses[strtolower($className)]) || !in_array($path . $extensionFileName, $this->processedClasses[strtolower($className)])) {
                 $this->processedClasses[strtolower($className)][] = $path . $extensionFileName;
             }
             $classNameToFileMapping[strtolower($className)] = str_replace('|', $extensionFileName, $valueWrap);
         }
     }
     ksort($classNameToFileMapping);
 }
Ejemplo n.º 12
0
 /**
  * Removes the extension directory (including content)
  *
  * @param	string		Extension directory to remove (with trailing slash)
  * @param	boolean		If set, will leave the extension directory
  * @return	boolean		False on success, otherwise error string.
  */
 function removeExtDirectory($removePath, $removeContentOnly = 0)
 {
     $errors = array();
     if (@is_dir($removePath) && substr($removePath, -1) == '/' && (t3lib_div::isFirstPartOfStr($removePath, tx_em_Tools::typePath('G')) || t3lib_div::isFirstPartOfStr($removePath, tx_em_Tools::typePath('L')) || t3lib_div::isFirstPartOfStr($removePath, tx_em_Tools::typePath('S')) && $this->systemInstall || t3lib_div::isFirstPartOfStr($removePath, PATH_site . $GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'] . '_temp_/'))) {
         // All files in extension directory:
         $fileArr = t3lib_div::getAllFilesAndFoldersInPath(array(), $removePath, '', 1);
         if (is_array($fileArr)) {
             // Remove files in dirs:
             foreach ($fileArr as $removeFile) {
                 if (!@is_dir($removeFile)) {
                     if (@is_file($removeFile) && t3lib_div::isFirstPartOfStr($removeFile, $removePath) && strcmp($removeFile, $removePath)) {
                         // ... we are very paranoid, so we check what cannot go wrong: that the file is in fact within the prefix path!
                         @unlink($removeFile);
                         clearstatcache();
                         if (@is_file($removeFile)) {
                             $errors[] = sprintf($GLOBALS['LANG']->getLL('rmExtDir_could_not_be_deleted'), $removeFile);
                         }
                     } else {
                         $errors[] = sprintf($GLOBALS['LANG']->getLL('rmExtDir_error_file'), $removeFile, $removePath);
                     }
                 }
             }
             // Remove directories:
             $remDirs = tx_em_Tools::extractDirsFromFileList(t3lib_div::removePrefixPathFromList($fileArr, $removePath));
             $remDirs = array_reverse($remDirs);
             // Must delete outer directories first...
             foreach ($remDirs as $removeRelDir) {
                 $removeDir = $removePath . $removeRelDir;
                 if (@is_dir($removeDir)) {
                     @rmdir($removeDir);
                     clearstatcache();
                     if (@is_dir($removeDir)) {
                         $errors[] = sprintf($GLOBALS['LANG']->getLL('rmExtDir_error_files_left'), $removeDir);
                     }
                 } else {
                     $errors[] = sprintf($GLOBALS['LANG']->getLL('rmExtDir_error_no_dir'), $removeDir);
                 }
             }
             // If extension dir should also be removed:
             if (!$removeContentOnly) {
                 @rmdir($removePath);
                 clearstatcache();
                 if (@is_dir($removePath)) {
                     $errors[] = sprintf($GLOBALS['LANG']->getLL('rmExtDir_error_folders_left'), $removePath);
                 }
             }
         } else {
             $errors[] = $GLOBALS['LANG']->getLL('rmExtDir_error') . ' ' . $fileArr;
         }
     } else {
         $errors[] = $GLOBALS['LANG']->getLL('rmExtDir_error_unallowed_path') . ' ' . $removePath;
     }
     // Return errors if any:
     return implode(LF, $errors);
 }
 function garbageCollector()
 {
     $iNow = time();
     $iGCProbability = intval($GLOBALS["TYPO3_CONF_VARS"]["EXTCONF"]["ameos_formidable"]["ext_conf_template"]["gc_probability"]);
     $iGCMaxAge = intval($GLOBALS["TYPO3_CONF_VARS"]["EXTCONF"]["ameos_formidable"]["ext_conf_template"]["gc_jsmaxage"]);
     if ($iGCProbability <= 0 || $iGCMaxAge <= 0) {
         return;
     }
     if ($iNow % $iGCProbability !== 0) {
         return;
     }
     // executing garabage collector
     // on temporary JS files
     $sPath = PATH_site . "typo3temp/ameos_formidable/js/";
     if (!file_exists($sPath)) {
         return;
     }
     $aFiles = t3lib_div::getAllFilesAndFoldersInPath(array(), $sPath, '', 0, 1);
     if (!empty($aFiles)) {
         reset($aFiles);
         while (list(, $sFile) = each($aFiles)) {
             if ($iNow - fileatime($sFile) > $iGCMaxAge) {
                 @unlink($sFile);
             }
         }
         clearstatcache();
     }
 }
Ejemplo n.º 14
0
 /**
  * Finds all files that are named like test files in the directory $directory
  * and recursively all its subdirectories.
  *
  * @param string $directory
  *        the absolute path of the directory in which to look for test cases
  *
  * @return array<string>
  *         sorted file names of the test cases in the directory $directory relative
  *         to $directory, will be empty if no test cases have been found
  *
  * @throws InvalidArgumentException
  */
 public function findTestCaseFilesInDirectory($directory)
 {
     if ($directory === '') {
         throw new InvalidArgumentException('$directory must not be empty.', 1334439798);
     }
     if (!is_dir($directory)) {
         throw new InvalidArgumentException('The directory ' . $directory . ' does not exist.', 1334439804);
     }
     if (!is_readable($directory)) {
         throw new InvalidArgumentException('The directory ' . $directory . ' exists, but is not readable.', 1334439813);
     }
     $directoryLength = strlen($directory);
     $testFiles = array();
     $allPhpFiles = t3lib_div::getAllFilesAndFoldersInPath(array(), $directory, 'php');
     foreach ($allPhpFiles as $filePath) {
         if ($this->isNotFixturesPath($filePath) && $this->isTestCaseFileName($filePath)) {
             $testFiles[] = substr($filePath, $directoryLength);
         }
     }
     sort($testFiles, SORT_STRING);
     return $testFiles;
 }
Ejemplo n.º 15
0
	/**
	 * Find and check all templates within the template paths
	 *
	 * @return	array		all relevant templates
	 */
	protected function getTemplateFiles() {
		$paths = $this->getTemplatePaths();
		$files = array();
		foreach ($paths as $path) {
			$files = array_merge(t3lib_div::getAllFilesAndFoldersInPath(array(), $prefix . $path . ((substr($path, -1) != '/') ? '/' : ''), 'html,htm,tmpl', 0), $files);
		}
		return $files;
	}
Ejemplo n.º 16
0
 /**
  * Indexing files from fileadmin
  *
  * @param	array		Indexing Configuration Record
  * @param	array		Session data for the indexing session spread over multiple instances of the script. Passed by reference so changes hereto will be saved for the next call!
  * @param	array		Parameters from the log queue.
  * @param	object		Parent object (from "crawler" extension!)
  * @return	void
  */
 function crawler_execute_type2($cfgRec, &$session_data, $params, &$pObj)
 {
     // Prepare path, making it absolute and checking:
     $readpath = $params['url'];
     if (!t3lib_div::isAbsPath($readpath)) {
         $readpath = t3lib_div::getFileAbsFileName($readpath);
     }
     if (t3lib_div::isAllowedAbsPath($readpath)) {
         if (@is_file($readpath)) {
             // If file, index it!
             // Get root line (need to provide this when indexing external files)
             $rl = $this->getUidRootLineForClosestTemplate($cfgRec['pid']);
             // Load indexer if not yet.
             $this->loadIndexerClass();
             // (Re)-Indexing file on page.
             $indexerObj = t3lib_div::makeInstance('tx_indexedsearch_indexer');
             $indexerObj->backend_initIndexer($cfgRec['pid'], 0, 0, '', $rl);
             $indexerObj->backend_setFreeIndexUid($cfgRec['uid'], $cfgRec['set_id']);
             $indexerObj->hash['phash'] = -1;
             // EXPERIMENT - but to avoid phash_t3 being written to file sections (otherwise they are removed when page is reindexed!!!)
             // Index document:
             $indexerObj->indexRegularDocument(substr($readpath, strlen(PATH_site)), TRUE);
         } elseif (@is_dir($readpath)) {
             // If dir, read content and create new pending items for log:
             // Select files and directories in path:
             $extList = implode(',', t3lib_div::trimExplode(',', $cfgRec['extensions'], 1));
             $fileArr = array();
             $files = t3lib_div::getAllFilesAndFoldersInPath($fileArr, $readpath, $extList, 0, 0);
             $directoryList = t3lib_div::get_dirs($readpath);
             if (is_array($directoryList) && $params['depth'] < $cfgRec['depth']) {
                 foreach ($directoryList as $subdir) {
                     if ((string) $subdir != '') {
                         $files[] = $readpath . $subdir . '/';
                     }
                 }
             }
             $files = t3lib_div::removePrefixPathFromList($files, PATH_site);
             // traverse the items and create log entries:
             foreach ($files as $path) {
                 $this->instanceCounter++;
                 if ($path !== $params['url']) {
                     // Parameters:
                     $nparams = array('indexConfigUid' => $cfgRec['uid'], 'url' => $path, 'procInstructions' => array('[Index Cfg UID#' . $cfgRec['uid'] . ']'), 'depth' => $params['depth'] + 1);
                     $pObj->addQueueEntry_callBack($cfgRec['set_id'], $nparams, $this->callBack, $cfgRec['pid'], $GLOBALS['EXEC_TIME'] + $this->instanceCounter * $this->secondsPerExternalUrl);
                 }
             }
         }
     }
 }
Ejemplo n.º 17
0
 /**
  * Generate the $classNameToFileMapping for a given filePath.
  *
  * @param	array	$classNameToFileMapping	(Reference to array) All values are appended to this array.
  * @param	string	$path	Path which should be crawled
  * @param	string	$excludeRegularExpression	Exclude regular expression, to exclude certain files from being processed
  * @param	string	$valueWrap	Wrap for the file name
  * @return void
  */
 protected function buildAutoloadRegistryForSinglePath(&$classNameToFileMapping, $path, $excludeRegularExpression = '', $valueWrap = '\'|\'')
 {
     //		if (file_exists($path . 'Classes/')) {
     //			return "<b>This appears to be a new-style extension which has its PHP classes inside the Classes/ subdirectory. It is not needed to generate the autoload registry for these extensions.</b>";
     //		}
     $extensionFileNames = t3lib_div::removePrefixPathFromList(t3lib_div::getAllFilesAndFoldersInPath(array(), $path, 'php', FALSE, 99, $excludeRegularExpression), $path);
     foreach ($extensionFileNames as $extensionFileName) {
         $classNamesInFile = $this->extractClassNames($path . $extensionFileName);
         if (!count($classNamesInFile)) {
             continue;
         }
         foreach ($classNamesInFile as $className) {
             $classNameToFileMapping[strtolower($className)] = str_replace('|', $extensionFileName, $valueWrap);
         }
     }
 }
Ejemplo n.º 18
0
 /**
  * Recursively gather all files and folders of a path.
  * Usage: 5
  *
  * @param	array		$fileArr: Empty input array (will have files added to it)
  * @param	string		$path: The path to read recursively from (absolute) (include trailing slash!)
  * @param	string		$extList: Comma list of file extensions: Only files with extensions in this list (if applicable) will be selected.
  * @param	boolean		$regDirs: If set, directories are also included in output.
  * @param	integer		$recursivityLevels: The number of levels to dig down...
  * @param string		$excludePattern: regex pattern of files/directories to exclude
  * @return	array		An array with the found files/directories.
  */
 public static function getAllFilesAndFoldersInPath(array $fileArr, $path, $extList = '', $regDirs = 0, $recursivityLevels = 99, $excludePattern = '')
 {
     if ($regDirs) {
         $fileArr[] = $path;
     }
     $fileArr = array_merge($fileArr, t3lib_div::getFilesInDir($path, $extList, 1, 1, $excludePattern));
     $dirs = t3lib_div::get_dirs($path);
     if (is_array($dirs) && $recursivityLevels > 0) {
         foreach ($dirs as $subdirs) {
             if ((string) $subdirs != '' && (!strlen($excludePattern) || !preg_match('/^' . $excludePattern . '$/', $subdirs))) {
                 $fileArr = t3lib_div::getAllFilesAndFoldersInPath($fileArr, $path . $subdirs . '/', $extList, $regDirs, $recursivityLevels - 1, $excludePattern);
             }
         }
     }
     return $fileArr;
 }
Ejemplo n.º 19
0
    /**
     * Wizard Step 1: Selecting template file.
     *
     * @return	void
     */
    function wizard_step1()
    {
        if (@is_dir(PATH_site . $this->templatesDir)) {
            $this->wizardData = array();
            $outputString .= nl2br('The first step is to select the HTML file you want to base the new website design on. Below you see a list of HTML files found in the folder "' . $this->templatesDir . '". Click the "Preview"-link to see what the file looks like and when the right template is found, just click the "Choose as template"-link in order to proceed.
				If the list of files is empty you must now copy the HTML file you want to use as a template into the template folder. When you have done that, press the refresh button to refresh the list.<br/>');
            // Get all HTML files:
            $fileArr = t3lib_div::getAllFilesAndFoldersInPath(array(), PATH_site . $this->templatesDir, 'html,htm', 0, 1);
            $fileArr = t3lib_div::removePrefixPathFromList($fileArr, PATH_site);
            // Prepare header:
            $tRows = array();
            $tRows[] = '<tr class="tableheader bgColor5">
				<td>Path:</td>
				<td>Usage:</td>
				<td>Action:</td>
			</tr>';
            // Traverse available template files:
            foreach ($fileArr as $file) {
                // Has been used:
                $tosForTemplate = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('uid', 'tx_templavoila_tmplobj', 'fileref=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($file, 'tx_templavoila_tmplobj') . t3lib_BEfunc::deleteClause('tx_templavoila_tmplobj'));
                // Preview link
                $onClick = 'vHWin=window.open(\'' . $this->doc->backPath . '../' . $file . '\',\'tvTemplatePreview\',\'status=1,menubar=1,scrollbars=1,location=1\');vHWin.focus();return false;';
                // Make row:
                $tRows[] = '<tr class="bgColor4">
					<td>' . htmlspecialchars($file) . '</td>
					<td>' . (count($tosForTemplate) ? 'Used ' . count($tosForTemplate) . ' times' : 'Not used yet') . '</td>
					<td>' . '<a href="#" onclick="' . htmlspecialchars($onClick) . '">[Preview first]</a> ' . '<a href="' . htmlspecialchars('index.php?SET[wiz_step]=2&CFG[file]=' . rawurlencode($file)) . '">[Choose as Template]</a> ' . '</td>
				</tr>';
            }
            $outputString .= '<table border="0" cellpadding="1" cellspacing="1" class="lrPadding">' . implode('', $tRows) . '</table>';
            // Refresh button:
            $outputString .= '<br/><input type="submit" value="Refresh" onclick="' . htmlspecialchars('document.location=\'index.php?SET[wiz_step]=1\'; return false;') . '" />';
            // Add output:
            $this->content .= $this->doc->section('Step 1: Select the template HTML file', $outputString, 0, 1);
        } else {
            $this->content .= $this->doc->section('TemplaVoila wizard error', $this->templatesDir . ' is not a directory! Please, create it before starting this wizard.', 0, 1);
        }
    }