Ejemplo n.º 1
0
 public function cb_parseTemplate(\Template &$objTemplate)
 {
     global $objPage;
     if (strpos($objTemplate->getName(), 'news_') === 0) {
         if ($objTemplate->source == 'singlefile') {
             $modelFile = \FilesModel::findByUuid($objTemplate->singlefileSRC);
             try {
                 if ($modelFile === null) {
                     throw new \Exception("no file");
                 }
                 $allowedDownload = trimsplit(',', strtolower($GLOBALS['TL_CONFIG']['allowedDownload']));
                 if (!in_array($modelFile->extension, $allowedDownload)) {
                     throw new Exception("download not allowed by extension");
                 }
                 $objFile = new \File($modelFile->path, true);
                 $strHref = \System::urlEncode($objFile->value);
             } catch (\Exception $e) {
                 $strHref = "";
             }
             $target = $objPage->outputFormat == 'xhtml' ? ' onclick="return !window.open(this.href)"' : ' target="_blank"';
             $objTemplate->more = sprintf('<a %s href="%s" title="%s">%s</a>', $target, $strHref, specialchars(sprintf($GLOBALS['TL_LANG']['MSC']['open'], $objFile->basename)), $GLOBALS['TL_LANG']['MSC']['more']);
             $objTemplate->linkHeadline = sprintf('<a %s href="%s" title="%s">%s</a>', $target, $strHref, specialchars(sprintf($GLOBALS['TL_LANG']['MSC']['open'], $objFile->basename)), $objTemplate->headline);
         }
     }
 }
Ejemplo n.º 2
0
 protected static function addToPDFSearchIndex($strFile, $arrParentSet)
 {
     $objFile = new \File($strFile);
     if (!Validator::isValidPDF($objFile)) {
         return false;
     }
     $objDatabase = \Database::getInstance();
     $objModel = $objFile->getModel();
     $arrMeta = \Frontend::getMetaData($objModel->meta, $arrParentSet['language']);
     // Use the file name as title if none is given
     if ($arrMeta['title'] == '') {
         $arrMeta['title'] = specialchars($objFile->basename);
     }
     $strHref = \Environment::get('base') . \Environment::get('request');
     // Remove an existing file parameter
     if (preg_match('/(&(amp;)?|\\?)file=/', $strHref)) {
         $strHref = preg_replace('/(&(amp;)?|\\?)file=[^&]+/', '', $strHref);
     }
     $strHref .= (\Config::get('disableAlias') || strpos($strHref, '?') !== false ? '&amp;' : '?') . 'file=' . \System::urlEncode($objFile->value);
     $arrSet = array('pid' => $arrParentSet['pid'], 'tstamp' => time(), 'title' => $arrMeta['title'], 'url' => $strHref, 'filesize' => \System::getReadableSize($objFile->size, 2), 'checksum' => $objFile->hash, 'protected' => $arrParentSet['protected'], 'groups' => $arrParentSet['groups'], 'language' => $arrParentSet['language'], 'mime' => $objFile->mime);
     // Return if the file is indexed and up to date
     $objIndex = $objDatabase->prepare("SELECT * FROM tl_search WHERE pid=? AND checksum=?")->execute($arrSet['pid'], $arrSet['checksum']);
     // there are already indexed files containing this file (same checksum and filename)
     if ($objIndex->numRows) {
         // Return if the page with the file is indexed
         if (in_array($arrSet['pid'], $objIndex->fetchEach('pid'))) {
             return false;
         }
         $strContent = $objIndex->text;
     } else {
         try {
             // parse only for the first occurrence
             $parser = new \Smalot\PdfParser\Parser();
             $objPDF = $parser->parseFile($strFile);
             $strContent = $objPDF->getText();
         } catch (\Exception $e) {
             // Missing object refernce #...
             return false;
         }
     }
     // Put everything together
     $arrSet['text'] = $strContent;
     $arrSet['text'] = trim(preg_replace('/ +/', ' ', \String::decodeEntities($arrSet['text'])));
     // Update an existing old entry
     if ($objIndex->pid == $arrSet['pid']) {
         $objDatabase->prepare("UPDATE tl_search %s WHERE id=?")->set($arrSet)->execute($objIndex->id);
         $intInsertId = $objIndex->id;
     } else {
         $objInsertStmt = $objDatabase->prepare("INSERT INTO tl_search %s")->set($arrSet)->execute();
         $intInsertId = $objInsertStmt->insertId;
     }
     static::indexContent($arrSet, $intInsertId);
 }
 public function generate(WatchlistItemModel $objItem, Watchlist $objWatchlist)
 {
     global $objPage;
     $objFileModel = \FilesModel::findById($objItem->uuid);
     if ($objFileModel === null) {
         return;
     }
     $file = \Input::get('file', true);
     // Send the file to the browser and do not send a 404 header (see #4632)
     if ($file != '' && $file == $objFileModel->path) {
         \Controller::sendFileToBrowser($file);
     }
     $objFile = new \File($objFileModel->path, true);
     $objContent = \ContentModel::findByPk($objItem->cid);
     $objT = new \FrontendTemplate('watchlist_view_download');
     $objT->setData($objFileModel->row());
     $linkTitle = specialchars($objFile->name);
     // use generate for download & downloads as well
     if ($objContent->type == 'download' && $objContent->linkTitle != '') {
         $linkTitle = $objContent->linkTitle;
     }
     $arrMeta = deserialize($objFileModel->meta);
     // Language support
     if (($arrLang = $arrMeta[$GLOBALS['TL_LANGUAGE']]) != '') {
         $linkTitle = $arrLang['title'] ? $arrLang['title'] : $linkTitle;
     }
     $strHref = \Controller::generateFrontendUrl($objPage->row());
     // Remove an existing file parameter (see #5683)
     if (preg_match('/(&(amp;)?|\\?)file=/', $strHref)) {
         $strHref = preg_replace('/(&(amp;)?|\\?)file=[^&]+/', '', $strHref);
     }
     $strHref .= (\Config::get('disableAlias') || strpos($strHref, '?') !== false ? '&amp;' : '?') . 'file=' . \System::urlEncode($objFile->path);
     $objT->link = ($objItemTitle = $objItem->title) ? $objItemTitle : $linkTitle;
     $objT->title = specialchars($objContent->titleText ?: $linkTitle);
     $objT->href = $strHref;
     $objT->filesize = \System::getReadableSize($objFile->filesize, 1);
     $objT->icon = TL_ASSETS_URL . 'assets/contao/images/' . $objFile->icon;
     $objT->mime = $objFile->mime;
     $objT->extension = $objFile->extension;
     $objT->path = $objFile->dirname;
     $objT->actions = $this->generateEditActions($objItem, $objWatchlist);
     return $objT->parse();
 }
Ejemplo n.º 4
0
 /**
  * Generate the content element
  */
 protected function compile()
 {
     $objFile = new \File($this->singleSRC);
     if ($this->linkTitle == '') {
         $this->linkTitle = specialchars($objFile->basename);
     }
     $strHref = \Environment::get('request');
     // Remove an existing file parameter (see #5683)
     if (preg_match('/(&(amp;)?|\\?)file=/', $strHref)) {
         $strHref = preg_replace('/(&(amp;)?|\\?)file=[^&]+/', '', $strHref);
     }
     $strHref .= (strpos($strHref, '?') !== false ? '&amp;' : '?') . 'file=' . \System::urlEncode($objFile->value);
     $this->Template->link = $this->linkTitle;
     $this->Template->title = specialchars($this->titleText ?: sprintf($GLOBALS['TL_LANG']['MSC']['download'], $objFile->basename));
     $this->Template->href = $strHref;
     $this->Template->filesize = $this->getReadableSize($objFile->filesize, 1);
     $this->Template->icon = TL_ASSETS_URL . 'assets/contao/images/' . $objFile->icon;
     $this->Template->mime = $objFile->mime;
     $this->Template->extension = $objFile->extension;
     $this->Template->path = $objFile->dirname;
 }
 public static function generateImageContaoLogic($image, $width, $height, $mode = '', $target = null, $force = false)
 {
     if ($image == '') {
         return null;
     }
     $image = rawurldecode($image);
     // Check whether the file exists
     if (!is_file(TL_ROOT . '/' . $image)) {
         \System::log('Image "' . $image . '" could not be found', __METHOD__, TL_ERROR);
         return null;
     }
     $objFile = new \File($image, true);
     $arrAllowedTypes = trimsplit(',', strtolower(\Config::get('validImageTypes')));
     // Check the file type
     if (!in_array($objFile->extension, $arrAllowedTypes)) {
         \System::log('Image type "' . $objFile->extension . '" was not allowed to be processed', __METHOD__, TL_ERROR);
         return null;
     }
     // No resizing required
     if (($objFile->width == $width || !$width) && ($objFile->height == $height || !$height)) {
         // Return the target image (thanks to Tristan Lins) (see #4166)
         if ($target) {
             // Copy the source image if the target image does not exist or is older than the source image
             if (!file_exists(TL_ROOT . '/' . $target) || $objFile->mtime > filemtime(TL_ROOT . '/' . $target)) {
                 \Files::getInstance()->copy($image, $target);
             }
             return \System::urlEncode($target);
         }
         return \System::urlEncode($image);
     }
     // No mode given
     if ($mode == '') {
         // Backwards compatibility
         if ($width && $height) {
             $mode = 'center_top';
         } else {
             $mode = 'proportional';
         }
     }
     // Backwards compatibility
     if ($mode == 'crop') {
         $mode = 'center_center';
     }
     $strCacheKey = substr(md5('-w' . $width . '-h' . $height . '-' . $image . '-' . $mode . '-' . $objFile->mtime), 0, 8);
     $strCacheName = 'assets/images/' . substr($strCacheKey, -1) . '/' . $objFile->filename . '-' . $strCacheKey . '.' . $objFile->extension;
     // Check whether the image exists already
     if (!\Config::get('debugMode')) {
         // Custom target (thanks to Tristan Lins) (see #4166)
         if ($target && !$force) {
             if (file_exists(TL_ROOT . '/' . $target) && $objFile->mtime <= filemtime(TL_ROOT . '/' . $target)) {
                 return \System::urlEncode($target);
             }
         }
         // Regular cache file
         if (file_exists(TL_ROOT . '/' . $strCacheName)) {
             // Copy the cached file if it exists
             if ($target) {
                 \Files::getInstance()->copy($strCacheName, $target);
                 return \System::urlEncode($target);
             }
             return \System::urlEncode($strCacheName);
         }
     }
     // Return the path to the original image if the GDlib cannot handle it
     if (!extension_loaded('gd') || !$objFile->isGdImage || $objFile->width > \Config::get('gdMaxImgWidth') || $objFile->height > \Config::get('gdMaxImgHeight') || !$width && !$height || $width > \Config::get('gdMaxImgWidth') || $height > \Config::get('gdMaxImgHeight')) {
         return \System::urlEncode($image);
     }
     $intPositionX = 0;
     $intPositionY = 0;
     $intWidth = $width;
     $intHeight = $height;
     // Mode-specific changes
     if ($intWidth && $intHeight) {
         switch ($mode) {
             case 'proportional':
                 if ($objFile->width >= $objFile->height) {
                     unset($height, $intHeight);
                 } else {
                     unset($width, $intWidth);
                 }
                 break;
             case 'box':
                 if (round($objFile->height * $width / $objFile->width) <= $intHeight) {
                     unset($height, $intHeight);
                 } else {
                     unset($width, $intWidth);
                 }
                 break;
         }
     }
     $strNewImage = null;
     $strSourceImage = null;
     // Resize width and height and crop the image if necessary
     if ($intWidth && $intHeight) {
         if ($intWidth * $objFile->height != $intHeight * $objFile->width) {
             $intWidth = max(round($objFile->width * $height / $objFile->height), 1);
             $intPositionX = -intval(($intWidth - $width) / 2);
             if ($intWidth < $width) {
                 $intWidth = $width;
                 $intHeight = max(round($objFile->height * $width / $objFile->width), 1);
                 $intPositionX = 0;
                 $intPositionY = -intval(($intHeight - $height) / 2);
             }
         }
         // Advanced crop modes
         switch ($mode) {
             case 'left_top':
                 $intPositionX = 0;
                 $intPositionY = 0;
                 break;
             case 'center_top':
                 $intPositionX = -intval(($intWidth - $width) / 2);
                 $intPositionY = 0;
                 break;
             case 'right_top':
                 $intPositionX = -intval($intWidth - $width);
                 $intPositionY = 0;
                 break;
             case 'left_center':
                 $intPositionX = 0;
                 $intPositionY = -intval(($intHeight - $height) / 2);
                 break;
             case 'center_center':
                 $intPositionX = -intval(($intWidth - $width) / 2);
                 $intPositionY = -intval(($intHeight - $height) / 2);
                 break;
             case 'right_center':
                 $intPositionX = -intval($intWidth - $width);
                 $intPositionY = -intval(($intHeight - $height) / 2);
                 break;
             case 'left_bottom':
                 $intPositionX = 0;
                 $intPositionY = -intval($intHeight - $height);
                 break;
             case 'center_bottom':
                 $intPositionX = -intval(($intWidth - $width) / 2);
                 $intPositionY = -intval($intHeight - $height);
                 break;
             case 'right_bottom':
                 $intPositionX = -intval($intWidth - $width);
                 $intPositionY = -intval($intHeight - $height);
                 break;
         }
         $strNewImage = imagecreatetruecolor($width, $height);
     } elseif ($intWidth) {
         $intHeight = max(round($objFile->height * $width / $objFile->width), 1);
         $strNewImage = imagecreatetruecolor($intWidth, $intHeight);
     } elseif ($intHeight) {
         $intWidth = max(round($objFile->width * $height / $objFile->height), 1);
         $strNewImage = imagecreatetruecolor($intWidth, $intHeight);
     }
     $arrGdinfo = gd_info();
     $strGdVersion = preg_replace('/[^0-9\\.]+/', '', $arrGdinfo['GD Version']);
     switch ($objFile->extension) {
         case 'gif':
             if ($arrGdinfo['GIF Read Support']) {
                 $strSourceImage = imagecreatefromgif(TL_ROOT . '/' . $image);
                 $intTranspIndex = imagecolortransparent($strSourceImage);
                 // Handle transparency
                 if ($intTranspIndex >= 0 && $intTranspIndex < imagecolorstotal($strSourceImage)) {
                     $arrColor = imagecolorsforindex($strSourceImage, $intTranspIndex);
                     $intTranspIndex = imagecolorallocate($strNewImage, $arrColor['red'], $arrColor['green'], $arrColor['blue']);
                     imagefill($strNewImage, 0, 0, $intTranspIndex);
                     imagecolortransparent($strNewImage, $intTranspIndex);
                 }
             }
             break;
         case 'jpg':
         case 'jpeg':
             if ($arrGdinfo['JPG Support'] || $arrGdinfo['JPEG Support']) {
                 $strSourceImage = imagecreatefromjpeg(TL_ROOT . '/' . $image);
             }
             break;
         case 'png':
             if ($arrGdinfo['PNG Support']) {
                 $strSourceImage = imagecreatefrompng(TL_ROOT . '/' . $image);
                 // Handle transparency (GDlib >= 2.0 required)
                 if (version_compare($strGdVersion, '2.0', '>=')) {
                     imagealphablending($strNewImage, false);
                     $intTranspIndex = imagecolorallocatealpha($strNewImage, 0, 0, 0, 127);
                     imagefill($strNewImage, 0, 0, $intTranspIndex);
                     imagesavealpha($strNewImage, true);
                 }
             }
             break;
     }
     // The new image could not be created
     if (!$strSourceImage) {
         imagedestroy($strNewImage);
         \System::log('Image "' . $image . '" could not be processed', __METHOD__, TL_ERROR);
         return null;
     }
     imageinterlace($strNewImage, 1);
     // see #6529
     imagecopyresampled($strNewImage, $strSourceImage, $intPositionX, $intPositionY, 0, 0, $intWidth, $intHeight, $objFile->width, $objFile->height);
     // Fallback to PNG if GIF ist not supported
     if ($objFile->extension == 'gif' && !$arrGdinfo['GIF Create Support']) {
         $objFile->extension = 'png';
     }
     // Create the new image
     switch ($objFile->extension) {
         case 'gif':
             imagegif($strNewImage, TL_ROOT . '/' . $strCacheName);
             break;
         case 'jpg':
         case 'jpeg':
             imagejpeg($strNewImage, TL_ROOT . '/' . $strCacheName, \Config::get('jpgQuality') ?: 80);
             break;
         case 'png':
             // Optimize non-truecolor images (see #2426)
             if (version_compare($strGdVersion, '2.0', '>=') && function_exists('imagecolormatch') && !imageistruecolor($strSourceImage)) {
                 // TODO: make it work with transparent images, too
                 if (imagecolortransparent($strSourceImage) == -1) {
                     $intColors = imagecolorstotal($strSourceImage);
                     // Convert to a palette image
                     // @see http://www.php.net/manual/de/function.imagetruecolortopalette.php#44803
                     if ($intColors > 0 && $intColors < 256) {
                         $wi = imagesx($strNewImage);
                         $he = imagesy($strNewImage);
                         $ch = imagecreatetruecolor($wi, $he);
                         imagecopymerge($ch, $strNewImage, 0, 0, 0, 0, $wi, $he, 100);
                         imagetruecolortopalette($strNewImage, false, $intColors);
                         imagecolormatch($ch, $strNewImage);
                         imagedestroy($ch);
                     }
                 }
             }
             imagepng($strNewImage, TL_ROOT . '/' . $strCacheName);
             break;
     }
     // Destroy the temporary images
     imagedestroy($strSourceImage);
     imagedestroy($strNewImage);
     // Resize the original image
     if ($target) {
         \Files::getInstance()->copy($strCacheName, $target);
         return \System::urlEncode($target);
     }
     // Set the file permissions when the Safe Mode Hack is used
     if (\Config::get('useFTP')) {
         \Files::getInstance()->chmod($strCacheName, \Config::get('defaultFileChmod'));
     }
     // Return the path to new image
     return \System::urlEncode($strCacheName);
 }
 /**
  * Generate content element
  */
 protected function compile()
 {
     if (!$this->previewSettings) {
         return '';
     }
     $objParams = $this->Database->prepare("SELECT * FROM tl_download_settings WHERE id = ?")->limit(1)->execute($this->previewSettings);
     if (!$objParams->previewImageSize) {
         return '';
     }
     if ($objParams->previewTemplate == '') {
         $objParams->previewTemplate = 'ce_download_extended';
     }
     $this->Template = new FrontendTemplate($objParams->previewTemplate);
     $objFile = new \File($this->singleSRC, true);
     $allowedDownload = trimsplit(',', strtolower($GLOBALS['TL_CONFIG']['allowedDownload']));
     if (!in_array($objFile->extension, $allowedDownload)) {
         return;
     }
     if (!strlen($this->linkTitle)) {
         $this->linkTitle = $objFile->basename;
     }
     $d_path = 'assets/images/download_extended/';
     if (!is_dir(TL_ROOT . '/' . $d_path)) {
         mkdir(TL_ROOT . '/' . $d_path);
         if (!is_dir(TL_ROOT . '/' . $d_path)) {
             return false;
         }
     }
     $preview = $d_path . substr(preg_replace('/[^a-zA-Z0-9]/', '', $objFile->filename), 0, 8) . '-' . substr(md5($objFile->path), 0, 8) . '.jpg';
     if ($this->previewImage) {
         $objImage = \FilesModel::findByUuid($this->previewImage);
         if ($objImage !== null && is_file(TL_ROOT . '/' . $objImage->path)) {
             $preview = $objImage->path;
         }
     } elseif ($objParams->previewGenerateImage) {
         if (!is_file(TL_ROOT . '/' . $preview) || filemtime(TL_ROOT . '/' . $preview) < time() - 604800) {
             if (class_exists('Imagick', false) && !extension_loaded('imagick')) {
                 //!@todo Imagick PHP-Funktionen verwenden, falls vorhanden
             } else {
                 $strFirst = $objFile->extension == 'pdf' ? '[0]' : '';
                 @exec(sprintf('PATH=\\$PATH:%s;export PATH;%s/convert %s/%s' . $strFirst . ' %s/%s 2>&1', $objParams->pathImageMagick, $objParams->pathImageMagick, TL_ROOT, escapeshellarg($objFile->path), TL_ROOT, $preview), $convert_output, $convert_code);
                 if (!is_file(TL_ROOT . '/' . $preview)) {
                     $convert_output = implode("<br />", $convert_output);
                     $reason = 'ImageMagick Exit Code: ' . $convert_code;
                     if ($convert_code == 127) {
                         $reason = 'ImageMagick is not available at ' . $objParams->pathImageMagick;
                     }
                     if (strpos($convert_output, 'gs: command not found')) {
                         $reason = 'Unable to read PDF due to GhostScript error.';
                     }
                     $this->log('Creating preview from "' . $objFile->path . '" failed! ' . $reason . "\n\n" . $convert_output, 'ContentPreviewDownload compile()', TL_ERROR);
                     if (TL_MODE == 'BE') {
                         $this->linkTitle .= $GLOBALS['TL_LANG']['MSC']['creatingPreviewFailed'];
                     }
                 }
             }
         }
     } elseif ($objParams->previewStandardImage) {
         $objImage = \FilesModel::findByUuid($objParams->previewStandardImage);
         if ($objImage !== null && is_file(TL_ROOT . '/' . $objImage->path)) {
             $preview = $objImage->path;
         }
     }
     if (is_file(TL_ROOT . '/' . $preview)) {
         //            $imgIndividualSize = deserialize($this->size);
         $imgDefaultSize = deserialize($objParams->previewImageSize);
         $arrImageSize = getimagesize(TL_ROOT . '/' . $preview);
         if ($imgIndividualSize[0] > 0 || $imgIndividualSize[1] > 0) {
             // individualSize
             $imgSize = $imgIndividualSize;
         } elseif ($imgDefaultSize[0] > 0 || $imgDefaultSize[1] > 0) {
             // preferences -> defaultSize
             if ($objParams->previewConsiderOrientation && $arrImageSize[0] >= $arrImageSize[1]) {
                 $imgSize = array($imgDefaultSize[1], $imgDefaultSize[0], $imgDefaultSize[2]);
             } else {
                 $imgSize = $imgDefaultSize;
             }
         } else {
             $imgSize = array(0, 0, 'proportional');
         }
         $src = $this->getImage($preview, $imgSize[0], $imgSize[1], $imgSize[2]);
         if (($imgSize = @getimagesize(TL_ROOT . '/' . $src)) !== false) {
             $this->Template->preview = $src;
             $this->Template->previewImgSize = ' ' . $imgSize[3];
         }
     }
     $arrMetainfo = array();
     if ($objParams->previewExtension) {
         $arrMetainfo['extension'] = strtoupper($objFile->extension);
     }
     if ($objParams->previewFilesizeD) {
         $intSize = $objFile->filesize;
         for ($i = 0; $intSize >= 1000; $i++) {
             $intSize /= 1000;
         }
         $arrMetainfo['filesize_dec'] = static::getFormattedNumber($intSize, 1) . ' ' . str_replace(array('KiB', 'i'), array('kB', ''), $GLOBALS['TL_LANG']['UNITS'][$i]);
     }
     if ($objParams->previewFilesizeB) {
         $arrMetainfo['filesize_bin'] = $this->getReadableSize($objFile->filesize, 1);
     }
     $strHref = \Environment::get('request');
     // Remove an existing file parameter (see #5683)
     if (preg_match('/(&(amp;)?|\\?)file=/', $strHref)) {
         $strHref = preg_replace('/(&(amp;)?|\\?)file=[^&]+/', '', $strHref);
     }
     $strHref .= ($GLOBALS['TL_CONFIG']['disableAlias'] || strpos($strHref, '?') !== false ? '&amp;' : '?') . 'file=' . \System::urlEncode($objFile->value);
     $this->Template->margin = $this->generateMargin(deserialize($objParams->previewImageMargin), 'margin');
     // Float image
     if ($objParams->previewImageFloating) {
         $this->Template->floatClass = ' float_' . $objParams->previewImageFloating;
     }
     // Icon
     if ($objParams->previewIcon) {
         $this->Template->icon = TL_ASSETS_URL . 'assets/contao/images/' . $objFile->icon;
     }
     /*
             if ($objParams->previewFilesizeD)
             {
                 $this->Template->filesize = $arrMetainfo['filesize_dec'];
             } elseif ($objParams->previewFilesizeB)
             {
                 $this->Template->filesize = $arrMetainfo['filesize_bin'];
             }
     */
     $this->Template->link = $this->linkTitle;
     $this->Template->description = $this->description;
     $this->Template->title = specialchars($this->titleText ?: $this->linkTitle);
     $this->Template->href = $strHref;
     $this->Template->mime = $objFile->mime;
     $this->Template->extension = $objFile->extension;
     $this->Template->arrMetainfo = $arrMetainfo;
     $this->Template->path = $objFile->dirname;
 }
Ejemplo n.º 7
0
 /**
  * Add enclosures to a template
  *
  * @param object $objTemplate The template object to add the enclosures to
  * @param array  $arrItem     The element or module as array
  * @param string $strKey      The name of the enclosures field in $arrItem
  */
 public static function addEnclosuresToTemplate($objTemplate, $arrItem, $strKey = 'enclosure')
 {
     $arrEnclosures = deserialize($arrItem[$strKey]);
     if (!is_array($arrEnclosures) || empty($arrEnclosures)) {
         return;
     }
     $objFiles = \FilesModel::findMultipleByUuids($arrEnclosures);
     if ($objFiles === null) {
         if (!\Validator::isUuid($arrEnclosures[0])) {
             foreach (array('details', 'answer', 'text') as $key) {
                 if (isset($objTemplate->{$key})) {
                     $objTemplate->{$key} = '<p class="error">' . $GLOBALS['TL_LANG']['ERR']['version2format'] . '</p>';
                 }
             }
         }
         return;
     }
     $file = \Input::get('file', true);
     // Send the file to the browser and do not send a 404 header (see #5178)
     if ($file != '') {
         while ($objFiles->next()) {
             if ($file == $objFiles->path) {
                 static::sendFileToBrowser($file);
             }
         }
         $objFiles->reset();
     }
     /** @var \PageModel $objPage */
     global $objPage;
     $arrEnclosures = array();
     $allowedDownload = trimsplit(',', strtolower(\Config::get('allowedDownload')));
     // Add download links
     while ($objFiles->next()) {
         if ($objFiles->type == 'file') {
             if (!in_array($objFiles->extension, $allowedDownload) || !is_file(TL_ROOT . '/' . $objFiles->path)) {
                 continue;
             }
             $objFile = new \File($objFiles->path, true);
             $strHref = \Environment::get('request');
             // Remove an existing file parameter (see #5683)
             if (preg_match('/(&(amp;)?|\\?)file=/', $strHref)) {
                 $strHref = preg_replace('/(&(amp;)?|\\?)file=[^&]+/', '', $strHref);
             }
             $strHref .= (\Config::get('disableAlias') || strpos($strHref, '?') !== false ? '&amp;' : '?') . 'file=' . \System::urlEncode($objFiles->path);
             $arrMeta = \Frontend::getMetaData($objFiles->meta, $objPage->language);
             if (empty($arrMeta) && $objPage->rootFallbackLanguage !== null) {
                 $arrMeta = \Frontend::getMetaData($objFiles->meta, $objPage->rootFallbackLanguage);
             }
             // Use the file name as title if none is given
             if ($arrMeta['title'] == '') {
                 $arrMeta['title'] = specialchars($objFile->basename);
             }
             $arrEnclosures[] = array('link' => $arrMeta['title'], 'filesize' => static::getReadableSize($objFile->filesize), 'title' => specialchars(sprintf($GLOBALS['TL_LANG']['MSC']['download'], $objFile->basename)), 'href' => $strHref, 'enclosure' => $objFiles->path, 'icon' => TL_ASSETS_URL . 'assets/contao/images/' . $objFile->icon, 'mime' => $objFile->mime, 'meta' => $arrMeta);
         }
     }
     $objTemplate->enclosure = $arrEnclosures;
 }
 /**
  * Generate the content element
  */
 protected function compile()
 {
     /** @var \PageModel $objPage */
     global $objPage;
     $files = array();
     $auxDate = array();
     $objFiles = $this->objFiles;
     $allowedDownload = trimsplit(',', strtolower(\Config::get('allowedDownload')));
     // Get all files
     while ($objFiles->next()) {
         // Continue if the files has been processed or does not exist
         if (isset($files[$objFiles->path]) || !file_exists(TL_ROOT . '/' . $objFiles->path)) {
             continue;
         }
         // Single files
         if ($objFiles->type == 'file') {
             $objFile = new \File($objFiles->path, true);
             if (!in_array($objFile->extension, $allowedDownload) || preg_match('/^meta(_[a-z]{2})?\\.txt$/', $objFile->basename)) {
                 continue;
             }
             $arrMeta = $this->getMetaData($objFiles->meta, $objPage->language);
             if (empty($arrMeta)) {
                 if ($this->metaIgnore) {
                     continue;
                 } elseif ($objPage->rootFallbackLanguage !== null) {
                     $arrMeta = $this->getMetaData($objFiles->meta, $objPage->rootFallbackLanguage);
                 }
             }
             // Use the file name as title if none is given
             if ($arrMeta['title'] == '') {
                 $arrMeta['title'] = specialchars($objFile->basename);
             }
             $strHref = \Environment::get('request');
             // Remove an existing file parameter (see #5683)
             if (preg_match('/(&(amp;)?|\\?)file=/', $strHref)) {
                 $strHref = preg_replace('/(&(amp;)?|\\?)file=[^&]+/', '', $strHref);
             }
             $strHref .= (\Config::get('disableAlias') || strpos($strHref, '?') !== false ? '&amp;' : '?') . 'file=' . \System::urlEncode($objFiles->path);
             // Add the image
             $files[$objFiles->path] = array('id' => $objFiles->id, 'uuid' => $objFiles->uuid, 'name' => $objFile->basename, 'title' => specialchars(sprintf($GLOBALS['TL_LANG']['MSC']['download'], $objFile->basename)), 'link' => $arrMeta['title'], 'caption' => $arrMeta['caption'], 'href' => $strHref, 'filesize' => $this->getReadableSize($objFile->filesize, 1), 'icon' => TL_ASSETS_URL . 'assets/contao/images/' . $objFile->icon, 'mime' => $objFile->mime, 'meta' => $arrMeta, 'extension' => $objFile->extension, 'path' => $objFile->dirname);
             $auxDate[] = $objFile->mtime;
         } else {
             $objSubfiles = \FilesModel::findByPid($objFiles->uuid);
             if ($objSubfiles === null) {
                 continue;
             }
             while ($objSubfiles->next()) {
                 // Skip subfolders
                 if ($objSubfiles->type == 'folder') {
                     continue;
                 }
                 $objFile = new \File($objSubfiles->path, true);
                 if (!in_array($objFile->extension, $allowedDownload) || preg_match('/^meta(_[a-z]{2})?\\.txt$/', $objFile->basename)) {
                     continue;
                 }
                 $arrMeta = $this->getMetaData($objSubfiles->meta, $objPage->language);
                 if (empty($arrMeta)) {
                     if ($this->metaIgnore) {
                         continue;
                     } elseif ($objPage->rootFallbackLanguage !== null) {
                         $arrMeta = $this->getMetaData($objSubfiles->meta, $objPage->rootFallbackLanguage);
                     }
                 }
                 // Use the file name as title if none is given
                 if ($arrMeta['title'] == '') {
                     $arrMeta['title'] = specialchars($objFile->basename);
                 }
                 $strHref = \Environment::get('request');
                 // Remove an existing file parameter (see #5683)
                 if (preg_match('/(&(amp;)?|\\?)file=/', $strHref)) {
                     $strHref = preg_replace('/(&(amp;)?|\\?)file=[^&]+/', '', $strHref);
                 }
                 $strHref .= (\Config::get('disableAlias') || strpos($strHref, '?') !== false ? '&amp;' : '?') . 'file=' . \System::urlEncode($objSubfiles->path);
                 // Add the image
                 $files[$objSubfiles->path] = array('id' => $objSubfiles->id, 'uuid' => $objSubfiles->uuid, 'name' => $objFile->basename, 'title' => specialchars(sprintf($GLOBALS['TL_LANG']['MSC']['download'], $objFile->basename)), 'link' => $arrMeta['title'], 'caption' => $arrMeta['caption'], 'href' => $strHref, 'filesize' => $this->getReadableSize($objFile->filesize, 1), 'icon' => TL_ASSETS_URL . 'assets/contao/images/' . $objFile->icon, 'mime' => $objFile->mime, 'meta' => $arrMeta, 'extension' => $objFile->extension, 'path' => $objFile->dirname);
                 $auxDate[] = $objFile->mtime;
             }
         }
     }
     // Sort array
     switch ($this->sortBy) {
         default:
         case 'name_asc':
             uksort($files, 'basename_natcasecmp');
             break;
         case 'name_desc':
             uksort($files, 'basename_natcasercmp');
             break;
         case 'date_asc':
             array_multisort($files, SORT_NUMERIC, $auxDate, SORT_ASC);
             break;
         case 'date_desc':
             array_multisort($files, SORT_NUMERIC, $auxDate, SORT_DESC);
             break;
         case 'meta':
             // Backwards compatibility
         // Backwards compatibility
         case 'custom':
             if ($this->orderSRC != '') {
                 $tmp = deserialize($this->orderSRC);
                 if (!empty($tmp) && is_array($tmp)) {
                     // Remove all values
                     $arrOrder = array_map(function () {
                     }, array_flip($tmp));
                     // Move the matching elements to their position in $arrOrder
                     foreach ($files as $k => $v) {
                         if (array_key_exists($v['uuid'], $arrOrder)) {
                             $arrOrder[$v['uuid']] = $v;
                             unset($files[$k]);
                         }
                     }
                     // Append the left-over files at the end
                     if (!empty($files)) {
                         $arrOrder = array_merge($arrOrder, array_values($files));
                     }
                     // Remove empty (unreplaced) entries
                     $files = array_values(array_filter($arrOrder));
                     unset($arrOrder);
                 }
             }
             break;
         case 'random':
             shuffle($files);
             break;
     }
     $this->Template->files = array_values($files);
 }
 public static function addDownloadsFromProductDownloadsToTemplate($objTemplate)
 {
     $arrDownloads = array();
     // array for downloadfiles from db
     $arrFiles = array();
     // contains queryresults from db
     $strTable = "tl_iso_download";
     // name of download table
     global $objPage;
     $arrOptions = array('order' => 'sorting ASC');
     $arrFiles = \Isotope\Model\Download::findBy('pid', $objTemplate->id, $arrOptions);
     if ($arrFiles === null) {
         return $arrDownloads;
     }
     while ($arrFiles->next()) {
         $objModel = \FilesModel::findByUuid($arrFiles->singleSRC);
         if ($objModel === null) {
             if (!\Validator::isUuid($arrFiles->singleSRC)) {
                 $objTemplate->text = '<p class="error">' . $GLOBALS['TL_LANG']['ERR']['version2format'] . '</p>';
             }
         } elseif (is_file(TL_ROOT . '/' . $objModel->path)) {
             $objFile = new \File($objModel->path, true);
             $file = \Input::get('file', true);
             // Send the file to the browser and do not send a 404 header (see #4632)
             if ($file != '' && $file == $objFile->path) {
                 \Controller::sendFileToBrowser($file);
             }
             $arrMeta = \Frontend::getMetaData($objModel->meta, $objPage->language);
             if (empty($arrMeta)) {
                 if ($objPage->rootFallbackLanguage !== null) {
                     $arrMeta = \Frontend::getMetaData($objModel->meta, $objPage->rootFallbackLanguage);
                 }
             }
             $strHref = \Environment::get('request');
             // Remove an existing file parameter (see #5683)
             if (preg_match('/(&(amp;)?|\\?)file=/', $strHref)) {
                 $strHref = preg_replace('/(&(amp;)?|\\?)file=[^&]+/', '', $strHref);
             }
             $strHref .= (\Config::get('disableAlias') || strpos($strHref, '?') !== false ? '&amp;' : '?') . 'file=' . \System::urlEncode($objFile->path);
             $objDownload = new \stdClass();
             $objDownload->id = $objModel->id;
             $objDownload->uuid = $objModel->uuid;
             $objDownload->name = $objFile->basename;
             $objDownload->formedname = preg_replace(array('/_/', '/.\\w+$/'), array(' ', ''), $objFile->basename);
             $objDownload->title = specialchars(sprintf($GLOBALS['TL_LANG']['MSC']['download'], $objFile->basename));
             $objDownload->link = $arrMeta['title'];
             $objDownload->filesize = \System::getReadableSize($objFile->filesize, 1);
             $objDownload->icon = TL_ASSETS_URL . 'assets/contao/images/' . $objFile->icon;
             $objDownload->href = $strHref;
             $objDownload->mime = $objFile->mime;
             $objDownload->extension = $objFile->extension;
             $objDownload->path = $objFile->dirname;
             $objDownload->class = 'isotope-download isotope-download-file';
             $objT = new \FrontendTemplate('isotope_download_from_attribute');
             $objT->setData((array) $objDownload);
             $objDownload->output = $objT->parse();
             $arrDownloads[] = $objDownload;
         }
     }
     $objTemplate->downloads = $arrDownloads;
 }
Ejemplo n.º 10
0
 /**
  * Returns the information-array about an album
  *
  * @param null $intPictureId
  * @param $objThis
  * @return array|null
  */
 public static function getPictureInformationArray($intPictureId = null, $objThis)
 {
     if ($intPictureId < 1) {
         return;
     }
     global $objPage;
     $defaultThumbSRC = $objThis->defaultThumb;
     if (\Config::get('gc_error404_thumb') !== '') {
         $objFile = \FilesModel::findByUuid(\Config::get('gc_error404_thumb'));
         if ($objFile !== null) {
             if (\Validator::isUuid(\Config::get('gc_error404_thumb'))) {
                 if (is_file(TL_ROOT . '/' . $objFile->path)) {
                     $defaultThumbSRC = $objFile->path;
                 }
             }
         }
     }
     // Get the page model
     $objPageModel = \PageModel::findByPk($objPage->id);
     $objPicture = \Database::getInstance()->prepare('SELECT * FROM tl_gallery_creator_pictures WHERE id=?')->execute($intPictureId);
     //Alle Informationen zum Album in ein array packen
     $objAlbum = \Database::getInstance()->prepare('SELECT * FROM tl_gallery_creator_albums WHERE id=?')->execute($objPicture->pid);
     $arrAlbumInfo = $objAlbum->fetchAssoc();
     //Bild-Besitzer
     $objOwner = \Database::getInstance()->prepare('SELECT name FROM tl_user WHERE id=?')->execute($objPicture->owner);
     $strImageSrc = '';
     $arrMeta = array();
     $objFileModel = \FilesModel::findByUuid($objPicture->uuid);
     if ($objFileModel == null) {
         $strImageSrc = $defaultThumbSRC;
     } else {
         $strImageSrc = $objFileModel->path;
         if (!is_file(TL_ROOT . '/' . $strImageSrc)) {
             // Fallback to the default thumb
             $strImageSrc = $defaultThumbSRC;
         }
         //meta
         $arrMeta = $objThis->getMetaData($objFileModel->meta, $objPage->language);
         // Use the file name as title if none is given
         if ($arrMeta['title'] == '') {
             $arrMeta['title'] = specialchars($objFileModel->name);
         }
     }
     // get thumb dimensions
     $arrSize = unserialize($objThis->gc_size_detailview);
     //Generate the thumbnails and the picture element
     try {
         $thumbSrc = \Image::create($strImageSrc, $arrSize)->executeResize()->getResizedPath();
         $picture = \Picture::create($strImageSrc, $arrSize)->getTemplateData();
         if ($thumbSrc !== $strImageSrc) {
             $objFile = new \File(rawurldecode($thumbSrc), true);
         }
     } catch (\Exception $e) {
         \System::log('Image "' . $strImageSrc . '" could not be processed: ' . $e->getMessage(), __METHOD__, TL_ERROR);
         $thumbSrc = '';
         $picture = array('img' => array('src' => '', 'srcset' => ''), 'sources' => array());
     }
     $picture['alt'] = $objPicture->title != '' ? specialchars($objPicture->title) : specialchars($arrMeta['title']);
     $picture['title'] = $objPicture->comment != '' ? $objPage->outputFormat == 'xhtml' ? specialchars(\String::toXhtml($objPicture->comment)) : specialchars(\String::toHtml5($objPicture->comment)) : specialchars($arrMeta['caption']);
     $objFileThumb = new \File(rawurldecode($thumbSrc));
     $arrSize[0] = $objFileThumb->width;
     $arrSize[1] = $objFileThumb->height;
     $arrFile["thumb_width"] = $objFileThumb->width;
     $arrFile["thumb_height"] = $objFileThumb->height;
     // get some image params
     if (is_file(TL_ROOT . '/' . $strImageSrc)) {
         $objFileImage = new \File($strImageSrc);
         if (!$objFileImage->isGdImage) {
             return null;
         }
         $arrFile["path"] = $objFileImage->path;
         $arrFile["basename"] = $objFileImage->basename;
         // filename without extension
         $arrFile["filename"] = $objFileImage->filename;
         $arrFile["extension"] = $objFileImage->extension;
         $arrFile["dirname"] = $objFileImage->dirname;
         $arrFile["image_width"] = $objFileImage->width;
         $arrFile["image_height"] = $objFileImage->height;
     } else {
         return null;
     }
     //check if there is a custom thumbnail selected
     if ($objPicture->addCustomThumb && !empty($objPicture->customThumb)) {
         $customThumbModel = \FilesModel::findByUuid($objPicture->customThumb);
         if ($customThumbModel !== null) {
             if (is_file(TL_ROOT . '/' . $customThumbModel->path)) {
                 $objFileCustomThumb = new \File($customThumbModel->path, true);
                 if ($objFileCustomThumb->isGdImage) {
                     $arrSize = unserialize($objThis->gc_size_detailview);
                     $thumbSrc = \Image::get($objFileCustomThumb->path, $arrSize[0], $arrSize[1], $arrSize[2]);
                     $objFileCustomThumb = new \File(rawurldecode($thumbSrc));
                     $arrSize[0] = $objFileCustomThumb->width;
                     $arrSize[1] = $objFileCustomThumb->height;
                     $arrFile["thumb_width"] = $objFileCustomThumb->width;
                     $arrFile["thumb_height"] = $objFileCustomThumb->height;
                 }
             }
         }
     }
     //exif
     if ($GLOBALS['TL_CONFIG']['gc_read_exif']) {
         try {
             $exif = is_callable('exif_read_data') && TL_MODE == 'FE' ? exif_read_data($strImageSrc) : array('info' => "The function 'exif_read_data()' is not available on this server.");
         } catch (Exception $e) {
             $exif = array('info' => "The function 'exif_read_data()' is not available on this server.");
         }
     } else {
         $exif = array('info' => "The function 'exif_read_data()' has not been activated in the Contao backend settings.");
     }
     //video-integration
     $strMediaSrc = trim($objPicture->socialMediaSRC) != "" ? trim($objPicture->socialMediaSRC) : "";
     if (\Validator::isUuid($objPicture->localMediaSRC)) {
         //get path of a local Media
         $objMovieFile = \FilesModel::findById($objPicture->localMediaSRC);
         $strMediaSrc = $objMovieFile !== null ? $objMovieFile->path : $strMediaSrc;
     }
     $href = null;
     if (TL_MODE == 'FE' && $objThis->gc_fullsize) {
         $href = $strMediaSrc != "" ? $strMediaSrc : \System::urlEncode($strImageSrc);
     }
     //cssID
     $cssID = deserialize($objPicture->cssID, true);
     // build the array
     $arrPicture = array('id' => $objPicture->id, 'pid' => $objPicture->pid, 'date' => $objPicture->date, 'owner' => $objPicture->owner, 'owners_name' => $objOwner->name, 'album_id' => $objPicture->pid, 'name' => specialchars($arrFile["basename"]), 'filename' => $arrFile["filename"], 'uuid' => $objPicture->uuid, 'path' => $arrFile["path"], 'basename' => $arrFile["basename"], 'dirname' => $arrFile["dirname"], 'extension' => $arrFile["extension"], 'alt' => $objPicture->title != '' ? specialchars($objPicture->title) : specialchars($arrMeta['title']), 'title' => $objPicture->title != '' ? specialchars($objPicture->title) : specialchars($arrMeta['title']), 'comment' => $objPicture->comment != '' ? $objPage->outputFormat == 'xhtml' ? specialchars(\String::toXhtml($objPicture->comment)) : specialchars(\String::toHtml5($objPicture->comment)) : specialchars($arrMeta['caption']), 'caption' => $objPicture->comment != '' ? $objPage->outputFormat == 'xhtml' ? specialchars(\String::toXhtml($objPicture->comment)) : specialchars(\String::toHtml5($objPicture->comment)) : specialchars($arrMeta['caption']), 'href' => TL_FILES_URL . $href, 'single_image_url' => $objPageModel->getFrontendUrl(($GLOBALS['TL_CONFIG']['useAutoItem'] ? '/' : '/items/') . \Input::get('items') . '/img/' . $arrFile["filename"], $objPage->language), 'image_src' => $arrFile["path"], 'media_src' => $strMediaSrc, 'socialMediaSRC' => $objPicture->socialMediaSRC, 'localMediaSRC' => $objPicture->localMediaSRC, 'addCustomThumb' => $objPicture->addCustomThumb, 'thumb_src' => isset($thumbSrc) ? TL_FILES_URL . $thumbSrc : '', 'size' => $arrSize, 'thumb_width' => $arrFile["thumb_width"], 'thumb_height' => $arrFile["thumb_height"], 'image_width' => $arrFile["image_width"], 'image_height' => $arrFile["image_height"], 'lightbox' => $objPage->outputFormat == 'xhtml' ? 'rel="lightbox[lb' . $objPicture->pid . ']"' : 'data-lightbox="lb' . $objPicture->pid . '"', 'tstamp' => $objPicture->tstamp, 'sorting' => $objPicture->sorting, 'published' => $objPicture->published, 'exif' => $exif, 'albuminfo' => $arrAlbumInfo, 'metaData' => $arrMeta, 'cssID' => $cssID[0] != '' ? $cssID[0] : '', 'cssClass' => $cssID[1] != '' ? $cssID[1] : '', 'externalFile' => $objPicture->externalFile, 'picture' => $picture);
     //Fuegt dem Array weitere Eintraege hinzu, falls tl_gallery_creator_pictures erweitert wurde
     $objPicture = \Database::getInstance()->prepare('SELECT * FROM tl_gallery_creator_pictures WHERE id=?')->execute($intPictureId);
     foreach ($objPicture->fetchAssoc() as $key => $value) {
         if (!array_key_exists($key, $arrPicture)) {
             $arrPicture[$key] = $value;
         }
     }
     return $arrPicture;
 }
 /**
  * Get all data for a file
  */
 private function getFileData($objFile, $objElements, $objPage)
 {
     $arrMeta = $this->getMetaData($objElements->meta, $objPage->language);
     // Use the file name as title if none is given
     if ($arrMeta['title'] == '') {
         $arrMeta['title'] = specialchars($objFile->basename);
     }
     // Use the title as link if none is given
     if ($arrMeta['link'] == '') {
         $arrMeta['link'] = $arrMeta['title'];
     }
     $strHref = \Environment::get('request');
     // Remove an existing file parameter (see #5683)
     if (preg_match('/(&(amp;)?|\\?)file=/', $strHref)) {
         $strHref = preg_replace('/(&(amp;)?|\\?)file=[^&]+/', '', $strHref);
     }
     $strHref .= ($GLOBALS['TL_CONFIG']['disableAlias'] || strpos($strHref, '?') !== false ? '&amp;' : '?') . 'file=' . \System::urlEncode($objElements->path);
     return array('id' => $objFile->id, 'uuid' => $objFile->uuid, 'name' => $objFile->basename, 'title' => $arrMeta['title'], 'link' => $arrMeta['link'], 'caption' => $arrMeta['caption'], 'href' => $strHref, 'filesize' => $this->getReadableSize($objFile->filesize, 1), 'icon' => TL_ASSETS_URL . 'assets/contao/images/' . $objFile->icon, 'mime' => $objFile->mime, 'meta' => $arrMeta, 'extension' => $objFile->extension, 'path' => $objFile->dirname);
 }
Ejemplo n.º 12
0
 /**
  * Generate download attributes
  * @param IsotopeProduct
  * @return string
  */
 public function generate(IsotopeProduct $objProduct, array $arrOptions = array())
 {
     global $objPage;
     $arrFiles = deserialize($objProduct->{$this->field_name});
     // Return if there are no files
     if (empty($arrFiles) || !is_array($arrFiles)) {
         return '';
     }
     // Get the file entries from the database
     $objFiles = \FilesModel::findMultipleByIds($arrFiles);
     if (null === $objFiles) {
         return '';
     }
     $file = \Input::get('file', true);
     // Send the file to the browser and do not send a 404 header (see #4632)
     if ($file != '' && !preg_match('/^meta(_[a-z]{2})?\\.txt$/', basename($file))) {
         while ($objFiles->next()) {
             if ($file == $objFiles->path || dirname($file) == $objFiles->path) {
                 \Controller::sendFileToBrowser($file);
             }
         }
         $objFiles->reset();
     }
     $files = array();
     $auxDate = array();
     $allowedDownload = trimsplit(',', strtolower($GLOBALS['TL_CONFIG']['allowedDownload']));
     // Get all files
     while ($objFiles->next()) {
         // Continue if the files has been processed or does not exist
         if (isset($files[$objFiles->path]) || !file_exists(TL_ROOT . '/' . $objFiles->path)) {
             continue;
         }
         // Single files
         if ($objFiles->type == 'file') {
             $objFile = new \File($objFiles->path, true);
             if (!in_array($objFile->extension, $allowedDownload) || preg_match('/^meta(_[a-z]{2})?\\.txt$/', $objFile->basename)) {
                 continue;
             }
             $arrMeta = \Frontend::getMetaData($objFiles->meta, $objPage->language);
             // Use the file name as title if none is given
             if ($arrMeta['title'] == '') {
                 $arrMeta['title'] = specialchars(str_replace('_', ' ', preg_replace('/^[0-9]+_/', '', $objFile->filename)));
             }
             $strHref = \Environment::get('request');
             // Remove an existing file parameter (see #5683)
             if (preg_match('/(&(amp;)?|\\?)file=/', $strHref)) {
                 $strHref = preg_replace('/(&(amp;)?|\\?)file=[^&]+/', '', $strHref);
             }
             $strHref .= ($GLOBALS['TL_CONFIG']['disableAlias'] || strpos($strHref, '?') !== false ? '&amp;' : '?') . 'file=' . \System::urlEncode($objFiles->path);
             // Add the image
             $files[$objFiles->path] = array('id' => $objFiles->id, 'uuid' => $objFiles->uuid, 'name' => $objFile->basename, 'title' => $arrMeta['title'], 'link' => $arrMeta['title'], 'caption' => $arrMeta['caption'], 'href' => $strHref, 'filesize' => \System::getReadableSize($objFile->filesize, 1), 'icon' => TL_ASSETS_URL . 'assets/contao/images/' . $objFile->icon, 'mime' => $objFile->mime, 'meta' => $arrMeta, 'extension' => $objFile->extension, 'path' => $objFile->dirname);
             $auxDate[] = $objFile->mtime;
         } else {
             $objSubfiles = \FilesModel::findByPid($objFiles->id);
             if ($objSubfiles === null) {
                 continue;
             }
             while ($objSubfiles->next()) {
                 // Skip subfolders
                 if ($objSubfiles->type == 'folder') {
                     continue;
                 }
                 $objFile = new \File($objSubfiles->path, true);
                 if (!in_array($objFile->extension, $allowedDownload) || preg_match('/^meta(_[a-z]{2})?\\.txt$/', $objFile->basename)) {
                     continue;
                 }
                 $arrMeta = \Frontend::getMetaData($objSubfiles->meta, $objPage->language);
                 // Use the file name as title if none is given
                 if ($arrMeta['title'] == '') {
                     $arrMeta['title'] = specialchars(str_replace('_', ' ', preg_replace('/^[0-9]+_/', '', $objFile->filename)));
                 }
                 $strHref = \Environment::get('request');
                 // Remove an existing file parameter (see #5683)
                 if (preg_match('/(&(amp;)?|\\?)file=/', $strHref)) {
                     $strHref = preg_replace('/(&(amp;)?|\\?)file=[^&]+/', '', $strHref);
                 }
                 $strHref .= ($GLOBALS['TL_CONFIG']['disableAlias'] || strpos($strHref, '?') !== false ? '&amp;' : '?') . 'file=' . \System::urlEncode($objSubfiles->path);
                 // Add the image
                 $files[$objSubfiles->path] = array('id' => $objSubfiles->id, 'uuid' => $objSubfiles->uuid, 'name' => $objFile->basename, 'title' => $arrMeta['title'], 'link' => $arrMeta['title'], 'caption' => $arrMeta['caption'], 'href' => $strHref, 'filesize' => \System::getReadableSize($objFile->filesize, 1), 'icon' => TL_ASSETS_URL . 'assets/contao/images/' . $objFile->icon, 'mime' => $objFile->mime, 'meta' => $arrMeta, 'extension' => $objFile->extension, 'path' => $objFile->dirname);
                 $auxDate[] = $objFile->mtime;
             }
         }
     }
     // Sort array
     $sortBy = $arrOptions['sortBy'] ?: $this->sortBy;
     switch ($sortBy) {
         default:
         case 'name_asc':
             uksort($files, 'basename_natcasecmp');
             break;
         case 'name_desc':
             uksort($files, 'basename_natcasercmp');
             break;
         case 'date_asc':
             array_multisort($files, SORT_NUMERIC, $auxDate, SORT_ASC);
             break;
         case 'date_desc':
             array_multisort($files, SORT_NUMERIC, $auxDate, SORT_DESC);
             break;
         case 'custom':
             if ($objProduct->{$this->field_name . '_order'} != '') {
                 $tmp = deserialize($objProduct->{$this->field_name . '_order'});
                 if (!empty($tmp) && is_array($tmp)) {
                     // Remove all values
                     $arrOrder = array_map(function () {
                     }, array_flip($tmp));
                     // Move the matching elements to their position in $arrOrder
                     foreach ($files as $k => $v) {
                         if (array_key_exists($v['uuid'], $arrOrder)) {
                             $arrOrder[$v['uuid']] = $v;
                             unset($files[$k]);
                         }
                     }
                     // Append the left-over files at the end
                     if (!empty($files)) {
                         $arrOrder = array_merge($arrOrder, array_values($files));
                     }
                     // Remove empty (unreplaced) entries
                     $files = array_values(array_filter($arrOrder));
                     unset($arrOrder);
                 }
             }
             break;
         case 'random':
             shuffle($files);
             break;
     }
     $objTemplate = new \Isotope\Template('ce_downloads');
     $objTemplate->class = $this->field_name;
     $objTemplate->files = array_values($files);
     return $objTemplate->parse();
 }
Ejemplo n.º 13
0
 /**
  * Generate an XML files and save them to the root directory
  *
  * @param array
  */
 protected function generateFiles($arrFeed)
 {
     $arrArchives = deserialize($arrFeed['archives']);
     if (!is_array($arrArchives) || empty($arrArchives)) {
         return;
     }
     $strType = 'generateItunes';
     $strLink = $arrFeed['feedBase'] ?: \Environment::get('base');
     $strFile = $arrFeed['feedName'];
     $objFeed = new iTunesFeed($strFile);
     $objFeed->link = $strLink;
     $objFeed->podcastUrl = $strLink . 'share/' . $strFile . '.xml';
     $objFeed->title = $arrFeed['title'];
     $objFeed->subtitle = $arrFeed['subtitle'];
     $objFeed->description = $this->cleanHtml($arrFeed['description']);
     $objFeed->explicit = $arrFeed['explicit'];
     $objFeed->language = $arrFeed['language'];
     $objFeed->author = $arrFeed['author'];
     $objFeed->owner = $arrFeed['owner'];
     $objFeed->email = $arrFeed['email'];
     $objFeed->category = $arrFeed['category'];
     $objFeed->published = $arrFeed['tstamp'];
     //Add Feed Image
     $objFile = \FilesModel::findByUuid($arrFeed['image']);
     if ($objFile !== null) {
         $objFeed->imageUrl = \Environment::get('base') . $objFile->path;
     }
     // Get the items
     if ($arrFeed['maxItems'] > 0) {
         $objPodcasts = \NewsPodcastsModel::findPublishedByPids($arrArchives, null, $arrFeed['maxItems']);
     } else {
         $objPodcasts = \NewsPodcastsModel::findPublishedByPids($arrArchives);
     }
     // Parse the items
     if ($objPodcasts !== null) {
         $arrUrls = array();
         while ($objPodcasts->next()) {
             $jumpTo = $objPodcasts->getRelated('pid')->jumpTo;
             // No jumpTo page set (see #4784)
             if (!$jumpTo) {
                 continue;
             }
             // Get the jumpTo URL
             if (!isset($arrUrls[$jumpTo])) {
                 $objParent = \PageModel::findWithDetails($jumpTo);
                 // A jumpTo page is set but does no longer exist (see #5781)
                 if ($objParent === null) {
                     $arrUrls[$jumpTo] = false;
                 } else {
                     $arrUrls[$jumpTo] = $this->generateFrontendUrl($objParent->row(), $GLOBALS['TL_CONFIG']['useAutoItem'] && !$GLOBALS['TL_CONFIG']['disableAlias'] ? '/%s' : '/items/%s', $objParent->language);
                 }
             }
             // Skip the event if it requires a jumpTo URL but there is none
             if ($arrUrls[$jumpTo] === false && $objPodcasts->source == 'default') {
                 continue;
             }
             $strUrl = $arrUrls[$jumpTo];
             $objItem = new \FeedItem();
             $objItem->headline = $this->cleanHtml($objPodcasts->headline);
             $objItem->subheadline = $this->cleanHtml($objPodcasts->subheadline !== null ? $objPodcasts->subheadline : $objPodcasts->description);
             $objItem->link = $strLink . sprintf($strUrl, $objPodcasts->alias != '' && !$GLOBALS['TL_CONFIG']['disableAlias'] ? $objPodcasts->alias : $objPodcasts->id);
             $objItem->published = $objPodcasts->date;
             $objAuthor = $objPodcasts->getRelated('author');
             $objItem->author = $objAuthor->name;
             $objItem->description = $this->cleanHtml($objPodcasts->teaser);
             $objItem->explicit = $objPodcasts->explicit;
             // Add the article image as enclosure
             $objItem->addEnclosure($objFeed->imageUrl);
             // Add the Audio File
             if ($objPodcasts->podcast) {
                 $objFile = \FilesModel::findByUuid($objPodcasts->podcast);
                 if ($objFile !== null) {
                     // Add statistics service
                     if (!empty($arrFeed['addStatistics'])) {
                         // If no trailing slash given, add one
                         $statisticsPrefix = rtrim($arrFeed['statisticsPrefix'], '/') . '/';
                         $podcastPath = $statisticsPrefix . \Environment::get('host') . '/' . preg_replace('(^https?://)', '', $objFile->path);
                     } else {
                         $podcastPath = \Environment::get('base') . \System::urlEncode($objFile->path);
                     }
                     $objItem->podcastUrl = $podcastPath;
                     // Prepare the duration / prefer linux tool mp3info
                     $mp3file = new GetMp3Duration(TL_ROOT . '/' . $objFile->path);
                     if ($this->checkMp3InfoInstalled()) {
                         $shell_command = 'mp3info -p "%S" ' . escapeshellarg(TL_ROOT . '/' . $objFile->path);
                         $duration = shell_exec($shell_command);
                     } else {
                         $duration = $mp3file->getDuration();
                     }
                     $objPodcastFile = new \File($objFile->path, true);
                     $objItem->length = $objPodcastFile->size;
                     $objItem->type = $objPodcastFile->mime;
                     $objItem->duration = $mp3file->formatTime($duration);
                 }
             }
             $objFeed->addItem($objItem);
         }
     }
     // Create the file
     \File::putContent('share/' . $strFile . '.xml', $this->replaceInsertTags($objFeed->{$strType}(), false));
 }
Ejemplo n.º 14
0
 /**
  * Generate an image tag and return it as string
  *
  * @param string $src        The image path
  * @param string $alt        An optional alt attribute
  * @param string $attributes A string of other attributes
  *
  * @return string The image HTML tag
  */
 public static function getHtml($src, $alt = '', $attributes = '')
 {
     $src = static::getPath($src);
     if ($src == '' || !is_file(TL_ROOT . '/' . $src)) {
         return '';
     }
     $objFile = new \File($src, true);
     $static = strncmp($src, 'assets/', 7) === 0 ? TL_ASSETS_URL : TL_FILES_URL;
     return '<img src="' . $static . \System::urlEncode($src) . '" width="' . $objFile->width . '" height="' . $objFile->height . '" alt="' . specialchars($alt) . '"' . ($attributes != '' ? ' ' . $attributes : '') . '>';
 }
Ejemplo n.º 15
0
 /**
  * Generate an image tag and return it as string
  *
  * @param string $src        The image path
  * @param string $alt        An optional alt attribute
  * @param string $attributes A string of other attributes
  *
  * @return string The image HTML tag
  */
 public static function getHtml($src, $alt = '', $attributes = '')
 {
     $src = static::getPath($src);
     if ($src == '') {
         return '';
     }
     if (!is_file(TL_ROOT . '/' . $src)) {
         // Handle public bundle resources
         if (file_exists(TL_ROOT . '/web/' . $src)) {
             $src = 'web/' . $src;
         } else {
             return '';
         }
     }
     $objFile = new \File($src);
     // Strip the web/ prefix (see #337)
     if (strncmp($src, 'web/', 4) === 0) {
         $src = substr($src, 4);
     }
     $static = strncmp($src, 'assets/', 7) === 0 ? TL_ASSETS_URL : TL_FILES_URL;
     return '<img src="' . $static . \System::urlEncode($src) . '" width="' . $objFile->width . '" height="' . $objFile->height . '" alt="' . \StringUtil::specialchars($alt) . '"' . ($attributes != '' ? ' ' . $attributes : '') . '>';
 }
Ejemplo n.º 16
0
 /**
  * Add an enclosure
  *
  * @param string $strFile The file path
  * @param string $strUrl  The base URL
  */
 public function addEnclosure($strFile, $strUrl = null)
 {
     if ($strFile == '' || !file_exists(TL_ROOT . '/' . $strFile)) {
         return;
     }
     if ($strUrl === null) {
         $strUrl = \Environment::get('base');
     }
     $objFile = new \File($strFile, true);
     $this->arrData['enclosure'][] = array('url' => $strUrl . \System::urlEncode($strFile), 'length' => $objFile->size, 'type' => $objFile->mime);
 }
 protected function getInfoAction(\File $objFile)
 {
     $strUrl = null;
     $strFileNameEncoded = utf8_convert_encoding($objFile->name, \Config::get('characterSet'));
     switch (TL_MODE) {
         case 'FE':
             $strHref = Url::getCurrentUrlWithoutParameters();
             $strHref .= (\Config::get('disableAlias') || strpos($strHref, '?') !== false ? '&amp;' : '?') . 'file=' . \System::urlEncode($objFile->value);
             return 'window.open("' . $strHref . '", "_blank");';
             break;
         case 'BE':
             if (\Input::get('popup')) {
                 return null;
             } else {
                 $popupWidth = 664;
                 $popupHeight = 299;
                 $href = 'contao/popup.php?src=' . base64_encode($objFile->value);
                 return 'Backend.openModalIframe({"width":"' . $popupWidth . '","title":"' . str_replace("'", "\\'", specialchars($strFileNameEncoded, false, true)) . '","url":"' . $href . '","height":"' . $popupHeight . '"});return false';
             }
             break;
     }
     return $strUrl;
 }
Ejemplo n.º 18
0
 /**
  * Generate an image tag and return it as string
  *
  * @param string $src        The image path
  * @param string $alt        An optional alt attribute
  * @param string $attributes A string of other attributes
  *
  * @return string The image HTML tag
  */
 public static function getHtml($src, $alt = '', $attributes = '')
 {
     $static = TL_FILES_URL;
     $src = rawurldecode($src);
     if (strpos($src, '/') === false) {
         if (strncmp($src, 'icon', 4) === 0) {
             $static = TL_ASSETS_URL;
             $src = 'assets/contao/images/' . $src;
         } else {
             $src = 'system/themes/' . \Backend::getTheme() . '/images/' . $src;
         }
     }
     if (!file_exists(TL_ROOT . '/' . $src)) {
         return '';
     }
     $size = getimagesize(TL_ROOT . '/' . $src);
     return '<img src="' . $static . \System::urlEncode($src) . '" ' . $size[3] . ' alt="' . specialchars($alt) . '"' . ($attributes != '' ? ' ' . $attributes : '') . '>';
 }
 /**
  * Handle downloads
  * @return bool return true, or false if the file does not exist
  */
 protected function handleDownload()
 {
     $objFile = \HeimrichHannot\Haste\Util\Files::getFileFromUuid($this->fileSRC);
     if ($objFile === null) {
         return false;
     }
     $allowedDownload = trimsplit(',', strtolower(\Config::get('allowedDownload')));
     // Return if the file type is not allowed
     if (!in_array($objFile->extension, $allowedDownload) || preg_match('/^meta(_[a-z]{2})?\\.txt$/', $objFile->basename)) {
         return false;
     }
     $arrMeta = $this->getMetaFromFile($objFile);
     $file = \Input::get('file', true);
     // Send the file to the browser and do not send a 404 header (see #4632)
     if ($file != '' && $file == $objFile->path) {
         \Controller::sendFileToBrowser($file);
     }
     $this->setHref(\Environment::get('request'));
     // Remove an existing file parameter (see #5683)
     if (preg_match('/(&(amp;)?|\\?)file=/', $this->getHref())) {
         $this->setHref(preg_replace('/(&(amp;)?|\\?)file=[^&]+/', '', $this->getHref()));
     }
     $this->setHref($this->getHref() . (\Config::get('disableAlias') || strpos($this->getHref(), '?') !== false ? '&amp;' : '?') . 'file=' . \System::urlEncode($objFile->path));
     $this->setTitle(sprintf($GLOBALS['TL_LANG']['MSC']['linkteaser']['downloadTitle'], $arrMeta['title']));
     $this->setLink(sprintf($this->getLink(), $arrMeta['title']));
     return true;
 }
Ejemplo n.º 20
0
 /**
  * Generate an image tag and return it as string
  *
  * @param string $src        The image path
  * @param string $alt        An optional alt attribute
  * @param string $attributes A string of other attributes
  *
  * @return string The image HTML tag
  */
 public static function getHtml($src, $alt = '', $attributes = '')
 {
     $static = TL_FILES_URL;
     $src = rawurldecode($src);
     if (strpos($src, '/') === false) {
         if (strncmp($src, 'icon', 4) === 0) {
             $static = TL_ASSETS_URL;
             $src = 'assets/contao/images/' . $src;
         } else {
             $src = 'system/themes/' . \Backend::getTheme() . '/images/' . $src;
         }
     }
     $path = $src;
     if (!file_exists(TL_ROOT . '/' . $src)) {
         // Handle public bundle resources
         if (file_exists(TL_ROOT . '/web/' . $src)) {
             $path = 'web/' . $src;
         } else {
             return '';
         }
     }
     $objFile = new \File($path);
     return '<img src="' . $static . \System::urlEncode($src) . '" width="' . $objFile->width . '" height="' . $objFile->height . '" alt="' . specialchars($alt) . '"' . ($attributes != '' ? ' ' . $attributes : '') . '>';
 }
 public function compile()
 {
     if (TL_MODE == 'FE') {
         $strHref = \Environment::get('request');
         // Remove an existing file parameter (see #5683)
         if (preg_match('/(&(amp;)?|\\?)' . $this->strQsParam . '=/', $strHref)) {
             $strHref = preg_replace('/(&(amp;)?|\\?)' . $this->strQsParam . '=[^&]+/', '', $strHref);
         }
         $strDownloadBaseUrl = $strHref . (\Config::get('disableAlias') || strpos($strHref, '?') !== false ? '&amp;' : '?') . $this->strQsParam . '=';
         //$appInfo = new dbx\AppInfo(\Config::get('dropboxApiKey'), \Config::get('dropboxApiSecret'));
         //$webAuth = new dbx\WebAuthNoRedirect($appInfo, "PHP-Example/1.0");
         //$authorizeUrl = $webAuth->start();
         $accessToken = \Config::get('dropboxAccessToken');
         $dbxClient = new \DropboxClient($accessToken, "PHP-Example/1.0");
         // =========================================================================================================
         // get metadata by chooser
         // =========================================================================================================
         if ($this->dropboxChooserFiles !== '') {
             $children = json_decode($this->dropboxChooserFiles, true);
             //		        foreach ($filesList as $f)
             //		        {
             //			        $f['path'] = $f['name'];
             //			        //$f['download_link'] = $dbxClient->createTemporaryDirectLink($f['link']);
             //		        }
             //$this->Template->filesInFolder = $filesList;
         }
         // $previewLink = 'https://www.dropbox.com/s/wq6u9zx1psa9nrh/2012-11-26%201%20Battesimo.pdf?dl=0';
         // $metadata = $dbxClient->getMetadataSharedLink($previewLink);
         // =========================================================================================================
         // get metadata by path
         // =========================================================================================================
         //$metadata = $dbxClient->getMetadataWithChildren(urldecode($this->dropboxPath));
         //            $pathError = dbx\Path::findError($this->dropboxPath);
         //            if ($pathError !== null)
         //            {
         //                $this->Template->errors = "Invalid <dropbox-path>: $pathError";
         //                return;
         //            }
         Dump($children);
         if ($this->dropboxPath !== '') {
             if ($metadata === null) {
                 $this->Template->errors = "No file or folder at that path.";
                 return;
             }
             // If it's a folder, remove the 'contents' list from $metadata; print that stuff out after.
             $children = null;
             if ($metadata['is_dir']) {
                 $children = $metadata['contents'];
                 unset($metadata['contents']);
             }
             $this->Template->metadata = $metadata;
         }
         $ff = array();
         foreach ($children as $f) {
             if (array_key_exists('path', $f)) {
                 $name = dbx\Path::getName($f['path']);
             } else {
                 $name = $f['name'];
             }
             // Put a "/" after folder names.
             $f['name'] = $name . ($f['is_dir'] ? '/' : '');
             if ($f['is_dir']) {
                 $f['download_link'] = '';
             } else {
                 $f['download_link'] = $strDownloadBaseUrl . \System::urlEncode($name);
             }
             $ff[] = $f;
         }
         $this->Template->filesInFolder = $ff;
         Dump($GLOBALS['TL_DCA']['tl_content']['palettes']['__selector__']);
     }
 }