/**
  * Create all the thumbnails for a picture.
  *
  * @param string        $path Path to the file. This can be a virtual path or a absolute path.
  * @param string        $fileNamePlain Plain file name without extension
  * @param string        $fileExtension Extension of the file
  * @param \ImageManager $imageManager
  *
  * <code>
  * <?php
  * \Cx\Core_Modules\MediaBrowser\Model\FileSystem::createThumbnail(
  *      'files/',
  *      'Django,
  *      'jpg',
  *      new ImageManager() // Please recycle the instance and don't create a new anonymous instance for each call.
  *                         // This is just a simple example.
  * );
  * ?>
  * </code>
  *
  * @return array With all thumbnail types and if they were generated successfully.
  */
 public static function createThumbnail($path, $fileNamePlain, $fileExtension, \ImageManager $imageManager, $generateThumbnailByRatio = false)
 {
     $success = array();
     foreach (UploaderConfiguration::getInstance()->getThumbnails() as $thumbnail) {
         if (\Cx\Lib\FileSystem\FileSystem::exists(MediaSourceManager::getAbsolutePath($path) . $fileNamePlain . $thumbnail['value'] . '.' . $fileExtension)) {
             $success[$thumbnail['value']] = self::THUMBNAIL_GENERATOR_NEUTRAL;
             continue;
         }
         if ($imageManager->_createThumb(MediaSourceManager::getAbsolutePath($path) . '/', '', $fileNamePlain . '.' . $fileExtension, $thumbnail['size'], $thumbnail['quality'], $fileNamePlain . $thumbnail['value'] . '.' . $fileExtension, $generateThumbnailByRatio)) {
             $success[$thumbnail['value']] = self::THUMBNAIL_GENERATOR_SUCCESS;
             continue;
         }
         $success[$thumbnail['value']] = self::THUMBNAIL_GENERATOR_FAIL;
     }
     return $success;
 }
Exemplo n.º 2
0
 public function getFileList($directory, $recursive = false)
 {
     $recursiveIteratorIterator = new \RegexIterator(new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator(rtrim($this->rootPath . '/' . $directory, '/')), \RecursiveIteratorIterator::SELF_FIRST), '/^((?!thumb(_[a-z]+)?).)*$/');
     $jsonFileArray = array();
     $thumbnailList = UploaderConfiguration::getInstance()->getThumbnails();
     foreach ($recursiveIteratorIterator as $file) {
         /**
          * @var $file \SplFileInfo
          */
         $extension = 'Dir';
         if (!$file->isDir()) {
             $extension = ucfirst(pathinfo($file->getFilename(), PATHINFO_EXTENSION));
         }
         // filters
         if ($file->getFilename() == '.' || $file->getFilename() == 'index.php' || 0 === strpos($file->getFilename(), '.')) {
             continue;
         }
         // set preview if image
         $preview = 'none';
         $thumbnails = array();
         if ($this->isImage($extension)) {
             $thumbnails = $this->getThumbnails($thumbnailList, $extension, $file, $thumbnails);
             $preview = current($thumbnails);
             if (!file_exists($this->cx->getWebsitePath() . $preview)) {
                 $preview = '';
             }
         }
         $fileInfos = array('filepath' => mb_strcut($file->getPath() . '/' . $file->getFilename(), mb_strlen($this->cx->getWebsitePath())), 'name' => $file->getFilename(), 'size' => $this->formatBytes($file->getSize()), 'cleansize' => $file->getSize(), 'extension' => ucfirst(mb_strtolower($extension)), 'preview' => $preview, 'active' => false, 'type' => $file->getType(), 'thumbnail' => $thumbnails);
         // filters
         if ($fileInfos['name'] == '.' || preg_match('/\\.thumb/', $fileInfos['name']) || $fileInfos['name'] == 'index.php' || 0 === strpos($fileInfos['name'], '.')) {
             continue;
         }
         $path = array($file->getFilename() => array('datainfo' => $fileInfos));
         for ($depth = $recursiveIteratorIterator->getDepth() - 1; $depth >= 0; $depth--) {
             $path = array($recursiveIteratorIterator->getSubIterator($depth)->current()->getFilename() => $path);
         }
         $jsonFileArray = array_merge_recursive($jsonFileArray, $path);
     }
     return $jsonFileArray;
 }
 /**
  * Handles the upload request.
  *
  * @param array $conf
  *
  * @return array|bool
  */
 static function handleRequest($conf = array())
 {
     $cx = Cx::instanciate();
     // 5 minutes execution time
     @set_time_limit(5 * 60);
     self::$_error = null;
     // start fresh
     $conf = self::$conf = array_merge(array('file_data_name' => 'file', 'tmp_dir' => $_SESSION->getTempPath(), 'target_dir' => 'images/content/', 'cleanup' => true, 'max_file_age' => 5 * 3600, 'chunk' => isset($_REQUEST['chunk']) ? intval($_REQUEST['chunk']) : 0, 'chunks' => isset($_REQUEST['chunks']) ? intval($_REQUEST['chunks']) : 0, 'fileName' => isset($_REQUEST['name']) ? $_REQUEST['name'] : false, 'allow_extensions' => false, 'delay' => 0, 'cb_sanitizeFileName' => array(__CLASS__, 'sanitizeFileName'), 'cb_check_file' => false), $conf);
     try {
         if (!$conf['fileName']) {
             if (!empty($_FILES)) {
                 $conf['fileName'] = $_FILES[$conf['file_data_name']]['name'];
             } else {
                 throw new UploaderException('', PLUPLOAD_INPUT_ERR);
             }
         }
         // Cleanup outdated temp files and folders
         if ($conf['cleanup']) {
             self::cleanup();
         }
         // Fake network congestion
         if ($conf['delay']) {
             usleep($conf['delay']);
         }
         // callback function for sanitizie filename
         if (is_callable($conf['cb_sanitizeFileName'])) {
             $fileName = call_user_func($conf['cb_sanitizeFileName'], $conf['fileName']);
         } else {
             $fileName = $conf['fileName'];
         }
         // Check if file type is allowed
         if ($conf['allow_extensions']) {
             if (is_string($conf['allow_extensions'])) {
                 $conf['allow_extensions'] = preg_split('{\\s*,\\s*}', $conf['allow_extensions']);
             }
             if (!in_array(strtolower(pathinfo($fileName, PATHINFO_EXTENSION)), $conf['allow_extensions'])) {
                 throw new UploaderException('', PLUPLOAD_TYPE_ERR);
             }
         }
         $file_path = rtrim($conf['tmp_dir'], DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $fileName;
         $tmp_path = $file_path . ".part";
         // Write file or chunk to appropriate temp location
         if ($conf['chunks']) {
             self::writeFileTo("{$file_path}.dir.part" . DIRECTORY_SEPARATOR . $conf['chunk']);
             // Check if all chunks already uploaded
             if ($conf['chunk'] == $conf['chunks'] - 1) {
                 self::writeChunksToFile("{$file_path}.dir.part", $tmp_path);
             }
         } else {
             self::writeFileTo($tmp_path);
         }
         // Upload complete write a temp file to the final destination
         if (!$conf['chunks'] || $conf['chunk'] == $conf['chunks'] - 1) {
             if (is_callable($conf['cb_check_file']) && !call_user_func($conf['cb_check_file'], $tmp_path)) {
                 @unlink($tmp_path);
                 throw new UploaderException('', PLUPLOAD_SECURITY_ERR);
             }
             $new_path = $conf['target_dir'] . $fileName;
             \Cx\Lib\FileSystem\FileSystem::move($tmp_path, $new_path, true);
             $rootPath = $cx->getWebsitePath() . $conf['target_dir'];
             $rootPathFull = $cx->getWebsitePath() . $new_path;
             $filePathinfo = pathinfo($rootPathFull);
             $fileExtension = $filePathinfo['extension'];
             $fileNamePlain = $filePathinfo['filename'];
             $im = new \ImageManager();
             if ($im->_isImage($rootPathFull)) {
                 foreach (UploaderConfiguration::getInstance()->getThumbnails() as $thumbnail) {
                     $im->_createThumb($rootPath, $conf['target_dir'], $fileName, $thumbnail['size'], $thumbnail['quality'], $fileNamePlain . $thumbnail['value'] . '.' . $fileExtension);
                 }
             }
             return array('name' => $fileName, 'path' => $file_path, 'size' => filesize($file_path));
         }
         // ok so far
         return true;
     } catch (UploaderException $ex) {
         self::$_error = $ex->getCode();
         return array('error' => $ex->getCode());
     }
 }
Exemplo n.º 4
0
 /**
  * Regenerate the thumbnails
  * 
  * @param array $post $_POST values
  */
 protected function generateThumbnail($post)
 {
     // release the locks, session not needed
     $session = \cmsSession::getInstance();
     $session->releaseLocks();
     session_write_close();
     $cx = Cx::instanciate();
     $key = $_GET['key'];
     if (!preg_match("/[A-Z0-9]{5}/i", $key)) {
         die;
     }
     $processFile = $session->getTempPath() . '/progress' . $key . '.txt';
     if (\Cx\Lib\FileSystem\FileSystem::exists($processFile)) {
         die;
     }
     try {
         $objProcessFile = new \Cx\Lib\FileSystem\File($processFile);
         $objProcessFile->touch();
     } catch (\Cx\Lib\FileSystem\FileSystemException $ex) {
         die;
     }
     $recursiveIteratorIterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($cx->getWebsiteImagesPath() . '/'), \RecursiveIteratorIterator::SELF_FIRST);
     $jsonFileArray = array();
     $thumbnailList = UploaderConfiguration::getInstance()->getThumbnails();
     $imageManager = new \ImageManager();
     $fileCounter = 0;
     $generalSuccess = true;
     $imageFiles = array();
     foreach ($recursiveIteratorIterator as $file) {
         /**
          * @var $file \SplFileInfo
          */
         $extension = 'Dir';
         if (!$file->isDir()) {
             $extension = ucfirst(pathinfo($file->getFilename(), PATHINFO_EXTENSION));
         }
         $filePathinfo = pathinfo($file->getRealPath());
         $fileNamePlain = $filePathinfo['filename'];
         // set preview if image
         $preview = 'none';
         $fileInfos = array('filepath' => mb_strcut($file->getPath() . '/' . $file->getFilename(), mb_strlen($cx->getCodeBasePath())), 'name' => $file->getFilename(), 'cleansize' => $file->getSize(), 'extension' => ucfirst(mb_strtolower($extension)), 'type' => $file->getType());
         // filters
         if ($fileInfos['name'] == '.' || preg_match('/\\.thumb/', $fileInfos['name']) || $fileInfos['name'] == 'index.php' || 0 === strpos($fileInfos['name'], '.')) {
             continue;
         }
         if (!preg_match("/(jpg|jpeg|gif|png)/i", ucfirst($extension))) {
             continue;
         }
         $imageFiles[] = $file;
     }
     $imageFilesCount = count($imageFiles);
     if ($imageFilesCount == 0) {
         $objProcessFile->write(100);
         die;
     }
     foreach ($imageFiles as $file) {
         /**
          * @var $file \SplFileInfo
          */
         $extension = 'Dir';
         if (!$file->isDir()) {
             $extension = ucfirst(pathinfo($file->getFilename(), PATHINFO_EXTENSION));
         }
         $filePathinfo = pathinfo($file->getRealPath());
         $fileNamePlain = $filePathinfo['filename'];
         $fileInfos = array('filepath' => mb_strcut($file->getPath() . '/' . $file->getFilename(), mb_strlen(ASCMS_PATH)), 'name' => $file->getFilename(), 'cleansize' => $file->getSize(), 'extension' => ucfirst(mb_strtolower($extension)), 'type' => $file->getType());
         $filePathinfo = pathinfo($file->getRealPath());
         $fileExtension = isset($filePathinfo['extension']) ? $filePathinfo['extension'] : '';
         $preview = $cx->getCodeBaseOffsetPath() . str_replace($cx->getCodeBaseDocumentRootPath(), '', $file->getRealPath());
         $previewList = array();
         foreach ($thumbnailList as $thumbnail) {
             $previewList[] = str_replace('.' . lcfirst($extension), $thumbnail['value'] . '.' . lcfirst($extension), $preview);
         }
         $allThumbnailsExists = true;
         foreach ($previewList as $previewImage) {
             if (!FileSystem::exists($previewImage)) {
                 $allThumbnailsExists = false;
             }
         }
         if (!$allThumbnailsExists) {
             if ($imageManager->_isImage($file->getRealPath())) {
                 ThumbnailGenerator::createThumbnail($file->getPath(), $fileNamePlain, $fileExtension, $imageManager, true);
             }
         }
         $fileCounter++;
         $objProcessFile->write($fileCounter / $imageFilesCount * 100);
     }
     $objProcessFile->write(100);
     die;
 }
 /**
  * @param Sigma $template
  */
 public function preFinalize(Sigma $template)
 {
     if (count($this->mediaBrowserInstances) == 0) {
         return;
     } else {
         global $_ARRAYLANG;
         /**
          * @var $init \InitCMS
          */
         $init = \Env::get('init');
         $init->loadLanguageData('MediaBrowser');
         foreach ($_ARRAYLANG as $key => $value) {
             if (preg_match("/TXT_FILEBROWSER_[A-Za-z0-9]+/", $key)) {
                 \ContrexxJavascript::getInstance()->setVariable($key, $value, 'mediabrowser');
             }
         }
         $thumbnailsTemplate = new Sigma();
         $thumbnailsTemplate->loadTemplateFile($this->cx->getCoreModuleFolderName() . '/MediaBrowser/View/Template/Thumbnails.html');
         $thumbnailsTemplate->setVariable('TXT_FILEBROWSER_THUMBNAIL_ORIGINAL_SIZE', sprintf($_ARRAYLANG['TXT_FILEBROWSER_THUMBNAIL_ORIGINAL_SIZE']));
         foreach (UploaderConfiguration::getInstance()->getThumbnails() as $thumbnail) {
             $thumbnailsTemplate->setVariable(array('THUMBNAIL_NAME' => sprintf($_ARRAYLANG['TXT_FILEBROWSER_THUMBNAIL_' . strtoupper($thumbnail['name']) . '_SIZE'], $thumbnail['size']), 'THUMBNAIL_ID' => $thumbnail['id'], 'THUMBNAIL_SIZE' => $thumbnail['size']));
             $thumbnailsTemplate->parse('thumbnails');
         }
         \ContrexxJavascript::getInstance()->setVariable('thumbnails_template', $thumbnailsTemplate->get(), 'mediabrowser');
         \JS::activate('mediabrowser');
         \JS::registerJS('core_modules/MediaBrowser/View/Script/mediabrowser.js');
     }
 }