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; }
function sendMail(eZMail $mail) { $ini = eZINI::instance(); $sendmailOptions = ''; $emailFrom = $mail->sender(); $emailSender = $emailFrom['email']; if (!$emailSender || count($emailSender) <= 0) { $emailSender = $ini->variable('MailSettings', 'EmailSender'); } if (!$emailSender) { $emailSender = $ini->variable('MailSettings', 'AdminEmail'); } if (!eZMail::validate($emailSender)) { $emailSender = false; } $isSafeMode = ini_get('safe_mode'); if ($isSafeMode and $emailSender and $mail->sender() == false) { $mail->setSenderText($emailSender); } $filename = time() . '-' . mt_rand() . '.mail'; $data = preg_replace('/(\\r\\n|\\r|\\n)/', "\r\n", $mail->headerText() . "\n" . $mail->body()); $returnedValue = eZFile::create($filename, 'var/log/mail', $data); if ($returnedValue === false) { eZDebug::writeError('An error occurred writing the e-mail file in var/log/mail', __METHOD__); } return $returnedValue; }
function sendMail(ezcMail $mail) { $separator = "/"; $mail->appendExcludeHeaders(array('to', 'subject')); $headers = rtrim($mail->generateHeaders()); // rtrim removes the linebreak at the end, mail doesn't want it. if (count($mail->to) + count($mail->cc) + count($mail->bcc) < 1) { throw new ezcMailTransportException('No recipient addresses found in message header.'); } $additionalParameters = ""; if (isset($mail->returnPath)) { $additionalParameters = "-f{$mail->returnPath->email}"; } $sys = eZSys::instance(); $fname = time() . '-' . rand() . '.mail'; $qdir = eZSys::siteDir() . eZSys::varDirectory() . $separator . 'mailq'; $data = $headers . ezcMailTools::lineBreak(); $data .= ezcMailTools::lineBreak(); $data .= $mail->generateBody(); $data = preg_replace('/(\\r\\n|\\r|\\n)/', "\r\n", $data); $success = eZFile::create($fname, $qdir, $data); if ($success === false) { throw new ezcMailTransportException('The email could not be sent by sendmail'); } }
public function synchronise(eZSolrBase $collection, $elevateXML, $params) { $uri_components = parse_url($collection->SearchServerURI); // The extra variables are used to avoid PHP strict warnings using end() directly on the preg_split result $pathElements = preg_split('/\\//', $uri_components['path']); $collectionName = end($pathElements); $filename = implode('__', array($uri_components['host'], $uri_components['port'], $collectionName, 'elevate.xml')); return eZFile::create($filename, $params['base_dir'], $elevateXML); }
/** * Regression test for issue 16400 * @link http://issues.ez.no/16400 * @return unknown_type */ public function testIssue16400() { $className = 'Media test class'; $classIdentifier = 'media_test_class'; $filePath = 'tests/tests/kernel/datatypes/ezmedia/ezmediatype_regression_issue16400.flv'; eZFile::create( $filePath ); $attributeName = 'Media'; $attributeIdentifier = 'media'; $attributeType = 'ezmedia'; //1. test method fetchByContentObjectID $class = new ezpClass( $className, $classIdentifier, $className ); $class->add( $attributeName, $attributeIdentifier, $attributeType ); $attribute = $class->class->fetchAttributeByIdentifier( $attributeIdentifier ); $attribute->setAttribute( 'can_translate', 0 ); $class->store(); $object = new ezpObject( $classIdentifier, 2 ); $dataMap = $object->object->dataMap(); $fileAttribute = $dataMap[$attributeIdentifier]; $dataType = new eZMediaType(); $dataType->fromString( $fileAttribute, $filePath ); $fileAttribute->store(); $object->publish(); $object->refresh(); //verify fetchByContentObjectID $mediaObject = eZMedia::fetch( $fileAttribute->attribute( 'id' ), 1 ); $medias = eZMedia::fetchByContentObjectID( $object->object->attribute( 'id' ) ); $this->assertEquals( $mediaObject->attribute( 'filename' ), $medias[0]->attribute( 'filename' ) ); $medias = eZMedia::fetchByContentObjectID( $object->object->attribute( 'id' ), $fileAttribute->attribute( 'language_code' ) ); $this->assertEquals( $mediaObject->attribute( 'filename' ), $medias[0]->attribute( 'filename' ) ); //2. test issue // create translation $contentObject = $object->object; $storedFileName = $mediaObject->attribute( 'filename' ); $version = $contentObject->createNewVersionIn( 'nor-NO', $fileAttribute->attribute( 'language_code' ) ); $version->setAttribute( 'status', eZContentObjectVersion::STATUS_INTERNAL_DRAFT ); $version->store(); $version->removeThis(); $sys = eZSys::instance(); $dir = $sys->storageDirectory(); //verify the file is deleted $storedFilePath = $dir . '/original/video/' . $storedFileName; $file = eZClusterFileHandler::instance( $storedFilePath ); $this->assertTrue( $file->exists( $storedFilePath ) ); if ( $file->exists( $storedFilePath ) ) unlink( $storedFilePath ); }
private function __construct() { $ini_varnish = eZINI::instance('mugo_varnish.ini'); $this->debug = $ini_varnish->variable('VarnishSettings', 'DebugCurl') == 'enabled'; $this->varnishServers = $ini_varnish->variable('VarnishSettings', 'VarnishServers'); // override connection timeout if ($ini_varnish->variable('VarnishSettings', 'ConnectionTimeout') > -1) { $this->baseCurlOptions[CURLOPT_CONNECTTIMEOUT] = $ini_varnish->variable('VarnishSettings', 'ConnectionTimeout'); } // make sure the log file exits if (!file_exists(self::CURL_DEBUG_OUTPUT_FILE)) { eZFile::create(self::CURL_DEBUG_OUTPUT_FILE); } }
static function checkMD5Sums($file) { $lines = eZFile::splitLines($file); $result = array(); if (is_array($lines)) { foreach (array_keys($lines) as $key) { $line =& $lines[$key]; if (strlen($line) > 34) { $md5Key = substr($line, 0, 32); $filename = substr($line, 34); if (!file_exists($filename) || $md5Key != md5_file($filename)) { $result[] = $filename; } } } } return $result; }
static function create($filename, $directory = false, $data = false, $atomic = false) { $filepath = $filename; if ($directory) { if (!file_exists($directory)) { eZDir::mkdir($directory, false, true); // eZDebugSetting::writeNotice( 'ezfile-create', "Created directory $directory", 'eZFile::create' ); } $filepath = $directory . '/' . $filename; } // If atomic creation is needed we will use a temporary // file when writing the data, then rename it to the correct path. if ($atomic) { $realpath = $filepath; $dirname = dirname($filepath); if (strlen($dirname) != 0) { $dirname .= "/"; } $filepath = $dirname . "ezfile-tmp." . md5($filepath . getmypid() . mt_rand()); } $file = fopen($filepath, 'wb'); if ($file) { // eZDebugSetting::writeNotice( 'ezfile-create', "Created file $filepath", 'eZFile::create' ); if ($data) { if (is_resource($data)) { // block-copy source $data to new $file in 1MB chunks while (!feof($data)) { fwrite($file, fread($data, 1048576)); } fclose($data); } else { fwrite($file, $data); } } fclose($file); if ($atomic) { // If the renaming process fails, delete the temporary file eZFile::rename($filepath, $realpath, false, eZFile::CLEAN_ON_FAILURE); } return true; } // eZDebugSetting::writeNotice( 'ezfile-create', "Failed creating file $filepath", 'eZFile::create' ); return false; }
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(); } } } }
/** * Downloads file. * * Sets $this->ErrorMsg in case of an error. * * \private * \param $url URL. * \param $outDir Directory where to put downloaded file to. * \param $forcedFileName Force saving downloaded file under this name. * \return false on error, path to downloaded package otherwise. */ function downloadFile($url, $outDir, $forcedFileName = false) { $fileName = $outDir . "/" . ($forcedFileName ? $forcedFileName : basename($url)); eZDebug::writeNotice("Downloading file '{$fileName}' from {$url}"); // Create the out directory if not exists. if (!file_exists($outDir)) { eZDir::mkdir($outDir, false, true); } // First try CURL if (extension_loaded('curl')) { $ch = curl_init($url); $fp = eZStepSiteTypes::fopen($fileName, 'wb'); if ($fp === false) { $this->ErrorMsg = ezpI18n::tr('design/standard/setup/init', 'Cannot write to file') . ': ' . $this->FileOpenErrorMsg; return false; } curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_FAILONERROR, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3); // Get proxy $ini = eZINI::instance(); $proxy = $ini->hasVariable('ProxySettings', 'ProxyServer') ? $ini->variable('ProxySettings', 'ProxyServer') : false; if ($proxy) { curl_setopt($ch, CURLOPT_PROXY, $proxy); $userName = $ini->hasVariable('ProxySettings', 'User') ? $ini->variable('ProxySettings', 'User') : false; $password = $ini->hasVariable('ProxySettings', 'Password') ? $ini->variable('ProxySettings', 'Password') : false; if ($userName) { curl_setopt($ch, CURLOPT_PROXYUSERPWD, "{$userName}:{$password}"); } } if (!curl_exec($ch)) { $this->ErrorMsg = curl_error($ch); return false; } curl_close($ch); fclose($fp); } else { $parsedUrl = parse_url($url); $checkIP = isset($parsedUrl['host']) ? ip2long(gethostbyname($parsedUrl['host'])) : false; if ($checkIP === false) { return false; } // If we don't have CURL installed we used standard fopen urlwrappers // Note: Could be blocked by not allowing remote calls. if (!copy($url, $fileName)) { $buf = eZHTTPTool::sendHTTPRequest($url, 80, false, 'eZ Publish', false); $header = false; $body = false; if (eZHTTPTool::parseHTTPResponse($buf, $header, $body)) { eZFile::create($fileName, false, $body); } else { $this->ErrorMsg = ezpI18n::tr('design/standard/setup/init', 'Failed to copy %url to local file %filename', null, array("%url" => $url, "%filename" => $fileName)); return false; } } } return $fileName; }
/** * Stores the content of the INI object to the cache file \a $cachedFile. * * @param string $cachedDir Cache dir, usually "var/cache/ini/" * @param string $cachedFile Name of cache file as returned by cacheFileName() * @param array $data Configuration data as an associative array structure * @param array $inputFiles List of input files used as basis for cache (for use in load cache to check mtime) * @param string $iniFile Ini file path string returned by findInputFiles() for main ini file * @return bool */ protected function saveCache($cachedDir, $cachedFile, array $data, array $inputFiles, $iniFile) { if (!file_exists($cachedDir)) { if (!eZDir::mkdir($cachedDir, 0777, true)) { eZDebug::writeError("Couldn't create cache directory {$cachedDir}, perhaps wrong permissions", __METHOD__); return false; } } // Save the data to a temp cached file $tmpCacheFile = $cachedFile . '_' . substr(md5(mt_rand()), 0, 8); $fp = @fopen($tmpCacheFile, "w"); if ($fp === false) { eZDebug::writeError("Couldn't create cache file '{$cachedFile}', perhaps wrong permissions?", __METHOD__); return false; } // Write cache data as a php structure with some meta information for use while reading cache fwrite($fp, "<?php\n// This is a auto generated ini cache file, time created:" . date(DATE_RFC822) . "\n"); fwrite($fp, "\$data = array(\n"); fwrite($fp, "'rev' => " . eZINI::CONFIG_CACHE_REV . ",\n"); fwrite($fp, "'created' => '" . date('c') . "',\n"); if ($this->Codec) { fwrite($fp, "'charset' => \"" . $this->Codec->RequestedOutputCharsetCode . "\",\n"); } else { fwrite($fp, "'charset' => \"{$this->Charset}\",\n"); } fwrite($fp, "'files' => " . preg_replace("@\n[\\s]+@", '', var_export($inputFiles, true)) . ",\n"); fwrite($fp, "'file' => '{$iniFile}',\n"); fwrite($fp, "'val' => " . preg_replace("@\n[\\s]+@", '', var_export($data, true)) . ");"); fwrite($fp, "\n?>"); fclose($fp); // Rename cache temp file to final desitination and set permissions eZFile::rename($tmpCacheFile, $cachedFile); chmod($cachedFile, self::$filePermission); if (eZINI::isDebugEnabled()) { eZDebug::writeNotice("Wrote cache file '{$cachedFile}'", __METHOD__); } return true; }
/** * Stores the data in $fileData to the remote and local file and commits the * transaction. * * The parameter $fileData must contain the same as information as the * $generateCallback returns as explained in processCache(). * @note This method is just a continuation of the code in processCache() * and is not meant to be called alone since it relies on specific * state in the database. */ public function storeCache($fileData) { $scope = false; $datatype = false; $binaryData = null; $fileContent = null; $store = true; $storeCache = false; if (is_array($fileData)) { if (isset($fileData['scope'])) { $scope = $fileData['scope']; } if (isset($fileData['datatype'])) { $datatype = $fileData['datatype']; } if (isset($fileData['content'])) { $fileContent = $fileData['content']; } if (isset($fileData['binarydata'])) { $binaryData = $fileData['binarydata']; } if (isset($fileData['store'])) { $store = $fileData['store']; } } else { $binaryData = $fileData; } // This checks if we entered timeout and got our generating file stolen // If this happens, we don't store our cache if ($store and $this->checkCacheGenerationTimeout()) { $storeCache = true; } $result = null; if ($binaryData === null && $fileContent === null) { eZDebug::writeError("Write callback need to set the 'content' or 'binarydata' entry for '{$this->filePath}'", __METHOD__); $this->abortCacheGeneration(); return null; } if ($binaryData === null) { $binaryData = "<" . "?php\n\treturn " . var_export($fileContent, true) . ";\n?" . ">\n"; } if ($fileContent === null) { $result = $binaryData; } else { $result = $fileContent; } if (!$this->filePath) { return $result; } // no store advice from cache generation timeout or disabled viewcache, // we just return the result if (!$storeCache) { eZDebugSetting::writeDebug('kernel-clustering', "Not storing this cache", __METHOD__); $this->abortCacheGeneration(); return $result; } // stale cache handling: we just return the result, no lock has been set if ($this->useStaleCache) { eZDebugSetting::writeDebug('kernel-clustering', "Stalecache mode enabled for this cache", "dfs::storeCache( {$this->filePath} )"); // we write the generated cache to disk if it does not exist yet, // to speed up the next uncached operation // This file will be overwritten by the real file clearstatcache(); if (!file_exists($this->filePath)) { eZDebugSetting::writeDebug('kernel-clustering', "Writing stale file content to local file {$this->filePath}", __METHOD__); eZFile::create(basename($this->filePath), dirname($this->filePath), $binaryData, true); } return $result; } // Check if we are allowed to store the data, if not just return the result if (!$store) { $this->abortCacheGeneration(); return $result; } // Distinguish bool from eZClusterFileFailure, and call abortCacheGeneration() $storeContentsResult = $this->storeContents($binaryData, $scope, $datatype, $storeLocally = false); // Cache was stored, we end cache generation if ($storeContentsResult === true) { $this->endCacheGeneration(); } else { if ($storeContentsResult instanceof eZMySQLBackendError) { $this->abortCacheGeneration(); } } // We don't do anything if false (not stored for known reasons) has been returned return $result; }
static function create($filename, $directory = false, $data = false, $atomic = false) { $filepath = $filename; if ($directory) { if (!file_exists($directory)) { eZDir::mkdir($directory, false, true); // eZDebugSetting::writeNotice( 'ezfile-create', "Created directory $directory", 'eZFile::create' ); } $filepath = $directory . '/' . $filename; } // If atomic creation is needed we will use a temporary // file when writing the data, then rename it to the correct path. if ($atomic) { $realpath = $filepath; $dirname = dirname($filepath); if (strlen($dirname) != 0) { $dirname .= "/"; } $filepath = $dirname . "ezfile-tmp." . md5($filepath . getmypid() . mt_rand()); } $file = fopen($filepath, 'wb'); if ($file) { // eZDebugSetting::writeNotice( 'ezfile-create', "Created file $filepath", 'eZFile::create' ); if ($data) { fwrite($file, $data); } fclose($file); if ($atomic) { eZFile::rename($filepath, $realpath); } return true; } // eZDebugSetting::writeNotice( 'ezfile-create', "Failed creating file $filepath", 'eZFile::create' ); return false; }
function eZSetupPrvtAreDirAndFilesWritable($dir) { if (!eZDir::isWriteable($dir)) { return FALSE; } // Check if all files within a given directory are writeable $files = eZDir::findSubitems($dir, 'f'); // find only files, skip dirs and symlinks $fileSeparator = eZSys::fileSeparator(); foreach ($files as $file) { if (!eZFile::isWriteable($dir . $fileSeparator . $file)) { return FALSE; } } return TRUE; }
function close() { if ($this->ClusteringEnabled) { $this->ClusterHandler = null; return; } if ($this->FileResource) { fclose($this->FileResource); if ($this->isAtomic) { eZFile::rename($this->tmpFilename, $this->requestedFilename); } $this->FileResource = false; } }
static function renameDir( $dir ) { // just rename. Actual removing will be performed by cronjob. // This directory renaming is only performed on the local filesystem // to ensure purging of really old data. If the DB file handler is in // use it will check the modified_subnode field of the tree structure // to determin expiry when the cache-block entry is accessed. if ( file_exists( $dir ) ) { if ( is_dir( $dir ) ) { $expiryCacheDir = eZTemplateCacheFunction::expiryTemplateBlockCacheDir(); $uniqid = md5( uniqid( 'ezpsubtreecache'. getmypid(), true ) ); $expiryCacheDir .= '/' . $uniqid[0] . '/' . $uniqid[1] . '/' . $uniqid[2] . '/' . $uniqid; if ( !file_exists( $expiryCacheDir ) ) { eZDir::mkdir( $expiryCacheDir, false, true ); } eZFile::rename( $dir, $expiryCacheDir, false, eZFile::APPEND_DEBUG_ON_FAILURE ); } else { eZDebug::writeWarning( "$dir should be a directory. Template-block caches for 'subtree_expiry' are not removed.", __METHOD__ ); } } }
static function doRename( $destinationFilename, $sourceFilename ) { return eZFile::rename( $sourceFilename, $destinationFilename ); }
protected function createFile($filePath, $contents, $atomic = true) { // $contents can result from a failed file_get_contents(). In this case if ($contents === false) { return false; } $createResult = eZFile::create(basename($filePath), dirname($filePath), $contents, $atomic); if ($createResult) { $this->fixPermissions($filePath); } return $createResult; }
/** * store mailitem on filesystem * * @todo eZFile::create result * @return void */ private function storeMessageToFilesystem() { $mailboxItemId = $this->attribute('id'); $mailboxId = $this->attribute('mailbox_id'); $messageId = $this->attribute('message_id'); $currentTimestamp = time(); // return filepath $filePathArray = $this->getFilePathArray(); // return content string of mail item $messageData = $this->MessageString; // create file in path with content $createResult = eZFile::create($filePathArray['file_name'], $filePathArray['file_dir'], $messageData); }
$script->startup(); $options = $script->getOptions('', '', array()); $script->initialize(); $limit = 20; $offset = 0; $db = eZDB::instance(); $script->setIterationData('.', '~'); while ($binaryFiles = eZPersistentObject::fetchObjectList(eZBinaryFile::definition(), null, null, null, array('offset' => $offset, 'limit' => $limit))) { foreach ($binaryFiles as $binaryFile) { $fileName = $binaryFile->attribute('filename'); if (strpos($fileName, '.') !== false) { $text = "skipping {$fileName}, it contains a suffix"; $script->iterate($cli, true, $text); continue; } $suffix = eZFile::suffix($binaryFile->attribute('original_filename')); if ($suffix) { $newFileName = $fileName . '.' . $suffix; $db->begin(); $oldFilePath = $binaryFile->attribute('filepath'); $binaryFile->setAttribute('filename', $newFileName); $binaryFile->store(); $newFilePath = $binaryFile->attribute('filepath'); $file = eZClusterFileHandler::instance($oldFilePath); if ($file->exists()) { $text = "renamed {$fileName} to {$newFileName}"; $file->move($newFilePath); } else { $text = "file not found: {$oldFilePath}"; $script->iterate($cli, false, $text); $db->rollback();
/** * Fetches the file $filePath from the database, saving it locally with its * original name, or $uniqueName if given * * @param string $filePath * @param string $uniqueName * @return the file physical path, or false if fetch failed */ function _fetch($filePath, $uniqueName = false) { $metaData = $this->_fetchMetadata($filePath); if (!$metaData) { eZDebug::writeError("File '{$filePath}' does not exist while trying to fetch.", __METHOD__); return false; } $contentLength = $metaData['size']; $sql = "SELECT filedata, offset FROM " . TABLE_DATA . " WHERE name_hash=" . $this->_md5($filePath) . " ORDER BY offset"; if (!($res = $this->_query($sql, "_fetch({$filePath})"))) { eZDebug::writeError("Failed to fetch file data for file '{$filePath}'.", __METHOD__); return false; } if (!mysql_num_rows($res)) { eZDebug::writeError("No rows in file '{$filePath}' being fetched.", __METHOD__); mysql_free_result($res); return false; } // create temporary file if (strrpos($filePath, '.') > 0) { $tmpFilePath = substr_replace($filePath, getmypid() . 'tmp', strrpos($filePath, '.'), 0); } else { $tmpFilePath = $filePath . '.' . getmypid() . 'tmp'; } $this->__mkdir_p(dirname($tmpFilePath)); if (!($fp = fopen($tmpFilePath, 'wb'))) { eZDebug::writeError("Cannot write to '{$tmpFilePath}' while fetching file.", __METHOD__); return false; } $offset = 0; while ($row = mysql_fetch_row($res)) { $expectedOffset = $row[1]; if ($expectedOffset != $offset) { eZDebug::writeError("The fetched offset value '{$expectedOffset}' does not match the computed one for the file '{$filePath}', aborting fetch.", __METHOD__); fclose($fp); @unlink($filePath); return false; } fwrite($fp, $row[0]); $offset += strlen($row[0]); } if ($offset != $contentLength) { eZDebug::writeError("The size of the fetched data '{$offset}' does not match the expected size '{$contentLength}' for the file '{$filePath}', aborting fetch.", __METHOD__); fclose($fp); @unlink($filePath); return false; } fclose($fp); // Make sure all data is written correctly clearstatcache(); $tmpSize = filesize($tmpFilePath); if ($tmpSize != $metaData['size']) { eZDebug::writeError("Size ({$tmpSize}) of written data for file '{$tmpFilePath}' does not match expected size " . $metaData['size'], __METHOD__); return false; } if (!$uniqueName === true) { eZFile::rename($tmpFilePath, $filePath, false, eZFile::CLEAN_ON_FAILURE | eZFile::APPEND_DEBUG_ON_FAILURE); } else { $filePath = $tmpFilePath; } mysql_free_result($res); return $filePath; }
function fetchNodeInfo( &$node ) { // When finished, we'll return an array of attributes/properties. $entry = array(); // Grab settings from the ini file: $webdavINI = eZINI::instance( eZWebDAVContentServer::WEBDAV_INI_FILE ); $iniSettings = $webdavINI->variable( 'DisplaySettings', 'FileAttribute' ); $classIdentifier = $node->attribute( 'class_identifier' ); $object = $node->attribute( 'object' ); // By default, everything is displayed as a folder: // Trim the name of the node, it is in some cases whitespace in eZ Publish $entry["name"] = trim( $node->attribute( 'name' ) ); $entry["size"] = 0; $entry["mimetype"] = 'httpd/unix-directory'; $entry["ctime"] = $object->attribute( 'published' ); $entry["mtime"] = $object->attribute( 'modified' ); $upload = new eZContentUpload(); $info = $upload->objectFileInfo( $object ); $suffix = ''; $class = $object->contentClass(); $isObjectFolder = $this->isObjectFolder( $object, $class ); if ( $isObjectFolder ) { // We do nothing, the default is to see it as a folder } else if ( $info ) { $filePath = $info['filepath']; $entry["mimetype"] = false; $entry["size"] = false; if ( isset( $info['filesize'] ) ) $entry['size'] = $info['filesize']; if ( isset( $info['mime_type'] ) ) $entry['mimetype'] = $info['mime_type']; // Fill in information from the actual file if they are missing. $file = eZClusterFileHandler::instance( $filePath ); if ( !$entry['size'] and $file->exists() ) { $entry["size"] = $file->size(); } if ( !$entry['mimetype'] ) { $mimeInfo = eZMimeType::findByURL( $filePath ); $entry["mimetype"] = $mimeInfo['name']; $suffix = $mimeInfo['suffix']; if ( strlen( $suffix ) > 0 ) $entry["name"] .= '.' . $suffix; } else { // eZMimeType returns first suffix in its list // this could be another one than the original file extension // so let's try to get the suffix from the file path first $suffix = eZFile::suffix( $filePath ); if ( !$suffix ) { $mimeInfo = eZMimeType::findByName( $entry['mimetype'] ); $suffix = $mimeInfo['suffix']; } if ( strlen( $suffix ) > 0 ) $entry["name"] .= '.' . $suffix; } if ( $file->exists() ) { $entry["ctime"] = $file->mtime(); $entry["mtime"] = $file->mtime(); } } else { // Here we only show items as folders if they have // is_container set to true, otherwise it's an unknown binary file if ( !$class->attribute( 'is_container' ) ) { $entry['mimetype'] = 'application/octet-stream'; } } $scriptURL = eZSys::instance()->RequestURI; if ( strlen( $scriptURL ) > 0 and $scriptURL[ strlen( $scriptURL ) - 1 ] != "/" ) $scriptURL .= "/"; $trimmedScriptURL = trim( $scriptURL, '/' ); $scriptURLParts = explode( '/', $trimmedScriptURL ); $siteAccess = $scriptURLParts[0]; $virtualFolder = $scriptURLParts[1]; $startURL = '/' . $siteAccess . '/' . $virtualFolder . '/'; // Set the href attribute (note that it doesn't just equal the name). if ( !isset( $entry['href'] ) ) { if ( strlen( $suffix ) > 0 ) $suffix = '.' . $suffix; $alias = $node->urlAlias(); if ( $virtualFolder == eZWebDAVContentServer::virtualMediaFolderName() ) { // remove the real media node url alias, the virtual media folder is already in $startURL $aliasParts = explode( '/', $alias ); array_shift( $aliasParts ); $alias = implode( '/', $aliasParts ); } $entry["href"] = $startURL . $alias . $suffix; } // Return array of attributes/properties (name, size, mime, times, etc.). return $entry; }
protected function createFile($path, $content) { return eZFile::create(basename($path), dirname($path), $content, false); }
/** * Gathers information about a given node specified as parameter. * * The format of the returned array is: * <code> * array( 'name' => node name (eg. 'Group picture'), * 'size' => storage size of the_node in bytes (eg. 57123), * 'mimetype' => mime type of the node (eg. 'image/jpeg'), * 'ctime' => creation time as timestamp, * 'mtime' => latest modification time as timestamp, * 'href' => the path to the node (eg. '/plain_site_user/Content/Folder1/file1.jpg') * </code> * * @param string $target Eg. '/plain_site_user/Content/Folder1/file1.jpg * @param eZContentObject &$node The node corresponding to $target * @return array(string=>mixed) * @todo remove/replace .ini calls, eZContentUpload, eZMimeType, eZSys RequestURI * @todo handle articles as files */ protected function fetchNodeInfo($target, &$node) { // When finished, we'll return an array of attributes/properties. $entry = array(); $classIdentifier = $node->attribute('class_identifier'); $object = $node->attribute('object'); $urlAlias = $node->urlAlias(); // By default, everything is displayed as a folder: // Trim the name of the node, it is in some cases whitespace in eZ Publish $name = trim($node->attribute('name')); // @as 2009-03-09: return node_id as displayname in case name is missing // displayname is not actually used by WebDAV clients $entry["name"] = $name !== '' && $name !== NULL ? $name : $node->attribute('node_id'); $entry["size"] = 0; $entry["mimetype"] = self::DIRECTORY_MIMETYPE; eZWebDAVContentBackend::appendLogEntry('FetchNodeInfo:' . $node->attribute('name') . '/' . $urlAlias); // @todo handle articles as files // if ( $classIdentifier === 'article' ) // { // $entry["mimetype"] = 'application/ms-word'; // } $entry["ctime"] = $object->attribute('published'); $entry["mtime"] = $object->attribute('modified'); $upload = new eZContentUpload(); $info = $upload->objectFileInfo($object); $suffix = ''; $class = $object->contentClass(); $isObjectFolder = $this->isObjectFolder($object, $class); if ($isObjectFolder) { // We do nothing, the default is to see it as a folder } else { if ($info) { $filePath = $info['filepath']; $entry['filepath'] = $filePath; $entry["mimetype"] = false; $entry["size"] = false; if (isset($info['filesize'])) { $entry['size'] = $info['filesize']; } if (isset($info['mime_type'])) { $entry['mimetype'] = $info['mime_type']; } // Fill in information from the actual file if they are missing. $file = eZClusterFileHandler::instance($filePath); if (!$entry['size'] and $file->exists()) { $entry["size"] = $file->size(); } if (!$entry['mimetype']) { $mimeInfo = eZMimeType::findByURL($filePath); $entry["mimetype"] = $mimeInfo['name']; $suffix = $mimeInfo['suffix']; if (strlen($suffix) > 0) { $entry["name"] .= '.' . $suffix; } } else { // eZMimeType returns first suffix in its list // this could be another one than the original file extension // so let's try to get the suffix from the file path first $suffix = eZFile::suffix($filePath); if (!$suffix) { $mimeInfo = eZMimeType::findByName($entry['mimetype']); $suffix = $mimeInfo['suffix']; } if (strlen($suffix) > 0) { $entry["name"] .= '.' . $suffix; } } if ($file->exists()) { $entry["ctime"] = $file->mtime(); $entry["mtime"] = $file->mtime(); } } else { // Here we only show items as folders if they have // is_container set to true, otherwise it's an unknown binary file if (!$class->attribute('is_container')) { $entry['mimetype'] = 'application/octet-stream'; } } } $scriptURL = $target; if (strlen($scriptURL) > 0 and $scriptURL[strlen($scriptURL) - 1] !== "/") { $scriptURL .= "/"; } $trimmedScriptURL = trim($scriptURL, '/'); $scriptURLParts = explode('/', $trimmedScriptURL); $urlPartCount = count($scriptURLParts); if ($urlPartCount >= 2) { // one of the virtual folders // or inside one of the virtual folders $siteAccess = $scriptURLParts[0]; $virtualFolder = $scriptURLParts[1]; // only when the virtual folder is Content we need to add its path to the start URL // the paths of other top level folders (like Media) are included in URL aliases of their descending nodes if ($virtualFolder === self::virtualContentFolderName()) { $startURL = '/' . $siteAccess . '/' . $virtualFolder . '/'; } else { if ($virtualFolder === self::virtualMediaFolderName()) { $startURL = '/' . $siteAccess . '/' . $virtualFolder . '/'; $urlAlias = substr($urlAlias, strpos($urlAlias, '/') + 1); } else { $startURL = '/' . $siteAccess . '/'; } } } else { // site access level $startURL = $scriptURL; } // Set the href attribute (note that it doesn't just equal the name). if (!isset($entry['href'])) { if (strlen($suffix) > 0) { $suffix = '.' . $suffix; } $entry["href"] = $startURL . $urlAlias . $suffix; } // Return array of attributes/properties (name, size, mime, times, etc.). return $entry; }
/** * Fetches the file $filePath from the database to its own name * * Saving $filePath locally with its original name, or $uniqueName if given * * @param string $filePath * @param string $uniqueName Alternative name to save the file to * @return string|bool the file physical path, or false if fetch failed */ public function _fetch( $filePath, $uniqueName = false ) { $metaData = $this->_fetchMetadata( $filePath ); if ( !$metaData ) { // @todo Throw an exception eZDebug::writeError( "File '$filePath' does not exist while trying to fetch.", __METHOD__ ); return false; } // create temporary file if ( strrpos( $filePath, '.' ) > 0 ) $tmpFilePath = substr_replace( $filePath, getmypid().'tmp', strrpos( $filePath, '.' ), 0 ); else $tmpFilePath = $filePath . '.' . getmypid().'tmp'; $this->__mkdir_p( dirname( $tmpFilePath ) ); // copy DFS file to temporary FS path // @todo Throw an exception if ( !$this->dfsbackend->copyFromDFS( $filePath, $tmpFilePath ) ) { eZDebug::writeError("Failed copying DFS://$filePath to FS://$tmpFilePath "); return false; } // Make sure all data is written correctly clearstatcache(); $tmpSize = filesize( $tmpFilePath ); // @todo Throw an exception if ( $tmpSize != $metaData['size'] ) { eZDebug::writeError( "Size ($tmpSize) of written data for file '$tmpFilePath' does not match expected size " . $metaData['size'], __METHOD__ ); return false; } if ( $uniqueName !== true ) { eZFile::rename( $tmpFilePath, $filePath, false, eZFile::CLEAN_ON_FAILURE | eZFile::APPEND_DEBUG_ON_FAILURE ); } else { $filePath = $tmpFilePath; } return $filePath; }
/** * Creates the object from the uploaded file and displays the preview of it * * @param array $args * @return array * @throw RuntimeException if the previously uploaded file cannot be fetched */ static function preview( $args ) { $http = eZHTTPTool::instance(); $handler = self::getHandler( $args ); if ( !$handler->canUpload() ) { throw new RuntimeException( ezpI18n::tr( 'extension/ezjscore/ajaxuploader', 'You are not allowed to upload a file.' ) ); } $file = $http->postVariable( 'UploadFile', false ); $fileHandler = eZClusterFileHandler::instance(); if ( $file === false || !$fileHandler->fileExists( $file ) || !$fileHandler->fileFetch( $file ) ) { throw new RuntimeException( ezpI18n::tr( 'extension/ezjscore/ajaxuploader', 'Unable to retrieve the uploaded file.' ) ); } else { $tmpFile = eZSys::cacheDirectory() . '/' . eZINI::instance()->variable( 'FileSettings', 'TemporaryDir' ) . '/' . str_replace( array( '/', '\\' ), '_', $http->postVariable( 'UploadOriginalFilename' ) ); eZFile::rename( $file, $tmpFile, true ); $fileHandler->fileDelete( $file ); $fileHandler->fileDeleteLocal( $file ); } $contentObject = $handler->createObject( $tmpFile, $http->postVariable( 'UploadLocation', false ), $http->postVariable( 'UploadName', '' ) ); unlink( $tmpFile ); $tpl = eZTemplate::factory(); $tpl->setVariable( 'object', $contentObject ); return array( 'meta_data' => $handler->serializeObject( $contentObject ), 'html' => $tpl->fetch( 'design:ajaxuploader/preview.tpl' ) ); }
/** * Move file. * * \public * \static */ function fileMove($srcPath, $dstPath) { eZDebugSetting::writeDebug('kernel-clustering', "fs::fileMove( '{$srcPath}', '{$dstPath}' )", __METHOD__); eZDebug::accumulatorStart('dbfile', false, 'dbfile'); eZFile::rename($srcPath, $dstPath, true); eZDebug::accumulatorStop('dbfile'); }
public function testDownloadNoFile() { ob_start(); $this->assertFalse(eZFile::downloadContent("unexisting.txt")); $this->assertEquals("", ob_get_clean()); }
static function rotateLog($fileName) { $maxLogrotateFiles = eZDebug::maxLogrotateFiles(); if ($maxLogrotateFiles == 0) { return; } for ($i = $maxLogrotateFiles; $i > 0; --$i) { $logRotateName = $fileName . '.' . $i; if (file_exists($logRotateName)) { if ($i == $maxLogrotateFiles) { @unlink($logRotateName); } else { $newLogRotateName = $fileName . '.' . ($i + 1); eZFile::rename($logRotateName, $newLogRotateName); } } } if (file_exists($fileName)) { $newLogRotateName = $fileName . '.' . 1; eZFile::rename($fileName, $newLogRotateName); return true; } return false; }
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); }