function eZMutex($name)
 {
     $this->Name = md5($name);
     $mutexPath = eZDir::path(array(eZSys::cacheDirectory(), 'ezmutex'));
     eZDir::mkdir($mutexPath, false, true);
     $this->FileName = eZDir::path(array($mutexPath, $this->Name));
     $this->MetaFileName = eZDir::path(array($mutexPath, $this->Name . '_meta'));
 }
 /**
  * tmp dir for mail parser
  *    ezvardir / cjw_newsletter/tmp/
  * @return string dirname
  */
 public function getTmpDir($createDirIfNotExists = true)
 {
     $varDir = eZSys::varDirectory();
     // $dir = $varDir . "/cjw_newsletter/tmp/";
     $dir = eZDir::path(array($varDir, 'cjw_newsletter', 'tmp'));
     $fileSep = eZSys::fileSeparator();
     $filePath = $dir . $fileSep;
     if ($createDirIfNotExists === true) {
         if (!file_exists($filePath)) {
             eZDir::mkdir($filePath, false, true);
         }
     }
     return $filePath;
 }
 public static function clearCache()
 {
     eZDebug::writeNotice("Clear calendar taxonomy cache", __METHOD__);
     $ini = eZINI::instance();
     if ($ini->hasVariable('SiteAccessSettings', 'RelatedSiteAccessList') && ($relatedSiteAccessList = $ini->variable('SiteAccessSettings', 'RelatedSiteAccessList'))) {
         if (!is_array($relatedSiteAccessList)) {
             $relatedSiteAccessList = array($relatedSiteAccessList);
         }
         $relatedSiteAccessList[] = $GLOBALS['eZCurrentAccess']['name'];
         $siteAccesses = array_unique($relatedSiteAccessList);
     } else {
         $siteAccesses = $ini->variable('SiteAccessSettings', 'AvailableSiteAccessList');
     }
     $cacheBaseDir = eZDir::path(array(eZSys::cacheDirectory(), self::cacheDirectory()));
     $fileHandler = eZClusterFileHandler::instance();
     $fileHandler->fileDeleteByDirList($siteAccesses, $cacheBaseDir, '');
     $fileHandler = eZClusterFileHandler::instance($cacheBaseDir);
     $fileHandler->purge();
 }
 /**
  *
  * http://maps.googleapis.com/maps/api/staticmap?zoom=13&size=600x300&maptype=roadmap&markers=color:blue|{first_set( $attribute.content.latitude, '0.0')},{first_set( $attribute.content.longitude, '0.0')}
  * @param array $parameters
  * @param eZContentObjectAttribute $attribute
  * @return string
  */
 public static function gmapStaticImage(array $parameters, eZContentObjectAttribute $attribute, $extraCacheFileNameStrings = array())
 {
     $cacheParameters = array(serialize($parameters));
     $cacheFile = $attribute->attribute('id') . implode('-', $extraCacheFileNameStrings) . '-' . md5(implode('-', $cacheParameters)) . '.cache';
     $extraPath = eZDir::filenamePath($attribute->attribute('id'));
     $cacheDir = eZDir::path(array(eZSys::cacheDirectory(), 'gmap_static', $extraPath));
     // cacenllo altri file con il medesimo attributo
     $fileList = array();
     $deleteItems = eZDir::recursiveList($cacheDir, $cacheDir, $fileList);
     foreach ($fileList as $file) {
         if ($file['type'] == 'file' && $file['name'] !== $cacheFile) {
             unlink($file['path'] . '/' . $file['name']);
         }
     }
     $cachePath = eZDir::path(array($cacheDir, $cacheFile));
     $args = compact('parameters', 'attribute');
     $cacheFile = eZClusterFileHandler::instance($cachePath);
     $result = $cacheFile->processCache(array('OCOperatorsCollectionsTools', 'gmapStaticImageRetrieve'), array('OCOperatorsCollectionsTools', 'gmapStaticImageGenerate'), null, null, $args);
     return $result;
 }
 /**
  * Constructs an empty CjwNewsletterLog instance
  *
  * This constructor is private as this class should be used as a
  * singleton. Use the getInstance() method instead to get an ezcLog instance.
  *
  * @param boolean $isCliMode
  * @return void
  */
 protected function __construct($isCliMode = false)
 {
     if ($isCliMode === true) {
         $this->isCliMode = true;
     }
     $this->reset();
     $log = $this;
     // "var/log"
     $ini = eZINI::instance();
     $varDir = eZSys::varDirectory();
     $iniLogDir = $ini->variable('FileSettings', 'LogDir');
     $permissions = octdec($ini->variable('FileSettings', 'LogFilePermissions'));
     $logDir = eZDir::path(array($varDir, $iniLogDir));
     $logNamePostfix = '';
     // Debug enabled
     $cjwNewsletterIni = eZINI::instance('cjw_newsletter.ini');
     if ($cjwNewsletterIni->variable('DebugSettings', 'Debug') == 'enabled') {
         $this->debug = true;
     }
     if ($isCliMode === true) {
         $logNamePostfix = 'cli_';
     }
     // Create the writers
     $generalFilename = "cjw_newsletter_" . $logNamePostfix . "general.log";
     $errorFilename = "cjw_newsletter_" . $logNamePostfix . "error.log";
     $writeAll = new ezcLogUnixFileWriter($logDir, $generalFilename);
     $writeErrors = new ezcLogUnixFileWriter($logDir, $errorFilename);
     // Check file permissions
     foreach (array($generalFilename, $errorFilename) as $file) {
         $path = eZDir::path(array($logDir, $file));
         if (substr(decoct(fileperms($path)), 2) !== $permissions) {
             @chmod($path, $permissions);
         }
     }
     $errorFilter = new ezcLogFilter();
     $errorFilter->severity = ezcLog::ERROR;
     $log->getMapper()->appendRule(new ezcLogFilterRule($errorFilter, $writeErrors, true));
     $log->getMapper()->appendRule(new ezcLogFilterRule(new ezcLogFilter(), $writeAll, true));
 }
    /**
     * @param string $cluster
     * @param string $path
     * @param bool $clusterizedPath
     * @return bool|string
     */
    public static function clusterFilePath($cluster, $path, $clusterizedPath = true)
    {
        if (!$cluster)
        {
            $cluster = 'default';
        }

        $staticPath = eZDir::path(array(StaticData::directory(), $cluster, $path));
        $fullPath   = self::fileExists($staticPath);

        if ($fullPath)
        {
            return $clusterizedPath ? $fullPath : $staticPath;
        }

        if ($cluster != 'default')
        {
            return self::clusterFilePath('default', $path);
        }

        return false;
    }
 /**
  * Clears all static cache for a site
  * Removers all static cache, but not the static cache directory itself.
  *
  * Currently, this function only supports 'combined_host_url'
  *
  */
 static function clearStaticCache()
 {
     $ini = eZINI::instance('staticcache.ini');
     $storageDir = $ini->variable('CacheSettings', 'StaticStorageDir');
     // Check that we have combined_host_url hostmatching
     $siteIni = eZINI::instance();
     $matchType = $siteIni->variable('SiteAccessSettings', 'MatchOrder');
     if ($matchType !== 'combined_host_url') {
         throw new Exception('combined_host_url required for this workflow');
     }
     global $eZCurrentAccess;
     $siteAccess = $eZCurrentAccess['name'];
     //Get hostname part from siteaccess name (exclude for instance _eng or _admin)
     if (strpos($siteAccess, '_') === false) {
         $hostName = $siteAccess;
     } else {
         $hostName = substr($siteAccess, 0, strpos($siteAccess, '_'));
     }
     $staticCacheDir = eZDir::path(array($storageDir, $hostName));
     // Sanity checking, make sure we don't remove everyones static cache.
     if ($staticCacheDir == $storageDir) {
         throw new Exception("Failed to find correct static cache directory : {$staticCacheDir} \n");
     }
     $dirs = scandir($staticCacheDir);
     foreach ($dirs as $dir) {
         if ($dir !== '.' && $dir !== '..') {
             $fullPath = eZDir::path(array($staticCacheDir, $dir));
             if (is_dir($fullPath)) {
                 ezcBaseFile::removeRecursive($fullPath);
             } else {
                 if (!unlink($fullPath)) {
                     throw new ezsfFileCouldNotRemoveException($fullPath);
                 }
             }
         }
     }
 }
function eZSetupCheckExecutable($type)
{
    $http = eZHTTPTool::instance();
    $filesystemType = eZSys::filesystemType();
    $envSeparator = eZSys::envSeparator();
    $programs = eZSetupConfigVariableArray($type, $filesystemType . '_Executable');
    $systemSearchPaths = explode($envSeparator, eZSys::path(true));
    $additionalSearchPaths = eZSetupConfigVariableArray($type, $filesystemType . '_SearchPaths');
    $excludePaths = eZSetupConfigVariableArray($type, $filesystemType . '_ExcludePaths');
    $imageIniPath = eZSetupImageConfigVariableArray('ShellSettings', 'ConvertPath');
    /*
    We save once entered extra path in the persistent data list
    to keep it within setup steps.
    
    This trick is needed, for example, in "registration" step,
    where user has no chance to enter extra path again
    due to missing input field for this purpose.
    */
    // compute extra path
    $extraPath = array();
    if ($http->hasPostVariable($type . '_ExtraPath')) {
        $GLOBALS['eZSetupCheckExecutable_' . $type . '_ExtraPath'] = $http->postVariable($type . '_ExtraPath');
        $extraPath = explode($envSeparator, $http->postVariable($type . '_ExtraPath'));
    } else {
        if (isset($GLOBALS['eZSetupCheckExecutable_' . $type . '_ExtraPath'])) {
            $extraPath = explode($envSeparator, $GLOBALS['eZSetupCheckExecutable_' . $type . '_ExtraPath']);
        }
    }
    // if extra path was given in any way
    if ($extraPath) {
        // remove program from path name if entered
        foreach ($extraPath as $path) {
            foreach ($programs as $program) {
                if (strpos($path, $program) == strlen($path) - strlen($program)) {
                    $extraPath[] = substr($path, strpos($path, $program));
                }
            }
        }
    }
    $searchPaths = array_merge($systemSearchPaths, $additionalSearchPaths, $extraPath, $imageIniPath);
    $result = false;
    $correctPath = false;
    $correctProgram = false;
    foreach ($programs as $program) {
        foreach ($searchPaths as $path) {
            $pathProgram = eZDir::path(array($path, $program));
            if (file_exists($pathProgram)) {
                if ($filesystemType == 'unix') {
                    $relativePath = $path;
                    if (preg_match("#^/(.+)\$#", $path, $matches)) {
                        $relativePath = $matches[1];
                    }
                    $relativePath = eZDir::cleanPath($relativePath);
                } else {
                    $relativePath = $path;
                    if (preg_match("#^[a-zA-Z]:[/\\\\](.+)\$#", $path, $matches)) {
                        $relativePath = $matches[1];
                    }
                    $relativePath = eZDir::cleanPath($relativePath);
                }
                $exclude = false;
                foreach ($excludePaths as $excludePath) {
                    $excludePath = strtolower($excludePath);
                    $match = strtolower($program . "@" . $relativePath);
                    if ($match == $excludePath) {
                        $exclude = true;
                        break;
                    } else {
                        if ($relativePath == $excludePath) {
                            $exclude = true;
                            break;
                        }
                    }
                }
                if ($exclude) {
                    continue;
                }
                if (function_exists("is_executable")) {
                    if (is_executable($pathProgram)) {
                        $result = true;
                        $correctPath = $path;
                        $correctProgram = $program;
                        break;
                    }
                } else {
                    // Windows system
                    $result = true;
                    $correctPath = $path;
                    $correctProgram = $program;
                    break;
                }
            }
        }
        if ($result) {
            break;
        }
    }
    $extraPathAsString = implode($envSeparator, $extraPath);
    return array('result' => $result, 'persistent_data' => array('path' => array('value' => $correctPath), 'program' => array('value' => $correctProgram), 'extra_path' => array('value' => $extraPathAsString, 'merge' => TRUE), 'result' => array('value' => $result)), 'env_separator' => $envSeparator, 'filesystem_type' => $filesystemType, 'extra_path' => $extraPath, 'correct_path' => $correctPath, 'system_search_path' => $systemSearchPaths, 'additional_search_path' => $additionalSearchPaths);
}
    static function generatePHPCodeChildren($useComments, $php, $tpl, &$nodeChildren, &$resourceData, &$parameters, $currentParameters)
    {
        foreach ($nodeChildren as $node) {
            $newNode = false;
            $nodeType = $node[0];
            if ($nodeType > eZTemplate::NODE_USER_CUSTOM) {
                // Do custom nodes
            } else {
                if ($nodeType > eZTemplate::NODE_INTERNAL) {
                    // Do custom internal nodes
                    if ($nodeType == eZTemplate::NODE_INTERNAL_CODE_PIECE) {
                        $codePiece = $node[1];
                        $spacing = $currentParameters['spacing'];
                        if (isset($node[2]['spacing'])) {
                            $spacing += $node[2]['spacing'];
                        }
                        $php->addCodePiece($codePiece, array('spacing' => $spacing));
                    } else {
                        if ($nodeType == eZTemplate::NODE_INTERNAL_WARNING) {
                            $warningText = $php->thisVariableText($node[1], 23, 0, false);
                            $warningLabel = false;
                            $warningLabelText = '';
                            if (isset($node[2])) {
                                $warningLabelText = $php->thisVariableText($node[2], 0, 0, false);
                            }
                            $spacing = $currentParameters['spacing'];
                            if (isset($node[3]['spacing'])) {
                                $spacing += $node[3]['spacing'];
                            }
                            $placementText = 'false';
                            if (isset($node[4])) {
                                $placementText = $php->thisVariableText($node[4], 0, 0, false);
                            }
                            $php->addCodePiece("\$tpl->warning( " . $warningLabelText . ", " . $warningText . ", " . $placementText . " );", array('spacing' => $spacing));
                        } else {
                            if ($nodeType == eZTemplate::NODE_INTERNAL_ERROR) {
                                $errorText = $php->thisVariableText($node[1], 21, 0, false);
                                $errorLabel = false;
                                $errorLabelText = '';
                                if (isset($node[2])) {
                                    $errorLabelText = $php->thisVariableText($node[2], 0, 0, false);
                                }
                                $spacing = $currentParameters['spacing'];
                                if (isset($node[3]['spacing'])) {
                                    $spacing += $node[3]['spacing'];
                                }
                                $placementText = 'false';
                                if (isset($node[4])) {
                                    $placementText = $php->thisVariableText($node[4], 0, 0, false);
                                }
                                $php->addCodePiece("\$tpl->error( " . $errorLabelText . ", " . $errorText . ", " . $placementText . " );", array('spacing' => $spacing));
                            } else {
                                if ($nodeType == eZTemplate::NODE_INTERNAL_OUTPUT_READ) {
                                    $variableName = $node[1];
                                    $spacing = $currentParameters['spacing'];
                                    if (isset($node[2]['spacing'])) {
                                        $spacing += $node[2]['spacing'];
                                    }
                                    $textName = eZTemplateCompiler::currentTextName($parameters);
                                    $assignmentType = $node[3];
                                    $assignmentText = $php->variableNameText($variableName, $assignmentType, $node[2]);
                                    $php->addCodePiece("{$assignmentText}\${$textName};", array('spacing' => $spacing));
                                } else {
                                    if ($nodeType == eZTemplate::NODE_INTERNAL_OUTPUT_ASSIGN) {
                                        $variableName = $node[1];
                                        $spacing = $currentParameters['spacing'];
                                        if (isset($node[2]['spacing'])) {
                                            $spacing += $node[2]['spacing'];
                                        }
                                        $textName = eZTemplateCompiler::currentTextName($parameters);
                                        $assignmentType = $node[3];
                                        $assignmentText = $php->variableNameText($textName, $assignmentType, $node[2]);
                                        $php->addCodePiece("{$assignmentText}\${$variableName};", array('spacing' => $spacing));
                                    } else {
                                        if ($nodeType == eZTemplate::NODE_INTERNAL_OUTPUT_INCREASE) {
                                            $spacing = $currentParameters['spacing'];
                                            if (isset($node[1]['spacing'])) {
                                                $spacing += $node[1]['spacing'];
                                            }
                                            $textName = eZTemplateCompiler::currentTextName($parameters);
                                            $php->addCodePiece("if " . ($resourceData['use-comments'] ? "/*TC:" . __LINE__ . "*/" : "") . "( !isset( \$textStack ) )\n" . "    \$textStack = array();\n" . "\$textStack[] = \${$textName};\n" . "\${$textName} = '';", array('spacing' => $spacing));
                                        } else {
                                            if ($nodeType == eZTemplate::NODE_INTERNAL_OUTPUT_DECREASE) {
                                                $spacing = $currentParameters['spacing'];
                                                if (isset($node[1]['spacing'])) {
                                                    $spacing += $node[1]['spacing'];
                                                }
                                                $textName = eZTemplateCompiler::currentTextName($parameters);
                                                $php->addCodePiece("\${$textName} = array_pop( \$textStack );", array('spacing' => $spacing));
                                            } else {
                                                if ($nodeType == eZTemplate::NODE_INTERNAL_OUTPUT_SPACING_INCREASE) {
                                                    $spacing = $node[1];
                                                    $currentParameters['spacing'] += $spacing;
                                                    continue;
                                                } else {
                                                    if ($nodeType == eZTemplate::NODE_INTERNAL_SPACING_DECREASE) {
                                                        $spacing = $node[1];
                                                        $currentParameters['spacing'] -= $spacing;
                                                        continue;
                                                    } else {
                                                        if ($nodeType == eZTemplate::NODE_INTERNAL_VARIABLE_SET) {
                                                            $variableName = $node[1];
                                                            $variableValue = $node[2];
                                                            $spacing = $currentParameters['spacing'];
                                                            if (isset($node[3]['spacing'])) {
                                                                $spacing += $node[3]['spacing'];
                                                            }
                                                            $php->addVariable($variableName, $variableValue, eZPHPCreator::VARIABLE_ASSIGNMENT, array('spacing' => $spacing));
                                                        } else {
                                                            if ($nodeType == eZTemplate::NODE_INTERNAL_VARIABLE_UNSET) {
                                                                $variableName = $node[1];
                                                                $spacing = $currentParameters['spacing'];
                                                                if (isset($node[2]['spacing'])) {
                                                                    $spacing += $node[2]['spacing'];
                                                                }
                                                                if (is_array($variableName)) {
                                                                    $namespace = $variableName[0];
                                                                    $namespaceScope = $variableName[1];
                                                                    $variableName = $variableName[2];
                                                                    $namespaceText = eZTemplateCompiler::generateMergeNamespaceCode($php, $tpl, $namespace, $namespaceScope, array('spacing' => $spacing), true);
                                                                    if (!is_string($namespaceText)) {
                                                                        $namespaceText = "\$namespace";
                                                                    }
                                                                    $variableNameText = $php->thisVariableText($variableName, 0, 0, false);
                                                                    if (isset($node[2]['remember_set']) and $node[2]['remember_set']) {
                                                                        $php->addCodePiece("if " . ($resourceData['use-comments'] ? "/*TC:" . __LINE__ . "*/" : "") . "( isset( \$setArray[{$namespaceText}][{$variableNameText}] ) )\n" . "{\n");
                                                                        $spacing += 4;
                                                                    }
                                                                    if (isset($node[2]['local-variable'])) {
                                                                        $php->addCodePiece("\$tpl->unsetLocalVariable( {$variableNameText}, {$namespaceText} );\n", array('spacing' => $spacing));
                                                                    } else {
                                                                        $php->addCodePiece("unset( \$vars[{$namespaceText}][{$variableNameText}] );", array('spacing' => $spacing));
                                                                    }
                                                                    if (isset($node[2]['remember_set']) and $node[2]['remember_set']) {
                                                                        $php->addCodePiece("\n}\n");
                                                                        $spacing -= 4;
                                                                    }
                                                                } else {
                                                                    $php->addVariableUnset($variableName, array('spacing' => $spacing));
                                                                }
                                                            } else {
                                                                if ($nodeType == eZTemplate::NODE_INTERNAL_RESOURCE_ACQUISITION || $nodeType == eZTemplate::NODE_OPTIMIZED_RESOURCE_ACQUISITION) {
                                                                    $resource = $node[1];
                                                                    $resourceObject = $tpl->resourceHandler($resource);
                                                                    if (!$resourceObject) {
                                                                        continue;
                                                                    }
                                                                    $spacing = $currentParameters['spacing'];
                                                                    if (isset($node[7]['spacing'])) {
                                                                        $spacing += $node[7]['spacing'];
                                                                    }
                                                                    $newRootNamespace = $node[8];
                                                                    $resourceVariableName = $node[9];
                                                                    $resourceFilename = isset($node[10]) ? $node[10] : false;
                                                                    /* We can only use fallback code if we know upfront which
                                                                     * template is included; it does not work if we are using
                                                                     * something from the ezobjectforwarder which makes the
                                                                     * uriMap an array */
                                                                    $useFallbackCode = true;
                                                                    $uriMap = $node[2];
                                                                    if (is_string($uriMap)) {
                                                                        $uriMap = array($uriMap);
                                                                    } else {
                                                                        $useFallbackCode = false;
                                                                    }
                                                                    $resourceMap = array();
                                                                    $hasCompiledCode = false;
                                                                    if (is_array($uriMap)) {
                                                                        foreach ($uriMap as $uriKey => $originalURI) {
                                                                            $uri = $originalURI;
                                                                            if ($resource) {
                                                                                $uri = $resource . ':' . $uri;
                                                                            }
                                                                            unset($tmpResourceData);
                                                                            $tmpResourceData = $tpl->resourceData($resourceObject, $uri, $node[1], $originalURI);
                                                                            $uriText = $php->thisVariableText($uri, 0, 0, false);
                                                                            $resourceCanCache = true;
                                                                            if (!$resourceObject->servesStaticData()) {
                                                                                $resourceCanCache = false;
                                                                            }
                                                                            if (!$tpl->isCachingAllowed()) {
                                                                                $resourceCanCache = false;
                                                                            }
                                                                            $tmpResourceData['text'] = null;
                                                                            $tmpResourceData['root-node'] = null;
                                                                            $tmpResourceData['compiled-template'] = false;
                                                                            $tmpResourceData['time-stamp'] = null;
                                                                            $tmpResourceData['key-data'] = null;
                                                                            $tmpResourceData['use-comments'] = eZTemplateCompiler::isCommentsEnabled();
                                                                            $subSpacing = 0;
                                                                            $hasResourceData = false;
                                                                            $savedLocale = setlocale(LC_CTYPE, null);
                                                                            if (isset($GLOBALS['eZTemplateCompilerResourceCache'][$tmpResourceData['template-filename']])) {
                                                                                $tmpFileName = $tmpResourceData['template-filename'];
                                                                                unset($tmpResourceData);
                                                                                $tmpResourceData = $GLOBALS['eZTemplateCompilerResourceCache'][$tmpFileName];
                                                                                $tmpResourceData['compiled-template'] = true;
                                                                                $tmpResourceData['use-comments'] = eZTemplateCompiler::isCommentsEnabled();
                                                                                $hasResourceData = true;
                                                                                $hasCompiledCode = true;
                                                                            } else {
                                                                                if ($useFallbackCode) {
                                                                                    // If we can use fallback code we don't need to compile the templates in advance
                                                                                    // Simply fake that it has been compiled by setting some variables
                                                                                    // Note: Yes this is a hack, but rewriting this code is not an easy task
                                                                                    if ($resourceObject->handleResource($tpl, $tmpResourceData, $node[4], $node[5])) {
                                                                                        $tmpResourceData['compiled-template'] = true;
                                                                                        $hasResourceData = true;
                                                                                        $hasCompiledCode = true;
                                                                                    }
                                                                                } else {
                                                                                    if ($resourceObject->handleResource($tpl, $tmpResourceData, $node[4], $node[5])) {
                                                                                        if (!$tmpResourceData['compiled-template'] and $tmpResourceData['root-node'] === null) {
                                                                                            $root =& $tmpResourceData['root-node'];
                                                                                            $root = array(eZTemplate::NODE_ROOT, false);
                                                                                            $templateText =& $tmpResourceData["text"];
                                                                                            $keyData = $tmpResourceData['key-data'];
                                                                                            $rootNamespace = '';
                                                                                            $tpl->parse($templateText, $root, $rootNamespace, $tmpResourceData);
                                                                                            $hasResourceData = false;
                                                                                        }
                                                                                        /* We always DO need to execute this part if we
                                                                                         * don't have any fallback code. If we can
                                                                                         * generate the fallback code we make the
                                                                                         * included template compile on demand */
                                                                                        if (!$tmpResourceData['compiled-template'] and $resourceCanCache and $tpl->canCompileTemplate($tmpResourceData, $node[5]) and !$useFallbackCode) {
                                                                                            $generateStatus = $tpl->compileTemplate($tmpResourceData, $node[5]);
                                                                                            // Time limit #2:
                                                                                            /* We reset the time limit to 60 seconds to
                                                                                             * ensure that remaining template has
                                                                                             * enough time to compile. However if time
                                                                                             * limit is unlimited (0) we leave it be */
                                                                                            $maxExecutionTime = ini_get('max_execution_time');
                                                                                            if ($maxExecutionTime != 0 && $maxExecutionTime < 60) {
                                                                                                @set_time_limit(60);
                                                                                            }
                                                                                            if ($generateStatus) {
                                                                                                $tmpResourceData['compiled-template'] = true;
                                                                                            }
                                                                                        }
                                                                                    }
                                                                                    $GLOBALS['eZTemplateCompilerResourceCache'][$tmpResourceData['template-filename']] =& $tmpResourceData;
                                                                                }
                                                                            }
                                                                            setlocale(LC_CTYPE, $savedLocale);
                                                                            $textName = eZTemplateCompiler::currentTextName($parameters);
                                                                            if ($tmpResourceData['compiled-template']) {
                                                                                $hasCompiledCode = true;
                                                                                //                            if ( !eZTemplateCompiler::isFallbackResourceCodeEnabled() )
                                                                                //                                $useFallbackCode = false;
                                                                                $keyData = $tmpResourceData['key-data'];
                                                                                $templatePath = $tmpResourceData['template-name'];
                                                                                $key = $resourceObject->cacheKey($keyData, $tmpResourceData, $templatePath, $node[5]);
                                                                                $cacheFileName = eZTemplateCompiler::compilationFilename($key, $tmpResourceData);
                                                                                $directory = eZTemplateCompiler::compilationDirectory();
                                                                                $phpScript = eZDir::path(array($directory, $cacheFileName));
                                                                                $phpScriptText = $php->thisVariableText($phpScript, 0, 0, false);
                                                                                $resourceMap[$uriKey] = array('key' => $uriKey, 'uri' => $uri, 'phpscript' => $phpScript);
                                                                            }
                                                                        }
                                                                    }
                                                                    if ($useComments) {
                                                                        $variablePlacement = $node[6];
                                                                        if ($variablePlacement) {
                                                                            $originalText = eZTemplateCompiler::fetchTemplatePiece($variablePlacement);
                                                                            $php->addComment("Resource Acquisition:", true, true, array('spacing' => $spacing));
                                                                            $php->addComment($originalText, true, true, array('spacing' => $spacing));
                                                                        }
                                                                    }
                                                                    if ($hasCompiledCode) {
                                                                        if ($resourceVariableName) {
                                                                            $phpScriptText = '$phpScript';
                                                                            $phpScriptArray = array();
                                                                            foreach ($resourceMap as $resourceMapItem) {
                                                                                $phpScriptArray[$resourceMapItem['key']] = $resourceMapItem['phpscript'];
                                                                            }
                                                                            if (!$resourceFilename) {
                                                                                $php->addVariable("phpScriptArray", $phpScriptArray, eZPHPCreator::VARIABLE_ASSIGNMENT, array('spacing' => $spacing));
                                                                                $resourceVariableNameText = "\${$resourceVariableName}";
                                                                                $php->addCodePiece("\$phpScript = isset( \$phpScriptArray[{$resourceVariableNameText}] ) ? \$phpScriptArray[{$resourceVariableNameText}] : false;\n", array('spacing' => $spacing));
                                                                            } else {
                                                                                $php->addVariable("phpScript", $phpScriptArray[$node[10]], eZPHPCreator::VARIABLE_ASSIGNMENT, array('spacing' => $spacing));
                                                                            }
                                                                            // The default is to only check if it exists
                                                                            $modificationCheckText = "file_exists( {$phpScriptText} )";
                                                                            if (eZTemplateCompiler::isDevelopmentModeEnabled()) {
                                                                                $modificationCheckText = "@filemtime( {$phpScriptText} ) > filemtime( {$uriText} )";
                                                                            }
                                                                            $php->addCodePiece("\$resourceFound = false;\nif " . ($resourceData['use-comments'] ? "/*TC:" . __LINE__ . "*/" : "") . "( {$phpScriptText} !== false and {$modificationCheckText} )\n{\n", array('spacing' => $spacing));
                                                                        } else {
                                                                            $php->addCodePiece("\$resourceFound = false;\n", array('spacing' => $spacing));
                                                                            $phpScript = $resourceMap[0]['phpscript'];
                                                                            $phpScriptText = $php->thisVariableText($phpScript, 0, 0, false);
                                                                            // Not sure where this should come from
                                                                            //                         if ( $resourceIndex > 0 )
                                                                            //                             $php->addCodePiece( "else " );
                                                                            // The default is to only check if it exists
                                                                            $modificationCheckText = "file_exists( {$phpScriptText} )";
                                                                            if (eZTemplateCompiler::isDevelopmentModeEnabled()) {
                                                                                $modificationCheckText = "@filemtime( {$phpScriptText} ) > filemtime( {$uriText} )";
                                                                            }
                                                                            $php->addCodePiece("if " . ($resourceData['use-comments'] ? "/*TC:" . __LINE__ . "*/" : "") . "( {$modificationCheckText} )\n{\n", array('spacing' => $spacing));
                                                                        }
                                                                        /* Generate code to do a namespace switch and includes the template */
                                                                        $code = "\$resourceFound = true;\n\$namespaceStack[] = array( \$rootNamespace, \$currentNamespace );\n";
                                                                        if ($newRootNamespace) {
                                                                            $newRootNamespaceText = $php->thisVariableText($newRootNamespace, 0, 0, false);
                                                                            $code .= "\$currentNamespace = \$rootNamespace = !\$currentNamespace ? {$newRootNamespaceText} : ( \$currentNamespace . ':' . {$newRootNamespaceText} );\n";
                                                                        } else {
                                                                            $code .= "\$rootNamespace = \$currentNamespace;\n";
                                                                        }
                                                                        $code .= "\$tpl->createLocalVariablesList();\n" . "\$tpl->appendTemplateFetch( {$uriText} );\n" . "include( '" . eZTemplateCompiler::TemplatePrefix() . "' . {$phpScriptText} );\n" . "\$tpl->unsetLocalVariables();\n" . "\$tpl->destroyLocalVariablesList();\n" . "list( \$rootNamespace, \$currentNamespace ) = array_pop( \$namespaceStack );\n";
                                                                        $php->addCodePiece($code, array('spacing' => $spacing + 4));
                                                                        if ($useFallbackCode) {
                                                                            $php->addCodePiece("}\nelse\n{\n    \$resourceFound = true;\n", array('spacing' => $spacing));
                                                                        } else {
                                                                            $php->addCodePiece("}\n", array('spacing' => $spacing));
                                                                        }
                                                                        $subSpacing = 4;
                                                                    } else {
                                                                        /* Yes, this is a hack, but it is required because
                                                                         * sometimes the generated nodes after this one emit an
                                                                         * else statement while there is no accompanied if */
                                                                        $php->addCodePiece("\nif " . ($resourceData['use-comments'] ? "/*TC:" . __LINE__ . "*/" : "") . "(false)\n{\n}\n");
                                                                    }
                                                                    /* The fallback code will be added if we need to process an
                                                                     * URI, this will also compile a template then. We need to
                                                                     * do the namespace switch manually here otherwise the
                                                                     * processed template will be run on the node from which
                                                                     * the template was included from. */
                                                                    if ($useFallbackCode) {
                                                                        $code = "\$resourceFound = true;\n\$namespaceStack[] = array( \$rootNamespace, \$currentNamespace );\n";
                                                                        if ($newRootNamespace) {
                                                                            $newRootNamespaceText = $php->thisVariableText($newRootNamespace, 0, 0, false);
                                                                            $code .= "\$currentNamespace = \$rootNamespace = !\$currentNamespace ? {$newRootNamespaceText} : ( \$currentNamespace . ':' . {$newRootNamespaceText} );\n";
                                                                        } else {
                                                                            $code .= "\$rootNamespace = \$currentNamespace;\n";
                                                                        }
                                                                        $php->addCodePiece($code);
                                                                        $php->addCodePiece("\$textElements = array();\n\$extraParameters = array();\n\$tpl->processURI( {$uriText}, true, \$extraParameters, \$textElements, \$rootNamespace, \$currentNamespace );\n\${$textName} .= implode( '', \$textElements );\n", array('spacing' => $spacing + $subSpacing));
                                                                        $php->addCodePiece("list( \$rootNamespace, \$currentNamespace ) = array_pop( \$namespaceStack );\n");
                                                                    }
                                                                    if ($hasCompiledCode and $useFallbackCode) {
                                                                        $php->addCodePiece("}\n", array('spacing' => $spacing));
                                                                    }
                                                                } else {
                                                                    if ($nodeType == eZTemplate::NODE_INTERNAL_NAMESPACE_CHANGE) {
                                                                        $variableData = $node[1];
                                                                        $spacing = $currentParameters['spacing'];
                                                                        if (isset($node[2]['spacing'])) {
                                                                            $spacing += $node[2]['spacing'];
                                                                        }
                                                                        $php->addCodePiece("\$namespaceStack[] = \$currentNamespace;\n", array('spacing' => $spacing));
                                                                        $php->addCodePiece('$currentNamespace .= ( $currentNamespace ? ":" : "" ) . \'' . $variableData[0][1] . '\';' . "\n", array('spacing' => $spacing));
                                                                    } else {
                                                                        if ($nodeType == eZTemplate::NODE_INTERNAL_NAMESPACE_RESTORE) {
                                                                            $spacing = $currentParameters['spacing'];
                                                                            if (isset($node[1]['spacing'])) {
                                                                                $spacing += $node[1]['spacing'];
                                                                            }
                                                                            $php->addCodePiece("\$currentNamespace = array_pop( \$namespaceStack );\n", array('spacing' => $spacing));
                                                                        } else {
                                                                            if ($nodeType == eZTemplate::NODE_OPTIMIZED_INIT) {
                                                                                $code = <<<END
\$node = ( array_key_exists( \$rootNamespace, \$vars ) and array_key_exists( "node", \$vars[\$rootNamespace] ) ) ? \$vars[\$rootNamespace]["node"] : null;
if ( is_object( \$node ) )
\$object = \$node->attribute( 'object' );
if ( isset( \$object ) && is_object( \$object ) )
\$nod_{$resourceData['uniqid']} = \$object->attribute( 'data_map' );
else
\$nod_{$resourceData['uniqid']} = false;
unset( \$node, \$object );

END;
                                                                                $php->addCodePiece($code);
                                                                                // Tell the rest of the system that we have create the nod_* variable
                                                                                $resourceData['node-object-cached'] = true;
                                                                            } else {
                                                                                eZDebug::writeWarning("Unknown internal template node type {$nodeType}, ignoring node for code generation", 'eZTemplateCompiler:generatePHPCodeChildren');
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else {
                    if ($nodeType == eZTemplate::NODE_ROOT) {
                        $children = $node[1];
                        if ($children) {
                            $newCurrentParameters = $currentParameters;
                            $newCurrentParameters['spacing'] += 4;
                            eZTemplateCompiler::generatePHPCodeChildren($useComments, $php, $tpl, $children, $resourceData, $parameters, $newCurrentParameters);
                        }
                        continue;
                    } else {
                        if ($nodeType == eZTemplate::NODE_TEXT) {
                            $text = $node[2];
                            if ($text != '') {
                                $variablePlacement = $node[3];
                                $originalText = eZTemplateCompiler::fetchTemplatePiece($variablePlacement);
                                if ($useComments) {
                                    $php->addComment("Text start:", true, true, array('spacing' => $currentParameters['spacing']));
                                    $php->addComment($originalText, true, true, array('spacing' => $currentParameters['spacing']));
                                    $php->addComment("Text end:", true, true, array('spacing' => $currentParameters['spacing']));
                                }
                                $php->addVariable(eZTemplateCompiler::currentTextName($parameters), $text, eZPHPCreator::VARIABLE_APPEND_TEXT, array('spacing' => $currentParameters['spacing']));
                            }
                            continue;
                        } else {
                            if ($nodeType == eZTemplate::NODE_VARIABLE) {
                                $variableAssignmentName = $node[1];
                                $variableData = $node[2];
                                $variablePlacement = $node[3];
                                $variableParameters = array();
                                if (isset($node[4]) and $node[4]) {
                                    $variableParameters = $node[4];
                                }
                                $variableOnlyExisting = isset($node[5]) ? $node[5] : false;
                                $variableOverWrite = isset($node[6]) ? $node[6] : false;
                                $rememberSet = isset($node[7]) ? $node[7] : false;
                                $spacing = $currentParameters['spacing'];
                                if (isset($variableParameters['spacing'])) {
                                    $spacing += $variableParameters['spacing'];
                                }
                                $variableParameters = array_merge(array('variable-name' => 'var', 'text-result' => true), $variableParameters);
                                $dataInspection = eZTemplateCompiler::inspectVariableData($tpl, $variableData, $variablePlacement, $resourceData);
                                $newNode = $node;
                                $newNode[1] = false;
                                $treatVariableDataAsNonObject = isset($variableParameters['treat-value-as-non-object']) && $variableParameters['treat-value-as-non-object'];
                                if ($useComments) {
                                    $php->addComment("Variable data: " . "Is constant: " . ($dataInspection['is-constant'] ? 'Yes' : 'No') . " Is variable: " . ($dataInspection['is-variable'] ? 'Yes' : 'No') . " Has attributes: " . ($dataInspection['has-attributes'] ? 'Yes' : 'No') . " Has operators: " . ($dataInspection['has-operators'] ? 'Yes' : 'No'), true, true, array('spacing' => $spacing));
                                    $originalText = eZTemplateCompiler::fetchTemplatePiece($variablePlacement);
                                    $php->addComment('{' . $originalText . '}', true, true, array('spacing' => $spacing));
                                }
                                $generatedVariableName = $variableParameters['variable-name'];
                                $assignVariable = false;
                                if ($variableAssignmentName !== false) {
                                    if (is_array($variableAssignmentName)) {
                                        $variableParameters['text-result'] = false;
                                        $assignVariable = true;
                                    } else {
                                        $generatedVariableName = $variableAssignmentName;
                                        $variableParameters['text-result'] = false;
                                    }
                                }
                                $isStaticElement = false;
                                $nodeElements = $node[2];
                                $knownTypes = array();
                                if (eZTemplateNodeTool::isStaticElement($nodeElements) and !$variableParameters['text-result']) {
                                    $variableText = $php->thisVariableText(eZTemplateNodeTool::elementStaticValue($nodeElements), 0, 0, false);
                                    $isStaticElement = true;
                                } else {
                                    if (eZTemplateNodeTool::isPHPVariableElement($nodeElements) and !$variableParameters['text-result']) {
                                        $variableText = '$' . eZTemplateNodeTool::elementStaticValue($nodeElements);
                                        $isStaticElement = true;
                                    } else {
                                        $variableText = "\${$generatedVariableName}";
                                        eZTemplateCompiler::generateVariableCode($php, $tpl, $node, $knownTypes, $dataInspection, array('spacing' => $spacing, 'variable' => $generatedVariableName, 'treat-value-as-non-object' => $treatVariableDataAsNonObject, 'counter' => 0), $resourceData);
                                    }
                                }
                                if ($variableParameters['text-result']) {
                                    $textName = eZTemplateCompiler::currentTextName($parameters);
                                    if (count($knownTypes) == 0 or in_array('objectproxy', $knownTypes)) {
                                        $php->addCodePiece("\${$textName} .= ( is_object( \${$generatedVariableName} ) ? compiledFetchText( \$tpl, \$rootNamespace, \$currentNamespace, false, \${$generatedVariableName} ) : \${$generatedVariableName} );" . ($resourceData['use-comments'] ? "/*TC:" . __LINE__ . "*/" : "") . "\n" . "unset( \${$generatedVariableName} );\n", array('spacing' => $spacing));
                                    } else {
                                        $php->addCodePiece("\${$textName} .= \${$generatedVariableName};\n" . "unset( \${$generatedVariableName} );\n", array('spacing' => $spacing));
                                    }
                                } else {
                                    if ($assignVariable) {
                                        $namespace = $variableAssignmentName[0];
                                        $namespaceScope = $variableAssignmentName[1];
                                        $variableName = $variableAssignmentName[2];
                                        $namespaceText = eZTemplateCompiler::generateMergeNamespaceCode($php, $tpl, $namespace, $namespaceScope, array('spacing' => $spacing), true);
                                        if (!is_string($namespaceText)) {
                                            $namespaceText = "\$namespace";
                                        }
                                        $variableNameText = $php->thisVariableText($variableName, 0, 0, false);
                                        $unsetVariableText = false;
                                        if ($variableOnlyExisting) {
                                            if (!$isStaticElement) {
                                                $unsetVariableText = "\n    unset( {$variableText} );";
                                            }
                                            $php->addCodePiece("if " . ($resourceData['use-comments'] ? "/*TC:" . __LINE__ . "*/" : "") . "( array_key_exists( {$namespaceText}, \$vars ) && array_key_exists( {$variableNameText}, \$vars[{$namespaceText}] ) )\n" . "{\n" . "    \$vars[{$namespaceText}][{$variableNameText}] = {$variableText};{$unsetVariableText}\n" . "}", array('spacing' => $spacing));
                                        } else {
                                            if ($variableOverWrite) {
                                                if (!$isStaticElement) {
                                                    $unsetVariableText = "\nunset( {$variableText} );";
                                                }
                                                if (isset($variableParameters['local-variable'])) {
                                                    $php->addCodePiece("if ( \$tpl->hasVariable( {$variableNameText}, {$namespaceText} ) )\n{\n");
                                                    // if the variable already exists
                                                    $php->addCodePiece("    \$tpl->warning( '" . eZTemplateDefFunction::DEF_FUNCTION_NAME . "', \"Variable '{$variableName}' is already defined.\", " . $php->thisVariableText($variablePlacement) . " );\n");
                                                    $php->addCodePiece("    \$tpl->setVariable( {$variableNameText}, {$variableText}, {$namespaceText} );\n}\nelse\n{\n");
                                                    $php->addCodePiece("    \$tpl->setLocalVariable( {$variableNameText}, {$variableText}, {$namespaceText} );\n}\n", array('spacing' => $spacing));
                                                } else {
                                                    $php->addCodePiece("\$vars[{$namespaceText}][{$variableNameText}] = {$variableText};{$unsetVariableText}", array('spacing' => $spacing));
                                                }
                                            } else {
                                                if ($rememberSet) {
                                                    if (!$isStaticElement) {
                                                        $unsetVariableText = "\n    unset( {$variableText} );";
                                                    }
                                                    $php->addCodePiece("if " . ($resourceData['use-comments'] ? "/*TC:" . __LINE__ . "*/" : "") . "( !isset( \$vars[{$namespaceText}][{$variableNameText}] ) )\n" . "{\n" . "    \$vars[{$namespaceText}][{$variableNameText}] = {$variableText};{$unsetVariableText}\n" . "    \$setArray[{$namespaceText}][{$variableNameText}] = true;\n" . "}\n", array('spacing' => $spacing));
                                                } else {
                                                    if (!$isStaticElement) {
                                                        $unsetVariableText = "\n    unset( {$variableText} );";
                                                    }
                                                    $php->addCodePiece("if " . ($resourceData['use-comments'] ? "/*TC:" . __LINE__ . "*/" : "") . "( !isset( \$vars[{$namespaceText}][{$variableNameText}] ) )\n{\n    \$vars[{$namespaceText}][{$variableNameText}] = {$variableText};{$unsetVariableText}\n}", array('spacing' => $spacing));
                                                }
                                            }
                                        }
                                    } else {
                                        if ($variableAssignmentName !== false and $isStaticElement) {
                                            $php->addCodePiece("\${$generatedVariableName} = {$variableText};", array('spacing' => $spacing));
                                        } else {
                                            if ($variableAssignmentName !== false and !$isStaticElement and !$treatVariableDataAsNonObject) {
                                                // Normal assignment from an expression, no need to anything extra
                                            }
                                        }
                                    }
                                }
                                unset($dataInspection);
                            } else {
                                if ($nodeType == eZTemplate::NODE_FUNCTION) {
                                    $functionChildren = $node[1];
                                    $functionName = $node[2];
                                    $functionParameters = $node[3];
                                    $functionPlacement = $node[4];
                                    $newNode = array($nodeType, false, $functionName, $functionParameters, $functionPlacement);
                                    $parameterText = 'No parameters';
                                    if ($functionParameters) {
                                        $parameterText = "Parameters: " . implode(', ', array_keys($functionParameters));
                                    }
                                    if ($useComments) {
                                        $php->addComment("Function: {$functionName}, {$parameterText}", true, true, array('spacing' => $currentParameters['spacing']));
                                        $originalText = eZTemplateCompiler::fetchTemplatePiece($functionPlacement);
                                        $php->addComment('{' . $originalText . '}', true, true, array('spacing' => $currentParameters['spacing']));
                                    }
                                    if (isset($node[5])) {
                                        $functionHook = $node[5];
                                        $functionHookCustomFunction = $functionHook['function'];
                                        if ($functionHookCustomFunction) {
                                            $functionHookCustomFunction = array_merge(array('add-function-name' => false, 'add-hook-name' => false, 'add-template-handler' => true, 'add-function-hook-data' => false, 'add-function-parameters' => true, 'add-function-placement' => false, 'add-calculated-namespace' => false, 'add-namespace' => true, 'add-input' => false, 'return-value' => false), $functionHookCustomFunction);
                                            if (!isset($parameters['hook-result-variable-counter'][$functionName])) {
                                                $parameters['hook-result-variable-counter'][$functionName] = 0;
                                            }
                                            if ($functionHookCustomFunction['return-value']) {
                                                $parameters['hook-result-variable-counter'][$functionName]++;
                                            }
                                            $hookResultName = $functionName . 'Result' . $parameters['hook-result-variable-counter'][$functionName];
                                            if ($functionHookCustomFunction['add-input']) {
                                                $parameters['hook-result-variable-counter'][$functionName]--;
                                            }
                                            $functionHookCustomFunctionName = $functionHookCustomFunction['name'];
                                            $codeText = '';
                                            if ($functionHookCustomFunction['return-value']) {
                                                $codeText = "\${$hookResultName} = ";
                                            }
                                            if ($functionHookCustomFunction['static']) {
                                                $hookClassName = $functionHookCustomFunction['class-name'];
                                                $codeText .= "{$hookClassName}::{$functionHookCustomFunctionName}( ";
                                            } else {
                                                $codeText .= "\$functionObject->{$functionHookCustomFunctionName}( ";
                                            }
                                            $codeTextLength = strlen($codeText);
                                            $functionNameText = $php->thisVariableText($functionName, 0, 0, false);
                                            $functionChildrenText = $php->thisVariableText($functionChildren, $codeTextLength, 0, false);
                                            $inputFunctionParameters = $functionParameters;
                                            if ($functionHookCustomFunction['add-calculated-namespace']) {
                                                unset($inputFunctionParameters['name']);
                                            }
                                            $functionParametersText = $php->thisVariableText($inputFunctionParameters, $codeTextLength, 0, false);
                                            $functionPlacementText = $php->thisVariableText($functionPlacement, $codeTextLength, 0, false);
                                            $functionHookText = $php->thisVariableText($functionHook, $codeTextLength, 0, false);
                                            $functionHookName = $functionHook['name'];
                                            $functionHookNameText = $php->thisVariableText($functionHookName, 0, 0, false);
                                            $codeParameters = array();
                                            if ($functionHookCustomFunction['add-function-name']) {
                                                $codeParameters[] = $functionNameText;
                                            }
                                            if ($functionHookCustomFunction['add-hook-name']) {
                                                $codeParameters[] = $functionHookNameText;
                                            }
                                            if ($functionHookCustomFunction['add-function-hook-data']) {
                                                $codeParameters[] = $functionHookText;
                                            }
                                            if ($functionHookCustomFunction['add-template-handler']) {
                                                $codeParameters[] = "\$tpl";
                                            }
                                            if ($functionHookCustomFunction['add-function-parameters']) {
                                                $codeParameters[] = $functionParametersText;
                                            }
                                            if ($functionHookCustomFunction['add-function-placement']) {
                                                $codeParameters[] = $functionPlacementText;
                                            }
                                            if ($functionHookCustomFunction['add-calculated-namespace']) {
                                                $name = '';
                                                if (isset($functionParameters['name'])) {
                                                    $nameParameter = $functionParameters['name'];
                                                    $nameInspection = eZTemplateCompiler::inspectVariableData($tpl, $nameParameter, $functionPlacement, $resourceData);
                                                    if ($nameInspection['is-constant'] and !$nameInspection['is-variable'] and !$nameInspection['has-attributes'] and !$nameInspection['has-operators']) {
                                                        $nameData = $nameParameter[0][1];
                                                        $nameText = $php->thisVariableText($nameData, 0, 0, false);
                                                        $php->addCodePiece("if ( \$currentNamespace != '' )\n    \$name = \$currentNamespace . ':' . {$nameText};\nelse\n    \$name = {$nameText};\n", array('spacing' => $currentParameters['spacing']));
                                                        $codeParameters[] = "\$name";
                                                    } else {
                                                        $persistence = array();
                                                        $knownTypes = array();
                                                        eZTemplateCompiler::generateVariableCode($php, $tpl, $nameParameter, $knownTypes, $nameInspection, $persistence, array('variable' => 'name', 'counter' => 0), $resourceData);
                                                        $php->addCodePiece("if " . ($resourceData['use-comments'] ? "/*TC:" . __LINE__ . "*/" : "") . "( \$currentNamespace != '' )\n{\n    if ( \$name != '' )\n        \$name = \"\$currentNamespace:\$name\";\n    else\n        \$name = \$currentNamespace;\n}\n", array('spacing' => $currentParameters['spacing']));
                                                        $codeParameters[] = "\$name";
                                                    }
                                                } else {
                                                    $codeParameters[] = "\$currentNamespace";
                                                }
                                            }
                                            if ($functionHookCustomFunction['add-namespace']) {
                                                $codeParameters[] = "\$rootNamespace, \$currentNamespace";
                                            }
                                            if ($functionHookCustomFunction['add-input']) {
                                                $codeParameters[] = "\${$hookResultName}";
                                            }
                                            $codeText .= implode(",\n" . str_repeat(' ', $codeTextLength), $codeParameters);
                                            $codeText .= " );\n";
                                            if ($functionHookCustomFunction['static']) {
                                                $hookFile = $functionHookCustomFunction['php-file'];
                                                $hookFileText = $php->thisVariableText($hookFile, 0, 0, false);
                                                $php->addCodePiece("include_once( {$hookFileText} );\n", array('spacing' => $currentParameters['spacing']));
                                            } else {
                                                $php->addCodePiece("\$functionObject = \$tpl->fetchFunctionObject( {$functionNameText} );\n", array('spacing' => $currentParameters['spacing']));
                                            }
                                            $php->addCodePiece($codeText, array('spacing' => $currentParameters['spacing']));
                                        } else {
                                            $functionNameText = $php->thisVariableText($functionName, 0, 0, false);
                                            $functionChildrenText = $php->thisVariableText($functionChildren, 52, 0, false);
                                            $functionParametersText = $php->thisVariableText($functionParameters, 52, 0, false);
                                            $functionPlacementText = $php->thisVariableText($functionPlacement, 52, 0, false);
                                            $functionHookText = $php->thisVariableText($functionHook, 52, 0, false);
                                            $functionHookName = $functionHook['name'];
                                            $functionHookNameText = $php->thisVariableText($functionHookName, 0, 0, false);
                                            $functionHookParameters = $functionHook['parameters'];
                                            $php->addCodePiece("\$functionObject = \$tpl->fetchFunctionObject( {$functionNameText} );\n\$hookResult = \$functionObject->templateHookProcess( {$functionNameText}, {$functionHookNameText},\n                                                    {$functionHookText},\n                                                    \$tpl,\n                                                    {$functionParametersText},\n                                                    {$functionPlacementText},\n                                                    \$rootNamespace, \$currentNamespace );\n", array('spacing' => $currentParameters['spacing']));
                                        }
                                    } else {
                                        $textName = eZTemplateCompiler::currentTextName($parameters);
                                        $functionNameText = $php->thisVariableText($functionName, 0, 0, false);
                                        $functionChildrenText = $php->thisVariableText($functionChildren, 22, 0, false);
                                        $functionParametersText = $php->thisVariableText($functionParameters, 22, 0, false);
                                        $functionPlacementText = $php->thisVariableText($functionPlacement, 22, 0, false);
                                        $php->addCodePiece("\$textElements = array();\n\$tpl->processFunction( {$functionNameText}, \$textElements,\n                       {$functionChildrenText},\n                       {$functionParametersText},\n                       {$functionPlacementText},\n                       \$rootNamespace, \$currentNamespace );\n\${$textName} .= implode( '', \$textElements );\n", array('spacing' => $currentParameters['spacing']));
                                    }
                                }
                            }
                        }
                    }
                }
            }
            $php->addSpace();
        }
    }
 function storeObjectAttribute($attribute)
 {
     $ini = eZINI::instance();
     // Delete compiled template
     $siteINI = eZINI::instance();
     if ($siteINI->hasVariable('FileSettings', 'CacheDir')) {
         $cacheDir = $siteINI->variable('FileSettings', 'CacheDir');
         if ($cacheDir[0] == "/") {
             $cacheDir = eZDir::path(array($cacheDir));
         } else {
             if ($siteINI->hasVariable('FileSettings', 'VarDir')) {
                 $varDir = $siteINI->variable('FileSettings', 'VarDir');
                 $cacheDir = eZDir::path(array($varDir, $cacheDir));
             }
         }
     } else {
         if ($siteINI->hasVariable('FileSettings', 'VarDir')) {
             $varDir = $siteINI->variable('FileSettings', 'VarDir');
             $cacheDir = $ini->variable('FileSettings', 'CacheDir');
             $cacheDir = eZDir::path(array($varDir, $cacheDir));
         } else {
             $cacheDir = eZSys::cacheDirectory();
         }
     }
     $compiledTemplateDir = $cacheDir . "/template/compiled";
     eZDir::unlinkWildcard($compiledTemplateDir . "/", "*pagelayout*.*");
     // Expire template block cache
     eZContentCacheManager::clearTemplateBlockCacheIfNeeded(false);
 }
Exemple #11
0
 static function rootCacheDirectory()
 {
     $internalCharset = eZTextCodec::internalCharset();
     $ini = eZINI::instance();
     $translationRepository = $ini->variable('RegionalSettings', 'TranslationRepository');
     $translationExtensions = $ini->variable('RegionalSettings', 'TranslationExtensions');
     $uniqueParts = array($internalCharset, $translationRepository, implode(';', $translationExtensions));
     $sharedTsCacheDir = $ini->hasVariable('RegionalSettings', 'SharedTranslationCacheDir') ? trim($ini->variable('RegionalSettings', 'SharedTranslationCacheDir')) : '';
     if ($sharedTsCacheDir !== '') {
         $rootCacheDirectory = eZDir::path(array($sharedTsCacheDir, md5(implode('-', $uniqueParts))));
     } else {
         $rootCacheDirectory = eZDir::path(array(eZSys::cacheDirectory(), 'translation', md5(implode('-', $uniqueParts))));
     }
     return $rootCacheDirectory;
 }
 static function generateViewCacheFile($user, $nodeID, $offset, $layout, $language, $viewMode, $viewParameters = false, $cachedViewPreferences = false, $viewCacheTweak = '')
 {
     $cacheNameExtra = '';
     $ini = eZINI::instance();
     if (!$language) {
         $language = false;
     }
     if (!$viewCacheTweak && $ini->hasVariable('ContentSettings', 'ViewCacheTweaks')) {
         $viewCacheTweaks = $ini->variable('ContentSettings', 'ViewCacheTweaks');
         if (isset($viewCacheTweaks[$nodeID])) {
             $viewCacheTweak = $viewCacheTweaks[$nodeID];
         } else {
             if (isset($viewCacheTweaks['global'])) {
                 $viewCacheTweak = $viewCacheTweaks['global'];
             }
         }
     }
     // should we use current siteaccess or let several siteaccesse share cache?
     if (strpos($viewCacheTweak, 'ignore_siteaccess_name') === false) {
         $currentSiteAccess = $GLOBALS['eZCurrentAccess']['name'];
     } else {
         $currentSiteAccess = $ini->variable('SiteSettings', 'DefaultAccess');
     }
     $cacheHashArray = array($nodeID, $viewMode, $language, $offset, $layout);
     // several user related cache tweaks
     if (strpos($viewCacheTweak, 'ignore_userroles') === false) {
         $cacheHashArray[] = implode('.', $user->roleIDList());
     }
     if (strpos($viewCacheTweak, 'ignore_userlimitedlist') === false) {
         $cacheHashArray[] = implode('.', $user->limitValueList());
     }
     if (strpos($viewCacheTweak, 'ignore_discountlist') === false) {
         $cacheHashArray[] = implode('.', eZUserDiscountRule::fetchIDListByUserID($user->attribute('contentobject_id')));
     }
     $cacheHashArray[] = eZSys::indexFile();
     // Add access type to cache hash if current access is uri type (so uri and host doesn't share cache)
     if (strpos($viewCacheTweak, 'ignore_siteaccess_type') === false && $GLOBALS['eZCurrentAccess']['type'] === eZSiteAccess::TYPE_URI) {
         $cacheHashArray[] = eZSiteAccess::TYPE_URI;
     }
     // Make the cache unique for every logged in user
     if (strpos($viewCacheTweak, 'pr_user') !== false and !$user->isAnonymous()) {
         $cacheNameExtra = $user->attribute('contentobject_id') . '-';
     }
     // Make the cache unique for every case of view parameters
     if (strpos($viewCacheTweak, 'ignore_viewparameters') === false && $viewParameters) {
         $vpString = '';
         ksort($viewParameters);
         foreach ($viewParameters as $key => $value) {
             if (!$key || $key === '_custom') {
                 continue;
             }
             $vpString .= 'vp:' . $key . '=' . $value;
         }
         $cacheHashArray[] = $vpString;
     }
     // Make the cache unique for every case of the preferences
     if ($cachedViewPreferences === false) {
         $depPreferences = $ini->variable('ContentSettings', 'CachedViewPreferences');
     } else {
         $depPreferences = $cachedViewPreferences;
     }
     if (strpos($viewCacheTweak, 'ignore_userpreferences') === false && isset($depPreferences[$viewMode])) {
         $depPreferences = explode(';', $depPreferences[$viewMode]);
         $pString = '';
         // Fetch preferences for the specified user
         $preferences = eZPreferences::values($user);
         foreach ($depPreferences as $pref) {
             $pref = explode('=', $pref);
             if (isset($pref[0])) {
                 if (isset($preferences[$pref[0]])) {
                     $pString .= 'p:' . $pref[0] . '=' . $preferences[$pref[0]] . ';';
                 } else {
                     if (isset($pref[1])) {
                         $pString .= 'p:' . $pref[0] . '=' . $pref[1] . ';';
                     }
                 }
             }
         }
         $cacheHashArray[] = $pString;
     }
     $cacheFile = $nodeID . '-' . $cacheNameExtra . md5(implode('-', $cacheHashArray)) . '.cache';
     $extraPath = eZDir::filenamePath($nodeID);
     $cacheDir = eZDir::path(array(eZSys::cacheDirectory(), $ini->variable('ContentSettings', 'CacheDir'), $currentSiteAccess, $extraPath));
     $cachePath = eZDir::path(array($cacheDir, $cacheFile));
     return array('cache_path' => $cachePath, 'cache_dir' => $cacheDir, 'cache_file' => $cacheFile);
 }
Exemple #13
0
 static function repositoryPath()
 {
     $ini = eZINI::instance();
     $packageIni = eZINI::instance('package.ini');
     return eZDir::path(array('var', $ini->variable('FileSettings', 'StorageDir'), $packageIni->variable('RepositorySettings', 'RepositoryDirectory')));
 }
    static function cleanup( $nodeList, $userId = false )
    {
        // The view-cache has a different storage structure than before:
        // var/cache/content/<siteaccess>/<extra-path>/<nodeID>-<hash>.cache
        // Also it uses the cluster file handler to delete files using a wildcard (glob style).
        $ini = eZINI::instance();
        $extraCacheName = '';
        $cacheBaseDir = eZDir::path( array( eZSys::cacheDirectory(), $ini->variable( 'ContentSettings', 'CacheDir' ) ) );
        $fileHandler = eZClusterFileHandler::instance();

        if ( $userId !== false && is_numeric( $userId ) )
        {
            $extraCacheName = $userId . '-';
        }

        // Figure out the siteaccess which are related, first using the new
        // INI setting RelatedSiteAccessList then the old existing one
        // AvailableSiteAccessList
        if ( $ini->hasVariable( 'SiteAccessSettings', 'RelatedSiteAccessList' ) &&
             $relatedSiteAccessList = $ini->variable( 'SiteAccessSettings', 'RelatedSiteAccessList' ) )
        {
            if ( !is_array( $relatedSiteAccessList ) )
            {
                $relatedSiteAccessList = array( $relatedSiteAccessList );
            }
            $relatedSiteAccessList[] = $GLOBALS['eZCurrentAccess']['name'];
            $siteAccesses = array_unique( $relatedSiteAccessList );
        }
        else
        {
            $siteAccesses = $ini->variable( 'SiteAccessSettings', 'AvailableSiteAccessList' );
        }
        if ( !$siteAccesses )
        {
            return;
        }

        foreach ( $nodeList as $nodeID )
        {
            $extraPath = eZDir::filenamePath( $nodeID );
            $fileHandler->fileDeleteByDirList( $siteAccesses, $cacheBaseDir, "$extraPath$nodeID-$extraCacheName" );
        }
    }
    /**
     * Removes the static cache file (index.html) and its directory if it exists.
     * The directory path is based upon the URL $url and the configured static storage dir.
     *
     * @param string $url The URL for the current item, e.g /news
     */
    function removeURL( $url )
    {
        $dir = eZDir::path( array( $this->staticStorageDir, $url ) );

        @unlink( $dir . "/index.html" );
        @rmdir( $dir );
    }
 static function instantiate($handler, $repositories = false)
 {
     $objectCache =& $GLOBALS["eZCollaborationHandlerObjectCache"];
     if (!isset($objectCache)) {
         $objectCache = array();
     }
     if (isset($objectCache[$handler])) {
         return $objectCache[$handler];
     }
     if ($repositories === false) {
         $repositories = eZCollaborationItemHandler::handlerRepositories();
     }
     $handlerInstance = null;
     $foundHandlerFile = false;
     $foundHandler = false;
     foreach ($repositories as $repository) {
         $handlerFile = $handler . 'collaborationhandler.php';
         $handlerClass = $handler . 'collaborationhandler';
         $handlerPath = eZDir::path(array($repository, $handler, $handlerFile));
         if (file_exists($handlerPath)) {
             $foundHandlerFile = true;
             include_once $handlerPath;
             if (class_exists($handlerClass)) {
                 $foundHandler = true;
                 $handlerInstance = new $handlerClass();
                 $objectCache[$handler] = $handlerInstance;
                 $handlerClasses = $handlerInstance->classes();
                 foreach ($handlerClasses as $handlerClass) {
                 }
             }
         }
     }
     if (!$foundHandlerFile) {
         eZDebug::writeWarning("Collaboration file '{$handlerFile}' could not be found in " . implode(', ', $repositories), __METHOD__);
     } else {
         if (!$foundHandler) {
             eZDebug::writeWarning("Collaboration class '{$handlerClass}' does not exist", __METHOD__);
         }
     }
     return $handlerInstance;
 }
 function loadImage($dirs, $base, $md5Text, $alternativeText, $imageType)
 {
     $name = preg_replace(array("#[^a-zA-Z0-9_-]+#", "#__+#", "#_\$#"), array('_', '_', ''), $alternativeText);
     $file = "{$name}.{$imageType}";
     $splitMD5Path = eZDir::getPathFromFilename($md5Text);
     $dirPath = eZDir::path(array($dirs, $base, $splitMD5Path, $md5Text));
     $filePath = eZDir::path(array($dirPath, $file));
     $fileHandler = eZClusterFileHandler::instance($filePath);
     if (!$fileHandler->exists()) {
         return null;
     }
     // we use a local cache of the file, because the eZImage library only works on files on the file system
     $fileHandler->fetch(true);
     return eZImageLayer::createForFile($file, $dirPath, $this->StoreAs);
 }
Exemple #18
0
 /**
  * Inserts the SQL file $sqlFile found in the path $path into the currently connected database.
  *
  * @param string $path
  * @param string $sqlFile
  * @param bool $usePathType
  * @return bool true if succesful.
  */
 function insertFile($path, $sqlFile, $usePathType = true)
 {
     $type = $this->databaseName();
     if ($usePathType) {
         $sqlFileName = eZDir::path(array($path, $type, $sqlFile));
     } else {
         $sqlFileName = eZDir::path(array($path, $sqlFile));
     }
     if (!file_exists($sqlFileName)) {
         eZDebug::writeError("File not found: {$sqlFileName}", __METHOD__);
         return false;
     }
     $sqlFileHandler = fopen($sqlFileName, 'rb');
     $buffer = '';
     $done = false;
     while (count($sqlArray = $this->prepareSqlQuery($sqlFileHandler, $buffer)) > 0) {
         // Turn unneccessary SQL debug output off
         $oldOutputSQL = $this->OutputSQL;
         $this->OutputSQL = false;
         if ($sqlArray && is_array($sqlArray)) {
             $done = true;
             foreach ($sqlArray as $singleQuery) {
                 $singleQuery = preg_replace("/\n|\r\n|\r/", " ", $singleQuery);
                 if (preg_match("#^ */(.+)\$#", $singleQuery, $matches)) {
                     $singleQuery = $matches[1];
                 }
                 if (trim($singleQuery) != "") {
                     //                    eZDebug::writeDebug( $singleQuery );
                     $this->query(trim($singleQuery));
                     if ($this->errorNumber()) {
                         return false;
                     }
                 }
             }
         }
         $this->OutputSQL = $oldOutputSQL;
     }
     return $done;
 }
 /**
  * Returns temporary directory used to download files to.
  *
  * \static
  */
 function tempDir()
 {
     return eZDir::path(array(eZSys::cacheDirectory(), 'packages'));
 }
Exemple #20
0
    $siteINI = eZINI::instance('site.ini.append', $iniPath);
    if ($siteINI->hasVariable('FileSettings', 'CacheDir')) {
        $cacheDir = $siteINI->variable('FileSettings', 'CacheDir');
        if ($cacheDir[0] == "/") {
            $cacheDir = eZDir::path(array($cacheDir));
        } else {
            if ($siteINI->hasVariable('FileSettings', 'VarDir')) {
                $varDir = $siteINI->variable('FileSettings', 'VarDir');
                $cacheDir = eZDir::path(array($varDir, $cacheDir));
            }
        }
    } else {
        if ($siteINI->hasVariable('FileSettings', 'VarDir')) {
            $varDir = $siteINI->variable('FileSettings', 'VarDir');
            $cacheDir = $ini->variable('FileSettings', 'CacheDir');
            $cacheDir = eZDir::path(array($varDir, $cacheDir));
        } else {
            $cacheDir = eZSys::cacheDirectory();
        }
    }
    $compiledTemplateDir = $cacheDir . "/template/compiled";
    eZDir::unlinkWildcard($compiledTemplateDir . "/", "*pagelayout*.*");
    // Expire template block cache
    eZContentCacheManager::clearTemplateBlockCacheIfNeeded(false);
}
$availableMenuArray = $menuINI->variable('MenuSettings', 'AvailableMenuArray');
$menuArray = array();
foreach ($availableMenuArray as $menuType) {
    $menuArray[] = array('type' => $menuType, 'settings' => $menuINI->group($menuType));
}
$tpl->setVariable('available_menu_array', $menuArray);
 /**
  * create the dir and filename for the current mailboxItem
  *
  * @return array array( 'file_path' => $filePath,
  *                 'file_dir'  => $dir,
  *                 'file_name' => $fileName )
  */
 public function getFilePathArray()
 {
     $mailboxItemId = $this->attribute('id');
     $mailboxId = $this->attribute('mailbox_id');
     $messageId = $this->attribute('message_id');
     $messageIdentifier = $this->attribute('message_identifier');
     $createTimestamp = $this->attribute('created');
     $varDir = eZSys::varDirectory();
     $year = date('Y', $createTimestamp);
     $month = date('m', $createTimestamp);
     $day = date('d', $createTimestamp);
     // $dir = $varDir . "/cjw_newsletter/mailbox/$mailboxId/$year/$month/$day/";
     $dir = eZDir::path(array($varDir, 'cjw_newsletter', 'mailbox', $mailboxId, $year, $month, $day));
     $fileName = "{$mailboxId}-{$year}{$month}{$day}-{$mailboxItemId}.mail";
     $fileSep = eZSys::fileSeparator();
     $filePath = $dir . $fileSep . $fileName;
     return array('file_path' => $filePath, 'file_dir' => $dir, 'file_name' => $fileName);
 }
 /**
  * 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;
 }
 static function cacheDirectory()
 {
     $cacheDirectory =& $GLOBALS['eZTemplateTreeCacheDirectory'];
     if (!isset($cacheDirectory)) {
         $cacheDirectory = eZDir::path(array(eZSys::cacheDirectory(), 'template/tree'));
     }
     return $cacheDirectory;
 }
 function store($fileName, $filePath, $type)
 {
     if (!$this->IsProcessed) {
         $this->process();
     }
     $imageObject = $this->imageObject();
     switch ($type) {
         case 'png':
             if (!file_exists($filePath)) {
                 eZDir::mkdir($filePath, false, true);
             }
             $fileFullPath = eZDir::path(array($filePath, $fileName));
             ImagePNG($imageObject, $fileFullPath);
             $this->StoredPath = $filePath;
             $this->StoredFile = $fileName;
             $this->StoredType = $type;
             return true;
             break;
         case 'jpg':
             if (!file_exists($filePath)) {
                 eZDir::mkdir($filePath, false, true);
             }
             ImageJPEG($imageObject, eZDir::path(array($filePath, $fileName)));
             $this->StoredPath = $filePath;
             $this->StoredFile = $fileName;
             $this->StoredType = $type;
             return true;
             break;
         default:
             eZDebug::writeError('Image format not supported: ' . $type, __METHOD__);
     }
     return false;
 }
    /**
     * Prepends the extension path to $path if not already in $path
     *
     * @param string $path
     */
    protected function normalizeExtensionPath( $path )
    {
        if ( strpos( $path, eZExtension::baseDirectory() ) === false )
            $path = eZDir::path( array( eZExtension::baseDirectory(), $path ) );

        return $path;
    }
 function store($atomic = false)
 {
     if ($this->open($atomic)) {
         $this->write("<?php\n");
         $this->writeElements();
         $this->write("?>\n");
         $this->writeChunks();
         $this->flushChunks();
         $this->close();
         if (!$this->ClusteringEnabled) {
             $perm = octdec(eZINI::instance()->variable('FileSettings', 'StorageFilePermissions'));
             chmod(eZDir::path(array($this->PHPDir, $this->PHPFile)), $perm);
         }
         // Write log message to storage.log
         eZLog::writeStorageLog($this->PHPFile, $this->PHPDir . '/');
         return true;
     } else {
         eZDebug::writeError("Failed to open file '" . $this->PHPDir . '/' . $this->PHPFile . "'", 'eZPHPCreator::store');
         return false;
     }
 }
Exemple #27
0
function removeRelatedCache($siteAccess)
{
    // Delete compiled template
    $ini = eZINI::instance();
    $iniPath = eZSiteAccess::findPathToSiteAccess($siteAccess);
    $siteINI = eZINI::instance('site.ini.append', $iniPath);
    if ($siteINI->hasVariable('FileSettings', 'CacheDir')) {
        $cacheDir = $siteINI->variable('FileSettings', 'CacheDir');
        if ($cacheDir[0] == "/") {
            $cacheDir = eZDir::path(array($cacheDir));
        } else {
            if ($siteINI->hasVariable('FileSettings', 'VarDir')) {
                $varDir = $siteINI->variable('FileSettings', 'VarDir');
                $cacheDir = eZDir::path(array($varDir, $cacheDir));
            }
        }
    } else {
        if ($siteINI->hasVariable('FileSettings', 'VarDir')) {
            $varDir = $siteINI->variable('FileSettings', 'VarDir');
            $cacheDir = $ini->variable('FileSettings', 'CacheDir');
            $cacheDir = eZDir::path(array($varDir, $cacheDir));
        } else {
            $cacheDir = eZSys::cacheDirectory();
        }
    }
    $compiledTemplateDir = $cacheDir . "/template/compiled";
    eZDir::unlinkWildcard($compiledTemplateDir . "/", "*pagelayout*.*");
    eZCache::clearByTag('template-block');
    // Expire content view cache
    eZContentCacheManager::clearAllContentCache();
}
    /**
     * Returns the current cache directory.
     *
     * @return string
     */
    public static function cacheDirectory()
    {
        $ini = eZINI::instance();
        $cacheDir = $ini->variable( 'FileSettings', 'CacheDir' );

        if ( $cacheDir[0] == "/" )
        {
            return eZDir::path( array( $cacheDir ) );
        }
        else
        {
            return eZDir::path( array( self::varDirectory(), $cacheDir ) );
        }
    }
 static function printReport($newWindow = false, $as_html = true, $returnReport = false, $allowedDebugLevels = false, $useAccumulators = true, $useTiming = true, $useIncludedFiles = false)
 {
     if (!self::isDebugEnabled()) {
         return null;
     }
     $debug = self::instance();
     $report = $debug->printReportInternal($as_html, $returnReport & $newWindow, $allowedDebugLevels, $useAccumulators, $useTiming, $useIncludedFiles);
     if ($newWindow == true) {
         $debugFilePath = eZDir::path(array(eZSys::varDirectory(), 'cache', 'debug.html'));
         $debugFileURL = $debugFilePath;
         eZURI::transformURI($debugFileURL, true);
         print "\n<script type='text/javascript'>\n<!--\n\n(function()\n{\n    var debugWindow;\n\n    if  (navigator.appName == \"Microsoft Internet Explorer\")\n    {\n        //Microsoft Internet Explorer\n        debugWindow = window.open( '{$debugFileURL}', 'ezdebug', 'width=500,height=550,status,scrollbars,resizable,screenX=0,screenY=20,left=20,top=40');\n        debugWindow.document.close();\n        debugWindow.location.reload();\n    }\n    else if (navigator.appName == \"Opera\")\n    {\n        //Opera\n        debugWindow = window.open( '', 'ezdebug', 'width=500,height=550,status,scrollbars,resizable,screenX=0,screenY=20,left=20,top=40');\n        debugWindow.location.href=\"{$debugFileURL}\";\n        debugWindow.navigate(\"{$debugFileURL}\");\n    }\n    else\n    {\n        //Mozilla, Firefox, etc.\n        debugWindow = window.open( '', 'ezdebug', 'width=500,height=550,status,scrollbars,resizable,screenX=0,screenY=20,left=20,top=40');\n        debugWindow.document.location.href=\"{$debugFileURL}\";\n    };\n})();\n\n// -->\n</script>\n";
         $header = "<!DOCTYPE html><html><head><title>eZ debug</title></head><body>";
         $footer = "</body></html>";
         $fullPage = ezpEvent::getInstance()->filter('response/output', $header . $report . $footer);
         file_put_contents($debugFilePath, $fullPage);
     } else {
         if ($returnReport) {
             return $report;
         }
     }
     return null;
 }
Exemple #30
0
 function save($fileName = false, $suffix = false, $useOverride = false, $onlyModified = false, $useRootDir = true, $resetArrays = false, $encapsulateInPHP = true)
 {
     $lineSeparator = eZSys::lineSeparator();
     $pathArray = array();
     $dirArray = array();
     if ($fileName === false) {
         $fileName = $this->FileName;
     }
     if ($useRootDir === true) {
         $pathArray[] = $this->RootDir;
         $dirArray[] = $this->RootDir;
     } else {
         if (is_string($useRootDir)) {
             $pathArray[] = $useRootDir;
             $dirArray[] = $useRootDir;
         }
     }
     if ($useOverride) {
         $pathArray[] = 'override';
         $dirArray[] = 'override';
     }
     if ($useOverride === 'append') {
         $fileName .= '.append';
     }
     if ($suffix !== false) {
         $fileName .= $suffix;
     }
     /* Try to guess which filename would fit better: 'xxx.apend' or 'xxx.append.php'.
      * We choose 'xxx.append.php' in all cases except when
      * 'xxx.append' exists already and 'xxx.append.php' does not exist.
      */
     if (strstr($fileName, '.append')) {
         $fnAppend = preg_replace('#\\.php$#', '', $fileName);
         $fnAppendPhp = $fnAppend . '.php';
         $fpAppend = eZDir::path(array_merge($pathArray, array($fnAppend)));
         $fpAppendPhp = eZDir::path(array_merge($pathArray, array($fnAppendPhp)));
         $fileName = file_exists($fpAppend) && !file_exists($fpAppendPhp) ? $fnAppend : $fnAppendPhp;
     }
     $originalFileName = $fileName;
     $backupFileName = $originalFileName . eZSys::backupFilename();
     $fileName .= '.tmp';
     $dirPath = eZDir::path($dirArray);
     if (!file_exists($dirPath)) {
         eZDir::mkdir($dirPath, octdec('777'), true);
     }
     $filePath = eZDir::path(array_merge($pathArray, array($fileName)));
     $originalFilePath = eZDir::path(array_merge($pathArray, array($originalFileName)));
     $backupFilePath = eZDir::path(array_merge($pathArray, array($backupFileName)));
     $fp = @fopen($filePath, "w+");
     if (!$fp) {
         eZDebug::writeError("Failed opening file '{$filePath}' for writing", __METHOD__);
         return false;
     }
     $writeOK = true;
     $written = 0;
     $charset = $this->Codec ? $this->Codec->RequestedOutputCharsetCode : $this->Charset;
     if ($encapsulateInPHP) {
         $written = fwrite($fp, "<?php /* #?ini charset=\"{$charset}\"?{$lineSeparator}{$lineSeparator}");
     } else {
         $written = fwrite($fp, "#?ini charset=\"{$charset}\"?{$lineSeparator}{$lineSeparator}");
     }
     if ($written === false) {
         $writeOK = false;
     }
     $i = 0;
     if ($writeOK) {
         foreach (array_keys($this->BlockValues) as $blockName) {
             if ($onlyModified) {
                 $groupHasModified = false;
                 if (isset($this->ModifiedBlockValues[$blockName])) {
                     foreach ($this->ModifiedBlockValues[$blockName] as $modifiedValue) {
                         if ($modifiedValue) {
                             $groupHasModified = true;
                         }
                     }
                 }
                 if (!$groupHasModified) {
                     continue;
                 }
             }
             $written = 0;
             if ($i > 0) {
                 $written = fwrite($fp, "{$lineSeparator}");
             }
             if ($written === false) {
                 $writeOK = false;
                 break;
             }
             $written = fwrite($fp, "[{$blockName}]{$lineSeparator}");
             if ($written === false) {
                 $writeOK = false;
                 break;
             }
             foreach (array_keys($this->BlockValues[$blockName]) as $blockVariable) {
                 if ($onlyModified) {
                     if (!isset($this->ModifiedBlockValues[$blockName][$blockVariable]) or !$this->ModifiedBlockValues[$blockName][$blockVariable]) {
                         continue;
                     }
                 }
                 $varKey = $blockVariable;
                 $varValue = $this->BlockValues[$blockName][$blockVariable];
                 if (is_array($varValue)) {
                     if (count($varValue) > 0) {
                         $customResetArray = (isset($this->BlockValues[$blockName]['ResetArrays']) and $this->BlockValues[$blockName]['ResetArrays'] == 'false') ? true : false;
                         if ($resetArrays and !$customResetArray) {
                             $written = fwrite($fp, "{$varKey}" . "[]{$lineSeparator}");
                         }
                         foreach ($varValue as $varArrayKey => $varArrayValue) {
                             if (is_string($varArrayKey)) {
                                 $written = fwrite($fp, "{$varKey}" . "[{$varArrayKey}]={$varArrayValue}{$lineSeparator}");
                             } else {
                                 if ($varArrayValue == NULL) {
                                     $written = fwrite($fp, "{$varKey}" . "[]{$lineSeparator}");
                                 } else {
                                     $written = fwrite($fp, "{$varKey}" . "[]={$varArrayValue}{$lineSeparator}");
                                 }
                             }
                             if ($written === false) {
                                 break;
                             }
                         }
                     } else {
                         $written = fwrite($fp, "{$varKey}" . "[]{$lineSeparator}");
                     }
                 } else {
                     $written = fwrite($fp, "{$varKey}={$varValue}{$lineSeparator}");
                 }
                 if ($written === false) {
                     $writeOK = false;
                     break;
                 }
             }
             if (!$writeOK) {
                 break;
             }
             ++$i;
         }
     }
     if ($writeOK) {
         if ($encapsulateInPHP) {
             $written = fwrite($fp, "*/ ?>");
             if ($written === false) {
                 $writeOK = false;
             }
         }
     }
     @fclose($fp);
     if (!$writeOK) {
         unlink($filePath);
         return false;
     }
     chmod($filePath, self::$filePermission);
     if (file_exists($backupFilePath)) {
         unlink($backupFilePath);
     }
     if (file_exists($originalFilePath)) {
         if (!rename($originalFilePath, $backupFilePath)) {
             return false;
         }
     }
     if (!rename($filePath, $originalFilePath)) {
         rename($backupFilePath, $originalFilePath);
         return false;
     }
     return true;
 }