/** * @param $dbDirEntry */ protected function downloadDBFileToDirectory($dbDirEntry) { $dbPathAndFileName = $dbDirEntry['path']; t3lib_div::mkdir_deep($this->getFileadminPath(), $this->syncConfig->getLocalPath()); $dbFileName = basename($dbPathAndFileName); $localPathAndFileName = $this->getFileadminPath() . $this->syncConfig->getLocalPath() . '/' . $dbFileName; $fileContent = $this->dropbox->getFile($dbPathAndFileName); file_put_contents($localPathAndFileName, $fileContent); $this->fileTracker->updateFileMeta($localPathAndFileName, $dbDirEntry, $this->syncConfig, $this->runIdentifier); $this->runInfo->logLocalFileAdded($dbPathAndFileName, $this->syncConfig->getLocalPath()); }
/** * Function rendering the status form and executing the splitting operation * * @param array XML file content as array! * @param string The absolute file name the content is read from * @return string HTML content. */ function renderForm($fileContent, $phpFile) { // Meta Data of file $content .= 'Description: <b>' . htmlspecialchars($fileContent['meta']['description']) . '</b>'; if (!@is_writable($phpFile)) { return 'ERROR: File "' . $phpFile . '" was not writeable!'; } // Initiate: $languages = explode('|', TYPO3_languages); $createFile = t3lib_div::_POST('createFile'); $removePoint = t3lib_div::_POST('removePoint'); $log = array(); $saveOriginalBack = FALSE; $tableRows = array(); foreach ($languages as $lKey) { if ($lKey != 'default') { $tableCells = array(); // Title: $tableCells[] = htmlspecialchars($lKey); // Content: $tableCells[] = is_array($fileContent['data'][$lKey]) ? count($fileContent['data'][$lKey]) . ' labels locally' : htmlspecialchars($fileContent['data'][$lKey]); // Status: if (!is_array($fileContent['data'][$lKey]) && strlen(trim($fileContent['data'][$lKey]))) { // An external file WAS configured - we only give status then: $absFileName = t3lib_div::getFileAbsFileName($fileContent['data'][$lKey]); if ($absFileName) { if (@is_file($absFileName)) { $tableCells[] = 'External file exists, OK.'; } else { $tableCells[] = '<b>ERROR:</b> External file did not exist, should exist! <hr>REMOVE POINTER: <input type="checkbox" name="removePoint[' . $lKey . ']" value="1" />'; if (t3lib_div::_GP('_create_') && $removePoint[$lKey]) { $log[] = 'Removing pointer "' . $fileContent['data'][$lKey] . '"'; unset($fileContent['data'][$lKey]); $saveOriginalBack = TRUE; } } } else { $tableCells[] = 'External file path did not resolve, maybe extension is not loaded.'; } } else { // No external file yet: $fileName = t3lib_div::llXmlAutoFileName($phpFile, $lKey); # str_replace('###LANGKEY###',$lKey,$fileContent['meta']['ext_filename_template']); $absFileName = t3lib_div::getFileAbsFileName($fileName); if ($absFileName) { if (@is_file($absFileName)) { $tableCells[] = 'External Automatic file exists, OK.'; } else { if (t3lib_div::_GP('_create_')) { if ($createFile[$lKey]) { $OK = 1; $dirname = dirname($absFileName); if (!@is_dir($dirname)) { $OK = 0; if (t3lib_div::isFirstPartOfStr($dirname, PATH_site . 'typo3conf/l10n/')) { $err = t3lib_div::mkdir_deep(PATH_site . 'typo3conf/l10n/', substr($dirname, strlen(PATH_site . 'typo3conf/l10n/'))); if ($err) { $log[] = 'Creating directory ' . $dirname . ' failed'; } else { $OK = 1; } } else { $log[] = 'Creating directory ' . $dirname . ' failed (2)'; } } if ($OK) { // Creating data for external file: $extArray = array(); // Setting language specific information in the XML file array: $extArray['data'][$lKey] = is_array($fileContent['data'][$lKey]) ? $fileContent['data'][$lKey] : array(); $extArray['orig_hash'][$lKey] = is_array($fileContent['orig_hash'][$lKey]) ? $fileContent['orig_hash'][$lKey] : array(); $extArray['orig_text'][$lKey] = is_array($fileContent['orig_text'][$lKey]) ? $fileContent['orig_text'][$lKey] : array(); // Create XML and save file: $XML = $this->createXML($extArray, TRUE); // Write file: t3lib_div::writeFile($absFileName, $XML); // Checking if the localized file was saved as it should be: if (md5(t3lib_div::getUrl($absFileName)) == md5($XML)) { $log[] = 'Saved external XML, validated OK'; // Prepare SAVING original: // Setting reference to the external file: unset($fileContent['data'][$lKey]); // Unsetting the hash and original text for this language as well: unset($fileContent['orig_hash'][$lKey]); unset($fileContent['orig_text'][$lKey]); $saveOriginalBack = TRUE; } else { $log[] = 'ERROR: MD5 sum of saved external file did not match XML going in!'; } } } } else { $tableCells[] = ' <input type="checkbox" name="createFile[' . $lKey . ']" value="1" checked="checked" /> File did not exist, will be created if checkbox selected.<br/> (' . $fileName . ')'; } } } else { $tableCells[] = 'Template file path did not resolve, maybe extension is not loaded.'; } } // Compiling row: $tableRows[] = ' <tr> <td>' . implode('</td> <td>', $tableCells) . ' </td> </tr>'; } } if (t3lib_div::_GP('_create_')) { // SAVING ORIGINAL FILE BACK: if ($saveOriginalBack) { $log[] = 'Saving original back now...'; $XML = $this->createXML($fileContent); t3lib_div::writeFile($phpFile, $XML); // Checking if the main file was saved as it should be: if (md5(t3lib_div::getUrl($phpFile)) == md5($XML)) { $log[] = 'Validated OK'; } else { $log[] = 'ERROR: MD5 sum did not match!!!'; } } $content .= '<h3>LOG:</h3>' . implode('<br/>', $log) . ' <hr/> <input type="submit" name="" value="Back" />'; } else { $content .= '<table border="1" cellpadding="1" cellspacing="1">' . implode('', $tableRows) . '</table> <br/> <input type="submit" name="_create_" value="Update" />'; } // Meta Data of file $content .= '<h3>Meta Data and default labels of file:</h3>' . 'Meta data:' . (is_array($fileContent['meta']) ? Tx_Extdeveval_Compatibility::viewArray($fileContent['meta']) : '') . 'Default labels:' . (is_array($fileContent['data']['default']) ? Tx_Extdeveval_Compatibility::viewArray($fileContent['data']['default']) : ''); return $content; }
/** * wrapper for t3lib_div::mkdir_deep * checks for overwrite settings * * @param string $directory base path * @param string $deepDirectory */ protected function mkdir_deep($directory, $deepDirectory) { $subDirectories = explode('/', $deepDirectory); $tmpBasePath = $directory; foreach ($subDirectories as $subDirectory) { $overWriteMode = Tx_ExtensionBuilder_Service_RoundTrip::getOverWriteSettingForPath($tmpBasePath . $subDirectory, $this->extension); //throw new Exception($directory . $subDirectory . '/' . $overWriteMode); if ($overWriteMode === -1) { // skip creation return; } if (!is_dir($deepDirectory) || $this->roundTripEnabled && $overWriteMode < 2) { t3lib_div::mkdir_deep($tmpBasePath, $subDirectory); } $tmpBasePath .= $subDirectory . '/'; } }
/** * Creates directories in $extDirPath * * @param array Array of directories to create relative to extDirPath, eg. "blabla", "blabla/blabla" etc... * @param string Absolute path to directory. * @return mixed Returns false on success or an error string */ public static function createDirsInPath($dirs, $extDirPath) { if (is_array($dirs)) { foreach ($dirs as $dir) { $error = t3lib_div::mkdir_deep($extDirPath, $dir); if ($error) { return $error; } } } return FALSE; }
/** * Öffnet eine Datei für den debug. * * @param string $path * @param string $file * @return int */ public static function openFile($path = '', $file = '') { $file = $file ? $file : 'mklib_debug_' . date('Y-m-d_H-i-s', time()) . '.txt'; if (!$path) { $path = 'typo3temp/mklib/'; if (!is_writable(PATH_site . $path)) { t3lib_div::mkdir_deep(PATH_site, $path); } $path = PATH_site . $path; } self::$file = fopen($path . $file, "a"); unset($path); unset($file); return self::$file; }
/** * lessPhp * * @return void */ public function lessPhp( $files ) { require_once (t3lib_extMgm::extPath( 't3_less' ) . 'Resources/Private/Lib/' . $this->configuration['other']['lessPhpScriptPath']); // create outputfolder if it does not exist if( !is_dir( $this->outputfolder ) ) { t3lib_div::mkdir_deep( '', $this->outputfolder ); } $less = t3lib_div::makeInstance( 'lessc' ); $this->checkForAdditionalConfiguration( $less ); // compile each less-file foreach( $files as $file ) { //get only the name of less file $filename = array_pop( explode( '/', $file ) ); $md5 = md5( $filename . md5_file( $file ) ); $outputfile = $this->outputfolder . substr( $filename, 0, -5 ) . '_' . $md5 . '.css'; if( $this->configuration['other']['forceMode'] ) { unlink( $outputfile ); } if( !file_exists( $outputfile ) ) { if( $this->configuration['other']['compressed'] ) { $less->setFormatter( "compressed" ); lessc::ccompile( $file, $this->outputfolder . substr( $filename, 0, -5 ) . '_' . $md5 . '.css', $less ); } else { lessc::ccompile( $file, $this->outputfolder . substr( $filename, 0, -5 ) . '_' . $md5 . '.css' ); } t3lib_div::fixPermissions( $outputfile, FALSE ); } } // unlink compiled files which have no equal source less-file if( $this->configuration['other']['unlinkCssFilesWithNoSourceFile'] == 1 ) { $this->unlinkGeneratedFilesWithNoSourceFile( $files ); } $files = t3lib_div::getFilesInDir( $this->outputfolder, "css" ); //respect given sort order defined in TS usort( $files, array( $this, 'getSortOrderPhp' ) ); foreach( $files as $cssFile ) { $excludeFromPageRender = isset( $this->configuration['phpcompiler']['filesettings'][substr( $cssFile, 0, -37 )]['excludeFromPageRenderer'] ) ? $this->configuration['phpcompiler']['filesettings'][substr( $cssFile, 0, -37 )]['excludeFromPageRenderer'] : 0; if( !$excludeFromPageRender || $excludeFromPageRender == 0 ) { // array with filesettings from TS $tsOptions = $this->configuration['phpcompiler']['filesettings'][substr( $cssFile, 0, -37 )]; $GLOBALS['TSFE']->getPageRenderer()->addCssFile( $this->outputfolder . $cssFile, $rel = 'stylesheet', $media = isset( $tsOptions['media'] ) ? $tsOptions['media'] : 'all', $title = isset( $tsOptions['title'] ) ? $tsOptions['title'] : '', $compress = isset( $tsOptions['compress'] ) && $tsOptions['compress'] >= '0' ? (boolean) $tsOptions['compress'] : TRUE, $forceOnTop = isset( $tsOptions['forceOnTop'] ) && $tsOptions['forceOnTop'] >= '0' ? (boolean) $tsOptions['forceOnTop'] : FALSE, $allWrap = isset( $tsOptions['allWrap'] ) ? $tsOptions['allWrap'] : '', $excludeFromConcatenation = isset( $tsOptions['excludeFromConcatenation'] ) && $tsOptions['excludeFromConcatenation'] >= '0' ? (boolean) $tsOptions['excludeFromConcatenation'] : FALSE ); } } }
/** * Handling files for group/select function * * @param array Array of incoming file references. Keys are numeric, values are files (basically, this is the exploded list of incoming files) * @param array Configuration array from TCA of the field * @param string Current value of the field * @param array Array of uploaded files, if any * @param string Status ("update" or ?) * @param string tablename of record * @param integer UID of record * @param string Field identifier ([table:uid:field:....more for flexforms?] * @return array Modified value array * @see checkValue_group_select() */ function checkValue_group_select_file($valueArray, $tcaFieldConf, $curValue, $uploadedFileArray, $status, $table, $id, $recFID) { if (!$this->bypassFileHandling) { // If filehandling should NOT be bypassed, do processing: // If any files are uploaded, add them to value array if (is_array($uploadedFileArray) && $uploadedFileArray['name'] && strcmp($uploadedFileArray['tmp_name'], 'none')) { $valueArray[] = $uploadedFileArray['tmp_name']; $this->alternativeFileName[$uploadedFileArray['tmp_name']] = $uploadedFileArray['name']; } // Creating fileFunc object. if (!$this->fileFunc) { $this->fileFunc = t3lib_div::makeInstance('t3lib_basicFileFunctions'); $this->include_filefunctions = 1; } // Setting permitted extensions. $all_files = array(); $all_files['webspace']['allow'] = $tcaFieldConf['allowed']; $all_files['webspace']['deny'] = $tcaFieldConf['disallowed'] ? $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') { if (!$this->bypassFileHandling) { // If filehandling should NOT be bypassed, do processing: // 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 ($theFile === basename($theFile)) { // If it is an already attached file... $valueArray[$key] = PATH_site . $tcaFieldConf['uploadfolder'] . '/' . $theFile; } } } // Finding the CURRENT files listed, either from MM or from the current record. $theFileValues = array(); if ($tcaFieldConf['MM']) { // If MM relations for the files also! $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup'); /* @var $dbAnalysis t3lib_loadDBGroup */ $dbAnalysis->start('', 'files', $tcaFieldConf['MM'], $id); foreach ($dbAnalysis->itemArray as $item) { if ($item['id']) { $theFileValues[] = $item['id']; } } } else { $theFileValues = t3lib_div::trimExplode(',', $curValue, 1); } $currentFilesForHistory = implode(',', $theFileValues); // DELETE files: If existing files were found, traverse those and register files for deletion which has been removed: if (count($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(t3lib_div::fixWindowsFilePath($theFile), '/')) { $theFileValues = t3lib_div::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 ($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) { // 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(t3lib_div::fixWindowsFilePath($theFile), '/')) { // Init: $maxSize = intval($tcaFieldConf['max_size']); $cmd = ''; $theDestFile = ''; // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error! // Check various things before copying file: if (@is_dir($dest) && (@is_file($theFile) || @is_uploaded_file($theFile))) { // File and destination must exist // Finding size. For safe_mode we have to rely on the size in the upload array if the file is uploaded. if (is_uploaded_file($theFile) && $theFile == $uploadedFileArray['tmp_name']) { $fileSize = $uploadedFileArray['size']; } else { $fileSize = filesize($theFile); } if (!$maxSize || $fileSize <= $maxSize * 1024) { // Check file size: // Prepare filename: $theEndFileName = isset($this->alternativeFileName[$theFile]) ? $this->alternativeFileName[$theFile] : $theFile; $fI = t3lib_div::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) { t3lib_div::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 = t3lib_div::getUserObj($classRef); if (!$hookObject instanceof t3lib_TCEmain_processUploadHook) { throw new UnexpectedValueException('$hookObject must implement interface t3lib_TCEmain_processUploadHook', 1279962349); } $hookObject->processUpload_postProcessAction($theDestFile, $this); } } $this->copiedFileMap[$theFile] = $theDestFile; clearstatcache(); if (!@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']); } } else { $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']); } } else { $this->log($table, $id, 5, 0, 1, "File extension '%s' not allowed. (%s)", 12, array($fI['fileext'], $recFID), $propArr['event_pid']); } } else { $this->log($table, $id, 5, 0, 1, "Filesize (%s) of file '%s' exceeds limit (%s). (%s)", 13, array(t3lib_div::formatSize($fileSize), $theFile, t3lib_div::formatSize($maxSize * 1024), $recFID), $propArr['event_pid']); } } else { $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 = t3lib_div::split_fileref($theDestFile); $valueArray[$key] = $info['file']; // The value is set to the new filename } else { unset($valueArray[$key]); // The value is set to the new filename } } } } // 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']) { $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup'); /* @var $dbAnalysis t3lib_loadDBGroup */ $dbAnalysis->tableArray['files'] = array(); // dummy 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); // This will be traversed later to execute the actions } $valueArray = $dbAnalysis->countItems(); } //store path relative to site root (if uploadfolder is not set or internal_type is file_reference) } else { if (count($valueArray)) { if (!$this->bypassFileHandling) { // If filehandling should NOT be bypassed, do processing: $propArr = $this->getRecordProperties($table, $id); // For logging.. foreach ($valueArray as &$theFile) { // if alernative File Path is set for the file, then it was an import if ($this->alternativeFilePath[$theFile]) { // don't import the file if it already exists if (@is_file(PATH_site . $this->alternativeFilePath[$theFile])) { $theFile = PATH_site . $this->alternativeFilePath[$theFile]; // import the file } elseif (@is_file($theFile)) { $dest = dirname(PATH_site . $this->alternativeFilePath[$theFile]); if (!@is_dir($dest)) { t3lib_div::mkdir_deep(PATH_site, dirname($this->alternativeFilePath[$theFile]) . '/'); } // Init: $maxSize = intval($tcaFieldConf['max_size']); $cmd = ''; $theDestFile = ''; // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error! $fileSize = filesize($theFile); if (!$maxSize || $fileSize <= $maxSize * 1024) { // Check file size: // Prepare filename: $theEndFileName = isset($this->alternativeFileName[$theFile]) ? $this->alternativeFileName[$theFile] : $theFile; $fI = t3lib_div::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) { t3lib_div::upload_copy_move($theFile, $theDestFile); $this->copiedFileMap[$theFile] = $theDestFile; clearstatcache(); if (!@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']); } } else { $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']); } } else { $this->log($table, $id, 5, 0, 1, "File extension '%s' not allowed. (%s)", 12, array($fI['fileext'], $recFID), $propArr['event_pid']); } } else { $this->log($table, $id, 5, 0, 1, "Filesize (%s) of file '%s' exceeds limit (%s). (%s)", 13, array(t3lib_div::formatSize($fileSize), $theFile, t3lib_div::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)) { $theFile = $theDestFile; // The value is set to the new filename } else { unset($theFile); // The value is set to the new filename } } } $theFile = t3lib_div::fixWindowsFilePath($theFile); if (t3lib_div::isFirstPartOfStr($theFile, PATH_site)) { $theFile = substr($theFile, strlen(PATH_site)); } } } } } return $valueArray; }
/** * Builds an initial class file to test parsing and modifiying of existing classes * * This class file is generated based on the CodeTemplates * @param string $modelName */ function generateInitialModelClassFile($modelName) { $domainObject = $this->buildDomainObject($modelName); $classFileContent = $this->codeGenerator->generateDomainObjectCode($domainObject, $this->extension); $modelClassDir = 'Classes/Domain/Model/'; $result = t3lib_div::mkdir_deep($this->extension->getExtensionDir(), $modelClassDir); $absModelClassDir = $this->extension->getExtensionDir() . $modelClassDir; $this->assertTrue(is_dir($absModelClassDir), 'Directory ' . $absModelClassDir . ' was not created'); $modelClassPath = $absModelClassDir . $domainObject->getName() . '.php'; t3lib_div::writeFile($modelClassPath, $classFileContent); }
/** * generate a duplicate of a Class with an other Name * Mage_Core_Model_App -> Flagbit_Typo3connect_Rewrite_Core_Model_App * * @param string $className * @return string */ protected function rewriteClass($className) { // cache Path $cachePath = $this->config['path'] . 'var/cache/'; // get Filename from Classname $fileName = $this->_getClassPath($className); // generate a new Version of Classfile if not exists if (!file_exists($cachePath . $fileName)) { // get source of the original Class $content = file_get_contents($this->config['path'] . 'app/code/core/' . uc_words($className, DS) . '.php'); // change Classname $content = preg_replace('/class(.*)' . $className . '/iU', 'class\\1Flagbit_Typo3connect_Rewrite_' . $className, $content); // write new Class $classPath = substr($fileName, 0, strrpos($fileName, '/') + 1); t3lib_div::mkdir_deep($cachePath, substr($fileName, 0, strrpos($fileName, '/') + 1)); t3lib_div::writeFile($cachePath . $fileName, $content); } return $cachePath . $fileName; }
/** * Reads and parse an xml file, and returns an array of XML * Fresh or cached data, depending on $this->conf["cache."]["enabled"] * * @param string $sPath: abs server path to xml file * @param boolean $isSubXml * @return array xml data */ function _getXml($sPath, $isSubXml = FALSE, $bPlain = FALSE) { if (!file_exists($sPath)) { if ($isSubXml === FALSE) { $this->smartMayday_XmlFile($sPath); } else { $this->mayday("FORMIDABLE CORE - The given XML file path (<b>'" . $sPath . "'</b>) doesn't exists."); } } elseif (is_dir($sPath)) { $this->mayday("FORMIDABLE CORE - The given XML file path (<b>'" . $sPath . "'</b>) is a directory, and should be a file."); } elseif (!is_readable($sPath)) { $this->mayday("FORMIDABLE CORE - The given XML file path (<b>'" . $sPath . "'</b>) exists but is not readable."); } else { $sHash = md5($sPath); if (array_key_exists($sHash, $this->_aSubXmlCache)) { return $this->_aSubXmlCache[$sHash]; } else { $aConf = array(); if ($this->conf["cache."]["enabled"] == 1) { $sProtection = "<?php die('Formidable - Cache protected'); ?><!--FORMIDABLE_CACHE-->"; //debug(stat($sPath)); $sHash = md5($sPath . "-" . @filemtime($sPath) . "-" . $this->sApiVersion); $sFile = "formidablexmlcache_" . $sHash . ".php"; $sCacheDir = "ameos_formidable/cache/"; $sCachePath = PATH_site . "typo3temp/" . $sCacheDir . $sFile; if (file_exists($sCachePath)) { $aConf = unserialize(base64_decode(substr($this->file_readBin($sCachePath), strlen($sProtection) + 3))); if (is_array($aConf)) { reset($aConf); } } } if (empty($aConf)) { $sXmlData = $this->file_readBin($sPath); if (trim($sXmlData) === "") { $this->smartMayday_XmlFile($sPath, "FORMIDABLE CORE - The given XML file path (<b>'" . $sPath . "'</b>) exists but is empty."); } $aMatches = array(); preg_match("/^<\\?xml(.*)\\?>/", $sXmlData, $aMatches); // Check result if (!empty($aMatches)) { $sXmlProlog = $aMatches[0]; $sXmlData = preg_replace("/^<\\?xml(.*)\\?>/", "", $sXmlData); } else { $sXmlProlog = '<?xml version="1.0" encoding="utf-8" standalone="yes" ?>'; } if ($isSubXml) { $sXmlData = $sXmlProlog . "\n" . "<phparray>" . $sXmlData . "</phparray>"; } else { $sXmlData = $sXmlProlog . "\n" . $sXmlData; } if ($bPlain === FALSE) { $aConf = $this->div_xml2array($sXmlData); } else { $aConf = $this->div_xml2array_plain($sXmlData); } if (is_array($aConf)) { if ($isSubXml && array_key_exists("phparray", $aConf) && is_array($aConf["phparray"])) { $aConf = $aConf["phparray"]; } reset($aConf); } else { $this->mayday("FORMIDABLE CORE - The given XML file (<b>'" . $sPath . "'</b>) isn't well-formed XML<br>Parser says : <b>" . $aConf . "</b>"); } if ($this->conf["cache."]["enabled"] == 1) { if (!@is_dir(PATH_site . "typo3temp/" . $sCacheDir)) { if (function_exists("t3lib_div::mkdir_deep")) { t3lib_div::mkdir_deep(PATH_site . "typo3temp/", $sCacheDir); } else { $this->div_mkdir_deep(PATH_site . "typo3temp/", $sCacheDir); } } $this->file_writeBin($sCachePath, $sProtection . base64_encode(serialize($aConf)), TRUE); } } reset($aConf); $this->_aSubXmlCache[$sHash] = $aConf; return $aConf; } } }
/** * Install translations for all selected languages for an extension * * @param string $extKey The extension key to install the translations for * @param string $lang Language code of translation to fetch * @param string $mirrorURL Mirror URL to fetch data from * @return mixed true on success, error string on fauilure */ function updateTranslation($extKey, $lang, $mirrorURL) { $l10n = $this->parentObject->terConnection->fetchTranslation($extKey, $lang, $mirrorURL); if (is_array($l10n)) { $file = PATH_site . 'typo3temp/' . $extKey . '-l10n-' . $lang . '.zip'; $path = 'l10n/' . $lang . '/'; if (!is_dir(PATH_typo3conf . $path)) { t3lib_div::mkdir_deep(PATH_typo3conf, $path); } t3lib_div::writeFile($file, $l10n[0]); // this prevent first update having errors t3lib_div::rmdir(PATH_typo3conf . $path . $extKey, TRUE); if (tx_em_Tools::unzip($file, PATH_typo3conf . $path)) { return TRUE; } else { return $GLOBALS['LANG']->getLL('translation_unpacking_failed'); } } else { return $l10n; } }
/** * Write a simple model class for a non aggregate root domain object * * @depends checkRequirements * @test */ function writeSimpleControllerClassFromDomainObject() { $domainObject = $this->buildDomainObject('ModelCgt6', true); $action = t3lib_div::makeInstance('Tx_ExtensionBuilder_Domain_Model_DomainObject_Action'); $action->setName('list'); $domainObject->addAction($action); $classFileContent = $this->codeGenerator->generateActionControllerCode($domainObject, $this->extension); $controllerClassDir = 'Classes/Controller/'; $result = t3lib_div::mkdir_deep($this->extension->getExtensionDir(), $controllerClassDir); $absControllerClassDir = $this->extension->getExtensionDir() . $controllerClassDir; $this->assertTrue(is_dir($absControllerClassDir), 'Directory ' . $absControllerClassDir . ' was not created'); $controllerClassPath = $absControllerClassDir . $domainObject->getName() . 'Controller.php'; t3lib_div::writeFile($controllerClassPath, $classFileContent); $this->assertFileExists($controllerClassPath, 'File was not generated: ' . $controllerClassPath); $className = $domainObject->getControllerName(); include $controllerClassPath; $this->assertTrue(class_exists($className), 'Class was not generated:' . $className); }
/** * Sets up the PDO backend used for testing * * @return t3lib_cache_backend_PdoBackend * @author Karsten Dambekalns <*****@*****.**> */ protected function setUpBackend() { $this->fixtureFolder = sys_get_temp_dir() . '/' . 'typo3pdobackendtest/'; t3lib_div::mkdir_deep(sys_get_temp_dir() . '/', 'typo3pdobackendtest/'); $this->fixtureDB = uniqid('Cache') . '.db'; $pdoHelper = t3lib_div::makeInstance('t3lib_PdoHelper', 'sqlite:' . $this->fixtureFolder . $this->fixtureDB, '', ''); $pdoHelper->importSql(PATH_t3lib . 'cache/backend/resources/ddl.sql'); $mockCache = $this->getMock('t3lib_cache_frontend_Frontend', array(), array(), '', FALSE); $mockCache->expects($this->any())->method('getIdentifier')->will($this->returnValue('TestCache')); $backendOptions = array('dataSourceName' => 'sqlite:' . $this->fixtureFolder . $this->fixtureDB, 'username' => '', 'password' => ''); $backend = t3lib_div::makeInstance('t3lib_cache_backend_PdoBackend', $backendOptions); $backend->setCache($mockCache); return $backend; }
/** * Searches for upload folder settings in TypoScript setup. * If no settings is found, the default upload folder is set. * * Here is an example: * <code> * plugin.Tx_Formhandler.settings.files.tmpUploadFolder = uploads/formhandler/tmp * </code> * * The default upload folder is: '/uploads/formhandler/tmp/' * * @return void * @static * @author Reinhard Führicht <*****@*****.**> */ public static function getTempUploadFolder() { //set default upload folder $uploadFolder = '/uploads/formhandler/tmp/'; //if temp upload folder set in TypoScript, take that setting $settings = Tx_Formhandler_Globals::$session->get('settings'); if ($settings['files.']['uploadFolder']) { $uploadFolder = Tx_Formhandler_StaticFuncs::getSingle($settings['files.'], 'uploadFolder'); $uploadFolder = Tx_Formhandler_StaticFuncs::sanitizePath($uploadFolder); } //if the set directory doesn't exist, print a message and try to create if (!is_dir(Tx_Formhandler_StaticFuncs::getTYPO3Root() . $uploadFolder)) { Tx_Formhandler_StaticFuncs::debugMessage('folder_doesnt_exist', array(Tx_Formhandler_StaticFuncs::getTYPO3Root() . '/' . $uploadFolder), 2); t3lib_div::mkdir_deep(Tx_Formhandler_StaticFuncs::getTYPO3Root() . '/', $uploadFolder); } return $uploadFolder; }
/** * Main hook function * * @param array $params Array of CSS/javascript and other * files * @param object $pagerendere Pagerenderer object * @return null * */ public function renderPreProcessorProc(&$params, $pagerenderer) { if (!is_array($params['cssFiles'])) { return; } $setup = $GLOBALS['TSFE']->tmpl->setup; if (is_array($setup['plugin.']['tx_wsless.']['variables.'])) { $this->variables = $setup['plugin.']['tx_wsless.']['variables.']; } // we need to rebuild the CSS array to keep order of CSS // files $cssFiles = array(); foreach ($params['cssFiles'] as $file => $conf) { $pathinfo = pathinfo($conf['file']); if ($pathinfo['extension'] !== 'less') { $cssFiles[$file] = $conf; continue; } $outputdir = $this->defaultoutputdir; // search settings for less file foreach ($GLOBALS['TSFE']->pSetup['includeCSS.'] as $key => $subconf) { if (is_string($GLOBALS['TSFE']->pSetup['includeCSS.'][$key]) && $GLOBALS['TSFE']->tmpl->getFileName($GLOBALS['TSFE']->pSetup['includeCSS.'][$key]) == $file) { if (isset($GLOBALS['TSFE']->pSetup['includeCSS.'][$key . '.']['outputdir'])) { $outputdir = trim($GLOBALS['TSFE']->pSetup['includeCSS.'][$key . '.']['outputdir']); } } } $outputdir = substr($outputdir, -1) == '/' ? $outputdir : $outputdir . "/"; if (!strcmp(substr($outputdir, 0, 4), 'EXT:')) { $newFile = ''; list($extKey, $script) = explode('/', substr($outputdir, 4), 2); if ($extKey && \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded($extKey)) { $extPath = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath($extKey); $outputdir = substr($extPath, strlen(PATH_site)) . $script; } } $lessFilename = t3lib_div::getFileAbsFileName($conf['file']); // create filename - hash is importand due to the possible // conflicts with same filename in different folder t3lib_div::mkdir_deep(PATH_site . $outputdir); $cssRelativeFilename = $outputdir . $pathinfo['filename'] . ($outputdir == $this->defaultoutputdir ? "_" . hash('sha1', $file) : "") . ".css"; $cssFilename = PATH_site . $cssRelativeFilename; $cache = $GLOBALS['typo3CacheManager']->getCache('ws_less'); $cacheKey = hash('sha1', $cssRelativeFilename); $contentHash = $this->calculateContentHash($lessFilename); $contentHashCache = ''; if ($cache->has($cacheKey)) { $contentHashCache = $cache->get($cacheKey); } try { if ($contentHashCache == '' || $contentHashCache != $contentHash) { $this->compileScss($lessFilename, $cssFilename); } } catch (Exception $ex) { // log the exception to the TYPO3 log as error echo $ex->getMessage(); t3lib_div::sysLog($ex->getMessage(), t3lib_div::SYSLOG_SEVERITY_ERROR); } $cache->set($cacheKey, $contentHash, array()); $cssFiles[$cssRelativeFilename] = $params['cssFiles'][$file]; $cssFiles[$cssRelativeFilename]['file'] = $cssRelativeFilename; } $params['cssFiles'] = $cssFiles; }
/** * lessc * * @return void */ public function lessc( $files ) { // create outputfolder if it does not exist if( !is_dir( $this->outputfolder ) ) { t3lib_div::mkdir_deep( '', $this->outputfolder ); } // compile each less-file foreach( $files as $file ) { //get only the name of less file $filename = array_pop( explode( '/', $file ) ); $md5 = md5( $filename . md5_file( $file ) ); $outputfile = $this->outputfolder . substr( $filename, 0, -5 ) . '_' . $md5 . '.css'; if( $this->configuration['other']['forceMode'] && file_exists( $outputfile ) ) { unlink( $outputfile ); } if( !file_exists( $outputfile ) ) { $compressed = $this->configuration['other']['compressed'] ? '--compress' : ''; /* Define directories for @import scripts */ $importDirs = ''; if( isset( $this->configuration['other']['importDirs'] ) ) { $importDirs = implode( ':', Tx_T3Less_Utility_Utilities::splitAndResolveDirNames( $this->configuration['other']['importDirs'] ) ); } $lesscCommand = sprintf( 'lessc %s --line-numbers=\'comments\' --include-path=%s %s > %s 2>&1', $compressed, $importDirs, $file, $outputfile ); $lesscOutput = array( ); $lesscStatus = 0; exec( $lesscCommand, $lesscOutput, $lesscStatus ); t3lib_div::fixPermissions( $outputfile, FALSE ); } } // unlink compiled files which have no equal source less-file if( $this->configuration['other']['unlinkCssFilesWithNoSourceFile'] == 1 ) { $this->unlinkGeneratedFilesWithNoSourceFile( $files ); } $files = t3lib_div::getFilesInDir( $this->outputfolder, "css" ); //respect given sort order defined in TS usort( $files, array( $this, 'getSortOrderPhp' ) ); foreach( $files as $cssFile ) { $excludeFromPageRender = isset( $this->configuration['phpcompiler']['filesettings'][substr( $cssFile, 0, -37 )]['excludeFromPageRenderer'] ) ? $this->configuration['phpcompiler']['filesettings'][substr( $cssFile, 0, -37 )]['excludeFromPageRenderer'] : 0; if( !$excludeFromPageRender || $excludeFromPageRender == 0 ) { // array with filesettings from TS $tsOptions = $this->configuration['phpcompiler']['filesettings'][substr( $cssFile, 0, -37 )]; $GLOBALS['TSFE']->getPageRenderer()->addCssFile( $this->outputfolder . $cssFile, $rel = 'stylesheet', $media = isset( $tsOptions['media'] ) ? $tsOptions['media'] : 'all', $title = isset( $tsOptions['title'] ) ? $tsOptions['title'] : '', $compress = isset( $tsOptions['compress'] ) && $tsOptions['compress'] >= '0' ? (boolean) $tsOptions['compress'] : TRUE, $forceOnTop = isset( $tsOptions['forceOnTop'] ) && $tsOptions['forceOnTop'] >= '0' ? (boolean) $tsOptions['forceOnTop'] : FALSE, $allWrap = isset( $tsOptions['allWrap'] ) ? $tsOptions['allWrap'] : '', $excludeFromConcatenation = isset( $tsOptions['excludeFromConcatenation'] ) && $tsOptions['excludeFromConcatenation'] >= '0' ? (boolean) $tsOptions['excludeFromConcatenation'] : FALSE ); } } }
/** * Sets the directory where the cache files are stored. By default it is * assumed that the directory is below the TYPO3_DOCUMENT_ROOT. However, an * absolute path can be selected, too. * * @param string The directory. If a relative path is given, it's assumed it's in TYPO3_DOCUMENT_ROOT. If an absolute path is given it is taken as is. * @return void * @throws t3lib_cache_Exception if the directory does not exist, is not writable or could not be created. * @author Robert Lemke <*****@*****.**> * @author Ingo Renner <*****@*****.**> */ public function setCacheDirectory($cacheDirectory) { $documentRoot = PATH_site; if ($open_basedir = ini_get('open_basedir')) { if (TYPO3_OS === 'WIN') { $delimiter = ';'; $cacheDirectory = str_replace('\\', '/', $cacheDirectory); if (!preg_match('/[A-Z]:/', substr($cacheDirectory, 0, 2))) { $cacheDirectory = PATH_site . $cacheDirectory; } } else { $delimiter = ':'; if ($cacheDirectory[0] != '/') { // relative path to cache directory. $cacheDirectory = PATH_site . $cacheDirectory; } } $basedirs = explode($delimiter, $open_basedir); $cacheDirectoryInBaseDir = FALSE; foreach ($basedirs as $basedir) { if (TYPO3_OS === 'WIN') { $basedir = str_replace('\\', '/', $basedir); } if ($basedir[strlen($basedir) - 1] !== '/') { $basedir .= '/'; } if (t3lib_div::isFirstPartOfStr($cacheDirectory, $basedir)) { $documentRoot = $basedir; $cacheDirectory = str_replace($basedir, '', $cacheDirectory); $cacheDirectoryInBaseDir = TRUE; break; } } if (!$cacheDirectoryInBaseDir) { throw new t3lib_cache_Exception('Open_basedir restriction in effect. The directory "' . $cacheDirectory . '" is not in an allowed path.'); } } else { if ($cacheDirectory[0] == '/') { // Absolute path to cache directory. $documentRoot = '/'; } if (TYPO3_OS === 'WIN') { if (substr($cacheDirectory, 0, strlen($documentRoot)) === $documentRoot) { $documentRoot = ''; } } } // After this point all paths have '/' as directory seperator if ($cacheDirectory[strlen($cacheDirectory) - 1] !== '/') { $cacheDirectory .= '/'; } $cacheDirectory .= $this->cacheIdentifier; if ($cacheDirectory[strlen($cacheDirectory) - 1] !== '/') { $cacheDirectory .= '/'; } if (!is_writable($documentRoot . $cacheDirectory)) { t3lib_div::mkdir_deep($documentRoot, $cacheDirectory); } if (!is_dir($documentRoot . $cacheDirectory)) { throw new t3lib_cache_Exception('The directory "' . $documentRoot . $cacheDirectory . '" does not exist.', 1203965199); } if (!is_writable($documentRoot . $cacheDirectory)) { throw new t3lib_cache_Exception('The directory "' . $documentRoot . $cacheDirectory . '" is not writable.', 1203965200); } $this->root = $documentRoot; $this->cacheDirectory = $cacheDirectory; }
/** * * @param string $path * @return boolean TRUE if directory exists and is writable or could be created */ protected function checkDirectory($path) { $status = FALSE; $path = $path . (substr($path, -1) == '/' ? '' : '/'); if (@is_writable(PATH_site . $path)) { $status = TRUE; } if (!is_dir(PATH_site . $path)) { $errors = t3lib_div::mkdir_deep(PATH_site, $path); if ($errors === NULL) { $status = TRUE; } } return $status; }
/** * Install translations for all selected languages for an extension * * @param string $extKey The extension key to install the translations for * @param string $lang Language code of translation to fetch * @param string $mirrorURL Mirror URL to fetch data from * @return mixed true on success, error string on fauilure */ function updateTranslation($extKey, $lang, $mirrorURL) { $l10n = $this->fetchTranslation($extKey, $lang, $mirrorURL); if (is_array($l10n)) { $file = PATH_site . 'typo3temp/' . $extKey . '-l10n-' . $lang . '.zip'; $path = 'l10n/' . $lang . '/'; if (!is_dir(PATH_typo3conf . $path)) { t3lib_div::mkdir_deep(PATH_typo3conf, $path); } t3lib_div::writeFile($file, $l10n[0]); if (tx_em_Tools::unzip($file, PATH_typo3conf . $path)) { return TRUE; } } return FALSE; }
/** * Writes $content to a filename in the typo3temp/ folder (and possibly one or two subfolders...) * Accepts an additional subdirectory in the file path! * * @param string Absolute filepath to write to inside "typo3temp/". First part of this string must match PATH_site."typo3temp/" * @param string Content string to write * @return string Returns false on success, otherwise an error string telling about the problem. */ public static function writeFileToTypo3tempDir($filepath, $content) { // Parse filepath into directory and basename: $fI = pathinfo($filepath); $fI['dirname'] .= '/'; // Check parts: if (t3lib_div::validPathStr($filepath) && $fI['basename'] && strlen($fI['basename']) < 60) { if (defined('PATH_site')) { $dirName = PATH_site . 'typo3temp/'; // Setting main temporary directory name (standard) if (@is_dir($dirName)) { if (t3lib_div::isFirstPartOfStr($fI['dirname'], $dirName)) { // Checking if the "subdir" is found: $subdir = substr($fI['dirname'], strlen($dirName)); if ($subdir) { if (ereg('^[[:alnum:]_]+\\/$', $subdir) || ereg('^[[:alnum:]_]+\\/[[:alnum:]_]+\\/$', $subdir)) { $dirName .= $subdir; if (!@is_dir($dirName)) { t3lib_div::mkdir_deep(PATH_site . 'typo3temp/', $subdir); } } else { return 'Subdir, "' . $subdir . '", was NOT on the form "[[:alnum:]_]/" or "[[:alnum:]_]/[[:alnum:]_]/"'; } } // Checking dir-name again (sub-dir might have been created): if (@is_dir($dirName)) { if ($filepath == $dirName . $fI['basename']) { t3lib_div::writeFile($filepath, $content); if (!@is_file($filepath)) { return 'File not written to disk! Write permission error in filesystem?'; } } else { return 'Calculated filelocation didn\'t match input $filepath!'; } } else { return '"' . $dirName . '" is not a directory!'; } } else { return '"' . $fI['dirname'] . '" was not within directory PATH_site + "typo3temp/"'; } } else { return 'PATH_site + "typo3temp/" was not a directory!'; } } else { return 'PATH_site constant was NOT defined!'; } } else { return 'Input filepath "' . $filepath . '" was generally invalid!'; } }
/** * * @param string $path * @return boolean TRUE if directory exists and is writable or could be created */ protected function checkDirectory($path) { $status = FALSE; $path = rtrim($path, '/') . '/'; $absolutePath = t3lib_div::getFileAbsFileName($path); if (!empty($absolutePath)) { if (@is_writable($absolutePath)) { $status = TRUE; } if (!is_dir($absolutePath)) { try { $errors = t3lib_div::mkdir_deep(PATH_site, $path); if ($errors === NULL) { $status = TRUE; } } catch (\RuntimeException $e) { } } } return $status; }
/** * Write the proxy file * * @param string $content * @param string $identifier identifier of the file * @throws RuntimeException * @return string path of the written file */ protected function writeFile($content, $identifier) { $path = PATH_site . self::CACHE_FILE_LOCATION; if (!is_dir($path)) { t3lib_div::mkdir_deep(PATH_site, self::CACHE_FILE_LOCATION); } $content = '<?php ' . LF . $content . LF . '}' . LF . '?>'; $path .= $this->generateFileNameFromIdentifier($identifier); $success = t3lib_div::writeFile($path, $content); if (!$success) { throw new RuntimeException('File "' . $path . '" could not be written'); } return $path; }
/** * Gets all available XML or ZIP files from the FTP server * * @throws Exception * @return array List of files, as local paths */ protected function getFilesFromFtp() { $files = array(); // First try connecting and logging in $connection = ftp_connect($this->extensionConfiguration['ftp_server']); if ($connection === FALSE) { throw new Exception('Could not connect to FTP server', 1322489458); } else { if (@ftp_login($connection, $this->extensionConfiguration['ftp_server_username'], $this->extensionConfiguration['ftp_server_password'])) { ftp_pasv($connection, TRUE); // If a path was defined, change directory to this path if (!empty($this->extensionConfiguration['ftp_server_downpath'])) { $result = ftp_chdir($connection, $this->extensionConfiguration['ftp_server_downpath']); if ($result === FALSE) { throw new Exception('Could not change to directory: ' . $this->extensionConfiguration['ftp_server_downpath'], 1322489723); } } // Get list of files to download from current directory $filesToDownload = ftp_nlist($connection, ''); // If there are any files, loop on them if ($filesToDownload != FALSE) { // Check that download directory exists $downloadFolder = 'uploads/tx_l10nmgr/jobs/in/'; $downloadPath = PATH_site . $downloadFolder; if (!is_dir(t3lib_div::getFileAbsFileName($downloadPath))) { t3lib_div::mkdir_deep(PATH_site, $downloadFolder); } foreach ($filesToDownload as $aFile) { // Ignore current directory and reference to upper level if ($aFile != '.' && $aFile != '..') { $fileInformation = pathinfo($aFile); // Download only XML or ZIP files if ($fileInformation['extension'] == 'xml' || $fileInformation['extension'] == 'zip') { $savePath = $downloadPath . $aFile; // Get each file and save them to temporary directory $result = ftp_get($connection, $savePath, $aFile, FTP_BINARY); if ($result) { // If the file is XML, list it for usage as is if ($fileInformation['extension'] == 'xml') { $files[] = $savePath; } else { /** @var $unzip tx_l10nmgr_zip */ $unzip = t3lib_div::makeInstance('tx_l10nmgr_zip'); $unzipResource = $unzip->extractFile($savePath); // Process extracted files if file type = xml => IMPORT $archiveFiles = $this->checkFileType($unzipResource['fileArr'], 'xml'); $files = array_merge($files, $archiveFiles); // Store the temporary directory's path for later clean up $this->directoryToCleanUp = $unzipResource['tempDir']; } // Remove the file from the FTP server $result = ftp_delete($connection, $aFile); // If deleting failed, register error message // (don't throw exception as this does not need to interrupt the process) if (!$result) { $this->errors[] = 'Could not remove file ' . $aFile . 'from FTP server'; } // If getting the file failed, register error message // (don't throw exception as this does not need to interrupt the process) } else { $this->errors[] = 'Problem getting file ' . $aFile . 'from server or saving it locally'; } } } } } } else { ftp_close($connection); throw new Exception('Could not log into to FTP server', 1322489527); } } return $files; }
/** * * @param Tx_ExtensionBuilder_Domain_Model_Extension $extension * @param string $codeTemplateRootPath */ public function createInitialSettingsFile($extension, $codeTemplateRootPath) { t3lib_div::mkdir_deep($extension->getExtensionDir(), self::SETTINGS_DIR); $settings = file_get_contents($codeTemplateRootPath . 'Configuration/ExtensionBuilder/settings.yamlt'); $settings = str_replace('{extension.extensionKey}', $extension->getExtensionKey(), $settings); $settings = str_replace('<f:format.date>now</f:format.date>', date('Y-m-d H:i'), $settings); t3lib_div::writeFile($extension->getExtensionDir() . self::SETTINGS_DIR . 'settings.yaml', $settings); }