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');
     }
 }
 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;
 }
Exemplo n.º 3
0
 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 );
    }
Exemplo n.º 5
0
 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);
     }
 }
 /**
  * Import object.
  *
  * @param Array getParameters.
  * @param Array getOptions.
  * @param Array postParameters.
  * @param Array postOptions.
  * @param string Import type.
  *
  * @return DOMElement DOMElement containing OO document.
  */
 protected function importOODocument($getParams, $getOptions, $postParams, $postOptions, $importType = 'import')
 {
     $nodeID = $postParams['nodeID'];
     $data = $postParams['data'];
     // Alex 2008/04/22 - Added format argument: 'odt' (default), 'doc'
     $format = $postOptions['format'];
     $languageCode = $postOptions['languageCode'];
     $base64Encoded = $postOptions['base64Encoded'];
     $node = eZContentObjectTreeNode::fetch($nodeID, $languageCode);
     if (!$node) {
         throw new Exception('Could not fetch node: ' . $nodeID);
     }
     // Decode data.
     if ($base64Encoded) {
         // Alex 2008/04/16 - Added str_replace()
         $data = base64_decode(str_replace(' ', '+', $data));
     }
     // Store data to temporary file.
     // Alex 2008/04/22 - Added format argument: 'odt' (default), 'doc'
     $filename = substr(md5(mt_rand()), 0, 8) . ".{$format}";
     $tmpFilePath = eZSys::cacheDirectory() . '/ezodf/' . substr(md5(mt_rand()), 0, 8);
     $tmpFilename = $tmpFilePath . '/' . $filename;
     if (!eZFile::create($filename, $tmpFilePath, $data)) {
         throw new Exception('Could not create file: ' . $tmpFilename);
     }
     $import = new eZOOImport();
     $result = $import->import($tmpFilename, $nodeID, $filename, $importType);
     eZDir::recursiveDelete($tmpFilePath);
     if (!$result) {
         throw new Exception('OO import failed: ' . $import->getErrorNumber() . ' - ' . $import->getErrorMessage());
     }
     $domDocument = new DOMDocument('1.0', 'utf-8');
     $importElement = $domDocument->createElement('OOImport');
     // Add node info about imported document.
     $importElement->appendChild($this->createTreeNodeDOMElement($domDocument, $result['MainNode']));
     return $importElement;
 }
 /**
  * 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);
 }
Exemplo n.º 8
0
 function appendDocument($name, $mimeType = false, $os = false, $audience = false, $create = false, $data = false)
 {
     if (!$mimeType) {
         $mimeType = 'text/plain';
     }
     $this->Parameters['documents'][] = array('name' => $name, 'mime-type' => $mimeType, 'os' => $os, 'data' => $data, 'audience' => $audience);
     if ($create) {
         eZFile::create($name, $this->path() . '/' . eZPackage::documentDirectory(), $data);
     }
 }
Exemplo n.º 9
0
 /**
  * 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;
 }
 /**
  * Test for the fileStore() method with the delete option
  */
 public function testFileStoreWithoutDelete()
 {
     // create local file on disk
     $directory = 'var/tests/' . __FUNCTION__;
     $localFile = $directory . '/file.txt';
     eZFile::create('file.txt', $directory, md5(time()));
     // 1. First store to cluster, with delete option
     $ch = eZClusterFileHandler::instance();
     $ch->fileStore($localFile, 'test', false, 'text/plain');
     // 2. Check that the created file exists
     $ch2 = eZClusterFileHandler::instance($localFile);
     self::assertTrue($ch2->exists());
     if (!$this instanceof eZFSFileHandlerTest) {
         self::assertEquals('text/plain', $ch2->metaData['datatype']);
         self::assertEquals('test', $ch2->metaData['scope']);
         self::assertFileExists($localFile);
     }
     self::deleteLocalFiles($localFile);
 }
 /**
  * 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;
     }
     $mtime = false;
     $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;
     }
     // the .generating file is stored to DFS. $storeLocally is set to false
     // since we don't want to store the .generating file locally, only
     // the final file.
     $this->storeContents($binaryData, $scope, $datatype, $storeLocally = false);
     // we end the cache generation process, so that the .generating file
     // is removed (we don't need to rename since contents was already stored
     // above, using fileStoreContents
     $this->endCacheGeneration();
     if (self::LOCAL_CACHE) {
         eZDebugSetting::writeDebug('kernel-clustering', "Creating local copy of the file", "dfs::storeCache( '{$this->filePath}' )");
         eZFile::create(basename($this->filePath), dirname($this->filePath), $binaryData, true);
     }
     return $result;
 }
$sitemap_index = '<?xml version="1.0" encoding="UTF-8"?>';
$sitemap_index .= '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
$limit = 40000;
$offset = 0;
$sql_count = "SELECT count(*) FROM do_sitemap ";
$sitemap_number = 1;
while ($offset < $count) {
    $sitemap_file_name = 'sitemap_' . $sitemap_number . '.xml';
    $sql = "SELECT dosm_loc , dosm_lastmod , dosm_priority , dosm_changefreq FROM do_sitemap LIMIT {$offset} , {$limit} ";
    $results = $db->arrayQuery($sql);
    $sm = '<?xml version="1.0" encoding="UTF-8"?>';
    $sm .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
    foreach ($results as $result) {
        $sm .= '<url>';
        $sm .= '<loc>' . $result['dosm_loc'] . '</loc>';
        $sm .= '<lastmod>' . $result['dosm_lastmod'] . '</lastmod>';
        $sm .= '<changefreq>' . $result['dosm_changefreq'] . '</changefreq>';
        $sm .= '<priority>' . $result['dosm_priority'] . '</priority>';
        $sm .= '</url>';
    }
    $sm .= '</urlset>';
    eZFile::create($sitemap_file_name, eZSys::storageDirectory() . '/images/do_sitemap/', $sm);
    $sitemap_index .= '<sitemap>';
    $sitemap_index .= '<loc>' . $siteURL . '/' . eZSys::storageDirectory() . '/images/do_sitemap/' . $sitemap_file_name . '</loc>';
    $sitemap_index .= '</sitemap>';
    $offset = $offset + $limit;
    $sitemap_number++;
}
$sitemap_index .= '</sitemapindex>';
eZFile::create('sitemap.xml', eZSys::storageDirectory() . '/images/do_sitemap/', $sitemap_index);
 /**
  *
  * @param unknown_type $receiver
  * @param unknown_type $subject
  * @param unknown_type $message
  * @param unknown_type $extraHeaders
  * @param unknown_type $emailReturnPath
  * @return file
  */
 function createMailFile($receiver, $subject, $message, $extraHeaders, $emailReturnPath = '')
 {
     $sys = eZSys::instance();
     $lineBreak = $sys->osType() == 'win32' ? "\r\n" : "\n";
     // $separator =  ($sys->osType() == 'win32' ? "\\" : "/" );
     // $fileName = date("Ymd") .'-' .date("His").'-'.rand().'.mail';
     $fileName = time() . '-' . rand() . '-cjw_nl.mail';
     // $mailDir = eZSys::siteDir().eZSys::varDirectory().'/log/mail';
     // $mailDir = eZSys::siteDir().'var/log/mail';
     $data = $extraHeaders . $lineBreak;
     if ($emailReturnPath != '') {
         $data .= "Return-Path: <" . $emailReturnPath . ">" . $lineBreak;
     }
     $data .= "To: " . $receiver . $lineBreak;
     $data .= "Subject: " . $subject . $lineBreak;
     // $data .= "From: ".$emailSender.$lineBreak;
     $data .= $lineBreak;
     $data .= $message;
     $data = preg_replace('/(\\r\\n|\\r|\\n)/', "\r\n", $data);
     return eZFile::create($fileName, $this->mailDir, $data);
 }
 /**
  * Creates the file $filePath with contents $fileContents on DB + DFS
  *
  * The existing file will be removed unless $params[remove] is set to false
  *
  * @param string $filePath relative file path
  * @param string $fileContents file's content
  * @param array  $params
  *        Optional parameters for creation.
  *        Valid keys:datatype, scope, mtime, status, expired and remove
  *        if remove is set to true, the file will be removed before it is
  *        created
  * @return void
  **/
 protected function createFile($filePath, $fileContents = 'foobar', $params = array())
 {
     $datatype = isset($params['datatype']) ? $params['datatype'] : 'text/test';
     $scope = isset($params['scope']) ? $params['scope'] : 'test';
     $mtime = isset($params['mtime']) ? $params['mtime'] : time();
     $status = isset($params['status']) ? $params['status'] : 0;
     $expired = isset($params['expired']) ? $params['expired'] : 0;
     $createLocalFile = isset($params['create_local_file']) ? $params['create_local_file'] : false;
     $remove = isset($params['remove']) ? $params['remove'] : true;
     if ($remove) {
         $this->removeFile($filePath);
     }
     $nameHash = md5($filePath);
     $size = strlen($fileContents);
     // create DB file
     $sql = "INSERT INTO " . eZDFSFileHandlerMySQLBackend::TABLE_METADATA . "      ( name,        name_trunk,  name_hash,   datatype,    scope,    size,    mtime,    expired,    status )" . "VALUES( '{$filePath}', '{$filePath}', '{$nameHash}', '{$datatype}', '{$scope}', '{$size}', '{$mtime}', '{$expired}', '{$status}' )";
     $this->db->query($sql);
     // create DFS file
     $path = $this->makeDFSPath($filePath);
     eZFile::create(basename($path), dirname($path), $fileContents);
     // create local file
     if ($createLocalFile) {
         eZFile::create(basename($filePath), dirname($filePath), $fileContents);
     }
 }
Exemplo n.º 15
0
function exportCollection($objectID = false, $dir = 'var/export', $format = 'csv', $separator = ',', $days = false, $debug = false)
{
    $ret = false;
    $object = false;
    // Settings
    $ini = eZINI::instance("cie.ini");
    $excludeAttributeID = $ini->variable("CieSettings", "ExcludeAttributeID");
    if (is_numeric($objectID)) {
        $object =& eZContentObject::fetch($objectID);
        $classID = $object->attribute('contentclass_id');
    }
    // eZDebug::writeDebug( $object );
    if (is_numeric($classID)) {
        $class =& eZContentClass::fetch($classID);
    }
    if ($debug == true) {
        echo "Object ClassID: {$classID}\n";
    }
    if (is_object($class)) {
        $className = $class->attribute('identifier');
        $classDataMap = $class->attribute('data_map');
    }
    // Settings
    $ini = eZINI::instance("cie.ini");
    $excludeAttributeID = $ini->variable("CieSettings", "ExcludeAttributeID");
    if ($debug == true) {
        echo "Exporting Collection: {$objectID}\n";
        echo "Output Directory: {$dir}\n";
        echo "Output Format: {$format}\n";
        echo "Output Separator: {$separator}\n";
        echo "Object Collection ID: {$objectID}\n";
        echo "Object Class Name: {$className}\n";
    }
    // if ( $debug == true )
    // print_r( $classDataMap );
    // print_r( $class );
    // die( );
    if (!$object) {
        die('Encountered Non-Object, Unknown Error');
    }
    $collections = eZInformationCollection::fetchCollectionsList($objectID, false, false, array());
    $collection_count = eZInformationCollection::fetchCollectionCountForObject($objectID);
    if ($debug == true) {
        echo "Object Collection Count: {$collection_count}\n\n";
        echo "Object Collection Contents: \n";
        print_r($collections);
    }
    $attributes_to_export = array();
    // fetch collection class attributes for export
    foreach ($classDataMap as $attribute) {
        // print_r( $attribute );
        if (is_object($attribute)) {
            $is_ic = $attribute->attribute('is_information_collector');
            if (is_numeric($is_ic)) {
                if ($is_ic) {
                    $id = $attribute->attribute('id');
                    $name = $attribute->attribute('identifier');
                    $attributes_to_export[] = $id;
                    if ($debug) {
                        print_r("Object Class Attribute Name: {$name} \n");
                        // echo "Object Class Attribute is Information Collector: $is_ic\n";
                        print_r("Object Class Attribute ID: {$id} \n\n");
                    }
                }
            }
        }
    }
    // Set output file name pattern
    if ($days != false) {
        $start = mktime(0, 0, 0, date("m"), date("d") - $days, date("Y"));
        $namePattern = "_" . date("Y-m-d", $start) . "_to_" . date("Y-m-d");
    } else {
        $namePattern = "_export_" . date("Y-m-d_H-i");
    }
    // Set output file name
    switch ($format) {
        case 'csv':
            $filename = $object->attribute('name') . $namePattern . ".csv";
            break;
        case 'sylk':
            $filename = $object->attribute('name') . $namePattern . ".slk";
            break;
        default:
            $filename = $object->attribute('name') . $namePattern . ".csv";
            break;
    }
    $sdir = $dir . '/';
    $path = $sdir . $filename;
    if ($debug == true) {
        echo "Collection Output Filename: {$filename}\n";
        echo "Collection Output Path: {$path}\n";
    }
    if ($debug == true) {
        echo "Class Attributes ot Export (Array): \n";
        print_r($attributes_to_export);
        echo "\n";
    }
    print_r("Object information collection record entries fetch in progress...\n");
    $parser = new Parser();
    $data = $parser->exportInformationCollection($collections, $attributes_to_export, $separator, $format, $days);
    if ($debug == true) {
        echo "Collection Output Content:\n";
        echo "{$data}\n";
    }
    $file = new eZFile();
    $file->create($filename, $dir, $data);
    print_r("Object Collection Data Export File Path: {$path}\n");
    print_r("Object Collection Export Completed!\n\n");
    // flush();
    // eZExecution::cleanExit();
}
Exemplo n.º 16
0
 function createFile($message)
 {
     $sys = eZSys::instance();
     $lineBreak = $sys->osType() == 'win32' ? "\r\n" : "\n";
     $separator = $sys->osType() == 'win32' ? "\\" : "/";
     $fname = time() . '-' . rand() . '.sms';
     $qdir = eZSys::siteDir() . eZSys::varDirectory() . $separator . 'mailq';
     $data = $message;
     $data = preg_replace('/(\\r\\n|\\r|\\n)/', "\r\n", $data);
     // echo 'eZFile::create('.$fname.', '.$qdir.', '.$data.');';
     eZFile::create($fname, $qdir, $data);
 }
function storeImportResultToFile($importId, $data)
{
    $fileName = getImportResultFilePath($importId);
    $dir = dirname($fileName);
    $file = basename($fileName);
    // return content string of mail item
    $messageData = serialize($data);
    // create file in path with content
    $createResult = eZFile::create($file, $dir, $messageData);
}
Exemplo n.º 18
0
    /**
     * Creates the file $filePath on DFS with content $contents
     *
     * @param string $filePath
     * @param binary $contents
     *
     * @return bool
     */
    public function createFileOnDFS( $filePath, $contents )
    {
        $this->accumulatorStart();

        $filePath = $this->makeDFSPath( $filePath );
        $ret = eZFile::create( basename( $filePath ), dirname( $filePath ), $contents, false );

        $this->accumulatorStop();

        return $ret;
    }
Exemplo n.º 19
0
 function clearMeta()
 {
     $content = array();
     eZFile::create($this->MetaFileName, false, serialize($content), true);
 }
Exemplo n.º 20
0
 /**
  * Merges a collection of files togheter and returns array of paths to the files.
  * js /css content is returned as string if packlevel is 0 and you use a js/ css generator.
  * $fileArray can also be array of array of files, like array(  'file.js', 'file2.js', array( 'file5.js' ) )
  * The name of the cached file is a md5 hash consistant of the file paths
  * of the valid files in $file_array and the packlevel. 
  * The whole argument is used instead of file path on js/ css generators in the cache hash.
  *
  * @param array|string $fileArray Either array of file paths, or string with file path
  * @param string $subPath In witch sub path of design folder to look for files.
  * @param string $fileExtension File extension name (for use on cache file)
  * @param int $packLevel Level of packing, values: 0-3
  * @param bool $wwwInCacheHash To add www path in cahce hash or not
  * @return array List of css files
  */
 static function packFiles($fileArray, $subPath = '', $fileExtension = '.js', $packLevel = 2, $wwwInCacheHash = false)
 {
     if (!$fileArray) {
         return array();
     } else {
         if (!is_array($fileArray)) {
             $fileArray = array($fileArray);
         }
     }
     $cacheName = '';
     $lastmodified = 0;
     $httpFiles = array();
     $validFiles = array();
     $validWWWFiles = array();
     $bases = eZTemplateDesignResource::allDesignBases();
     // Only pack files if Packer is enabled and if not set DevelopmentMode is disabled
     $ezjscINI = eZINI::instance('ezjscore.ini');
     if ($ezjscINI->hasVariable('eZJSCore', 'Packer')) {
         $packerIniValue = $ezjscINI->variable('eZJSCore', 'Packer');
         if ($packerIniValue === 'disabled') {
             $packLevel = 0;
         } else {
             if (is_numeric($packerIniValue)) {
                 $packLevel = (int) $packerIniValue;
             }
         }
     } else {
         $ini = eZINI::instance();
         if ($ini->variable('TemplateSettings', 'DevelopmentMode') === 'enabled') {
             $packLevel = 0;
         }
     }
     $packerInfo = array('file_extension' => $fileExtension, 'pack_level' => $packLevel, 'sub_path' => $subPath, 'cache_dir' => self::getCacheDir(), 'www_dir' => self::getWwwDir());
     // needed for image includes to work on ezp installs with mixed access methods (virtualhost + url based setup)
     if ($wwwInCacheHash) {
         $cacheName = $packerInfo['www_dir'];
     }
     while (count($fileArray) > 0) {
         $file = array_shift($fileArray);
         // if $file is array, concat it to the file array and continue
         if ($file && is_array($file)) {
             $fileArray = array_merge($file, $fileArray);
             continue;
         } else {
             if (!$file) {
                 continue;
             } else {
                 if (strpos($file, '::') !== false) {
                     $server = self::serverCallHelper(explode('::', $file));
                     $fileTime = $server->getCacheTime($packerInfo);
                     // generate content straight away if packing is disabled
                     if ($packLevel === 0) {
                         $validWWWFiles[] = $server->call($fileArray);
                     } else {
                         if ($fileTime === -1) {
                             $validFiles[] = $server->call($fileArray);
                         } else {
                             $validFiles[] = $server;
                             $cacheName .= $file . '_';
                         }
                     }
                     $lastmodified = max($lastmodified, $fileTime);
                     continue;
                 } else {
                     if (strpos($file, 'http://') === 0 || strpos($file, 'https://') === 0) {
                         $httpFiles[] = $file;
                         continue;
                     } else {
                         if (strpos($file, 'var/') === 0) {
                             if (substr($file, 0, 2) === '//' || preg_match("#^[a-zA-Z0-9]+:#", $file)) {
                                 $file = '/';
                             } else {
                                 if (strlen($file) > 0 && $file[0] !== '/') {
                                     $file = '/' . $file;
                                 }
                             }
                             eZURI::transformURI($file, true, 'relative');
                             // get file time and continue if it return false
                             $file = str_replace('//' . $packerInfo['www_dir'], '', '//' . $file);
                             $fileTime = file_exists($file) ? filemtime($file) : false;
                             $wwwFile = $packerInfo['www_dir'] . $file;
                         } else {
                             // allow path to be outside subpath if it starts with '/'
                             if ($file[0] === '/') {
                                 $file = ltrim($file, '/');
                             } else {
                                 $file = $subPath . $file;
                             }
                             $triedFiles = array();
                             $match = eZTemplateDesignResource::fileMatch($bases, '', $file, $triedFiles);
                             if ($match === false) {
                                 eZDebug::writeWarning("Could not find: {$file}", __METHOD__);
                                 continue;
                             }
                             $file = htmlspecialchars($match['path']);
                             $fileTime = file_exists($file) ? filemtime($file) : false;
                             $wwwFile = $packerInfo['www_dir'] . $file;
                         }
                     }
                 }
             }
         }
         if ($fileTime === false) {
             eZDebug::writeWarning("Could not get modified time of file: {$file}", __METHOD__);
             continue;
         }
         // calculate last modified time and store in arrays
         $lastmodified = max($lastmodified, $fileTime);
         $validFiles[] = $file;
         $validWWWFiles[] = $wwwFile;
         // STEVO
         $cacheName .= $file . '_' . $fileTime . '_';
     }
     // if packing is disabled, return the valid paths / content we have generated
     if ($packLevel === 0) {
         return array_merge($httpFiles, $validWWWFiles);
     }
     if (!$validFiles) {
         eZDebug::writeWarning("Could not find any files: " . var_export($fileArray, true), __METHOD__);
         return array();
     }
     // generate cache file name and path
     $cacheName = md5($cacheName . $packLevel) . $fileExtension;
     $cachePath = $packerInfo['cache_dir'] . $subPath;
     if (file_exists($cachePath . $cacheName)) {
         // check last modified time and return path to cache file if valid
         if ($lastmodified <= filemtime($cachePath . $cacheName)) {
             $httpFiles[] = $packerInfo['www_dir'] . $cachePath . $cacheName;
             return $httpFiles;
         }
     }
     // Merge file content and create new cache file
     $content = '';
     foreach ($validFiles as $file) {
         // if this is a js / css generator, call to get content
         if ($file instanceof ezjscServerRouter) {
             $content .= $file->call($validFiles);
             continue;
         } else {
             if (!$file) {
                 continue;
             }
         }
         // else, get content of normal file
         $fileContent = file_get_contents($file);
         if (!trim($fileContent)) {
             $content .= "/* empty: {$file} */\r\n";
             continue;
         }
         // we need to fix relative background image paths if this is a css file
         if (strpos($fileExtension, '.css') !== false) {
             $fileContent = ezjscPacker::fixImgPaths($fileContent, $file);
         }
         $content .= "/* start: {$file} */\r\n";
         $content .= $fileContent;
         $content .= "\r\n/* end: {$file} */\r\n\r\n";
     }
     // Pack the file to save bandwidth
     if ($packLevel > 1) {
         if (strpos($fileExtension, '.css') !== false) {
             $content = ezjscPacker::optimizeCSS($content, $packLevel);
         } else {
             $content = ezjscPacker::optimizeScript($content, $packLevel);
         }
     }
     // save file and return path if sucsessfull
     if (eZFile::create($cacheName, $cachePath, $content)) {
         $httpFiles[] = $packerInfo['www_dir'] . $cachePath . $cacheName;
         return $httpFiles;
     }
     return array();
 }
Exemplo n.º 21
0
 protected function createFile($filePath, $contents, $atomic = true)
 {
     $createResult = eZFile::create(basename($filePath), dirname($filePath), $contents, $atomic);
     if ($createResult) {
         $this->fixPermissions($filePath);
     }
     return $createResult;
 }
 /**
  * Creates the file $filePath with contents $fileContents on DB + DFS
  *
  * The existing file will be removed unless $params[remove] is set to false
  *
  * @param string $filePath relative file path
  * @param string $fileContents file's content
  * @param array  $params
  *        Optional parameters for creation.
  *        Valid keys:datatype, scope, mtime, expired and remove
  *        if remove is set to true, the file will be removed before it is
  *        created
  * @return void
  **/
 protected function createFile($filePath, $fileContents = 'foobar', $params = array())
 {
     $datatype = isset($params['datatype']) ? $params['datatype'] : 'text/test';
     $scope = isset($params['scope']) ? $params['scope'] : 'test';
     $mtime = isset($params['mtime']) ? $params['mtime'] : time();
     $expired = isset($params['expired']) ? $params['expired'] : 0;
     $createLocalFile = isset($params['create_local_file']) ? $params['create_local_file'] : false;
     $remove = isset($params['remove']) ? $params['remove'] : true;
     if ($remove) {
         $this->removeFile($filePath);
     }
     $nameHash = md5($filePath);
     $size = strlen($fileContents);
     // create DB file
     $sql = "INSERT INTO " . self::$tableDefault . "      ( name,        name_trunk,  name_hash,   datatype,    scope,    size,    mtime,    expired )" . "VALUES( '{$filePath}', '{$filePath}', '{$nameHash}', '{$datatype}', '{$scope}', '{$size}', '{$mtime}', '{$expired}' )";
     $this->db->query($sql);
     // create DFS file
     $path = $this->makeDFSPath($filePath);
     eZFile::create(basename($path), dirname($path), $fileContents);
     // create local file
     if ($createLocalFile) {
         eZFile::create(basename($filePath), dirname($filePath), $fileContents);
     }
     return eZClusterFileHandler::instance($filePath);
 }
Exemplo n.º 23
0
 /**
  * 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;
 }
Exemplo n.º 24
0
 protected function createFile($path, $content)
 {
     return eZFile::create(basename($path), dirname($path), $content, false);
 }
Exemplo n.º 25
0
 function clearMeta()
 {
     $tmpFile = $this->MetaFileName . substr(md5(mt_rand()), 0, 8);
     $content = array();
     eZFile::create($tmpFile, false, serialize($content));
     eZFile::rename($tmpFile, $this->MetaFileName);
 }
Exemplo n.º 26
0
 public function generatePng($url, $density, $keys)
 {
     $data = $this->getPDF($url);
     // check if error occurred during pdf generation
     if ($data === false) {
         return false;
     }
     // save pdf, generate png, return url
     $cacheName = hash("md5", $url . '-' . $density . '-' . implode($keys, '-'));
     $cacheDir = self::getCacheDir();
     eZFile::create($cacheName . '.pdf', $cacheDir, $data);
     $pdfUrl = $cacheDir . $cacheName . '.pdf';
     $pngUrl = $cacheDir . $cacheName . '.png';
     $command = "gs -dNOPAUSE -dBATCH -sDEVICE=pngalpha -r{$density} -dEPSCrop -sOutputFile=" . eZSys::rootDir() . "/" . $pngUrl . " " . eZSys::rootDir() . "/" . $pdfUrl;
     exec($command, $output, $returnCode);
     //eZDebug::writeError($command, 'sPdf2png::exportPng');
     //eZDebug::writeError("pngUrl=".$pngUrl, 'sPdf2png::exportPng');
     //eZFileHandler::unlink($pdfUrl);
     return $this->getPngData($pngUrl);
     /*return array('url' => ,
     	 'width' => '100',
     	 'height' => '100' );*/
 }
Exemplo n.º 27
0
 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;
 }
Exemplo n.º 28
0
    $processor = new ExportProcessor($exporter, $formatter);
    $processor->export();
    // Rendering or splitting ?
    $exportDir = eZSys::varDirectory();
    $exportBaseFilename = 'comments-export';
    $exportFormat = $processor->getExportFormat();
    if (isset($options['split'])) {
        $cli->notice('Now splitting final file.');
        $splittedData = $processor->split();
        $cli->notice('Total size before splitting is ' . number_format($splittedData->totalSize / 1024 / 1024, 2) . 'M');
        foreach ($splittedData->stringArray as $i => $data) {
            $filename = "{$exportBaseFilename}.{$i}.{$exportFormat}";
            $cli->notice("Now rendering {$exportDir}/{$filename}");
            eZFile::create("{$filename}", $exportDir, $data, true);
        }
    } else {
        $cli->notice("Now rendering to {$exportDir}/{$exportBaseFilename}.{$exportFormat}");
        eZFile::create("{$exportBaseFilename}.{$exportFormat}", $exportDir, $processor->render(), true);
    }
    $memoryMax = memory_get_peak_usage();
    $memoryMax = round($memoryMax / 1024 / 1024, 2);
    // Convert in Megabytes
    $cli->notice('Peak memory usage : ' . $memoryMax . 'M');
    $script->shutdown();
} catch (Exception $e) {
    $errCode = $e->getCode();
    $errCode = $errCode != 0 ? $errCode : 1;
    // If an error has occured, script must terminate with a status other than 0
    $cli->error($e->getMessage());
    $script->shutdown($errCode);
}
 /**
  * Store file contents to disk
  *
  * @param string $contents Binary file data
  * @param string $datatype Not used in the FS handler
  * @param string $scope Not used in the FS handler
  * @param bool $storeLocally Not used in the FS handler
  *
  * @return void
  */
 function storeContents($contents, $scope = false, $datatype = false, $storeLocally = false)
 {
     $filePath = $this->filePath;
     eZDebugSetting::writeDebug('kernel-clustering', "fs::storeContents( '{$filePath}' )", __METHOD__);
     eZDebug::accumulatorStart('dbfile', false, 'dbfile');
     eZFile::create(basename($filePath), dirname($filePath), $contents, true);
     $perm = eZINI::instance()->variable('FileSettings', 'StorageFilePermissions');
     chmod($filePath, octdec($perm));
     eZDebug::accumulatorStop('dbfile');
 }
Exemplo n.º 30
0
 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;
     }
     $mtime = false;
     $result = null;
     if ($binaryData === null && $fileContent === null) {
         eZDebug::writeError("Write callback need to set the 'content' or 'binarydata' entry");
         $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, we just return the result
     if (!$storeCache) {
         $this->abortCacheGeneration();
         return $result;
     }
     // stale cache handling: we just return the result, no lock has been set
     if ($this->useStaleCache) {
         // 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}");
             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;
     }
     eZDebugSetting::writeDebug('kernel-clustering', "Writing new file content to database for {$this->filePath}");
     $this->storeContents($binaryData, $scope, $datatype, $storeLocally = false);
     // we end the cache generation process, so that the .generating file
     // is renamed to its final name
     $this->endCacheGeneration(strlen($binaryData), $scope, $datatype);
     // the generated file is written to disk
     if (self::LOCAL_CACHE) {
         // Store content also locally
         eZDebugSetting::writeDebug('kernel-clustering', "Writing new file content to local file {$this->filePath}");
         eZFile::create(basename($this->filePath), dirname($this->filePath), $binaryData, true);
     }
     return $result;
 }