/**
  * Import command
  *
  * @param string $icsCalendarUri
  * @param int    $pid
  */
 public function importCommand($icsCalendarUri = null, $pid = null)
 {
     if ($icsCalendarUri === null || !filter_var($icsCalendarUri, FILTER_VALIDATE_URL)) {
         $this->enqueueMessage('You have to enter a valid URL to the iCalendar ICS', 'Error', FlashMessage::ERROR);
         return;
     }
     if (!MathUtility::canBeInterpretedAsInteger($pid)) {
         $this->enqueueMessage('You have to enter a valid PID for the new created elements', 'Error', FlashMessage::ERROR);
         return;
     }
     // fetch external URI and write to file
     $this->enqueueMessage('Start to checkout the calendar: ' . $icsCalendarUri, 'Calendar', FlashMessage::INFO);
     $relativeIcalFile = 'typo3temp/ical.' . GeneralUtility::shortMD5($icsCalendarUri) . '.ical';
     $absoluteIcalFile = GeneralUtility::getFileAbsFileName($relativeIcalFile);
     $content = GeneralUtility::getUrl($icsCalendarUri);
     GeneralUtility::writeFile($absoluteIcalFile, $content);
     // get Events from file
     $icalEvents = $this->getIcalEvents($absoluteIcalFile);
     $this->enqueueMessage('Found ' . sizeof($icalEvents) . ' events in the given calendar', 'Items', FlashMessage::INFO);
     $events = $this->prepareEvents($icalEvents);
     $this->enqueueMessage('Found ' . sizeof($events) . ' events in ' . $icsCalendarUri, 'Items', FlashMessage::INFO);
     /** @var Dispatcher $signalSlotDispatcher */
     $signalSlotDispatcher = GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\SignalSlot\\Dispatcher');
     $this->enqueueMessage('Send the ' . __CLASS__ . '::importCommand signal for each event.', 'Signal', FlashMessage::INFO);
     foreach ($events as $event) {
         $arguments = ['event' => $event, 'commandController' => $this, 'pid' => $pid, 'handled' => false];
         $signalSlotDispatcher->dispatch(__CLASS__, 'importCommand', $arguments);
     }
 }
 /**
  * Import command
  *
  * @param string $icsCalendarUri
  * @param int    $pid
  */
 public function importCommand($icsCalendarUri = NULL, $pid = NULL)
 {
     if ($icsCalendarUri === NULL || !filter_var($icsCalendarUri, FILTER_VALIDATE_URL)) {
         $this->enqueueMessage('You have to enter a valid URL to the iCalendar ICS', 'Error', FlashMessage::ERROR);
     }
     if (!MathUtility::canBeInterpretedAsInteger($pid)) {
         $this->enqueueMessage('You have to enter a valid PID for the new created elements', 'Error', FlashMessage::ERROR);
     }
     // fetch external URI and write to file
     $this->enqueueMessage('Start to checkout the calendar: ' . $icsCalendarUri, 'Calendar', FlashMessage::INFO);
     $relativeIcalFile = 'typo3temp/ical.' . GeneralUtility::shortMD5($icsCalendarUri) . '.ical';
     $absoluteIcalFile = GeneralUtility::getFileAbsFileName($relativeIcalFile);
     $content = GeneralUtility::getUrl($icsCalendarUri);
     GeneralUtility::writeFile($absoluteIcalFile, $content);
     // get Events from file
     $icalEvents = $this->getIcalEvents($absoluteIcalFile);
     $this->enqueueMessage('Found ' . sizeof($icalEvents) . ' events in the given calendar', 'Items', FlashMessage::INFO);
     $events = $this->prepareEvents($icalEvents);
     $this->enqueueMessage('This is just a first draft. There are same missing fields. Will be part of the next release', 'Items', FlashMessage::ERROR);
     return;
     foreach ($events as $event) {
         $eventObject = $this->eventRepository->findOneByImportId($event['uid']);
         if ($eventObject instanceof Event) {
             // update
             $eventObject->setTitle($event['title']);
             $eventObject->setDescription($this->nl2br($event['description']));
             $this->eventRepository->update($eventObject);
             $this->enqueueMessage('Update Event Meta data: ' . $eventObject->getTitle(), 'Update');
         } else {
             // create
             $eventObject = new Event();
             $eventObject->setPid($pid);
             $eventObject->setImportId($event['uid']);
             $eventObject->setTitle($event['title']);
             $eventObject->setDescription($this->nl2br($event['description']));
             $configuration = new Configuration();
             $configuration->setType(Configuration::TYPE_TIME);
             $configuration->setFrequency(Configuration::FREQUENCY_NONE);
             /** @var \DateTime $startDate */
             $startDate = clone $event['start'];
             $startDate->setTime(0, 0, 0);
             $configuration->setStartDate($startDate);
             /** @var \DateTime $endDate */
             $endDate = clone $event['end'];
             $endDate->setTime(0, 0, 0);
             $configuration->setEndDate($endDate);
             $startTime = $this->dateTimeToDaySeconds($event['start']);
             if ($startTime > 0) {
                 $configuration->setStartTime($startTime);
                 $configuration->setEndTime($this->dateTimeToDaySeconds($event['end']));
                 $configuration->setAllDay(FALSE);
             } else {
                 $configuration->setAllDay(TRUE);
             }
             $eventObject->addCalendarize($configuration);
             $this->eventRepository->add($eventObject);
             $this->enqueueMessage('Add Event: ' . $eventObject->getTitle(), 'Add');
         }
     }
 }
Example #3
0
 /**
  * @param array $ajaxParams
  * @param \TYPO3\CMS\Core\Http\AjaxRequestHandler $ajaxObject
  * @return string
  */
 public function updateConfigurationFile($ajaxParams, $ajaxObject)
 {
     $extensionKey = \TYPO3\CMS\Core\Utility\GeneralUtility::_GP('extensionKey');
     if (!empty($extensionKey)) {
         $packageManager = \TYPO3\CMS\Core\Core\Bootstrap::getInstance()->getEarlyInstance('TYPO3\\Flow\\Package\\PackageManager');
         $extensionConfigurationPath = $packageManager->getPackage($extensionKey)->getPackagePath() . 'ext_emconf.php';
         $_EXTKEY = $extensionKey;
         $EM_CONF = NULL;
         $extension = NULL;
         if (file_exists($extensionConfigurationPath)) {
             include $extensionConfigurationPath;
             if (is_array($EM_CONF[$_EXTKEY])) {
                 $extension = $EM_CONF[$_EXTKEY];
             }
         }
         if ($EM_CONF !== NULL) {
             $currentMd5HashArray = \IchHabRecht\Devtools\Utility\ExtensionUtility::getMd5HashArrayForExtension($extensionKey);
             $EM_CONF[$extensionKey]['_md5_values_when_last_written'] = serialize($currentMd5HashArray);
             /** @var \TYPO3\CMS\Extensionmanager\Utility\EmConfUtility $emConfUtility */
             $emConfUtility = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('\\TYPO3\\CMS\\Extensionmanager\\Utility\\EmConfUtility');
             $extensionData = array('extKey' => $extensionKey, 'EM_CONF' => $EM_CONF[$extensionKey]);
             $emConfContent = $emConfUtility->constructEmConf($extensionData);
             \TYPO3\CMS\Core\Utility\GeneralUtility::writeFile($extensionConfigurationPath, $emConfContent);
         }
         $ajaxObject->setContentFormat('json');
         $ajaxObject->addContent('title', $this->translate('title'));
         $ajaxObject->addContent('message', sprintf($this->translate('message'), $extensionKey));
     }
 }
Example #4
0
 /**
  * Writes the GD font file
  *
  * @param \SJBR\SrFreecap\Domain\Model\Font the object to be stored
  * @return \SJBR\SrFreecap\Domain\Repository\FontRepository $this
  */
 public function writeFontFile(\SJBR\SrFreecap\Domain\Model\Font $font)
 {
     $relativeFileName = 'uploads/' . \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::getCN($this->extensionKey) . '/' . $font->getGdFontFilePrefix() . '_' . \TYPO3\CMS\Core\Utility\GeneralUtility::shortMD5($font->getGdFontData()) . '.gdf';
     if (\TYPO3\CMS\Core\Utility\GeneralUtility::writeFile(PATH_site . $relativeFileName, $font->getGdFontData())) {
         $font->setGdFontFileName($relativeFileName);
     }
     return $this;
 }
 /**
  * Puts all information compiled by the ClassLoadingInformationGenerator to files
  */
 public static function writeClassLoadingInformation()
 {
     self::ensureAutoloadInfoDirExists();
     $classInfoFiles = ClassLoadingInformationGenerator::buildAutoloadInformationFiles();
     GeneralUtility::writeFile(PATH_site . self::AUTOLOAD_INFO_DIR . self::AUTOLOAD_CLASSMAP_FILENAME, $classInfoFiles['classMapFile']);
     GeneralUtility::writeFile(PATH_site . self::AUTOLOAD_INFO_DIR . self::AUTOLOAD_PSR4_FILENAME, $classInfoFiles['psr-4File']);
     $classAliasMapFile = ClassLoadingInformationGenerator::buildClassAliasMapFile();
     GeneralUtility::writeFile(PATH_site . self::AUTOLOAD_INFO_DIR . self::AUTOLOAD_CLASSALIASMAP_FILENAME, $classAliasMapFile);
 }
 /**
  * @param \EBT\ExtensionBuilder\Domain\Model\Extension $extension
  */
 public function saveExtensionConfiguration(\EBT\ExtensionBuilder\Domain\Model\Extension $extension)
 {
     $extensionBuildConfiguration = $this->configurationManager->getConfigurationFromModeler();
     $extensionBuildConfiguration['log'] = array('last_modified' => date('Y-m-d h:i'), 'extension_builder_version' => \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::getExtensionVersion('extension_builder'), 'be_user' => $GLOBALS['BE_USER']->user['realName'] . ' (' . $GLOBALS['BE_USER']->user['uid'] . ')');
     $encodeOptions = 0;
     // option JSON_PRETTY_PRINT is available since PHP 5.4.0
     if (defined('JSON_PRETTY_PRINT')) {
         $encodeOptions |= JSON_PRETTY_PRINT;
     }
     \TYPO3\CMS\Core\Utility\GeneralUtility::writeFile($extension->getExtensionDir() . \EBT\ExtensionBuilder\Configuration\ConfigurationManager::EXTENSION_BUILDER_SETTINGS_FILE, json_encode($extensionBuildConfiguration, $encodeOptions));
 }
Example #7
0
 /**
  * Write a file and create the target folder, if the folder do not exists
  *
  * @param string $absoluteFileName
  * @param string $content
  *
  * @return bool
  * @throws Exception
  */
 public static function writeFileAndCreateFolder($absoluteFileName, $content)
 {
     $dir = PathUtility::dirname($absoluteFileName) . '/';
     if (!is_dir($dir)) {
         GeneralUtility::mkdir_deep($dir);
     }
     if (is_file($absoluteFileName) && !is_writable($absoluteFileName)) {
         throw new Exception('The autoloader try to add same content to ' . $absoluteFileName . ' but the file is not writable for the autoloader. Please fix it!', 234627835);
     }
     return GeneralUtility::writeFile($absoluteFileName, $content);
 }
Example #8
0
 /**
  * Create .htaccess file.
  */
 public function createHtaccessFile()
 {
     $htAccessFile = GeneralUtility::getFileAbsFileName(".htaccess");
     if (file_exists($htAccessFile)) {
         $this->addMessage(FlashMessage::NOTICE, '.htaccess not created', ' File .htaccess exists already in the root directory.');
         return;
     }
     $htAccessContent = GeneralUtility::getUrl(PATH_site . 'typo3_src/_.htaccess');
     GeneralUtility::writeFile($htAccessFile, $htAccessContent, TRUE);
     $this->addMessage(FlashMessage::OK, '.htaccess file created', 'File .htaccess was created in the root directory.');
 }
 /**
  * Creates a fake extension with a given table definition.
  *
  * @param string $tableDefinition SQL script to create the extension's tables
  * @throws \RuntimeException
  * @return void
  */
 protected function createFakeExtension($tableDefinition)
 {
     // Prepare a fake extension configuration
     $ext_tables = GeneralUtility::tempnam('ext_tables');
     if (!GeneralUtility::writeFile($ext_tables, $tableDefinition)) {
         throw new \RuntimeException('Can\'t write temporary ext_tables file.');
     }
     $this->temporaryFiles[] = $ext_tables;
     $GLOBALS['TYPO3_LOADED_EXT'] = array('test_dbal' => array('ext_tables.sql' => $ext_tables));
     // Append our test table to the list of existing tables
     $this->subject->initialize();
 }
 /**
  * Locks backend access for all users by writing a lock file that is checked when the backend is accessed.
  *
  * @param string $redirectUrl URL to redirect to when the backend is accessed
  */
 public function lockCommand($redirectUrl = NULL)
 {
     if (@is_file(PATH_typo3conf . 'LOCK_BACKEND')) {
         $this->outputLine('A lockfile already exists. Overwriting it...');
     }
     \TYPO3\CMS\Core\Utility\GeneralUtility::writeFile(PATH_typo3conf . 'LOCK_BACKEND', (string) $redirectUrl);
     if ($redirectUrl === NULL) {
         $this->outputLine('Wrote lock file to \'typo3conf/LOCK_BACKEND\'');
     } else {
         $this->outputLine('Wrote lock file to \'typo3conf/LOCK_BACKEND\' with instruction to redirect to: \'' . $redirectUrl . '\'');
     }
 }
Example #11
0
 /**
  * Get the ICS events in an array
  *
  * @param string $paramUrl
  *
  * @return array
  */
 function toArray($paramUrl)
 {
     $tempFileName = GeneralUtility::getFileAbsFileName('typo3temp/calendarize_temp_' . GeneralUtility::shortMD5($paramUrl));
     if (filemtime($tempFileName) < time() - 60 * 60) {
         $icsFile = GeneralUtility::getUrl($paramUrl);
         GeneralUtility::writeFile($tempFileName, $icsFile);
     }
     $backend = new ICalParser();
     if ($backend->parseFromFile($tempFileName)) {
         return $backend->getEvents();
     }
     return array();
 }
 /**
  * Puts all information compiled by the ClassLoadingInformationGenerator to files
  */
 public static function dumpClassLoadingInformation()
 {
     self::ensureAutoloadInfoDirExists();
     $composerClassLoader = static::getClassLoader();
     $activeExtensionPackages = static::getActiveExtensionPackages();
     /** @var ClassLoadingInformationGenerator  $generator */
     $generator = GeneralUtility::makeInstance(ClassLoadingInformationGenerator::class, $composerClassLoader, $activeExtensionPackages, PATH_site, self::isTestingContext());
     $classInfoFiles = $generator->buildAutoloadInformationFiles();
     GeneralUtility::writeFile(self::getClassLoadingInformationDirectory() . self::AUTOLOAD_CLASSMAP_FILENAME, $classInfoFiles['classMapFile']);
     GeneralUtility::writeFile(self::getClassLoadingInformationDirectory() . self::AUTOLOAD_PSR4_FILENAME, $classInfoFiles['psr-4File']);
     $classAliasMapFile = $generator->buildClassAliasMapFile();
     GeneralUtility::writeFile(self::getClassLoadingInformationDirectory() . self::AUTOLOAD_CLASSALIASMAP_FILENAME, $classAliasMapFile);
 }
 /**
  * Get the ICS events in an array
  *
  * @param string $paramUrl
  *
  * @return array
  */
 function toArray($paramUrl)
 {
     $tempFileName = $this->getCheckedCacheFolder() . GeneralUtility::shortMD5($paramUrl);
     if (!is_file($tempFileName) || filemtime($tempFileName) < time() - DateTimeUtility::SECONDS_HOUR) {
         $icsFile = GeneralUtility::getUrl($paramUrl);
         GeneralUtility::writeFile($tempFileName, $icsFile);
     }
     $backend = new ICalParser();
     if ($backend->parseFromFile($tempFileName)) {
         return $backend->getEvents();
     }
     return [];
 }
 /**
  * Initializes a poll repository.
  *
  * @return PollRepository
  */
 public static function initializePollRepository()
 {
     $settings = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['doodle']);
     /** @var \Causal\DoodleClient\Client $doodleClient */
     $doodleClient = GeneralUtility::makeInstance('Causal\\DoodleClient\\Client', $settings['username'], $settings['password']);
     $cookiePath = PATH_site . 'typo3temp/tx_doodle/';
     if (!is_dir($cookiePath)) {
         GeneralUtility::mkdir($cookiePath);
     }
     if (!is_file($cookiePath . '/.htaccess')) {
         GeneralUtility::writeFile($cookiePath . '/.htaccess', 'Deny from all');
     }
     $doodleClient->setCookiePath($cookiePath)->connect();
     /** @var \Causal\Doodle\Domain\Repository\PollRepository $pollRepository */
     $pollRepository = GeneralUtility::makeInstance('Causal\\Doodle\\Domain\\Repository\\PollRepository');
     $pollRepository->setDoodleClient($doodleClient);
     return $pollRepository;
 }
Example #15
0
    /**
     * CLI engine
     *
     * @param array $argv Command line arguments
     * @return string
     * @todo Define visibility
     */
    public function cli_main($argv)
    {
        // Force user to admin state and set workspace to "Live":
        $GLOBALS['BE_USER']->user['admin'] = 1;
        $GLOBALS['BE_USER']->setWorkspace(0);
        // Print help
        $analysisType = (string) $this->cli_args['_DEFAULT'][1];
        if (!$analysisType) {
            $this->cli_validateArgs();
            $this->cli_help();
            die;
        }
        // Analysis type:
        switch ((string) $analysisType) {
            case 'setBElock':
                if (@is_file(PATH_typo3conf . 'LOCK_BACKEND')) {
                    $this->cli_echo('A lockfile already exists. Overwriting it...
');
                }
                $lockFileContent = $this->cli_argValue('--redirect');
                \TYPO3\CMS\Core\Utility\GeneralUtility::writeFile(PATH_typo3conf . 'LOCK_BACKEND', $lockFileContent);
                $this->cli_echo('Wrote lock-file to \'' . PATH_typo3conf . 'LOCK_BACKEND\' with content \'' . $lockFileContent . '\'');
                break;
            case 'clearBElock':
                if (@is_file(PATH_typo3conf . 'LOCK_BACKEND')) {
                    unlink(PATH_typo3conf . 'LOCK_BACKEND');
                    if (@is_file(PATH_typo3conf . 'LOCK_BACKEND')) {
                        $this->cli_echo('ERROR: Could not remove lock file \'' . PATH_typo3conf . 'LOCK_BACKEND\'!!
', 1);
                    } else {
                        $this->cli_echo('Removed lock file \'' . PATH_typo3conf . 'LOCK_BACKEND\'
');
                    }
                } else {
                    $this->cli_echo('No lock file \'' . PATH_typo3conf . 'LOCK_BACKEND\' was found; hence no lock can be removed.\'
');
                }
                break;
            default:
                $this->cli_echo('Unknown toolkey, \'' . $analysisType . '\'');
        }
        $this->cli_echo(LF);
    }
Example #16
0
 /**
  * Creates .htaccess file inside the root directory
  *
  * @param string $htaccessFile Path of .htaccess file
  * @return void
  */
 public function createDefaultHtaccessFile()
 {
     $htaccessFile = GeneralUtility::getFileAbsFileName(".htaccess");
     if (file_exists($htaccessFile)) {
         /**
          * Add Flashmessage that there is already an .htaccess file and we are not going to override this.
          */
         $message = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Messaging\\FlashMessage', 'There is already an Apache .htaccess file in the root directory, please make sure that the url rewritings are set properly.<br>' . 'An example configuration is located at: <strong>typo3conf/ext/bootstrap_package/Configuration/Apache/.htaccess</strong>', 'Apache .htaccess file already exists', FlashMessage::NOTICE, TRUE);
         FlashMessageQueue::addMessage($message);
         return;
     }
     $htaccessContent = GeneralUtility::getUrl(ExtensionManagementUtility::extPath($this->extKey) . '/Configuration/Apache/.htaccess');
     GeneralUtility::writeFile($htaccessFile, $htaccessContent, TRUE);
     /**
      * Add Flashmessage that the example htaccess file was placed in the root directory
      */
     $message = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Messaging\\FlashMessage', 'For RealURL and optimization purposes an example .htaccess file was placed in your root directory. <br>' . ' Please check if the RewriteBase correctly set for your environment. ', 'Apache example .htaccess was placed in the root directory.', FlashMessage::OK, TRUE);
     FlashMessageQueue::addMessage($message);
 }
 /**
  * Creates custom-script.js file inside the fileadmin template directory
  *
  * @param string $jsFile Path of custom-script.js file
  * @return void
  */
 public function createCustomScriptJS($extension = NULL)
 {
     if ($extension == $this->extKey) {
         $jsFile = GeneralUtility::getFileAbsFileName("fileadmin/" . $this->extKey . "/Javascript/custom-script.js");
         if (file_exists($jsFile)) {
             /**
              * Add Flashmessage that there is already an custom-script.js file and we are not going to override this.
              */
             $message = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Messaging\\FlashMessage', 'There is already an custom-script.js file in the fileadmin ' . $this->extKey . ' directory.<br>' . 'An example custom-script.js is located at: <strong>typo3conf/ext/' . $this->extKey . '/Resources/Public/Javascript/custom-script.js</strong>', 'custom-script.js file already exists', FlashMessage::NOTICE, TRUE);
             FlashMessageQueue::addMessage($message);
             return;
         }
         $scriptContent = GeneralUtility::getUrl(ExtensionManagementUtility::extPath($this->extKey) . '/Resources/Public/Javascript/custom-script.js');
         GeneralUtility::mkdir_deep($_SERVER['DOCUMENT_ROOT'] . "/fileadmin/", $this->extKey . "/Javascript");
         GeneralUtility::writeFile($jsFile, $scriptContent, TRUE);
         /**
          * Add Flashmessage that the example custom-script.js file was placed in the fileadmin template directory
          */
         $message = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Messaging\\FlashMessage', 'You can use the custom-script.js file in the fileadmin ' . $this->extKey . ' directory for your custom scripts.', 'custom-script.js file was placed in your fileadmin ' . $this->extKey . ' directory.', FlashMessage::OK, TRUE);
         FlashMessageQueue::addMessage($message);
     }
 }
 /**
  * Unzip an extension.zip.
  *
  * @param string $file path to zip file
  * @param string $fileName file name
  * @param string $pathType path type (Local, Global, System)
  * @throws ExtensionManagerException
  * @return void
  */
 public function unzipExtensionFromFile($file, $fileName, $pathType = 'Local')
 {
     $extensionDir = $this->makeAndClearExtensionDir($fileName, $pathType);
     $zip = zip_open($file);
     if (is_resource($zip)) {
         while (($zipEntry = zip_read($zip)) !== false) {
             if (strpos(zip_entry_name($zipEntry), '/') !== false) {
                 $last = strrpos(zip_entry_name($zipEntry), '/');
                 $dir = substr(zip_entry_name($zipEntry), 0, $last);
                 $file = substr(zip_entry_name($zipEntry), strrpos(zip_entry_name($zipEntry), '/') + 1);
                 if (!is_dir($extensionDir . $dir)) {
                     GeneralUtility::mkdir_deep($extensionDir . $dir);
                 }
                 if (trim($file) !== '') {
                     $return = GeneralUtility::writeFile($extensionDir . $dir . '/' . $file, zip_entry_read($zipEntry, zip_entry_filesize($zipEntry)));
                     if ($return === false) {
                         throw new ExtensionManagerException('Could not write file ' . $this->getRelativePath($file), 1344691048);
                     }
                 }
             } else {
                 GeneralUtility::writeFile($extensionDir . zip_entry_name($zipEntry), zip_entry_read($zipEntry, zip_entry_filesize($zipEntry)));
             }
         }
     } else {
         throw new ExtensionManagerException('Unable to open zip file ' . $this->getRelativePath($file), 1344691049);
     }
 }
Example #19
0
 /**
  * Writes a file from the import memory having $fileID to file name $fileName which must be an absolute path inside PATH_site
  *
  * @param string $fileName Absolute filename inside PATH_site to write to
  * @param string $fileID File ID from import memory
  * @param boolean $bypassMountCheck Bypasses the checking against filemounts - only for RTE files!
  * @return boolean Returns TRUE if it went well. Notice that the content of the file is read again, and md5 from import memory is validated.
  * @todo Define visibility
  */
 public function writeFileVerify($fileName, $fileID, $bypassMountCheck = FALSE)
 {
     $fileProcObj = $this->getFileProcObj();
     if ($fileProcObj->actionPerms['newFile']) {
         // Just for security, check again. Should actually not be necessary.
         if ($fileProcObj->checkPathAgainstMounts($fileName) || $bypassMountCheck) {
             $fI = \TYPO3\CMS\Core\Utility\GeneralUtility::split_fileref($fileName);
             if ($fileProcObj->checkIfAllowed($fI['fileext'], $fI['path'], $fI['file']) || $this->allowPHPScripts && $GLOBALS['BE_USER']->isAdmin()) {
                 if (\TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName($fileName)) {
                     if ($this->dat['files'][$fileID]) {
                         \TYPO3\CMS\Core\Utility\GeneralUtility::writeFile($fileName, $this->dat['files'][$fileID]['content']);
                         $this->fileIDMap[$fileID] = $fileName;
                         if (md5(\TYPO3\CMS\Core\Utility\GeneralUtility::getUrl($fileName)) == $this->dat['files'][$fileID]['content_md5']) {
                             return TRUE;
                         } else {
                             $this->error('ERROR: File content "' . $fileName . '" was corrupted');
                         }
                     } else {
                         $this->error('ERROR: File ID "' . $fileID . '" could not be found');
                     }
                 } else {
                     $this->error('ERROR: Filename "' . $fileName . '" was not a valid relative file path!');
                 }
             } else {
                 $this->error('ERROR: Filename "' . $fileName . '" failed against extension check or deny-pattern!');
             }
         } else {
             $this->error('ERROR: Filename "' . $fileName . '" was not allowed in destination path!');
         }
     } else {
         $this->error('ERROR: You did not have sufficient permissions to write the file "' . $fileName . '"');
     }
 }
Example #20
0
 /**
  * Write a simple model class for a non aggregate root domain object
  *
  * @test
  */
 function writeRepositoryClassFromDomainObject()
 {
     $domainObject = $this->buildDomainObject('ModelCgt6', true, true);
     $classFileContent = $this->fileGenerator->generateDomainRepositoryCode($domainObject, false);
     $repositoryClassDir = 'Classes/Domain/Repository/';
     \TYPO3\CMS\Core\Utility\GeneralUtility::mkdir_deep($this->extension->getExtensionDir(), $repositoryClassDir);
     $absRepositoryClassDir = $this->extension->getExtensionDir() . $repositoryClassDir;
     $this->assertTrue(is_dir($absRepositoryClassDir), 'Directory ' . $absRepositoryClassDir . ' was not created');
     $repositoryClassPath = $absRepositoryClassDir . $domainObject->getName() . 'Repository.php';
     \TYPO3\CMS\Core\Utility\GeneralUtility::writeFile($repositoryClassPath, $classFileContent);
     $this->assertFileExists($repositoryClassPath, 'File was not generated: ' . $repositoryClassPath);
     $className = $domainObject->getFullyQualifiedDomainRepositoryClassName();
     if (!class_exists($className)) {
         include $repositoryClassPath;
     }
     $this->assertTrue(class_exists($className), 'Class was not generated:' . $className . 'in ' . $repositoryClassPath);
 }
Example #21
0
    /**
     * Search for commented INCLUDE_TYPOSCRIPT statements
     * and save the content between the BEGIN and the END line to the specified file
     *
     * @param string  $string Template content
     * @param int $cycle_counter Counter for detecting endless loops
     * @param array   $extractedFileNames
     * @param string  $parentFilenameOrPath
     *
     * @throws \RuntimeException
     * @throws \UnexpectedValueException
     * @return string Template content with uncommented include statements
     */
    public static function extractIncludes($string, $cycle_counter = 1, array $extractedFileNames = array(), $parentFilenameOrPath = '')
    {
        if ($cycle_counter > 10) {
            GeneralUtility::sysLog('It appears like TypoScript code is looping over itself. Check your templates for "&lt;INCLUDE_TYPOSCRIPT: ..." tags', 'Core', GeneralUtility::SYSLOG_SEVERITY_WARNING);
            return '
###
### ERROR: Recursion!
###
';
        }
        $expectedEndTag = '';
        $fileContent = array();
        $restContent = array();
        $fileName = NULL;
        $inIncludePart = FALSE;
        $lines = preg_split("/\r\n|\n|\r/", $string);
        $skipNextLineIfEmpty = FALSE;
        $openingCommentedIncludeStatement = NULL;
        $optionalProperties = '';
        foreach ($lines as $line) {
            // \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser::checkIncludeLines inserts
            // an additional empty line, remove this again
            if ($skipNextLineIfEmpty) {
                if (trim($line) === '') {
                    continue;
                }
                $skipNextLineIfEmpty = FALSE;
            }
            // Outside commented include statements
            if (!$inIncludePart) {
                // Search for beginning commented include statements
                if (preg_match('/###\\s*<INCLUDE_TYPOSCRIPT:\\s*source\\s*=\\s*"\\s*((?i)file|dir)\\s*:\\s*([^"]*)"(.*)>\\s*BEGIN/i', $line, $matches)) {
                    // Found a commented include statement
                    // Save this line in case there is no ending tag
                    $openingCommentedIncludeStatement = trim($line);
                    $openingCommentedIncludeStatement = preg_replace('/\\s*### Warning: .*###\\s*/', '', $openingCommentedIncludeStatement);
                    // type of match: FILE or DIR
                    $inIncludePart = strtoupper($matches[1]);
                    $fileName = $matches[2];
                    $optionalProperties = $matches[3];
                    $expectedEndTag = '### <INCLUDE_TYPOSCRIPT: source="' . $inIncludePart . ':' . $fileName . '"' . $optionalProperties . '> END';
                    // Strip all whitespace characters to make comparison safer
                    $expectedEndTag = strtolower(preg_replace('/\\s/', '', $expectedEndTag));
                } else {
                    // If this is not a beginning commented include statement this line goes into the rest content
                    $restContent[] = $line;
                }
                //if (is_array($matches)) GeneralUtility::devLog('matches', 'TypoScriptParser', 0, $matches);
            } else {
                // Inside commented include statements
                // Search for the matching ending commented include statement
                $strippedLine = preg_replace('/\\s/', '', $line);
                if (stripos($strippedLine, $expectedEndTag) !== FALSE) {
                    // Found the matching ending include statement
                    $fileContentString = implode(PHP_EOL, $fileContent);
                    // Write the content to the file
                    // Resolve a possible relative paths if a parent file is given
                    if ($parentFilenameOrPath !== '' && $fileName[0] === '.') {
                        $realFileName = PathUtility::getAbsolutePathOfRelativeReferencedFileOrPath($parentFilenameOrPath, $fileName);
                    } else {
                        $realFileName = $fileName;
                    }
                    $realFileName = GeneralUtility::getFileAbsFileName($realFileName);
                    if ($inIncludePart === 'FILE') {
                        // Some file checks
                        if (!GeneralUtility::verifyFilenameAgainstDenyPattern($realFileName)) {
                            throw new \UnexpectedValueException(sprintf('File "%s" was not included since it is not allowed due to fileDenyPattern.', $fileName), 1382651858);
                        }
                        if (empty($realFileName)) {
                            throw new \UnexpectedValueException(sprintf('"%s" is not a valid file location.', $fileName), 1294586441);
                        }
                        if (!is_writable($realFileName)) {
                            throw new \RuntimeException(sprintf('"%s" is not writable.', $fileName), 1294586442);
                        }
                        if (in_array($realFileName, $extractedFileNames)) {
                            throw new \RuntimeException(sprintf('Recursive/multiple inclusion of file "%s"', $realFileName), 1294586443);
                        }
                        $extractedFileNames[] = $realFileName;
                        // Recursive call to detected nested commented include statements
                        $fileContentString = self::extractIncludes($fileContentString, $cycle_counter + 1, $extractedFileNames, $realFileName);
                        // Write the content to the file
                        if (!GeneralUtility::writeFile($realFileName, $fileContentString)) {
                            throw new \RuntimeException(sprintf('Could not write file "%s"', $realFileName), 1294586444);
                        }
                        // Insert reference to the file in the rest content
                        $restContent[] = '<INCLUDE_TYPOSCRIPT: source="FILE:' . $fileName . '"' . $optionalProperties . '>';
                    } else {
                        // must be DIR
                        // Some file checks
                        if (empty($realFileName)) {
                            throw new \UnexpectedValueException(sprintf('"%s" is not a valid location.', $fileName), 1366493602);
                        }
                        if (!is_dir($realFileName)) {
                            throw new \RuntimeException(sprintf('"%s" is not a directory.', $fileName), 1366493603);
                        }
                        if (in_array($realFileName, $extractedFileNames)) {
                            throw new \RuntimeException(sprintf('Recursive/multiple inclusion of directory "%s"', $realFileName), 1366493604);
                        }
                        $extractedFileNames[] = $realFileName;
                        // Recursive call to detected nested commented include statements
                        self::extractIncludes($fileContentString, $cycle_counter + 1, $extractedFileNames, $realFileName);
                        // just drop content between tags since it should usually just contain individual files from that dir
                        // Insert reference to the dir in the rest content
                        $restContent[] = '<INCLUDE_TYPOSCRIPT: source="DIR:' . $fileName . '"' . $optionalProperties . '>';
                    }
                    // Reset variables (preparing for the next commented include statement)
                    $fileContent = array();
                    $fileName = NULL;
                    $inIncludePart = FALSE;
                    $openingCommentedIncludeStatement = NULL;
                    // \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser::checkIncludeLines inserts
                    // an additional empty line, remove this again
                    $skipNextLineIfEmpty = TRUE;
                } else {
                    // If this is not a ending commented include statement this line goes into the file content
                    $fileContent[] = $line;
                }
            }
        }
        // If we're still inside commented include statements copy the lines back to the rest content
        if ($inIncludePart) {
            $restContent[] = $openingCommentedIncludeStatement . ' ### Warning: Corresponding end line missing! ###';
            $restContent = array_merge($restContent, $fileContent);
        }
        $restContentString = implode(PHP_EOL, $restContent);
        return $restContentString;
    }
 /**
  * Unzips a document package.
  *
  * @param string $file path to zip file
  * @param string $path path to extract to
  * @throws \TYPO3\CMS\Documentation\Exception\Document
  * @return boolean
  */
 protected function unzipDocumentPackage($file, $path)
 {
     $zip = zip_open($file);
     if (is_resource($zip)) {
         $result = TRUE;
         if (!is_dir($path)) {
             GeneralUtility::mkdir_deep($path);
         }
         while (($zipEntry = zip_read($zip)) !== FALSE) {
             $zipEntryName = zip_entry_name($zipEntry);
             if (strpos($zipEntryName, '/') !== FALSE) {
                 $zipEntryPathSegments = explode('/', $zipEntryName);
                 $fileName = array_pop($zipEntryPathSegments);
                 // It is a folder, because the last segment is empty, let's create it
                 if (empty($fileName)) {
                     GeneralUtility::mkdir_deep($path, implode('/', $zipEntryPathSegments));
                 } else {
                     $absoluteTargetPath = GeneralUtility::getFileAbsFileName($path . implode('/', $zipEntryPathSegments) . '/' . $fileName);
                     if (strlen(trim($absoluteTargetPath)) > 0) {
                         $return = GeneralUtility::writeFile($absoluteTargetPath, zip_entry_read($zipEntry, zip_entry_filesize($zipEntry)));
                         if ($return === FALSE) {
                             throw new \TYPO3\CMS\Documentation\Exception\Document('Could not write file ' . $zipEntryName, 1374161546);
                         }
                     } else {
                         throw new \TYPO3\CMS\Documentation\Exception\Document('Could not write file ' . $zipEntryName, 1374161532);
                     }
                 }
             } else {
                 throw new \TYPO3\CMS\Documentation\Exception\Document('Extension directory missing in zip file!', 1374161519);
             }
         }
     } else {
         throw new \TYPO3\CMS\Documentation\Exception\Document('Unable to open zip file ' . $file, 1374161508);
     }
     return $result;
 }
Example #23
0
 /**
  * Writes string to a temporary file named after the md5-hash of the string
  *
  * @param string $str CSS styles / JavaScript to write to file.
  * @param string $ext Extension: "css" or "js
  * @return string <script> or <link> tag for the file.
  */
 public static function inline2TempFile($str, $ext)
 {
     // Create filename / tags:
     $script = '';
     switch ($ext) {
         case 'js':
             $script = 'typo3temp/javascript_' . substr(md5($str), 0, 10) . '.js';
             break;
         case 'css':
             $script = 'typo3temp/stylesheet_' . substr(md5($str), 0, 10) . '.css';
             break;
     }
     // Write file:
     if ($script) {
         if (!@is_file(PATH_site . $script)) {
             GeneralUtility::writeFile(PATH_site . $script, $str);
         }
     }
     return $script;
 }
 /**
  * @disabledtest
  */
 public function throwsParserExceptionIfTemplateSourceContainsErrors()
 {
     // @TODO: use vfs
     $validTemplatePathAndFilename = $this->getAbsoluteFixtureTemplatePathAndFilename(self::FIXTURE_TEMPLATE_ABSOLUTELYMINIMAL);
     $validTemplateSource = file_get_contents($validTemplatePathAndFilename);
     $invalidTemplateSource = $validTemplateSource . LF . LF . '</f:section>' . LF;
     $temporaryFilePathAndFilename = GeneralUtility::getFileAbsFileName('typo3temp/flux-temp-' . uniqid() . '.html');
     GeneralUtility::writeFile($temporaryFilePathAndFilename, $invalidTemplateSource);
     $view = $this->getPreparedViewWithTemplateFile($temporaryFilePathAndFilename);
     $this->setExpectedException('Tx_Fluid_Core_Parser_Exception');
     $this->callInaccessibleMethod($view, 'getStoredVariable', 'FluidTYPO3\\Flux\\ViewHelpers\\FormViewHelper', 'storage');
 }
Example #25
0
 /**
  * Generates the css files
  *
  * @return void
  */
 protected function generateCSS()
 {
     $cssData = '';
     if ($this->includeTimestampInCSS) {
         $timestamp = '?' . time();
     } else {
         $timestamp = '';
     }
     $spritePathForCSS = $this->resolveSpritePath();
     $markerArray = array('###NAMESPACE###' => $this->nameSpace, '###DEFAULTWIDTH###' => $this->defaultWidth, '###DEFAULTHEIGHT###' => $this->defaultHeight, '###SPRITENAME###' => '', '###SPRITEURL###' => $spritePathForCSS ? $spritePathForCSS . '/' : '');
     $markerArray['###SPRITEURL###'] .= $this->spriteName . '.png' . $timestamp;
     foreach ($this->spriteBases as $base) {
         $markerArray['###SPRITENAME###'] = $base;
         $cssData .= \TYPO3\CMS\Core\Html\HtmlParser::substituteMarkerArray($this->templateSprite, $markerArray);
     }
     foreach ($this->iconsData as $key => $data) {
         $temp = $data['iconNameParts'];
         array_shift($temp);
         $cssName = implode('-', $temp);
         $markerArrayIcons = array('###NAMESPACE###' => $this->nameSpace, '###ICONNAME###' => $cssName, '###LEFT###' => $data['left'], '###TOP###' => $data['top'], '###SIZE_INFO###' => '');
         if ($data['height'] != $this->defaultHeight) {
             $markerArrayIcons['###SIZE_INFO###'] .= TAB . 'height: ' . $data['height'] . 'px;' . LF;
         }
         if ($data['width'] != $this->defaultWidth) {
             $markerArrayIcons['###SIZE_INFO###'] .= TAB . 'width: ' . $data['width'] . 'px;' . LF;
         }
         $cssData .= \TYPO3\CMS\Core\Html\HtmlParser::substituteMarkerArray($this->templateIcon, $markerArrayIcons);
     }
     \TYPO3\CMS\Core\Utility\GeneralUtility::writeFile(PATH_site . $this->cssFolder . $this->spriteName . '.css', $cssData);
 }
 /**
  * Creates .htaccess file inside a new directory to access protect it
  *
  * @param string $htaccessFile Path of .htaccess file
  * @return void
  */
 protected function createHtaccessFile($htaccessFile)
 {
     // write .htaccess file to protect the log file
     if (!empty($GLOBALS['TYPO3_CONF_VARS']['SYS']['generateApacheHtaccess']) && !file_exists($htaccessFile)) {
         GeneralUtility::writeFile($htaccessFile, 'Deny From All');
     }
 }
Example #27
0
 /**
  * Writes a file from the import memory having $fileID to file name $fileName which must be an absolute path inside PATH_site
  *
  * @param string $fileName Absolute filename inside PATH_site to write to
  * @param string $fileID File ID from import memory
  * @param bool $bypassMountCheck Bypasses the checking against filemounts - only for RTE files!
  * @return bool Returns TRUE if it went well. Notice that the content of the file is read again, and md5 from import memory is validated.
  */
 public function writeFileVerify($fileName, $fileID, $bypassMountCheck = false)
 {
     $fileProcObj = $this->getFileProcObj();
     if (!$fileProcObj->actionPerms['addFile']) {
         $this->error('ERROR: You did not have sufficient permissions to write the file "' . $fileName . '"');
         return false;
     }
     // Just for security, check again. Should actually not be necessary.
     if (!$fileProcObj->checkPathAgainstMounts($fileName) && !$bypassMountCheck) {
         $this->error('ERROR: Filename "' . $fileName . '" was not allowed in destination path!');
         return false;
     }
     $fI = GeneralUtility::split_fileref($fileName);
     if (!$fileProcObj->checkIfAllowed($fI['fileext'], $fI['path'], $fI['file']) && (!$this->allowPHPScripts || !$this->getBackendUser()->isAdmin())) {
         $this->error('ERROR: Filename "' . $fileName . '" failed against extension check or deny-pattern!');
         return false;
     }
     if (!GeneralUtility::getFileAbsFileName($fileName)) {
         $this->error('ERROR: Filename "' . $fileName . '" was not a valid relative file path!');
         return false;
     }
     if (!$this->dat['files'][$fileID]) {
         $this->error('ERROR: File ID "' . $fileID . '" could not be found');
         return false;
     }
     GeneralUtility::writeFile($fileName, $this->dat['files'][$fileID]['content']);
     $this->fileIDMap[$fileID] = $fileName;
     if (md5(GeneralUtility::getUrl($fileName)) == $this->dat['files'][$fileID]['content_md5']) {
         return true;
     } else {
         $this->error('ERROR: File content "' . $fileName . '" was corrupted');
         return false;
     }
 }
 /**
  * @test
  * @dataProvider removeCurrentExtensionFromFileRemovesGivenExtensionDataProvider
  */
 public function removeCurrentExtensionFromFileRemovesGivenExtension($extensionToRemove, $extensions, $expectedExtensions)
 {
     $extensionCompatibilityTesterMock = $this->getAccessibleMock(\TYPO3\CMS\Install\Controller\Action\Ajax\ExtensionCompatibilityTester::class, array('dummy'), array());
     GeneralUtility::writeFile($extensionCompatibilityTesterMock->_get('protocolFile'), $extensions);
     $extensionCompatibilityTesterMock->_call('removeCurrentExtensionFromFile', $extensionToRemove);
     $fileContent = file_get_contents($extensionCompatibilityTesterMock->_get('protocolFile'));
     $this->assertEquals($expectedExtensions, $fileContent);
 }
Example #29
0
 /**
  * Write session data. See @session_set_save_handler
  *
  * @param string $id The session id
  * @param string $sessionData The data to be stored
  * @throws Exception
  * @return bool
  */
 public function write($id, $sessionData)
 {
     $sessionFile = $this->getSessionFile($id);
     $result = GeneralUtility::writeFile($sessionFile, $sessionData);
     if (!$result) {
         throw new Exception('Session file not writable. Please check permission on typo3temp/InstallToolSessions and its subdirectories.', 1424355157);
     }
     return $result;
 }
Example #30
0
 /**
  * Unzip an language.zip.
  *
  * @param string $file path to zip file
  * @param string $path path to extract to
  * @throws \TYPO3\CMS\Lang\Exception\Lang
  * @return boolean
  */
 protected function unzipTranslationFile($file, $path)
 {
     $zip = zip_open($file);
     if (is_resource($zip)) {
         $result = TRUE;
         if (!is_dir($path)) {
             \TYPO3\CMS\Core\Utility\GeneralUtility::mkdir_deep($path);
         }
         while (($zipEntry = zip_read($zip)) !== FALSE) {
             if (strpos(zip_entry_name($zipEntry), DIRECTORY_SEPARATOR) !== FALSE) {
                 $file = substr(zip_entry_name($zipEntry), strrpos(zip_entry_name($zipEntry), DIRECTORY_SEPARATOR) + 1);
                 if (strlen(trim($file)) > 0) {
                     $return = \TYPO3\CMS\Core\Utility\GeneralUtility::writeFile($path . '/' . $file, zip_entry_read($zipEntry, zip_entry_filesize($zipEntry)));
                     if ($return === FALSE) {
                         throw new \TYPO3\CMS\Lang\Exception\Lang('Could not write file ' . $file, 1345304560);
                     }
                 }
             } else {
                 $result = FALSE;
                 \TYPO3\CMS\Core\Utility\GeneralUtility::writeFile($path . zip_entry_name($zipEntry), zip_entry_read($zipEntry, zip_entry_filesize($zipEntry)));
             }
         }
     } else {
         throw new \TYPO3\CMS\Lang\Exception\Lang('Unable to open zip file ' . $file, 1345304561);
     }
     return $result;
 }