public function run()
 {
     if (version_compare(VERSION, '3.0', '>=') && $this->Database->tableExists('tl_files') && $this->Database->fieldExists('image', 'tl_link_data')) {
         $objData = $this->Database->prepare("SELECT id,image FROM tl_link_data WHERE 1")->execute();
         if ($objData->numRows) {
             while ($objData->next()) {
                 $objImage = $this->Database->prepare("SELECT id FROM tl_files WHERE path = ?")->execute($objData->image);
                 if ($objImage->id > 0) {
                     $this->log("UPDATE tl_link_data SET image = " . $objImage->id . " WHERE id = " . $objData->id . " ", 'SQL Update 2.x to 3.x', TL_GENERAL);
                     $this->Database->prepare("UPDATE tl_link_data SET image = ? WHERE id = ? ")->execute($objImage->id, $objData->id);
                 }
             }
         }
     }
     if (version_compare(VERSION, '3.2', '>=') && $this->Database->tableExists('tl_link_data')) {
         $arrFields = $this->Database->listFields('tl_link_data');
         foreach ($arrFields as $arrField) {
             if ($arrField['name'] == 'image' && $arrField['type'] != 'binary') {
                 Database\Updater::convertSingleField('tl_link_data', 'image');
             }
         }
     }
     /* remove protocol */
     $this->Database->prepare("UPDATE `tl_link_data` SET `url` = CONCAT(`url_protocol`, `url`), url_protocol = ''")->execute();
     if (version_compare(VERSION, '3.2', '>=')) {
         $strFile = 'system/modules/delirius_linkliste/config/database.sql';
         if (\Files::getInstance()->is_writeable($strFile)) {
             \Files::getInstance()->delete($strFile);
         }
     }
 }
 /**
  * Generate the widget and return it as string
  * @param array
  * @return string
  */
 public function parse($arrAttributes = null)
 {
     if ($this->varValue != '') {
         $blnTemporaryFile = $this->isTemporaryFile($this->varValue);
         if ($blnTemporaryFile) {
             $strNew = $this->getThumbnailPath($this->varValue);
             // Auto-resize the user avatar
             if (\Config::get('avatar_user_autoresize')) {
                 $this->varValue = \Image::get($this->varValue, $this->arrAvatarSize[0], $this->arrAvatarSize[1], 'center_center');
                 // Copy the file
                 if (\Files::getInstance()->rename($this->varValue, $strNew)) {
                     $this->varValue = $strNew;
                     $blnTemporaryFile = false;
                 }
             } else {
                 // If the file is temporary but has the exact avatar dimensions
                 // there is no need to crop it just treat it as a ready avatar
                 $arrSize = @getimagesize(TL_ROOT . '/' . $this->varValue);
                 if ($arrSize[0] == $this->arrAvatarSize[0] && $arrSize[1] == $this->arrAvatarSize[1] && \Files::getInstance()->rename($this->varValue, $strNew)) {
                     $this->varValue = $strNew;
                     $blnTemporaryFile = false;
                 }
             }
         }
         // Temporary file
         if ($blnTemporaryFile) {
             // Crop the file
             if (\Input::post('crop') != '') {
                 list($intPositionX, $intPositionY) = explode(',', \Input::post('crop'));
                 $this->varValue = $this->cropImage($this->varValue, $intPositionX, $intPositionY);
                 $this->thumbnail = \Image::getHtml($this->varValue);
                 $this->imgSize = @getimagesize(TL_ROOT . '/' . $this->varValue);
                 $this->set = $this->varValue;
                 $this->noCrop = true;
             } else {
                 // Crop mode
                 $strThumbnail = $this->getThumbnail($this->varValue);
                 $this->thumbnail = \Image::getHtml($strThumbnail);
                 $this->imgSize = @getimagesize(TL_ROOT . '/' . $strThumbnail);
             }
         } else {
             // Avatar
             $this->avatar = \Image::getHtml(\Image::get($this->varValue, $this->arrAvatarSize[0], $this->arrAvatarSize[1], 'center_center'));
             $this->set = $this->varValue;
         }
     }
     $this->ajax = \Environment::get('isAjaxRequest');
     $this->delete = $GLOBALS['TL_LANG']['MSC']['delete'];
     $this->deleteTitle = specialchars($GLOBALS['TL_LANG']['MSC']['delete']);
     $this->crop = $GLOBALS['TL_LANG']['MSC']['avatar_crop'];
     $this->cropTitle = specialchars($GLOBALS['TL_LANG']['MSC']['avatar_crop']);
     $this->extensions = json_encode(trimsplit(',', $this->getAllowedExtensions()));
     $this->sizeLimit = $this->getMaximumFileSize();
     $this->avatarSize = json_encode($this->arrAvatarSize);
     $this->texts = json_encode(array('text' => array('formatProgress' => $GLOBALS['TL_LANG']['MSC']['avatar_fineuploader_formatProgress'], 'failUpload' => $GLOBALS['TL_LANG']['MSC']['avatar_fineuploader_failUpload'], 'waitingForResponse' => $GLOBALS['TL_LANG']['MSC']['avatar_fineuploader_waitingForResponse'], 'paused' => $GLOBALS['TL_LANG']['MSC']['avatar_fineuploader_paused']), 'messages' => array('tooManyFilesError' => $GLOBALS['TL_LANG']['MSC']['avatar_fineuploader_tooManyFilesError'], 'unsupportedBrowser' => $GLOBALS['TL_LANG']['MSC']['avatar_fineuploader_unsupportedBrowser']), 'retry' => array('autoRetryNote' => $GLOBALS['TL_LANG']['MSC']['avatar_fineuploader_autoRetryNote']), 'deleteFile' => array('confirmMessage' => $GLOBALS['TL_LANG']['MSC']['avatar_fineuploader_confirmMessage'], 'deletingStatusText' => $GLOBALS['TL_LANG']['MSC']['avatar_fineuploader_deletingStatusText'], 'deletingFailedText' => $GLOBALS['TL_LANG']['MSC']['avatar_fineuploader_deletingFailedText']), 'paste' => array('namePromptMessage' => $GLOBALS['TL_LANG']['MSC']['avatar_fineuploader_namePromptMessage'])));
     $this->labels = array('drop' => $GLOBALS['TL_LANG']['MSC']['avatar_drop'], 'upload' => $GLOBALS['TL_LANG']['MSC']['avatar_upload'], 'processing' => $GLOBALS['TL_LANG']['MSC']['avatar_processing']);
     return parent::parse($arrAttributes);
 }
 /**
  * Create the new twig contao environment
  */
 protected function __construct()
 {
     $arrTemplatePaths = array();
     $blnDebug = $GLOBALS['TL_CONFIG']['debugMode'] || $GLOBALS['TL_CONFIG']['twigDebugMode'];
     // Make sure the cache directory exists
     if (version_compare(VERSION, '2', '<=') && !is_dir(TL_ROOT . '/system/cache')) {
         Files::getInstance()->mkdir('system/cache');
     }
     if (!is_dir(TL_ROOT . '/system/cache/twig')) {
         Files::getInstance()->mkdir('system/cache/twig');
     }
     // Add the layout templates directory
     if (TL_MODE == 'FE') {
         global $objPage;
         $strTemplateGroup = str_replace(array('../', 'templates/'), '', $objPage->templateGroup);
         if ($strTemplateGroup != '') {
             $arrTemplatePaths[] = TL_ROOT . '/templates/' . $strTemplateGroup;
         }
     }
     // Add the global templates directory
     $arrTemplatePaths[] = TL_ROOT . '/templates';
     // Add all modules templates directories
     foreach (Config::getInstance()->getActiveModules() as $strModule) {
         $strPath = TL_ROOT . '/system/modules/' . $strModule . '/templates';
         if (is_dir($strPath)) {
             $arrTemplatePaths[] = $strPath;
         }
     }
     // Create the default array loader
     $this->loaderArray = new Twig_Loader_Array(array());
     // Create the default filesystem loader
     $this->loaderFilesystem = new Twig_Loader_Filesystem($arrTemplatePaths);
     // Create the effective chain loader
     $this->loader = new Twig_Loader_Chain();
     // Register the default filesystem loaders
     $this->loader->addLoader($this->loaderArray);
     $this->loader->addLoader($this->loaderFilesystem);
     // Create the environment
     $this->environment = new Twig_Environment($this->loader, array('cache' => TL_ROOT . '/system/cache/twig', 'debug' => $blnDebug, 'autoescape' => false));
     // set default formats
     $this->environment->getExtension('core')->setNumberFormat(2, $GLOBALS['TL_LANG']['MSC']['decimalSeparator'], $GLOBALS['TL_LANG']['MSC']['thousandsSeparator']);
     // set default date format and timezone
     $this->environment->getExtension('core')->setDateFormat($GLOBALS['TL_CONFIG']['datimFormat']);
     $this->environment->getExtension('core')->setTimezone('Europe/Paris');
     // Add debug extension
     if ($blnDebug || $GLOBALS['TL_CONFIG']['twigDebugExtension']) {
         $this->environment->addExtension(new Twig_Extension_Debug());
     }
     $this->environment->addExtension(new ContaoTwigExtension());
     // HOOK: custom twig initialisation
     if (isset($GLOBALS['TL_HOOKS']['initializeTwig']) && is_array($GLOBALS['TL_HOOKS']['initializeTwig'])) {
         foreach ($GLOBALS['TL_HOOKS']['initializeTwig'] as $callback) {
             $this->import($callback[0]);
             $this->{$callback}[0]->{$callback}[1]($this);
         }
     }
 }
 /**
  * Construct object
  * 
  * @param string $strFileName
  * @param string $strPath 
  */
 public function __construct($strFileName, $strPath)
 {
     $this->_objHelper = ClipboardHelper::getInstance();
     $this->_objXmlWriter = ClipboardXmlWriter::getInstance();
     $this->_objXmlReader = ClipboardXmlReader::getInstance();
     $this->_objFiles = Files::getInstance();
     $this->_filename = $strFileName;
     $this->_path = $strPath;
 }
Beispiel #5
0
 /**
  * @param \Compat\FilesModel|int|string $file
  * @return bool
  */
 public static function deleteFile($file)
 {
     // normalize path
     $file = preg_replace('~//+~', '/', $file);
     if (file_exists(TL_ROOT . '/' . $file)) {
         return \Files::getInstance()->delete($file);
     }
     return false;
 }
Beispiel #6
0
 /**
  * Prevent constructing the object (Singleton)
  */
 protected function __construct()
 {
     parent::__construct();
     $this->import('BackendUser', 'User');
     $this->_objXmlReader = ClipboardXmlReader::getInstance();
     $this->_objXmlWriter = ClipboardXmlWriter::getInstance();
     $this->_objHelper = ClipboardHelper::getInstance();
     $this->_objFiles = Files::getInstance();
     $this->_createClipboardFromFiles();
 }
 /**
  * Compile the asset and return true on success
  *
  * @throws \Exception
  */
 protected function compile()
 {
     $file = $this->getTemporaryFile();
     $sourceMap = !$this->model->disableSourceMap;
     exec(sprintf('sass %s %s %s', TL_ROOT . '/' . $this->getSourceFile()->path, TL_ROOT . '/' . $file->path, !$sourceMap ? '--sourcemap=none' : ''));
     // Move the source map to assets folder
     if ($sourceMap) {
         $folder = str_replace(TL_ROOT, '', $file->dirname);
         $sourceMapFileName = $file->filename . '.css.map';
         \Files::getInstance()->rename($folder . '/' . $sourceMapFileName, 'assets/css/' . $sourceMapFileName);
     }
 }
 public function run()
 {
     if (!file_exists(TL_ROOT . '/system/languages/locallang.php')) {
         // The composer client uses a custom error handler so the auto creation of the folder does not work
         // because Contao does not check if the folder exists.
         if (!is_dir(TL_ROOT . '/system/languages')) {
             $files = \Files::getInstance();
             $files->mkdir('system/languages');
         }
         $file = new \File('system/languages/locallang.php');
         $file->write('<?php' . "\n");
         $file->close();
     }
 }
 /**
  * Moves an uploaded file to the tmp folder and returns its TL_ROOT relative path.
  * If it was not properly uploaded, the method will return null.
  *
  * @param array $file
  * @return null|string
  */
 public static function getFileUploadPathForToken(array $file)
 {
     if (!is_uploaded_file($file['tmp_name'])) {
         if (file_exists($file['tmp_name'])) {
             $basePath = TL_ROOT . "/";
             return str_replace($basePath, '', $file['tmp_name']);
         }
         return null;
     }
     $tmpDir = 'system/tmp';
     $filePath = $tmpDir . '/' . $file['name'];
     \Files::getInstance()->move_uploaded_file($file['tmp_name'], $filePath);
     \Files::getInstance()->chmod($filePath, $GLOBALS['TL_CONFIG']['defaultFileChmod']);
     return $filePath;
 }
Beispiel #10
0
 /**
  * Recursively create a directory
  * @param   string
  * @param   bool
  * @return  bool
  * @deprecated use `new Folder(...)` (see https://github.com/contao/core/issues/6553)
  */
 public static function mkdirr($strDirectory)
 {
     $components = explode('/', $strDirectory);
     $strDirectory = '';
     foreach ($components as $folder) {
         $strDirectory .= '/' . (string) $folder;
         $strDirectory = ltrim($strDirectory, '/');
         // Does not matter if file or directory
         if (!file_exists(TL_ROOT . '/' . $strDirectory)) {
             if (!\Files::getInstance()->mkdir($strDirectory)) {
                 return false;
             }
         }
     }
     return is_dir(TL_ROOT . '/' . $strDirectory);
 }
 public function run()
 {
     if (version_compare(VERSION, '3.2', '>=') && $this->Database->tableExists('tl_slogan_data')) {
         $arrFields = $this->Database->listFields('tl_slogan_data');
         foreach ($arrFields as $arrField) {
             if ($arrField['name'] == 'image' && $arrField['type'] != 'binary') {
                 Database\Updater::convertSingleField('tl_slogan_data', 'image');
             }
         }
     }
     if (version_compare(VERSION, '3.2', '>=')) {
         $strFile = 'system/modules/delirius_slogan/config/database.sql';
         if (\Files::getInstance()->is_writeable($strFile)) {
             \Files::getInstance()->delete($strFile);
         }
     }
 }
Beispiel #12
0
 /**
  * Constructor
  */
 public function __construct()
 {
     parent::__construct();
     // Init
     $this->objSyncCtoHelper = SyncCtoHelper::getInstance();
     $this->objFiles = \Files::getInstance();
     $this->strTimestampFormat = str_replace(array(':', ' '), array('', '_'), $GLOBALS['TL_CONFIG']['datimFormat']);
     // Load blacklists and whitelists
     $this->arrRootFolderList = $this->objSyncCtoHelper->getWhitelistFolder();
     // Get memory limit
     $this->intMaxMemoryUsage = SyncCtoModuleClient::parseSize(ini_get('memory_limit'));
     $this->intMaxMemoryUsage = $this->intMaxMemoryUsage / 100 * 30;
     // Get execution limit
     $this->intMaxExecutionTime = SyncCtoHelper::parseRuntime(ini_get('max_execution_time'));
     $this->intMaxExecutionTime = intval($this->intMaxExecutionTime / 100 * 25);
     // Flags for file scanning.
     $this->strRDIFlags = RecursiveDirectoryIterator::FOLLOW_SYMLINKS | RecursiveDirectoryIterator::SKIP_DOTS | RecursiveDirectoryIterator::UNIX_PATHS;
 }
 /**
  * {@inheritdoc}
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  */
 public function optimize($strImage, $strTarget = null)
 {
     $objFile = new \File($strImage, true);
     if (!$strTarget) {
         $strTarget = $strImage;
     }
     if ($objFile->exists() && $objFile->extension == 'png') {
         // advpng does not support output files,
         // so we need to copy the file before optimize it
         if ($strImage != $strTarget) {
             \Files::getInstance()->copy($strImage, $strTarget);
         }
         $objProcessBuilder = new ProcessBuilder();
         $objProcessBuilder->add($this->strPath);
         $objProcessBuilder->add('-z');
         switch ($this->strLevel) {
             case 'store':
                 $objProcessBuilder->add('--shrink-store');
                 break;
             case 'fast':
                 $objProcessBuilder->add('--shrink-fast');
                 break;
             case 'extra':
                 $objProcessBuilder->add('--shrink-extra');
                 break;
             case 'insane':
                 $objProcessBuilder->add('--shrink-insane');
                 break;
             default:
                 $objProcessBuilder->add('--shrink-normal');
                 break;
         }
         $objProcessBuilder->add(TL_ROOT . '/' . $strTarget);
         $objProcess = $objProcessBuilder->getProcess();
         $objProcess->run();
         if (!$objProcess->isSuccessful()) {
             throw new \RuntimeException('Could not execute advpng: ' . $objProcess->getErrorOutput());
         }
         return $strTarget;
     }
     return $strImage;
 }
 /**
  * Move the temporary file to its destination
  * @param string
  * @param string
  * @return string
  */
 protected function moveTemporaryFile($strFile, $strDestination)
 {
     if (!is_file(TL_ROOT . '/' . $strFile)) {
         return '';
     }
     // Do not store the file
     if (!$this->arrConfiguration['storeFile']) {
         return $strFile;
     }
     // The file is not temporary
     if (stripos($strFile, $this->strTemporaryPath) === false) {
         return $strFile;
     }
     $strNew = $strDestination . '/' . basename($strFile);
     // Do not overwrite existing files
     if ($this->arrConfiguration['doNotOverwrite']) {
         $strNew = $strDestination . '/' . $this->getFileName(basename($strFile), $strDestination);
     }
     $blnRename = \Files::getInstance()->rename($strFile, $strNew);
     // Add the file to Dbafs
     if ($this->arrConfiguration['addToDbafs'] && $blnRename) {
         $objModel = \Dbafs::addResource($strNew);
         if ($objModel !== null) {
             $strNew = $objModel->uuid;
         }
     }
     return $strNew;
 }
Beispiel #15
0
 /**
  * Resize an image and store the resized version in the assets/images folder
  *
  * @param string  $image  The image path
  * @param integer $width  The target width
  * @param integer $height The target height
  * @param string  $mode   The resize mode
  * @param string  $target An optional target path
  * @param boolean $force  Override existing target images
  *
  * @return string|null The path of the resized image or null
  */
 public static function get($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);
         }
     }
     // HOOK: add custom logic
     if (isset($GLOBALS['TL_HOOKS']['getImage']) && is_array($GLOBALS['TL_HOOKS']['getImage'])) {
         foreach ($GLOBALS['TL_HOOKS']['getImage'] as $callback) {
             $return = \System::importStatic($callback[0])->{$callback}[1]($image, $width, $height, $mode, $strCacheName, $objFile, $target);
             if (is_string($return)) {
                 return \System::urlEncode($return);
             }
         }
     }
     // 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);
 }
Beispiel #16
0
 /**
  * Write the central directory and close the file handle
  */
 public function close()
 {
     // Add archive header
     $arrArchive['archive_signature'] = self::CENTRAL_DIR_END;
     $arrArchive['number_of_this_disk'] = "";
     $arrArchive['number_of_disk_with_cd'] = "";
     $arrArchive['total_cd_entries_disk'] = pack('v', $this->intCount);
     $arrArchive['total_cd_entries'] = pack('v', $this->intCount);
     $arrArchive['size_of_cd'] = pack('V', strlen($this->strCentralDir));
     $arrArchive['offset_start_cd'] = pack('V', @ftell($this->resFile));
     $arrArchive['zipfile_comment_length'] = "";
     $arrArchive['zipfile_comment'] = '';
     // Add central directory and archive header (do not change this order)
     @fputs($this->resFile, $this->strCentralDir);
     @fputs($this->resFile, implode('', $arrArchive));
     // Close the file before renaming it
     @fclose($this->resFile);
     // Check if target file exists
     if (!file_exists(TL_ROOT . '/' . $this->strFile)) {
         // Handle open_basedir restrictions
         if (($strFolder = dirname($this->strFile)) == '.') {
             $strFolder = '';
         }
         // Create folder
         if (!is_dir(TL_ROOT . '/' . $strFolder)) {
             new \Folder($strFolder);
         }
     }
     // Rename file
     \Files::getInstance()->rename(self::TEMPORARY_FOLDER . '/' . basename($this->strTemp), $this->strFile);
 }
 protected function makeCacheDirectory()
 {
     \Files::getInstance()->mkdir($this->cacheDirectory);
 }
Beispiel #18
0
 /**
  * Remove a configuration variable
  * 
  * @param string $strKey The full variable name
  */
 public function delete($strKey)
 {
     $this->blnIsModified = true;
     $this->Files = \Files::getInstance();
     // Required in the destructor
     unset($this->arrData[$strKey]);
 }
 /**
  * Import files from selected folder
  *
  * @param string $strPath
  */
 protected function importFromPath($strPath)
 {
     $arrFiles = scan(TL_ROOT . '/' . $strPath);
     if (empty($arrFiles)) {
         \Message::addError($GLOBALS['TL_LANG']['MSC']['noFilesInFolder']);
         \Controller::reload();
     }
     $blnEmpty = true;
     $arrDelete = array();
     $objProducts = \Database::getInstance()->prepare("SELECT * FROM tl_iso_product WHERE pid=0")->execute();
     while ($objProducts->next()) {
         $arrImageNames = array();
         $arrImages = deserialize($objProducts->images);
         if (!is_array($arrImages)) {
             $arrImages = array();
         } else {
             foreach ($arrImages as $row) {
                 if ($row['src']) {
                     $arrImageNames[] = $row['src'];
                 }
             }
         }
         $arrPattern = array();
         $arrPattern[] = $objProducts->alias ? standardize($objProducts->alias) : null;
         $arrPattern[] = $objProducts->sku ? $objProducts->sku : null;
         $arrPattern[] = $objProducts->sku ? standardize($objProducts->sku) : null;
         $arrPattern[] = !empty($arrImageNames) ? implode('|', $arrImageNames) : null;
         // !HOOK: add custom import regex patterns
         if (isset($GLOBALS['ISO_HOOKS']['addAssetImportRegexp']) && is_array($GLOBALS['ISO_HOOKS']['addAssetImportRegexp'])) {
             foreach ($GLOBALS['ISO_HOOKS']['addAssetImportRegexp'] as $callback) {
                 $objCallback = \System::importStatic($callback[0]);
                 $arrPattern = $objCallback->{$callback}[1]($arrPattern, $objProducts);
             }
         }
         $strPattern = '@^(' . implode('|', array_filter($arrPattern)) . ')@i';
         $arrMatches = preg_grep($strPattern, $arrFiles);
         if (!empty($arrMatches)) {
             $arrNewImages = array();
             foreach ($arrMatches as $file) {
                 if (is_dir(TL_ROOT . '/' . $strPath . '/' . $file)) {
                     $arrSubfiles = scan(TL_ROOT . '/' . $strPath . '/' . $file);
                     if (!empty($arrSubfiles)) {
                         foreach ($arrSubfiles as $subfile) {
                             if (is_file($strPath . '/' . $file . '/' . $subfile)) {
                                 $objFile = new \File($strPath . '/' . $file . '/' . $subfile);
                                 if ($objFile->isGdImage) {
                                     $arrNewImages[] = $strPath . '/' . $file . '/' . $subfile;
                                 }
                             }
                         }
                     }
                 } elseif (is_file(TL_ROOT . '/' . $strPath . '/' . $file)) {
                     $objFile = new \File($strPath . '/' . $file);
                     if ($objFile->isGdImage) {
                         $arrNewImages[] = $strPath . '/' . $file;
                     }
                 }
             }
             if (!empty($arrNewImages)) {
                 foreach ($arrNewImages as $strFile) {
                     $pathinfo = pathinfo(TL_ROOT . '/' . $strFile);
                     // Will recursively create the folder
                     $objFolder = new \Folder('isotope/' . strtolower(substr($pathinfo['filename'], 0, 1)));
                     $strCacheName = $pathinfo['filename'] . '-' . substr(md5_file(TL_ROOT . '/' . $strFile), 0, 8) . '.' . $pathinfo['extension'];
                     \Files::getInstance()->copy($strFile, $objFolder->path . '/' . $strCacheName);
                     $arrImages[] = array('src' => $strCacheName);
                     $arrDelete[] = $strFile;
                     \Message::addConfirmation(sprintf($GLOBALS['TL_LANG']['MSC']['assetImportConfirmation'], $pathinfo['filename'] . '.' . $pathinfo['extension'], $objProducts->name));
                     $blnEmpty = false;
                 }
                 \Database::getInstance()->prepare("UPDATE tl_iso_product SET images=? WHERE id=?")->execute(serialize($arrImages), $objProducts->id);
             }
         }
     }
     if (!empty($arrDelete)) {
         $arrDelete = array_unique($arrDelete);
         foreach ($arrDelete as $file) {
             \Files::getInstance()->delete($file);
         }
     }
     if ($blnEmpty) {
         \Message::addInfo($GLOBALS['TL_LANG']['MSC']['assetImportNoFilesFound']);
     }
     \Controller::reload();
 }
Beispiel #20
0
    protected function generateEpub($objSiteExport)
    {
        $toc = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE ncx PUBLIC "-//NISO//DTD ncx 2005-1//EN" "http://www.daisy.org/z3986/2005/ncx-2005-1.dtd">
<ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1">
	<head>
		<meta name="dc:Title" content="' . $objSiteExport->ebookTitle . '"/>
		<meta name="dtb:uid" content="' . $objSiteExport->ebookIdentifier . '"/>
	</head>
	<docTitle>
		<text>' . $objSiteExport->ebookTitle . '</text>
	</docTitle>
	<navMap>
';
        /**
         * create ‘table of contents’
         */
        $lastLevel = -1;
        for ($i = 0; $i < count($this->arrPages); $i++) {
            if ($this->arrPages[$i]['level'] <= $lastLevel) {
                $toc .= str_pad("\t", $this->arrPages[$i]['level'] + 1, "\t") . str_pad('</navPoint>', 11 * ($lastLevel - $this->arrPages[$i]['level'] + 1), '</navPoint>') . "\n";
            }
            $toc .= str_pad("\t", $this->arrPages[$i]['level'] + 1, "\t") . '<navPoint playOrder="' . ($i + 1) . '" id="' . $this->arrPages[$i]['navId'] . '">' . "\n";
            $toc .= str_pad("\t", $this->arrPages[$i]['level'] + 2, "\t") . '<navLabel><text>' . $this->arrPages[$i]['title'] . '</text></navLabel>' . "\n";
            $toc .= str_pad("\t", $this->arrPages[$i]['level'] + 2, "\t") . '<content src="' . $this->arrPages[$i]['filename'] . '"/>' . "\n";
            $lastLevel = $this->arrPages[$i]['level'];
        }
        $toc .= str_pad("\t", $lastLevel + 1, "\t") . str_pad('</navPoint>', 11 * ($lastLevel + 1), '</navPoint>') . "\n";
        $toc .= '	</navMap>
</ncx>';
        /**
         * create ‘content.opf’
         */
        $content = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<package xmlns="http://www.idpf.org/2007/opf" xmlns:dc="http://purl.org/dc/elements/1.1/" unique-identifier="' . $objSiteExport->ebookIdentifier . '" version="2.0">
	<metadata>
		<meta name="generator" content="Contao :: Site Export"/>
		<dc:title>' . $objSiteExport->ebookTitle . '</dc:title>
		<dc:description>' . $objSiteExport->ebookDescription . '</dc:description>
		<dc:creator>' . $objSiteExport->ebookCreator . '</dc:creator>
		<dc:publisher>' . $objSiteExport->ebookPublisher . '</dc:publisher>
		<dc:date>' . $objSiteExport->ebookDate . '</dc:date>
		<dc:language>' . $objSiteExport->ebookLanguage . '</dc:language>
		<dc:identifier id="' . $objSiteExport->ebookIdentifier . '">' . $objSiteExport->ebookIdentifier . '</dc:identifier>
		<dc:subject>' . $objSiteExport->ebookSubject . '</dc:subject>
';
        if ($objSiteExport->ebookCover != '') {
            if (version_compare(VERSION, '3', '>=')) {
                $objEbookCover = \FilesModel::findByPk($objSiteExport->ebookCover);
                $strEbookCover = $objEbookCover->path;
            } else {
                $strEbookCover = $objSiteExport->ebookCover;
            }
            $epubCoverFile = basename($strEbookCover);
            $this->import('Files');
            $this->Files->copy($strEbookCover, $this->strTargetFolder . '/images/' . $epubCoverFile);
            $content .= '		<meta name="cover" content="cover"/>
	</metadata>
	<manifest>
			<item href="images/' . $epubCoverFile . '" id="cover" media-type="image/jpeg"/>';
        } else {
            $epubCoverFile = false;
            $content .= '
	</metadata>
	<manifest>';
        }
        $content .= '
		<item id="ncx" href="toc.ncx" media-type="application/x-dtbncx+xml"/>
';
        foreach ($this->getFiles($this->strTargetFolder . '/images', array('.jpg', '.jpeg')) as $file) {
            $content .= "\t\t" . '<item id="' . str_replace('@', 'at', strstr($file, '.', true)) . '" href="images/' . $file . '" media-type="image/jpeg"/>' . "\n";
        }
        foreach ($this->getFiles($this->strTargetFolder . '/images', array('.png')) as $file) {
            $content .= "\t\t" . '<item id="' . strstr($file, '.', true) . '" href="images/' . $file . '" media-type="image/png"/>' . "\n";
        }
        foreach ($this->getFiles($this->strTargetFolder, array('.css')) as $file) {
            $content .= "\t\t" . '<item id="' . strstr($file, '.', true) . '" href="' . $file . '" media-type="text/css"/>' . "\n";
        }
        $spine = '	<spine toc="ncx">' . "\n";
        if ($objSiteExport->toc != 'none') {
            $content .= "\t\t" . '<item id="id_book_toc" href="toc.xhtml" media-type="application/xhtml+xml"/>' . "\n";
            $spine .= "\t\t" . '<itemref idref="id_book_toc"/>' . "\n";
        }
        for ($i = 0; $i < count($this->arrPages); $i++) {
            $content .= "\t\t" . '<item id="' . $this->arrPages[$i]['navId'] . '" href="' . $this->arrPages[$i]['filename'] . '" media-type="application/xhtml+xml"/>' . "\n";
            $spine .= "\t\t" . '<itemref idref="' . $this->arrPages[$i]['navId'] . '"/>' . "\n";
        }
        $spine .= '	</spine>
';
        $content .= '	</manifest>
' . $spine . '
</package>';
        $arrDataFiles = scandir(TL_ROOT . '/' . $this->strTargetFolder);
        $arrImageFiles = scandir(TL_ROOT . '/' . $this->strTargetFolder . '/images');
        #		$this->import('MyZipWriter');
        $objArchive = new \MyZipWriter($this->strTargetFolder . '/' . $objSiteExport->ebookFilename);
        $objArchive->addStringUncompressed('application/epub+zip', 'mimetype');
        $objArchive->addString('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
		<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
			<rootfiles>
				<rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/>
			</rootfiles>
		</container>', 'META-INF/container.xml');
        $objArchive->addString($toc, 'OEBPS/toc.ncx');
        $objArchive->addString($content, 'OEBPS/content.opf');
        $files = Files::getInstance();
        foreach ($arrDataFiles as $strFile) {
            if (!is_dir(TL_ROOT . '/' . $this->strTargetFolder . '/' . $strFile) && !in_array($strFile, array('.', '..'))) {
                $file = new File($this->strTargetFolder . '/' . $strFile);
                $objArchive->addString($file->getContent(), 'OEBPS/' . $strFile);
                $file->close();
            }
        }
        foreach ($arrImageFiles as $strFile) {
            if (!is_dir(TL_ROOT . '/' . $this->strTargetFolder . '/' . $strFile) && !in_array($strFile, array('.', '..'))) {
                $file = new File($this->strTargetFolder . '/images/' . $strFile);
                $objArchive->addString($file->getContent(), 'OEBPS/images/' . $strFile);
                $file->close();
            }
        }
        $files->rrdir($this->strTargetFolder, true);
        $objArchive->close();
    }
 public function run()
 {
     $arrJobs = array();
     $objTemplate = new \BackendTemplate('be_rename_avatars');
     $objTemplate->isActive = $this->isActive();
     // Confirmation message
     if ($_SESSION['RENAME_AVATARS_CONFIRM'] != '') {
         $objTemplate->message = sprintf('<p class="tl_confirm">%s</p>' . "\n", $_SESSION['RENAME_AVATARS_CONFIRM']);
         $_SESSION['RENAME_AVATARS_CONFIRM'] = '';
     }
     // Add potential error messages
     if (!empty($_SESSION['TL_ERROR']) && is_array($_SESSION['TL_ERROR'])) {
         foreach ($_SESSION['TL_ERROR'] as $message) {
             $objTemplate->message .= sprintf('<p class="tl_error">%s</p>' . "\n", $message);
         }
         $_SESSION['TL_ERROR'] = array();
     }
     // Run the jobs
     if (\Input::post('FORM_SUBMIT') == 'tl_rename_avatars') {
         /**
          * @var \Files $files
          */
         $files = \Files::getInstance();
         /**
          * @var string $uploadDir
          */
         $uploadDir = \FilesModel::findByPk($GLOBALS['TL_CONFIG']['avatar_dir']);
         if ($uploadDir) {
             $uploadDir = $uploadDir->path;
         } else {
             $_SESSION['TL_ERROR'][] = 'Upload dir is invalid!';
             $this->reload();
         }
         /**
          * @var \MemberModel $member
          */
         $member = \MemberModel::findBy(array('avatar!=?'), '');
         $count = 0;
         while ($member->next()) {
             $avatarRecord = \FilesModel::findByUuid($member->avatar);
             if ($avatarRecord) {
                 $avatar = $avatarRecord->path;
             } else {
                 $_SESSION['TL_ERROR'][] = sprintf('Avatar for user ID %d is invalid', $member->id);
                 continue;
             }
             $pathinfo = pathinfo($avatar);
             $newName = standardize(\String::parseSimpleTokens($GLOBALS['TL_CONFIG']['avatar_name'], $member->row()));
             if ($pathinfo['filename'] != $newName) {
                 $newPath = $uploadDir . '/' . $newName . '.' . $pathinfo['extension'];
                 $n = 1;
                 while (file_exists(TL_ROOT . '/' . $newPath)) {
                     $newPath = $uploadDir . '/' . $newName . '__' . $n++ . '.' . $pathinfo['extension'];
                 }
                 $files->rename($avatar, $newPath);
                 $avatarRecord->path = $newPath;
                 $avatarRecord->name = $newName;
                 $avatarRecord->save();
                 $count++;
             }
         }
         $_SESSION['RENAME_AVATARS_CONFIRM'] = sprintf($GLOBALS['TL_LANG']['tl_maintenance']['avatarsRenamed'], $count);
         $this->reload();
     }
     $objTemplate->action = ampersand(\Environment::get('request'));
     $objTemplate->headline = $GLOBALS['TL_LANG']['tl_maintenance']['renameAvatars'];
     $objTemplate->submit = specialchars($GLOBALS['TL_LANG']['tl_maintenance']['doRenameAvatars']);
     $objTemplate->help = $GLOBALS['TL_LANG']['tl_maintenance']['renameAvatarsHelp'];
     return $objTemplate->parse();
 }
Beispiel #22
0
 /**
  * Validate input and set value
  */
 public function validate()
 {
     $this->varValue = $this->getPost($this->strName);
     if (!is_array($this->varValue)) {
         $this->varValue = array();
     }
     // Fetch fallback language record
     $arrFallback = $this->getFallbackData();
     if (is_array($arrFallback)) {
         foreach ($arrFallback as $k => $arrImage) {
             if ($arrImage['translate'] == 'all') {
                 unset($arrFallback[$k]);
             }
         }
     }
     // Check that image is not assigned in fallback language
     foreach ($this->varValue as $k => $v) {
         if (is_array($arrFallback) && in_array($v, $arrFallback)) {
             $this->addError($GLOBALS['TL_LANG']['ERR']['imageInFallback']);
         } elseif ($arrFallback !== false) {
             $this->varValue[$k]['translate'] = 'all';
         }
     }
     // Move all temporary files
     foreach ($this->varValue as $k => $v) {
         if (stripos($v['src'], $this->strTempFolder) !== false) {
             $strFile = $this->getFilePath(basename($v['src']));
             \Haste\Haste::mkdirr(dirname($strFile));
             if (\Files::getInstance()->rename($v['src'], $strFile)) {
                 $this->varValue[$k]['src'] = basename($strFile);
             } else {
                 unset($this->varValue[$k]);
             }
         }
     }
     // Check if there are values
     if ($this->mandatory) {
         foreach ($this->varValue as $file) {
             if (is_file(TL_ROOT . '/' . $this->getFilePath($file['src']))) {
                 return;
             }
         }
         if (!is_array($arrFallback) || empty($arrFallback)) {
             $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['mandatory'], $this->strLabel));
         }
     }
     if (empty($this->varValue)) {
         $this->varValue = null;
     }
 }
 /** @noinspection PhpHierarchyChecksInspection
  * {@inheritdoc}
  */
 public function get($image, $width, $height, $mode, $strCacheName, \File $objFile, $strTarget, $objImage)
 {
     if (!$width && !$height) {
         return false;
     }
     $strCacheName = $this->process($image, $strCacheName, $objFile, $objImage);
     // Set the file permissions when the Safe Mode Hack is used
     if ($this->blnSmhEnabled) {
         \Files::getInstance()->chmod($strCacheName, 0644);
     }
     if ($strTarget) {
         \Files::getInstance()->copy($strCacheName, $strTarget);
         return $strTarget;
     }
     // Return the path to new image
     return $strCacheName;
 }
Beispiel #24
0
 /**
  * Convert an existing image to the greyscale version
  *
  * @param string $data The image path or an UUID including url params for with/height/mode
  * @return string image path
  */
 public static function convert($data)
 {
     $params = array('width' => 0, 'height' => 0, 'mode' => '');
     if (strpos($data, '?') !== false) {
         // parse additonal tags
         $data = parse_url($data);
         $params = array();
         parse_str($data['query'], $params);
         if (!isset($params['width'])) {
             $params['width'] = false;
         }
         if (!isset($params['height'])) {
             $params['height'] = false;
         }
         if (!isset($params['mode'])) {
             $params['mode'] = '';
         }
         $objFile = self::checkFile($data['path']);
     } else {
         $objFile = self::checkFile($data);
     }
     /**
      * Check if file size is not greater then the contao max gd editing size #1
      */
     if ($objFile->width > $GLOBALS['TL_CONFIG']['gdMaxImgWidth'] || $objFile->height > $GLOBALS['TL_CONFIG']['gdMaxImgHeight']) {
         \System::log('Image "' . $objFile->path . '" could not be converted to greyscale cause its size is to large for the gd editing', __METHOD__, TL_ERROR);
         return null;
     }
     /**
      * Resize the image with the default contao image function
      */
     $image = \Image::get($objFile->path, $params['width'], $params['height'], $params['mode']);
     if (is_null($image)) {
         return null;
     }
     /**
      * Create cache name
      */
     $strCacheKey = substr(md5('-w' . $params['width'] . '-h' . $params['height'] . '-' . $image . '-' . $params['mode'] . '-' . $objFile->mtime), 0, 8);
     $strCacheName = 'assets/images/' . substr($strCacheKey, -1) . '/' . $objFile->filename . '-grey' . '-' . $strCacheKey . '.' . $objFile->extension;
     /**
      * Check if file already exists and if it was modified
      */
     if (!file_exists(TL_ROOT . '/' . $strCacheName) || $objFile->mtime >= filemtime(TL_ROOT . '/' . $strCacheName)) {
         /**
          * Copy original file to always display anything
          */
         \Files::getInstance()->copy($image, $strCacheName);
         /**
          * Read image from file
          */
         switch ($objFile->extension) {
             case 'png':
                 $strSourceImage = imagecreatefrompng($image);
                 $strImage = imagecreatetruecolor(imagesx($strSourceImage), imagesy($strSourceImage));
                 imagealphablending($strImage, false);
                 $intTranspIndex = imagecolorallocatealpha($strImage, 0, 0, 0, 127);
                 imagefill($strImage, 0, 0, $intTranspIndex);
                 imagesavealpha($strImage, true);
                 imagecopy($strImage, $strSourceImage, 0, 0, 0, 0, imagesx($strSourceImage), imagesx($strSourceImage));
                 break;
             case 'jpg':
             case 'jpeg':
                 $strImage = imagecreatefromjpeg($image);
                 break;
             case 'gif':
                 $strSourceImage = imagecreatefromgif($image);
                 $strImage = imagecreatetruecolor(imagesx($strSourceImage), imagesy($strSourceImage));
                 $transparent = imagecolorallocate($strImage, 0, 0, 0);
                 imagecolortransparent($strImage, $transparent);
                 imagecopy($strImage, $strSourceImage, 0, 0, 0, 0, imagesx($strSourceImage), imagesx($strSourceImage));
                 break;
         }
         /**
          * Convert colors
          */
         if (imagefilter($strImage, IMG_FILTER_GRAYSCALE)) {
             switch ($objFile->extension) {
                 case 'png':
                     imagepng($strImage, $strCacheName);
                     break;
                 case 'jpg':
                 case 'jpeg':
                     imagejpeg($strImage, $strCacheName, !$GLOBALS['TL_CONFIG']['jpgQuality'] ? 80 : $GLOBALS['TL_CONFIG']['jpgQuality']);
                     break;
                 case 'gif':
                     imagegif($strImage, $strCacheName);
                     break;
             }
         } else {
             \System::log('Image "' . $image . '" could not be converted to greyscale', __METHOD__, TL_ERROR);
         }
     }
     return $strCacheName;
 }
 /**
  * Move a file from a to b
  * 
  * @param array $arrMoveList
  * @throws Exception 
  */
 protected function moveFiles($arrMoveList)
 {
     $objFiles = Files::getInstance();
     foreach ($arrMoveList as $key => $value) {
         $strFolderPath = dirname($value);
         if ($strFolderPath != ".") {
             $objFolder = new Folder($strFolderPath);
             unset($objFolder);
         }
         if ($objFiles->copy($key, $value) == false) {
             throw new Exception("Could not move tmp file to destination. {$key} TO {$value}");
         }
     }
 }
    /**
     * Remove all files installed with ER2 client
     */
    protected function removeER2Files()
    {
        $files = \Files::getInstance();
        $file = \Database::getInstance()->query('SELECT f.*
				 FROM tl_repository_instfiles f
				 INNER JOIN tl_repository_installs i
				 ON i.id=f.pid
				 WHERE i.extension!="composer"
				 ORDER BY filetype="D", filetype="F", filename DESC');
        $fileIds = array();
        $installIds = array();
        while ($file->next()) {
            $path = TL_ROOT . '/' . $file->filename;
            switch ($file->filetype) {
                case 'F':
                    if (file_exists($path)) {
                        $fileIds[] = $file->id;
                        $installIds[] = $file->pid;
                        $files->delete($file->filename);
                    }
                    break;
                case 'D':
                    if (is_dir($path) && !count(scan($path))) {
                        $installIds[] = $file->pid;
                        $files->rmdir($file->filename);
                    }
                    break;
            }
        }
        if (count($installIds)) {
            \Database::getInstance()->query('UPDATE tl_repository_installs SET error=1 WHERE id IN (' . implode(',', array_unique($installIds)) . ')');
        }
        if (count($fileIds)) {
            \Database::getInstance()->query('UPDATE tl_repository_instfiles SET flag="D" WHERE id IN (' . implode(',', $fileIds) . ')');
        }
    }
Beispiel #27
0
 /**
  * Resize the image
  *
  * @return $this The image object
  */
 public function executeResize()
 {
     // HOOK: add custom logic
     if (isset($GLOBALS['TL_HOOKS']['executeResize']) && is_array($GLOBALS['TL_HOOKS']['executeResize'])) {
         foreach ($GLOBALS['TL_HOOKS']['executeResize'] as $callback) {
             $return = \System::importStatic($callback[0])->{$callback}[1]($this);
             if (is_string($return)) {
                 $this->resizedPath = \System::urlEncode($return);
                 return $this;
             }
         }
     }
     $importantPart = $this->getImportantPart();
     $widthMatches = $this->fileObj->width == $this->getTargetWidth() || !$this->getTargetWidth();
     $heightMatches = $this->fileObj->height == $this->getTargetHeight() || !$this->getTargetHeight();
     $zoomMatches = $importantPart['x'] === 0 && $importantPart['y'] === 0 && $importantPart['width'] === $this->fileObj->width && $importantPart['height'] === $this->fileObj->height || !$this->getZoomLevel();
     // No resizing required
     if ($widthMatches && $heightMatches && $zoomMatches) {
         // Return the target image (thanks to Tristan Lins) (see #4166)
         if ($this->getTargetPath()) {
             // Copy the source image if the target image does not exist or is older than the source image
             if (!file_exists(TL_ROOT . '/' . $this->getTargetPath()) || $this->fileObj->mtime > filemtime(TL_ROOT . '/' . $this->getTargetPath())) {
                 \Files::getInstance()->copy($this->getOriginalPath(), $this->getTargetPath());
             }
             $this->resizedPath = \System::urlEncode($this->getTargetPath());
             return $this;
         }
         $this->resizedPath = \System::urlEncode($this->getOriginalPath());
         return $this;
     }
     // Check whether the image exists already
     if (!\Config::get('debugMode')) {
         // Custom target (thanks to Tristan Lins) (see #4166)
         if ($this->getTargetPath() && !$this->getForceOverride()) {
             if (file_exists(TL_ROOT . '/' . $this->getTargetPath()) && $this->fileObj->mtime <= filemtime(TL_ROOT . '/' . $this->getTargetPath())) {
                 $this->resizedPath = \System::urlEncode($this->getOriginalPath());
                 return $this;
             }
         }
         // Regular cache file
         if (file_exists(TL_ROOT . '/' . $this->getCacheName())) {
             // Copy the cached file if it exists
             if ($this->getTargetPath()) {
                 \Files::getInstance()->copy($this->getCacheName(), $this->getTargetPath());
                 $this->resizedPath = \System::urlEncode($this->getTargetPath());
                 return $this;
             }
             $this->resizedPath = \System::urlEncode($this->getCacheName());
             return $this;
         }
     }
     // HOOK: add custom logic
     if (isset($GLOBALS['TL_HOOKS']['getImage']) && is_array($GLOBALS['TL_HOOKS']['getImage'])) {
         foreach ($GLOBALS['TL_HOOKS']['getImage'] as $callback) {
             $return = \System::importStatic($callback[0])->{$callback}[1]($this->getOriginalPath(), $this->getTargetWidth(), $this->getTargetHeight(), $this->getResizeMode(), $this->getCacheName(), $this->fileObj, $this->getTargetPath(), $this);
             if (is_string($return)) {
                 $this->resizedPath = \System::urlEncode($return);
                 return $this;
             }
         }
     }
     $svgNotPossible = $this->fileObj->isSvgImage && !extension_loaded('dom');
     $gdNotPossible = $this->fileObj->isGdImage && (!extension_loaded('gd') || $this->fileObj->width > \Config::get('gdMaxImgWidth') || $this->fileObj->height > \Config::get('gdMaxImgHeight') || $this->getTargetWidth() > \Config::get('gdMaxImgWidth') || $this->getTargetHeight() > \Config::get('gdMaxImgHeight'));
     // Return the path to the original image if it cannot be handled
     if (!$this->fileObj->isImage || $svgNotPossible || $gdNotPossible) {
         $this->resizedPath = \System::urlEncode($this->getOriginalPath());
         return $this;
     }
     // Create the resized image
     if ($this->fileObj->isSvgImage) {
         $this->executeResizeSvg();
     } else {
         $this->executeResizeGd();
     }
     // Resize the original image
     if ($this->getTargetPath()) {
         \Files::getInstance()->copy($this->getCacheName(), $this->getTargetPath());
         $this->resizedPath = \System::urlEncode($this->getTargetPath());
         return $this;
     }
     $this->resizedPath = \System::urlEncode($this->getCacheName());
     return $this;
 }
Beispiel #28
0
 /**
  * Apply a watermark to an image
  * @param string
  * @param string
  * @param string
  * @param string
  */
 public static function addWatermark($image, $watermark, $position = 'br', $target = null)
 {
     $image = urldecode($image);
     if (!is_file(TL_ROOT . '/' . $image) || !is_file(TL_ROOT . '/' . $watermark)) {
         return $image;
     }
     $objFile = new \File($image);
     $strCacheName = 'assets/images/' . substr($objFile->filename, -1) . '/' . $objFile->filename . '-' . substr(md5($watermark . '-' . $position . '-' . $objFile->mtime), 0, 8) . '.' . $objFile->extension;
     // Return the path of the new image if it exists already
     if (is_file(TL_ROOT . '/' . $strCacheName)) {
         return $strCacheName;
     }
     // !HOOK: override image watermark routine
     if (isset($GLOBALS['TL_HOOKS']['watermarkImage']) && is_array($GLOBALS['TL_HOOKS']['watermarkImage'])) {
         foreach ($GLOBALS['TL_HOOKS']['watermarkImage'] as $callback) {
             $objCallback = \System::importStatic($callback[0]);
             $return = $objCallback->{$callback[1]}($image, $watermark, $position, $target);
             if (is_string($return)) {
                 return $return;
             }
         }
     }
     $arrGdinfo = gd_info();
     $strImage = null;
     // Load image
     switch ($objFile->extension) {
         case 'gif':
             if ($arrGdinfo['GIF Read Support']) {
                 $strImage = imagecreatefromgif(TL_ROOT . '/' . $image);
             }
             break;
         case 'jpg':
         case 'jpeg':
             if ($arrGdinfo['JPG Support'] || $arrGdinfo['JPEG Support']) {
                 $strImage = imagecreatefromjpeg(TL_ROOT . '/' . $image);
             }
             break;
         case 'png':
             if ($arrGdinfo['PNG Support']) {
                 $strImage = imagecreatefrompng(TL_ROOT . '/' . $image);
             }
             break;
     }
     // Image could not be read
     if (!$strImage) {
         return $image;
     }
     $objWatermark = new \File($watermark);
     $resWatermark = null;
     // Load watermark
     switch ($objWatermark->extension) {
         case 'gif':
             if ($arrGdinfo['GIF Read Support']) {
                 $resWatermark = imagecreatefromgif(TL_ROOT . '/' . $watermark);
             }
             break;
         case 'jpg':
         case 'jpeg':
             if ($arrGdinfo['JPG Support'] || $arrGdinfo['JPEG Support']) {
                 $resWatermark = imagecreatefromjpeg(TL_ROOT . '/' . $watermark);
             }
             break;
         case 'png':
             if ($arrGdinfo['PNG Support']) {
                 $resWatermark = imagecreatefrompng(TL_ROOT . '/' . $watermark);
             }
             break;
     }
     // Image could not be read
     if (!is_resource($resWatermark)) {
         return $image;
     }
     switch ($position) {
         case 'left_top':
             $x = 0;
             $y = 0;
             break;
         case 'center_top':
             $x = $objFile->width / 2 - $objWatermark->width / 2;
             $y = 0;
             break;
         case 'right_top':
             $x = $objFile->width - $objWatermark->width;
             $y = 0;
             break;
         case 'left_center':
             $x = 0;
             $y = $objFile->height / 2 - $objWatermark->height / 2;
             break;
         case 'center_center':
             $x = $objFile->width / 2 - $objWatermark->width / 2;
             $y = $objFile->height / 2 - $objWatermark->height / 2;
             break;
         case 'right_center':
             $x = $objFile->width - $objWatermark->width;
             $y = $objFile->height / 2 - $objWatermark->height / 2;
             break;
         case 'left_bottom':
             $x = 0;
             $y = $objFile->height - $objWatermark->height;
             break;
         case 'center_bottom':
             $x = $objFile->width / 2 - $objWatermark->width / 2;
             $y = $objFile->height - $objWatermark->height;
             break;
         case 'right_bottom':
         default:
             $x = $objFile->width - $objWatermark->width;
             $y = $objFile->height - $objWatermark->height;
             break;
     }
     imagecopy($strImage, $resWatermark, $x, $y, 0, 0, $objWatermark->width, $objWatermark->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($strImage, TL_ROOT . '/' . $strCacheName);
             break;
         case 'jpg':
         case 'jpeg':
             imagejpeg($strImage, TL_ROOT . '/' . $strCacheName, !$GLOBALS['TL_CONFIG']['jpgQuality'] ? 80 : $GLOBALS['TL_CONFIG']['jpgQuality']);
             break;
         case 'png':
             imagepng($strImage, TL_ROOT . '/' . $strCacheName);
             break;
     }
     // Destroy the temporary images
     imagedestroy($strImage);
     imagedestroy($resWatermark);
     // Resize the original image
     if ($target) {
         $objFiles = \Files::getInstance();
         $objFiles->copy($strCacheName, $target);
         return $target;
     }
     // Set the file permissions when the Safe Mode Hack is used
     if ($GLOBALS['TL_CONFIG']['useFTP']) {
         $objFiles = \Files::getInstance();
         $objFiles->chmod($strCacheName, 0644);
     }
     // Return the path to new image
     return $strCacheName;
 }
Beispiel #29
0
 /**
  * Mark the object as modified
  */
 protected function markModified()
 {
     // Return if marked as modified already
     if ($this->blnIsModified === true) {
         return;
     }
     $this->blnIsModified = true;
     // Import the Files object (required in the destructor)
     $this->Files = \Files::getInstance();
     // Parse the local configuration file
     if (static::$blnHasLcf) {
         $strMode = 'top';
         $resFile = fopen(TL_ROOT . '/system/config/localconfig.php', 'rb');
         while (!feof($resFile)) {
             $strLine = fgets($resFile);
             $strTrim = trim($strLine);
             if ($strTrim == '?>') {
                 continue;
             }
             if ($strTrim == '### INSTALL SCRIPT START ###') {
                 $strMode = 'data';
                 continue;
             }
             if ($strTrim == '### INSTALL SCRIPT STOP ###') {
                 $strMode = 'bottom';
                 continue;
             }
             if ($strMode == 'top') {
                 $this->strTop .= $strLine;
             } elseif ($strMode == 'bottom') {
                 $this->strBottom .= $strLine;
             } elseif ($strTrim != '') {
                 $arrChunks = array_map('trim', explode('=', $strLine, 2));
                 $this->arrData[$arrChunks[0]] = $arrChunks[1];
             }
         }
         fclose($resFile);
     }
 }
Beispiel #30
0
 /**
  * Apply a watermark to an image
  * @param string
  * @param string
  * @param string
  */
 public static function watermarkImage($image, $watermark, $position = 'br')
 {
     $image = urldecode($image);
     if (!is_file(TL_ROOT . '/' . $image) || !is_file(TL_ROOT . '/' . $watermark)) {
         return $image;
     }
     $objFile = new File($image);
     $strCacheName = 'system/html/' . $objFile->filename . '-' . substr(md5($watermark . '-' . $position . '-' . $objFile->mtime), 0, 8) . '.' . $objFile->extension;
     // Return the path of the new image if it exists already
     if (file_exists(TL_ROOT . '/' . $strCacheName)) {
         return $strCacheName;
     }
     // HOOK: add custom logic
     if (isset($GLOBALS['ISO_HOOKS']['watermarkImage']) && is_array($GLOBALS['ISO_HOOKS']['watermarkImage'])) {
         foreach ($GLOBALS['ISO_HOOKS']['watermarkImage'] as $callback) {
             $objCallback = in_array('getInstance', get_class_methods($callback[0])) ? call_user_func(array($callback[0], 'getInstance')) : new $callback[0]();
             $return = $objCallback->{$callback}[1]($image, $watermark);
             if (is_string($return)) {
                 return $return;
             }
         }
     }
     $arrGdinfo = gd_info();
     $strGdVersion = preg_replace('/[^0-9\\.]+/', '', $arrGdinfo['GD Version']);
     // Load image
     switch ($objFile->extension) {
         case 'gif':
             if ($arrGdinfo['GIF Read Support']) {
                 $strImage = imagecreatefromgif(TL_ROOT . '/' . $image);
             }
             break;
         case 'jpg':
         case 'jpeg':
             if ($arrGdinfo['JPG Support'] || $arrGdinfo['JPEG Support']) {
                 $strImage = imagecreatefromjpeg(TL_ROOT . '/' . $image);
             }
             break;
         case 'png':
             if ($arrGdinfo['PNG Support']) {
                 $strImage = imagecreatefrompng(TL_ROOT . '/' . $image);
             }
             break;
     }
     // Image could not be read
     if (!$strImage) {
         return $image;
     }
     $objWatermark = new File($watermark);
     // Load watermark
     switch ($objWatermark->extension) {
         case 'gif':
             if ($arrGdinfo['GIF Read Support']) {
                 $strWatermark = imagecreatefromgif(TL_ROOT . '/' . $watermark);
             }
             break;
         case 'jpg':
         case 'jpeg':
             if ($arrGdinfo['JPG Support'] || $arrGdinfo['JPEG Support']) {
                 $strWatermark = imagecreatefromjpeg(TL_ROOT . '/' . $watermark);
             }
             break;
         case 'png':
             if ($arrGdinfo['PNG Support']) {
                 $strWatermark = imagecreatefrompng(TL_ROOT . '/' . $watermark);
             }
             break;
     }
     // Image could not be read
     if (!$strWatermark) {
         return $image;
     }
     switch ($position) {
         case 'tl':
             $x = 0;
             $y = 0;
             break;
         case 'tc':
             $x = $objFile->width / 2 - $objWatermark->width / 2;
             $y = 0;
             break;
         case 'tr':
             $x = $objFile->width - $objWatermark->width;
             $y = 0;
             break;
         case 'cc':
             $x = $objFile->width / 2 - $objWatermark->width / 2;
             $y = $objFile->height / 2 - $objWatermark->height / 2;
             break;
         case 'bl':
             $x = 0;
             $y = $objFile->height - $objWatermark->height;
             break;
         case 'bc':
             $x = $objFile->width / 2 - $objWatermark->width / 2;
             $y = $objFile->height - $objWatermark->height;
             break;
         case 'br':
         default:
             $x = $objFile->width - $objWatermark->width;
             $y = $objFile->height - $objWatermark->height;
             break;
     }
     imagecopy($strImage, $strWatermark, $x, $y, 0, 0, $objWatermark->width, $objWatermark->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($strImage, TL_ROOT . '/' . $strCacheName);
             break;
         case 'jpg':
         case 'jpeg':
             imagejpeg($strImage, TL_ROOT . '/' . $strCacheName, !$GLOBALS['TL_CONFIG']['jpgQuality'] ? 80 : $GLOBALS['TL_CONFIG']['jpgQuality']);
             break;
         case 'png':
             imagepng($strImage, TL_ROOT . '/' . $strCacheName);
             break;
     }
     // Destroy the temporary images
     imagedestroy($strImage);
     imagedestroy($strWatermark);
     // Resize the original image
     if ($target) {
         $objFiles = Files::getInstance();
         $objFiles->rename($strCacheName, $target);
         return $target;
     }
     // Set the file permissions when the Safe Mode Hack is used
     if ($GLOBALS['TL_CONFIG']['useFTP']) {
         $objFiles = Files::getInstance();
         $objFiles->chmod($strCacheName, 0644);
     }
     // Return the path to new image
     return $strCacheName;
 }