function handleFileDownload($contentObject, $contentObjectAttribute, $type, $fileInfo)
 {
     $fileName = $fileInfo['filepath'];
     $file = eZClusterFileHandler::instance($fileName);
     if ($fileName != "" and $file->exists()) {
         $fileSize = $file->size();
         if (isset($_SERVER['HTTP_RANGE']) && preg_match("/^bytes=(\\d+)-(\\d+)?\$/", trim($_SERVER['HTTP_RANGE']), $matches)) {
             $fileOffset = $matches[1];
             $contentLength = isset($matches[2]) ? $matches[2] - $matches[1] + 1 : $fileSize - $matches[1];
         } else {
             $fileOffset = 0;
             $contentLength = $fileSize;
         }
         // Figure out the time of last modification of the file right way to get the file mtime ... the
         $fileModificationTime = $file->mtime();
         // stop output buffering, and stop the session so that browsing can be continued while downloading
         eZSession::stop();
         ob_end_clean();
         eZFile::downloadHeaders($fileName, self::dispositionType($fileInfo['mime_type']) === 'attachment', false, $fileOffset, $contentLength, $fileSize);
         try {
             $file->passthrough($fileOffset, $contentLength);
         } catch (eZClusterFileHandlerNotFoundException $e) {
             eZDebug::writeError($e->getMessage, __METHOD__);
             header($_SERVER["SERVER_PROTOCOL"] . ' 500 Internal Server Error');
         } catch (eZClusterFileHandlerGeneralException $e) {
             eZDebug::writeError($e->getMessage, __METHOD__);
             header($_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
         }
         eZExecution::cleanExit();
     }
     return eZBinaryFileHandler::RESULT_UNAVAILABLE;
 }
Exemplo n.º 2
0
 static function generateNodeView($tpl, $node, $object, $languageCode, $viewMode, $offset, $cacheDir, $cachePath, $viewCacheEnabled, $viewParameters = array('offset' => 0, 'year' => false, 'month' => false, 'day' => false), $collectionAttributes = false, $validation = false)
 {
     $cacheFile = eZClusterFileHandler::instance($cachePath);
     $args = compact("tpl", "node", "object", "languageCode", "viewMode", "offset", "viewCacheEnabled", "viewParameters", "collectionAttributes", "validation");
     $Result = $cacheFile->processCache(null, array('eZNodeviewfunctions', 'generateCallback'), null, null, $args);
     return $Result;
 }
Exemplo n.º 3
0
function addFiles(&$index, $dirname, $dirArray)
{
    try {
        $dir = new eZClusterDirectoryIterator($dirname);
    } catch (Exception $e) {
        if ($e instanceof UnexpectedValueException) {
            eZDebug::writeDebug("Cannot add {$dirname} to the sitemaps index because it does not exist");
            return;
        }
    }
    foreach ($dir as $file) {
        $f = eZClusterFileHandler::instance($file->name());
        if ($f->exists()) {
            $exists = true;
            break;
        }
    }
    if (false != $exists) {
        foreach ($dir as $file) {
            if (in_array($file->name(), $dirArray)) {
                continue;
            }
            if ($file->size() > 50) {
                $date = new xrowSitemapItemModified();
                $date->date = new DateTime("@" . $file->mtime());
                $loc = 'http://' . $_SERVER['HTTP_HOST'] . '/' . $file->name();
                if (!in_array($loc, $GLOBALS['loc'])) {
                    $GLOBALS['loc'][] = $loc;
                    $index->add($loc, array($date));
                }
            }
        }
    }
}
 /**
  * (called for each obj attribute)
  */
 public function checkObjectAttribute(array $contentObjectAttribute)
 {
     // we adopt the ez api instead of acting on raw data
     $contentObjectAttribute = new eZContentObjectAttribute($contentObjectAttribute);
     $binaryFile = $contentObjectAttribute->attribute('content');
     $warnings = array();
     // do not check attributes which do not even contain images
     if ($binaryFile) {
         // get path to original file
         $filePath = $binaryFile->attribute('filepath');
         // check if it is on fs (remember, images are clusterized)
         $file = eZClusterFileHandler::instance($filePath);
         if (!$file->exists()) {
             $warnings[] = "Binary file not found: {$filePath}" . $this->postfixErrorMsg($contentObjectAttribute);
         } else {
             // if it is, check its size as well
             if ($this->maxSize > 0) {
                 $maxSize = $this->maxSize * 1024 * 1024;
                 if ($file->size() > $maxSize) {
                     $warnings[] = "Binary file larger than {$maxSize} bytes : " . $file->size() . $this->postfixErrorMsg($contentObjectAttribute);
                 }
             }
         }
     } else {
         if (!$this->nullable) {
             $warnings[] = "Attribute is null and it should not be" . $this->postfixErrorMsg($contentObjectAttribute);
         }
     }
     return $warnings;
 }
    public function tearDown()
    {
        ezpINIHelper::restoreINISettings();
        eZClusterFileHandler::resetHandler();

        parent::tearDown();
    }
Exemplo n.º 6
0
 /**
  * Constructor
  */
 public function __construct()
 {
     $http = eZHTTPTool::instance();
     //  @todo change hasVariable to hasPostVariable
     if (!$http->hasVariable('key') || !$http->hasVariable('image_id') || !$http->hasVariable('image_version') || !$http->hasVariable('history_version')) {
         //  @todo manage errors
         return;
     }
     $this->key = $http->variable('key');
     $this->image_id = $http->variable('image_id');
     $this->image_version = $http->variable('image_version');
     $this->history_version = $http->variable('history_version');
     // retieve the attribute image
     $this->original_image = eZContentObjectAttribute::fetch($this->image_id, $this->image_version)->attribute('content');
     if ($this->original_image === null) {
         //  @todo manage error (the image_id does not match any existing image)
         return;
     }
     // we could store the images in var/xxx/cache/public
     $this->working_folder = eZSys::cacheDirectory() . "/public/ezie/" . $this->key;
     $this->image_path = $this->working_folder . "/" . $this->history_version . "-" . $this->original_image->attributeFromOriginal('filename');
     // check if file exists (that will mean the data sent is correct)
     $absolute_image_path = eZSys::rootDir() . "/" . $this->image_path;
     $handler = eZClusterFileHandler::instance();
     if (!$handler->fileExists($this->image_path)) {
         // @todo manage error
         return;
     }
     $this->prepare_region();
 }
Exemplo n.º 7
0
    /**
     * @param string $path
     * @return bool|string
     */
    private static function fileExists($path)
    {
        $fileUtils = eZClusterFileHandler::instance($path);

        if ($fileUtils->requiresClusterizing())
        {
            if (!self::$dfsBackend)
            {
                self::$dfsBackend = new eZDFSFileHandlerDFSBackend();
            }

            $mountPoint = self::$dfsBackend->getMountPoint();
            $path       = eZDir::path(array($mountPoint, $path));

            if (file_exists($path))
            {
                return $path;
            }

        }
        else
        {
            if (file_exists($path))
            {
                return $path;
            }
        }

        return false;
    }
Exemplo n.º 8
0
    static function handle( $cachePath, $nodeID, $ttl, $useGlobalExpiry = true )
    {
        $globalExpiryTime = -1;
        eZExpiryHandler::registerShutdownFunction();
        if ( $useGlobalExpiry )
        {
            $globalExpiryTime = eZExpiryHandler::getTimestamp( 'template-block-cache', -1 );
        }

        $cacheHandler = eZClusterFileHandler::instance( $cachePath );

        $subtreeExpiry = -1;
        // Perform an extra check if the DB handler is in use,
        // get the modified_subnode value from the specified node ($nodeID)
        // and use it as an extra expiry value.
        if ( $cacheHandler instanceof eZDBFileHandler or $cacheHandler instanceof eZDFSFileHandler )
        {
            $subtreeExpiry = eZTemplateCacheBlock::getSubtreeModification( $nodeID );
        }
        $globalExpiryTime = max( eZExpiryHandler::getTimestamp( 'global-template-block-cache', -1 ), // This expiry value is the true global expiry for cache-blocks
                                 $globalExpiryTime,
                                 $subtreeExpiry );

        if ( $ttl == 0 )
            $ttl = -1;
        return array( &$cacheHandler,
                      $cacheHandler->processCache( array( 'eZTemplateCacheBlock', 'retrieveContent' ), null,
                                                   $ttl, $globalExpiryTime ) );
    }
 /**
  * Constructor
  */
 function __construct()
 {
     $this->Timestamps = array();
     $this->IsModified = false;
     $cacheDirectory = eZSys::cacheDirectory();
     $this->CacheFile = eZClusterFileHandler::instance($cacheDirectory . '/' . 'expiry.php');
     $this->restore();
 }
Exemplo n.º 10
0
 /**
  * Test for the fetchUnique() method
  *
  * Doesn't do much with eZFS. Nothing, actually.
  */
 public function testFetchUnique()
 {
     $testFile = 'var/tests/' . __FUNCTION__ . '/file.txt';
     $this->createFile($testFile, "contents");
     $clusterHandler = eZClusterFileHandler::instance($testFile);
     $fetchedFile = $clusterHandler->fetchUnique();
     self::assertSame($testFile, $fetchedFile, "A unique name should have been returned");
     self::deleteLocalFiles($testFile, $fetchedFile);
 }
Exemplo n.º 11
0
 function fileSize()
 {
     $fileInfo = $this->storedFileInfo();
     $file = eZClusterFileHandler::instance($fileInfo['filepath']);
     if ($file->exists()) {
         return $file->size();
     }
     return 0;
 }
Exemplo n.º 12
0
 /**
  * Overload of ezcImageAnalyzer::analyzeImage()
  * Creates a temporary local copy of the image file so that it can be analyzed
  *
  * @return void
  */
 public function analyzeImage()
 {
     $clusterHandler = eZClusterFileHandler::instance($this->filePath);
     $clusterHandler->fetch();
     parent::analyzeImage();
     if ($this->deleteLocal) {
         $clusterHandler->deleteLocal();
     }
 }
Exemplo n.º 13
0
 public static function save_token($SettingsBlock, $Token, $TokenSuffix = false)
 {
     $ngpush_cache = eZSys::cacheDirectory() . (self::ngpush_cache_dir ? '/' . self::ngpush_cache_dir : '');
     $token_file = $ngpush_cache . '/' . (self::token_prefix ? '_' . self::token_prefix : '') . $SettingsBlock . ($TokenSuffix ? '_' . $TokenSuffix : '') . '.txt';
     $fileHandler = eZClusterFileHandler::instance($token_file);
     $fileHandler->storeContents($Token);
     $storedToken = $fileHandler->fetchContents();
     if ($storedToken !== false) {
         return true;
     }
     return false;
 }
 function handleFileDownload($contentObject, $contentObjectAttribute, $type, $fileInfo)
 {
     $fileName = $fileInfo['filepath'];
     $file = eZClusterFileHandler::instance($fileName);
     if ($fileName != "" and $file->exists()) {
         $file->fetch(true);
         $fileSize = $file->size();
         $mimeType = $fileInfo['mime_type'];
         $contentLength = $fileSize;
         $fileOffset = false;
         $fileLength = false;
         if (isset($_SERVER['HTTP_RANGE'])) {
             $httpRange = trim($_SERVER['HTTP_RANGE']);
             if (preg_match("/^bytes=(\\d+)-(\\d+)?\$/", $httpRange, $matches)) {
                 $fileOffset = $matches[1];
                 if (isset($matches[2])) {
                     $fileLength = $matches[2] - $matches[1] + 1;
                     $lastPos = $matches[2];
                 } else {
                     $fileLength = $fileSize - $matches[1];
                     $lastPos = $fileSize - 1;
                 }
                 header("Content-Range: bytes {$matches['1']}-" . $lastPos . "/{$fileSize}");
                 header("HTTP/1.1 206 Partial Content");
                 $contentLength = $fileLength;
             }
         }
         // Figure out the time of last modification of the file right way to get the file mtime ... the
         $fileModificationTime = filemtime($fileName);
         ob_clean();
         header("Pragma: ");
         header("Cache-Control: ");
         /* Set cache time out to 10 minutes, this should be good enough to work around an IE bug */
         header("Expires: " . gmdate('D, d M Y H:i:s', time() + 600) . ' GMT');
         header("Last-Modified: " . gmdate('D, d M Y H:i:s', $fileModificationTime) . ' GMT');
         header("Content-Length: {$contentLength}");
         header("Content-Type: {$mimeType}");
         header("X-Powered-By: eZ Publish");
         header("Content-Disposition: " . self::dispositionType($mimeType));
         header("Content-Transfer-Encoding: binary");
         header("Accept-Ranges: bytes");
         $fh = fopen("{$fileName}", "rb");
         if ($fileOffset !== false && $fileLength !== false) {
             echo stream_get_contents($fh, $contentLength, $fileOffset);
         } else {
             ob_end_clean();
             fpassthru($fh);
         }
         fclose($fh);
         eZExecution::cleanExit();
     }
     return eZBinaryFileHandler::RESULT_UNAVAILABLE;
 }
 /**
  * Regression test for issue #18613 :
  * Empty ezcontentlanguage_cache.php not being regenerated.
  * This cache file should always exist, but if for some reason it's empty (lost sync with cluster for instance),
  * it should be at least properly regenerated
  *
  * @link http://issues.ez.no/18613
  * @group issue18613
  */
 public function testFetchListWithBlankCacheFile()
 {
     // First simulate a problem generating the language cache file (make it blank)
     $cachePath = eZSys::cacheDirectory() . '/ezcontentlanguage_cache.php';
     $clusterFileHandler = eZClusterFileHandler::instance($cachePath);
     $clusterFileHandler->storeContents('', 'content', 'php');
     unset($GLOBALS['eZContentLanguageList']);
     // Language list should never be empty
     self::assertNotEmpty(eZContentLanguage::fetchList());
     // Remove the test language cache file
     $clusterFileHandler->delete();
     $clusterFileHandler->purge();
 }
Exemplo n.º 16
0
 /**
  * Main method called to configure/initialize handler.
  * Here you may read your data to import
  */
 public function initialize()
 {
     if (!$this->options->file) {
         throw new SQLIImportConfigException('No file to import!');
     }
     $clusterFilePath = eZClusterFileHandler::instance()->fileFetch($this->options->file);
     if (!$clusterFilePath) {
         throw new SQLIImportConfigException($this->options->file . ' could not be found');
     }
     $this->validateFile('file', $clusterFilePath);
     $this->csv = new SQLICSVDoc(new SQLICSVOptions(array('csv_path' => $clusterFilePath)));
     $this->csv->parse();
 }
Exemplo n.º 17
0
 function outputSendDataToClient( $output, $headers_only = false )
 {
     if ( $output["file"] )
     {
         $realPath = $output["file"];
         $file = eZClusterFileHandler::instance( $realPath );
         $file->fetch();
     }
     $result = $this->outputSendDataToClientFull($output,$headers_only);
     if ( $output["file"] && is_object( $file ) )
         $file->deleteLocal();
     return $result;
 }
Exemplo n.º 18
0
 function outputSendDataToClient($output, $headers_only = false)
 {
     if ($output["file"]) {
         $realPath = $output["file"];
         require_once 'kernel/classes/ezclusterfilehandler.php';
         $file = eZClusterFileHandler::instance($realPath);
         $file->fetch();
     }
     $result = $this->outputSendDataToClientFull($output, $headers_only);
     if ($output["file"] && is_object($file)) {
         $file->deleteLocal();
     }
     return $result;
 }
Exemplo n.º 19
0
 /**
  * Saves the xml content
  *
  * @param $filename Path to file
  */
 function save($filename = 'sitemap.xml')
 {
     $file = eZClusterFileHandler::instance($filename);
     if ($file->exists()) {
         eZDebug::writeDebug("Time: " . date('d.m.Y H:i:s') . ". Action: " . $filename . " exists. File will be remove.");
         if (!$isQuiet) {
             $cli = eZCLI::instance();
             $cli->output("Time: " . date('d.m.Y H:i:s') . ". Action: " . $filename . " exists. File will be remove.");
             $cli->output("\n");
         }
         $file->delete();
     }
     $xml = $this->dom->saveXML();
     return $file->storeContents($xml, 'sitemap', 'text/xml');
 }
Exemplo n.º 20
0
 protected function tearDown()
 {
     chdir($this->legacyPath);
     if (file_exists('var/test')) {
         $fs = new Filesystem();
         $fs->remove('var/test');
     }
     /** @var $legacyKernel Kernel */
     $legacyKernel = $_ENV['legacyKernel'];
     $legacyKernel->runCallback(function () {
         \eZClusterFileHandler::instance()->fileDelete('var/test', true);
     });
     chdir($this->originalDir);
     parent::tearDown();
 }
Exemplo n.º 21
0
    /**
     * @param string  $clusterIdentifier
     * @param string $source
     * @param string $type
     * @param bool $forceUpdate
     */
    public function __construct( $clusterIdentifier, $source, $type = 'form', $forceUpdate = false )
    {
        $this->clusterIdentifier = $clusterIdentifier;
        $this->source = $source;
        $this->type = $type;
        $this->context = self::determineContextFromType( $type );
        $this->forceUpdate = $forceUpdate;

        $varDir = eZINI::instance( 'site.ini' )->variable( 'FileSettings', 'VarDir' );
        $outputFile = "{$varDir}/images/common/misc/{$this->clusterIdentifier}/{$this->type}/{$this->source}.png";
        $this->fileUtils = eZClusterFileHandler::instance( $outputFile );
        if ( !$this->fileUtils->fileExists( $outputFile ) )
        {
            $this->forceUpdate = true;
        }
    }
 public static function clearCache()
 {
     eZDebug::writeNotice("Clear calendar query cache", __METHOD__);
     $ini = eZINI::instance();
     if ($ini->hasVariable('SiteAccessSettings', 'RelatedSiteAccessList') && ($relatedSiteAccessList = $ini->variable('SiteAccessSettings', 'RelatedSiteAccessList'))) {
         if (!is_array($relatedSiteAccessList)) {
             $relatedSiteAccessList = array($relatedSiteAccessList);
         }
         $relatedSiteAccessList[] = $GLOBALS['eZCurrentAccess']['name'];
         $siteAccesses = array_unique($relatedSiteAccessList);
     } else {
         $siteAccesses = $ini->variable('SiteAccessSettings', 'AvailableSiteAccessList');
     }
     $cacheBaseDir = eZDir::path(array(eZSys::cacheDirectory(), static::cacheDirectory()));
     $fileHandler = eZClusterFileHandler::instance();
     $fileHandler->fileDeleteByDirList($siteAccesses, $cacheBaseDir, '');
     $fileHandler = eZClusterFileHandler::instance($cacheBaseDir);
     $fileHandler->purge();
 }
Exemplo n.º 23
0
 /**
  * (called for each obj attribute)
  */
 public function checkObjectAttribute(array $contentObjectAttribute)
 {
     // we adopt the ez api instead of acting on raw data
     $contentObjectAttribute = new eZContentObjectAttribute($contentObjectAttribute);
     $handler = $contentObjectAttribute->attribute('content');
     $warnings = array();
     // do not check attributes which do not even contain images
     if ($handler->attribute('is_valid')) {
         // get path to original file
         $original = $handler->attribute('original');
         $filePath = $original['full_path'];
         // check if it is on fs (remember, images are clusterized)
         $file = eZClusterFileHandler::instance($filePath);
         if (!$file->exists()) {
             $warnings[] = array("Image file not found: {$filePath}" . $this->postfixErrorMsg($contentObjectAttribute));
         } else {
             // if it is, check its size as well
             if ($this->maxSize > 0) {
                 $maxSize = $this->maxSize * 1024 * 1024;
                 if ($file->size() > $maxSize) {
                     $warnings[] = "Image bigger than {$maxSize} bytes : " . $file->size() . $this->postfixErrorMsg($contentObjectAttribute);
                 }
             }
         }
         // check if it is in custom table in db
         $image = eZImageFile::fetchByFilepath($contentObjectAttribute->attribute('id'), $filePath, false);
         if (!$image) {
             $warnings[] = "Image not found in ezimagefile table: {$filePath}" . $this->postfixErrorMsg($contentObjectAttribute);
         }
     } else {
         if (!$this->nullable) {
             $warnings[] = "Attribute is null and it should not be" . $this->postfixErrorMsg($contentObjectAttribute);
         }
         // q: are these old images possibly tied to older versions of the content ?
         /*$db = eZDB::instance();
           $count = $db->arrayQuery('select count(*) as leftovers from ezimagefile where contentobject_attribute_id='.$contentObjectAttribute->attribute('id'));
           if($count[0]['leftovers'])
           {
               $warnings[] = "Leftovers in ezimageattribute table" . $this->postfixErrorMsg( $contentObjectAttribute );
           }*/
     }
     return $warnings;
 }
 /**
  *
  * http://maps.googleapis.com/maps/api/staticmap?zoom=13&size=600x300&maptype=roadmap&markers=color:blue|{first_set( $attribute.content.latitude, '0.0')},{first_set( $attribute.content.longitude, '0.0')}
  * @param array $parameters
  * @param eZContentObjectAttribute $attribute
  * @return string
  */
 public static function gmapStaticImage(array $parameters, eZContentObjectAttribute $attribute, $extraCacheFileNameStrings = array())
 {
     $cacheParameters = array(serialize($parameters));
     $cacheFile = $attribute->attribute('id') . implode('-', $extraCacheFileNameStrings) . '-' . md5(implode('-', $cacheParameters)) . '.cache';
     $extraPath = eZDir::filenamePath($attribute->attribute('id'));
     $cacheDir = eZDir::path(array(eZSys::cacheDirectory(), 'gmap_static', $extraPath));
     // cacenllo altri file con il medesimo attributo
     $fileList = array();
     $deleteItems = eZDir::recursiveList($cacheDir, $cacheDir, $fileList);
     foreach ($fileList as $file) {
         if ($file['type'] == 'file' && $file['name'] !== $cacheFile) {
             unlink($file['path'] . '/' . $file['name']);
         }
     }
     $cachePath = eZDir::path(array($cacheDir, $cacheFile));
     $args = compact('parameters', 'attribute');
     $cacheFile = eZClusterFileHandler::instance($cachePath);
     $result = $cacheFile->processCache(array('OCOperatorsCollectionsTools', 'gmapStaticImageRetrieve'), array('OCOperatorsCollectionsTools', 'gmapStaticImageGenerate'), null, null, $args);
     return $result;
 }
Exemplo n.º 25
0
 /**
  * Executes the purge operation
  *
  * @todo Endless loop on fetch list. The expired items are returned over and over again
  */
 public function run()
 {
     $cli = eZCLI::instance();
     if ($this->optMemoryMonitoring == true) {
         eZLog::rotateLog(self::LOG_FILE);
         $cli->output("Logging memory usage to " . self::LOG_FILE);
     }
     if ($this->optIterationSleep > 0) {
         $sleep = $this->optIterationSleep * 1000000;
     } else {
         $sleep = false;
     }
     $limit = array(0, $this->optIterationLimit);
     $cli->output("Purging expired items:");
     self::monitor("start");
     // Fetch a limited list of purge items from the handler itself
     $clusterHandler = eZClusterFileHandler::instance();
     while ($filesList = $clusterHandler->fetchExpiredItems($this->optScopes, $limit, $this->optExpiry)) {
         self::monitor("iteration start");
         foreach ($filesList as $file) {
             $cli->output("- {$file}");
             if ($this->optDryRun == false) {
                 self::monitor("purge");
                 $fh = eZClusterFileHandler::instance($file);
                 $fh->purge(false, false);
                 unset($fh);
             }
         }
         if ($sleep !== false) {
             usleep($sleep);
         }
         // the offset only has to be increased in dry run mode
         // since each batch is not deleted
         if ($this->optDryRun == true) {
             $limit[0] += $limit[1];
         }
         self::monitor("iteration end");
     }
     self::monitor("end");
 }
 function __construct($dirname, $scope = null)
 {
     $handler = eZClusterFileHandler::instance();
     if ($handler instanceof eZFSFileHandler) {
         $dir = new DirectoryIterator($dirname);
         foreach ($dir as $file) {
             if ($file->isDot() and $file->isDir()) {
                 continue;
             }
             $this->array[] = eZClusterFileHandler::instance($dirname . '/' . $file->getFilename());
         }
     } elseif ($handler instanceof eZDFSFileHandler or $handler instanceof eZDBFileHandler) {
         $sitemaplist = $handler->getFileList(array("sitemap"));
         foreach ($sitemaplist as $sitemap) {
             $so = eZClusterFileHandler::instance($sitemap);
             if (strpos($so->name(), $dirname) !== false and !$so->isExpired(-1, time(), null)) {
                 $this->array[] = $so;
             }
         }
     }
     $this->position = 0;
 }
Exemplo n.º 27
0
 function trashStoredObjectAttribute($contentObjectAttribute, $version = null)
 {
     $contentObjectAttributeID = $contentObjectAttribute->attribute("id");
     $imageHandler = $contentObjectAttribute->attribute('content');
     $imageFiles = eZImageFile::fetchForContentObjectAttribute($contentObjectAttributeID);
     foreach ($imageFiles as $imageFile) {
         if ($imageFile == null) {
             continue;
         }
         $existingFilepath = $imageFile;
         // Check if there are any other records in ezimagefile that point to that filename.
         $imageObjectsWithSameFileName = eZImageFile::fetchByFilepath(false, $existingFilepath);
         $file = eZClusterFileHandler::instance($existingFilepath);
         if ($file->exists() and count($imageObjectsWithSameFileName) <= 1) {
             $orig_dir = dirname($existingFilepath) . '/trashed';
             $fileName = basename($existingFilepath);
             // create dest filename in the same manner as eZHTTPFile::store()
             // grab file's suffix
             $fileSuffix = eZFile::suffix($fileName);
             // prepend dot
             if ($fileSuffix) {
                 $fileSuffix = '.' . $fileSuffix;
             }
             // grab filename without suffix
             $fileBaseName = basename($fileName, $fileSuffix);
             // create dest filename
             $newFileBaseName = md5($fileBaseName . microtime() . mt_rand());
             $newFileName = $newFileBaseName . $fileSuffix;
             $newFilepath = $orig_dir . '/' . $newFileName;
             // rename the file, and update the database data
             $imageHandler->updateAliasPath($orig_dir, $newFileBaseName);
             if ($imageHandler->isStorageRequired()) {
                 $imageHandler->store($contentObjectAttribute);
                 $contentObjectAttribute->store();
             }
         }
     }
 }
Exemplo n.º 28
0
 /**
  * Returns the configured instance of an eZClusterFileHandlerInterface
  * See ClusteringSettings.FileHandler in php.ini
  *
  * @param string|bool $filename
  *        Optional filename the handler should be initialized with
  *
  * @return eZClusterFileHandlerInterface
  */
 static function instance($filename = false)
 {
     if (self::$isShutdownFunctionRegistered !== true) {
         eZExecution::addCleanupHandler(array(__CLASS__, 'cleanupGeneratingFiles'));
         self::$isShutdownFunctionRegistered = true;
     }
     if ($filename !== false) {
         $optionArray = array('iniFile' => 'file.ini', 'iniSection' => 'ClusteringSettings', 'iniVariable' => 'FileHandler', 'handlerParams' => array($filename));
         $options = new ezpExtensionOptions($optionArray);
         $handler = eZExtension::getHandlerClass($options);
         return $handler;
     } else {
         // return Filehandler from GLOBALS based on ini setting.
         if (!isset($GLOBALS['eZClusterFileHandler_chosen_handler'])) {
             $optionArray = array('iniFile' => 'file.ini', 'iniSection' => 'ClusteringSettings', 'iniVariable' => 'FileHandler');
             $options = new ezpExtensionOptions($optionArray);
             $handler = eZExtension::getHandlerClass($options);
             $GLOBALS['eZClusterFileHandler_chosen_handler'] = $handler;
         } else {
             $handler = $GLOBALS['eZClusterFileHandler_chosen_handler'];
         }
         return $handler;
     }
 }
Exemplo n.º 29
0
 /**
  * Performs the ezcImageConverter transformation
  *
  * @param  string $src Source image
  * @param  string $dst Destination image
  * @return void
  */
 public function perform($src, $dst)
 {
     // fetch the input file locally
     $inClusterHandler = eZClusterFileHandler::instance($src);
     $inClusterHandler->fetch();
     try {
         $this->converter->transform('transformation', $src, $dst);
     } catch (Exception $e) {
         $inClusterHandler->deleteLocal();
         throw $e;
     }
     // store the output file to the cluster
     $outClusterHandler = eZClusterFileHandler::instance();
     // @todo Check if the local output file can be deleted at that stage. Theorically yes.
     $outClusterHandler->fileStore($dst, true);
     // fixing the file permissions
     eZImageHandler::changeFilePermissions($dst);
 }
Exemplo n.º 30
0
    /**
     * Converts the source image $sourceMimeData into the destination image
     * $destinationMimeData.
     *
     * @param mixed $sourceMimeData Source image, either a mimedata array or the
     *        source image path
     * @param mixed $destinationMimeData
     *        Either a mimedata array or the target image path
     * @param mixed $aliasName
     *        Target alias (small, medium, large...)
     * @param array $parameters
     *        Optional parameters. Known ones so far: (basename)
     * @return bool
     */
    function convert( $sourceMimeData, &$destinationMimeData, $aliasName = false, $parameters = array() )
    {
        // if the local file doesn't exist, we need to fetch it locally
        if ( !file_exists( $sourceMimeData['url'] ) )
        {
            $sourceFileHandler = eZClusterFileHandler::instance( $sourceMimeData['url'] );
            $sourceFileHandler->fetch();
        }

        if ( is_string( $sourceMimeData ) )
            $sourceMimeData = eZMimeType::findByFileContents( $sourceMimeData );

        $this->analyzeImage( $sourceMimeData );
        $currentMimeData = $sourceMimeData;
        $handlers = $this->ImageHandlers;
        $supportedMIMEMap = $this->SupportedMIMEMap;
        if ( is_string( $destinationMimeData ) )
        {
            $destinationPath = $destinationMimeData;
            $destinationMimeData = eZMimeType::findByFileContents( $destinationPath );
        }

        $filters = array();
        $alias = false;
        if ( $aliasName )
        {
            $aliasList = $this->aliasList();
            if ( isset( $aliasList[$aliasName] ) )
            {
                $alias = $aliasList[$aliasName];
                $filters = $alias['filters'];
                if ( $alias['mime_type'] )
                {
                    eZMimeType::changeMIMEType( $destinationMimeData, $alias['mime_type'] );
                }
            }
        }
        $mimeTypeOverride = $this->mimeTypeOverride( $sourceMimeData );
        if ( $mimeTypeOverride )
            $alias['override_mime_type'] = $mimeTypeOverride;

        if ( isset( $parameters['filters'] ) )
        {
            $filters = array_merge( $filters, $parameters['filters'] );
        }

        $wantedFilters = $filters;
        $mimeTypeFilters = $this->mimeTypeFilters( $sourceMimeData );
        if ( is_array( $mimeTypeFilters ) )
            $wantedFilters = array_merge( $wantedFilters, $mimeTypeFilters );
        $filters = array();
        foreach ( array_keys( $wantedFilters ) as $wantedFilterKey )
        {
            $wantedFilter = $wantedFilters[$wantedFilterKey];
            if ( !$this->isFilterSupported( $wantedFilter['name'] ) )
            {
                eZDebug::writeWarning( "The filter '" . $wantedFilter['name'] . "' is not supported by any of the image handlers, will ignore this filter", __METHOD__ );
                continue;
            }
            $filters[] = $wantedFilter;
        }
        if ( !$destinationMimeData['is_valid'] )
        {
            $destinationDirPath = $destinationMimeData['dirpath'];
            $destinationBasename = $destinationMimeData['basename'];
            if ( isset( $supportedMIMEMap[$sourceMimeData['name']] ) )
            {
                $destinationMimeData = $sourceMimeData;
                if ( $alias['mime_type'] )
                {
                    eZMimeType::changeMIMEType( $destinationMimeData, $alias['mime_type'] );
                }
                eZMimeType::changeFileData( $destinationMimeData, $destinationDirPath, $destinationBasename );
            }
            else
            {
                $hasDestination = false;
                foreach ( $handlers as $handler )
                {
                    $gotMimeData = true;
                    while( $gotMimeData )
                    {
                        $gotMimeData = false;
                        $outputMimeData = $handler->outputMIMEType( $this, $sourceMimeData, false, $this->SupportedFormats, $aliasName );
                        if ( $outputMimeData and
                             isset( $supportedMIMEMap[$outputMimeData['name']] ) )
                        {
                            $destinationMimeData = $outputMimeData;
                            eZMimeType::changeFileData( $destinationMimeData, $destinationDirPath, $destinationBasename );
                            $hasDestination = true;
                            $gotMimeData = true;
                            break;
                        }
                    }
                }
                if ( !$hasDestination )
                {
                    if ( isset( $sourceFileHandler ) )
                        $sourceFileHandler->deleteLocal();
                    return false;
                }
            }
        }

        $wantedFilters = $filters;
        $filters = array();
        foreach ( array_keys( $wantedFilters ) as $wantedFilterKey )
        {
            $wantedFilter = $wantedFilters[$wantedFilterKey];
            if ( !$this->isFilterAllowed( $wantedFilter['name'], $destinationMimeData ) )
            {
                continue;
            }
            $filters[] = $wantedFilter;
        }
        $result = true;
        $tempFiles = array();
        if ( $currentMimeData['name'] != $destinationMimeData['name'] or
             count( $filters ) > 0 )
        {
            while ( $currentMimeData['name'] != $destinationMimeData['name'] or
                    count( $filters ) > 0 )
            {
                $nextMimeData = false;
                $nextHandler = false;
                foreach ( $handlers as $handler )
                {
                    if ( !$handler )
                        continue;

                    $handlerFilters = array();
                    $leftoverFilters = array();
                    foreach ( $filters as $filter )
                    {
                        if ( $handler->isFilterSupported( $filter ) )
                            $handlerFilters[] = $filter;
                        else
                            $leftoverFilters[] = $filter;
                    }

                    $outputMimeData = $handler->outputMIMEType( $this, $currentMimeData, $destinationMimeData, $this->SupportedFormats, $aliasName );
                    if ( $outputMimeData['name'] == $destinationMimeData['name'] and count( $handlerFilters ) > 0 )
                    {
                        $nextMimeData = $outputMimeData;
                        $nextHandler = $handler;
                        break;
                    }
                    if ( $outputMimeData and
                         !$nextMimeData )
                    {
                        $nextMimeData = $outputMimeData;
                        $nextHandler = $handler;
                    }
                }
                if ( !$nextMimeData )
                {
                    eZDebug::writeError( "None of the handlers can convert MIME-Type " . $currentMimeData['name'], __METHOD__ );
                    if ( isset( $sourceFile ) )
                        $sourceFile->deleteLocal();
                    return false;
                }

                $useTempImage = false;
                if ( $nextMimeData['name'] == $destinationMimeData['name'] and
                     count( $leftoverFilters ) == 0 )
                {
                    $nextMimeData['dirpath'] = $destinationMimeData['dirpath'];
                }
                else
                {
                    $useTempImage = true;
                    $nextMimeData['dirpath'] = $this->temporaryImageDirPath();
                }
                eZMimeType::changeDirectoryPath( $nextMimeData, $nextMimeData['dirpath'] );

                if ( $nextMimeData['dirpath'] and
                     !file_exists( $nextMimeData['dirpath'] ) )
                    eZDir::mkdir( $nextMimeData['dirpath'], false, true );
                if ( $currentMimeData['name'] == $nextMimeData['name'] and
                     count( $handlerFilters ) == 0 )
                {
                    if ( $currentMimeData['url'] != $nextMimeData['url'] )
                    {
                        if ( eZFileHandler::copy( $currentMimeData['url'], $nextMimeData['url'] ) )
                        {
                            if ( $useTempImage )
                                $tempFiles[] = $nextMimeData['url'];
                        }
                        else
                        {
                            $result = false;
                            break;
                        }
                    }
                    $currentMimeData = $nextMimeData;
                }
                else
                {
                    if ( $nextHandler->convert( $this, $currentMimeData, $nextMimeData, $handlerFilters ) )
                    {
                        if ( $useTempImage )
                            $tempFiles[] = $nextMimeData['url'];
                    }
                    else
                    {
                        $result = false;
                        break;
                    }
                    // store the converted file to cluster if the conversion is between mime name
                    $fileHandler = eZClusterFileHandler::instance();
                    $fileHandler->fileStore( $nextMimeData['url'], 'image', false, $nextMimeData['name']  );

                    $currentMimeData = $nextMimeData;
                }
                $filters = $leftoverFilters;
            }
        }
        else
        {
            $useCopy = false;
            if ( $aliasName and
                 $aliasName != 'original' )
            {
                $destinationMimeData['filename'] = $destinationMimeData['basename'] . '_' . $aliasName . '.' . $destinationMimeData['suffix'];
                if ( $destinationMimeData['dirpath'] )
                    $destinationMimeData['url'] = $destinationMimeData['dirpath'] . '/' . $destinationMimeData['filename'];
                else
                    $destinationMimeData['url'] = $destinationMimeData['filename'];
            }
            if ( $sourceMimeData['url'] != $destinationMimeData['url'] )
            {
                if ( $useCopy )
                {
                    eZFileHandler::copy( $sourceMimeData['url'], $destinationMimeData['url'] );
                }
                else
                {
                    eZFileHandler::linkCopy( $sourceMimeData['url'], $destinationMimeData['url'], false );
                }
                $currentMimeData = $destinationMimeData;
            }
        }
        foreach ( $tempFiles as $tempFile )
        {
            if ( !@unlink( $tempFile ) )
            {
                eZDebug::writeError( "Failed to unlink temporary image file $tempFile", __METHOD__ );
            }
        }
        $destinationMimeData = $currentMimeData;

        if ( $aliasName && $aliasName != 'original' )
        {
            if ( $result )
            {
                $destinationFilePath = $destinationMimeData['url'];
                $fileHandler = eZClusterFileHandler::instance();
                $fileHandler->fileStore( $destinationFilePath, 'image', true, $destinationMimeData['name'] );
            }

            if ( isset( $sourceFileHandler ) )
                $sourceFileHandler->deleteLocal();
        }

        return $result;
    }