function install( $package, $installType, $parameters, $name, $os, $filename, $subdirectory, $content, &$installParameters, &$installData ) { $collectionName = $parameters['collection']; $installVariables = array(); if ( isset( $installParameters['variables'] ) ) $installVariables = $installParameters['variables']; $iniFileVariables = false; if ( isset( $installParameters['ini'] ) ) $iniFileVariables = $installParameters['ini']; $fileList = $package->fileList( $collectionName ); if ( $fileList ) { foreach ( $fileList as $fileItem ) { $newFilePath = false; if ( $fileItem['type'] == 'thumbnail' ) { } else { $filePath = $package->fileItemPath( $fileItem, $collectionName ); if ( is_dir( $filePath ) ) { $newFilePath = $package->fileStorePath( $fileItem, $collectionName, $installParameters['path'], $installVariables ); eZDir::mkdir( $newFilePath, false, true ); } else { $newFilePath = $package->fileStorePath( $fileItem, $collectionName, $installParameters['path'], $installVariables ); if ( preg_match( "#^(.+)/[^/]+$#", $newFilePath, $matches ) ) { eZDir::mkdir( $matches[1], false, true ); } eZFileHandler::copy( $filePath, $newFilePath ); } } if ( $fileItem['type'] == 'ini' and $iniFileVariables and $newFilePath ) { $fileRole = $fileItem['role']; $fileRoleValue = $fileItem['role-value']; $fileVariableName = $fileItem['variable-name']; $fileName = $fileItem['name']; if ( $fileVariableName and isset( $installParameters['variables'][$fileVariableName] ) ) $fileRoleValue = $installParameters['variables'][$fileVariableName]; if ( isset( $iniFileVariables[$fileRole][$fileRoleValue][$fileName] ) ) { $variables = $iniFileVariables[$fileRole][$fileRoleValue][$fileName]; $ini = eZINI::fetchFromFile( $newFilePath ); $ini->setVariables( $variables ); $ini->save( false, false, false, false, false ); } } } } return true; }
public function archiveFile($path, $seeds, $prefix = null, $realm = null) { $archiveFileName = $this->getArchiveFileName($path, $seeds, $prefix, $realm); if (eZFileHandler::copy($path, $archiveFileName)) { return array('archive_file_name' => $archiveFileName, 'seeds' => $seeds, 'prefix' => $prefix, 'realm' => $realm); } else { return false; } }
function createInstallNode($package, $installNode, $installItem, $installType) { $installNode->setAttribute('original-path', $installItem['path']); $installNode->setAttribute('database-type', $installItem['database-type']); $originalPath = $installItem['path']; $installDirectory = $package->path() . '/' . eZDBPackageHandler::sqlDirectory(); if ($installItem['database-type']) { $installDirectory .= '/' . $installItem['database-type']; } if (!file_exists($installDirectory)) { eZDir::mkdir($installDirectory, false, true); } eZFileHandler::copy($originalPath, $installDirectory . '/' . $installItem['filename']); }
function installTemplates( $templateList, $package, $subdirectory, &$installParameters ) { if ( !$templateList ) { return true; } $siteAccessDesignPathArray = array(); $templateRootPath = $package->path() . '/' . $subdirectory; foreach( $templateList->getElementsByTagName( 'file' ) as $fileNode ) { $originalSiteAccess = $fileNode->getAttribute( 'site-access' ); if ( isset( $installParameters['site_access_map'][$originalSiteAccess] ) ) { $newSiteAccess = $installParameters['site_access_map'][$originalSiteAccess]; } else { $newSiteAccess = $installParameters['site_access_map']['*']; } if ( !isset( $siteAccessDesignPathArray[$newSiteAccess] ) ) { $ini = eZINI::instance( 'site.ini', 'settings', null, null, true ); $ini->prependOverrideDir( "siteaccess/$newSiteAccess", false, 'siteaccess' ); $ini->loadCache(); if ( isset( $installParameters['design_map'] ) ) { $designMap = $installParameters['design_map']; if ( isset( $designMap[$originalSiteAccess] ) ) $siteAccessDesignPathArray[$newSiteAccess] = eZTemplateDesignResource::designStartPath() . '/' . $designMap[$originalSiteAccess]; else $siteAccessDesignPathArray[$newSiteAccess] = eZTemplateDesignResource::designStartPath() . '/' . $designMap['*']; } else { $siteAccessDesignPathArray[$newSiteAccess] = eZTemplateDesignResource::designStartPath() . '/' . $ini->variable( "DesignSettings", "StandardDesign" ); } } $path = ''; foreach( $fileNode->childNodes as $pathNode ) { if ( $pathNode->nodeName == 'path' ) { $path = $pathNode->nodeValue; break; } } $sourcePath = $templateRootPath . $path; $destinationPath = $siteAccessDesignPathArray[$newSiteAccess] . $path; eZDir::mkdir( eZDir::dirpath( $destinationPath ), false, true ); if ( !eZFileHandler::copy( $sourcePath, $destinationPath ) ) return false; // eZDebug::writeNotice( 'Copied: "' . $sourcePath . '" to: "' . $destinationPath . '"', __METHOD__ ); } return true; }
/** * Retrieve list of packages available to download. * * Example of return value: * array( * 'packages' => array( * '<package_name1>' => array( "name" =>... , "version" =>... , "summary" => ... "url" =>... ), * '<package_name2>' => array( "name" =>... , "version" =>... , "summary" => ... "url" =>... ) * ) * ); * */ function retrieveRemotePackagesList($onlySitePackages = false) { // Download index file. $idxFileName = $this->downloadFile($this->XMLIndexURL, eZStepSiteTypes::tempDir(), 'index.xml'); if ($idxFileName === false) { // Searching for a local index.xml file to use for offline installation $destIndexPath = eZStepSiteTypes::tempDir() . DIRECTORY_SEPARATOR . 'index.xml'; $repo = eZPackage::systemRepositoryInformation(); if ($repo) { $sourceIndexPath = $repo['path'] . DIRECTORY_SEPARATOR . 'index.xml'; if (file_exists($sourceIndexPath)) { eZFileHandler::copy($sourceIndexPath, $destIndexPath); $idxFileName = $destIndexPath; // Removing error message from downloadFile $this->ErrorMsg = false; } } } if ($idxFileName === false) { $this->ErrorMsg = ezpI18n::tr('design/standard/setup/init', 'Retrieving remote site packages list failed. ' . 'You may upload packages manually.'); eZDebug::writeNotice("Cannot download remote packages index file from '{$this->XMLIndexURL}'."); return false; } // Parse it. $dom = new DOMDocument('1.0', 'utf-8'); $dom->preserveWhiteSpace = false; $success = $dom->load(realpath($idxFileName)); @unlink($idxFileName); if (!$success) { eZDebug::writeError("Unable to open index file."); return false; } $root = $dom->documentElement; if ($root->localName != 'packages') { eZDebug::writeError("Malformed index file."); return false; } $packageList = array(); foreach ($root->childNodes as $packageNode) { if ($packageNode->localName != 'package') { // skip unwanted chilren continue; } if ($onlySitePackages && $packageNode->getAttribute('type') != 'site') { // skip non-site packages continue; } $packageAttributes = array(); foreach ($packageNode->attributes as $attributeNode) { $packageAttributes[$attributeNode->localName] = $attributeNode->value; } $packageList[$packageAttributes['name']] = $packageAttributes; } return $packageList; }
function appendSimpleFile($key, $filepath) { if (!isset($this->Parameters['simple-file-list'])) { $this->Parameters['simple-file-list'] = array(); } $suffix = eZFile::suffix($filepath); //$sourcePath = $fileInfo['original-path']; $packagePath = eZPackage::simpleFilesDirectory() . '/' . substr(md5(mt_rand()), 0, 8) . '.' . $suffix; $destinationPath = $this->path() . '/' . $packagePath; eZDir::mkdir(eZDir::dirpath($destinationPath), false, true); //SP DBfile $fileHandler = eZClusterFileHandler::instance(); $fileHandler->fileFetch($filepath); eZFileHandler::copy($filepath, $destinationPath); $this->Parameters['simple-file-list'][$key] = array('original-path' => $filepath, 'package-path' => $packagePath); }
/** * * Clears or purges the cache item $cacheItem. * * If $purge is true then the system will ensure the entries are removed from * local storage or database backend, otherwise it will use possible optimizations * which might only invalidate the cache entry directly or use global expiry values. * * @param $cacheItem Cache item array taken from fetchList() * @param $purge Controls whether clearing/invalidation or purge is used. * @param $reporter Callback which is called when the system has purged files from the system, called with filename and purge count as parameters. * @param $iterationSleep The amount of microseconds to sleep between each purge iteration, false means no sleep. * @param $iterationMax The maximum number of items to purge in one iteration, false means use default limit. * @param $expiry A timestamp which is matched against all cache items, if the modification of the cache is older than the expiry the cache is purged, false means no expiry checking. */ static function clearItem($cacheItem, $purge = false, $reporter = false, $iterationSleep = false, $iterationMax = false, $expiry = false) { // Get the global expiry value if one is set and compare it with supplied $expiry value. // Use the largest value of the two. if (isset($cacheItem['expiry-key'])) { $key = $cacheItem['expiry-key']; eZExpiryHandler::registerShutdownFunction(); $expiryHandler = eZExpiryHandler::instance(); $keyValue = $expiryHandler->getTimestamp($key); if ($keyValue !== false) { if ($expiry !== false) { $expiry = max($expiry, $keyValue); } else { $expiry = $keyValue; } } } $cacheItem['purge'] = $purge; $cacheItem['reporter'] = $reporter; $cacheItem['iterationSleep'] = $iterationSleep; $cacheItem['iterationMax'] = $iterationMax; $cacheItem['expiry'] = $expiry; $functionName = false; if ($purge && isset($cacheItem['purge-function'])) { $functionName = 'purge-function'; } else { if (!$purge && isset($cacheItem['function'])) { $functionName = 'function'; } } if ($functionName) { $function = $cacheItem[$functionName]; if (is_callable($function)) { call_user_func_array($function, array($cacheItem)); } else { eZDebug::writeError("Could not call cache item {$functionName} for id '{$cacheItem['id']}', is it a static public function?", __METHOD__); } } else { if (!isset($cacheItem['path']) || strlen($cacheItem['path']) < 1) { eZDebug::writeError("No path specified for cache item '{$cacheItem['name']}', can not clear cache.", __METHOD__); return; } $cachePath = eZSys::cacheDirectory() . "/" . $cacheItem['path']; if (isset($cacheItem['is-clustered'])) { $isClustered = $cacheItem['is-clustered']; } else { $isClustered = false; } if ($isClustered) { $fileHandler = eZClusterFileHandler::instance($cachePath); if ($purge) { $fileHandler->purge($reporter, $iterationSleep, $iterationMax, $expiry); } else { $fileHandler->delete(); } return; } if (is_file($cachePath)) { $handler = eZFileHandler::instance(false); $handler->unlink($cachePath); } else { eZDir::recursiveDelete($cachePath); } } }
/** * Downloads and imports package. * * Sets $this->ErrorMsg in case of an error. * * \param $forceDownload download even if this package already exists. * \private * \return false on error, package object otherwise. */ function downloadAndImportPackage($packageName, $packageUrl, $forceDownload = false) { $package = eZPackage::fetch($packageName, false, false, false); if (is_object($package)) { if ($forceDownload) { $package->remove(); } else { eZDebug::writeNotice("Skipping download of package '{$packageName}': package already exists."); return $package; } } $archiveName = $this->downloadFile($packageUrl, eZStepSiteTypes::tempDir()); if ($archiveName === false) { eZDebug::writeWarning("Download of package '{$packageName}' from '{$packageUrl}' failed: {$this->ErrorMsg}"); $this->ErrorMsg = ezpI18n::tr('design/standard/setup/init', 'Download of package \'%pkg\' failed. You may upload the package manually.', false, array('%pkg' => $packageName)); return false; } $package = eZPackage::import($archiveName, $packageName, false); // Remove downloaded ezpkg file eZFileHandler::unlink($archiveName); if (!$package instanceof eZPackage) { if ($package == eZPackage::STATUS_INVALID_NAME) { eZDebug::writeNotice("The package name {$packageName} is invalid"); } else { eZDebug::writeNotice("Invalid package"); } $this->ErrorMsg = ezpI18n::tr('design/standard/setup/init', 'Invalid package'); return false; } return $package; }
/** * Move file. * * \public */ function move($dstPath) { $srcPath = $this->filePath; eZDebugSetting::writeDebug('kernel-clustering', "fs::move( '{$srcPath}', '{$dstPath}' )", __METHOD__); eZDebug::accumulatorStart('dbfile', false, 'dbfile'); eZFileHandler::move($srcPath, $dstPath); eZDebug::accumulatorStop('dbfile'); }
function initializeFromFile($filename, $imageAltText = false, $originalFilename = false) { if (!file_exists($filename)) { $contentObjectID = isset($this->ContentObjectAttributeData['contentobject_id']) ? $this->ContentObjectAttributeData['contentobject_id'] : 0; $contentObjectAttributeID = isset($this->ContentObjectAttributeData['id']) ? $this->ContentObjectAttributeData['id'] : 0; $version = isset($this->ContentObjectAttributeData['version']) ? $this->ContentObjectAttributeData['version'] : 0; $contentObject = eZContentObject::fetch($contentObjectID); $contentObjectAttribute = eZContentObjectAttribute::fetch($contentObjectAttributeID, $version); $contentObjectAttributeName = ''; $contentObjectName = ''; if ($contentObject instanceof eZContentObject) { $contentObjectName = $contentObject->attribute('name'); } if ($contentObjectAttribute instanceof eZContentObjectAttribute) { $contentObjectAttributeName = $contentObjectAttribute->attribute('contentclass_attribute_name'); } eZDebug::writeError("The image '{$filename}' does not exist, cannot initialize image attribute: '{$contentObjectAttributeName}' (id: {$contentObjectAttributeID}) for content object: '{$contentObjectName}' (id: {$contentObjectID})", __METHOD__); return false; } $this->increaseImageSerialNumber(); if (!$originalFilename) { $originalFilename = basename($filename); } $mimeData = eZMimeType::findByFileContents($filename); if (!$mimeData['is_valid'] and $originalFilename != $filename) { $mimeData = eZMimeType::findByFileContents($originalFilename); } $attr = false; $this->removeAliases($attr); $this->setOriginalAttributeDataValues($this->ContentObjectAttributeData['id'], $this->ContentObjectAttributeData['version'], $this->ContentObjectAttributeData['language_code']); $contentVersion = eZContentObjectVersion::fetchVersion($this->ContentObjectAttributeData['version'], $this->ContentObjectAttributeData['contentobject_id']); $objectName = $this->imageName($this->ContentObjectAttributeData, $contentVersion); $objectPathString = $this->imagePath($this->ContentObjectAttributeData, $contentVersion, true); eZMimeType::changeBaseName($mimeData, $objectName); eZMimeType::changeDirectoryPath($mimeData, $objectPathString); if (!file_exists($mimeData['dirpath'])) { eZDir::mkdir($mimeData['dirpath'], false, true); } eZFileHandler::copy($filename, $mimeData['url']); return $this->initialize($mimeData, $originalFilename, $imageAltText); }
/** * Clears (removes) active extension cache files from the cache folder. * @return void */ public static function clearActiveExtensionsCache() { $filesList = glob(self::CACHE_DIR . 'active_extensions_*.php'); foreach ($filesList as $path) { if (is_file($path)) { $handler = eZFileHandler::instance(false); $handler->unlink($path); } } }
$newSuffix = $suffix; $contentVersion = eZContentObjectVersion::fetchVersion($attributeVersion, $objectID); if ($contentVersion) { $objectName = $imageAliasHandler->imageName($contentObjectAttribute, $contentVersion); $objectPathString = $imageAliasHandler->imagePath($contentObjectAttribute, $contentVersion); $newDirPath = $objectPathString; $newFileName = $objectName . '.' . $mimeInfo['suffix']; $newSuffix = $mimeInfo['suffix']; $newFilePath = $newDirPath . '/' . $newFileName; $newBaseName = $objectName; } if ($newFilePath != $filePath) { if (!file_exists($newDirPath)) { eZDir::mkdir($newDirPath, false, true); } eZFileHandler::copy($filePath, $newFilePath); $filePath = $newFilePath; $fileName = $newFileName; $suffix = $newSuffix; $dirPath = $newDirPath; $baseName = $newBaseName; } } } $mimeData = eZMimeType::findByFileContents($fileName); $imageManager->analyzeImage($mimeData); $imageNode->setAttribute('serial_number', false); $imageNode->setAttribute('is_valid', $isValid); $imageNode->setAttribute('filename', $fileName); $imageNode->setAttribute('suffix', $suffix); $imageNode->setAttribute('basename', $baseName);
function unserializeContentObjectAttribute($package, $objectAttribute, $attributeNode) { $mediaNode = $attributeNode->getElementsByTagName('media-file')->item(0); if (!$mediaNode) { // No media type data found. return; } $mediaFile = eZMedia::create($objectAttribute->attribute('id'), $objectAttribute->attribute('version')); $sourcePath = $package->simpleFilePath($mediaNode->getAttribute('filekey')); $ini = eZINI::instance(); $mimeType = $mediaNode->getAttribute('mime-type'); list($mimeTypeCategory, $mimeTypeName) = explode('/', $mimeType); $destinationPath = eZSys::storageDirectory() . '/original/' . $mimeTypeCategory . '/'; if (!file_exists($destinationPath)) { if (!eZDir::mkdir($destinationPath, false, true)) { return false; } } $basename = basename($mediaNode->getAttribute('filename')); while (file_exists($destinationPath . $basename)) { $basename = substr(md5(mt_rand()), 0, 8) . '.' . eZFile::suffix($mediaNode->getAttribute('filename')); } eZFileHandler::copy($sourcePath, $destinationPath . $basename); eZDebug::writeNotice('Copied: ' . $sourcePath . ' to: ' . $destinationPath . $basename, __METHOD__); $mediaFile->setAttribute('contentobject_attribute_id', $objectAttribute->attribute('id')); $mediaFile->setAttribute('filename', $basename); $mediaFile->setAttribute('original_filename', $mediaNode->getAttribute('original-filename')); $mediaFile->setAttribute('mime_type', $mediaNode->getAttribute('mime-type')); $mediaFile->setAttribute('width', $mediaNode->getAttribute('width')); $mediaFile->setAttribute('height', $mediaNode->getAttribute('height')); $mediaFile->setAttribute('has_controller', $mediaNode->getAttribute('has-controller')); $mediaFile->setAttribute('controls', $mediaNode->getAttribute('controls')); $mediaFile->setAttribute('is_autoplay', $mediaNode->getAttribute('is-autoplay')); $mediaFile->setAttribute('pluginspage', $mediaNode->getAttribute('plugins-page')); $mediaFile->setAttribute('quality', $mediaNode->getAttribute('quality')); $mediaFile->setAttribute('is_loop', $mediaNode->getAttribute('is-loop')); $fileHandler = eZClusterFileHandler::instance(); $fileHandler->fileStore($destinationPath . $basename, 'mediafile', true); $mediaFile->store(); }
static function unlink($filename = false) { if (!$filename) { if ($this->isOpen()) { $this->close(); } $filename = $this->FileName; } $result = eZFileHandler::doUnlink($filename); if (!$result) { eZDebug::writeError("Failed unlinking file " . $filename, 'eZFileHandler::unlink'); } return $result; }
if ($attributeStringContent != '') { switch ($datatypeString = $attribute->attribute('data_type_string')) { case 'ezimage': $imagePathParts = explode('/', $attributeStringContent); $imageFile = array_pop($imagePathParts); // here it would be nice to add a check if such file allready exists $success = eZFileHandler::copy($attributeStringContent, $storageDir . '/' . $imageFile); if (!$success) { $status = false; } $attributeStringContent = $imageFile; break; case 'ezbinaryfile': case 'ezmedia': $binaryData = explode('|', $attributeStringContent); $success = eZFileHandler::copy($binaryData[0], $storageDir . '/' . $binaryData[1]); if (!$success) { $status = false; } $attributeStringContent = $binaryData[1]; break; default: } } $objectData[] = $attributeStringContent; } if (!$fp) { $cli->error("Can not open output file"); $script->shutdown(5); } if (!fputcsv($fp, $objectData, ';')) {
function unserializeContentObjectAttribute( $package, $objectAttribute, $attributeNode ) { $fileNode = $attributeNode->getElementsByTagName( 'binary-file' )->item( 0 ); if ( !is_object( $fileNode ) or !$fileNode->hasAttributes() ) { return; } $binaryFile = eZBinaryFile::create( $objectAttribute->attribute( 'id' ), $objectAttribute->attribute( 'version' ) ); $sourcePath = $package->simpleFilePath( $fileNode->getAttribute( 'filekey' ) ); if ( !file_exists( $sourcePath ) ) { eZDebug::writeError( "The file '$sourcePath' does not exist, cannot initialize file attribute with it", __METHOD__ ); return false; } $ini = eZINI::instance(); $mimeType = $fileNode->getAttribute( 'mime-type' ); list( $mimeTypeCategory, $mimeTypeName ) = explode( '/', $mimeType ); $destinationPath = eZSys::storageDirectory() . '/original/' . $mimeTypeCategory . '/'; if ( !file_exists( $destinationPath ) ) { $oldumask = umask( 0 ); if ( !eZDir::mkdir( $destinationPath, false, true ) ) { umask( $oldumask ); return false; } umask( $oldumask ); } $basename = basename( $fileNode->getAttribute( 'filename' ) ); while ( file_exists( $destinationPath . $basename ) ) { $basename = substr( md5( mt_rand() ), 0, 8 ) . '.' . eZFile::suffix( $fileNode->getAttribute( 'filename' ) ); } eZFileHandler::copy( $sourcePath, $destinationPath . $basename ); eZDebug::writeNotice( 'Copied: ' . $sourcePath . ' to: ' . $destinationPath . $basename, __METHOD__ ); $binaryFile->setAttribute( 'contentobject_attribute_id', $objectAttribute->attribute( 'id' ) ); $binaryFile->setAttribute( 'filename', $basename ); $binaryFile->setAttribute( 'original_filename', $fileNode->getAttribute( 'original-filename' ) ); $binaryFile->setAttribute( 'mime_type', $fileNode->getAttribute( 'mime-type' ) ); $binaryFile->store(); $fileHandler = eZClusterFileHandler::instance(); $fileHandler->fileStore( $destinationPath . $basename, 'binaryfile', true ); }
function unlink( $filename = false ) { if ( !$filename ) { if ( $this->isOpen() ) $this->close(); $filename = $this->FileName; } $result = eZFileHandler::doUnlink( $filename ); if ( !$result ) eZDebug::writeError( "Failed unlinking file " . $filename, __METHOD__ ); return $result; }
static function copy( $sourceDirectory, &$destinationDirectory, $asChild = true, $recursive = true, $includeHidden = false, $excludeItems = false ) { if ( !is_dir( $sourceDirectory ) ) { eZDebug::writeError( "Source $sourceDirectory is not a directory, cannot copy from it", __METHOD__ ); return false; } if ( !is_dir( $destinationDirectory ) ) { eZDebug::writeError( "Destination $destinationDirectory is not a directory, cannot copy to it", __METHOD__ ); return false; } if ( $asChild ) { if ( preg_match( "#^.+/([^/]+)$#", $sourceDirectory, $matches ) ) { eZDir::mkdir( $destinationDirectory . '/' . $matches[1], eZDir::directoryPermission(), false ); $destinationDirectory .= '/' . $matches[1]; } } $items = eZDir::findSubitems( $sourceDirectory, 'df', false, $includeHidden, $excludeItems ); $totalItems = $items; while ( count( $items ) > 0 ) { $currentItems = $items; $items = array(); foreach ( $currentItems as $item ) { $fullPath = $sourceDirectory . '/' . $item; if ( is_file( $fullPath ) ) eZFileHandler::copy( $fullPath, $destinationDirectory . '/' . $item ); else if ( is_dir( $fullPath ) ) { eZDir::mkdir( $destinationDirectory . '/' . $item, eZDir::directoryPermission(), false ); $newItems = eZDir::findSubitems( $fullPath, 'df', $item, $includeHidden, $excludeItems ); $items = array_merge( $items, $newItems ); $totalItems = array_merge( $totalItems, $newItems ); unset( $newItems ); } } } // eZDebugSetting::writeNotice( 'lib-ezfile-copy', // "Copied directory $sourceDirectory to destination $destinationDirectory", // 'eZDir::copy' ); return $totalItems; }
/** * 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; }
/** * Converts xhtml to pdf * * @param $xhtml * @return Binary pdf content or false if error */ public function generatePDF($xhtml) { //check if $tmpdir exists else try to create it if (!eZFileHandler::doExists($this->tmpDir)) { if (!eZDir::mkdir($this->tmpDir, eZDir::directoryPermission(), true)) { eZDebug::writeWarning("ParadoxPDF::generatePDF Error : could not create temporary directory {$this->tmpDir} ", 'ParadoxPDF::generatePDF'); eZLog::write("ParadoxPDF::generatePDF Error : could not create temporary directory {$this->tmpDir} ", 'paradoxpdf.log'); return false; } } elseif (!eZFileHandler::doIsWriteable($this->tmpDir)) { //check if $tmpdir is writable eZDebug::writeWarning("ParadoxPDF::generatePDF Error : please make {$this->tmpDir} writable ", 'ParadoxPDF::generatePDF'); eZLog::write("ParadoxPDF::generatePDF Error : please make {$this->tmpDir} writable ", 'paradoxpdf.log'); return false; } $rand = md5('paradoxpdf' . getmypid() . mt_rand()); $tmpXHTMLFile = eZDir::path(array($this->tmpDir, "{$rand}.xhtml")); $tmpPDFFile = eZDir::path(array($this->tmpDir, "{$rand}.pdf")); //fix relative urls to match ez root directory $xhtml = $this->fixURL($xhtml); eZFile::create($tmpXHTMLFile, false, $xhtml); $pdfContent = ''; //run jar in headless mode $command = $this->javaExec . " -Djava.awt.headless=true"; if ($this->debugEnabled && $this->debugVerbose) { $command .= " -Dxr.util-logging.loggingEnabled=true"; } $command .= " -jar " . $this->paradoxPDFExec . " {$tmpXHTMLFile} {$tmpPDFFile}"; //fix to get all command output $command .= " 2>&1"; //Enter the Matrix exec($command, $output, $returnCode); //Cant trust java return code so we test if a plain pdf file is genereated if (!(eZFileHandler::doExists($tmpPDFFile) && ($this->size = filesize($tmpPDFFile)))) { $this->writeCommandLog($command, $output, false); return false; } $this->writeCommandLog($command, $output, true); $pdfContent = file_get_contents($tmpPDFFile); //cleanup temporary files //if debug enabled preseves the temporary pdf file //else remove all temporary files if (!$this->debugEnabled) { eZFileHandler::unlink($tmpPDFFile); eZFileHandler::unlink($tmpXHTMLFile); } return $pdfContent; }