Example #1
0
 /**
  * Rendering the cObject, FILE
  *
  * @param array $conf Array of TypoScript properties
  * @return string Output
  */
 public function render($conf = [])
 {
     $theValue = '';
     $file = isset($conf['file.']) ? $this->cObj->stdWrap($conf['file'], $conf['file.']) : $conf['file'];
     $file = $this->getTypoScriptFrontendController()->tmpl->getFileName($file);
     if ($file !== null && file_exists($file)) {
         $fileInfo = GeneralUtility::split_fileref($file);
         $extension = $fileInfo['fileext'];
         if ($extension === 'jpg' || $extension === 'jpeg' || $extension === 'gif' || $extension === 'png') {
             $imgInfo = @getimagesize($file);
             $altParameters = trim($this->cObj->getAltParam($conf, false));
             $theValue = '<img src="' . htmlspecialchars($this->getTypoScriptFrontendController()->absRefPrefix . $file) . '" width="' . (int) $imgInfo[0] . '" height="' . (int) $imgInfo[1] . '"' . $this->cObj->getBorderAttr(' border="0"') . ' ' . $altParameters . ' />';
         } elseif (filesize($file) < 1024 * 1024) {
             $theValue = file_get_contents($file);
         }
     }
     $linkWrap = isset($conf['linkWrap.']) ? $this->cObj->stdWrap($conf['linkWrap'], $conf['linkWrap.']) : $conf['linkWrap'];
     if ($linkWrap) {
         $theValue = $this->cObj->linkWrap($theValue, $linkWrap);
     }
     $wrap = isset($conf['wrap.']) ? $this->cObj->stdWrap($conf['wrap'], $conf['wrap.']) : $conf['wrap'];
     if ($wrap) {
         $theValue = $this->cObj->wrap($theValue, $wrap);
     }
     if (isset($conf['stdWrap.'])) {
         $theValue = $this->cObj->stdWrap($theValue, $conf['stdWrap.']);
     }
     return $theValue;
 }
 /**
  * Manipulating the input array, $params, adding new selectorbox items.
  *
  * @param	array	$params array of select field options (reference)
  * @param	object	$pObj parent object (reference)
  * @return	void
  */
 function main(&$params, &$pObj)
 {
     // get the current page ID
     $thePageId = $params['row']['pid'];
     /** @var TemplateService $template */
     $template = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\TypoScript\\TemplateService');
     // do not log time-performance information
     $template->tt_track = 0;
     $template->init();
     /** @var PageRepository $sys_page */
     $sys_page = GeneralUtility::makeInstance('TYPO3\\CMS\\Frontend\\Page\\PageRepository');
     $rootLine = $sys_page->getRootLine($thePageId);
     // generate the constants/config + hierarchy info for the template.
     $template->runThroughTemplates($rootLine);
     $template->generateConfig();
     // get value for the path containing the template files
     $readPath = GeneralUtility::getFileAbsFileName($template->setup['plugin.']['tx_ttaddress_pi1.']['templatePath']);
     // if that direcotry is valid and is a directory then select files in it
     if (@is_dir($readPath)) {
         $template_files = GeneralUtility::getFilesInDir($readPath, 'tmpl,html,htm', 1, 1);
         /** @var HtmlParser $parseHTML */
         $parseHTML = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Html\\HtmlParser');
         foreach ($template_files as $htmlFilePath) {
             // reset vars
             $selectorBoxItem_title = '';
             $selectorBoxItem_icon = '';
             // read template content
             $content = GeneralUtility::getUrl($htmlFilePath);
             // ... and extract content of the title-tags
             $parts = $parseHTML->splitIntoBlock('title', $content);
             $titleTagContent = $parseHTML->removeFirstAndLastTag($parts[1]);
             // set the item label
             $selectorBoxItem_title = trim($titleTagContent . ' (' . basename($htmlFilePath) . ')');
             // try to look up an image icon for the template
             $fI = GeneralUtility::split_fileref($htmlFilePath);
             $testImageFilename = $readPath . $fI['filebody'] . '.gif';
             if (@is_file($testImageFilename)) {
                 $selectorBoxItem_icon = '../' . substr($testImageFilename, strlen(PATH_site));
             }
             // finally add the new item
             $params['items'][] = array($selectorBoxItem_title, basename($htmlFilePath), $selectorBoxItem_icon);
         }
     }
 }
Example #3
0
 /**
  * Uploads a new avatar to the server.
  * @author  Martin Helmich <*****@*****.**>
  * @author  Georg Ringer <*****@*****.**>
  * @version 2007-10-03
  * @param   string $content The plugin content
  * @return  string          The content
  */
 function uploadAvatar($content)
 {
     $avatarFile = $_FILES[$this->prefixId];
     if (isset($this->piVars['del_avatar'])) {
         $this->user->removeAvatar($this->conf['path_avatar']);
         $this->user->updateDatabase();
         return $content;
     }
     $fI = GeneralUtility::split_fileref($avatarFile['name']['file']);
     $fileExt = $fI['fileext'];
     if (!GeneralUtility::verifyFilenameAgainstDenyPattern($avatarFile['name']['file']) || !GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], $fileExt)) {
         return '';
     }
     if (isset($this->piVars['upload'])) {
         $uploaddir = $this->conf['path_avatar'];
         /*
          * Load the allowed file size for avatar image from the TCA and
          * check against the size of the uploaded image.
          */
         if (filesize($avatarFile['tmp_name']['file']) > $GLOBALS['TCA']['fe_users']['columns']['tx_mmforum_avatar']['config']['max_size'] * 1024) {
             return '';
         }
         $file = $this->user->getUid() . '_' . $GLOBALS['EXEC_TIME'] . '.' . $fileExt;
         $uploadfile = $uploaddir . $file;
         if (GeneralUtility::upload_copy_move($avatarFile['tmp_name']['file'], $uploadfile)) {
             $this->user->setAvatar($file);
             $this->user->updateDatabase();
         }
     }
     return $content;
 }
 /**
  * Renders the actual image
  *
  * @param \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer $contentObject
  * @param $file
  * @param array $fileConfiguration
  * @return array
  */
 public function getImgResource(\TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer $contentObject, $file, array $fileConfiguration)
 {
     if ($fileConfiguration['import.']) {
         $ifile = $contentObject->stdWrap('', $fileConfiguration['import.']);
         if ($ifile) {
             $file = $fileConfiguration['import'] . $ifile;
         }
     }
     if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($file)) {
         $file = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\ResourceFactory')->getFileObject($file);
     }
     if ($file instanceof \TYPO3\CMS\Core\Resource\FileInterface) {
         $theImage = $file->getForLocalProcessing(FALSE);
     } else {
         // clean ../ sections of the path and resolve to proper string.
         // This is necessary for the \TYPO3\CMS\Core\Resource\Service\FrontendContentAdapterService to work.
         $file = \TYPO3\CMS\Core\Utility\GeneralUtility::resolveBackPath($file);
         $theImage = $GLOBALS['TSFE']->tmpl->getFileName($file);
         if (!$theImage) {
             return array();
         }
     }
     $fileConfiguration = $this->processFileConfiguration($fileConfiguration, $contentObject);
     $maskArray = $fileConfiguration['m.'];
     $maskImages = array();
     // Must render mask images and include in hash-calculating - else we
     // cannot be sure the filename is unique for the setup!
     if (is_array($maskArray)) {
         $maskImages['m_mask'] = $this->getImgResource($contentObject, $maskArray['mask'], $maskArray['mask.']);
         $maskImages['m_bgImg'] = $this->getImgResource($contentObject, $maskArray['bgImg'], $maskArray['bgImg.']);
         $maskImages['m_bottomImg'] = $this->getImgResource($contentObject, $maskArray['bottomImg'], $maskArray['bottomImg.']);
         $maskImages['m_bottomImg_mask'] = $this->getImgResource($contentObject, $maskArray['bottomImg_mask'], $maskArray['bottomImg_mask.']);
     }
     // TODO use \TYPO3\CMS\Core\Resource\FileInterface here
     if ($file instanceof \TYPO3\CMS\Core\Resource\FileReference) {
         $hash = $file->getOriginalFile()->calculateChecksum();
     } else {
         $hash = \TYPO3\CMS\Core\Utility\GeneralUtility::shortMD5($theImage . serialize($fileConfiguration) . serialize($maskImages));
     }
     if (isset($GLOBALS['TSFE']->tmpl->fileCache[$hash])) {
         return $GLOBALS['TSFE']->tmpl->fileCache[$hash];
     }
     /** @var $gifCreator tslib_gifbuilder */
     $gifCreator = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('tslib_gifbuilder');
     $gifCreator->init();
     if ($GLOBALS['TSFE']->config['config']['meaningfulTempFilePrefix']) {
         $filename = basename($theImage);
         // Remove extension
         $filename = substr($filename, 0, strrpos($filename, '.'));
         $tempFilePrefixLength = intval($GLOBALS['TSFE']->config['config']['meaningfulTempFilePrefix']);
         if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['UTF8filesystem']) {
             /** @var $t3libCsInstance \TYPO3\CMS\Core\Charset\CharsetConverter */
             $t3libCsInstance = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Charset\\CharsetConverter');
             $filenamePrefix = $t3libCsInstance->substr('utf-8', $filename, 0, $tempFilePrefixLength);
         } else {
             // Strip everything non-ascii
             $filename = preg_replace('/[^A-Za-z0-9_-]/', '', trim($filename));
             $filenamePrefix = substr($filename, 0, $tempFilePrefixLength);
         }
         $gifCreator->filenamePrefix = $filenamePrefix . '_';
         unset($filename);
     }
     if ($fileConfiguration['sample']) {
         $gifCreator->scalecmd = '-sample';
         $GLOBALS['TT']->setTSlogMessage('Sample option: Images are scaled with -sample.');
     }
     if ($fileConfiguration['alternativeTempPath'] && \TYPO3\CMS\Core\Utility\GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['FE']['allowedTempPaths'], $fileConfiguration['alternativeTempPath'])) {
         $gifCreator->tempPath = $fileConfiguration['alternativeTempPath'];
         $GLOBALS['TT']->setTSlogMessage('Set alternativeTempPath: ' . $fileConfiguration['alternativeTempPath']);
     }
     if (!trim($fileConfiguration['ext'])) {
         $fileConfiguration['ext'] = 'web';
     }
     $options = array();
     if ($fileConfiguration['maxW']) {
         $options['maxW'] = $fileConfiguration['maxW'];
     }
     if ($fileConfiguration['maxH']) {
         $options['maxH'] = $fileConfiguration['maxH'];
     }
     if ($fileConfiguration['minW']) {
         $options['minW'] = $fileConfiguration['minW'];
     }
     if ($fileConfiguration['minH']) {
         $options['minH'] = $fileConfiguration['minH'];
     }
     if ($fileConfiguration['noScale']) {
         $options['noScale'] = $fileConfiguration['noScale'];
     }
     $fileInformation = \TYPO3\CMS\Core\Utility\GeneralUtility::split_fileref($theImage);
     $imgExt = strtolower($fileInformation['fileext']) == $gifCreator->gifExtension ? $gifCreator->gifExtension : 'jpg';
     // If no mask  is used or ImageMagick is disabled, processing is quite simple
     if (!is_array($maskArray) || !$GLOBALS['TYPO3_CONF_VARS']['GFX']['im']) {
         $fileConfiguration['params'] = $this->modifyImageMagickStripProfileParameters($fileConfiguration['params'], $fileConfiguration);
         $GLOBALS['TSFE']->tmpl->fileCache[$hash] = $gifCreator->imageMagickConvert($theImage, $fileConfiguration['ext'], $fileConfiguration['width'], $fileConfiguration['height'], $fileConfiguration['params'], $fileConfiguration['frame'], $options);
         if (($fileConfiguration['reduceColors'] || $imgExt === 'png' && !$gifCreator->png_truecolor) && is_file($GLOBALS['TSFE']->tmpl->fileCache[$hash][3])) {
             $reduced = $gifCreator->IMreduceColors($GLOBALS['TSFE']->tmpl->fileCache[$hash][3], \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($fileConfiguration['reduceColors'], 256, $gifCreator->truecolorColors, 256));
             if (is_file($reduced)) {
                 unlink($GLOBALS['TSFE']->tmpl->fileCache[$hash][3]);
                 rename($reduced, $GLOBALS['TSFE']->tmpl->fileCache[$hash][3]);
             }
         }
     } else {
         // Filename:
         $fileDestination = $gifCreator->tempPath . $hash . '.' . $imgExt;
         // Generate!
         if (!file_exists($fileDestination)) {
             $this->processMask($maskImages, $gifCreator, $theImage, $fileConfiguration, $options, $fileDestination);
         }
         // Finish off
         if (($fileConfiguration['reduceColors'] || $imgExt === 'png' && !$gifCreator->png_truecolor) && is_file($fileDestination)) {
             $reduced = $gifCreator->IMreduceColors($fileDestination, \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($fileConfiguration['reduceColors'], 256, $gifCreator->truecolorColors, 256));
             if (is_file($reduced)) {
                 unlink($fileDestination);
                 rename($reduced, $fileDestination);
             }
         }
         $GLOBALS['TSFE']->tmpl->fileCache[$hash] = $gifCreator->getImageDimensions($fileDestination);
     }
     $GLOBALS['TSFE']->tmpl->fileCache[$hash]['origFile'] = $theImage;
     // This is needed by tslib_gifbuilder, in order for the setup-array to create a unique filename hash.
     $GLOBALS['TSFE']->tmpl->fileCache[$hash]['origFile_mtime'] = @filemtime($theImage);
     $GLOBALS['TSFE']->tmpl->fileCache[$hash]['fileCacheHash'] = $hash;
     if ($file instanceof \TYPO3\CMS\Core\Resource\FileInterface && \TYPO3\CMS\Core\Utility\GeneralUtility::isAbsPath($GLOBALS['TSFE']->tmpl->fileCache[$hash][3])) {
         $GLOBALS['TSFE']->tmpl->fileCache[$hash][3] = $file->getPublicUrl();
     }
     $imageResource = $GLOBALS['TSFE']->tmpl->fileCache[$hash];
     return $imageResource;
 }
 protected function getUniqueName(\TYPO3\CMS\Core\Resource\Folder $folder, $theFile, $dontCheckForUnique = FALSE)
 {
     static $maxNumber = 99, $uniqueNamePrefix = '';
     // Fetches info about path, name, extention of $theFile
     $origFileInfo = \TYPO3\CMS\Core\Utility\GeneralUtility::split_fileref($theFile);
     // Adds prefix
     if ($uniqueNamePrefix) {
         $origFileInfo['file'] = $uniqueNamePrefix . $origFileInfo['file'];
         $origFileInfo['filebody'] = $uniqueNamePrefix . $origFileInfo['filebody'];
     }
     // Check if the file exists and if not - return the fileName...
     $fileInfo = $origFileInfo;
     // The destinations file
     $theDestFile = $fileInfo['file'];
     // If the file does NOT exist we return this fileName
     if (!$this->driver->fileExistsInFolder($theDestFile, $folder) || $dontCheckForUnique) {
         return $theDestFile;
     }
     // Well the fileName in its pure form existed. Now we try to append
     // numbers / unique-strings and see if we can find an available fileName
     // This removes _xx if appended to the file
     $theTempFileBody = preg_replace('/_[0-9][0-9]$/', '', $origFileInfo['filebody']);
     $theOrigExt = $origFileInfo['realFileext'] ? '.' . $origFileInfo['realFileext'] : '';
     for ($a = 1; $a <= $maxNumber + 1; $a++) {
         // First we try to append numbers
         if ($a <= $maxNumber) {
             $insert = '_' . sprintf('%02d', $a);
         } else {
             // TODO remove constant 6
             $insert = '_' . substr(md5(uniqId('')), 0, 6);
         }
         $theTestFile = $theTempFileBody . $insert . $theOrigExt;
         // The destinations file
         $theDestFile = $theTestFile;
         // If the file does NOT exist we return this fileName
         if (!$this->driver->fileExistsInFolder($theDestFile, $folder)) {
             return $theDestFile;
         }
     }
     throw new \RuntimeException('Last possible name "' . $theDestFile . '" is already taken.', 1325194291);
 }
 /**
  * Creates a list of links to files.
  * Implements the stdWrap property "filelink"
  *
  * @param string $theValue The filename to link to, possibly prefixed with $conf[path]
  * @param array $conf TypoScript parameters for the TypoScript function ->filelink
  * @return string The link to the file possibly with icons, thumbnails, size in bytes shown etc.
  * @access private
  * @see stdWrap()
  */
 public function filelink($theValue, $conf)
 {
     $conf['path'] = isset($conf['path.']) ? $this->stdWrap($conf['path'], $conf['path.']) : $conf['path'];
     $theFile = trim($conf['path']) . $theValue;
     if (!@is_file($theFile)) {
         return '';
     }
     $theFileEnc = str_replace('%2F', '/', rawurlencode($theFile));
     $title = $conf['title'];
     if (isset($conf['title.'])) {
         $title = $this->stdWrap($title, $conf['title.']);
     }
     $target = $conf['target'];
     if (isset($conf['target.'])) {
         $target = $this->stdWrap($target, $conf['target.']);
     }
     $tsfe = $this->getTypoScriptFrontendController();
     $typoLinkConf = array('parameter' => $theFileEnc, 'fileTarget' => $target, 'title' => $title, 'ATagParams' => $this->getATagParams($conf));
     if (isset($conf['typolinkConfiguration.'])) {
         $additionalTypoLinkConfiguration = $conf['typolinkConfiguration.'];
         // We only allow additional configuration. This is why the generated conf overwrites the additional conf.
         ArrayUtility::mergeRecursiveWithOverrule($additionalTypoLinkConfiguration, $typoLinkConf);
         $typoLinkConf = $additionalTypoLinkConfiguration;
     }
     $theLinkWrap = $this->typoLink('|', $typoLinkConf);
     $theSize = filesize($theFile);
     $fI = GeneralUtility::split_fileref($theFile);
     $icon = '';
     if ($conf['icon']) {
         $conf['icon.']['path'] = isset($conf['icon.']['path.']) ? $this->stdWrap($conf['icon.']['path'], $conf['icon.']['path.']) : $conf['icon.']['path'];
         $iconP = !empty($conf['icon.']['path']) ? $conf['icon.']['path'] : ExtensionManagementUtility::siteRelPath('frontend') . 'Resources/Public/Icons/FileIcons/';
         $conf['icon.']['ext'] = isset($conf['icon.']['ext.']) ? $this->stdWrap($conf['icon.']['ext'], $conf['icon.']['ext.']) : $conf['icon.']['ext'];
         $iconExt = !empty($conf['icon.']['ext']) ? '.' . $conf['icon.']['ext'] : '.gif';
         $icon = @is_file($iconP . $fI['fileext'] . $iconExt) ? $iconP . $fI['fileext'] . $iconExt : $iconP . 'default' . $iconExt;
         // Checking for images: If image, then return link to thumbnail.
         $IEList = isset($conf['icon_image_ext_list.']) ? $this->stdWrap($conf['icon_image_ext_list'], $conf['icon_image_ext_list.']) : $conf['icon_image_ext_list'];
         $image_ext_list = str_replace(' ', '', strtolower($IEList));
         if ($fI['fileext'] && GeneralUtility::inList($image_ext_list, $fI['fileext'])) {
             if ($conf['iconCObject']) {
                 $icon = $this->cObjGetSingle($conf['iconCObject'], $conf['iconCObject.'], 'iconCObject');
             } else {
                 $notFoundThumb = ExtensionManagementUtility::extPath('core') . 'Resources/Public/Images/NotFound.gif';
                 $sizeParts = array(64, 64);
                 if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['thumbnails']) {
                     // using the File Abstraction Layer to generate a preview image
                     try {
                         /** @var File $fileObject */
                         $fileObject = ResourceFactory::getInstance()->retrieveFileOrFolderObject($theFile);
                         if ($fileObject->isMissing()) {
                             $icon = $notFoundThumb;
                         } else {
                             $fileExtension = $fileObject->getExtension();
                             if ($fileExtension === 'ttf' || GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], $fileExtension)) {
                                 if ($conf['icon_thumbSize'] || $conf['icon_thumbSize.']) {
                                     $thumbSize = isset($conf['icon_thumbSize.']) ? $this->stdWrap($conf['icon_thumbSize'], $conf['icon_thumbSize.']) : $conf['icon_thumbSize'];
                                     $sizeParts = explode('x', $thumbSize);
                                 }
                                 $icon = $fileObject->process(ProcessedFile::CONTEXT_IMAGEPREVIEW, array('width' => $sizeParts[0], 'height' => $sizeParts[1]))->getPublicUrl(true);
                             }
                         }
                     } catch (ResourceDoesNotExistException $exception) {
                         $icon = $notFoundThumb;
                     }
                 } else {
                     $icon = $notFoundThumb;
                 }
                 $urlPrefix = '';
                 if (parse_url($icon, PHP_URL_HOST) === null) {
                     $urlPrefix = $tsfe->absRefPrefix;
                 }
                 $icon = '<img src="' . htmlspecialchars($urlPrefix . $icon) . '"' . 'width="' . (int) $sizeParts[0] . '" height="' . (int) $sizeParts[1] . '" ' . $this->getBorderAttr(' border="0"') . '' . $this->getAltParam($conf) . ' />';
             }
         } else {
             $conf['icon.']['widthAttribute'] = isset($conf['icon.']['widthAttribute.']) ? $this->stdWrap($conf['icon.']['widthAttribute'], $conf['icon.']['widthAttribute.']) : $conf['icon.']['widthAttribute'];
             $iconWidth = !empty($conf['icon.']['widthAttribute']) ? $conf['icon.']['widthAttribute'] : 18;
             $conf['icon.']['heightAttribute'] = isset($conf['icon.']['heightAttribute.']) ? $this->stdWrap($conf['icon.']['heightAttribute'], $conf['icon.']['heightAttribute.']) : $conf['icon.']['heightAttribute'];
             $iconHeight = !empty($conf['icon.']['heightAttribute']) ? (int) $conf['icon.']['heightAttribute'] : 16;
             $icon = '<img src="' . htmlspecialchars($tsfe->absRefPrefix . $icon) . '" width="' . (int) $iconWidth . '" height="' . (int) $iconHeight . '"' . $this->getBorderAttr(' border="0"') . $this->getAltParam($conf) . ' />';
         }
         if ($conf['icon_link'] && !$conf['combinedLink']) {
             $icon = $this->wrap($icon, $theLinkWrap);
         }
         $icon = isset($conf['icon.']) ? $this->stdWrap($icon, $conf['icon.']) : $icon;
     }
     $size = '';
     if ($conf['size']) {
         $size = isset($conf['size.']) ? $this->stdWrap($theSize, $conf['size.']) : $theSize;
     }
     // Wrapping file label
     if ($conf['removePrependedNumbers']) {
         $theValue = preg_replace('/_[0-9][0-9](\\.[[:alnum:]]*)$/', '\\1', $theValue);
     }
     if (isset($conf['labelStdWrap.'])) {
         $theValue = $this->stdWrap($theValue, $conf['labelStdWrap.']);
     }
     // Wrapping file
     $wrap = isset($conf['wrap.']) ? $this->stdWrap($conf['wrap'], $conf['wrap.']) : $conf['wrap'];
     if ($conf['combinedLink']) {
         $theValue = $icon . $theValue;
         if ($conf['ATagBeforeWrap']) {
             $theValue = $this->wrap($this->wrap($theValue, $wrap), $theLinkWrap);
         } else {
             $theValue = $this->wrap($this->wrap($theValue, $theLinkWrap), $wrap);
         }
         $file = isset($conf['file.']) ? $this->stdWrap($theValue, $conf['file.']) : $theValue;
         // output
         $output = $file . $size;
     } else {
         if ($conf['ATagBeforeWrap']) {
             $theValue = $this->wrap($this->wrap($theValue, $wrap), $theLinkWrap);
         } else {
             $theValue = $this->wrap($this->wrap($theValue, $theLinkWrap), $wrap);
         }
         $file = isset($conf['file.']) ? $this->stdWrap($theValue, $conf['file.']) : $theValue;
         // output
         $output = $icon . $file . $size;
     }
     if (isset($conf['stdWrap.'])) {
         $output = $this->stdWrap($output, $conf['stdWrap.']);
     }
     return $output;
 }
 /**
  * Returns the reference to a 'resource' in TypoScript.
  * This could be from the filesystem if '/' is found in the value $fileFromSetup, else from the resource-list
  *
  * @param string $fileFromSetup TypoScript "resource" data type value.
  * @return string Resulting filename, if any.
  * @todo Define visibility
  */
 public function getFileName($fileFromSetup)
 {
     $file = trim($fileFromSetup);
     if (!$file) {
         return;
     } elseif (strstr($file, '../')) {
         if ($this->tt_track) {
             $GLOBALS['TT']->setTSlogMessage('File path "' . $file . '" contained illegal string "../"!', 3);
         }
         return;
     }
     // Cache
     $hash = md5($file);
     if (isset($this->fileCache[$hash])) {
         return $this->fileCache[$hash];
     }
     if (substr($file, 0, 4) === 'EXT:') {
         $newFile = '';
         list($extKey, $script) = explode('/', substr($file, 4), 2);
         if ($extKey && \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded($extKey)) {
             $extPath = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath($extKey);
             $newFile = \TYPO3\CMS\Core\Utility\PathUtility::stripPathSitePrefix($extPath) . $script;
         }
         if (!@file_exists(PATH_site . $newFile)) {
             if ($this->tt_track) {
                 $GLOBALS['TT']->setTSlogMessage('Extension media file "' . $newFile . '" was not found!', 3);
             }
             return;
         } else {
             $file = $newFile;
         }
     }
     // if this is an URL, it can be returned directly
     $urlScheme = parse_url($file, PHP_URL_SCHEME);
     if ($urlScheme === 'https' || $urlScheme === 'http' || is_file(PATH_site . $file)) {
         return $file;
     }
     // Find
     if (strpos($file, '/') !== FALSE) {
         // If the file is in the media/ folder but it doesn't exist,
         // it is assumed that it's in the tslib folder
         if (GeneralUtility::isFirstPartOfStr($file, 'media/') && !file_exists($this->getFileName_backPath . $file)) {
             $file = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::siteRelPath('cms') . 'tslib/' . $file;
         }
         if (file_exists($this->getFileName_backPath . $file)) {
             $outFile = $file;
             $fileInfo = GeneralUtility::split_fileref($outFile);
             $OK = 0;
             foreach ($this->allowedPaths as $val) {
                 if (substr($fileInfo['path'], 0, strlen($val)) == $val) {
                     $OK = 1;
                     break;
                 }
             }
             if ($OK) {
                 $this->fileCache[$hash] = $outFile;
                 return $outFile;
             } elseif ($this->tt_track) {
                 $GLOBALS['TT']->setTSlogMessage('"' . $file . '" was not located in the allowed paths: (' . implode(',', $this->allowedPaths) . ')', 3);
             }
         } elseif ($this->tt_track) {
             $GLOBALS['TT']->setTSlogMessage('"' . $this->getFileName_backPath . $file . '" is not a file (non-uploads/.. resource, did not exist).', 3);
         }
     }
 }
 /**
  * Reduce colors in image using IM and create a palette based image if possible (<=256 colors)
  *
  * @param string $file Image file to reduce
  * @param int $cols Number of colors to reduce the image to.
  * @return string Reduced file
  */
 public function IMreduceColors($file, $cols)
 {
     $fI = GeneralUtility::split_fileref($file);
     $ext = strtolower($fI['fileext']);
     $result = $this->randomName() . '.' . $ext;
     $reduce = MathUtility::forceIntegerInRange($cols, 0, $ext == 'gif' ? 256 : $this->truecolorColors, 0);
     if ($reduce > 0) {
         $params = ' -colors ' . $reduce;
         if ($reduce <= 256) {
             $params .= ' -type Palette';
         }
         $prefix = $ext === 'png' && $reduce <= 256 ? 'png8:' : '';
         $this->imageMagickExec($file, $prefix . $result, $params);
         if ($result) {
             return $result;
         }
     }
     return '';
 }
Example #9
0
 /**
  * Handling files for group/select function
  *
  * @param array $valueArray Array of incoming file references. Keys are numeric, values are files (basically, this is the exploded list of incoming files)
  * @param array $tcaFieldConf Configuration array from TCA of the field
  * @param string $curValue Current value of the field
  * @param array $uploadedFileArray Array of uploaded files, if any
  * @param string $status 'update' or 'new' flag
  * @param string $table tablename of record
  * @param int $id UID of record
  * @param string $recFID Field identifier [table:uid:field] for flexforms
  * @return array Modified value array
  *
  * @throws \RuntimeException
  * @see checkValue_group_select()
  */
 public function checkValue_group_select_file($valueArray, $tcaFieldConf, $curValue, $uploadedFileArray, $status, $table, $id, $recFID)
 {
     // If file handling should NOT be bypassed, do processing:
     if (!$this->bypassFileHandling) {
         // If any files are uploaded, add them to value array
         // Numeric index means that there are multiple files
         if (isset($uploadedFileArray[0])) {
             $uploadedFiles = $uploadedFileArray;
         } else {
             // There is only one file
             $uploadedFiles = array($uploadedFileArray);
         }
         foreach ($uploadedFiles as $uploadedFileArray) {
             if (!empty($uploadedFileArray['name']) && $uploadedFileArray['tmp_name'] !== 'none') {
                 $valueArray[] = $uploadedFileArray['tmp_name'];
                 $this->alternativeFileName[$uploadedFileArray['tmp_name']] = $uploadedFileArray['name'];
             }
         }
         // Creating fileFunc object.
         if (!$this->fileFunc) {
             $this->fileFunc = GeneralUtility::makeInstance(BasicFileUtility::class);
             $this->include_filefunctions = 1;
         }
         // Setting permitted extensions.
         $all_files = array();
         $all_files['webspace']['allow'] = $tcaFieldConf['allowed'];
         $all_files['webspace']['deny'] = $tcaFieldConf['disallowed'] ?: '*';
         $all_files['ftpspace'] = $all_files['webspace'];
         $this->fileFunc->init('', $all_files);
     }
     // If there is an upload folder defined:
     if ($tcaFieldConf['uploadfolder'] && $tcaFieldConf['internal_type'] == 'file') {
         $currentFilesForHistory = null;
         // If filehandling should NOT be bypassed, do processing:
         if (!$this->bypassFileHandling) {
             // For logging..
             $propArr = $this->getRecordProperties($table, $id);
             // Get destrination path:
             $dest = $this->destPathFromUploadFolder($tcaFieldConf['uploadfolder']);
             // If we are updating:
             if ($status == 'update') {
                 // Traverse the input values and convert to absolute filenames in case the update happens to an autoVersionized record.
                 // Background: This is a horrible workaround! The problem is that when a record is auto-versionized the files of the record get copied and therefore get new names which is overridden with the names from the original record in the incoming data meaning both lost files and double-references!
                 // The only solution I could come up with (except removing support for managing files when autoversioning) was to convert all relative files to absolute names so they are copied again (and existing files deleted). This should keep references intact but means that some files are copied, then deleted after being copied _again_.
                 // Actually, the same problem applies to database references in case auto-versioning would include sub-records since in such a case references are remapped - and they would be overridden due to the same principle then.
                 // Illustration of the problem comes here:
                 // We have a record 123 with a file logo.gif. We open and edit the files header in a workspace. So a new version is automatically made.
                 // The versions uid is 456 and the file is copied to "logo_01.gif". But the form data that we sent was based on uid 123 and hence contains the filename "logo.gif" from the original.
                 // The file management code below will do two things: First it will blindly accept "logo.gif" as a file attached to the record (thus creating a double reference) and secondly it will find that "logo_01.gif" was not in the incoming filelist and therefore should be deleted.
                 // If we prefix the incoming file "logo.gif" with its absolute path it will be seen as a new file added. Thus it will be copied to "logo_02.gif". "logo_01.gif" will still be deleted but since the files are the same the difference is zero - only more processing and file copying for no reason. But it will work.
                 if ($this->autoVersioningUpdate === true) {
                     foreach ($valueArray as $key => $theFile) {
                         // If it is an already attached file...
                         if ($theFile === basename($theFile)) {
                             $valueArray[$key] = PATH_site . $tcaFieldConf['uploadfolder'] . '/' . $theFile;
                         }
                     }
                 }
                 // Finding the CURRENT files listed, either from MM or from the current record.
                 $theFileValues = array();
                 // If MM relations for the files also!
                 if ($tcaFieldConf['MM']) {
                     $dbAnalysis = $this->createRelationHandlerInstance();
                     /** @var $dbAnalysis RelationHandler */
                     $dbAnalysis->start('', 'files', $tcaFieldConf['MM'], $id);
                     foreach ($dbAnalysis->itemArray as $item) {
                         if ($item['id']) {
                             $theFileValues[] = $item['id'];
                         }
                     }
                 } else {
                     $theFileValues = GeneralUtility::trimExplode(',', $curValue, true);
                 }
                 $currentFilesForHistory = implode(',', $theFileValues);
                 // DELETE files: If existing files were found, traverse those and register files for deletion which has been removed:
                 if (!empty($theFileValues)) {
                     // Traverse the input values and for all input values which match an EXISTING value, remove the existing from $theFileValues array (this will result in an array of all the existing files which should be deleted!)
                     foreach ($valueArray as $key => $theFile) {
                         if ($theFile && !strstr(GeneralUtility::fixWindowsFilePath($theFile), '/')) {
                             $theFileValues = ArrayUtility::removeArrayEntryByValue($theFileValues, $theFile);
                         }
                     }
                     // This array contains the filenames in the uploadfolder that should be deleted:
                     foreach ($theFileValues as $key => $theFile) {
                         $theFile = trim($theFile);
                         if (@is_file($dest . '/' . $theFile)) {
                             $this->removeFilesStore[] = $dest . '/' . $theFile;
                         } elseif ($this->enableLogging && $theFile) {
                             $this->log($table, $id, 5, 0, 1, 'Could not delete file \'%s\' (does not exist). (%s)', 10, array($dest . '/' . $theFile, $recFID), $propArr['event_pid']);
                         }
                     }
                 }
             }
             // Traverse the submitted values:
             foreach ($valueArray as $key => $theFile) {
                 // Init:
                 $maxSize = (int) $tcaFieldConf['max_size'];
                 // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!
                 $theDestFile = '';
                 // a FAL file was added, now resolve the file object and get the absolute path
                 // @todo in future versions this needs to be modified to handle FAL objects natively
                 if (!empty($theFile) && MathUtility::canBeInterpretedAsInteger($theFile)) {
                     $fileObject = ResourceFactory::getInstance()->getFileObject($theFile);
                     $theFile = $fileObject->getForLocalProcessing(false);
                 }
                 // NEW FILES? If the value contains '/' it indicates, that the file
                 // is new and should be added to the uploadsdir (whether its absolute or relative does not matter here)
                 if (strstr(GeneralUtility::fixWindowsFilePath($theFile), '/')) {
                     // Check various things before copying file:
                     // File and destination must exist
                     if (@is_dir($dest) && (@is_file($theFile) || @is_uploaded_file($theFile))) {
                         // Finding size.
                         if (is_uploaded_file($theFile) && $theFile == $uploadedFileArray['tmp_name']) {
                             $fileSize = $uploadedFileArray['size'];
                         } else {
                             $fileSize = filesize($theFile);
                         }
                         // Check file size:
                         if (!$maxSize || $fileSize <= $maxSize * 1024) {
                             // Prepare filename:
                             $theEndFileName = isset($this->alternativeFileName[$theFile]) ? $this->alternativeFileName[$theFile] : $theFile;
                             $fI = GeneralUtility::split_fileref($theEndFileName);
                             // Check for allowed extension:
                             if ($this->fileFunc->checkIfAllowed($fI['fileext'], $dest, $theEndFileName)) {
                                 $theDestFile = $this->fileFunc->getUniqueName($this->fileFunc->cleanFileName($fI['file']), $dest);
                                 // If we have a unique destination filename, then write the file:
                                 if ($theDestFile) {
                                     GeneralUtility::upload_copy_move($theFile, $theDestFile);
                                     // Hook for post-processing the upload action
                                     if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processUpload'])) {
                                         foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processUpload'] as $classRef) {
                                             $hookObject = GeneralUtility::getUserObj($classRef);
                                             if (!$hookObject instanceof DataHandlerProcessUploadHookInterface) {
                                                 throw new \UnexpectedValueException('$hookObject must implement interface TYPO3\\CMS\\Core\\DataHandling\\DataHandlerProcessUploadHookInterface', 1279962349);
                                             }
                                             $hookObject->processUpload_postProcessAction($theDestFile, $this);
                                         }
                                     }
                                     $this->copiedFileMap[$theFile] = $theDestFile;
                                     clearstatcache();
                                     if ($this->enableLogging && !@is_file($theDestFile)) {
                                         $this->log($table, $id, 5, 0, 1, 'Copying file \'%s\' failed!: The destination path (%s) may be write protected. Please make it write enabled!. (%s)', 16, array($theFile, dirname($theDestFile), $recFID), $propArr['event_pid']);
                                     }
                                 } elseif ($this->enableLogging) {
                                     $this->log($table, $id, 5, 0, 1, 'Copying file \'%s\' failed!: No destination file (%s) possible!. (%s)', 11, array($theFile, $theDestFile, $recFID), $propArr['event_pid']);
                                 }
                             } elseif ($this->enableLogging) {
                                 $this->log($table, $id, 5, 0, 1, 'File extension \'%s\' not allowed. (%s)', 12, array($fI['fileext'], $recFID), $propArr['event_pid']);
                             }
                         } elseif ($this->enableLogging) {
                             $this->log($table, $id, 5, 0, 1, 'Filesize (%s) of file \'%s\' exceeds limit (%s). (%s)', 13, array(GeneralUtility::formatSize($fileSize), $theFile, GeneralUtility::formatSize($maxSize * 1024), $recFID), $propArr['event_pid']);
                         }
                     } elseif ($this->enableLogging) {
                         $this->log($table, $id, 5, 0, 1, 'The destination (%s) or the source file (%s) does not exist. (%s)', 14, array($dest, $theFile, $recFID), $propArr['event_pid']);
                     }
                     // If the destination file was created, we will set the new filename in the value array, otherwise unset the entry in the value array!
                     if (@is_file($theDestFile)) {
                         $info = GeneralUtility::split_fileref($theDestFile);
                         // The value is set to the new filename
                         $valueArray[$key] = $info['file'];
                     } else {
                         // The value is set to the new filename
                         unset($valueArray[$key]);
                     }
                 }
             }
         }
         // If MM relations for the files, we will set the relations as MM records and change the valuearray to contain a single entry with a count of the number of files!
         if ($tcaFieldConf['MM']) {
             /** @var $dbAnalysis RelationHandler */
             $dbAnalysis = $this->createRelationHandlerInstance();
             // Dummy
             $dbAnalysis->tableArray['files'] = array();
             foreach ($valueArray as $key => $theFile) {
                 // Explode files
                 $dbAnalysis->itemArray[]['id'] = $theFile;
             }
             if ($status == 'update') {
                 $dbAnalysis->writeMM($tcaFieldConf['MM'], $id, 0);
                 $newFiles = implode(',', $dbAnalysis->getValueArray());
                 list(, , $recFieldName) = explode(':', $recFID);
                 if ($currentFilesForHistory != $newFiles) {
                     $this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$recFieldName] = $currentFilesForHistory;
                     $this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$recFieldName] = $newFiles;
                 } else {
                     $this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$recFieldName] = '';
                     $this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$recFieldName] = '';
                 }
             } else {
                 $this->dbAnalysisStore[] = array($dbAnalysis, $tcaFieldConf['MM'], $id, 0);
             }
             $valueArray = $dbAnalysis->countItems();
         }
     } else {
         if (!empty($valueArray)) {
             // If filehandling should NOT be bypassed, do processing:
             if (!$this->bypassFileHandling) {
                 // For logging..
                 $propArr = $this->getRecordProperties($table, $id);
                 foreach ($valueArray as &$theFile) {
                     // FAL handling: it's a UID, thus it is resolved to the absolute path
                     if (!empty($theFile) && MathUtility::canBeInterpretedAsInteger($theFile)) {
                         $fileObject = ResourceFactory::getInstance()->getFileObject($theFile);
                         $theFile = $fileObject->getForLocalProcessing(false);
                     }
                     if ($this->alternativeFilePath[$theFile]) {
                         // If alternative File Path is set for the file, then it was an import
                         // don't import the file if it already exists
                         if (@is_file(PATH_site . $this->alternativeFilePath[$theFile])) {
                             $theFile = PATH_site . $this->alternativeFilePath[$theFile];
                         } elseif (@is_file($theFile)) {
                             $dest = dirname(PATH_site . $this->alternativeFilePath[$theFile]);
                             if (!@is_dir($dest)) {
                                 GeneralUtility::mkdir_deep(PATH_site, dirname($this->alternativeFilePath[$theFile]) . '/');
                             }
                             // Init:
                             $maxSize = (int) $tcaFieldConf['max_size'];
                             // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!
                             $theDestFile = '';
                             $fileSize = filesize($theFile);
                             // Check file size:
                             if (!$maxSize || $fileSize <= $maxSize * 1024) {
                                 // Prepare filename:
                                 $theEndFileName = isset($this->alternativeFileName[$theFile]) ? $this->alternativeFileName[$theFile] : $theFile;
                                 $fI = GeneralUtility::split_fileref($theEndFileName);
                                 // Check for allowed extension:
                                 if ($this->fileFunc->checkIfAllowed($fI['fileext'], $dest, $theEndFileName)) {
                                     $theDestFile = PATH_site . $this->alternativeFilePath[$theFile];
                                     // Write the file:
                                     if ($theDestFile) {
                                         GeneralUtility::upload_copy_move($theFile, $theDestFile);
                                         $this->copiedFileMap[$theFile] = $theDestFile;
                                         clearstatcache();
                                         if ($this->enableLogging && !@is_file($theDestFile)) {
                                             $this->log($table, $id, 5, 0, 1, 'Copying file \'%s\' failed!: The destination path (%s) may be write protected. Please make it write enabled!. (%s)', 16, array($theFile, dirname($theDestFile), $recFID), $propArr['event_pid']);
                                         }
                                     } elseif ($this->enableLogging) {
                                         $this->log($table, $id, 5, 0, 1, 'Copying file \'%s\' failed!: No destination file (%s) possible!. (%s)', 11, array($theFile, $theDestFile, $recFID), $propArr['event_pid']);
                                     }
                                 } elseif ($this->enableLogging) {
                                     $this->log($table, $id, 5, 0, 1, 'File extension \'%s\' not allowed. (%s)', 12, array($fI['fileext'], $recFID), $propArr['event_pid']);
                                 }
                             } elseif ($this->enableLogging) {
                                 $this->log($table, $id, 5, 0, 1, 'Filesize (%s) of file \'%s\' exceeds limit (%s). (%s)', 13, array(GeneralUtility::formatSize($fileSize), $theFile, GeneralUtility::formatSize($maxSize * 1024), $recFID), $propArr['event_pid']);
                             }
                             // If the destination file was created, we will set the new filename in the value array, otherwise unset the entry in the value array!
                             if (@is_file($theDestFile)) {
                                 // The value is set to the new filename
                                 $theFile = $theDestFile;
                             } else {
                                 // The value is set to the new filename
                                 unset($theFile);
                             }
                         }
                     }
                     if (!empty($theFile)) {
                         $theFile = GeneralUtility::fixWindowsFilePath($theFile);
                         if (GeneralUtility::isFirstPartOfStr($theFile, PATH_site)) {
                             $theFile = PathUtility::stripPathSitePrefix($theFile);
                         }
                     }
                 }
                 unset($theFile);
             }
         }
     }
     return $valueArray;
 }
 /**
  * The main processing method if this class
  *
  * @return string Information of the template status or the taken actions as HTML string
  * @todo Define visibility
  */
 public function main()
 {
     global $BACK_PATH;
     global $tmpl, $tplRow, $theConstants;
     $this->pObj->MOD_MENU['includeTypoScriptFileContent'] = TRUE;
     $edit = $this->pObj->edit;
     $e = $this->pObj->e;
     \TYPO3\CMS\Core\Utility\GeneralUtility::loadTCA('sys_template');
     // Checking for more than one template an if, set a menu...
     $manyTemplatesMenu = $this->pObj->templateMenu();
     $template_uid = 0;
     if ($manyTemplatesMenu) {
         $template_uid = $this->pObj->MOD_SETTINGS['templatesOnPage'];
     }
     // Initialize
     $existTemplate = $this->initialize_editor($this->pObj->id, $template_uid);
     if ($existTemplate) {
         $saveId = $tplRow['_ORIG_uid'] ? $tplRow['_ORIG_uid'] : $tplRow['uid'];
     }
     // Create extension template
     $newId = $this->pObj->createTemplate($this->pObj->id, $saveId);
     if ($newId) {
         // Switch to new template
         $urlParameters = array('id' => $this->pObj->id, 'SET[templatesOnPage]' => $newId);
         $aHref = \TYPO3\CMS\Backend\Utility\BackendUtility::getModuleUrl('web_ts', $urlParameters);
         \TYPO3\CMS\Core\Utility\HttpUtility::redirect($aHref);
     }
     if ($existTemplate) {
         // Update template ?
         $POST = \TYPO3\CMS\Core\Utility\GeneralUtility::_POST();
         if ($POST['submit'] || \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($POST['submit_x']) && \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($POST['submit_y']) || $POST['saveclose'] || \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($POST['saveclose_x']) && \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($POST['saveclose_y'])) {
             // Set the data to be saved
             $recData = array();
             $alternativeFileName = array();
             $tmp_upload_name = '';
             // Set this to blank
             $tmp_newresource_name = '';
             if (is_array($POST['data'])) {
                 foreach ($POST['data'] as $field => $val) {
                     switch ($field) {
                         case 'constants':
                         case 'config':
                         case 'title':
                         case 'sitetitle':
                         case 'description':
                             $recData['sys_template'][$saveId][$field] = $val;
                             break;
                     }
                 }
             }
             if (count($recData)) {
                 $recData['sys_template'][$saveId] = $this->processTemplateRowBeforeSaving($recData['sys_template'][$saveId]);
                 // Create new  tce-object
                 $tce = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\DataHandling\\DataHandler');
                 $tce->stripslashes_values = 0;
                 $tce->alternativeFileName = $alternativeFileName;
                 // Initialize
                 $tce->start($recData, array());
                 // Saved the stuff
                 $tce->process_datamap();
                 // Clear the cache (note: currently only admin-users can clear the cache in tce_main.php)
                 $tce->clear_cacheCmd('all');
                 // tce were processed successfully
                 $this->tce_processed = TRUE;
                 // re-read the template ...
                 $this->initialize_editor($this->pObj->id, $template_uid);
             }
             // If files has been edited:
             if (is_array($edit)) {
                 if ($edit['filename'] && $tplRow['resources'] && \TYPO3\CMS\Core\Utility\GeneralUtility::inList($tplRow['resources'], $edit['filename'])) {
                     // Check if there are resources, and that the file is in the resourcelist.
                     $path = PATH_site . $GLOBALS['TCA']['sys_template']['columns']['resources']['config']['uploadfolder'] . '/' . $edit['filename'];
                     $fI = \TYPO3\CMS\Core\Utility\GeneralUtility::split_fileref($edit['filename']);
                     if (@is_file($path) && \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName($path) && \TYPO3\CMS\Core\Utility\GeneralUtility::inList($this->pObj->textExtensions, $fI['fileext'])) {
                         // checks that have already been done.. Just to make sure
                         // @TODO: Check if the hardcorded value already has a config member, otherwise create one
                         // Checks that have already been done.. Just to make sure
                         if (filesize($path) < 30720) {
                             \TYPO3\CMS\Core\Utility\GeneralUtility::writeFile($path, $edit['file']);
                             $theOutput .= $this->pObj->doc->spacer(10);
                             $theOutput .= $this->pObj->doc->section('<font color=red>' . $GLOBALS['LANG']->getLL('fileChanged') . '</font>', sprintf($GLOBALS['LANG']->getLL('resourceUpdated'), $edit['filename']), 0, 0, 0, 1);
                             // Clear cache - the file has probably affected the template setup
                             // @TODO: Check if the edited file really had something to do with cached data and prevent this clearing if possible!
                             /** @var $tce \TYPO3\CMS\Core\DataHandling\DataHandler */
                             $tce = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\DataHandling\\DataHandler');
                             $tce->stripslashes_values = 0;
                             $tce->start(array(), array());
                             $tce->clear_cacheCmd('all');
                         }
                     }
                 }
             }
         }
         // Hook	post updating template/TCE processing
         if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/tstemplate_info/class.tx_tstemplateinfo.php']['postTCEProcessingHook'])) {
             $postTCEProcessingHook =& $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/tstemplate_info/class.tx_tstemplateinfo.php']['postTCEProcessingHook'];
             if (is_array($postTCEProcessingHook)) {
                 $hookParameters = array('POST' => $POST, 'tce' => $tce);
                 foreach ($postTCEProcessingHook as $hookFunction) {
                     \TYPO3\CMS\Core\Utility\GeneralUtility::callUserFunction($hookFunction, $hookParameters, $this);
                 }
             }
         }
         $content = \TYPO3\CMS\Backend\Utility\IconUtility::getSpriteIconForRecord('sys_template', $tplRow) . '<strong>' . htmlspecialchars($tplRow['title']) . '</strong>' . htmlspecialchars(trim($tplRow['sitetitle']) ? ' (' . $tplRow['sitetitle'] . ')' : '');
         $theOutput .= $this->pObj->doc->section($GLOBALS['LANG']->getLL('templateInformation'), $content, 0, 1);
         if ($manyTemplatesMenu) {
             $theOutput .= $this->pObj->doc->section('', $manyTemplatesMenu);
         }
         $theOutput .= $this->pObj->doc->spacer(10);
         $numberOfRows = 35;
         // If abort pressed, nothing should be edited:
         if ($POST['abort'] || \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($POST['abort_x']) && \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($POST['abort_y']) || $POST['saveclose'] || \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($POST['saveclose_x']) && \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($POST['saveclose_y'])) {
             unset($e);
         }
         if ($e['title']) {
             $outCode = '<input type="Text" name="data[title]" value="' . htmlspecialchars($tplRow['title']) . '"' . $this->pObj->doc->formWidth() . '>';
             $outCode .= '<input type="Hidden" name="e[title]" value="1">';
             $theOutput .= $this->pObj->doc->spacer(15);
             $theOutput .= $this->pObj->doc->section($GLOBALS['LANG']->getLL('title'), $outCode, TRUE);
         }
         if ($e['sitetitle']) {
             $outCode = '<input type="Text" name="data[sitetitle]" value="' . htmlspecialchars($tplRow['sitetitle']) . '"' . $this->pObj->doc->formWidth() . '>';
             $outCode .= '<input type="Hidden" name="e[sitetitle]" value="1">';
             $theOutput .= $this->pObj->doc->spacer(15);
             $theOutput .= $this->pObj->doc->section($GLOBALS['LANG']->getLL('sitetitle'), $outCode, TRUE);
         }
         if ($e['description']) {
             $outCode = '<textarea name="data[description]" rows="5" class="fixed-font enable-tab"' . $this->pObj->doc->formWidthText(48, '', '') . '>' . \TYPO3\CMS\Core\Utility\GeneralUtility::formatForTextarea($tplRow['description']) . '</textarea>';
             $outCode .= '<input type="Hidden" name="e[description]" value="1">';
             $theOutput .= $this->pObj->doc->spacer(15);
             $theOutput .= $this->pObj->doc->section($GLOBALS['LANG']->getLL('description'), $outCode, TRUE);
         }
         if ($e['constants']) {
             $outCode = '<textarea name="data[constants]" rows="' . $numberOfRows . '" wrap="off" class="fixed-font enable-tab"' . $this->pObj->doc->formWidthText(48, 'width:98%;height:70%', 'off') . ' class="fixed-font">' . \TYPO3\CMS\Core\Utility\GeneralUtility::formatForTextarea($tplRow['constants']) . '</textarea>';
             $outCode .= '<input type="Hidden" name="e[constants]" value="1">';
             // Display "Include TypoScript file content?" checkbox
             $outCode .= \TYPO3\CMS\Backend\Utility\BackendUtility::getFuncCheck($this->pObj->id, 'SET[includeTypoScriptFileContent]', $this->pObj->MOD_SETTINGS['includeTypoScriptFileContent'], '', '&e[constants]=1', 'id="checkIncludeTypoScriptFileContent"');
             $outCode .= '<label for="checkIncludeTypoScriptFileContent">' . $GLOBALS['LANG']->getLL('includeTypoScriptFileContent') . '</label><br />';
             $theOutput .= $this->pObj->doc->spacer(15);
             $theOutput .= $this->pObj->doc->section($GLOBALS['LANG']->getLL('constants'), '', TRUE);
             $theOutput .= $this->pObj->doc->sectionEnd() . $outCode;
         }
         if ($e['file']) {
             $path = PATH_site . $GLOBALS['TCA']['sys_template']['columns']['resources']['config']['uploadfolder'] . '/' . $e[file];
             $fI = \TYPO3\CMS\Core\Utility\GeneralUtility::split_fileref($e[file]);
             if (@is_file($path) && \TYPO3\CMS\Core\Utility\GeneralUtility::inList($this->pObj->textExtensions, $fI['fileext'])) {
                 if (filesize($path) < $GLOBALS['TCA']['sys_template']['columns']['resources']['config']['max_size'] * 1024) {
                     $fileContent = \TYPO3\CMS\Core\Utility\GeneralUtility::getUrl($path);
                     $outCode = $GLOBALS['LANG']->getLL('file') . ' <strong>' . $e[file] . '</strong><BR>';
                     $outCode .= '<textarea name="edit[file]" rows="' . $numberOfRows . '" wrap="off" class="fixed-font enable-tab"' . $this->pObj->doc->formWidthText(48, 'width:98%;height:70%', 'off') . ' class="fixed-font">' . \TYPO3\CMS\Core\Utility\GeneralUtility::formatForTextarea($fileContent) . '</textarea>';
                     $outCode .= '<input type="Hidden" name="edit[filename]" value="' . $e[file] . '">';
                     $outCode .= '<input type="Hidden" name="e[file]" value="' . htmlspecialchars($e[file]) . '">';
                     $theOutput .= $this->pObj->doc->spacer(15);
                     $theOutput .= $this->pObj->doc->section($GLOBALS['LANG']->getLL('editResource'), '');
                     $theOutput .= $this->pObj->doc->sectionEnd() . $outCode;
                 } else {
                     $theOutput .= $this->pObj->doc->spacer(15);
                     $fileToBig = sprintf($GLOBALS['LANG']->getLL('filesizeExceeded'), $GLOBALS['TCA']['sys_template']['columns']['resources']['config']['max_size']);
                     $filesizeNotAllowed = sprintf($GLOBALS['LANG']->getLL('notAllowed'), $GLOBALS['TCA']['sys_template']['columns']['resources']['config']['max_size']);
                     $theOutput .= $this->pObj->doc->section('<font color=red>' . $fileToBig . '</font>', $filesizeNotAllowed, 0, 0, 0, 1);
                 }
             }
         }
         if ($e['config']) {
             $outCode = '<textarea name="data[config]" rows="' . $numberOfRows . '" wrap="off" class="fixed-font enable-tab"' . $this->pObj->doc->formWidthText(48, 'width:98%;height:70%', 'off') . ' class="fixed-font">' . \TYPO3\CMS\Core\Utility\GeneralUtility::formatForTextarea($tplRow['config']) . '</textarea>';
             $outCode .= '<input type="Hidden" name="e[config]" value="1">';
             // Display "Include TypoScript file content?" checkbox
             $outCode .= \TYPO3\CMS\Backend\Utility\BackendUtility::getFuncCheck($this->pObj->id, 'SET[includeTypoScriptFileContent]', $this->pObj->MOD_SETTINGS['includeTypoScriptFileContent'], '', '&e[config]=1', 'id="checkIncludeTypoScriptFileContent"');
             $outCode .= '<label for="checkIncludeTypoScriptFileContent">' . $GLOBALS['LANG']->getLL('includeTypoScriptFileContent') . '</label><br />';
             if (\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('tsconfig_help')) {
                 $url = $BACK_PATH . 'wizard_tsconfig.php?mode=tsref';
                 $params = array('formName' => 'editForm', 'itemName' => 'data[config]');
                 $outCode .= '<a href="#" onClick="vHWin=window.open(\'' . $url . \TYPO3\CMS\Core\Utility\GeneralUtility::implodeArrayForUrl('', array('P' => $params)) . '\',\'popUp' . $md5ID . '\',\'height=500,width=780,status=0,menubar=0,scrollbars=1\');vHWin.focus();return false;">' . \TYPO3\CMS\Backend\Utility\IconUtility::getSpriteIcon('actions-system-typoscript-documentation-open', array('title' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:tsRef', TRUE))) . '</a>';
             }
             $theOutput .= $this->pObj->doc->spacer(15);
             $theOutput .= $this->pObj->doc->section($GLOBALS['LANG']->getLL('setup'), '', TRUE);
             $theOutput .= $this->pObj->doc->sectionEnd() . $outCode;
         }
         // Processing:
         $outCode = '';
         $outCode .= $this->tableRow($GLOBALS['LANG']->getLL('title'), htmlspecialchars($tplRow['title']), 'title');
         $outCode .= $this->tableRow($GLOBALS['LANG']->getLL('sitetitle'), htmlspecialchars($tplRow['sitetitle']), 'sitetitle');
         $outCode .= $this->tableRow($GLOBALS['LANG']->getLL('description'), nl2br(htmlspecialchars($tplRow['description'])), 'description');
         $outCode .= $this->tableRow($GLOBALS['LANG']->getLL('constants'), sprintf($GLOBALS['LANG']->getLL('editToView'), trim($tplRow[constants]) ? count(explode(LF, $tplRow[constants])) : 0), 'constants');
         $outCode .= $this->tableRow($GLOBALS['LANG']->getLL('setup'), sprintf($GLOBALS['LANG']->getLL('editToView'), trim($tplRow[config]) ? count(explode(LF, $tplRow[config])) : 0), 'config');
         $outCode = '<table class="t3-table-info">' . $outCode . '</table>';
         // Edit all icon:
         $outCode .= '<br /><a href="#" onClick="' . \TYPO3\CMS\Backend\Utility\BackendUtility::editOnClick(rawurlencode('&createExtension=0') . '&amp;edit[sys_template][' . $tplRow['uid'] . ']=edit', $BACK_PATH, '') . '"><strong>' . \TYPO3\CMS\Backend\Utility\IconUtility::getSpriteIcon('actions-document-open', array('title' => $GLOBALS['LANG']->getLL('editTemplateRecord'))) . $GLOBALS['LANG']->getLL('editTemplateRecord') . '</strong></a>';
         $theOutput .= $this->pObj->doc->section('', $outCode);
         // hook	after compiling the output
         if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/tstemplate_info/class.tx_tstemplateinfo.php']['postOutputProcessingHook'])) {
             $postOutputProcessingHook =& $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/tstemplate_info/class.tx_tstemplateinfo.php']['postOutputProcessingHook'];
             if (is_array($postOutputProcessingHook)) {
                 $hookParameters = array('theOutput' => &$theOutput, 'POST' => $POST, 'e' => $e, 'tplRow' => $tplRow, 'numberOfRows' => $numberOfRows);
                 foreach ($postOutputProcessingHook as $hookFunction) {
                     \TYPO3\CMS\Core\Utility\GeneralUtility::callUserFunction($hookFunction, $hookParameters, $this);
                 }
             }
         }
     } else {
         $theOutput .= $this->pObj->noTemplate(1);
     }
     return $theOutput;
 }
 /**
  * Get unique/non-existing filename out of a relative path
  *        func. replace \TYPO3\CMS\Core\Utility\File\BasicFileUtility::getUniqueName()
  *        with endless limit for appending numbers
  *
  * @param string $filename
  * @param string $destinationPath Relative Path to destination
  * @param bool $addPath
  * @param bool $randomized
  * @return string new filename or filenameAndPath
  */
 public static function getUniqueName($filename, $destinationPath, $addPath = true, $randomized = false)
 {
     self::cleanFileName($filename);
     self::getAndSetRandomizedFileName($filename, $randomized);
     $absoluteDestination = self::getAbsoluteFolder($destinationPath);
     $fileInfo = GeneralUtility::split_fileref($filename);
     $newFileName = $filename;
     $newPathAndFileName = $absoluteDestination . $fileInfo['file'];
     if (file_exists($newPathAndFileName)) {
         $theTempFileBody = self::removeAppendingNumbersInString($fileInfo['filebody']);
         $extension = $fileInfo['realFileext'] ? '.' . $fileInfo['realFileext'] : '';
         for ($a = 1; true; $a++) {
             $appendix = '_' . sprintf('%02d', $a);
             $newFileName = $theTempFileBody . $appendix . $extension;
             $newPathAndFileName = $absoluteDestination . $newFileName;
             if (!file_exists($newPathAndFileName)) {
                 break;
             }
         }
     }
     if ($addPath) {
         return $newPathAndFileName;
     }
     return $newFileName;
 }
 /**
  * Actually convert from $source to $targetType, taking into account the fully
  * built $convertedChildProperties and $configuration.
  *
  * The return value can be one of three types:
  * - an arbitrary object, or a simple type (which has been created while mapping).
  *   This is the normal case.
  * - NULL, indicating that this object should *not* be mapped (i.e. a "File Upload" Converter could return NULL if no file has been uploaded, and a silent failure should occur.
  * - An instance of \TYPO3\CMS\Extbase\Error\Error -- This will be a user-visible error message later on.
  * Furthermore, it should throw an Exception if an unexpected failure (like a security error) occurred or a configuration issue happened.
  *
  * @param mixed $source
  * @param string $targetType
  * @param array $convertedChildProperties
  * @param \TYPO3\CMS\Extbase\Property\PropertyMappingConfigurationInterface $configuration
  *
  * @return mixed|\TYPO3\CMS\Extbase\Error\Error the target type, or an error object if a user-error occurred
  *
  * @throws \TYPO3\CMS\Extbase\Property\Exception\TypeConverterException thrown in case a developer error occurred
  */
 public function convertFrom($source, $targetType, array $convertedChildProperties = array(), \TYPO3\CMS\Extbase\Property\PropertyMappingConfigurationInterface $configuration = null)
 {
     /** @var \TYPO3\CMS\Extbase\Domain\Model\FileReference $alreadyPersistedImage */
     $alreadyPersistedImage = $configuration->getConfigurationValue('JWeiland\\Clubdirectory\\Property\\TypeConverter\\UploadOneFileConverter', 'IMAGE');
     // if no file was uploaded use the already persisted one
     if (!isset($source['error']) || !isset($source['name']) || !isset($source['size']) || !isset($source['tmp_name']) || !isset($source['type']) || $source['error'] === 4) {
         return $alreadyPersistedImage;
     }
     // check if uploaded file returns an error
     if ($source['error'] !== 0) {
         return new \TYPO3\CMS\Extbase\Error\Error(LocalizationUtility::translate('error.upload', 'clubdirectory') . $source['error'], 1396957314);
     }
     // now we have a valid uploaded file. Check if user has rights to upload this file
     if (!isset($source['rights']) || empty($source['rights'])) {
         return new \TYPO3\CMS\Extbase\Error\Error(LocalizationUtility::translate('error.uploadRights', 'clubdirectory'), 1397464390);
     }
     // check if file extension is allowed
     $fileParts = GeneralUtility::split_fileref($source['name']);
     if (!GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], $fileParts['fileext'])) {
         return new \TYPO3\CMS\Extbase\Error\Error(LocalizationUtility::translate('error.fileExtension', 'clubdirectory', array($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'])), 1402981282);
     }
     // before uploading the new file we should remove the old one
     if ($alreadyPersistedImage instanceof \TYPO3\CMS\Extbase\Domain\Model\FileReference) {
         $alreadyPersistedImage->getOriginalResource()->delete();
     }
     return $this->getExtbaseFileReference($source);
 }
Example #13
0
 /**
  * Parse speaking URL and translate it to parameters understood by TYPO3
  * Function is called from tslib_fe
  * The overall format of a speaking URL is these five parts [TYPO3_SITE_URL] / [pre-var] / [page-identification] / [post-vars] / [file.ext]
  * - "TYPO3_SITE_URL" is fixed value from the environment,
  * - "pre-var" is any number of segments separated by "/" mapping to GETvars AND with a known lenght,
  * - "page-identification" identifies the page id in TYPO3 possibly with multiple segments separated by "/" BUT with an UNKNOWN length,
  * - "post-vars" is sets of segments offering the same features as "pre-var"
  * - "file.ext" is any filename that might apply
  *
  * @param array $params Params for hook
  * @return void Setting internal variables.
  */
 public function decodeSpURL($params)
 {
     $this->devLog('Entering decodeSpURL');
     // Setting parent object reference (which is $GLOBALS['TSFE'])
     $this->pObj =& $params['pObj'];
     // Initializing config / request URL
     $this->setConfig();
     $this->adjustConfigurationByHost('decode');
     $this->adjustRootPageId();
     // If there has been a redirect (basically; we arrived here otherwise than via "index.php" in the URL) this can happend either due to a CGI-script or because of reWrite rule. Earlier we used $GLOBALS['HTTP_SERVER_VARS']['REDIRECT_URL'] to check but...
     if ($this->pObj->siteScript && substr($this->pObj->siteScript, 0, 9) != 'index.php' && substr($this->pObj->siteScript, 0, 1) != '?') {
         // Getting the path which is above the current site url
         // For instance "first/second/third/index.html?&param1=value1&param2=value2"
         // should be the result of the URL
         // "http://localhost/typo3/dev/dummy_1/first/second/third/index.html?&param1=value1&param2=value2"
         // Note: sometimes in fcgi installations it is absolute, so we have to make it
         // relative to work properly.
         $speakingURIpath = $this->pObj->siteScript[0] == '/' ? substr($this->pObj->siteScript, 1) : $this->pObj->siteScript;
         // Call hooks
         if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl']['decodeSpURL_preProc'])) {
             foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl']['decodeSpURL_preProc'] as $userFunc) {
                 $hookParams = array('pObj' => &$this, 'params' => $params, 'URL' => &$speakingURIpath);
                 \TYPO3\CMS\Core\Utility\GeneralUtility::callUserFunction($userFunc, $hookParams, $this);
             }
         }
         // Append missing slash if configured for
         if ($this->extConf['init']['appendMissingSlash']) {
             $regexp = '~^([^\\?]*[^/])(\\?.*)?$~';
             if (substr($speakingURIpath, -1, 1) == '?') {
                 $speakingURIpath = substr($speakingURIpath, 0, -1);
             }
             if (preg_match($regexp, $speakingURIpath)) {
                 // Only process if a slash is missing:
                 $options = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', $this->extConf['init']['appendMissingSlash'], true);
                 if (in_array('ifNotFile', $options)) {
                     if (!preg_match('/\\/[^\\/\\?]+\\.[^\\/]+(\\?.*)?$/', '/' . $speakingURIpath)) {
                         $speakingURIpath = preg_replace($regexp, '\\1/\\2', $speakingURIpath);
                         $this->appendedSlash = true;
                     }
                 } else {
                     $speakingURIpath = preg_replace($regexp, '\\1/\\2', $speakingURIpath);
                     $this->appendedSlash = true;
                 }
                 if ($this->appendedSlash && count($options) > 0) {
                     foreach ($options as $option) {
                         $matches = array();
                         if (preg_match('/^redirect(\\[(30[1237])\\])?$/', $option, $matches)) {
                             $code = count($matches) > 1 ? $matches[2] : 301;
                             $status = 'HTTP/1.1 ' . $code . ' TYPO3 RealURL redirect M' . __LINE__;
                             // Check path segment to be relative for the current site.
                             // parse_url() does not work with relative URLs, so we use it to test
                             if (!@parse_url($speakingURIpath, PHP_URL_HOST)) {
                                 @ob_end_clean();
                                 header($status);
                                 header('Location: ' . \TYPO3\CMS\Core\Utility\GeneralUtility::locationHeaderUrl($speakingURIpath));
                                 exit;
                             }
                         }
                     }
                 }
             }
         }
         // If the URL is a single script like "123.1.html" it might be an "old" simulateStaticDocument request. If this is the case and support for this is configured, do NOT try and resolve it as a Speaking URL
         $fI = \TYPO3\CMS\Core\Utility\GeneralUtility::split_fileref($speakingURIpath);
         if (!\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($this->pObj->id) && $fI['path'] == '' && $this->extConf['fileName']['defaultToHTMLsuffixOnPrev'] && $this->extConf['init']['respectSimulateStaticURLs']) {
             // If page ID does not exist yet and page is on the root level and both
             // respectSimulateStaticURLs and defaultToHTMLsuffixOnPrev are set, than
             // ignore respectSimulateStaticURLs and attempt to resolve page id.
             // See http://bugs.typo3.org/view.php?id=1530
             /** @noinspection PhpUndefinedMethodInspection */
             $GLOBALS['TT']->setTSlogMessage('decodeSpURL: ignoring respectSimulateStaticURLs due defaultToHTMLsuffixOnPrev for the root level page!)', 2);
             $this->extConf['init']['respectSimulateStaticURLs'] = false;
         }
         if (!$this->extConf['init']['respectSimulateStaticURLs'] || $fI['path']) {
             $this->devLog('RealURL powered decoding (TM) starting!');
             // Parse path
             $uParts = @parse_url($speakingURIpath);
             if (!is_array($uParts)) {
                 $this->decodeSpURL_throw404('Current URL is invalid');
             }
             $speakingURIpath = $this->speakingURIpath_procValue = $uParts['path'];
             // Redirecting if needed (exits if so).
             $this->decodeSpURL_checkRedirects($speakingURIpath);
             // Looking for cached information
             $cachedInfo = $this->decodeSpURL_decodeCache($speakingURIpath);
             // If no cached info was found, create it
             if (!is_array($cachedInfo)) {
                 // Decode URL
                 $cachedInfo = $this->decodeSpURL_doDecode($speakingURIpath, $this->extConf['init']['enableCHashCache']);
                 // Storing cached information
                 $this->decodeSpURL_decodeCache($speakingURIpath, $cachedInfo);
             }
             // Re-create QUERY_STRING from Get vars for use with typoLink()
             $_SERVER['QUERY_STRING'] = $this->decodeSpURL_createQueryString($cachedInfo['GET_VARS']);
             if (is_callable('TYPO3\\CMS\\Core\\Utility\\GeneralUtility::flushInternalRuntimeCaches')) {
                 \TYPO3\CMS\Core\Utility\GeneralUtility::flushInternalRuntimeCaches();
             }
             // Jump-admin if configured
             $this->decodeSpURL_jumpAdmin_goBackend($cachedInfo['id']);
             // Setting info in TSFE
             $this->pObj->mergingWithGetVars($cachedInfo['GET_VARS']);
             $this->pObj->id = $cachedInfo['id'];
             if ($this->mimeType) {
                 header('Content-type: ' . $this->mimeType);
                 $this->mimeType = null;
             }
         }
     }
 }
Example #14
0
 protected function getFileMarker($marker, &$template, &$sims, &$rems)
 {
     if (!$this->isAllowed($marker)) {
         return;
     }
     $max = $GLOBALS['TCA']['tx_cal_' . $this->objectString]['columns'][$marker]['config']['maxitems'];
     $sims['###' . strtoupper($marker) . '###'] = '';
     $sims['###' . strtoupper($marker) . '_VALUE###'] = '';
     $sims['###' . strtoupper($marker) . '_CAPTION###'] = '';
     $sims['###' . strtoupper($marker) . '_CAPTION_VALUE###'] = '';
     if ($this->isConfirm) {
         $sims['###' . strtoupper($marker) . '###'] = '';
         $fileFunc = new \TYPO3\CMS\Core\Utility\File\BasicFileUtility();
         $all_files = array();
         $all_files['webspace']['allow'] = '*';
         $all_files['webspace']['deny'] = '';
         $fileFunc->init('', $all_files);
         $allowedExt = array();
         $denyExt = array();
         if ($marker == 'image') {
             $allowedExt = explode(',', $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext']);
         } else {
             if ($marker == 'attachment') {
                 $allowedExt = explode(',', $GLOBALS['TYPO3_CONF_VARS']['BE']['fileExtensions']['webspace']['allow']);
                 $denyExt = explode(',', $GLOBALS['TYPO3_CONF_VARS']['BE']['fileExtensions']['webspace']['deny']);
             }
         }
         $i = 0;
         // new files
         if (is_array($_FILES[$this->prefixId]['name'])) {
             foreach ($_FILES[$this->prefixId]['name'][$marker] as $id => $filename) {
                 $theDestFile = '';
                 $iConf = $this->conf['view.'][$this->conf['view'] . '.'][strtolower($marker) . '_stdWrap.'];
                 if ($_FILES[$this->prefixId]['error'][$marker][$id]) {
                     continue;
                 } else {
                     $theFile = GeneralUtility::upload_to_tempfile($_FILES[$this->prefixId]['tmp_name'][$marker][$id]);
                     $fI = GeneralUtility::split_fileref($filename);
                     if (in_array($fI['fileext'], $denyExt)) {
                         continue;
                     } else {
                         if ($marker == 'image' && !in_array($fI['fileext'], $allowedExt)) {
                             continue;
                         }
                     }
                     $theDestFile = $fileFunc->getUniqueName($fileFunc->cleanFileName($fI['file']), 'typo3temp');
                     GeneralUtility::upload_copy_move($theFile, $theDestFile);
                     $iConf['file'] = $theDestFile;
                     $return = '__NEW__' . basename($theDestFile);
                 }
                 $temp_sims = array();
                 $temp_sims['###INDEX###'] = $id;
                 $temp_sims['###' . strtoupper($marker) . '_VALUE###'] = $return;
                 $temp = '';
                 if ($marker == 'image') {
                     $temp = $this->renderImage($iConf['file'], $this->controller->piVars[$marker . '_caption'][$id], $this->controller->piVars[$marker . '_title'][$id], $marker, true);
                 } else {
                     if ($marker == 'attachment' || $marker == 'ics_file') {
                         $temp = $this->renderFile($iConf['file'], $this->controller->piVars[$marker . '_caption'][$id], $this->controller->piVars[$marker . '_title'][$id], $marker, true);
                     }
                 }
                 if ($this->isAllowed($marker . '_caption')) {
                     $temp .= $this->applyStdWrap($this->controller->piVars[$marker . '_caption'][$id], $marker . '_caption_stdWrap');
                 }
                 if ($this->isAllowed($marker . '_title')) {
                     $temp .= $this->applyStdWrap($this->controller->piVars[$marker . '_title'][$id], $marker . '_title_stdWrap');
                 }
                 $sims['###' . strtoupper($marker) . '###'] .= \TYPO3\CMS\Cal\Utility\Functions::substituteMarkerArrayNotCached($temp, $temp_sims, array(), array());
                 $i++;
             }
         }
         $removeFiles = $this->controller->piVars['remove_' . $marker] ? $this->controller->piVars['remove_' . $marker] : array();
         $where = 'uid_foreign = ' . $this->conf['uid'] . ' AND  tablenames=\'tx_cal_' . $this->objectString . '\' AND fieldname=\'' . $marker . '\' AND deleted=0';
         if (!empty($removeFiles)) {
             $where .= ' AND uid not in (' . implode(',', array_values($removeFiles)) . ')';
         }
         $result = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'sys_file_reference', $where);
         while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
             if ($marker == 'image') {
                 $temp = $this->renderImage($row, $row['description'], $row['title'], $marker, false);
             } else {
                 if ($marker == 'attachment' || $marker == 'ics_file') {
                     $temp = $this->renderFile($row, $row['description'], $row['title'], $marker, false);
                 }
             }
             $temp_sims = array();
             $temp_sims['###' . strtoupper($marker) . '_VALUE###'] = $row['uid'];
             foreach ($this->controller->piVars[$marker] as $index => $image) {
                 if ($image == $row['uid']) {
                     if (isset($this->controller->piVars[$marker . '_caption'][$index])) {
                         $row['description'] = $this->controller->piVars[$marker . '_caption'][$index];
                     }
                     if (isset($this->controller->piVars[$marker . '_title'][$index])) {
                         $row['title'] = $this->controller->piVars[$marker . '_title'][$index];
                     }
                     $temp_sims['###INDEX###'] = $index;
                     break;
                 }
             }
             if ($this->isAllowed($marker . '_caption')) {
                 $temp .= $this->applyStdWrap($row['description'], $marker . '_caption_stdWrap');
             }
             if ($this->isAllowed($marker . '_title')) {
                 $temp .= $this->applyStdWrap($row['title'], $marker . '_title_stdWrap');
             }
             $sims['###' . strtoupper($marker) . '###'] .= \TYPO3\CMS\Cal\Utility\Functions::substituteMarkerArrayNotCached($temp, $temp_sims, array(), array());
         }
         $GLOBALS['TYPO3_DB']->sql_free_result($result);
         foreach ($removeFiles as $removeFile) {
             $sims['###' . strtoupper($marker) . '###'] .= '<input type="hidden" name="tx_cal_controller[remove_' . $marker . '][]" value="' . $removeFile . '">';
         }
     } else {
         if ($this->isEditMode && $this->rightsObj->isAllowedTo('edit', $this->objectString, $marker)) {
             $sims['###' . strtoupper($marker) . '###'] = '';
             $i = 0;
             $result = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'sys_file_reference', 'uid_foreign = ' . $this->conf['uid'] . ' AND  tablenames=\'tx_cal_' . $this->objectString . '\' AND fieldname=\'' . $marker . '\' AND deleted=0');
             while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
                 $temp_sims = array();
                 $temp_sims['###' . strtoupper($marker) . '_VALUE###'] = $row['uid'];
                 $temp = $this->cObj->stdWrap('', $this->conf['view.'][$this->conf['view'] . '.'][strtolower($marker) . '_stdWrap.']);
                 if ($marker == 'image') {
                     $temp_sims['###' . strtoupper($marker) . '_PREVIEW###'] = $this->renderImage($row, $row['description'], $row['title'], $marker, false);
                 } else {
                     if ($marker == 'attachment' || $marker == 'ics_file') {
                         $temp_sims['###' . strtoupper($marker) . '_PREVIEW###'] = $this->renderFile($row, $row['description'], $row['title'], $marker, false);
                     }
                 }
                 $temp = \TYPO3\CMS\Cal\Utility\Functions::substituteMarkerArrayNotCached($temp, $temp_sims, array(), array());
                 if ($this->isAllowed($marker . '_caption')) {
                     $temp .= $this->applyStdWrap($row['description'], $marker . '_caption_stdWrap');
                 }
                 if ($this->isAllowed($marker . '_title')) {
                     $temp .= $this->applyStdWrap($row['title'], $marker . '_title_stdWrap');
                 }
                 $temp_sims['###INDEX###'] = $i;
                 $sims['###' . strtoupper($marker) . '###'] .= \TYPO3\CMS\Cal\Utility\Functions::substituteMarkerArrayNotCached($temp, $temp_sims, array(), array());
                 $i++;
             }
             $GLOBALS['TYPO3_DB']->sql_free_result($result);
             $upload = '';
             for (; $i < $max; $i++) {
                 $temp_sims = array();
                 $upload .= $this->cObj->stdWrap('', $this->conf['view.'][$this->conf['view'] . '.'][$marker . 'Upload_stdWrap.']);
                 if ($this->isAllowed($marker . '_caption')) {
                     $upload .= $this->applyStdWrap('', $marker . '_caption_stdWrap');
                 }
                 if ($this->isAllowed($marker . '_title')) {
                     $upload .= $this->applyStdWrap('', $marker . '_title_stdWrap');
                 }
                 $temp_sims['###INDEX###'] = $i;
                 $upload = \TYPO3\CMS\Cal\Utility\Functions::substituteMarkerArrayNotCached($upload, $temp_sims, array(), array());
             }
             $sims['###' . strtoupper($marker) . '###'] .= $upload;
         } else {
             if (!$this->isEditMode && $this->rightsObj->isAllowedTo('create', $this->objectString, $marker)) {
                 for ($i = 0; $i < $max; $i++) {
                     $value = '';
                     $upload = $this->cObj->stdWrap($value, $this->conf['view.'][$this->conf['view'] . '.'][$marker . 'Upload_stdWrap.']);
                     $value = '';
                     if ($this->isAllowed($marker . '_caption')) {
                         $upload .= $this->applyStdWrap('', $marker . '_caption_stdWrap');
                     }
                     if ($this->isAllowed($marker . '_title')) {
                         $upload .= $this->applyStdWrap('', $marker . '_title_stdWrap');
                     }
                     $temp_sims['###INDEX###'] = $i;
                     $sims['###' . strtoupper($marker) . '###'] .= \TYPO3\CMS\Cal\Utility\Functions::substituteMarkerArrayNotCached($upload, $temp_sims, array(), array());
                 }
             }
         }
     }
 }
 /**
  * Actually convert from $source to $targetType, taking into account the fully
  * built $convertedChildProperties and $configuration.
  *
  * The return value can be one of three types:
  * - an arbitrary object, or a simple type (which has been created while mapping).
  *   This is the normal case.
  * - NULL, indicating that this object should *not* be mapped (i.e. a "File Upload" Converter could return NULL if no file has been uploaded, and a silent failure should occur.
  * - An instance of \TYPO3\CMS\Extbase\Error\Error -- This will be a user-visible error message later on.
  * Furthermore, it should throw an Exception if an unexpected failure (like a security error) occurred or a configuration issue happened.
  *
  * @param mixed $source
  * @param string $targetType
  * @param array $convertedChildProperties
  * @param \TYPO3\CMS\Extbase\Property\PropertyMappingConfigurationInterface $configuration
  *
  * @return mixed|\TYPO3\CMS\Extbase\Error\Error the target type, or an error object if a user-error occurred
  *
  * @throws \TYPO3\CMS\Extbase\Property\Exception\TypeConverterException thrown in case a developer error occurred
  */
 public function convertFrom($source, $targetType, array $convertedChildProperties = array(), \TYPO3\CMS\Extbase\Property\PropertyMappingConfigurationInterface $configuration = null)
 {
     $alreadyPersistedImages = $configuration->getConfigurationValue('JWeiland\\Clubdirectory\\Property\\TypeConverter\\UploadMultipleFilesConverter', 'IMAGES');
     $originalSource = $source;
     foreach ($originalSource as $key => $uploadedFile) {
         // check if $source contains an uploaded file. 4 = no file uploaded
         if (!isset($uploadedFile['error']) || !isset($uploadedFile['name']) || !isset($uploadedFile['size']) || !isset($uploadedFile['tmp_name']) || !isset($uploadedFile['type']) || $uploadedFile['error'] === 4) {
             if ($alreadyPersistedImages[$key] !== null) {
                 $source[$key] = $alreadyPersistedImages[$key];
             } else {
                 unset($source[$key]);
             }
             continue;
         }
         // check if uploaded file returns an error
         if (!$uploadedFile['error'] === 0) {
             return new \TYPO3\CMS\Extbase\Error\Error(LocalizationUtility::translate('error.upload', 'clubdirectory') . $uploadedFile['error'], 1396957314);
         }
         // now we have a valid uploaded file. Check if user has rights to upload this file
         if (!isset($uploadedFile['rights']) || empty($uploadedFile['rights'])) {
             return new \TYPO3\CMS\Extbase\Error\Error(LocalizationUtility::translate('error.uploadRights', 'clubdirectory'), 1397464390);
         }
         // check if file extension is allowed
         $fileParts = GeneralUtility::split_fileref($uploadedFile['name']);
         if (!GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], $fileParts['fileext'])) {
             return new \TYPO3\CMS\Extbase\Error\Error(LocalizationUtility::translate('error.fileExtension', 'clubdirectory', array($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'])), 1402981282);
         }
         // OK...we have a valid file and the user has the rights. It's time to check, if an old file can be deleted
         if ($alreadyPersistedImages[$key] instanceof \TYPO3\CMS\Extbase\Domain\Model\FileReference) {
             /** @var \TYPO3\CMS\Extbase\Domain\Model\FileReference $oldFile */
             $oldFile = $alreadyPersistedImages[$key];
             $oldFile->getOriginalResource()->getOriginalFile()->delete();
         }
     }
     // I will do two foreach here. First: everything must be OK, before files will be uploaded
     // upload file and add it to ObjectStorage
     /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $references */
     $references = $this->objectManager->get('TYPO3\\CMS\\Extbase\\Persistence\\ObjectStorage');
     foreach ($source as $uploadedFile) {
         if ($uploadedFile instanceof \TYPO3\CMS\Extbase\Domain\Model\FileReference) {
             $references->attach($uploadedFile);
         } else {
             $references->attach($this->getExtbaseFileReference($uploadedFile));
         }
     }
     return $references;
 }
Example #16
0
 /**
  * This method returns the label for a specified URL.
  * If the page is local and contains a fragment it returns the label of the content element linked to.
  * In any other case it simply fetches the page and extracts the <title> tag content as label
  *
  * @param string $url The statistics click-URL for which to return a label
  * @param string $urlStr  A processed variant of the url string. This could get appended to the label???
  * @param bool $forceFetch When this parameter is set to true the "fetch and extract <title> tag" method will get used
  * @param string $linkedWord The word to be linked
  *
  * @return string The label for the passed $url parameter
  */
 function getLinkLabel($url, $urlStr, $forceFetch = false, $linkedWord = '')
 {
     $pathSite = $this->getBaseURL();
     $label = $linkedWord;
     $contentTitle = '';
     $urlParts = parse_url($url);
     if (!$forceFetch && substr($url, 0, strlen($pathSite)) === $pathSite) {
         if ($urlParts['fragment'] && substr($urlParts['fragment'], 0, 1) == 'c') {
             // linking directly to a content
             $elementUid = intval(substr($urlParts['fragment'], 1));
             $row = BackendUtility::getRecord('tt_content', $elementUid);
             if ($row) {
                 $contentTitle = BackendUtility::getRecordTitle('tt_content', $row, false, true);
             }
         } else {
             $contentTitle = $this->getLinkLabel($url, $urlStr, true);
         }
     } else {
         if (empty($urlParts['host']) && substr($url, 0, strlen($pathSite)) !== $pathSite) {
             // it's internal
             $url = $pathSite . $url;
         }
         $content = GeneralUtility::getURL($url);
         if (preg_match('/\\<\\s*title\\s*\\>(.*)\\<\\s*\\/\\s*title\\s*\\>/i', $content, $matches)) {
             // get the page title
             $contentTitle = GeneralUtility::fixed_lgd_cs(trim($matches[1]), 50);
         } else {
             // file?
             $file = GeneralUtility::split_fileref($url);
             $contentTitle = $file['file'];
         }
     }
     if ($this->params['showContentTitle'] == 1) {
         $label = $contentTitle;
     }
     if ($this->params['prependContentTitle'] == 1) {
         $label = $contentTitle . ' (' . $linkedWord . ')';
     }
     if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXT']['directmail']['getLinkLabel'])) {
         foreach ($GLOBALS['TYPO3_CONF_VARS']['EXT']['directmail']['getLinkLabel'] as $funcRef) {
             $params = array('pObj' => &$this, 'url' => $url, 'urlStr' => $urlStr, 'label' => $label);
             $label = GeneralUtility::callUserFunction($funcRef, $params, $this);
         }
     }
     if (isset($this->params['maxLabelLength']) && $this->params['maxLabelLength'] > 0) {
         $label = GeneralUtility::fixed_lgd_cs($label, $this->params['maxLabelLength']);
     }
     return $label;
 }
Example #17
0
 /**
  * Unzipping file (action=7)
  * This is permitted only if the user has fullAccess or if the file resides
  *
  * @param array $cmds $cmds['data'] is the zip-file. $cmds['target'] is the target directory. If not set we'll default to the same directory as the file is in.
  * @return bool Returns TRUE on success
  */
 public function func_unzip($cmds)
 {
     if (!$this->isInit || $this->dont_use_exec_commands) {
         return FALSE;
     }
     $theFile = $cmds['data'];
     if (!@is_file($theFile)) {
         $this->writelog(7, 2, 105, 'The file "%s" did not exist!', array($theFile));
         return FALSE;
     }
     $fI = GeneralUtility::split_fileref($theFile);
     if (!isset($cmds['target'])) {
         $cmds['target'] = $fI['path'];
     }
     // Clean up destination directory
     // !!! Method has been put in the local driver, can be saftely removed
     $theDest = $this->is_directory($cmds['target']);
     if (!$theDest) {
         $this->writelog(7, 2, 104, 'Destination "%s" was not a directory', array($cmds['target']));
         return FALSE;
     }
     if (!$this->actionPerms['unzipFile']) {
         $this->writelog(7, 1, 103, 'You are not allowed to unzip files', '');
         return FALSE;
     }
     if ($fI['fileext'] != 'zip') {
         $this->writelog(7, 1, 102, 'File extension is not "zip"', '');
         return FALSE;
     }
     if (!$this->checkIfFullAccess($theDest)) {
         $this->writelog(7, 1, 101, 'You don\'t have full access to the destination directory "%s"!', array($theDest));
         return FALSE;
     }
     // !!! Method has been put in the sotrage driver, can be saftely removed
     if ($this->checkPathAgainstMounts($theFile) && $this->checkPathAgainstMounts($theDest . '/')) {
         // No way to do this under windows.
         $cmd = $this->unzipPath . 'unzip -qq ' . escapeshellarg($theFile) . ' -d ' . escapeshellarg($theDest);
         CommandUtility::exec($cmd);
         $this->writelog(7, 0, 1, 'Unzipping file "%s" in "%s"', array($theFile, $theDest));
         return TRUE;
     } else {
         $this->writelog(7, 1, 100, 'File "%s" or destination "%s" was not within your mountpoints!', array($theFile, $theDest));
         return FALSE;
     }
 }
 /**
  * Returns the destination path/filename of a unique filename/foldername in that path.
  * If $theFile exists in $theDest (directory) the file have numbers appended up to $this->maxNumber. Hereafter a unique string will be appended.
  * This function is used by fx. TCEmain when files are attached to records and needs to be uniquely named in the uploads/* folders
  *
  * @param string The input filename to check
  * @param string The directory for which to return a unique filename for $theFile. $theDest MUST be a valid directory. Should be absolute.
  * @param bool If set the filename is returned with the path prepended without checking whether it already existed!
  * @return string The destination absolute filepath (not just the name!) of a unique filename/foldername in that path.
  * @see \TYPO3\CMS\Core\DataHandling\DataHandler::checkValue()
  * @todo Deprecate, but still in use by the Core (DataHandler...)
  * @deprecated but still in use in the Core. Don't use in your extensions!
  */
 public function getUniqueName($theFile, $theDest, $dontCheckForUnique = 0)
 {
     // @todo: should go into the LocalDriver in a protected way (not important to the outside world)
     $theDest = $this->is_directory($theDest);
     // $theDest is cleaned up
     $origFileInfo = GeneralUtility::split_fileref($theFile);
     // Fetches info about path, name, extension of $theFile
     if ($theDest) {
         if ($this->getUniqueNamePrefix) {
             // Adds prefix
             $origFileInfo['file'] = $this->getUniqueNamePrefix . $origFileInfo['file'];
             $origFileInfo['filebody'] = $this->getUniqueNamePrefix . $origFileInfo['filebody'];
         }
         // Check if the file exists and if not - return the filename...
         $fileInfo = $origFileInfo;
         $theDestFile = $theDest . '/' . $fileInfo['file'];
         // The destinations file
         if (!file_exists($theDestFile) || $dontCheckForUnique) {
             // If the file does NOT exist we return this filename
             return $theDestFile;
         }
         // Well the filename in its pure form existed. Now we try to append numbers / unique-strings and see if we can find an available filename...
         $theTempFileBody = preg_replace('/_[0-9][0-9]$/', '', $origFileInfo['filebody']);
         // This removes _xx if appended to the file
         $theOrigExt = $origFileInfo['realFileext'] ? '.' . $origFileInfo['realFileext'] : '';
         for ($a = 1; $a <= $this->maxNumber + 1; $a++) {
             if ($a <= $this->maxNumber) {
                 // First we try to append numbers
                 $insert = '_' . sprintf('%02d', $a);
             } else {
                 // .. then we try unique-strings...
                 $insert = '_' . substr(md5(uniqid('', true)), 0, $this->uniquePrecision);
             }
             $theTestFile = $theTempFileBody . $insert . $theOrigExt;
             $theDestFile = $theDest . '/' . $theTestFile;
             // The destinations file
             if (!file_exists($theDestFile)) {
                 // If the file does NOT exist we return this filename
                 return $theDestFile;
             }
         }
     }
 }
    /**
     * Rendering the cObject, SWFOBJECT
     *
     * @param array $conf Array of TypoScript properties
     * @return string Output
     */
    public function render($conf = array())
    {
        /** @var $pageRenderer \TYPO3\CMS\Core\Page\PageRenderer */
        $pageRenderer = $GLOBALS['TSFE']->getPageRenderer();
        $params = $prefix = '';
        if ($GLOBALS['TSFE']->baseUrl) {
            $prefix = $GLOBALS['TSFE']->baseUrl;
        }
        if ($GLOBALS['TSFE']->absRefPrefix) {
            $prefix = $GLOBALS['TSFE']->absRefPrefix;
        }
        // Initialize content
        $replaceElementIdString = str_replace('.', '', uniqid('mmswf', TRUE));
        $GLOBALS['TSFE']->register['MMSWFID'] = $replaceElementIdString;
        $layout = isset($conf['layout.']) ? $this->cObj->stdWrap($conf['layout'], $conf['layout.']) : $conf['layout'];
        $content = str_replace('###ID###', $replaceElementIdString, $layout);
        $type = isset($conf['type.']) ? $this->cObj->stdWrap($conf['type'], $conf['type.']) : $conf['type'];
        $typeConf = $conf[$type . '.'];
        // Add Flowplayer js-file
        $pageRenderer->addJsFile($this->getPathToLibrary('flowplayer/flowplayer-3.2.13.min.js'));
        // Add Flowpayer css for exprss install
        $pageRenderer->addCssFile($this->getPathToLibrary('flowplayer/express-install/express-install.css'));
        // Add videoJS js-file
        $pageRenderer->addJsFile($this->getPathToLibrary('videojs/video-js/video.js'));
        // Add videoJS css-file
        $pageRenderer->addCssFile($this->getPathToLibrary('videojs/video-js/video-js.css'));
        // Add extended videoJS control bar
        $pageRenderer->addJsFile($this->getPathToLibrary('videojs/video-js/controls/control-bar.js'));
        $pageRenderer->addCssFile($this->getPathToLibrary('videojs/video-js/controls/control-bar.css'));
        // Build Flash configuration
        $player = isset($typeConf['player.']) ? $this->cObj->stdWrap($typeConf['player'], $typeConf['player.']) : $typeConf['player'];
        if (!$player) {
            $player = $prefix . $this->getPathToLibrary('flowplayer/flowplayer-3.2.18.swf');
        } elseif (strpos($player, 'EXT:') === 0) {
            $player = $prefix . $GLOBALS['TSFE']->tmpl->getFileName($player);
        }
        $installUrl = isset($conf['installUrl.']) ? $this->cObj->stdWrap($conf['installUrl'], $conf['installUrl.']) : $conf['installUrl'];
        if (!$installUrl) {
            $installUrl = $prefix . $this->getPathToLibrary('flowplayer/expressinstall.swf');
        } elseif (strpos($installUrl, 'EXT:') === 0) {
            $installUrl = $prefix . $GLOBALS['TSFE']->tmpl->getFileName($installUrl);
        }
        $flashVersion = isset($conf['flashVersion.']) ? $this->cObj->stdWrap($conf['flashVersion'], $conf['flashVersion.']) : $conf['flashVersion'];
        if (!$flashVersion) {
            $flashVersion = array(9, 115);
        }
        $flashConfiguration = array('src' => $player, 'expressInstall' => $installUrl, 'version' => $flashVersion, 'onFail' => '###ONFAIL###');
        $flashDownloadUrl = 'http://www.adobe.com/go/getflashplayer';
        $onFail = 'function()  {
			if (!(flashembed.getVersion()[0] > 0)) {
				var message = "<p>" + "' . $GLOBALS['TSFE']->sL('LLL:EXT:cms/locallang_ttc.xlf:media.needFlashPlugin') . '" + "</p>" + "<p>" + "<a href=\\"' . $flashDownloadUrl . '\\">' . $GLOBALS['TSFE']->sL('LLL:EXT:cms/locallang_ttc.xlf:media.downloadFlash') . '</a>" + "</p>";
				document.getElementById("' . $replaceElementIdString . '_flash_install_info").innerHTML = "<div class=\\"message\\">" + message + "</div>";
			}
		}';
        $flashConfiguration = json_encode($flashConfiguration);
        $flashConfiguration = str_replace('"###ONFAIL###"', $onFail, $flashConfiguration);
        $filename = isset($conf['file.']) ? $this->cObj->stdWrap($conf['file'], $conf['file.']) : $conf['file'];
        if ($filename) {
            if (strpos($filename, '://') !== FALSE) {
                $conf['flashvars.']['url'] = $filename;
            } else {
                if ($prefix) {
                    $conf['flashvars.']['url'] = $prefix . $filename;
                } else {
                    $conf['flashvars.']['url'] = str_repeat('../', substr_count($player, '/')) . $filename;
                }
            }
        }
        if (is_array($conf['sources'])) {
            foreach ($conf['sources'] as $key => $source) {
                if (strpos($source, '://') === FALSE) {
                    $conf['sources'][$key] = $prefix . $source;
                }
            }
        }
        if (is_array($conf['audioSources'])) {
            foreach ($conf['audioSources'] as $key => $source) {
                if (strpos($source, '://') === FALSE) {
                    $conf['audioSources'][$key] = $prefix . $source;
                }
            }
        }
        if (isset($conf['audioFallback']) && strpos($conf['audioFallback'], '://') === FALSE) {
            $conf['audioFallback'] = $prefix . $conf['audioFallback'];
        }
        if (isset($conf['caption']) && strpos($conf['caption'], '://') === FALSE) {
            $conf['caption'] = $prefix . $conf['caption'];
        }
        // Write calculated values in conf for the hook
        $conf['player'] = $player ?: $filename;
        $conf['installUrl'] = $installUrl;
        $conf['filename'] = $conf['flashvars.']['url'];
        $conf['prefix'] = $prefix;
        // merge with default parameters
        $conf['flashvars.'] = array_merge((array) $typeConf['default.']['flashvars.'], (array) $conf['flashvars.']);
        $conf['params.'] = array_merge((array) $typeConf['default.']['params.'], (array) $conf['params.']);
        $conf['attributes.'] = array_merge((array) $typeConf['default.']['attributes.'], (array) $conf['attributes.']);
        $conf['embedParams'] = 'flashvars, params, attributes';
        // Hook for manipulating the conf array, it's needed for some players like flowplayer
        if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/hooks/class.tx_cms_mediaitems.php']['swfParamTransform'])) {
            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/hooks/class.tx_cms_mediaitems.php']['swfParamTransform'] as $classRef) {
                \TYPO3\CMS\Core\Utility\GeneralUtility::callUserFunction($classRef, $conf, $this);
            }
        }
        // Flowplayer config
        $flowplayerVideoConfig = array();
        $flowplayerAudioConfig = array();
        if (is_array($conf['flashvars.']) && is_array($typeConf['mapping.']['flashvars.'])) {
            ArrayUtility::remapArrayKeys($conf['flashvars.'], $typeConf['mapping.']['flashvars.']);
        } else {
            $conf['flashvars.'] = array();
        }
        $conf['videoflashvars'] = $conf['flashvars.'];
        $conf['audioflashvars'] = $conf['flashvars.'];
        $conf['audioflashvars']['url'] = $conf['audioFallback'];
        // Render video sources
        $videoSources = '';
        if (is_array($conf['sources'])) {
            foreach ($conf['sources'] as $source) {
                $fileinfo = \TYPO3\CMS\Core\Utility\GeneralUtility::split_fileref($source);
                $mimeType = $this->mimeTypes[$fileinfo['fileext']]['video'];
                $videoSources .= '<source src="' . $source . '"' . ($mimeType ? ' type="' . $mimeType . '"' : '') . ' />' . LF;
            }
        }
        // Render audio sources
        $audioSources = '';
        if (is_array($conf['audioSources'])) {
            foreach ($conf['audioSources'] as $source) {
                $fileinfo = \TYPO3\CMS\Core\Utility\GeneralUtility::split_fileref($source);
                $mimeType = $this->mimeTypes[$fileinfo['fileext']]['audio'];
                $audioSources .= '<source src="' . $source . '"' . ($mimeType ? ' type="' . $mimeType . '"' : '') . ' />' . LF;
            }
        }
        // Configure captions
        if ($conf['type'] === 'video' && isset($conf['caption'])) {
            // Assemble captions track tag
            $videoCaptions = '<track id="' . $replaceElementIdString . '_captions_track" kind="captions" src="' . $conf['caption'] . '" default>' . LF;
            // Add videoJS extension for captions
            $pageRenderer->addJsFile($this->getPathToLibrary('videojs/video-js/controls/captions.js'));
            // Flowplayer captions
            $conf['videoflashvars']['captionUrl'] = $conf['caption'];
            // Flowplayer captions plugin configuration
            $flowplayerVideoConfig = array_merge_recursive($flowplayerVideoConfig, $this->flowplayerCaptionsConfig);
        }
        // Configure flowplayer audio fallback
        if (isset($conf['audioFallback'])) {
            $flowplayerAudioConfig = array_merge_recursive($flowplayerAudioConfig, $this->flowplayerAudioConfig);
        }
        // Configure audio description
        if ($conf['type'] == 'video') {
            if (is_array($conf['audioSources']) && count($conf['audioSources'])) {
                // Add videoJS audio description toggle
                $pageRenderer->addJsFile($this->getPathToLibrary('videojs/video-js/controls/audio-description.js'));
            }
            if (isset($conf['audioFallback'])) {
                // Audio description flowplayer config (remove controls)
                $flowplayerAudioConfig = array_merge_recursive($flowplayerAudioConfig, $this->flowplayerAudioDescriptionConfig);
            }
        }
        // Assemble Flowplayer configuration
        if (count($conf['videoflashvars'])) {
            $flowplayerVideoConfig = array_merge_recursive($flowplayerVideoConfig, array('clip' => $conf['videoflashvars']));
        }
        $flowplayerVideoJsonConfig = str_replace(array('"true"', '"false"'), array('true', 'false'), json_encode($flowplayerVideoConfig));
        if (count($conf['audioflashvars'])) {
            $flowplayerAudioConfig = array_merge_recursive($flowplayerAudioConfig, array('clip' => $conf['audioflashvars']));
        }
        $flowplayerAudioJsonConfig = str_replace(array('"true"', '"false"'), array('true', 'false'), json_encode($flowplayerAudioConfig));
        // Assemble param tags (required?)
        if (is_array($conf['params.']) && is_array($typeConf['mapping.']['params.'])) {
            ArrayUtility::remapArrayKeys($conf['params.'], $typeConf['mapping.']['params.']);
        }
        $videoFlashParams = '';
        if (is_array($conf['params.'])) {
            foreach ($conf['params.'] as $name => $value) {
                $videoFlashParams .= '<param name="' . $name . '" value="' . $value . '" />' . LF;
            }
        }
        $audioFlashParams = $videoFlashParams;
        // Required param tags
        $videoFlashParams .= '<param name="movie" value="' . $player . '" />' . LF;
        $videoFlashParams .= '<param name="flashvars" value=\'config=' . $flowplayerVideoJsonConfig . '\' />' . LF;
        $audioFlashParams .= '<param name="movie" value="' . $player . '" />' . LF;
        $audioFlashParams .= '<param name="flashvars" value=\'config=' . $flowplayerAudioJsonConfig . '\' />' . LF;
        // Assemble audio/video tag attributes
        $attributes = '';
        if (is_array($conf['attributes.']) && is_array($typeConf['attributes.']['params.'])) {
            ArrayUtility::remapArrayKeys($conf['attributes.'], $typeConf['attributes.']['params.']);
        }
        foreach ($this->html5TagAttributes as $attribute) {
            if ($conf['attributes.'][$attribute] === 'true' || $conf['attributes.'][$attribute] === strtolower($attribute) || $conf['attributes.'][$attribute] === $attribute) {
                $attributes .= strtolower($attribute) . '="' . strtolower($attribute) . '" ';
            }
        }
        // Media dimensions
        $width = isset($conf['width.']) ? $this->cObj->stdWrap($conf['width'], $conf['width.']) : $conf['width'];
        if (!$width) {
            $width = $conf[$type . '.']['defaultWidth'];
        }
        $height = isset($conf['height.']) ? $this->cObj->stdWrap($conf['height'], $conf['height.']) : $conf['height'];
        if (!$height) {
            $height = $conf[$type . '.']['defaultHeight'];
        }
        // Alternate content
        $alternativeContent = isset($conf['alternativeContent.']) ? $this->cObj->stdWrap($conf['alternativeContent'], $conf['alternativeContent.']) : $conf['alternativeContent'];
        // Render video
        if ($conf['type'] === 'video') {
            if ($conf['preferFlashOverHtml5']) {
                // Flash with video tag fallback
                $conf['params.']['playerFallbackOrder'] = array('flash', 'html5');
                $flashDivContent = $videoFlashParams . LF . '<video id="' . $replaceElementIdString . '_video_js" class="video-js" ' . $attributes . 'controls="controls"  mediagroup="' . $replaceElementIdString . '" width="' . $width . '" height="' . $height . '">' . LF . $videoSources . $videoCaptions . $alternativeContent . LF . '</video>' . LF;
                $divContent = '
					<div id="' . $replaceElementIdString . '_flash_install_info" class="flash-install-info"></div>' . LF . '<noscript>' . LF . '<object id="' . $replaceElementIdString . '_vjs_flash" type="application/x-shockwave-flash" data="' . $player . '" width="' . $width . '" height="' . $height . '">' . LF . $flashDivContent . '</object>' . LF . '</noscript>' . LF;
                $content = str_replace('###SWFOBJECT###', '<div id="' . $replaceElementIdString . '_video" class="flashcontainer" style="width:' . $width . 'px; height:' . $height . 'px;">' . LF . $divContent . '</div>', $content);
            } else {
                // Video tag with Flash fallback
                $conf['params.']['playerFallbackOrder'] = array('html5', 'flash');
                $videoTagContent = $videoSources . $videoCaptions;
                if (isset($conf['videoflashvars']['url'])) {
                    $videoTagContent .= '
						<noscript>' . LF . '<object class="vjs-flash-fallback" id="' . $replaceElementIdString . '_vjs_flash_fallback" type="application/x-shockwave-flash" data="' . $player . '" width="' . $width . '" height="' . $height . '">' . LF . $videoFlashParams . LF . $alternativeContent . LF . '</object>' . LF . '</noscript>';
                }
                $divContent = '
					<div id="' . $replaceElementIdString . '_flash_install_info" class="flash-install-info"></div>' . LF . '<video id="' . $replaceElementIdString . '_video_js" class="video-js" ' . $attributes . 'controls="controls" mediagroup="' . $replaceElementIdString . '" width="' . $width . '" height="' . $height . '">' . LF . $videoTagContent . '</video>';
                $content = str_replace('###SWFOBJECT###', '<div id="' . $replaceElementIdString . '_video" class="video-js-box" style="width:' . $width . 'px; height:' . $height . 'px;">' . LF . $divContent . '</div>', $content);
            }
        }
        // Render audio
        if ($conf['type'] === 'audio' || $audioSources || isset($conf['audioFallback'])) {
            if ($conf['preferFlashOverHtml5']) {
                // Flash with audio tag fallback
                $flashDivContent = $audioFlashParams . LF . '<audio id="' . $replaceElementIdString . '_audio_element"' . $attributes . ($conf['type'] === 'video' ? ' mediagroup="' . $replaceElementIdString . 'style="position:absolute;left:-10000px;"' : ' controls="controls"') . ' style="width:' . $width . 'px; height:' . $height . 'px;">' . LF . $audioSources . $alternativeContent . LF . '</audio>' . LF;
                $divContent = ($conf['type'] === 'video' ? '' : '<div id="' . $replaceElementIdString . '_flash_install_info" class="flash-install-info"></div>' . LF) . '<noscript>' . LF . '<object id="' . $replaceElementIdString . '_audio_flash" type="application/x-shockwave-flash" data="' . $player . '" width="' . ($conf['type'] === 'video' ? 0 : $width) . '" height="' . ($conf['type'] === 'video' ? 0 : $height) . '">' . LF . $flashDivContent . '</object>' . LF . '</noscript>' . LF;
                $audioContent = '<div id="' . $replaceElementIdString . '_audio_box" class="audio-flash-container" style="width:' . ($conf['type'] === 'video' ? 0 : $width) . 'px; height:' . ($conf['type'] === 'video' ? 0 : $height) . 'px;">' . LF . $divContent . '</div>';
            } else {
                // Audio tag with Flash fallback
                $audioTagContent = $audioSources;
                if (isset($conf['audioflashvars']['url'])) {
                    $audioTagContent .= '
						<noscript>' . LF . '<object class="audio-flash-fallback" id="' . $replaceElementIdString . '_audio_flash" type="application/x-shockwave-flash" data="' . $player . '" width="' . $width . '" height="' . $height . '">' . LF . $audioFlashParams . LF . $alternativeContent . LF . '</object>' . LF . '</noscript>';
                }
                $divContent = ($conf['type'] === 'video' ? '' : '<div id="' . $replaceElementIdString . '_flash_install_info" class="flash-install-info"></div>' . LF) . '<audio id="' . $replaceElementIdString . '_audio_element" class="audio-element"' . $attributes . ($conf['type'] === 'video' ? ' mediagroup="' . $replaceElementIdString . '" style="position:absolute;left:-10000px;"' : ' controls="controls"') . '>' . LF . $audioTagContent . '</audio>' . LF . $audioSourcesEmbeddingJsScript;
                $audioContent = '<div id="' . $replaceElementIdString . '_audio_box" class="audio-box" style="width:' . ($conf['type'] === 'video' ? 0 : $width) . 'px; height:' . ($conf['type'] === 'video' ? 0 : $height) . 'px;">' . LF . $divContent . '</div>';
            }
            if ($conf['type'] === 'audio') {
                $content = str_replace('###SWFOBJECT###', $audioContent, $content);
            } else {
                $content .= LF . $audioContent;
            }
        }
        // Assemble inline JS code
        $videoJsSetup = '';
        $flowplayerHandlers = '';
        if ($conf['type'] === 'video') {
            // Assemble videoJS options
            $videoJsOptions = array();
            foreach ($this->videoJsOptions as $videoJsOption) {
                if (isset($conf['params.'][$videoJsOption])) {
                    $videoJsOptions[$videoJsOption] = $conf['params.'][$videoJsOption];
                }
            }
            $videoJsOptions = count($videoJsOptions) ? json_encode($videoJsOptions) : '{}';
            // videoJS setup and videoJS listeners for audio description synchronisation
            if ($audioSources || isset($conf['audioFallback'])) {
                $videoJsSetup = '
			var ' . $replaceElementIdString . '_video = VideoJS.setup("' . $replaceElementIdString . '_video_js", ' . $videoJsOptions . ');
			var ' . $replaceElementIdString . '_video_element = document.getElementById("' . $replaceElementIdString . '_video_js");
			var ' . $replaceElementIdString . '_audio_element = document.getElementById("' . $replaceElementIdString . '_audio_element");
			if (!!' . $replaceElementIdString . '_video_element && !!' . $replaceElementIdString . '_audio_element) {
				' . $replaceElementIdString . '_audio_element.muted = true;
				VideoJS.addListener(' . $replaceElementIdString . '_video_element, "pause", function () { document.getElementById("' . $replaceElementIdString . '_audio_element").pause(); });
				VideoJS.addListener(' . $replaceElementIdString . '_video_element, "play", function () { try {document.getElementById("' . $replaceElementIdString . '_audio_element").currentTime = document.getElementById("' . $replaceElementIdString . '_video_js").currentTime} catch(e) {}; document.getElementById("' . $replaceElementIdString . '_audio_element").play(); });
				VideoJS.addListener(' . $replaceElementIdString . '_video_element, "seeked", function () { document.getElementById("' . $replaceElementIdString . '_audio_element").currentTime = document.getElementById("' . $replaceElementIdString . '_video_js").currentTime; });
				VideoJS.addListener(' . $replaceElementIdString . '_video_element, "volumechange", function () { document.getElementById("' . $replaceElementIdString . '_audio_element").volume = document.getElementById("' . $replaceElementIdString . '_video_js").volume; });
			}';
            } else {
                $videoJsSetup = '
			var ' . $replaceElementIdString . '_video = VideoJS.setup("' . $replaceElementIdString . '_video_js", ' . $videoJsOptions . ');
			';
            }
            // Prefer Flash or fallback to Flash
            $videoSourcesEmbedding = '';
            // If we have a video file for Flash
            if (isset($conf['filename'])) {
                // If we prefer Flash
                if ($conf['preferFlashOverHtml5']) {
                    $videoTagAssembly = '';
                    // Create "source" elements
                    if (is_array($conf['sources']) && count($conf['sources'])) {
                        foreach ($conf['sources'] as $source) {
                            $fileinfo = \TYPO3\CMS\Core\Utility\GeneralUtility::split_fileref($source);
                            $mimeType = $this->mimeTypes[$fileinfo['fileext']]['video'];
                            $videoTagAssembly .= '
			' . $replaceElementIdString . '_video_js.appendChild($f.extend(document.createElement("source"), {
				src: "' . $source . '",
				type: "' . $mimeType . '"
			}));';
                        }
                        // Create "track" elements
                        if (isset($conf['caption'])) {
                            // Assemble captions track tag
                            // It will take a while before the captions are loaded and parsed...
                            $videoTagAssembly .= '
			var track  = document.createElement("track");
			track.setAttribute("src", "' . $conf['caption'] . '");
			track.setAttribute("id", "' . $replaceElementIdString . '_captions_track");
			track.setAttribute("kind", "captions");
			track.setAttribute("default", "default");
			' . $replaceElementIdString . '_video_js.appendChild(track);';
                        }
                        $videoTagAssembly .= '
			$f.extend(' . $replaceElementIdString . '_video_js, {
				id: "' . $replaceElementIdString . '_video_js",
				className: "video-js",
				controls: "controls",
				mediagroup: "' . $replaceElementIdString . '",
				preload: "none",
				width: "' . $width . '",
				height: "' . $height . '"
			});
			' . $replaceElementIdString . '_video.appendChild(' . $replaceElementIdString . '_video_js);
			' . $replaceElementIdString . '_video.className = "video-js-box";';
                        $videoTagAssembly .= $videoJsSetup;
                    }
                    $videoSourcesEmbedding = '
		var ' . $replaceElementIdString . '_video = document.getElementById("' . $replaceElementIdString . '_video");
		var ' . $replaceElementIdString . '_video_js = document.createElement("video");
		if (flashembed.getVersion()[0] > 0) {
				// Flash is available
			var videoPlayer = flowplayer("' . $replaceElementIdString . '_video", ' . $flashConfiguration . ', ' . $flowplayerVideoJsonConfig . ').load();
			videoPlayer.onBeforeUnload(function () { return false; });
		} else if (!!' . $replaceElementIdString . '_video_js.canPlayType) {
				// Flash is not available: fallback to videoJS if video tag is supported
			' . $videoTagAssembly . '
		} else {
				// Neither Flash nor video is available: offer to install Flash
			flashembed("' . $replaceElementIdString . '_video", ' . $flashConfiguration . ');
		}';
                } elseif (is_array($conf['sources'])) {
                    // HTML5 is the preferred rendering method
                    // Test whether the browser supports any of types of the provided sources
                    $supported = array();
                    foreach ($conf['sources'] as $source) {
                        $fileinfo = \TYPO3\CMS\Core\Utility\GeneralUtility::split_fileref($source);
                        $mimeType = $this->mimeTypes[$fileinfo['fileext']]['video'];
                        $supported[] = $replaceElementIdString . '_videoTag.canPlayType("' . $mimeType . '") != ""';
                    }
                    // Testing whether the browser supports the video tag with any of the provided source types
                    // If no support, embed flowplayer
                    $videoSourcesEmbedding = '
		var ' . $replaceElementIdString . '_videoTag = document.createElement(\'video\');
		var ' . $replaceElementIdString . '_video_box = document.getElementById("' . $replaceElementIdString . '_video");
		if (' . $replaceElementIdString . '_video_box) {
			if (!' . $replaceElementIdString . '_videoTag || !' . $replaceElementIdString . '_videoTag.canPlayType || !(' . (count($supported) ? implode(' || ', $supported) : 'false') . ')) {
					// Avoid showing an empty video element
				if (document.getElementById("' . $replaceElementIdString . '_video_js")) {
					document.getElementById("' . $replaceElementIdString . '_video_js").style.display = "none";
				}
				if (flashembed.getVersion()[0] > 0) {
						// Flash is available
					var videoPlayer = flowplayer("' . $replaceElementIdString . '_video", ' . $flashConfiguration . ', ' . $flowplayerVideoJsonConfig . ').load();
					videoPlayer.onBeforeUnload(function () { return false; });
				} else {
						// Neither Flash nor video is available: offer to install Flash
					flashembed("' . $replaceElementIdString . '_video", ' . $flashConfiguration . ');
				}
			} else {' . $videoJsSetup . '
			}
		}';
                }
            }
        }
        // Audio fallback to Flash
        $audioSourcesEmbedding = '';
        // If we have an audio file for Flash
        if (isset($conf['audioFallback'])) {
            // If we prefer Flash in
            if ($conf['preferFlashOverHtml5']) {
                $audioTagAssembly = '';
                // Create "source" elements
                if (is_array($conf['audioSources']) && count($conf['audioSources'])) {
                    foreach ($conf['audioSources'] as $source) {
                        $fileinfo = \TYPO3\CMS\Core\Utility\GeneralUtility::split_fileref($source);
                        $mimeType = $this->mimeTypes[$fileinfo['fileext']]['audio'];
                        $audioTagAssembly .= '
		' . $replaceElementIdString . '_audio_element.appendChild($f.extend(document.createElement("source"), {
			src: "' . $source . '",
			type: "' . $mimeType . '"
		}));';
                    }
                    $audioTagAssembly .= '
		$f.extend(' . $replaceElementIdString . '_audio_element, {
			id: "' . $replaceElementIdString . '_audio_element",
			className: "audio-element",
			controls: "' . ($conf['type'] === 'video' ? '' : 'controls') . '",
			mediagroup: "' . $replaceElementIdString . '",
			preload: "none",
			width: "' . ($conf['type'] === 'video' ? 0 : $width) . 'px",
			height: "' . ($conf['type'] === 'video' ? 0 : $height) . 'px"
		});
		' . $replaceElementIdString . '_audio_box.appendChild(' . $replaceElementIdString . '_audio_element);
		' . $replaceElementIdString . '_audio_box.className = "audio-box";';
                }
                $audioSourcesEmbedding = '
		var ' . $replaceElementIdString . '_audio_box = document.getElementById("' . $replaceElementIdString . '_audio_box");
		var ' . $replaceElementIdString . '_audio_element = document.createElement("audio");
		if (flashembed.getVersion()[0] > 0) {
				// Flash is available
			var audioPlayer = flowplayer("' . $replaceElementIdString . '_audio_box", ' . $flashConfiguration . ', ' . $flowplayerAudioJsonConfig . ').load();
			audioPlayer.onBeforeUnload(function () { return false; });
			' . ($conf['type'] === 'video' ? 'audioPlayer.mute();' : '') . '
		} else if (!!' . $replaceElementIdString . '_audio_element.canPlayType) {
				// Flash is not available: fallback to audio element if audio tag is supported
			' . $audioTagAssembly . '
		} else {
				// Neither Flash nor audio is available: offer to install Flash if this is not an audio description of a video
			' . ($conf['type'] === 'video' ? '' : 'flashembed("' . $replaceElementIdString . '_audio_box", ' . $flashConfiguration . ');') . '
		}';
            } elseif (is_array($conf['audioSources'])) {
                // HTML5 is the preferred rendering method
                // Test whether the browser supports any of types of the provided sources
                $supported = array();
                foreach ($conf['audioSources'] as $source) {
                    $fileinfo = \TYPO3\CMS\Core\Utility\GeneralUtility::split_fileref($source);
                    $mimeType = $this->mimeTypes[$fileinfo['fileext']]['audio'];
                    $supported[] = $replaceElementIdString . '_audioTag.canPlayType("' . $mimeType . '") != ""';
                }
                // Testing whether the browser supports the audio tag with any of the provided source types
                // If no support, embed flowplayer
                $audioSourcesEmbedding = '
		var ' . $replaceElementIdString . '_audioTag = document.createElement(\'audio\');
		var ' . $replaceElementIdString . '_audio_box = document.getElementById("' . $replaceElementIdString . '_audio_box");
		if (' . $replaceElementIdString . '_audio_box) {
			if (!' . $replaceElementIdString . '_audioTag || !' . $replaceElementIdString . '_audioTag.canPlayType || !(' . (count($supported) ? implode(' || ', $supported) : 'false') . ')) {
					// Avoid showing an empty audio element
				if (document.getElementById("' . $replaceElementIdString . '_audio_element")) {
					document.getElementById("' . $replaceElementIdString . '_audio_element").style.display = "none";
				}
				if (flashembed.getVersion()[0] > 0) {
					var audioPlayer = flowplayer("' . $replaceElementIdString . '_audio_box", ' . $flashConfiguration . ', ' . $flowplayerAudioJsonConfig . ').load();
					audioPlayer.onBeforeUnload(function () { return false; });
					' . ($conf['type'] === 'video' ? 'audioPlayer.mute()' : '') . '
				} else {
						// Neither Flash nor audio is available: offer to install Flash if this is not an audio description of a video
					' . ($conf['type'] === 'video' ? '' : 'flashembed("' . $replaceElementIdString . '_audio_box", ' . $flashConfiguration . ');') . '
				}
			}
		}';
            }
            // Flowplayer eventHandlers for audio description synchronisation
            $flowplayerHandlers = '';
            if ($conf['type'] === 'video') {
                $flowplayerHandlers = '
		if (flashembed.getVersion()[0] > 0) {
				// Flash is available
			var videoPlayer = flowplayer("' . $replaceElementIdString . '_video");
			if (videoPlayer) {
					// Control audio description through video control bar
				videoPlayer.onVolume(function (volume) { flowplayer("' . $replaceElementIdString . '_audio_box").setVolume(volume); });
				videoPlayer.onMute(function () { flowplayer("' . $replaceElementIdString . '_audio_box").mute(); });
				videoPlayer.onUnmute(function () { flowplayer("' . $replaceElementIdString . '_audio_box").unmute(); });
				videoPlayer.onPause(function () { flowplayer("' . $replaceElementIdString . '_audio_box").pause(); });
				videoPlayer.onResume(function () { flowplayer("' . $replaceElementIdString . '_audio_box").resume(); });
				videoPlayer.onStart(function () { flowplayer("' . $replaceElementIdString . '_audio_box").play(); });
				videoPlayer.onStop(function () { flowplayer("' . $replaceElementIdString . '_audio_box").stop(); });
				videoPlayer.onSeek(function (clip, seconds) { flowplayer("' . $replaceElementIdString . '_audio_box").seek(seconds); });
					// Mute audio description on start
				flowplayer("' . $replaceElementIdString . '_audio_box").onStart(function () { this.mute()});
					// Audio description toggle
				var videoContainer = document.getElementById("' . $replaceElementIdString . '_video");
				var buttonContainer = document.createElement("div");
				$f.extend(buttonContainer, {
					id: "' . $replaceElementIdString . '_audio_description_toggle",
					className: "vjs-audio-description-control"
				});
				var button = document.createElement("div");
				buttonContainer.appendChild(button);
				buttonContainer.style.position = "relative";
				buttonContainer.style.left = (parseInt(' . $width . ', 10)-27) + "px";
				videoContainer.parentNode.insertBefore(buttonContainer, videoContainer.nextSibling);
				VideoJS.addListener(buttonContainer, "click", function () {
					var buttonContainer = document.getElementById("' . $replaceElementIdString . '_audio_description_toggle");
					var state = buttonContainer.getAttribute("data-state");
					if (state == "enabled") {
						buttonContainer.setAttribute("data-state", "disabled");
						flowplayer("' . $replaceElementIdString . '_audio_box").mute();
					} else {
						buttonContainer.setAttribute("data-state", "enabled");
						flowplayer("' . $replaceElementIdString . '_audio_box").unmute();
					}
				});
			}
		}';
            }
        }
        // Wrap up inline JS code
        $jsInlineCode = $audioSourcesEmbedding . $videoSourcesEmbedding . $flowplayerHandlers;
        if ($jsInlineCode) {
            $jsInlineCode = 'VideoJS.DOMReady(function(){' . $jsInlineCode . LF . '});';
        }
        $pageRenderer->addJsInlineCode($replaceElementIdString, $jsInlineCode);
        if (isset($conf['stdWrap.'])) {
            $content = $this->cObj->stdWrap($content, $conf['stdWrap.']);
        }
        return $content;
    }
Example #20
0
 /**
  * Set mode by file
  *
  * @param string $file
  * @return string
  */
 public function setModeByFile($file)
 {
     $fileInfo = \TYPO3\CMS\Core\Utility\GeneralUtility::split_fileref($file);
     return $this->setModeByType($fileInfo['fileext']);
 }
 /**
  * Rendering the cObject, MULTIMEDIA
  *
  * @param array $conf Array of TypoScript properties
  * @return string Output
  */
 public function render($conf = array())
 {
     $content = '';
     $filename = isset($conf['file.']) ? $this->cObj->stdWrap($conf['file'], $conf['file.']) : $conf['file'];
     $incFile = $GLOBALS['TSFE']->tmpl->getFileName($filename);
     if ($incFile) {
         $fileinfo = \TYPO3\CMS\Core\Utility\GeneralUtility::split_fileref($incFile);
         if (\TYPO3\CMS\Core\Utility\GeneralUtility::inList('txt,html,htm', $fileinfo['fileext'])) {
             $content = $GLOBALS['TSFE']->tmpl->fileContent($incFile);
         } else {
             // Default params...
             $parArray = array();
             // Src is added
             $width = isset($conf['width.']) ? $this->cObj->stdWrap($conf['width'], $conf['width.']) : $conf['width'];
             if (!$width) {
                 $width = 200;
             }
             $height = isset($conf['height.']) ? $this->cObj->stdWrap($conf['height'], $conf['height.']) : $conf['height'];
             if (!$height) {
                 $height = 200;
             }
             $parArray['src'] = 'src="' . $GLOBALS['TSFE']->absRefPrefix . $incFile . '"';
             if (\TYPO3\CMS\Core\Utility\GeneralUtility::inList('au,wav,mp3', $fileinfo['fileext'])) {
             }
             if (\TYPO3\CMS\Core\Utility\GeneralUtility::inList('avi,mov,mpg,asf,wmv', $fileinfo['fileext'])) {
                 $parArray['width'] = 'width="' . $width . '"';
                 $parArray['height'] = 'height="' . $height . '"';
             }
             if (\TYPO3\CMS\Core\Utility\GeneralUtility::inList('swf,swa,dcr', $fileinfo['fileext'])) {
                 $parArray['quality'] = 'quality="high"';
                 $parArray['width'] = 'width="' . $width . '"';
                 $parArray['height'] = 'height="' . $height . '"';
             }
             if (\TYPO3\CMS\Core\Utility\GeneralUtility::inList('class', $fileinfo['fileext'])) {
                 $parArray['width'] = 'width="' . $width . '"';
                 $parArray['height'] = 'height="' . $height . '"';
             }
             // fetching params
             $params = isset($conf['params.']) ? $this->cObj->stdWrap($conf['params'], $conf['params.']) : $conf['params'];
             $lines = explode(LF, $params);
             foreach ($lines as $l) {
                 $parts = explode('=', $l);
                 $parameter = strtolower(trim($parts[0]));
                 $value = trim($parts[1]);
                 if ((string) $value != '') {
                     $parArray[$parameter] = $parameter . '="' . htmlspecialchars($value) . '"';
                 } else {
                     unset($parArray[$parameter]);
                 }
             }
             if ($fileinfo['fileext'] == 'class') {
                 unset($parArray['src']);
                 $parArray['code'] = 'code="' . htmlspecialchars($fileinfo['file']) . '"';
                 $parArray['codebase'] = 'codebase="' . htmlspecialchars($fileinfo['path']) . '"';
                 $content = '<applet ' . implode(' ', $parArray) . '></applet>';
             } else {
                 $content = '<embed ' . implode(' ', $parArray) . '></embed>';
             }
         }
     }
     if (isset($conf['stdWrap.'])) {
         $content = $this->cObj->stdWrap($content, $conf['stdWrap.']);
     }
     return $content;
 }
Example #22
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;
     }
 }
Example #23
0
 /**
  * Rendering the cObject, MEDIA
  *
  * @param array $conf Array of TypoScript properties
  * @return string Output
  */
 public function render($conf = array())
 {
     $content = '';
     // Add flex parameters to configuration
     $flexParams = isset($conf['flexParams.']) ? $this->cObj->stdWrap($conf['flexParams'], $conf['flexParams.']) : $conf['flexParams'];
     if ($flexParams[0] === '<') {
         // It is a content element rather a TS object
         $flexParams = \TYPO3\CMS\Core\Utility\GeneralUtility::xml2array($flexParams, 'T3');
         foreach ($flexParams['data'] as $sheetData) {
             $this->cObj->readFlexformIntoConf($sheetData['lDEF'], $conf['parameter.'], TRUE);
         }
     }
     // Type is video or audio
     $conf['type'] = $this->doFlexFormOverlay($conf, 'type');
     // Video sources
     $sources = $this->doFlexFormOverlay($conf, 'sources', 'mmSourcesContainer');
     if (is_array($sources) && !empty($sources)) {
         $conf['sources'] = array();
         foreach ($sources as $key => $source) {
             if (isset($source['mmSource'])) {
                 $source = $source['mmSource'];
                 $conf['sources'][$key] = $this->retrieveMediaUrl($source);
             }
         }
     } else {
         unset($conf['sources']);
     }
     // Video fallback and backward compatibility file
     $videoFallback = $this->doFlexFormOverlay($conf, 'file');
     // Backward compatibility file
     if ($videoFallback !== NULL) {
         $conf['file'] = $this->retrieveMediaUrl($videoFallback);
     } else {
         unset($conf['file']);
     }
     // Audio sources
     $audioSources = $this->doFlexFormOverlay($conf, 'audioSources', 'mmAudioSourcesContainer');
     if (is_array($audioSources) && !empty($audioSources)) {
         $conf['audioSources'] = array();
         foreach ($audioSources as $key => $source) {
             if (isset($source['mmAudioSource'])) {
                 $source = $source['mmAudioSource'];
                 $conf['audioSources'][$key] = $this->retrieveMediaUrl($source);
             }
         }
     } else {
         unset($conf['audioSources']);
     }
     // Audio fallback
     $audioFallback = $this->doFlexFormOverlay($conf, 'audioFallback');
     if ($audioFallback) {
         $conf['audioFallback'] = $this->retrieveMediaUrl($audioFallback);
     } else {
         unset($conf['audioFallback']);
     }
     // Caption file
     $caption = $this->doFlexFormOverlay($conf, 'caption');
     if ($caption) {
         $conf['caption'] = $this->retrieveMediaUrl($caption);
     } else {
         unset($conf['caption']);
     }
     // Establish render type
     $renderType = $this->doFlexFormOverlay($conf, 'renderType');
     $conf['preferFlashOverHtml5'] = 0;
     if ($renderType === 'preferFlashOverHtml5') {
         $renderType = 'auto';
     }
     if ($renderType === 'auto') {
         // Default renderType is swf
         $renderType = 'swf';
         $handler = array_keys($conf['fileExtHandler.']);
         if ($conf['type'] === 'video') {
             $fileinfo = \TYPO3\CMS\Core\Utility\GeneralUtility::split_fileref($conf['file']);
         } else {
             $fileinfo = \TYPO3\CMS\Core\Utility\GeneralUtility::split_fileref($conf['audioFallback']);
         }
         if (in_array($fileinfo['fileext'], $handler)) {
             $renderType = strtolower($conf['fileExtHandler.'][$fileinfo['fileext']]);
         }
     }
     $mime = $renderType . 'object';
     $typeConf = $conf['mimeConf.'][$mime . '.'][$conf['type'] . '.'] ?: array();
     $conf['predefined'] = array();
     // Width and height
     $conf['width'] = (int) $this->doFlexFormOverlay($conf, 'width');
     $conf['height'] = (int) $this->doFlexFormOverlay($conf, 'height');
     if (is_array($conf['parameter.']['mmMediaOptions'])) {
         foreach ($conf['parameter.']['mmMediaOptions'] as $key => $value) {
             if ($key == 'mmMediaCustomParameterContainer') {
                 foreach ($value as $val) {
                     // Custom parameter entry
                     $rawTS = $val['mmParamCustomEntry'];
                     // Read and merge
                     $tmp = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(LF, $rawTS);
                     if (!empty($tmp)) {
                         foreach ($tmp as $tsLine) {
                             if ($tsLine[0] !== '#' && ($pos = strpos($tsLine, '.'))) {
                                 $parts[0] = substr($tsLine, 0, $pos);
                                 $parts[1] = substr($tsLine, $pos + 1);
                                 $valueParts = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode('=', $parts[1], TRUE);
                                 switch (strtolower($parts[0])) {
                                     case 'flashvars':
                                         $conf['flashvars.'][$valueParts[0]] = $valueParts[1];
                                         break;
                                     case 'params':
                                         $conf['params.'][$valueParts[0]] = $valueParts[1];
                                         break;
                                     case 'attributes':
                                         $conf['attributes.'][$valueParts[0]] = $valueParts[1];
                                         break;
                                 }
                             }
                         }
                     }
                 }
             } elseif ($key == 'mmMediaOptionsContainer') {
                 foreach ($value as $val) {
                     if (isset($val['mmParamSet'])) {
                         $pName = $val['mmParamName'];
                         $pSet = $val['mmParamSet'];
                         $pValue = $pSet == 2 ? $val['mmParamValue'] : ($pSet == 0 ? 'false' : 'true');
                         $conf['predefined'][$pName] = $pValue;
                     }
                 }
             }
         }
     }
     if ($renderType === 'swf' && $this->doFlexFormOverlay($conf, 'useHTML5')) {
         $renderType = 'flowplayer';
     }
     if ($conf['type'] === 'audio' && !isset($conf['audioSources'])) {
         $renderType = 'swf';
     }
     if ($renderType !== 'qt' && $renderType !== 'embed' && $conf['type'] == 'video') {
         if (isset($conf['file']) && (strpos($conf['file'], '.swf') !== FALSE || strpos($conf['file'], '://') !== FALSE && strpos(\TYPO3\CMS\Core\Utility\GeneralUtility::getUrl($conf['file'], 2), 'application/x-shockwave-flash') !== FALSE)) {
             $conf = array_merge((array) $conf['mimeConf.']['swfobject.'], $conf);
             $conf[$conf['type'] . '.']['player'] = strpos($conf['file'], '://') === FALSE ? 'http://' . $conf['file'] : $conf['file'];
             $conf['installUrl'] = 'null';
             $conf['forcePlayer'] = 0;
             $renderType = 'swf';
         } elseif (isset($conf['file']) && strpos($conf['file'], '://') !== FALSE) {
             $mediaWizard = \TYPO3\CMS\Mediace\MediaWizard\MediaWizardProviderManager::getValidMediaWizardProvider($conf['file']);
             if ($mediaWizard !== NULL) {
                 $conf['installUrl'] = 'null';
                 $conf['forcePlayer'] = 0;
                 $renderType = 'swf';
             }
         } elseif (isset($conf['file']) && !isset($conf['caption']) && !isset($conf['sources'])) {
             $renderType = 'swf';
             $conf['forcePlayer'] = 1;
         }
     }
     switch ($renderType) {
         case 'flowplayer':
             $conf[$conf['type'] . '.'] = array_merge((array) $conf['mimeConf.']['flowplayer.'][$conf['type'] . '.'], $typeConf);
             $conf = array_merge((array) $conf['mimeConf.']['flowplayer.'], $conf);
             unset($conf['mimeConf.']);
             $conf['attributes.'] = array_merge((array) $conf['attributes.'], $conf['predefined']);
             $conf['params.'] = array_merge((array) $conf['params.'], $conf['predefined']);
             $conf['flashvars.'] = array_merge((array) $conf['flashvars.'], $conf['predefined']);
             $content = $this->cObj->cObjGetSingle('FLOWPLAYER', $conf);
             break;
         case 'swf':
             $conf[$conf['type'] . '.'] = array_merge((array) $conf['mimeConf.']['swfobject.'][$conf['type'] . '.'], $typeConf);
             $conf = array_merge((array) $conf['mimeConf.']['swfobject.'], $conf);
             unset($conf['mimeConf.']);
             $conf['flashvars.'] = array_merge((array) $conf['flashvars.'], $conf['predefined']);
             $content = $this->cObj->cObjGetSingle('SWFOBJECT', $conf);
             break;
         case 'qt':
             $conf[$conf['type'] . '.'] = array_merge($conf['mimeConf.']['swfobject.'][$conf['type'] . '.'], $typeConf);
             $conf = array_merge($conf['mimeConf.']['qtobject.'], $conf);
             unset($conf['mimeConf.']);
             $conf['params.'] = array_merge((array) $conf['params.'], $conf['predefined']);
             $content = $this->cObj->cObjGetSingle('QTOBJECT', $conf);
             break;
         case 'embed':
             $paramsArray = array_merge((array) $typeConf['default.']['params.'], (array) $conf['params.'], $conf['predefined']);
             $conf['params'] = '';
             foreach ($paramsArray as $key => $value) {
                 $conf['params'] .= $key . '=' . $value . LF;
             }
             $content = $this->cObj->cObjGetSingle('MULTIMEDIA', $conf);
             break;
         default:
             if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/hooks/class.tx_cms_mediaitems.php']['customMediaRender'])) {
                 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/hooks/class.tx_cms_mediaitems.php']['customMediaRender'] as $classRef) {
                     $hookObj = \TYPO3\CMS\Core\Utility\GeneralUtility::getUserObj($classRef);
                     $conf['file'] = $videoFallback;
                     $conf['mode'] = is_file(PATH_site . $videoFallback) ? 'file' : 'url';
                     if (method_exists($hookObj, 'customMediaRender')) {
                         $content = $hookObj->customMediaRender($renderType, $conf, $this);
                     }
                 }
             }
             if (isset($conf['stdWrap.'])) {
                 $content = $this->cObj->stdWrap($content, $conf['stdWrap.']);
             }
     }
     return $content;
 }
 /**
  * Creates a list of links to files.
  * Implements the stdWrap property "filelink"
  *
  * @param string $theValue The filename to link to, possibly prefixed with $conf[path]
  * @param array $conf TypoScript parameters for the TypoScript function ->filelink
  * @return string The link to the file possibly with icons, thumbnails, size in bytes shown etc.
  * @access private
  * @see stdWrap()
  * @todo Define visibility
  */
 public function filelink($theValue, $conf)
 {
     $conf['path'] = isset($conf['path.']) ? $this->stdWrap($conf['path'], $conf['path.']) : $conf['path'];
     $theFile = trim($conf['path']) . $theValue;
     if (@is_file($theFile)) {
         $theFileEnc = str_replace('%2F', '/', rawurlencode($theFile));
         $title = $conf['title'];
         if (isset($conf['title.'])) {
             $title = $this->stdWrap($title, $conf['title.']);
         }
         $target = $conf['target'];
         if (isset($conf['target.'])) {
             $target = $this->stdWrap($target, $conf['target.']);
         }
         // The jumpURL feature will be taken care of by typoLink, only "jumpurl.secure = 1" is applyable needed for special link creation
         if ($conf['jumpurl.']['secure']) {
             $alternativeJumpUrlParameter = isset($conf['jumpurl.']['parameter.']) ? $this->stdWrap($conf['jumpurl.']['parameter'], $conf['jumpurl.']['parameter.']) : $conf['jumpurl.']['parameter'];
             $typoLinkConf = array('parameter' => $alternativeJumpUrlParameter ? $alternativeJumpUrlParameter : $GLOBALS['TSFE']->id . ',' . $GLOBALS['TSFE']->type, 'fileTarget' => $target, 'title' => $title, 'ATagParams' => $this->getATagParams($conf), 'additionalParams' => '&jumpurl=' . rawurlencode($theFileEnc) . $this->locDataJU($theFileEnc, $conf['jumpurl.']['secure.']) . $GLOBALS['TSFE']->getMethodUrlIdToken);
         } else {
             $typoLinkConf = array('parameter' => $theFileEnc, 'fileTarget' => $target, 'title' => $title, 'ATagParams' => $this->getATagParams($conf));
         }
         // If the global jumpURL feature is activated, but is disabled for this
         // filelink, the global parameter needs to be disabled as well for this link creation
         $globalJumpUrlEnabled = $GLOBALS['TSFE']->config['config']['jumpurl_enable'];
         if ($globalJumpUrlEnabled && isset($conf['jumpurl']) && $conf['jumpurl'] == 0) {
             $GLOBALS['TSFE']->config['config']['jumpurl_enable'] = 0;
         } elseif (!$globalJumpUrlEnabled && $conf['jumpurl']) {
             $GLOBALS['TSFE']->config['config']['jumpurl_enable'] = 1;
         }
         $theLinkWrap = $this->typoLink('|', $typoLinkConf);
         // Now the original value is set again
         $GLOBALS['TSFE']->config['config']['jumpurl_enable'] = $globalJumpUrlEnabled;
         $theSize = filesize($theFile);
         $fI = GeneralUtility::split_fileref($theFile);
         if ($conf['icon']) {
             $conf['icon.']['path'] = isset($conf['icon.']['path.']) ? $this->stdWrap($conf['icon.']['path'], $conf['icon.']['path.']) : $conf['icon.']['path'];
             $iconP = !empty($conf['icon.']['path']) ? $conf['icon.']['path'] : TYPO3_mainDir . '/gfx/fileicons/';
             $conf['icon.']['ext'] = isset($conf['icon.']['ext.']) ? $this->stdWrap($conf['icon.']['ext'], $conf['icon.']['ext.']) : $conf['icon.']['ext'];
             $iconExt = !empty($conf['icon.']['ext']) ? '.' . $conf['icon.']['ext'] : '.gif';
             $icon = @is_file($iconP . $fI['fileext'] . $iconExt) ? $iconP . $fI['fileext'] . $iconExt : $iconP . 'default' . $iconExt;
             // Checking for images: If image, then return link to thumbnail.
             $IEList = isset($conf['icon_image_ext_list.']) ? $this->stdWrap($conf['icon_image_ext_list'], $conf['icon_image_ext_list.']) : $conf['icon_image_ext_list'];
             $image_ext_list = str_replace(' ', '', strtolower($IEList));
             if ($fI['fileext'] && GeneralUtility::inList($image_ext_list, $fI['fileext'])) {
                 if ($conf['iconCObject']) {
                     $icon = $this->cObjGetSingle($conf['iconCObject'], $conf['iconCObject.'], 'iconCObject');
                 } else {
                     if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['thumbnails']) {
                         $thumbSize = '';
                         if ($conf['icon_thumbSize'] || $conf['icon_thumbSize.']) {
                             $thumbSize = '&size=' . (isset($conf['icon_thumbSize.']) ? $this->stdWrap($conf['icon_thumbSize'], $conf['icon_thumbSize.']) : $conf['icon_thumbSize']);
                         }
                         $check = basename($theFile) . ':' . filemtime($theFile) . ':' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
                         $md5sum = '&md5sum=' . md5($check);
                         $icon = 'typo3/thumbs.php?file=' . rawurlencode('../' . $theFile) . $thumbSize . $md5sum;
                     } else {
                         $icon = TYPO3_mainDir . 'gfx/fileicons/notfound_thumb.gif';
                     }
                     $icon = '<img src="' . htmlspecialchars($GLOBALS['TSFE']->absRefPrefix . $icon) . '"' . $this->getBorderAttr(' border="0"') . '' . $this->getAltParam($conf) . ' />';
                 }
             } else {
                 $conf['icon.']['widthAttribute'] = isset($conf['icon.']['widthAttribute.']) ? $this->stdWrap($conf['icon.']['widthAttribute'], $conf['icon.']['widthAttribute.']) : $conf['icon.']['widthAttribute'];
                 $iconWidth = !empty($conf['icon.']['widthAttribute']) ? $conf['icon.']['widthAttribute'] : 18;
                 $conf['icon.']['heightAttribute'] = isset($conf['icon.']['heightAttribute.']) ? $this->stdWrap($conf['icon.']['heightAttribute'], $conf['icon.']['heightAttribute.']) : $conf['icon.']['heightAttribute'];
                 $iconHeight = !empty($conf['icon.']['heightAttribute']) ? $conf['icon.']['heightAttribute'] : 16;
                 $icon = '<img src="' . htmlspecialchars($GLOBALS['TSFE']->absRefPrefix . $icon) . '" width="' . $iconWidth . '" height="' . $iconHeight . '"' . $this->getBorderAttr(' border="0"') . $this->getAltParam($conf) . ' />';
             }
             if ($conf['icon_link'] && !$conf['combinedLink']) {
                 $icon = $this->wrap($icon, $theLinkWrap);
             }
             $icon = isset($conf['icon.']) ? $this->stdWrap($icon, $conf['icon.']) : $icon;
         }
         if ($conf['size']) {
             $size = isset($conf['size.']) ? $this->stdWrap($theSize, $conf['size.']) : $theSize;
         }
         // Wrapping file label
         if ($conf['removePrependedNumbers']) {
             $theValue = preg_replace('/_[0-9][0-9](\\.[[:alnum:]]*)$/', '\\1', $theValue);
         }
         if (isset($conf['labelStdWrap.'])) {
             $theValue = $this->stdWrap($theValue, $conf['labelStdWrap.']);
         }
         // Wrapping file
         $wrap = isset($conf['wrap.']) ? $this->stdWrap($conf['wrap'], $conf['wrap.']) : $conf['wrap'];
         if ($conf['combinedLink']) {
             $theValue = $icon . $theValue;
             if ($conf['ATagBeforeWrap']) {
                 $theValue = $this->wrap($this->wrap($theValue, $wrap), $theLinkWrap);
             } else {
                 $theValue = $this->wrap($this->wrap($theValue, $theLinkWrap), $wrap);
             }
             $file = isset($conf['file.']) ? $this->stdWrap($theValue, $conf['file.']) : $theValue;
             // output
             $output = $file . $size;
         } else {
             if ($conf['ATagBeforeWrap']) {
                 $theValue = $this->wrap($this->wrap($theValue, $wrap), $theLinkWrap);
             } else {
                 $theValue = $this->wrap($this->wrap($theValue, $theLinkWrap), $wrap);
             }
             $file = isset($conf['file.']) ? $this->stdWrap($theValue, $conf['file.']) : $theValue;
             // output
             $output = $icon . $file . $size;
         }
         if (isset($conf['stdWrap.'])) {
             $output = $this->stdWrap($output, $conf['stdWrap.']);
         }
         return $output;
     }
 }
 /**
  * Set mode by file
  *
  * @param string $file
  * @return string
  */
 public function setModeByFile($file)
 {
     $fileInfo = GeneralUtility::split_fileref($file);
     // @TODO: @FIXME: the method setModeByType returns void, so this method will never return a string
     return $this->setModeByType($fileInfo['fileext']);
 }
 /**
  * @param $fileref
  * @return array
  * @see t3lib_div::split_fileref
  */
 public function split_fileref($fileref)
 {
     return GeneralUtility::split_fileref($fileref);
 }
 /**
  * @test
  */
 public function splitFileRefReturnsFileTypeForFilesWithoutPathSite()
 {
     $testFile = 'fileadmin/media/someFile.png';
     $fileInfo = Utility\GeneralUtility::split_fileref($testFile);
     $this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_ARRAY, $fileInfo);
     $this->assertEquals('fileadmin/media/', $fileInfo['path']);
     $this->assertEquals('someFile.png', $fileInfo['file']);
     $this->assertEquals('someFile', $fileInfo['filebody']);
     $this->assertEquals('png', $fileInfo['fileext']);
 }
Example #28
0
 /**
  * Like ->getHeader() but for files in the File>* main module/submodules
  * Returns the file-icon with the path of the file set in the alt/title attribute. Shows the file-name after the icon.
  *
  * @param string $title Title string, expected to be the filepath
  * @param string $path Alt text
  * @param string $iconfile The icon file (relative to TYPO3 dir)
  * @return string HTML content
  * @deprecated since 6.2 remove 2 version later use getResourceHeader() instead
  */
 public function getFileheader($title, $path, $iconfile)
 {
     GeneralUtility::logDeprecatedFunction();
     $fileInfo = GeneralUtility::split_fileref($title);
     $title = htmlspecialchars(GeneralUtility::fixed_lgd_cs($fileInfo['path'], -35)) . '<strong>' . htmlspecialchars($fileInfo['file']) . '</strong>';
     return '<span class="typo3-moduleHeader"><img' . IconUtility::skinImg($this->backPath, $iconfile, 'width="18" height="16"') . ' title="' . htmlspecialchars($path) . '" alt="" />' . $title . '</span>';
 }
Example #29
0
 /**
  * Add file relation entries for a record's rels-array
  *
  * @param array $rels Array of file IDs
  * @param array $lines Output lines array (is passed by reference and modified)
  * @param string $preCode Pre-HTML code
  * @param string $htmlColorClass Alternative HTML color class to use.
  * @param string $tokenID Token ID if this is a softreference (in which case it only makes sense with a single element in the $rels array!)
  * @return void
  * @access private
  * @see singleRecordLines()
  */
 public function addFiles($rels, &$lines, $preCode, $htmlColorClass = '', $tokenID = '')
 {
     foreach ($rels as $ID) {
         // Process file:
         $pInfo = array();
         $fI = $this->dat['header']['files'][$ID];
         if (!is_array($fI)) {
             if (!$tokenID || $this->includeSoftref($tokenID)) {
                 $pInfo['msg'] = 'MISSING FILE: ' . $ID;
                 $this->error('MISSING FILE: ' . $ID);
             } else {
                 return;
             }
         }
         $pInfo['preCode'] = $preCode . '&nbsp;&nbsp;&nbsp;&nbsp;' . $this->iconFactory->getIcon('status-status-reference-hard', Icon::SIZE_SMALL)->render();
         $pInfo['title'] = htmlspecialchars($fI['filename']);
         $pInfo['ref'] = 'FILE';
         $pInfo['size'] = $fI['filesize'];
         $pInfo['class'] = $htmlColorClass ?: 'bgColor3';
         $pInfo['type'] = 'file';
         // If import mode and there is a non-RTE softreference, check the destination directory:
         if ($this->mode === 'import' && $tokenID && !$fI['RTE_ORIG_ID']) {
             if (isset($fI['parentRelFileName'])) {
                 $pInfo['msg'] = 'Seems like this file is already referenced from within an HTML/CSS file. That takes precedence. ';
             } else {
                 $testDirPrefix = PathUtility::dirname($fI['relFileName']) . '/';
                 $testDirPrefix2 = $this->verifyFolderAccess($testDirPrefix);
                 if (!$testDirPrefix2) {
                     $pInfo['msg'] = 'ERROR: There are no available filemounts to write file in! ';
                 } elseif ($testDirPrefix !== $testDirPrefix2) {
                     $pInfo['msg'] = 'File will be attempted written to "' . $testDirPrefix2 . '". ';
                 }
             }
             // Check if file exists:
             if (file_exists(PATH_site . $fI['relFileName'])) {
                 if ($this->update) {
                     $pInfo['updatePath'] .= 'File exists.';
                 } else {
                     $pInfo['msg'] .= 'File already exists! ';
                 }
             }
             // Check extension:
             $fileProcObj = $this->getFileProcObj();
             if ($fileProcObj->actionPerms['addFile']) {
                 $testFI = GeneralUtility::split_fileref(PATH_site . $fI['relFileName']);
                 if (!$this->allowPHPScripts && !$fileProcObj->checkIfAllowed($testFI['fileext'], $testFI['path'], $testFI['file'])) {
                     $pInfo['msg'] .= 'File extension was not allowed!';
                 }
             } else {
                 $pInfo['msg'] = 'You user profile does not allow you to create files on the server!';
             }
         }
         $pInfo['showDiffContent'] = PathUtility::stripPathSitePrefix($this->fileIDMap[$ID]);
         $lines[] = $pInfo;
         unset($this->remainHeader['files'][$ID]);
         // RTE originals:
         if ($fI['RTE_ORIG_ID']) {
             $ID = $fI['RTE_ORIG_ID'];
             $pInfo = array();
             $fI = $this->dat['header']['files'][$ID];
             if (!is_array($fI)) {
                 $pInfo['msg'] = 'MISSING RTE original FILE: ' . $ID;
                 $this->error('MISSING RTE original FILE: ' . $ID);
             }
             $pInfo['showDiffContent'] = PathUtility::stripPathSitePrefix($this->fileIDMap[$ID]);
             $pInfo['preCode'] = $preCode . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' . $this->iconFactory->getIcon('status-status-reference-hard', Icon::SIZE_SMALL)->render();
             $pInfo['title'] = htmlspecialchars($fI['filename']) . ' <em>(Original)</em>';
             $pInfo['ref'] = 'FILE';
             $pInfo['size'] = $fI['filesize'];
             $pInfo['class'] = $htmlColorClass ?: 'bgColor3';
             $pInfo['type'] = 'file';
             $lines[] = $pInfo;
             unset($this->remainHeader['files'][$ID]);
         }
         // External resources:
         if (is_array($fI['EXT_RES_ID'])) {
             foreach ($fI['EXT_RES_ID'] as $extID) {
                 $pInfo = array();
                 $fI = $this->dat['header']['files'][$extID];
                 if (!is_array($fI)) {
                     $pInfo['msg'] = 'MISSING External Resource FILE: ' . $extID;
                     $this->error('MISSING External Resource FILE: ' . $extID);
                 } else {
                     $pInfo['updatePath'] = $fI['parentRelFileName'];
                 }
                 $pInfo['showDiffContent'] = PathUtility::stripPathSitePrefix($this->fileIDMap[$extID]);
                 $pInfo['preCode'] = $preCode . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' . $this->iconFactory->getIcon('actions-insert-reference', Icon::SIZE_SMALL)->render();
                 $pInfo['title'] = htmlspecialchars($fI['filename']) . ' <em>(Resource)</em>';
                 $pInfo['ref'] = 'FILE';
                 $pInfo['size'] = $fI['filesize'];
                 $pInfo['class'] = $htmlColorClass ?: 'bgColor3';
                 $pInfo['type'] = 'file';
                 $lines[] = $pInfo;
                 unset($this->remainHeader['files'][$extID]);
             }
         }
     }
 }
 /**
  * Creates a list of links to files.
  * Implements the stdWrap property "filelink"
  *
  * @param string $theValue The filename to link to, possibly prefixed with $conf[path]
  * @param array $conf TypoScript parameters for the TypoScript function ->filelink
  * @return string The link to the file possibly with icons, thumbnails, size in bytes shown etc.
  * @access private
  * @see stdWrap()
  */
 public function filelink($theValue, $conf)
 {
     $conf['path'] = isset($conf['path.']) ? $this->stdWrap($conf['path'], $conf['path.']) : $conf['path'];
     $theFile = trim($conf['path']) . $theValue;
     if (@is_file($theFile)) {
         $theFileEnc = str_replace('%2F', '/', rawurlencode($theFile));
         $title = $conf['title'];
         if (isset($conf['title.'])) {
             $title = $this->stdWrap($title, $conf['title.']);
         }
         $target = $conf['target'];
         if (isset($conf['target.'])) {
             $target = $this->stdWrap($target, $conf['target.']);
         }
         // The jumpURL feature will be taken care of by typoLink, only "jumpurl.secure = 1" is applyable needed for special link creation
         if ($conf['jumpurl.']['secure']) {
             $alternativeJumpUrlParameter = isset($conf['jumpurl.']['parameter.']) ? $this->stdWrap($conf['jumpurl.']['parameter'], $conf['jumpurl.']['parameter.']) : $conf['jumpurl.']['parameter'];
             $typoLinkConf = array('parameter' => $alternativeJumpUrlParameter ? $alternativeJumpUrlParameter : $GLOBALS['TSFE']->id . ',' . $GLOBALS['TSFE']->type, 'fileTarget' => $target, 'title' => $title, 'ATagParams' => $this->getATagParams($conf), 'additionalParams' => '&jumpurl=' . rawurlencode($theFileEnc) . $this->locDataJU($theFileEnc, $conf['jumpurl.']['secure.']) . $GLOBALS['TSFE']->getMethodUrlIdToken);
         } else {
             $typoLinkConf = array('parameter' => $theFileEnc, 'fileTarget' => $target, 'title' => $title, 'ATagParams' => $this->getATagParams($conf));
         }
         // If the global jumpURL feature is activated, but is disabled for this
         // filelink, the global parameter needs to be disabled as well for this link creation
         $globalJumpUrlEnabled = $GLOBALS['TSFE']->config['config']['jumpurl_enable'];
         if ($globalJumpUrlEnabled && isset($conf['jumpurl']) && $conf['jumpurl'] == 0) {
             $GLOBALS['TSFE']->config['config']['jumpurl_enable'] = 0;
         } elseif (!$globalJumpUrlEnabled && $conf['jumpurl']) {
             $GLOBALS['TSFE']->config['config']['jumpurl_enable'] = 1;
         }
         $theLinkWrap = $this->typoLink('|', $typoLinkConf);
         // Now the original value is set again
         $GLOBALS['TSFE']->config['config']['jumpurl_enable'] = $globalJumpUrlEnabled;
         $theSize = filesize($theFile);
         $fI = GeneralUtility::split_fileref($theFile);
         if ($conf['icon']) {
             $conf['icon.']['path'] = isset($conf['icon.']['path.']) ? $this->stdWrap($conf['icon.']['path'], $conf['icon.']['path.']) : $conf['icon.']['path'];
             $iconP = !empty($conf['icon.']['path']) ? $conf['icon.']['path'] : ExtensionManagementUtility::siteRelPath('frontend') . 'Resources/Public/Icons/FileIcons/';
             $conf['icon.']['ext'] = isset($conf['icon.']['ext.']) ? $this->stdWrap($conf['icon.']['ext'], $conf['icon.']['ext.']) : $conf['icon.']['ext'];
             $iconExt = !empty($conf['icon.']['ext']) ? '.' . $conf['icon.']['ext'] : '.gif';
             $icon = @is_file($iconP . $fI['fileext'] . $iconExt) ? $iconP . $fI['fileext'] . $iconExt : $iconP . 'default' . $iconExt;
             // Checking for images: If image, then return link to thumbnail.
             $IEList = isset($conf['icon_image_ext_list.']) ? $this->stdWrap($conf['icon_image_ext_list'], $conf['icon_image_ext_list.']) : $conf['icon_image_ext_list'];
             $image_ext_list = str_replace(' ', '', strtolower($IEList));
             if ($fI['fileext'] && GeneralUtility::inList($image_ext_list, $fI['fileext'])) {
                 if ($conf['iconCObject']) {
                     $icon = $this->cObjGetSingle($conf['iconCObject'], $conf['iconCObject.'], 'iconCObject');
                 } else {
                     $notFoundThumb = TYPO3_mainDir . 'gfx/notfound_thumb.gif';
                     $sizeParts = array(64, 64);
                     if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['thumbnails']) {
                         // using the File Abstraction Layer to generate a preview image
                         try {
                             /** @var File $fileObject */
                             $fileObject = ResourceFactory::getInstance()->retrieveFileOrFolderObject($theFile);
                             if ($fileObject->isMissing()) {
                                 $icon = $notFoundThumb;
                             } else {
                                 $fileExtension = $fileObject->getExtension();
                                 if ($fileExtension === 'ttf' || GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], $fileExtension)) {
                                     if ($conf['icon_thumbSize'] || $conf['icon_thumbSize.']) {
                                         $thumbSize = isset($conf['icon_thumbSize.']) ? $this->stdWrap($conf['icon_thumbSize'], $conf['icon_thumbSize.']) : $conf['icon_thumbSize'];
                                         $sizeParts = explode('x', $thumbSize);
                                     }
                                     $icon = $fileObject->process(ProcessedFile::CONTEXT_IMAGEPREVIEW, array('width' => $sizeParts[0], 'height' => $sizeParts[1]))->getPublicUrl(TRUE);
                                 }
                             }
                         } catch (ResourceDoesNotExistException $exception) {
                             $icon = $notFoundThumb;
                         }
                     } else {
                         $icon = $notFoundThumb;
                     }
                     $icon = '<img src="' . htmlspecialchars($GLOBALS['TSFE']->absRefPrefix . $icon) . '"' . 'width="' . $sizeParts[0] . '" height="' . $sizeParts[1] . '" ' . $this->getBorderAttr(' border="0"') . '' . $this->getAltParam($conf) . ' />';
                 }
             } else {
                 $conf['icon.']['widthAttribute'] = isset($conf['icon.']['widthAttribute.']) ? $this->stdWrap($conf['icon.']['widthAttribute'], $conf['icon.']['widthAttribute.']) : $conf['icon.']['widthAttribute'];
                 $iconWidth = !empty($conf['icon.']['widthAttribute']) ? $conf['icon.']['widthAttribute'] : 18;
                 $conf['icon.']['heightAttribute'] = isset($conf['icon.']['heightAttribute.']) ? $this->stdWrap($conf['icon.']['heightAttribute'], $conf['icon.']['heightAttribute.']) : $conf['icon.']['heightAttribute'];
                 $iconHeight = !empty($conf['icon.']['heightAttribute']) ? $conf['icon.']['heightAttribute'] : 16;
                 $icon = '<img src="' . htmlspecialchars($GLOBALS['TSFE']->absRefPrefix . $icon) . '" width="' . $iconWidth . '" height="' . $iconHeight . '"' . $this->getBorderAttr(' border="0"') . $this->getAltParam($conf) . ' />';
             }
             if ($conf['icon_link'] && !$conf['combinedLink']) {
                 $icon = $this->wrap($icon, $theLinkWrap);
             }
             $icon = isset($conf['icon.']) ? $this->stdWrap($icon, $conf['icon.']) : $icon;
         }
         if ($conf['size']) {
             $size = isset($conf['size.']) ? $this->stdWrap($theSize, $conf['size.']) : $theSize;
         }
         // Wrapping file label
         if ($conf['removePrependedNumbers']) {
             $theValue = preg_replace('/_[0-9][0-9](\\.[[:alnum:]]*)$/', '\\1', $theValue);
         }
         if (isset($conf['labelStdWrap.'])) {
             $theValue = $this->stdWrap($theValue, $conf['labelStdWrap.']);
         }
         // Wrapping file
         $wrap = isset($conf['wrap.']) ? $this->stdWrap($conf['wrap'], $conf['wrap.']) : $conf['wrap'];
         if ($conf['combinedLink']) {
             $theValue = $icon . $theValue;
             if ($conf['ATagBeforeWrap']) {
                 $theValue = $this->wrap($this->wrap($theValue, $wrap), $theLinkWrap);
             } else {
                 $theValue = $this->wrap($this->wrap($theValue, $theLinkWrap), $wrap);
             }
             $file = isset($conf['file.']) ? $this->stdWrap($theValue, $conf['file.']) : $theValue;
             // output
             $output = $file . $size;
         } else {
             if ($conf['ATagBeforeWrap']) {
                 $theValue = $this->wrap($this->wrap($theValue, $wrap), $theLinkWrap);
             } else {
                 $theValue = $this->wrap($this->wrap($theValue, $theLinkWrap), $wrap);
             }
             $file = isset($conf['file.']) ? $this->stdWrap($theValue, $conf['file.']) : $theValue;
             // output
             $output = $icon . $file . $size;
         }
         if (isset($conf['stdWrap.'])) {
             $output = $this->stdWrap($output, $conf['stdWrap.']);
         }
         return $output;
     }
 }