예제 #1
0
 /**
  * Reimplement parent's method to make use of a tracing dfs backend class
  */
 public function _connect()
 {
     $siteINI = eZINI::instance('site.ini');
     // DB Connection setup
     // This part is not actually required since _connect will only be called
     // once, but it is useful to run the unit tests. So be it.
     // @todo refactor this using eZINI::setVariable in unit tests
     if (parent::$dbparams === null) {
         $fileINI = eZINI::instance('file.ini');
         parent::$dbparams = array();
         parent::$dbparams['host'] = $fileINI->variable('eZDFSClusteringSettings', 'DBHost');
         $dbPort = $fileINI->variable('eZDFSClusteringSettings', 'DBPort');
         parent::$dbparams['port'] = $dbPort !== '' ? $dbPort : null;
         parent::$dbparams['socket'] = $fileINI->variable('eZDFSClusteringSettings', 'DBSocket');
         parent::$dbparams['dbname'] = $fileINI->variable('eZDFSClusteringSettings', 'DBName');
         parent::$dbparams['user'] = $fileINI->variable('eZDFSClusteringSettings', 'DBUser');
         parent::$dbparams['pass'] = $fileINI->variable('eZDFSClusteringSettings', 'DBPassword');
         parent::$dbparams['max_connect_tries'] = $fileINI->variable('eZDFSClusteringSettings', 'DBConnectRetries');
         parent::$dbparams['max_execute_tries'] = $fileINI->variable('eZDFSClusteringSettings', 'DBExecuteRetries');
         parent::$dbparams['sql_output'] = $siteINI->variable("DatabaseSettings", "SQLOutput") == "enabled";
         parent::$dbparams['cache_generation_timeout'] = $siteINI->variable("ContentSettings", "CacheGenerationTimeout");
     }
     $serverString = parent::$dbparams['host'];
     if (parent::$dbparams['socket']) {
         $serverString .= ':' . parent::$dbparams['socket'];
     } elseif (parent::$dbparams['port']) {
         $serverString .= ':' . parent::$dbparams['port'];
     }
     $maxTries = parent::$dbparams['max_connect_tries'];
     $tries = 0;
     eZPerfLogger::accumulatorStart('mysql_cluster_connect', 'MySQL Cluster', 'Cluster database connection');
     while ($tries < $maxTries) {
         if ($this->db = mysqli_connect(parent::$dbparams['host'], parent::$dbparams['user'], parent::$dbparams['pass'], parent::$dbparams['dbname'], parent::$dbparams['port'])) {
             break;
         }
         ++$tries;
     }
     eZPerfLogger::accumulatorStop('mysql_cluster_connect');
     if (!$this->db) {
         throw new eZClusterHandlerDBNoConnectionException($serverString, parent::$dbparams['user'], parent::$dbparams['pass']);
     }
     /*if ( !mysql_select_db( parent::$dbparams['dbname'], $this->db ) )
       throw new eZClusterHandlerDBNoDatabaseException( parent::$dbparams['dbname'] );*/
     // DFS setup
     if ($this->dfsbackend === null) {
         $this->dfsbackend = new eZDFSFileHandlerTracing46DFSBackend();
     }
     $charset = trim($siteINI->variable('DatabaseSettings', 'Charset'));
     if ($charset === '') {
         $charset = eZTextCodec::internalCharset();
     }
     if ($charset) {
         if (!mysqli_set_charset($this->db, eZMySQLCharset::mapTo($charset))) {
             $this->_fail("Failed to set Database charset to {$charset}.");
         }
     }
 }
 function transformByGroup($text, $group, $charset = false, $useCache = true)
 {
     if ($text === '') {
         return $text;
     }
     $charsetName = $charset === false ? eZTextCodec::internalCharset() : eZCharsetInfo::realCharsetCode($charset);
     if ($useCache) {
         // CRC32 is used for speed, MD5 would be more unique but is slower
         $keyText = 'Group:' . $group;
         $key = eZSys::ezcrc32($keyText . '-' . $charset);
         $filepath = $this->cacheFilePath('g-' . $group . '-', '-' . $charsetName, $key);
         // Try to execute code in the cache file, if it succeeds
         // \a $text will/ transformated
         $retText = $this->executeCacheFile($text, $filepath);
         if ($retText !== false) {
             return $retText;
         }
     }
     $commands = $this->groupCommands($group);
     if ($commands === false) {
         return false;
     }
     $mapper = new eZCodeMapper();
     $mapper->loadTransformationFiles($charsetName, $group);
     $rules = array();
     foreach ($commands as $command) {
         $rules = array_merge($rules, $mapper->decodeCommand($command['command'], $command['parameters']));
     }
     // First generate a unicode based mapping table from the rules
     $unicodeTable = $mapper->generateMappingCode($rules);
     unset($unicodeTable[0]);
     // Then transform that to a table that works with the current charset
     // Any character not available in the current charset will be removed
     $charsetTable = $mapper->generateCharsetMappingTable($unicodeTable, $charset);
     $transformationData = array('table' => $charsetTable);
     unset($unicodeTable);
     if ($useCache) {
         $extraCode = '';
         foreach ($commands as $command) {
             $code = $mapper->generateCommandCode($command, $charsetName);
             if ($code !== false) {
                 $extraCode .= $code . "\n";
             }
         }
         $this->storeCacheFile($filepath, $transformationData, $extraCode, 'Group:' . $group, $charsetName);
     }
     // Execute transformations
     $text = strtr($text, $transformationData['table']);
     // Execute custom code
     foreach ($commands as $command) {
         $mapper->executeCommandCode($text, $command, $charsetName);
     }
     return $text;
 }
예제 #3
0
파일: mysqli.php 프로젝트: legende91/ez
 function _connect()
 {
     $siteINI = eZINI::instance('site.ini');
     if (!isset($GLOBALS['eZDBFileHandlerMysqlBackend_dbparams'])) {
         $fileINI = eZINI::instance('file.ini');
         $params['host'] = $fileINI->variable('ClusteringSettings', 'DBHost');
         $params['port'] = $fileINI->variable('ClusteringSettings', 'DBPort');
         $params['socket'] = $fileINI->variable('ClusteringSettings', 'DBSocket');
         $params['dbname'] = $fileINI->variable('ClusteringSettings', 'DBName');
         $params['user'] = $fileINI->variable('ClusteringSettings', 'DBUser');
         $params['pass'] = $fileINI->variable('ClusteringSettings', 'DBPassword');
         $params['chunk_size'] = $fileINI->variable('ClusteringSettings', 'DBChunkSize');
         $params['max_connect_tries'] = $fileINI->variable('ClusteringSettings', 'DBConnectRetries');
         $params['max_execute_tries'] = $fileINI->variable('ClusteringSettings', 'DBExecuteRetries');
         $params['sql_output'] = $siteINI->variable("DatabaseSettings", "SQLOutput") == "enabled";
         $params['cache_generation_timeout'] = $siteINI->variable("ContentSettings", "CacheGenerationTimeout");
         $GLOBALS['eZDBFileHandlerMysqlBackend_dbparams'] = $params;
     } else {
         $params = $GLOBALS['eZDBFileHandlerMysqlBackend_dbparams'];
     }
     $this->dbparams = $params;
     $maxTries = $params['max_connect_tries'];
     $tries = 0;
     eZDebug::accumulatorStart('mysql_cluster_connect', 'mysql_cluster_total', 'Cluster_database_connection');
     while ($tries < $maxTries) {
         /// @todo what if port is null, '' ??? to be tested
         if ($this->db = mysqli_connect($params['host'], $params['user'], $params['pass'], $params['dbname'], $params['port'])) {
             break;
         }
         ++$tries;
     }
     eZDebug::accumulatorStop('mysql_cluster_connect');
     if (!$this->db) {
         return $this->_die("Unable to connect to storage server");
     }
     $charset = trim($siteINI->variable('DatabaseSettings', 'Charset'));
     if ($charset === '') {
         $charset = eZTextCodec::internalCharset();
     }
     if ($charset) {
         if (!mysqli_set_charset($this->db, eZMySQLCharset::mapTo($charset))) {
             return $this->_die("Failed to set Database charset to {$charset}.");
         }
     }
 }
예제 #4
0
 public static function instance()
 {
     if ( is_null(self::$_instance) )
     {
         $ini = eZINI::instance();
         if ( !$ini->hasSection( 'MMDatabaseSettings') )
             return eZDB::instance();
         
         list( $server, $port, $user, $pwd, $db ) =
             $ini->variableMulti( 'MMDatabaseSettings', array( 'Server', 'Port', 'User', 'Password', 'Database' ) );
         list( $charset, $retries, $usePersistentConnection ) =
             $ini->variableMulti( 'DatabaseSettings', array( 'Charset', 'ConnectRetries', 'UserPersistentConnection' ) );
         
         $isInternalCharset = false;
         if ( trim( $charset ) == '' )
         {
             $charset = eZTextCodec::internalCharset();
             $isInternalCharset = true;
         }
         $builtinEncoding = ( $ini->variable( 'DatabaseSettings', 'UseBuiltinEncoding' ) == 'true' );
         
         $params = array('server' => $server,
                         'port' => $port,
                         'user' => $user,
                         'password' => $pwd,
                         'database' => $db,
                         'use_slave_server' => false,
                         'slave_server' => null,
                         'slave_port' => null,
                         'slave_user' => null,
                         'slave_password' => null,
                         'slave_database' => null,
                         'charset' => $charset,
                         'is_internal_charset' => $isInternalCharset,
                         'socket' => false,
                         'builtin_encoding' => $builtinEncoding,
                         'connect_retries' => $retries,
                         'use_persistent_connection' => $usePersistentConnection,
                         'show_errors' => true );
         self::$_instance = new eZMySQLiDB( $params );
     }
     
     return self::$_instance;
 }
예제 #5
0
 function __construct()
 {
     $this->ReceiverElements = array();
     $this->MobileElements = array();
     $this->From = false;
     $this->CcElements = array();
     $this->BccElements = array();
     $this->ReplyTo = false;
     $this->Subject = false;
     $this->BodyText = false;
     $this->ExtraHeaders = array();
     $this->TextCodec = false;
     $this->MessageID = false;
     $this->Date = false;
     // Sets some default values
     $version = eZPublishSDK::version();
     $this->MIMEVersion = '1.0';
     $this->ContentType = array('type' => 'text/plain', 'charset' => eZTextCodec::internalCharset(), 'transfer-encoding' => '8bit', 'disposition' => 'inline', 'boundary' => false);
     $this->UserAgent = "eZ publish, Version {$version}";
     $ini = eZINI::instance();
     // HACK! Ignore system content type
     //if ( $ini->hasVariable( 'MailSettings', 'ContentType' ) )
     //    $this->setContentType( $ini->variable( 'MailSettings', 'ContentType' ) );
     if (!defined('EZ_MAIL_LINE_SEPARATOR')) {
         $ini = eZINI::instance('site.ini');
         $ending = $ini->variable('MailSettings', 'HeaderLineEnding');
         if ($ending == 'auto') {
             $sys = eZSys::instance();
             // For windows we use \r\n which is the endline defined in RFC 2045
             if ($sys->osType() == 'win32') {
                 $separator = "\r\n";
             } else {
                 $separator = "\n";
             }
         } else {
             $separator = urldecode($ending);
         }
         define('EZ_MAIL_LINE_SEPARATOR', $separator);
     }
 }
예제 #6
0
파일: mysql.php 프로젝트: rmiguel/ezpublish
 function _connect($newLink = false)
 {
     $siteINI = eZINI::instance('site.ini');
     if (!isset($GLOBALS['eZDBFileHandlerMysqlBackend_dbparams'])) {
         $fileINI = eZINI::instance('file.ini');
         $params['host'] = $fileINI->variable('ClusteringSettings', 'DBHost');
         $params['port'] = $fileINI->variable('ClusteringSettings', 'DBPort');
         $params['socket'] = $fileINI->variable('ClusteringSettings', 'DBSocket');
         $params['dbname'] = $fileINI->variable('ClusteringSettings', 'DBName');
         $params['user'] = $fileINI->variable('ClusteringSettings', 'DBUser');
         $params['pass'] = $fileINI->variable('ClusteringSettings', 'DBPassword');
         $params['chunk_size'] = $fileINI->variable('ClusteringSettings', 'DBChunkSize');
         $params['max_connect_tries'] = $fileINI->variable('ClusteringSettings', 'DBConnectRetries');
         $params['max_execute_tries'] = $fileINI->variable('ClusteringSettings', 'DBExecuteRetries');
         $params['sql_output'] = $siteINI->variable("DatabaseSettings", "SQLOutput") == "enabled";
         $params['cache_generation_timeout'] = $siteINI->variable("ContentSettings", "CacheGenerationTimeout");
         $GLOBALS['eZDBFileHandlerMysqlBackend_dbparams'] = $params;
     } else {
         $params = $GLOBALS['eZDBFileHandlerMysqlBackend_dbparams'];
     }
     $this->dbparams = $params;
     $serverString = $params['host'];
     if ($params['socket']) {
         $serverString .= ':' . $params['socket'];
     } elseif ($params['port']) {
         $serverString .= ':' . $params['port'];
     }
     $maxTries = $params['max_connect_tries'];
     $tries = 0;
     while ($tries < $maxTries) {
         if ($this->db = mysql_connect($serverString, $params['user'], $params['pass'], $newLink)) {
             break;
         }
         ++$tries;
     }
     if (!$this->db) {
         return $this->_die("Unable to connect to storage server");
     }
     if (!mysql_select_db($params['dbname'], $this->db)) {
         return $this->_die("Unable to select database {$params['dbname']}");
     }
     $charset = trim($siteINI->variable('DatabaseSettings', 'Charset'));
     if ($charset === '') {
         $charset = eZTextCodec::internalCharset();
     }
     if ($charset) {
         if (!mysql_query("SET NAMES '" . eZMySQLCharset::mapTo($charset) . "'", $this->db)) {
             return $this->_die("Failed to set Database charset to {$charset}.");
         }
     }
 }
예제 #7
0
            if ( $customMatch['match_file'] == $template )
            {
                $originalTemplate = $overrideSetting['template'];
                break 2;
            }
        }
    }
}

/* Check if we need to do characterset conversions for editting and saving
 * templates. */
$templateConfig = eZINI::instance( 'template.ini' );
$i18nConfig = eZINI::instance( 'i18n.ini' );

/* First we check the HTML Output Charset */
$outputCharset = eZTextCodec::internalCharset();

if ( $module->isCurrentAction( 'Save' ) )
{
    if ( $http->hasPostVariable( 'TemplateContent' ) )
    {
        $templateContent = $http->postVariable( 'TemplateContent' );

        if ( $templateConfig->variable( 'CharsetSettings', 'AutoConvertOnSave') == 'enabled' )
        {
            $outputCharset = eZCharsetInfo::realCharsetCode( $outputCharset );
            if ( preg_match( '|{\*\?template.*charset=([a-zA-Z0-9-]*).*\?\*}|', $templateContent, $matches ) )
            {
                $templateContent = preg_replace( '|({\*\?template.*charset=)[a-zA-Z0-9-]*(.*\?\*})|',
                                                 '\\1'. $outputCharset. '\\2',
                                                 $templateContent );
예제 #8
0
파일: feed.php 프로젝트: nfrp/ezpublish
eZURI::setTransformURIMode('full');
if ($cacheTime <= 0) {
    $xmlDoc = $RSSExport->attribute('rss-xml-content');
    $rssContent = $xmlDoc;
} else {
    $cacheDir = eZSys::cacheDirectory();
    $currentSiteAccessName = $GLOBALS['eZCurrentAccess']['name'];
    $cacheFilePath = $cacheDir . '/rss/' . md5($currentSiteAccessName . $feedName) . '.xml';
    if (!is_dir(dirname($cacheFilePath))) {
        eZDir::mkdir(dirname($cacheFilePath), false, true);
    }
    $cacheFile = eZClusterFileHandler::instance($cacheFilePath);
    if (!$cacheFile->exists() or time() - $cacheFile->mtime() > $cacheTime) {
        $xmlDoc = $RSSExport->attribute('rss-xml-content');
        // Get current charset
        $charset = eZTextCodec::internalCharset();
        $rssContent = trim($xmlDoc);
        $cacheFile->storeContents($rssContent, 'rsscache', 'xml');
    } else {
        $lastModified = gmdate('D, d M Y H:i:s', $cacheFile->mtime()) . ' GMT';
        if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
            $ifModifiedSince = $_SERVER['HTTP_IF_MODIFIED_SINCE'];
            // Internet Explorer specific
            $pos = strpos($ifModifiedSince, ';');
            if ($pos !== false) {
                $ifModifiedSince = substr($ifModifiedSince, 0, $pos);
            }
            if (strcmp($lastModified, $ifModifiedSince) == 0) {
                header('HTTP/1.1 304 Not Modified');
                header('Last-Modified: ' . $lastModified);
                header('X-Powered-By: ' . eZPublishSDK::EDITION);
예제 #9
0
파일: ezdb.php 프로젝트: nfrp/ezpublish
 /**
  * Returns a shared instance of the eZDBInterface class aka database object.
  * If you want to change the current database values you should use $forceNewInstance.
  *
  * @param string|false $databaseImplementation
  * @param array|false $databaseParameters If array, then key 'use_defaults' (bool) is used.
  * @param bool $forceNewInstance
  * @return eZDBInterface
  */
 static function instance($databaseImplementation = false, $databaseParameters = false, $forceNewInstance = false)
 {
     $impl =& $GLOBALS['eZDBGlobalInstance'];
     $fetchInstance = false;
     if (!$impl instanceof eZDBInterface) {
         $fetchInstance = true;
     }
     if ($forceNewInstance) {
         unset($impl);
         $impl = false;
         $fetchInstance = true;
     }
     $useDefaults = true;
     if (is_array($databaseParameters) and isset($databaseParameters['use_defaults'])) {
         $useDefaults = $databaseParameters['use_defaults'];
     }
     if ($fetchInstance) {
         $ini = eZINI::instance();
         if ($databaseImplementation === false and $useDefaults) {
             $databaseImplementation = $ini->variable('DatabaseSettings', 'DatabaseImplementation');
         }
         $server = $user = $pwd = $db = $usePersistentConnection = $port = false;
         if ($useDefaults) {
             list($server, $port, $user, $pwd, $db, $usePersistentConnection) = $ini->variableMulti('DatabaseSettings', array('Server', 'Port', 'User', 'Password', 'Database', 'UsePersistentConnection'));
         }
         $socketPath = false;
         if ($useDefaults) {
             $socket = $ini->variable('DatabaseSettings', 'Socket');
             if (trim($socket != "") and $socket != "disabled") {
                 $socketPath = $socket;
             }
         }
         // Check slave servers
         $slaveServer = null;
         $slaveServerPort = null;
         $slaveServerUser = null;
         $slaveServerPassword = null;
         $slaveServerDatabase = null;
         $useSlave = $ini->variable('DatabaseSettings', 'UseSlaveServer');
         if ($useSlave == "enabled") {
             $slaveServers = $ini->variable('DatabaseSettings', 'SlaveServerArray');
             $slaveServerPorts = $ini->variable('DatabaseSettings', 'SlaveServerPort');
             $slaveServerUsers = $ini->variable('DatabaseSettings', 'SlaverServerUser');
             $slaveServerPasswords = $ini->variable('DatabaseSettings', 'SlaverServerPassword');
             $slaveServerDatabases = $ini->variable('DatabaseSettings', 'SlaverServerDatabase');
             $numberServers = count($slaveServers);
             if ($numberServers > 1) {
                 $index = mt_rand(1, $numberServers) - 1;
             } else {
                 $index = 0;
             }
             $slaveServer = $slaveServers[$index];
             $slaveServerPort = $slaveServerPorts[$index];
             $slaveServerUser = $slaveServerUsers[$index];
             $slaveServerPassword = $slaveServerPasswords[$index];
             $slaveServerDatabase = $slaveServerDatabases[$index];
         }
         list($charset, $retries) = $ini->variableMulti('DatabaseSettings', array('Charset', 'ConnectRetries'));
         $isInternalCharset = false;
         if (trim($charset) == '') {
             $charset = eZTextCodec::internalCharset();
             $isInternalCharset = true;
         }
         $builtinEncoding = $ini->variable('DatabaseSettings', 'UseBuiltinEncoding') == 'true';
         $impl = null;
         $useSlaveServer = false;
         if ($useSlave == "enabled") {
             $useSlaveServer = true;
         }
         $defaultDatabaseParameters = array('server' => $server, 'port' => $port, 'user' => $user, 'password' => $pwd, 'database' => $db, 'use_slave_server' => $useSlaveServer, 'slave_server' => $slaveServer, 'slave_port' => $slaveServerPort, 'slave_user' => $slaveServerUser, 'slave_password' => $slaveServerPassword, 'slave_database' => $slaveServerDatabase, 'charset' => $charset, 'is_internal_charset' => $isInternalCharset, 'socket' => $socketPath, 'builtin_encoding' => $builtinEncoding, 'connect_retries' => $retries, 'use_persistent_connection' => $usePersistentConnection, 'show_errors' => true);
         /* This looks funny, but is needed to fix a crash in PHP */
         $b = $databaseParameters;
         $databaseParameters = $defaultDatabaseParameters;
         if (isset($b['server'])) {
             $databaseParameters['server'] = $b['server'];
         }
         if (isset($b['port'])) {
             $databaseParameters['port'] = $b['port'];
         }
         if (isset($b['user'])) {
             $databaseParameters['user'] = $b['user'];
         }
         if (isset($b['password'])) {
             $databaseParameters['password'] = $b['password'];
         }
         if (isset($b['database'])) {
             $databaseParameters['database'] = $b['database'];
         }
         if (isset($b['use_slave_server'])) {
             $databaseParameters['use_slave_server'] = $b['use_slave_server'];
         }
         if (isset($b['slave_server'])) {
             $databaseParameters['slave_server'] = $b['slave_server'];
         }
         if (isset($b['slave_port'])) {
             $databaseParameters['slave_port'] = $b['slave_port'];
         }
         if (isset($b['slave_user'])) {
             $databaseParameters['slave_user'] = $b['slave_user'];
         }
         if (isset($b['slave_password'])) {
             $databaseParameters['slave_password'] = $b['slave_password'];
         }
         if (isset($b['slave_database'])) {
             $databaseParameters['slave_database'] = $b['slave_database'];
         }
         if (isset($b['charset'])) {
             $databaseParameters['charset'] = $b['charset'];
             $databaseParameters['is_internal_charset'] = false;
         }
         if (isset($b['socket'])) {
             $databaseParameters['socket'] = $b['socket'];
         }
         if (isset($b['builtin_encoding'])) {
             $databaseParameters['builtin_encoding'] = $b['builtin_encoding'];
         }
         if (isset($b['connect_retries'])) {
             $databaseParameters['connect_retries'] = $b['connect_retries'];
         }
         if (isset($b['use_persistent_connection'])) {
             $databaseParameters['use_persistent_connection'] = $b['use_persistent_connection'];
         }
         if (isset($b['show_errors'])) {
             $databaseParameters['show_errors'] = $b['show_errors'];
         }
         $optionArray = array('iniFile' => 'site.ini', 'iniSection' => 'DatabaseSettings', 'iniVariable' => 'ImplementationAlias', 'handlerIndex' => $databaseImplementation, 'handlerParams' => array($databaseParameters));
         $options = new ezpExtensionOptions($optionArray);
         $impl = eZExtension::getHandlerClass($options);
         if (!$impl) {
             $impl = new eZNullDB($databaseParameters);
             $impl->ErrorMessage = "No database handler was found for '{$databaseImplementation}'";
             $impl->ErrorNumber = -1;
             if ($databaseParameters['show_errors']) {
                 eZDebug::writeError('Database implementation not supported: ' . $databaseImplementation, __METHOD__);
             }
         }
         $impl->setErrorHandling(self::$errorHandling);
     }
     return $impl;
 }
예제 #10
0
 protected function cacheFileName($placement = false)
 {
     $cacheFileName = $this->FileName . '-' . $this->RootDir . '-' . $this->DirectAccess;
     if (!$this->DirectAccess) {
         $cacheFileName .= '-' . serialize($this->overrideDirs());
     }
     if ($this->UseTextCodec) {
         $cacheFileName .= '-' . eZTextCodec::internalCharset();
     }
     if ($placement) {
         $cacheFileName .= '-placement:' . $placement;
     }
     $filePreFix = explode('.', $this->FileName);
     return $filePreFix[0] . '-' . md5($cacheFileName) . '.php';
 }
예제 #11
0
 static function compilationFilename($key, $resourceData)
 {
     $internalCharset = eZTextCodec::internalCharset();
     $templateFilepath = $resourceData['template-filename'];
     $extraName = '';
     if (preg_match("#^.+/(.*)\\.tpl\$#", $templateFilepath, $matches)) {
         $extraName = $matches[1] . '-';
     } else {
         if (preg_match("#^(.*)\\.tpl\$#", $templateFilepath, $matches)) {
             $extraName = $matches[1] . '-';
         }
     }
     $accessText = false;
     if (isset($GLOBALS['eZCurrentAccess']['name'])) {
         $accessText = '-' . $GLOBALS['eZCurrentAccess']['name'];
     }
     $locale = eZLocale::instance();
     $language = $locale->localeFullCode();
     $http = eZHTTPTool::instance();
     $useFullUrlText = $http->UseFullUrl ? 'full' : 'relative';
     $pageLayoutVariable = "";
     if (isset($GLOBALS['eZCustomPageLayout'])) {
         $pageLayoutVariable = $GLOBALS['eZCustomPageLayout'];
     }
     $ini = eZINI::instance();
     $shareTemplates = $ini->hasVariable('TemplateSettings', 'ShareCompiledTemplates') ? $ini->variable('TemplateSettings', 'ShareCompiledTemplates') == 'enabled' : false;
     if ($shareTemplates) {
         $cacheFileKey = $key . '-' . $language;
     } else {
         $cacheFileKey = $key . '-' . $internalCharset . '-' . $language . '-' . $useFullUrlText . $accessText . "-" . $pageLayoutVariable . '-' . eZSys::indexFile();
     }
     $cacheFileName = $extraName . md5($cacheFileKey) . '.php';
     return $cacheFileName;
 }
예제 #12
0
 static function sendNewsletterMail($newsletter, $sendPreview = false, $previewFormat = false, $receiverLimit = null)
 {
     $sendMailSettings = eZINI::instance('ezsendmailsettings.ini');
     $replaceMsgIDHost = $sendMailSettings->variable('SendNewsletter', 'ReplaceMessageIDHost');
     $newSendHost = $sendMailSettings->variable('SendNewsletter', 'Host');
     $hostSettings['replace'] = $replaceMsgIDHost;
     $hostSettings['host'] = $newSendHost;
     $mail = new eZNewsletterMail();
     $sys = eZSys::instance();
     $newsletterMailData = array();
     // Check that the newsletter type exists, if not, process next newsletter
     if (!$newsletter->attribute('newsletter_type')) {
         return;
     }
     $newsletterMailData[eZNewsletter::OutputFormatText] = $newsletter->generateNewsletter(eZNewsletter::OutputFormatText, $sendPreview);
     $newsletterMailData[eZNewsletter::OutputFormatHTML] = $newsletter->generateNewsletter(eZNewsletter::OutputFormatHTML, $sendPreview);
     $newsletterMailData[eZNewsletter::OutputFormatExternalHTML] = $newsletter->generateNewsletter(eZNewsletter::OutputFormatExternalHTML, $sendPreview);
     $newsletterMailData[eZNewsletter::OutputFormatSMS] = $newsletter->generateNewsletter(eZNewsletter::OutputFormatSMS, $sendPreview);
     $newsletterOutputFormatList = $newsletter->attribute('output_format_list');
     $noMimeMessage = "This message is in MIME format. Since your mail reader does not understand\nthis format, some or all of this message may not be legible.";
     $lineBreak = "\r\n";
     $partCounter = 0;
     $boundary = date("YmdGHjs") . ':' . getmypid() . ':' . $partCounter++;
     $charset = eZTextCodec::internalCharset();
     $contentTypeHtmlPart = "Content-Type: text/html; charset={$charset}";
     foreach (array(eZNewsletter::OutputFormatHTML, eZNewsletter::OutputFormatExternalHTML) as $key) {
         $htmlOutput =& $newsletterMailData[$key];
         if ($htmlOutput['imageNameMap']) {
             $data = $noMimeMessage . $lineBreak;
             $data .= $lineBreak . '--' . $boundary . $lineBreak;
             $data .= $contentTypeHtmlPart . $lineBreak;
             $data .= "Content-Transfer-Encoding: 8bit" . $lineBreak . $lineBreak;
             $data .= $htmlOutput['body'] . $lineBreak;
             foreach ($htmlOutput['imageNameMap'] as $id => $filename) {
                 $filename = trim($filename);
                 if (is_readable($filename)) {
                     $mime = eZMimeType::findByURL($filename);
                     $encodedFileContent = chunk_split(base64_encode(file_get_contents($filename)), 76, $lineBreak);
                     $data .= $lineBreak . '--' . $boundary . $lineBreak;
                     $data .= "Content-Type: " . $mime['name'] . ';' . $lineBreak . ' name="' . basename($filename) . '"' . $lineBreak;
                     $data .= "Content-ID: <" . $id . ">" . $lineBreak;
                     $data .= "Content-Transfer-Encoding: base64" . $lineBreak;
                     $original_filename = basename($filename);
                     if ($htmlOutput['imageNameMapName'][$id]) {
                         $original_filename = $htmlOutput['imageNameMapName'][$id];
                     }
                     $data .= 'Content-Disposition: INLINE;' . $lineBreak . ' filename="' . $original_filename . '"' . $lineBreak . $lineBreak;
                     $data .= $encodedFileContent;
                 }
             }
             $data .= $lineBreak . '--' . $boundary . '--';
             $htmlOutput['body'] = $data;
         } else {
             $data = $noMimeMessage . $lineBreak;
             $data .= $lineBreak . '--' . $boundary . $lineBreak;
             $data .= $contentTypeHtmlPart . $lineBreak;
             $data .= "Content-Transfer-Encoding: 8bit" . $lineBreak . $lineBreak;
             $data .= $htmlOutput['body'] . $lineBreak;
             $data .= $lineBreak . '--' . $boundary . '--';
             $htmlOutput['body'] = $data;
         }
     }
     // 4. Go through revceivers, and send emails.
     if (!$sendPreview) {
         $mail->setSender($newsletterMailData[eZNewsletter::OutputFormatText]['emailSender'], $newsletterMailData[eZNewsletter::OutputFormatText]['emailSenderName']);
         $idcounter = 0;
         $sendCount = 0;
         $skipCount = 0;
         // HACK!
         $receiverList = eZSendNewsletterItem::fetchByNewsletterID($newsletter->attribute('id'), 0, $receiverLimit);
         foreach ($receiverList as $receiver) {
             $msgid = eZNewsletter::generateMessageId($newsletterMailData[eZNewsletter::OutputFormatText]['emailSender'], $receiver->attribute('id'), $idcounter++, $hostSettings);
             $mail->setMessageID($msgid);
             $userData = $receiver->attribute('user_data');
             if (!$userData) {
                 //When no userdata is found, it is usually the result of a deleted subscription,
                 //we mark the mail as being sent, without sending it.
                 $receiver->setAttribute('send_status', eZSendNewsletterItem::SendStatusSent);
                 $receiver->setAttribute('send_ts', time());
                 $receiver->sync();
                 continue;
             }
             // #TODO# IDs expected
             $userOutputFormatList = explode(',', $userData['output_format']);
             // #TODO#
             #echo " ### userOutputFormatList\n";  ok
             #var_dump( $userOutputFormatList );
             #echo " ### newsletterOutputFormatList\n"; ok
             #var_dump( $newsletterOutputFormatList );
             $outputFormat = false;
             //special case for SMS sending
             if (in_array(eZNewsletter::OutputFormatSMS, $userOutputFormatList) && in_array(eZNewsletter::OutputFormatSMS, $newsletterOutputFormatList)) {
                 $mail->setContentType("sms", false, false, false, $boundary);
                 $outputFormat = eZNewsletter::OutputFormatSMS;
                 //$mail->setSubject( $userMailData['subject'] );                                        ### $userMailData is undefined
                 # echo " ### userMailData\n";
                 # var_dump( $userMailData );
                 # $mail->setSubject( $userMailData['subject'] );
                 # $mail->setReceiver( $userData['email'] );
                 # $mail->setMobile( $userData['mobile'] );
                 //$mail->setBody( $userMailData['body'] );                                              ### $userMailData is undefined
                 # $mail->setBody( $userMailData['body'] );
                 # $mail->setDateTimestamp( $newsletter->attribute( 'send_date') );
                 $mailResult = eZNewsletterMailTransport::send($mail, false);
             }
             //send regular emails
             if (in_array(eZNewsletter::OutputFormatHTML, $userOutputFormatList) && in_array(eZNewsletter::OutputFormatHTML, $newsletterOutputFormatList)) {
                 $mail->setContentType("multipart/related", false, false, false, $boundary);
                 $outputFormat = eZNewsletter::OutputFormatHTML;
             }
             if (in_array(eZNewsletter::OutputFormatExternalHTML, $userOutputFormatList) && in_array(eZNewsletter::OutputFormatExternalHTML, $newsletterOutputFormatList)) {
                 $mail->setContentType("multipart/related", false, false, false, $boundary);
                 $outputFormat = eZNewsletter::OutputFormatExternalHTML;
             }
             // ...
             if ($outputFormat === false) {
                 $outputIntersect = array_intersect($userOutputFormatList, $newsletterOutputFormatList);
                 if (count($outputIntersect) > 0) {
                     $outputFormat = $outputIntersect[0];
                 }
             }
             if ($outputFormat !== false) {
                 //personalize if set in type
                 $newsletter_type = eZNewsletterType::fetch($newsletter->attribute('newslettertype_id'));
                 if ($newsletter_type->attribute('personalise') === '1') {
                     $userMailData = eZNewsletter::personalize($newsletterMailData[$outputFormat], $userData, true);
                 } else {
                     $userMailData = eZNewsletter::personalize($newsletterMailData[$outputFormat], $userData, false);
                 }
                 $mail->setSubject($userMailData['subject']);
                 $mail->setReceiver($userData['email']);
                 $mail->setMobile($userData['mobile']);
                 $mail->setBody($userMailData['body']);
                 $mail->setDateTimestamp($newsletter->attribute('send_date'));
                 //if only SMS was selected, don't send email
                 if (!(in_array(eZNewsletter::OutputFormatSMS, $userOutputFormatList) && count($userOutputFormatList) == 1)) {
                     $mailResult = eZNewsletterMailTransport::send($mail, false);
                 }
                 $sendCount++;
             } else {
                 // User doesnt want any format we defined - skipped
                 $skipCount++;
             }
             $receiver->setAttribute('send_status', eZSendNewsletterItem::SendStatusSent);
             $receiver->setAttribute('send_ts', time());
             $receiver->sync();
         }
         //send SMS messages
         $instance = eZSMS::instance();
         if ($instance->countNumbers() > 0) {
             echo "Preparing to send " . $instance->countNumbers() . " SMS messages..." . "\n";
             $instance->setContent($newsletterMailData[eZNewsletter::OutputFormatSMS]['body']);
             foreach ($instance->getNumbers() as $number) {
                 echo "Recipient is: " . $number . "\n";
             }
             $reply = $instance->sendMessages();
             if ($reply != "") {
                 echo "SMS Reply:" . "\n";
                 echo $reply;
             }
         }
         //}
         return array('sendCount' => $sendCount, 'skipCount' => $skipCount);
     } else {
         //send preview
         $msgid = eZNewsletter::generateMessageId($newsletterMailData[eZNewsletter::OutputFormatText]['emailSender'], 0, 0, $hostSettings);
         $mail->setMessageID($msgid);
         $userOutputFormatList = $previewFormat;
         $outputFormat = false;
         //special case for SMS sending
         if (in_array(eZNewsletter::OutputFormatSMS, $userOutputFormatList)) {
             $mail->setContentType("sms", false, false, false, $boundary);
             $outputFormat = eZNewsletter::OutputFormatSMS;
             $newsletterMail = $newsletterMailData[eZNewsletter::OutputFormatSMS];
             $mail->setSender($newsletterMail['emailSender'], $newsletterMail['emailSenderName']);
             $mail->setReceiver($newsletter->attribute('preview_email'));
             $mail->setMobile($newsletter->attribute('preview_mobile'));
             $mail->setBody($newsletterMail['body']);
             $mail->setSubject($newsletterMail['subject']);
             $mail->setDateTimestamp($newsletter->attribute('send_date'));
             $mailResult = eZNewsletterMailTransport::send($mail, true);
         }
         //send regular emails
         if (in_array(eZNewsletter::OutputFormatHTML, $userOutputFormatList)) {
             $mail->setContentType("multipart/related", false, false, false, $boundary);
             $outputFormat = eZNewsletter::OutputFormatHTML;
         }
         if (in_array(eZNewsletter::OutputFormatExternalHTML, $userOutputFormatList)) {
             $mail->setContentType("multipart/related", false, false, false, $boundary);
             $outputFormat = eZNewsletter::OutputFormatExternalHTML;
         }
         if ($outputFormat === false) {
             $outputIntersect = array_intersect($userOutputFormatList, $newsletterOutputFormatList);
             if (count($outputIntersect) > 0) {
                 $outputFormat = $outputIntersect[0];
             }
         }
         if ($outputFormat === false) {
             $outputFormat = $newsletterOutputFormatList[0];
             if ($outputFormat == eZNewsletter::OutputFormatHTML || $outputFormat == eZNewsletter::OutputFormatExternalHTML) {
                 $mail->setContentType("multipart/related", false, false, false, $boundary);
             }
         }
         $user = eZUser::currentUser();
         $userObject = $user->attribute('contentobject');
         //personalize if set in type
         $newsletter_type = eZNewsletterType::fetch($newsletter->attribute('newslettertype_id'));
         if ($newsletter_type->attribute('personalise') === '1') {
             $newsletterMail = $newsletter->personalize($newsletterMailData[$outputFormat], array('name' => $userObject->attribute('name')), true);
         } else {
             $newsletterMail = $newsletter->personalize($newsletterMailData[$outputFormat], array('name' => $userObject->attribute('name')), false);
         }
         $mail->setSender($newsletterMail['emailSender']);
         $mail->setReceiver($newsletter->attribute('preview_email'));
         $mail->setMobile($newsletter->attribute('preview_mobile'));
         $mail->setBody($newsletterMail['body']);
         $mail->setSubject($newsletterMail['subject']);
         $mail->setDateTimestamp($newsletter->attribute('send_date'));
         //if only SMS was selected, don't send email
         if (!(in_array(eZNewsletter::OutputFormatSMS, $userOutputFormatList) && count($userOutputFormatList) == 1)) {
             $mailResult = eZNewsletterMailTransport::send($mail, true);
         }
         //send SMS messages
         $instance = eZSMS::instance();
         if ($instance->countNumbers() > 0) {
             //echo "Preparing to send ".$instance->countNumbers()." SMS messages..."."\n";
             $instance->setContent($newsletterMailData[eZNewsletter::OutputFormatSMS]['body']);
             $reply = $instance->sendMessages();
             if ($reply != "") {
                 echo "SMS Reply:" . "\n";
                 echo $reply;
             }
         }
     }
 }
 function modify($tpl, $operatorName, $operatorParameters, $rootNamespace, $currentNamespace, &$operatorValue, $namedParameters, $placement)
 {
     switch ($operatorName) {
         // Convert all alphabetical chars of operatorvalue to uppercase.
         case $this->UpcaseName:
             $funcName = function_exists('mb_strtoupper') ? 'mb_strtoupper' : 'strtoupper';
             $operatorValue = $funcName($operatorValue);
             break;
             // Convert all alphabetical chars of operatorvalue to lowercase.
         // Convert all alphabetical chars of operatorvalue to lowercase.
         case $this->DowncaseName:
             $funcName = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
             $operatorValue = $funcName($operatorValue);
             break;
             // Count and return the number of words in operatorvalue.
         // Count and return the number of words in operatorvalue.
         case $this->Count_wordsName:
             $operatorValue = preg_match_all("#(\\w+)#", $operatorValue, $dummy_match);
             break;
             // Count and return the number of chars in operatorvalue.
         // Count and return the number of chars in operatorvalue.
         case $this->Count_charsName:
             $funcName = function_exists('mb_strlen') ? 'mb_strlen' : 'strlen';
             $operatorValue = $funcName($operatorValue);
             break;
             // Insert HTML line breaks before newlines.
         // Insert HTML line breaks before newlines.
         case $this->BreakName:
             $operatorValue = nl2br($operatorValue);
             break;
             // Wrap line (insert newlines).
         // Wrap line (insert newlines).
         case $this->WrapName:
             $parameters = array($operatorValue);
             if ($namedParameters['wrap_at_position']) {
                 $parameters[] = $namedParameters['wrap_at_position'];
                 if ($namedParameters['break_sequence']) {
                     $parameters[] = $namedParameters['break_sequence'];
                     if ($namedParameters['cut']) {
                         $parameters[] = $namedParameters['cut'];
                     }
                 }
             }
             $operatorValue = call_user_func_array('wordwrap', $parameters);
             break;
             // Convert the first character to uppercase.
         // Convert the first character to uppercase.
         case $this->UpfirstName:
             $i18nIni = eZINI::instance('i18n.ini');
             $hasMBString = ($i18nIni->variable('CharacterSettings', 'MBStringExtension') == 'enabled' and function_exists("mb_strtoupper") and function_exists("mb_substr") and function_exists("mb_strlen"));
             if ($hasMBString) {
                 $encoding = eZTextCodec::internalCharset();
                 $firstLetter = mb_strtoupper(mb_substr($operatorValue, 0, 1, $encoding), $encoding);
                 $remainingText = mb_substr($operatorValue, 1, mb_strlen($operatorValue, $encoding), $encoding);
                 $operatorValue = $firstLetter . $remainingText;
             } else {
                 $operatorValue = ucfirst($operatorValue);
             }
             break;
             // Simplify / transform multiple consecutive characters into one.
         // Simplify / transform multiple consecutive characters into one.
         case $this->SimplifyName:
             $simplifyCharacter = $namedParameters['char'];
             if ($namedParameters['char'] === false) {
                 $replace_this = "/ {2,}/";
                 $simplifyCharacter = ' ';
             } else {
                 $replace_this = "/" . $simplifyCharacter . "{2,}/";
             }
             $operatorValue = preg_replace($replace_this, $simplifyCharacter, $operatorValue);
             break;
             // Convert all first characters [in all words] to uppercase.
         // Convert all first characters [in all words] to uppercase.
         case $this->UpwordName:
             $i18nIni = eZINI::instance('i18n.ini');
             $hasMBString = ($i18nIni->variable('CharacterSettings', 'MBStringExtension') == 'enabled' and function_exists("mb_strtoupper") and function_exists("mb_substr") and function_exists("mb_strlen"));
             if ($hasMBString) {
                 $encoding = eZTextCodec::internalCharset();
                 $words = explode(" ", $operatorValue);
                 $newString = array();
                 foreach ($words as $word) {
                     $firstLetter = mb_strtoupper(mb_substr($word, 0, 1, $encoding), $encoding);
                     $remainingText = mb_substr($word, 1, mb_strlen($word, $encoding), $encoding);
                     $newString[] = $firstLetter . $remainingText;
                 }
                 $operatorValue = implode(" ", $newString);
                 unset($newString, $words);
             } else {
                 $operatorValue = ucwords($operatorValue);
             }
             break;
             // Strip whitespace from the beginning and end of a string.
         // Strip whitespace from the beginning and end of a string.
         case $this->TrimName:
             if ($namedParameters['chars_to_remove'] === false) {
                 $operatorValue = trim($operatorValue);
             } else {
                 $operatorValue = trim($operatorValue, $namedParameters['chars_to_remove']);
             }
             break;
             // Pad...
         // Pad...
         case $this->PadName:
             if (strlen($operatorValue) < $namedParameters['desired_length']) {
                 $operatorValue = str_pad($operatorValue, $namedParameters['desired_length'], $namedParameters['pad_sequence']);
             }
             break;
             // Shorten string [default or specified length, length=text+"..."] and add '...'
         // Shorten string [default or specified length, length=text+"..."] and add '...'
         case $this->ShortenName:
             $strlenFunc = function_exists('mb_strlen') ? 'mb_strlen' : 'strlen';
             $substrFunc = function_exists('mb_substr') ? 'mb_substr' : 'substr';
             if ($strlenFunc($operatorValue) > $namedParameters['chars_to_keep']) {
                 $operatorLength = $strlenFunc($operatorValue);
                 if ($namedParameters['trim_type'] === 'middle') {
                     $appendedStrLen = $strlenFunc($namedParameters['str_to_append']);
                     if ($namedParameters['chars_to_keep'] > $appendedStrLen) {
                         $chop = $namedParameters['chars_to_keep'] - $appendedStrLen;
                         $middlePos = (int) ($chop / 2);
                         $leftPartLength = $middlePos;
                         $rightPartLength = $chop - $middlePos;
                         $operatorValue = trim($substrFunc($operatorValue, 0, $leftPartLength) . $namedParameters['str_to_append'] . $substrFunc($operatorValue, $operatorLength - $rightPartLength, $rightPartLength));
                     } else {
                         $operatorValue = $namedParameters['str_to_append'];
                     }
                 } else {
                     $chop = $namedParameters['chars_to_keep'] - $strlenFunc($namedParameters['str_to_append']);
                     $operatorValue = $substrFunc($operatorValue, 0, $chop);
                     $operatorValue = trim($operatorValue);
                     if ($operatorLength > $chop) {
                         $operatorValue = $operatorValue . $namedParameters['str_to_append'];
                     }
                 }
             }
             break;
             // Wash (translate strings to non-spammable text):
         // Wash (translate strings to non-spammable text):
         case $this->WashName:
             $type = $namedParameters['type'];
             $operatorValue = $this->wash($operatorValue, $tpl, $type);
             break;
             // Ord (translate a unicode string to actual unicode id/numbers):
         // Ord (translate a unicode string to actual unicode id/numbers):
         case $this->OrdName:
             $codec = eZTextCodec::instance(false, 'unicode');
             $output = $codec->convertString($operatorValue);
             $operatorValue = $output;
             break;
             // Chr (generate unicode characters based on input):
         // Chr (generate unicode characters based on input):
         case $this->ChrName:
             $codec = eZTextCodec::instance('unicode', false);
             $output = $codec->convertString($operatorValue);
             $operatorValue = $output;
             break;
             // Default case: something went wrong - unknown things...
         // Default case: something went wrong - unknown things...
         default:
             $tpl->warning($operatorName, "Unknown string type '{$type}'", $placement);
             break;
     }
 }
예제 #14
0
 static function treeCacheFilename($key, $templateFilepath)
 {
     $internalCharset = eZTextCodec::internalCharset();
     $extraName = '';
     if (preg_match("#^.+/(.*)\\.tpl\$#", $templateFilepath, $matches)) {
         $extraName = '-' . $matches[1];
     } else {
         if (preg_match("#^(.*)\\.tpl\$#", $templateFilepath, $matches)) {
             $extraName = '-' . $matches[1];
         }
     }
     $cacheFileKey = "{$key}-{$internalCharset}";
     $cacheFileName = md5($cacheFileKey) . $extraName . '.php';
     return $cacheFileName;
 }
예제 #15
0
 /**
  * Creates a new content or updates an existing one based on $file
  *
  * @param string $file the file to import
  * @param int $placeNodeID the node id where to place the new document or
  *        the node of the document to update
  * @param string $originalFileName
  * @param string $importType "import" or "replace"
  * @param eZContentUpload|null $upload (not used in this method)
  * @param string|false $locale the locale to use while creating/updating
  *        the content
  * @return array|false false if something went wrong
  */
 function import($file, $placeNodeID, $originalFileName, $importType = "import", $upload = null, $locale = false)
 {
     $ooINI = eZINI::instance('odf.ini');
     //$tmpDir = $ooINI->variable( 'ODFSettings', 'TmpDir' );
     // Use var-directory as temporary directory
     $tmpDir = getcwd() . "/" . eZSys::cacheDirectory();
     $allowedTypes = $ooINI->variable('DocumentType', 'AllowedTypes');
     $convertTypes = $ooINI->variable('DocumentType', 'ConvertTypes');
     $originalFileType = array_slice(explode('.', $originalFileName), -1, 1);
     $originalFileType = strtolower($originalFileType[0]);
     if (!in_array($originalFileType, $allowedTypes, false) and !in_array($originalFileType, $convertTypes, false)) {
         $this->setError(self::ERROR_UNSUPPORTEDTYPE, ezpI18n::tr('extension/ezodf/import/error', "Filetype: ") . $originalFileType);
         return false;
     }
     // If replacing/updating the document we need the ID.
     if ($importType == "replace") {
         $GLOBALS["OOImportObjectID"] = $placeNodeID;
     }
     // Check if we have access to node
     $place_node = eZContentObjectTreeNode::fetch($placeNodeID);
     $importClassIdentifier = $ooINI->variable('ODFImport', 'DefaultImportClass');
     // Check if class exist
     $class = eZContentClass::fetchByIdentifier($importClassIdentifier);
     if (!is_object($class)) {
         eZDebug::writeError("Content class <strong>{$importClassIdentifier}</strong> specified in odf.ini does not exist.");
         $this->setError(self::ERROR_UNKNOWNCLASS, $importClassIdentifier);
         return false;
     }
     if (!is_object($place_node)) {
         $locationOK = false;
         if ($upload !== null) {
             $parentNodes = false;
             $parentMainNode = false;
             $locationOK = $upload->detectLocations($importClassIdentifier, $class, $placeNodeID, $parentNodes, $parentMainNode);
         }
         if ($locationOK === false || $locationOK === null) {
             $this->setError(self::ERROR_UNKNOWNNODE, ezpI18n::tr('extension/ezodf/import/error', "Unable to fetch node with id ") . $placeNodeID);
             return false;
         }
         $placeNodeID = $parentMainNode;
         $place_node = eZContentObjectTreeNode::fetch($placeNodeID);
     }
     // Check if document conversion is needed
     //
     // Alex 2008/04/21 - added !== false
     if (in_array($originalFileType, $convertTypes, false) !== false) {
         $uniqueStamp = md5(time());
         $tmpFromFile = $tmpDir . "/convert_from_{$uniqueStamp}.doc";
         $tmpToFile = $tmpDir . "/ooo_converted_{$uniqueStamp}.odt";
         copy(realpath($file), $tmpFromFile);
         /// Convert document using the eZ Publish document conversion daemon
         if (!$this->daemonConvert($tmpFromFile, $tmpToFile)) {
             if ($this->getErrorNumber() == 0) {
                 $this->setError(self::ERROR_CONVERT);
             }
             return false;
         }
         // At this point we can unlink the sourcefile for conversion
         unlink($tmpFromFile);
         // Overwrite the file location
         $file = $tmpToFile;
     }
     $importResult = array();
     $unzipResult = "";
     $uniqueImportDir = $this->ImportDir;
     eZDir::mkdir($uniqueImportDir, false, true);
     $http = eZHTTPTool::instance();
     $archiveOptions = new ezcArchiveOptions(array('readOnly' => true));
     $archive = ezcArchive::open($file, null, $archiveOptions);
     $archive->extract($uniqueImportDir);
     $fileName = $uniqueImportDir . "content.xml";
     $dom = new DOMDocument('1.0', 'UTF-8');
     $success = $dom->load($fileName);
     $sectionNodeHash = array();
     // At this point we could unlink the destination file from the conversion, if conversion was used
     if (isset($tmpToFile)) {
         unlink($tmpToFile);
     }
     if (!$success) {
         $this->setError(self::ERROR_PARSEXML);
         return false;
     }
     // Fetch the automatic document styles
     $automaticStyleArray = $dom->getElementsByTagNameNS(self::NAMESPACE_OFFICE, 'automatic-styles');
     if ($automaticStyleArray->length == 1) {
         $this->AutomaticStyles = $automaticStyleArray->item(0)->childNodes;
     }
     // Fetch the body section content
     $sectionNodeArray = $dom->getElementsByTagNameNS(self::NAMESPACE_TEXT, 'section');
     $customClassFound = false;
     if ($sectionNodeArray->length > 0) {
         $registeredClassArray = $ooINI->variable('ODFImport', 'RegisteredClassArray');
         // Check the defined sections in OO document
         $sectionNameArray = array();
         foreach ($sectionNodeArray as $sectionNode) {
             $sectionNameArray[] = strtolower($sectionNode->getAttributeNS(self::NAMESPACE_TEXT, "name"));
         }
         // Check if there is a coresponding eZ Publish class for this document
         foreach ($registeredClassArray as $className) {
             $attributeArray = $ooINI->variable($className, 'Attribute');
             if (!empty($attributeArray)) {
                 // Convert space to _ in section names
                 foreach ($sectionNameArray as $key => $value) {
                     $sectionNameArray[$key] = str_replace(" ", "_", $value);
                 }
                 sort($attributeArray);
                 sort($sectionNameArray);
                 $diff = array_diff($attributeArray, $sectionNameArray);
                 if (empty($diff)) {
                     $importClassIdentifier = $className;
                     $customClassFound = true;
                     break;
                 }
             }
         }
         if ($customClassFound == true) {
             foreach ($sectionNodeArray as $sectionNode) {
                 $sectionName = str_replace(" ", "_", strtolower($sectionNode->getAttributeNS(self::NAMESPACE_TEXT, 'name')));
                 $xmlText = "";
                 $level = 1;
                 $childArray = $sectionNode->childNodes;
                 $nodeCount = 1;
                 foreach ($childArray as $childNode) {
                     if ($childNode->nodeType === XML_ELEMENT_NODE) {
                         $isLastTag = $nodeCount == $childArray->length;
                         $xmlText .= self::handleNode($childNode, $level, $isLastTag);
                     }
                     $nodeCount++;
                 }
                 $endSectionPart = "";
                 $levelDiff = 1 - $level;
                 if ($levelDiff < 0) {
                     $endSectionPart = str_repeat("</section>", abs($levelDiff));
                 }
                 $charset = eZTextCodec::internalCharset();
                 // Store the original XML for each section, since some datatypes needs to handle the XML specially
                 $sectionNodeHash[$sectionName] = $sectionNode;
                 $xmlTextArray[$sectionName] = "<?xml version='1.0' encoding='{$charset}' ?>" . "<section xmlns:image='http://ez.no/namespaces/ezpublish3/image/' " . "  xmlns:xhtml='http://ez.no/namespaces/ezpublish3/xhtml/'><section>" . $xmlText . $endSectionPart . "</section></section>";
             }
         }
     }
     if ($customClassFound == false) {
         // No defined sections. Do default import.
         $bodyNodeArray = $dom->getElementsByTagNameNS(self::NAMESPACE_OFFICE, 'text');
         // Added by Soushi
         // check the parent-style-name [ eZSectionDefinition ]
         $eZSectionDefinitionStyleName = array();
         foreach ($automaticStyleArray->item(0)->childNodes as $child) {
             if ($child->nodeType === XML_ELEMENT_NODE && $child->getAttributeNS(self::NAMESPACE_STYLE, 'parent-style-name') === 'eZSectionDefinition') {
                 $eZSectionDefinitionStyleName[] = $child->getAttributeNS(self::NAMESPACE_STYLE, 'name');
             }
         }
         $sectionNameArray = array();
         $sectionNodeArray = array();
         $paragraphSectionName = NULL;
         $firstChildFlag = false;
         $paragraphSectionNodeArray = array();
         foreach ($bodyNodeArray->item(0)->childNodes as $childNode) {
             $firstChildFlag = true;
             if ($childNode->nodeType === XML_ELEMENT_NODE && (in_array($childNode->getAttributeNS(self::NAMESPACE_TEXT, 'style-name'), $eZSectionDefinitionStyleName) || $childNode->getAttributeNS(self::NAMESPACE_TEXT, 'style-name') === 'eZSectionDefinition')) {
                 $firstChildFlag = false;
                 $childNodeChildren = $childNode->childNodes;
                 $paragraphSectionName = trim($childNodeChildren->item(0)->textContent);
                 $sectionNameArray[] = $paragraphSectionName;
             }
             if ($paragraphSectionName && $firstChildFlag) {
                 $paragraphSectionNodeArray[$paragraphSectionName][] = $childNode;
             }
         }
         $sectionNodeArray = array();
         foreach ($paragraphSectionNodeArray as $key => $childNodes) {
             $sectionNode = $dom->createElement('section');
             foreach ($childNodes as $childNode) {
                 $sectionNode->appendChild($childNode);
             }
             $sectionNodeArray[$key] = $sectionNode;
         }
         $customClassFound = false;
         if ($sectionNameArray) {
             $registeredClassArray = $ooINI->variable('ODFImport', 'RegisteredClassArray');
             // Check if there is a coresponding eZ Publish class for this document
             foreach ($registeredClassArray as $className) {
                 $attributeArray = $ooINI->variable($className, 'Attribute');
                 if (!empty($attributeArray)) {
                     // Convert space to _ in section names
                     foreach ($sectionNameArray as $key => $value) {
                         $sectionNameArray[$key] = str_replace(" ", "_", $value);
                     }
                     sort($attributeArray);
                     sort($sectionNameArray);
                     $diff = array_diff($attributeArray, $sectionNameArray);
                     if (empty($diff)) {
                         $importClassIdentifier = $className;
                         $customClassFound = true;
                         break;
                     }
                 }
             }
         }
         if ($sectionNameArray && $customClassFound == true) {
             foreach ($sectionNodeArray as $key => $sectionNode) {
                 $sectionName = str_replace(" ", "_", $key);
                 $xmlText = "";
                 $level = 1;
                 foreach ($sectionNode->childNodes as $childNode) {
                     $isLastTag = !isset($childNode->nextSibling);
                     $xmlText .= self::handleNode($childNode, $level, $isLastTag);
                 }
                 $endSectionPart = "";
                 $levelDiff = 1 - $level;
                 if ($levelDiff < 0) {
                     $endSectionPart = str_repeat("</section>", abs($levelDiff));
                 }
                 $charset = eZTextCodec::internalCharset();
                 // Store the original XML for each section, since some datatypes needs to handle the XML specially
                 $sectionNodeHash[$sectionName] = $sectionNode;
                 $xmlTextArray[$sectionName] = "<?xml version='1.0' encoding='{$charset}' ?>" . "<section xmlns:image='http://ez.no/namespaces/ezpublish3/image/' " . "  xmlns:xhtml='http://ez.no/namespaces/ezpublish3/xhtml/'><section>" . $xmlText . $endSectionPart . "</section></section>";
             }
         } else {
             if ($bodyNodeArray->length === 1) {
                 $xmlText = "";
                 $level = 1;
                 foreach ($bodyNodeArray->item(0)->childNodes as $childNode) {
                     $xmlText .= self::handleNode($childNode, $level);
                 }
                 $endSectionPart = "";
                 $levelDiff = 1 - $level;
                 if ($levelDiff < 0) {
                     $endSectionPart = str_repeat("</section>", abs($levelDiff));
                 }
                 $charset = eZTextCodec::internalCharset();
                 $xmlTextBody = "<?xml version='1.0' encoding='{$charset}' ?>" . "<section xmlns:image='http://ez.no/namespaces/ezpublish3/image/' " . "  xmlns:xhtml='http://ez.no/namespaces/ezpublish3/xhtml/'><section>" . $xmlText . $endSectionPart . "</section></section>";
             }
         }
     }
     if ($importType == "replace") {
         // Check if we are allowed to edit the node
         $functionCollection = new eZContentFunctionCollection();
         $access = $functionCollection->checkAccess('edit', $place_node, false, false, $locale);
     } else {
         // Check if we are allowed to create a node under the node
         $functionCollection = new eZContentFunctionCollection();
         $access = $functionCollection->checkAccess('create', $place_node, $importClassIdentifier, $place_node->attribute('class_identifier'), $locale);
     }
     if ($access['result']) {
         // Check if we should replace the current object or import a new
         if ($importType !== "replace") {
             $class = eZContentClass::fetchByIdentifier($importClassIdentifier);
             $place_object = $place_node->attribute('object');
             $sectionID = $place_object->attribute('section_id');
             $creatorID = $this->currentUserID;
             $parentNodeID = $placeNodeID;
             if (!is_object($class)) {
                 eZDebug::writeError("Content class <strong>{$importClassIdentifier}</strong> specified in odf.ini does not exist.");
                 $this->setError(self::ERROR_UNKNOWNCLASS, $importClassIdentifier);
                 return false;
             }
             $object = $class->instantiate($creatorID, $sectionID, false, $locale);
             $nodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $object->attribute('id'), 'contentobject_version' => $object->attribute('current_version'), 'parent_node' => $parentNodeID, 'is_main' => 1));
             $nodeAssignment->store();
             $version = $object->version(1);
             $version->setAttribute('modified', eZDateTime::currentTimeStamp());
             $version->setAttribute('status', eZContentObjectVersion::STATUS_DRAFT);
             $version->store();
             $dataMap = $object->dataMap();
         } else {
             // Check if class is supported before we start changing anything
             $placeClassIdentifier = $place_node->attribute('class_identifier');
             if ($ooINI->hasVariable($placeClassIdentifier, 'DefaultImportTitleAttribute') && $ooINI->hasVariable($placeClassIdentifier, 'DefaultImportBodyAttribute')) {
                 $titleAttribute = $ooINI->variable($placeClassIdentifier, 'DefaultImportTitleAttribute');
                 $bodyAttribute = $ooINI->variable($placeClassIdentifier, 'DefaultImportBodyAttribute');
                 // Extra check to see if attributes exist in dataMap (config is not wrong)
                 $dataMap = $place_node->attribute('data_map');
                 if (!isset($dataMap[$titleAttribute]) || !isset($dataMap[$bodyAttribute])) {
                     $this->setError(self::ERROR_IMPORTING, "Error in configuration for {$placeClassIdentifier}, please check configuration file.");
                     return false;
                 }
                 unset($dataMap);
             } else {
                 $this->setError(self::ERROR_IMPORTING, "No settings for replacing node of type {$placeClassIdentifier}. Stopping.");
                 return false;
             }
             // Change class for importing
             $importClassIdentifier = $placeClassIdentifier;
             // already fetched: $node = eZContentObjectTreeNode::fetch( $placeNodeID );
             $object = $place_node->attribute('object');
             $version = $object->createNewVersionIn($locale);
             $dataMap = $version->dataMap();
         }
         $contentObjectID = $object->attribute('id');
         if ($customClassFound == true) {
             // Initialize the actual object attributes
             $attributeArray = $ooINI->variable($importClassIdentifier, 'Attribute');
             foreach ($attributeArray as $attributeIdentifier => $sectionName) {
                 switch ($dataMap[$attributeIdentifier]->DataTypeString) {
                     case "ezstring":
                     case "eztext":
                         if (!isset($xmlTextArray[$sectionName])) {
                             continue;
                         }
                         $eztextDom = new DOMDOcument('1.0', 'UTF-8');
                         $eztextDom->loadXML($xmlTextArray[$sectionName]);
                         $text = $eztextDom->documentElement->textContent;
                         $dataMap[$attributeIdentifier]->setAttribute('data_text', trim($text));
                         $dataMap[$attributeIdentifier]->store();
                         break;
                     case "ezxmltext":
                         if (!isset($xmlTextArray[$sectionName])) {
                             continue;
                         }
                         $dataMap[$attributeIdentifier]->setAttribute('data_text', $xmlTextArray[$sectionName]);
                         $dataMap[$attributeIdentifier]->store();
                         break;
                     case "ezdate":
                         // Only support date formats as a single paragraph in a section with the format:
                         // day/month/year
                         if (!isset($xmlTextArray[$sectionName])) {
                             continue;
                         }
                         $dateString = strip_tags($xmlTextArray[$sectionName]);
                         $dateArray = explode("/", $dateString);
                         if (count($dateArray) == 3) {
                             $year = $dateArray[2];
                             $month = $dateArray[1];
                             $day = $dateArray[0];
                             $date = new eZDate();
                             $contentClassAttribute = $dataMap[$attributeIdentifier];
                             $date->setMDY($month, $day, $year);
                             $dataMap[$attributeIdentifier]->setAttribute('data_int', $date->timeStamp());
                             $dataMap[$attributeIdentifier]->store();
                         }
                         break;
                     case "ezdatetime":
                         // Only support date formats as a single paragraph in a section with the format:
                         // day/month/year 14:00
                         if (!isset($xmlTextArray[$sectionName])) {
                             continue;
                         }
                         $dateString = trim(strip_tags($xmlTextArray[$sectionName]));
                         $dateTimeArray = explode(" ", $dateString);
                         $dateArray = explode("/", $dateTimeArray[0]);
                         $timeArray = explode(":", $dateTimeArray[1]);
                         if (count($dateArray) == 3 and count($timeArray) == 2) {
                             $year = $dateArray[2];
                             $month = $dateArray[1];
                             $day = $dateArray[0];
                             $hour = $timeArray[0];
                             $minute = $timeArray[1];
                             $dateTime = new eZDateTime();
                             $contentClassAttribute = $dataMap[$attributeIdentifier];
                             $dateTime->setMDYHMS($month, $day, $year, $hour, $minute, 0);
                             $dataMap[$attributeIdentifier]->setAttribute('data_int', $dateTime->timeStamp());
                             $dataMap[$attributeIdentifier]->store();
                         }
                         break;
                     case "ezimage":
                         $hasImage = false;
                         // Images are treated as an image object inside a paragrah.
                         // We fetch the first image object if there are multiple and ignore the rest
                         if (is_object($sectionNodeHash[$sectionName])) {
                             // Look for paragraphs in the section
                             foreach ($sectionNodeHash[$sectionName]->childNodes as $paragraph) {
                                 if (!$paragraph->hasChildNodes()) {
                                     continue;
                                 }
                                 // Look for frame node
                                 foreach ($paragraph->childNodes as $frame) {
                                     // finally look for the image node
                                     $children = $frame->childNodes;
                                     $imageNode = $children->item(0);
                                     if ($imageNode && $imageNode->localName == "image") {
                                         $fileName = ltrim($imageNode->getAttributeNS(self::NAMESPACE_XLINK, 'href'), '#');
                                         $filePath = $this->ImportDir . $fileName;
                                         if (file_exists($filePath)) {
                                             $imageContent = $dataMap[$attributeIdentifier]->attribute('content');
                                             $imageContent->initializeFromFile($filePath, false, basename($filePath));
                                             $imageContent->store($dataMap[$attributeIdentifier]);
                                             $dataMap[$attributeIdentifier]->store();
                                         }
                                         $hasImage = true;
                                     }
                                 }
                             }
                         }
                         if (!$hasImage) {
                             $imageHandler = $dataMap[$attributeIdentifier]->attribute('content');
                             if ($imageHandler) {
                                 $imageHandler->removeAliases($dataMap[$attributeIdentifier]);
                             }
                         }
                         break;
                     case "ezmatrix":
                         $matrixHeaderArray = array();
                         // Fetch the current defined columns in the matrix
                         $matrix = $dataMap[$attributeIdentifier]->content();
                         $columns = $matrix->attribute("columns");
                         foreach ($columns['sequential'] as $column) {
                             $matrixHeaderArray[] = $column['name'];
                         }
                         $headersValid = true;
                         $originalHeaderCount = count($matrixHeaderArray);
                         $headerCount = 0;
                         $rowCount = 0;
                         $cellArray = array();
                         // A matrix is supported as a table inside sections. If multiple tables are present we take the first.
                         if (is_object($sectionNodeHash[$sectionName])) {
                             // Look for paragraphs in the section
                             foreach ($sectionNodeHash[$sectionName]->childNodes as $table) {
                                 if ($table->localName == "table") {
                                     // Loop the rows in the table
                                     foreach ($table->childNodes as $row) {
                                         // Check the headers and compare with the defined matrix
                                         if ($row->localName == "table-header-rows") {
                                             $rowArray = $row->childNodes;
                                             if ($rowArray->length == 1) {
                                                 foreach ($rowArray->item(0)->childNodes as $headerCell) {
                                                     if ($headerCell->localName == "table-cell") {
                                                         $paragraphArray = $headerCell->childNodes;
                                                         if ($paragraphArray->length == 1) {
                                                             $headerName = $paragraphArray->item(0)->textContent;
                                                             if ($matrixHeaderArray[$headerCount] != $headerName) {
                                                                 $headersValid = false;
                                                             }
                                                             $headerCount++;
                                                         }
                                                     }
                                                 }
                                             }
                                         }
                                         // Check the rows
                                         if ($row->localName == "table-row") {
                                             foreach ($row->childNodes as $cell) {
                                                 if ($cell->childNodes->length >= 1) {
                                                     $firstParagraph = $cell->childNodes->item(0);
                                                     $cellArray[] = $firstParagraph->textContent;
                                                 }
                                             }
                                             $rowCount++;
                                         }
                                     }
                                 }
                             }
                         }
                         if ($headerCount == $originalHeaderCount and $headersValid == true) {
                             // Remove all existing rows
                             for ($i = 0; $i < $matrix->attribute("rowCount"); $i++) {
                                 $matrix->removeRow($i);
                             }
                             // Insert new rows
                             $matrix->addRow(false, $rowCount);
                             $matrix->Cells = $cellArray;
                             $dataMap[$attributeIdentifier]->setAttribute('data_text', $matrix->xmlString());
                             $matrix->decodeXML($dataMap[$attributeIdentifier]->attribute('data_text'));
                             $dataMap[$attributeIdentifier]->setContent($matrix);
                             $dataMap[$attributeIdentifier]->store();
                         }
                         break;
                     default:
                         eZDebug::writeError("Unsupported datatype for OpenOffice.org import: " . $dataMap[$attributeIdentifier]->DataTypeString);
                         break;
                 }
             }
         } else {
             // Check if attributes are already fetched
             if (!isset($titleAttribute) || !isset($bodyAttribute)) {
                 // Set attributes accorring to import class
                 $titleAttribute = $ooINI->variable($importClassIdentifier, 'DefaultImportTitleAttribute');
                 $bodyAttribute = $ooINI->variable($importClassIdentifier, 'DefaultImportBodyAttribute');
             }
             $objectName = basename($originalFileName);
             // Remove extension from name
             $objectName = preg_replace("/(\\....)\$/", "", $objectName);
             // Convert _ to spaces and upcase the first character
             $objectName = ucfirst(str_replace("_", " ", $objectName));
             $dataMap[$titleAttribute]->setAttribute('data_text', $objectName);
             $dataMap[$titleAttribute]->store();
             $dataMap[$bodyAttribute]->setAttribute('data_text', $xmlTextBody);
             $dataMap[$bodyAttribute]->store();
         }
         $operationResult = eZOperationHandler::execute('content', 'publish', array('object_id' => $contentObjectID, 'version' => $version->attribute('version')));
         $storeImagesInMedia = $ooINI->variable("ODFImport", "PlaceImagesInMedia") == "true";
         if ($storeImagesInMedia == true) {
             // Fetch object to get correct name
             $object = eZContentObject::fetch($contentObjectID);
             $contentINI = eZINI::instance('content.ini');
             $mediaRootNodeID = $contentINI->variable("NodeSettings", "MediaRootNode");
             $node = eZContentObjectTreeNode::fetch($mediaRootNodeID);
             $articleFolderName = $object->attribute('name');
             $importFolderName = $ooINI->variable('ODFImport', 'ImportedImagesMediaNodeName');
             $importNode = self::createSubNode($node, $importFolderName);
             $articleNode = self::createSubNode($importNode, $articleFolderName);
             $imageRootNode = $articleNode->attribute("node_id");
         } else {
             $imageRootNode = $object->attribute("main_node_id");
         }
         // Publish all embedded images as related objects
         foreach ($this->RelatedImageArray as $image) {
             // Publish related images
             $nodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $image['ID'], 'contentobject_version' => 1, 'parent_node' => $imageRootNode, 'is_main' => 1));
             $nodeAssignment->store();
             eZOperationHandler::execute('content', 'publish', array('object_id' => $image['ID'], 'version' => 1));
             $object->addContentObjectRelation($image['ID'], 1);
         }
         $mainNode = $object->attribute('main_node');
         // Create object stop.
         $importResult['Object'] = $object;
         $importResult['Published'] = $operationResult['status'] == eZModuleOperationInfo::STATUS_CONTINUE;
         if ($mainNode instanceof eZContentObjectTreeNode) {
             $importResult['MainNode'] = $mainNode;
             $importResult['URLAlias'] = $mainNode->attribute('url_alias');
             $importResult['NodeName'] = $mainNode->attribute('name');
         } else {
             $importResult['MainNode'] = false;
             $importResult['URLAlias'] = false;
             $importResult['NodeName'] = false;
         }
         $importResult['ClassIdentifier'] = $importClassIdentifier;
     } else {
         $this->setError(self::ERROR_ACCESSDENIED);
         return false;
     }
     // Clean up
     eZDir::recursiveDelete($uniqueImportDir);
     return $importResult;
 }
 static function httpCharset()
 {
     $realCharset =& $GLOBALS['eZTextCodecHTTPCharsetReal'];
     if (!isset($realCharset)) {
         $charset = '';
         if (isset($GLOBALS['eZTextCodecHTTPCharset'])) {
             $charset = $GLOBALS['eZTextCodecHTTPCharset'];
         }
         if ($charset == '') {
             if (isset($GLOBALS['eZTextCodecInternalCharsetReal'])) {
                 $realCharset = $GLOBALS['eZTextCodecInternalCharsetReal'];
             } else {
                 $realCharset = eZTextCodec::internalCharset();
             }
         } else {
             $realCharset = eZCharsetInfo::realCharsetCode($charset);
         }
     }
     return $realCharset;
 }
예제 #17
0
 function executeCommandCode(&$text, $command, $charsetName)
 {
     if ($command['command'] == 'url_cleanup_iri') {
         $text = eZCharTransform::commandUrlCleanupIRI($text, $charsetName);
         return true;
     } else {
         if ($command['command'] == 'url_cleanup') {
             $text = eZCharTransform::commandUrlCleanup($text, $charsetName);
             return true;
         } else {
             if ($command['command'] == 'url_cleanup_compat') {
                 $text = eZCharTransform::commandUrlCleanupCompat($text, $charsetName);
                 return true;
             } else {
                 if ($command['command'] == 'identifier_cleanup') {
                     $text = strtolower($text);
                     $text = preg_replace(array("#[^a-z0-9_ ]#", "/ /", "/__+/", "/^_|_\$/"), array(" ", "_", "_", ""), $text);
                     return true;
                 } else {
                     if ($command['command'] == 'search_cleanup') {
                         $nonCJKCharsets = $this->nonCJKCharsets();
                         if (!in_array($charsetName, $nonCJKCharsets)) {
                             // 4 Add spaces after chinese / japanese / korean multibyte characters
                             $codec = eZTextCodec::instance(false, 'unicode');
                             $unicodeValueArray = $codec->convertString($text);
                             $normalizedTextArray = array();
                             $bFlag = false;
                             foreach (array_keys($unicodeValueArray) as $valueKey) {
                                 // Check for word characters that should be broken up for search
                                 if ($unicodeValueArray[$valueKey] >= 12289 and $unicodeValueArray[$valueKey] <= 12542 or $unicodeValueArray[$valueKey] >= 13312 and $unicodeValueArray[$valueKey] <= 40863 or $unicodeValueArray[$valueKey] >= 44032 and $unicodeValueArray[$valueKey] <= 55203) {
                                     if ($bFlag) {
                                         $normalizedTextArray[] = $unicodeValueArray[$valueKey];
                                     }
                                     $normalizedTextArray[] = 32;
                                     // A space
                                     $normalizedTextArray[] = $unicodeValueArray[$valueKey];
                                     $bFlag = true;
                                 } else {
                                     if ($bFlag) {
                                         $normalizedTextArray[] = 32;
                                         // A space
                                     }
                                     $normalizedTextArray[] = $unicodeValueArray[$valueKey];
                                     $bFlag = false;
                                 }
                             }
                             if ($bFlag) {
                                 $normalizedTextArray[count($normalizedTextArray) - 1] = 32;
                             }
                             $revCodec = eZTextCodec::instance('unicode', false);
                             // false means use internal charset
                             $text = $revCodec->convertString($normalizedTextArray);
                         }
                         // Make sure dots inside words/numbers are kept, the rest is turned into space
                         $text = preg_replace(array("#(\\.){2,}#", "#^\\.#", "#\\s\\.#", "#\\.\\s#", "#\\.\$#", "#([^0-9])%#"), array(" ", " ", " ", " ", " ", "\$1 "), $text);
                         $ini = eZINI::instance();
                         if ($ini->variable('SearchSettings', 'EnableWildcard') != 'true') {
                             $text = str_replace("*", " ", $text);
                         }
                         $charset = eZTextCodec::internalCharset();
                         $hasUTF8 = $charset == "utf-8";
                         if ($hasUTF8) {
                             $text = preg_replace("#(\\s+)#u", " ", $text);
                         } else {
                             $text = preg_replace("#(\\s+)#", " ", $text);
                         }
                         return true;
                     } else {
                         $ini = eZINI::instance('transform.ini');
                         $commands = $ini->variable('Extensions', 'Commands');
                         if (isset($commands[$command['command']])) {
                             list($path, $className) = explode(':', $commands[$command['command']], 2);
                             if (file_exists($path)) {
                                 include_once $path;
                                 $text = call_user_func_array(array($className, 'executeCommand'), array($text, $command['command'], $charsetName));
                                 return true;
                             } else {
                                 eZDebug::writeError("Could not locate include file '{$path}' for transformation '" . $command['command'] . "'");
                             }
                         }
                     }
                 }
             }
         }
     }
     return false;
 }
예제 #18
0
    /**
     * Connects to the database.
     *
     * @return void
     * @throw eZClusterHandlerDBNoConnectionException
     * @throw eZClusterHandlerDBNoDatabaseException
     */
    public function _connect()
    {
        $siteINI = eZINI::instance( 'site.ini' );
        // DB Connection setup
        // This part is not actually required since _connect will only be called
        // once, but it is useful to run the unit tests. So be it.
        // @todo refactor this using eZINI::setVariable in unit tests
        if ( self::$dbparams === null )
        {
            $fileINI = eZINI::instance( 'file.ini' );

            self::$dbparams = array();
            self::$dbparams['host']       = $fileINI->variable( 'eZDFSClusteringSettings', 'DBHost' );
            self::$dbparams['port']       = $fileINI->variable( 'eZDFSClusteringSettings', 'DBPort' );
            self::$dbparams['socket']     = $fileINI->variable( 'eZDFSClusteringSettings', 'DBSocket' );
            self::$dbparams['dbname']     = $fileINI->variable( 'eZDFSClusteringSettings', 'DBName' );
            self::$dbparams['user']       = $fileINI->variable( 'eZDFSClusteringSettings', 'DBUser' );
            self::$dbparams['pass']       = $fileINI->variable( 'eZDFSClusteringSettings', 'DBPassword' );

            self::$dbparams['max_connect_tries'] = $fileINI->variable( 'eZDFSClusteringSettings', 'DBConnectRetries' );
            self::$dbparams['max_execute_tries'] = $fileINI->variable( 'eZDFSClusteringSettings', 'DBExecuteRetries' );

            self::$dbparams['sql_output'] = $siteINI->variable( "DatabaseSettings", "SQLOutput" ) == "enabled";

            self::$dbparams['cache_generation_timeout'] = $siteINI->variable( "ContentSettings", "CacheGenerationTimeout" );
        }

        $serverString = self::$dbparams['host'];
        if ( self::$dbparams['socket'] )
            $serverString .= ':' . self::$dbparams['socket'];
        elseif ( self::$dbparams['port'] )
            $serverString .= ':' . self::$dbparams['port'];

        $maxTries = self::$dbparams['max_connect_tries'];
        $tries = 0;
        while ( $tries < $maxTries )
        {
            if ( $this->db = mysql_connect( $serverString, self::$dbparams['user'], self::$dbparams['pass'] ) )
                break;
            ++$tries;
        }
        if ( !$this->db )
            throw new eZClusterHandlerDBNoConnectionException( $serverString, self::$dbparams['user'], self::$dbparams['pass'] );

        if ( !mysql_select_db( self::$dbparams['dbname'], $this->db ) )
            throw new eZClusterHandlerDBNoDatabaseException( self::$dbparams['dbname'] );

        // DFS setup
        if ( $this->dfsbackend === null )
        {
            $this->dfsbackend = new eZDFSFileHandlerDFSBackend();
        }

        $charset = trim( $siteINI->variable( 'DatabaseSettings', 'Charset' ) );
        if ( $charset === '' )
        {
            $charset = eZTextCodec::internalCharset();
        }

        if ( $charset )
        {
            if ( !mysql_query( "SET NAMES '" . eZMySQLCharset::mapTo( $charset ) . "'", $this->db ) )
            {
                $this->_fail( "Failed to set Database charset to $charset." );
            }
        }
    }
function fileDBInstance()
{
    $fileIni = eZINI::instance('file.ini');
    $ini = eZINI::instance();

    list( $server, $port, $user, $pwd, $db, $retries ) =
        $fileIni->variableMulti( 'eZDFSClusteringSettings', array( 'DBHost', 'DBPort', 'DBUser', 'DBPassword', 'DBName', 'DBConnectRetries' ) );
    list( $charset, $usePersistentConnection ) =
        $ini->variableMulti( 'DatabaseSettings', array( 'Charset', 'UserPersistentConnection' ) );

    $isInternalCharset = false;
    if ( trim( $charset ) == '' )
    {
        $charset = eZTextCodec::internalCharset();
        $isInternalCharset = true;
    }
    $builtinEncoding = ( $ini->variable( 'DatabaseSettings', 'UseBuiltinEncoding' ) == 'true' );

    $params = array('server' => $server,
                    'port' => $port,
                    'user' => $user,
                    'password' => $pwd,
                    'database' => $db,
                    'use_slave_server' => false,
                    'slave_server' => null,
                    'slave_port' => null,
                    'slave_user' => null,
                    'slave_password' => null,
                    'slave_database' => null,
                    'charset' => $charset,
                    'is_internal_charset' => $isInternalCharset,
                    'socket' => false,
                    'builtin_encoding' => $builtinEncoding,
                    'connect_retries' => $retries,
                    'use_persistent_connection' => $usePersistentConnection,
                    'show_errors' => true );

    return new eZMySQLiDB( $params );
}
예제 #20
0
 static function storeCache($key)
 {
     $translationCache = eZTranslationCache::cacheTable();
     if (!isset($translationCache[$key])) {
         eZDebug::writeWarning("Translation cache for key '{$key}' does not exist, cannot store cache", __METHOD__);
         return;
     }
     $internalCharset = eZTextCodec::internalCharset();
     //         $cacheFileKey = "$key-$internalCharset";
     $cacheFileKey = $key;
     $cacheFileName = md5($cacheFileKey) . '.php';
     $cache =& $translationCache[$key];
     if (!file_exists(eZTranslationCache::cacheDirectory())) {
         eZDir::mkdir(eZTranslationCache::cacheDirectory(), false, true);
     }
     $php = new eZPHPCreator(eZTranslationCache::cacheDirectory(), $cacheFileName);
     $php->addRawVariable('eZTranslationCacheCodeDate', self::CODE_DATE);
     $php->addSpace();
     $php->addRawVariable('CacheInfo', array('charset' => $internalCharset));
     $php->addRawVariable('TranslationInfo', $cache['info']);
     $php->addSpace();
     $php->addRawVariable('TranslationRoot', $cache['root']);
     $php->store();
 }
예제 #21
0
 /**
  * Loads a translation file
  * Will load from cache if possible, or generate cache if needed
  *
  * Also checks for translation files expiry based on mtime if RegionalSettings.TranslationCheckMTime is enabled
  *
  * @access private
  * @param string $locale
  * @param string $filename
  * @param string $requestedContext
  *
  * @return bool The operation status, true or false
  */
 function loadTranslationFile($locale, $filename, $requestedContext)
 {
     // First try for current charset
     $charset = eZTextCodec::internalCharset();
     $tsTimeStamp = false;
     $ini = eZINI::instance();
     $checkMTime = $ini->variable('RegionalSettings', 'TranslationCheckMTime') === 'enabled';
     if (!$this->RootCache) {
         $roots = array($ini->variable('RegionalSettings', 'TranslationRepository'));
         $extensionBase = eZExtension::baseDirectory();
         $translationExtensions = $ini->variable('RegionalSettings', 'TranslationExtensions');
         foreach ($translationExtensions as $translationExtension) {
             $extensionPath = $extensionBase . '/' . $translationExtension . '/translations';
             if (!$checkMTime || file_exists($extensionPath)) {
                 $roots[] = $extensionPath;
             }
         }
         $this->RootCache = array('roots' => $roots);
     } else {
         $roots = $this->RootCache['roots'];
         if (isset($this->RootCache['timestamp'])) {
             $tsTimeStamp = $this->RootCache['timestamp'];
         }
     }
     // Load cached translations if possible
     if ($this->UseCache == true) {
         if (!$tsTimeStamp) {
             $expiry = eZExpiryHandler::instance();
             $globalTsTimeStamp = $expiry->getTimestamp(self::EXPIRY_KEY, 0);
             $localeTsTimeStamp = $expiry->getTimestamp(self::EXPIRY_KEY . '-' . $locale, 0);
             $tsTimeStamp = max($globalTsTimeStamp, $localeTsTimeStamp);
             if ($checkMTime && $tsTimeStamp < time()) {
                 // iterate over each known TS file, and get the highest timestamp
                 // this value will be used to check for cache validity
                 foreach ($roots as $root) {
                     $path = eZDir::path(array($root, $locale, $charset, $filename));
                     if (file_exists($path)) {
                         $timestamp = filemtime($path);
                         if ($timestamp > $tsTimeStamp) {
                             $tsTimeStamp = $timestamp;
                         }
                     } else {
                         $path = eZDir::path(array($root, $locale, $filename));
                         if (file_exists($path)) {
                             $timestamp = filemtime($path);
                             if ($timestamp > $tsTimeStamp) {
                                 $tsTimeStamp = $timestamp;
                             }
                         }
                     }
                 }
             }
             $this->RootCache['timestamp'] = $tsTimeStamp;
         }
         $key = 'cachecontexts';
         if ($this->HasRestoredCache or eZTranslationCache::canRestoreCache($key, $tsTimeStamp)) {
             eZDebug::accumulatorStart('tstranslator_cache_load', 'tstranslator', 'TS cache load');
             if (!$this->HasRestoredCache) {
                 if (!eZTranslationCache::restoreCache($key)) {
                     $this->BuildCache = true;
                 }
                 $contexts = eZTranslationCache::contextCache($key);
                 if (!is_array($contexts)) {
                     $contexts = array();
                 }
                 $this->HasRestoredCache = $contexts;
             } else {
                 $contexts = $this->HasRestoredCache;
             }
             if (!$this->BuildCache) {
                 $contextName = $requestedContext;
                 if (!isset($this->CachedMessages[$contextName])) {
                     eZDebug::accumulatorStart('tstranslator_context_load', 'tstranslator', 'TS context load');
                     if (eZTranslationCache::canRestoreCache($contextName, $tsTimeStamp)) {
                         if (!eZTranslationCache::restoreCache($contextName)) {
                             $this->BuildCache = true;
                         }
                         $this->CachedMessages[$contextName] = eZTranslationCache::contextCache($contextName);
                         foreach ($this->CachedMessages[$contextName] as $key => $msg) {
                             $this->Messages[$key] = $msg;
                         }
                     }
                     eZDebug::accumulatorStop('tstranslator_context_load');
                 }
             }
             eZDebugSetting::writeNotice('i18n-tstranslator', "Loading cached translation", __METHOD__);
             eZDebug::accumulatorStop('tstranslator_cache_load');
             if (!$this->BuildCache) {
                 return true;
             }
         }
         eZDebugSetting::writeNotice('i18n-tstranslator', "Translation cache has expired. Will rebuild it from source.", __METHOD__);
         $this->BuildCache = true;
     }
     $status = false;
     // first process country translation files
     // then process country variation translation files
     $localeParts = explode('@', $locale);
     $triedPaths = array();
     $loadedPaths = array();
     $ini = eZINI::instance("i18n.ini");
     $fallbacks = $ini->variable('TranslationSettings', 'FallbackLanguages');
     foreach ($localeParts as $localePart) {
         $localeCodeToProcess = isset($localeCodeToProcess) ? $localeCodeToProcess . '@' . $localePart : $localePart;
         // array with alternative subdirs to check
         $alternatives = array(array($localeCodeToProcess, $charset, $filename), array($localeCodeToProcess, $filename));
         if (isset($fallbacks[$localeCodeToProcess]) && $fallbacks[$localeCodeToProcess]) {
             if ($fallbacks[$localeCodeToProcess] === 'eng-GB') {
                 $fallbacks[$localeCodeToProcess] = 'untranslated';
             }
             $alternatives[] = array($fallbacks[$localeCodeToProcess], $charset, $filename);
             $alternatives[] = array($fallbacks[$localeCodeToProcess], $filename);
         }
         foreach ($roots as $root) {
             if (!file_exists($root)) {
                 continue;
             }
             unset($path);
             foreach ($alternatives as $alternative) {
                 $pathParts = $alternative;
                 array_unshift($pathParts, $root);
                 $pathToTry = eZDir::path($pathParts);
                 $triedPaths[] = $pathToTry;
                 if (file_exists($pathToTry)) {
                     $path = $pathToTry;
                     break;
                 }
             }
             if (!isset($path)) {
                 continue;
             }
             eZDebug::accumulatorStart('tstranslator_load', 'tstranslator', 'TS load');
             $doc = new DOMDocument('1.0', 'utf-8');
             $success = $doc->load($path);
             if (!$success) {
                 eZDebug::writeWarning("Unable to load XML from file {$path}", __METHOD__);
                 continue;
             }
             if (!$this->validateDOMTree($doc)) {
                 eZDebug::writeWarning("XML text for file {$path} did not validate", __METHOD__);
                 continue;
             }
             $loadedPaths[] = $path;
             $status = true;
             $treeRoot = $doc->documentElement;
             $children = $treeRoot->childNodes;
             for ($i = 0; $i < $children->length; $i++) {
                 $child = $children->item($i);
                 if ($child->nodeType == XML_ELEMENT_NODE) {
                     if ($child->tagName == "context") {
                         $this->handleContextNode($child);
                     }
                 }
             }
             eZDebug::accumulatorStop('tstranslator_load');
         }
     }
     eZDebugSetting::writeDebug('i18n-tstranslator', implode(PHP_EOL, $triedPaths), __METHOD__ . ': tried paths');
     eZDebugSetting::writeDebug('i18n-tstranslator', implode(PHP_EOL, $loadedPaths), __METHOD__ . ': loaded paths');
     // Save translation cache
     if ($this->UseCache == true && $this->BuildCache == true) {
         eZDebug::accumulatorStart('tstranslator_store_cache', 'tstranslator', 'TS store cache');
         if (eZTranslationCache::contextCache('cachecontexts') == null) {
             $contexts = array_keys($this->CachedMessages);
             eZTranslationCache::setContextCache('cachecontexts', $contexts);
             eZTranslationCache::storeCache('cachecontexts');
             $this->HasRestoredCache = $contexts;
         }
         foreach ($this->CachedMessages as $contextName => $context) {
             if (eZTranslationCache::contextCache($contextName) == null) {
                 eZTranslationCache::setContextCache($contextName, $context);
             }
             eZTranslationCache::storeCache($contextName);
         }
         $this->BuildCache = false;
         eZDebug::accumulatorStop('tstranslator_store_cache');
     }
     return $status;
 }
예제 #22
0
 function domString($domDocument)
 {
     $ini = eZINI::instance();
     $xmlCharset = $ini->variable('RegionalSettings', 'ContentXMLCharset');
     if ($xmlCharset == 'enabled') {
         $charset = eZTextCodec::internalCharset();
     } else {
         if ($xmlCharset == 'disabled') {
             $charset = true;
         } else {
             $charset = $xmlCharset;
         }
     }
     if ($charset !== true) {
         $charset = eZCharsetInfo::realCharsetCode($charset);
     }
     $domString = $domDocument->saveXML();
     return $domString;
 }
예제 #23
0
                 $dom = new DOMDocument('1.0', 'utf-8');
                 if ($dom->loadXML($xmlText)) {
                     $OriginalFilename = $dom->getElementsByTagName('OriginalFilename')->item(0)->textContent;
                     $FileType = $dom->getElementsByTagName('Type')->item(0)->textContent;
                     $Filename = $dom->getElementsByTagName('Filename')->item(0)->textContent;
                     if (file_exists(eZSys::wwwDir() . $Filename)) {
                         $fileAttachments[] = array(eZSys::wwwDir() . $Filename, $OriginalFilename, $FileType);
                     }
                 }
             }
         }
     }
     if (count($fileAttachments) != 0) {
         $mime_boundary = "==Multipart_Boundary_" . md5(time());
         //Plain Text part of Message
         $message = "--{$mime_boundary}\n" . "Content-Type: text/html; " . eZTextCodec::internalCharset() . "\n" . "Content-Transfer-Encoding: 8bit\n\n";
         //Form Result
         $message .= $templateResult;
         //Attachment(s) part of message
         foreach ($fileAttachments as $attacharray) {
             $filedata = chunk_split(base64_encode(eZFile::getContents($attacharray[0])));
             $message .= "\n\n\n--{$mime_boundary}\n" . "Content-Type: " . $attacharray[2] . ";\n" . " name=\"" . $attacharray[1] . "\"\n" . "Content-Transfer-Encoding: base64\n" . "Content-Disposition: inline;\n" . " filename=\"" . $attacharray[1] . "\"\n\n" . $filedata . "\n";
         }
         $message .= "--{$mime_boundary}--\n\n\n";
         $templateResult = $message;
         $mail->setContentType("multipart/mixed;boundary={$mime_boundary}", false, false, false);
     }
     //END ENHANCED BINARY EXTENSION MAIL CODE ADDITION
     $mail->setBody($templateResult);
     $mailResult = eZMailTransport::send($mail);
 }
 static function strtolower($text)
 {
     //We need to detect our internal charset
     if (self::$charset === null) {
         self::$charset = eZTextCodec::internalCharset();
     }
     //First try to use mbstring
     if (extension_loaded('mbstring')) {
         return mb_strtolower($text, self::$charset);
     } else {
         // Fall back if mbstring is not available
         $char = eZCharTransform::instance();
         return $char->transformByGroup($text, 'lowercase');
     }
 }
예제 #25
0
파일: ezpdf.php 프로젝트: nottavi/ezpublish
    function modify( $tpl, $operatorName, $operatorParameters, $rootNamespace, $currentNamespace, &$operatorValue, $namedParameters, $placement )
    {
        $config = eZINI::instance( 'pdf.ini' );

        switch ( $namedParameters['operation'] )
        {
            case 'toc':
            {
                $operatorValue = '<C:callTOC';

                if ( count( $operatorParameters ) > 1 )
                {
                    $params = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );

                    $operatorValue .= isset( $params['size'] ) ? ':size:'. implode(',', $params['size'] ) : '';
                    $operatorValue .= isset( $params['dots'] ) ? ':dots:'. $params['dots'] : '';
                    $operatorValue .= isset( $params['contentText'] ) ? ':contentText:'. $params['contentText'] : '';
                    $operatorValue .= isset( $params['indent'] ) ? ':indent:'. implode(',', $params['indent'] ) : '';

                }

                $operatorValue .= '>';
                eZDebug::writeNotice( 'PDF: Generating TOC', __METHOD__ );
            } break;

            case 'set_font':
            {
                $params = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );

                $operatorValue = '<ezCall:callFont';

                foreach ( $params as $key => $value )
                {
                    if ( $key == 'colorCMYK' )
                    {
                        $operatorValue .= ':cmyk:' . implode( ',', $value );
                    }
                    else if ( $key == 'colorRGB' )
                    {
                        $operatorValue .= ':cmyk:' . implode( ',', eZMath::rgbToCMYK2( $value[0]/255,
                                                                                       $value[1]/255,
                                                                                       $value[2]/255 ) );
                    }
                    else
                    {
                        $operatorValue .= ':' . $key . ':' . $value;
                    }
                }
                $operatorValue .= '>';

                eZDebug::writeNotice( 'PDF: Changed font.' );
            } break;

            case 'table':
            {
                $operatorValue = '<ezGroup:callTable';

                if ( count( $operatorParameters > 2 ) )
                {
                    $tableSettings = $tpl->elementValue( $operatorParameters[2], $rootNamespace, $currentNamespace );

                    if ( is_array( $tableSettings ) )
                    {
                        foreach( array_keys( $tableSettings ) as $key )
                        {
                            switch( $key )
                            {
                                case 'headerCMYK':
                                case 'cellCMYK':
                                case 'textCMYK':
                                case 'titleCellCMYK':
                                case 'titleTextCMYK':
                                {
                                    $operatorValue .= ':' . $key . ':' . implode( ',', $tableSettings[$key] );
                                } break;

                                default:
                                {
                                    $operatorValue .= ':' . $key . ':' . $tableSettings[$key];
                                } break;
                            }
                        }
                    }
                }

                $operatorValue .= '>';

                $rows = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );

                $rows = str_replace( array( ' ', "\t", "\r\n", "\n" ),
                                                          '',
                                                          $rows );
                $httpCharset = eZTextCodec::internalCharset();
                $outputCharset = $config->hasVariable( 'PDFGeneral', 'OutputCharset' )
                                 ? $config->variable( 'PDFGeneral', 'OutputCharset' )
                                 : 'iso-8859-1';
                $codec = eZTextCodec::instance( $httpCharset, $outputCharset );
                // Convert current text to $outputCharset (by default iso-8859-1)
                $rows = $codec->convertString( $rows );

                $operatorValue .= urlencode( $rows );

                $operatorValue .= '</ezGroup:callTable><C:callNewLine>';

                eZDebug::writeNotice( 'PDF: Added table to PDF', __METHOD__ );
            } break;

            case 'header':
            {
                $header = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );

                $header['text'] = str_replace( array( ' ', "\t", "\r\n", "\n" ),
                                               '',
                                               $header['text'] );

                $operatorValue = '<ezCall:callHeader:level:'. $header['level'] .':size:'. $header['size'];

                if ( isset( $header['align'] ) )
                {
                    $operatorValue .= ':justification:'. $header['align'];
                }

                if ( isset( $header['font'] ) )
                {
                    $operatorValue .= ':fontName:'. $header['font'];
                }

                $operatorValue .= ':label:'. rawurlencode( $header['text'] );

                $operatorValue .= '><C:callNewLine>'. $header['text'] .'</ezCall:callHeader><C:callNewLine>';

                eZDebug::writeNotice( 'PDF: Added header: '. $header['text'] .', size: '. $header['size'] .
                                      ', align: '. $header['align'] .', level: '. $header['level'],
                                      __METHOD__ );
            } break;

            case 'create':
            {
                $this->createPDF();
            } break;

            case 'new_line':
            case 'newline':  // Deprecated
            {
                $operatorValue = '<C:callNewLine>';
            } break;

            case 'new_page':
            case 'newpage':  // Deprecated
            {
                $operatorValue = '<C:callNewPage><C:callNewLine>';

                eZDebug::writeNotice( 'PDF: New page', __METHOD__ );
            } break;

            case 'image':
            {
                $image = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );

                $width = isset( $image['width'] ) ? $image['width']: 100;
                $height = isset( $image['height'] ) ? $image['height']: 100;

                $operatorValue = '<C:callImage:src:'. rawurlencode( $image['src'] ) .':width:'. $width .':height:'. $height;

                if ( isset( $image['static'] ) )
                {
                    $operatorValue .= ':static:' . $image['static'];
                }

                if ( isset ( $image['x'] ) )
                {
                    $operatorValue .= ':x:' . $image['x'];
                }

                if ( isset( $image['y'] ) )
                {
                    $operatorValue .= ':y:' . $image['y'];
                }

                if ( isset( $image['dpi'] ) )
                {
                    $operatorValue .= ':dpi:' . $image['dpi'];
                }

                if ( isset( $image['align'] ) ) // left, right, center, full
                {
                    $operatorValue .= ':align:' . $image['align'];
                }

                $operatorValue .= '>';

                eZDebug::writeNotice( 'PDF: Added Image '.$image['src'].' to PDF file', __METHOD__ );
            } break;

            case 'anchor':
            {
                $name = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );

                $operatorValue = '<C:callAnchor:'. $name['name'] .':FitH:>';
                eZDebug::writeNotice( 'PDF: Added anchor: '.$name['name'], __METHOD__ );
            } break;

            case 'link': // external link
            {
                $link = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );

                $link['text'] = str_replace( '&quot;',
                                             '"',
                                             $link['text'] );

                $operatorValue = '<c:alink:'. rawurlencode( $link['url'] ) .'>'. $link['text'] .'</c:alink>';
                eZDebug::writeNotice( 'PDF: Added link: '. $link['text'] .', url: '.$link['url'], __METHOD__ );
            } break;

            case 'stream':
            {
                $this->PDF->ezStream();
            }

            case 'close':
            {
                $filename = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );

                eZDir::mkdir( eZDir::dirpath( $filename ), false, true );

                $file = eZClusterFileHandler::instance( $filename );
                $file->storeContents( $this->PDF->ezOutput(), 'viewcache', 'pdf' );

                eZDebug::writeNotice( 'PDF file closed and saved to '. $filename, __METHOD__ );
            } break;

            case 'strike':
            {
                $text = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );
                $operatorValue = '<c:strike>'. $text .'</c:strike>';
                eZDebug::writeNotice( 'Striked text added to PDF: "'. $text .'"', __METHOD__ );
            } break;

            /* usage : execute/add text to pdf file, pdf(execute,<text>) */
            case 'execute':
            {
                $text = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );

                if ( count ( $operatorParameters ) > 2 )
                {
                    $options = $tpl->elementValue( $operatorParameters[2], $rootNamespace, $currentNamespace );

                    $size = isset( $options['size'] ) ? $options['size'] : $config->variable( 'PDFGeneral', 'Format' );
                    $orientation = isset( $options['orientation'] ) ? $options['orientation'] : $config->variable( 'PDFGeneral', 'Orientation' );

                    $this->createPDF( $size, $orientation );
                }
                else
                {
                    $this->createPDF( $config->variable( 'PDFGeneral', 'Format' ), $config->variable( 'PDFGeneral', 'Orientation' ) );
                }

                $text = str_replace( array( ' ', "\n", "\t" ), '', $text );
                $httpCharset = eZTextCodec::internalCharset();
                $outputCharset = $config->hasVariable( 'PDFGeneral', 'OutputCharset' )
                                 ? $config->variable( 'PDFGeneral', 'OutputCharset' )
                                 : 'iso-8859-1';
                $codec = eZTextCodec::instance( $httpCharset, $outputCharset );
                // Convert current text to $outputCharset (by default iso-8859-1)
                $text = $codec->convertString( $text );

                $this->PDF->ezText( $text );
                eZDebug::writeNotice( 'Execute text in PDF, length: "'. strlen( $text ) .'"', __METHOD__ );
            } break;

            case 'page_number':
            case 'pageNumber':
            {
                $numberDesc = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );

                if ( isset( $numberDesc['identifier'] ) )
                {
                    $identifier = $numberDesc['identifier'];
                }
                else
                {
                    $identifier = 'main';
                }

                if ( isset( $numberDesc['start'] ) )
                {
                    $operatorValue = '<C:callStartPageCounter:start:'. $numberDesc['start'] .':identifier:'. $identifier .'>';
                }
                else if ( isset( $numberDesc['stop'] ) )
                {
                    $operatorValue = '<C:callStartPageCounter:stop:1:identifier:'. $identifier .'>';
                }
            } break;

            /* usage {pdf( line, hash( x1, <x>, y1, <y>, x2, <x2>, y2, <y2>, pages, <all|current>, thickness, <1..100>,  ) )} */
            case 'line':
            {
                $lineDesc = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );

                if ( isset( $lineDesc['pages']) and
                     $lineDesc['pages'] == 'all' )
                {
                    $operatorValue = '<ezGroup:callLine';
                }
                else
                {
                    $operatorValue = '<C:callDrawLine';
                }

                $operatorValue .= ':x1:' . $lineDesc['x1'];
                $operatorValue .= ':x2:' . $lineDesc['x2'];
                $operatorValue .= ':y1:' . $lineDesc['y1'];
                $operatorValue .= ':y2:' . $lineDesc['y2'];

                $operatorValue .= ':thickness:' . ( isset( $lineDesc['thickness'] ) ? $lineDesc['thickness'] : '1' );

                $operatorValue .= '>';

                if ( $lineDesc['pages'] == 'all' )
                {
                    $operatorValue .= '___</ezGroup:callLine>';
                }

                return $operatorValue;
            } break;

            case 'footer_block':
            case 'header_block':
            {
                $frameDesc = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );

                $operatorValue = '<ezGroup:callBlockFrame';
                $operatorValue .= ':location:'. $namedParameters['operation'];
                $operatorValue .= '>';

                if ( isset( $frameDesc['block_code'] ) )
                {
                    $httpCharset = eZTextCodec::internalCharset();
                    $outputCharset = $config->hasVariable( 'PDFGeneral', 'OutputCharset' )
                                 ? $config->variable( 'PDFGeneral', 'OutputCharset' )
                                 : 'iso-8859-1';
                    $codec = eZTextCodec::instance( $httpCharset, $outputCharset );
                    // Convert current text to $outputCharset (by default iso-8859-1)
                    $frameDesc['block_code'] = $codec->convertString( $frameDesc['block_code'] );
                    $operatorValue .= urlencode( $frameDesc['block_code'] );
                }

                $operatorValue .= '</ezGroup:callBlockFrame>';

                eZDebug::writeNotice( 'PDF: Added Block '.$namedParameters['operation'] .': '.$operatorValue, __METHOD__ );
                return $operatorValue;

            } break;

            /* deprecated */
            case 'footer':
            case 'frame_header':
            {
                $frameDesc = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );

                $operatorValue  = '<ezGroup:callFrame';
                $operatorValue .= ':location:'. $namedParameters['operation'];

                if ( $namedParameters['operation'] == 'footer' )
                {
                    $frameType = 'Footer';
                }
                else if( $namedParameters['operation'] == 'frame_header' )
                {
                    $frameType = 'Header';
                }

                if ( isset( $frameDesc['align'] ) )
                {
                    $operatorValue .= ':justification:'. $frameDesc['align'];
                }

                if ( isset( $frameDesc['page'] ) )
                {
                    $operatorValue .= ':page:'. $frameDesc['page'];
                }
                else
                {
                    $operatorValue .= ':page:all';
                }

                $operatorValue .= ':newline:' . ( isset( $frameDesc['newline'] ) ? $frameDesc['newline'] : 0 );

                $operatorValue .= ':pageOffset:';
                if ( isset( $frameDesc['pageOffset'] ) )
                {
                    $operatorValue .= $frameDesc['pageOffset'];
                }
                else
                {
                    $operatorValue .= $this->Config->variable( $frameType, 'PageOffset' );
                }

                if ( isset( $frameDesc['size'] ) )
                {
                    $operatorValue .= ':size:'. $frameDesc['size'];
                }

                if ( isset( $frameDesc['font'] ) )
                {
                    $operatorValue .= ':font:'. $frameDesc['font'];
                }

                $operatorValue .= '>';

                if ( isset( $frameDesc['text'] ) )
                {
                    $httpCharset = eZTextCodec::internalCharset();
                    $outputCharset = $config->hasVariable( 'PDFGeneral', 'OutputCharset' )
                                 ? $config->variable( 'PDFGeneral', 'OutputCharset' )
                                 : 'iso-8859-1';
                    $codec = eZTextCodec::instance( $httpCharset, $outputCharset );
                    // Convert current text to $outputCharset (by default iso-8859-1)
                    $frameDesc['text'] = $codec->convertString( $frameDesc['text'] );
                    $operatorValue .= urlencode( $frameDesc['text'] );
                }

                $operatorValue .= '</ezGroup:callFrame>';

                if ( isset( $frameDesc['margin'] ) )
                {
                    $operatorValue .= '<C:callFrameMargins';

                    $operatorValue .= ':identifier:'. $namedParameters['operation'];

                    $operatorValue .= ':topMargin:';
                    if ( isset( $frameDesc['margin']['top'] ) )
                    {
                        $operatorValue .= $frameDesc['margin']['top'];
                    }
                    else
                    {
                        $operatorValue .= $this->Config->variable( $frameType, 'TopMargin' );
                    }

                    $operatorValue .= ':bottomMargin:';
                    if ( isset( $frameDesc['margin']['bottom'] ) )
                    {
                        $operatorValue .= $frameDesc['margin']['bottom'];
                    }
                    else
                    {
                        $operatorValue .= $this->Config->variable( $frameType, 'BottomMargin' );
                    }

                    $operatorValue .= ':leftMargin:';
                    if ( isset( $frameDesc['margin']['left'] ) )
                    {
                        $operatorValue .= $frameDesc['margin']['left'];
                    }
                    else
                    {
                        $operatorValue .= $this->Config->variable( $frameType, 'LeftMargin' );
                    }

                    $operatorValue .= ':rightMargin:';
                    if ( isset( $frameDesc['margin']['right'] ) )
                    {
                        $operatorValue .= $frameDesc['margin']['right'];
                    }
                    else
                    {
                        $operatorValue .= $this->Config->variable( $frameType, 'RightMargin' );
                    }

                    $operatorValue .= ':height:';
                    if ( isset( $frameDesc['margin']['height'] ) )
                    {
                        $operatorValue .= $frameDesc['margin']['height'];
                    }
                    else
                    {
                        $operatorValue .= $this->Config->variable( $frameType, 'Height' );
                    }

                    $operatorValue .= '>';
                }

                if ( isset( $frameDesc['line'] ) )
                {
                    $operatorValue .= '<C:callFrameLine';
                    $operatorValue .= ':location:'. $namedParameters['operation'];

                    $operatorValue .= ':margin:';
                    if( isset( $frameDesc['line']['margin'] ) )
                    {
                        $operatorValue .= $frameDesc['line']['margin'];
                    }
                    else
                    {
                        $operatorValue .= $this->Config->variable( $frameType, 'LineMargin' );
                    }

                    if ( isset( $frameDesc['line']['leftMargin'] ) )
                    {
                        $operatorValue .= ':leftMargin:'. $frameDesc['line']['leftMargin'];
                    }
                    if ( isset( $frameDesc['line']['rightMargin'] ) )
                    {
                        $operatorValue .= ':rightMargin:'. $frameDesc['line']['rightMargin'];
                    }

                    $operatorValue .= ':pageOffset:';
                    if ( isset( $frameDesc['line']['pageOffset'] ) )
                    {
                        $operatorValue .= $frameDesc['line']['pageOffset'];
                    }
                    else
                    {
                        $operatorValue .= $this->Config->variable( $frameType, 'PageOffset' );
                    }

                    $operatorValue .= ':page:';
                    if ( isset( $frameDesc['line']['page'] ) )
                    {
                        $operatorValue .= $frameDesc['line']['page'];
                    }
                    else
                    {
                        $operatorValue .= $this->Config->variable( $frameType, 'Page' );
                    }

                    $operatorValue .= ':thickness:';
                    if ( isset( $frameDesc['line']['thickness'] ) )
                    {
                        $operatorValue .= $frameDesc['line']['thickness'];
                    }
                    else
                    {
                        $operatorValue .= $this->Config->variable( $frameType, 'LineThickness' );
                    }
                    $operatorValue .= '>';
                }

                eZDebug::writeNotice( 'PDF: Added frame '.$frameType .': '.$operatorValue, __METHOD__ );
            } break;

            case 'frontpage':
            {
                $pageDesc = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );

                $align = isset( $pageDesc['align'] ) ? $pageDesc['align'] : 'center';
                $text = isset( $pageDesc['text'] ) ? $pageDesc['text'] : '';
                $top_margin = isset( $pageDesc['top_margin'] ) ? $pageDesc['top_margin'] : 100;

                $operatorValue = '<ezGroup:callFrontpage:justification:'. $align .':top_margin:'. $top_margin;

                if ( isset( $pageDesc['size'] ) )
                {
                    $operatorValue .= ':size:'. $pageDesc['size'];
                }

                $text = str_replace( array( ' ', "\t", "\r\n", "\n" ),
                                     '',
                                     $text );
                $httpCharset = eZTextCodec::internalCharset();
                $outputCharset = $config->hasVariable( 'PDFGeneral', 'OutputCharset' )
                             ? $config->variable( 'PDFGeneral', 'OutputCharset' )
                             : 'iso-8859-1';
                $codec = eZTextCodec::instance( $httpCharset, $outputCharset );
                // Convert current text to $outputCharset (by default iso-8859-1)
                $text = $codec->convertString( $text );

                $operatorValue .= '>'. urlencode( $text ) .'</ezGroup:callFrontpage>';

                eZDebug::writeNotice( 'Added content to frontpage: '. $operatorValue, __METHOD__ );
            } break;

            /* usage: pdf(set_margin( hash( left, <left_margin>,
                                            right, <right_margin>,
                                            x, <x offset>,
                                            y, <y offset> )))
            */
            case 'set_margin':
            {
                $operatorValue = '<C:callSetMargin';
                $options = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );

                foreach( array_keys( $options ) as $key )
                {
                    $operatorValue .= ':' . $key . ':' . $options[$key];
                }

                $operatorValue .= '>';

                eZDebug::writeNotice( 'Added new margin/offset setup: ' . $operatorValue );

                return $operatorValue;
            } break;

            /* add keyword to pdf document */
            case 'keyword':
            {
                $text = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );

                $text = str_replace( array( ' ', "\n", "\t" ), '', $text );
                $httpCharset = eZTextCodec::internalCharset();
                $outputCharset = $config->hasVariable( 'PDFGeneral', 'OutputCharset' )
                             ? $config->variable( 'PDFGeneral', 'OutputCharset' )
                             : 'iso-8859-1';
                $codec = eZTextCodec::instance( $httpCharset, $outputCharset );
                // Convert current text to $outputCharset (by default iso-8859-1)
                $text = $codec->convertString( $text );

                $operatorValue = '<C:callKeyword:'. rawurlencode( $text ) .'>';
            } break;

            /* add Keyword index to pdf document */
            case 'createIndex':
            case 'create_index':
            {
                $operatorValue = '<C:callIndex>';

                eZDebug::writeNotice( 'Adding Keyword index to PDF', __METHOD__ );
            } break;

            case 'ul':
            {
                $text = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );
                if ( count( $operatorParameters ) > 2 )
                {
                    $params = $tpl->elementValue( $operatorParameters[2], $rootNamespace, $currentNamespace );
                }
                else
                {
                    $params = array();
                }

                if ( isset( $params['rgb'] ) )
                {
                    $params['rgb'] = eZMath::normalizeColorArray( $params['rgb'] );
                    $params['cmyk'] = eZMath::rgbToCMYK2( $params['rgb'][0]/255,
                                                          $params['rgb'][1]/255,
                                                          $params['rgb'][2]/255 );
                }

                if ( !isset( $params['cmyk'] ) )
                {
                    $params['cmyk'] = eZMath::rgbToCMYK2( 0, 0, 0 );
                }
                if ( !isset( $params['radius'] ) )
                {
                    $params['radius'] = 2;
                }
                if ( !isset ( $params['pre_indent'] ) )
                {
                    $params['pre_indent'] = 0;
                }
                if ( !isset ( $params['indent'] ) )
                {
                    $params['indent'] = 2;
                }
                if ( !isset ( $params['yOffset'] ) )
                {
                    $params['yOffset'] = -1;
                }

                $operatorValue = '<C:callCircle' .
                     ':pages:current' .
                     ':x:-1' .
                     ':yOffset:' . $params['yOffset'] .
                     ':y:-1' .
                     ':indent:' . $params['indent'] .
                     ':pre_indent:' . $params['pre_indent'] .
                     ':radius:' . $params['radius'] .
                     ':cmyk:' . implode( ',', $params['cmyk'] ) .
                     '>';

                $operatorValue .= '<C:callSetMargin' .
                     ':delta_left:' . ( $params['indent'] + $params['radius'] * 2 + $params['pre_indent'] ) .
                     '>';

                $operatorValue .= $text;

                $operatorValue .= '<C:callSetMargin' .
                     ':delta_left:' . -1 * ( $params['indent'] + $params['radius'] * 2 + $params['pre_indent'] ) .
                     '>';
            } break;

            case 'filled_circle':
            {
                $operatorValue = '';
                $options = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );

                if ( !isset( $options['pages'] ) )
                {
                    $options['pages'] = 'current';
                }

                if ( !isset( $options['x'] ) )
                {
                    $options['x'] = -1;
                }

                if ( !isset( $options['y'] ) )
                {
                    $options['y'] = -1;
                }

                if ( isset( $options['rgb'] ) )
                {
                    $options['rgb'] = eZMath::normalizeColorArray( $options['rgb'] );
                    $options['cmyk'] = eZMath::rgbToCMYK2( $options['rgb'][0]/255,
                                                           $options['rgb'][1]/255,
                                                           $options['rgb'][2]/255 );
                }

                $operatorValue = '<C:callCircle' .
                     ':pages:' . $options['pages'] .
                     ':x:' . $options['x'] .
                     ':y:' . $options['y'] .
                     ':radius:' . $options['radius'];

                if ( isset( $options['cmyk'] ) )
                {
                    $operatorValue .= ':cmyk:' . implode( ',', $options['cmyk'] );
                }

                $operatorValue .= '>';

                eZDebug::writeNotice( 'PDF Added circle: ' . $operatorValue );

                return $operatorValue;
            } break;

            case 'rectangle':
            {
                $operatorValue = '';
                $options = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );

                if ( !isset( $options['pages'] ) )
                {
                    $options['pages'] = 'current';
                }
                if ( !isset( $options['line_width'] ) )
                {
                    $options['line_width'] = 1;
                }
                if ( !isset( $options['round_corner'] ) )
                {
                    $options['round_corner'] = false;
                }

                $operatorValue = '<C:callRectangle';
                foreach ( $options as $key => $value )
                {
                    if ( $key == 'rgb' )
                    {
                        $options['rgb'] = eZMath::normalizeColorArray( $options['rgb'] );
                        $operatorValue .= ':cmyk:' . implode( ',',  eZMath::rgbToCMYK2( $options['rgb'][0]/255,
                                                                                        $options['rgb'][1]/255,
                                                                                        $options['rgb'][2]/255 ) );
                    }
                    else if ( $key == 'cmyk' )
                    {
                        $operatorValue .= ':cmyk:' . implode( ',', $value );
                    }
                    else
                    {
                        $operatorValue .= ':' . $key . ':' . $value;
                    }
                }
                $operatorValue .= '>';

                eZDebug::writeNotice( 'PDF Added rectangle: ' . $operatorValue );

                return $operatorValue;
            } break;

            /* usage: pdf( filled_rectangle, hash( 'x', <x offset>, 'y' => <y offset>, 'width' => <width>, 'height' => <height>,
                                                    'pages', <'all'|'current'|odd|even>, (supported, current)
                                                    'rgb', array( <r>, <g>, <b> ),
                                                    'cmyk', array( <c>, <m>, <y>, <k> ),
                                                    'rgbTop', array( <r>, <b>, <g> ),
                                                    'rgbBottom', array( <r>, <b>, <g> ),
                                                    'cmykTop', array( <c>, <m>, <y>, <k> ),
                                                    'cmykBottom', array( <c>, <m>, <y>, <k> ) ) ) */
            case 'filled_rectangle':
            {
                $operatorValue = '';
                $options = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );

                if ( !isset( $options['pages'] ) )
                {
                    $options['pages'] = 'current';
                }

                if ( isset( $options['rgb'] ) )
                {
                    $options['rgb'] = eZMath::normalizeColorArray( $options['rgb'] );
                    $options['cmyk'] = eZMath::rgbToCMYK2( $options['rgb'][0]/255,
                                                           $options['rgb'][1]/255,
                                                           $options['rgb'][2]/255 );
                }

                if ( isset( $options['cmyk'] ) )
                {
                    $options['cmykTop'] = $options['cmyk'];
                    $options['cmykBottom'] = $options['cmyk'];
                }

                if ( !isset( $options['cmykTop'] ) )
                {
                    if ( isset( $options['rgbTop'] ) )
                    {
                        $options['rgbTop'] = eZMath::normalizeColorArray( $options['rgbTop'] );
                        $options['cmykTop'] = eZMath::rgbToCMYK2( $options['rgbTop'][0]/255,
                                                                  $options['rgbTop'][1]/255,
                                                                  $options['rgbTop'][2]/255 );
                    }
                    else
                    {
                        $options['cmykTop'] = eZMath::rgbToCMYK2( 0, 0, 0 );
                    }
                }

                if ( !isset( $options['cmykBottom'] ) )
                {
                    if ( isset( $options['rgbBottom'] ) )
                    {
                        $options['rgbBottom'] = eZMath::normalizeColorArray( $options['rgbBottom'] );
                        $options['cmykBottom'] = eZMath::rgbToCMYK2( $options['rgbBottom'][0]/255,
                                                                     $options['rgbBottom'][1]/255,
                                                                     $options['rgbBottom'][2]/255 );
                    }
                    else
                    {
                        $options['cmykBottom'] = eZMath::rgbToCMYK2( 0, 0, 0 );
                    }
                }

                if ( !isset( $options['pages'] ) )
                {
                    $options['pages'] = 'current';
                }

                $operatorValue = '<C:callFilledRectangle' .
                     ':pages:' . $options['pages'] .
                     ':x:' . $options['x'] .
                     ':y:' . $options['y'] .
                     ':width:' . $options['width'] .
                     ':height:' . $options['height'] .
                     ':cmykTop:' . implode( ',', $options['cmykTop'] ) .
                     ':cmykBottom:' . implode( ',', $options['cmykBottom'] ) .
                     '>';

                eZDebug::writeNotice( 'Added rectangle: ' . $operatorValue );
            } break;

            /* usage : pdf(text, <text>, array( 'font' => <fontname>, 'size' => <fontsize> )) */
            case 'text':
            {
                $text = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );

                $operatorValue = '';
                $changeFont = false;

                if ( count( $operatorParameters ) >= 3)
                {
                    $textSettings = $tpl->elementValue( $operatorParameters[2], $rootNamespace, $currentNamespace );

                    if ( isset( $textSettings ) )
                    {
                        $operatorValue .= '<ezCall:callText';
                        $changeFont = true;

                        if ( isset( $textSettings['font'] ) )
                        {
                            $operatorValue .= ':font:'. $textSettings['font'];
                        }

                        if ( isset( $textSettings['size'] ) )
                        {
                            $operatorValue .= ':size:'. $textSettings['size'];
                        }

                        if ( isset( $textSettings['align'] ) )
                        {
                            $operatorValue .= ':justification:'. $textSettings['align'];
                        }

                        if ( isset( $textSettings['rgb'] ) )
                        {
                            $textSettings['cmyk'] = eZMath::rgbToCMYK2( $textSettings['rgb'][0]/255,
                                                                        $textSettings['rgb'][1]/255,
                                                                        $textSettings['rgb'][2]/255 );
                        }

                        if ( isset( $textSettings['cmyk'] ) )
                        {
                            $operatorValue .= ':cmyk:' . implode( ',', $textSettings['cmyk'] );
                        }

                        $operatorValue .= '>';
                    }
                }

                $operatorValue .= $text;
                if ( $changeFont )
                {
                    $operatorValue .= '</ezCall:callText>';
                }

            } break;

            case 'text_box':
            {
                $parameters = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );

                $operatorValue = '<ezGroup:callTextBox';

                foreach( array_keys( $parameters ) as $key )
                {
                    if ( $key != 'text' )
                    {
                        $operatorValue .= ':' . $key . ':' . urlencode( $parameters[$key] );
                    }
                }

                $httpCharset = eZTextCodec::internalCharset();
                $outputCharset = $config->hasVariable( 'PDFGeneral', 'OutputCharset' )
                             ? $config->variable( 'PDFGeneral', 'OutputCharset' )
                             : 'iso-8859-1';
                $codec = eZTextCodec::instance( $httpCharset, $outputCharset );
                // Convert current text to $outputCharset (by default iso-8859-1)
                $parameters['text'] = $codec->convertString( $parameters['text'] );

                $operatorValue .= '>';
                $operatorValue .= urlencode( $parameters['text'] );
                $operatorValue .= '</ezGroup:callTextBox>';

                return $operatorValue;
            } break;

            case 'text_frame':
            {
                $text = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );

                $operatorValue = '';
                $changeFont = false;

                if ( count( $operatorParameters ) >= 3)
                {
                    $textSettings = $tpl->elementValue( $operatorParameters[2], $rootNamespace, $currentNamespace );

                    if ( isset( $textSettings ) )
                    {
                        $operatorValue .= '<ezGroup:callTextFrame';
                        $changeFont = true;

                        foreach ( array_keys( $textSettings ) as $key ) //settings, padding (left, right, top, bottom), textcmyk, framecmyk
                        {
                            if ( $key == 'frameCMYK' )
                            {
                                $operatorValue .= ':frameCMYK:' . implode( ',', $textSettings['frameCMYK'] );
                            }
                            else if ( $key == 'frameRGB' )
                            {
                                $operatorValue .= ':frameCMYK:' . implode( ',', eZMath::rgbToCMYK2( $textSettings['frameRGB'][0]/255,
                                                                                                    $textSettings['frameRGB'][1]/255,
                                                                                                    $textSettings['frameRGB'][2]/255 ) );
                            }
                            else if ( $key == 'textCMYK' )
                            {
                                $operatorValue .= ':textCMYK:' . implode( ',', $textSettings['textCMYK'] );
                            }
                            else if ( $key == 'textRGB' )
                            {
                                $operatorValue .= ':textCMYK:' . implode( ',', eZMath::rgbToCMYK2( $textSettings['textRGB'][0]/255,
                                                                                                   $textSettings['textRGB'][1]/255,
                                                                                                   $textSettings['textRGB'][2]/255 ) );
                            }
                            else
                            {
                                $operatorValue .= ':' . $key . ':' . $textSettings[$key];
                            }
                        }

                        $httpCharset = eZTextCodec::internalCharset();
                        $outputCharset = $config->hasVariable( 'PDFGeneral', 'OutputCharset' )
                                     ? $config->variable( 'PDFGeneral', 'OutputCharset' )
                                     : 'iso-8859-1';
                        $codec = eZTextCodec::instance( $httpCharset, $outputCharset );
                        // Convert current text to $outputCharset (by default iso-8859-1)
                        $text = $codec->convertString( $text );

                        $operatorValue .= '>' . urlencode( $text ) . '</ezGroup::callTextFrame>';

                    }
                }

                eZDebug::writeNotice( 'Added TextFrame: ' . $operatorValue );
            } break;

            default:
            {
                eZDebug::writeError( 'PDF operation "'. $namedParameters['operation'] .'" undefined', __METHOD__ );
            }

        }

    }