function sendConfirmation()
 {
     if ($this->attribute('status') != eZSubscription::StatusPending) {
         return;
     }
     $res = eZTemplateDesignResource::instance();
     $ini = eZINI::instance();
     $hostname = eZSys::hostname();
     $template = 'design:eznewsletter/sendout/registration.tpl';
     $tpl = eZNewsletterTemplateWrapper::templateInit();
     $tpl->setVariable('userData', eZUserSubscriptionData::fetch($this->attribute('email')));
     $tpl->setVariable('hostname', $hostname);
     $tpl->setVariable('subscription', $this);
     $tpl->setVariable('subscriptionList', $this->attribute('subscription_list'));
     $templateResult = $tpl->fetch($template);
     if ($tpl->hasVariable('subject')) {
         $subject = $tpl->variable('subject');
     }
     $mail = new eZMail();
     $mail->setSender($ini->variable('MailSettings', 'EmailSender'), $ini->variable('SiteSettings', 'SiteName'));
     $mail->setReceiver($this->attribute('email'));
     $mail->setBody($templateResult);
     $mail->setSubject($subject);
     eZMailTransport::send($mail);
 }
 /**
  * Invoca il template per il form di attributo
  *
  * @see SearchFormOperator::modify
  * @param OCClassSearchFormHelper $instance
  * @param OCClassSearchFormAttributeField $field
  *
  * @return array|null|string
  */
 public static function displayAttribute(OCClassSearchFormHelper $instance, OCClassSearchFormAttributeField $field)
 {
     $keyArray = array(array('class', $instance->getContentClass()->attribute('id')), array('class_identifier', $instance->getContentClass()->attribute('identifier')), array('class_group', $instance->getContentClass()->attribute('match_ingroup_id_list')), array('attribute', $field->contentClassAttribute->attribute('id')), array('attribute_identifier', $field->contentClassAttribute->attribute('identifier')));
     $tpl = eZTemplate::factory();
     $tpl->setVariable('class', $instance->getContentClass());
     $tpl->setVariable('attribute', $field->contentClassAttribute);
     $res = eZTemplateDesignResource::instance();
     $res->setKeys($keyArray);
     $templateName = $field->contentClassAttribute->attribute('data_type_string');
     return $tpl->fetch('design:class_search_form/datatypes/' . $templateName . '.tpl');
 }
Пример #3
0
    /**
     * @return mixed
     */
    public function getLessFilePath()
    {
        if ( is_null($this->_lessFilePath) )
        {
            $bases = eZTemplateDesignResource::allDesignBases();
            $triedFiles = array();
            $match = eZTemplateDesignResource::fileMatch($bases, '', 'stylesheets/' . $this->getLessFileName(), $triedFiles);

            if ( !$match )
            {
                eZDebug::writeError(sprintf('File %s not found in %s', $this->getLessFileName(), implode(', ', $triedFiles)), __METHOD__);
                return false;
            }

            $this->_lessFilePath = $match['path'];
        }

        return $this->_lessFilePath;
    }
 function fetchOverrideTemplateList($classID)
 {
     $class = eZContentClass::fetch($classID);
     $classIdentifier = $class->attribute('identifier');
     $result = array();
     $ini = eZINI::instance();
     $siteAccessArray = $ini->variable('SiteAccessSettings', 'AvailableSiteAccessList');
     foreach ($siteAccessArray as $siteAccess) {
         $overrides = eZTemplateDesignResource::overrideArray($siteAccess);
         foreach ($overrides as $override) {
             if (isset($override['custom_match'])) {
                 foreach ($override['custom_match'] as $customMatch) {
                     if (isset($customMatch['conditions']['class_identifier']) && $customMatch['conditions']['class_identifier'] == $classIdentifier) {
                         $result[] = array('siteaccess' => $siteAccess, 'block' => $customMatch['override_name'], 'source' => $override['template'], 'target' => $customMatch['match_file']);
                     }
                     if (isset($customMatch['conditions']['class']) && $customMatch['conditions']['class'] == $classID) {
                         $result[] = array('siteaccess' => $siteAccess, 'block' => $customMatch['override_name'], 'source' => $override['template'], 'target' => $customMatch['match_file']);
                     }
                 }
             }
         }
     }
     return array('result' => $result);
 }
Пример #5
0
 function handlePublishEvent($event, &$parameters)
 {
     $versionObject = $event->attribute('content');
     if (!$versionObject) {
         return eZNotificationEventHandler::EVENT_SKIPPED;
     }
     $contentObject = $versionObject->attribute('contentobject');
     if (!$contentObject) {
         return eZNotificationEventHandler::EVENT_SKIPPED;
     }
     $contentNode = $contentObject->attribute('main_node');
     if (!$contentNode) {
         return eZNotificationEventHandler::EVENT_SKIPPED;
     }
     // Notification should only be sent out when the object is published (is visible)
     if ($contentNode->attribute('is_invisible') == 1) {
         return eZNotificationEventHandler::EVENT_SKIPPED;
     }
     $contentClass = $contentObject->attribute('content_class');
     if (!$contentClass) {
         return eZNotificationEventHandler::EVENT_SKIPPED;
     }
     if ($versionObject->attribute('version') != $contentObject->attribute('current_version')) {
         return eZNotificationEventHandler::EVENT_SKIPPED;
     }
     $tpl = eZTemplate::factory();
     $tpl->resetVariables();
     $parentNode = $contentNode->attribute('parent');
     if (!$parentNode instanceof eZContentObjectTreeNode) {
         eZDebug::writeError('DB corruption: Node id ' . $contentNode->attribute('node_id') . ' is missing parent node.', __METHOD__);
         return eZNotificationEventHandler::EVENT_SKIPPED;
     }
     $parentContentObject = $parentNode->attribute('object');
     if (!$parentContentObject instanceof eZContentObject) {
         eZDebug::writeError('DB corruption: Node id ' . $parentNode->attribute('node_id') . ' is missing object.', __METHOD__);
         return eZNotificationEventHandler::EVENT_SKIPPED;
     }
     $parentContentClass = $parentContentObject->attribute('content_class');
     if (!$parentContentClass instanceof eZContentClass) {
         eZDebug::writeError('DB corruption: Object id ' . $parentContentObject->attribute('id') . ' is missing class object.', __METHOD__);
         return eZNotificationEventHandler::EVENT_SKIPPED;
     }
     $res = eZTemplateDesignResource::instance();
     $res->setKeys(array(array('object', $contentObject->attribute('id')), array('node', $contentNode->attribute('node_id')), array('class', $contentObject->attribute('contentclass_id')), array('class_identifier', $contentClass->attribute('identifier')), array('parent_node', $contentNode->attribute('parent_node_id')), array('parent_class', $parentContentObject->attribute('contentclass_id')), array('parent_class_identifier', $parentContentClass != null ? $parentContentClass->attribute('identifier') : 0), array('depth', $contentNode->attribute('depth')), array('url_alias', $contentNode->attribute('url_alias'))));
     $tpl->setVariable('object', $contentObject);
     $notificationINI = eZINI::instance('notification.ini');
     $emailSender = $notificationINI->variable('MailSettings', 'EmailSender');
     $ini = eZINI::instance();
     if (!$emailSender) {
         $emailSender = $ini->variable('MailSettings', 'EmailSender');
     }
     if (!$emailSender) {
         $emailSender = $ini->variable("MailSettings", "AdminEmail");
     }
     $tpl->setVariable('sender', $emailSender);
     $result = $tpl->fetch('design:notification/handler/ezsubtree/view/plain.tpl');
     $subject = $tpl->variable('subject');
     if ($tpl->hasVariable('message_id')) {
         $parameters['message_id'] = $tpl->variable('message_id');
     }
     if ($tpl->hasVariable('references')) {
         $parameters['references'] = $tpl->variable('references');
     }
     if ($tpl->hasVariable('reply_to')) {
         $parameters['reply_to'] = $tpl->variable('reply_to');
     }
     if ($tpl->hasVariable('from')) {
         $parameters['from'] = $tpl->variable('from');
     }
     if ($tpl->hasVariable('content_type')) {
         $parameters['content_type'] = $tpl->variable('content_type');
     }
     $collection = eZNotificationCollection::create($event->attribute('id'), self::NOTIFICATION_HANDLER_ID, self::TRANSPORT);
     $collection->setAttribute('data_subject', $subject);
     $collection->setAttribute('data_text', $result);
     $collection->store();
     $assignedNodes = $contentObject->parentNodes(true);
     $nodeIDList = array();
     foreach ($assignedNodes as $node) {
         if ($node) {
             $pathString = $node->attribute('path_string');
             $pathString = ltrim(rtrim($pathString, '/'), '/');
             $nodeIDListPart = explode('/', $pathString);
             $nodeIDList = array_merge($nodeIDList, $nodeIDListPart);
         }
     }
     $nodeIDList[] = $contentNode->attribute('node_id');
     $nodeIDList = array_unique($nodeIDList);
     $userList = eZSubtreeNotificationRule::fetchUserList($nodeIDList, $contentObject);
     $locale = eZLocale::instance();
     $weekDayNames = $locale->attribute('weekday_name_list');
     $weekDaysByName = array_flip($weekDayNames);
     foreach ($userList as $subscriber) {
         $item = $collection->addItem($subscriber['address']);
         if ($subscriber['use_digest'] == 0) {
             $settings = eZGeneralDigestUserSettings::fetchByUserId($subscriber['user_id']);
             if ($settings !== null && $settings->attribute('receive_digest') == 1) {
                 $time = $settings->attribute('time');
                 $timeArray = explode(':', $time);
                 $hour = $timeArray[0];
                 if ($settings->attribute('digest_type') == eZGeneralDigestUserSettings::TYPE_DAILY) {
                     eZNotificationSchedule::setDateForItem($item, array('frequency' => 'day', 'hour' => $hour));
                 } else {
                     if ($settings->attribute('digest_type') == eZGeneralDigestUserSettings::TYPE_WEEKLY) {
                         $weekday = $weekDaysByName[$settings->attribute('day')];
                         eZNotificationSchedule::setDateForItem($item, array('frequency' => 'week', 'day' => $weekday, 'hour' => $hour));
                     } else {
                         if ($settings->attribute('digest_type') == eZGeneralDigestUserSettings::TYPE_MONTHLY) {
                             eZNotificationSchedule::setDateForItem($item, array('frequency' => 'month', 'day' => $settings->attribute('day'), 'hour' => $hour));
                         }
                     }
                 }
                 $item->store();
             }
         }
     }
     return eZNotificationEventHandler::EVENT_HANDLED;
 }
Пример #6
0
function contentPDFGenerate($cacheFile, $node, $object = false, $viewCacheEnabled = true, $languageCode = false, $viewParameters = array())
{
    if ($languageCode) {
        $node->setCurrentLanguage($languageCode);
    }
    if ($object == false) {
        $object = $node->attribute('object');
    }
    $res = eZTemplateDesignResource::instance();
    $res->setKeys(array(array('object', $node->attribute('contentobject_id')), array('remote_id', $object->attribute('remote_id')), array('node_remote_id', $node->attribute('remote_id')), array('section', $object->attribute('section_id')), array('node', $node->attribute('node_id')), array('parent_node', $node->attribute('parent_node_id')), array('class', $object->attribute('contentclass_id')), array('depth', $node->attribute('depth')), array('url_alias', $node->attribute('url_alias')), array('class_group', $object->attribute('match_ingroup_id_list')), array('class_identifier', $object->attribute('class_identifier'))));
    $tpl = eZTemplate::factory();
    $tpl->setVariable('view_parameters', $viewParameters);
    $tpl->setVariable('node', $node);
    $tpl->setVariable('generate_toc', 0);
    $tpl->setVariable('tree_traverse', 0);
    $tpl->setVariable('class_array', 0);
    $tpl->setVariable('show_frontpage', 0);
    if ($viewCacheEnabled) {
        $tpl->setVariable('generate_file', 1);
        $tpl->setVariable('filename', $cacheFile);
    } else {
        $tpl->setVariable('generate_file', 0);
        $tpl->setVariable('generate_stream', 1);
    }
    $textElements = array();
    $uri = 'design:node/view/pdf.tpl';
    $tpl->setVariable('pdf_root_template', 1);
    eZTemplateIncludeFunction::handleInclude($textElements, $uri, $tpl, '', '');
    $pdf_definition = implode('', $textElements);
    $pdf_definition = str_replace(array(' ', "\r\n", "\t", "\n"), '', $pdf_definition);
    $tpl->setVariable('pdf_definition', $pdf_definition);
    $uri = 'design:node/view/execute_pdf.tpl';
    $textElements = '';
    eZTemplateIncludeFunction::handleInclude($textElements, $uri, $tpl, '', '');
}
Пример #7
0
    /**
     * Reloads extensions and changes siteaccess globally
     * If you only want changes on a instance of ini, use {@link eZSiteAccess::getIni()}
     *
     * - clears all in-memory caches used by the INI system
     * - re-builds the list of paths where INI files are searched for
     * - runs {@link eZSiteAccess::change()}
     * - re-searches module paths {@link eZModule::setGlobalPathList()}
     *
     * @since 4.4
     * @param array $access An associative array with 'name' (string), 'type' (int) and 'uri_part' (array).
     *                      See {@link eZSiteAccess::match()} for array structure definition
     * @param eZINI|null $siteINI Optional parameter to be able to only do change on specific instance of site.ini
     *                            If set, then global siteacceess will not be changed as well.
     * @return array The $access parameter
     */
    static function load( array $access, eZINI $siteINI = null )
    {
        $currentSiteAccess = $GLOBALS['eZCurrentAccess'];
        unset( $GLOBALS['eZCurrentAccess'] );

        // Clear all ini override dirs
        if ( $siteINI instanceof eZINI )
        {
            $siteINI->resetOverrideDirs();
        }
        else
        {
            eZINI::resetAllInstances();
            eZExtension::clearActiveExtensionsMemoryCache();
            eZTemplateDesignResource::clearInMemoryCache();
        }

        // Reload extensions, siteaccess and access extensions
        eZExtension::activateExtensions( 'default', $siteINI );
        $access = self::change( $access, $siteINI );
        eZExtension::activateExtensions( 'access', $siteINI );

        // Restore current (old) siteacces if changes where only to be applied to locale instance of site.ini
        if ( $siteINI instanceof eZINI )
        {
            $GLOBALS['eZCurrentAccess'] = $currentSiteAccess;
        }
        else
        {
            $moduleRepositories = eZModule::activeModuleRepositories();
            eZModule::setGlobalPathList( $moduleRepositories );
        }

        return $access;
    }
Пример #8
0
include_once "kernel/setup/ezsetuptests.php";
include_once 'kernel/setup/ezsetup_summary.php';
// Initialize template
$tpl = eZTemplate::instance();
//$tpl->registerFunction( "section", new eZTemplateSectionFunction( "section" ) );
//$tpl->registerFunction( "include", new eZTemplateIncludeFunction() );
$ini = eZINI::instance();
if ($ini->variable('TemplateSettings', 'Debug') == 'enabled') {
    eZTemplate::setIsDebugEnabled(true);
}
//eZDebug::setLogOnly( true );
//$ini->setVariable( 'RegionalSettings', 'TextTranslation', 'disabled' );
$Module = $Params['Module'];
$tpl->setAutoloadPathList($ini->variable('TemplateSettings', 'AutoloadPathList'));
$tpl->autoload();
$tpl->registerResource(eZTemplateDesignResource::instance());
// Initialize HTTP variables
$http = eZHTTPTool::instance();
$baseDir = 'kernel/setup/';
// Load step list data. See this file for install step references.
$stepDataFile = $baseDir . "steps/ezstep_data.php";
$stepData = null;
if (file_exists($stepDataFile)) {
    include_once $stepDataFile;
    $stepData = new eZStepData();
}
if ($stepData == null) {
    print "<h1>Setup step data file not found. Setup is exiting...</h1>";
    //TODO : i18n translate
    eZDisplayResult($templateResult);
    eZExecution::cleanExit();
    /**
     * Reloads extensions and changes siteaccess globally
     * If you only want changes on a instance of ini, use {@link eZSiteAccess::getIni()}
     *
     * - clears all in-memory caches used by the INI system
     * - re-builds the list of paths where INI files are searched for
     * - runs {@link eZSiteAccess::change()}
     * - re-searches module paths {@link eZModule::setGlobalPathList()}
     *
     * @since 4.4
     * @param array $access An associative array with 'name' (string), 'type' (int) and 'uri_part' (array).
     *                      See {@link eZSiteAccess::match()} for array structure definition
     * @param eZINI|null $siteINI Optional parameter to be able to only do change on specific instance of site.ini
     *                            If set, then global siteacceess will not be changed as well.
     * @return array The $access parameter
     */
    static function load( array $access, eZINI $siteINI = null )
    {
        $currentSiteAccess = $GLOBALS['eZCurrentAccess'];
        unset( $GLOBALS['eZCurrentAccess'] );

        // Clear all ini override dirs
        if ( $siteINI instanceof eZINI )
        {
            $siteINI->resetOverrideDirs();
        }
        else
        {
            eZINI::resetAllInstances();
            eZExtension::clearActiveExtensionsMemoryCache();
            eZTemplateDesignResource::clearInMemoryCache();
        }

        // Reload extensions, siteaccess and access extensions
        eZExtension::activateExtensions( 'default', $siteINI );
        $access = self::change( $access, $siteINI );
        eZExtension::activateExtensions( 'access', $siteINI );

        // Reload Extenion ordering to reorder eZINI Global Override Dirs.
        // @TODO : Améliorer la gestion globale (éviter des appels multiples !!!)
        if (  $siteINI instanceof eZINI  && $siteINI->variable( 'ExtensionSettings', 'ExtensionOrdering' ) === 'enabled' )
        {
            eZINI::removeGlobalOverrideDirsByScope( 'sa-extension' );
            eZINI::removeGlobalOverrideDirsByScope( 'extension' );
            eZExtension::activateExtensions( false );
        }

        // Restore current (old) siteacces if changes where only to be applied to locale instance of site.ini
        if ( $siteINI instanceof eZINI )
        {
            $GLOBALS['eZCurrentAccess'] = $currentSiteAccess;
        }
        else
        {
            $moduleRepositories = eZModule::activeModuleRepositories();
            eZModule::setGlobalPathList( $moduleRepositories );
        }

        return $access;
    }
 function &outputText()
 {
     if (!$this->XMLData) {
         $output = '';
         return $output;
     }
     $this->Tpl = eZTemplate::factory();
     $this->Res = eZTemplateDesignResource::instance();
     if ($this->ContentObjectAttribute) {
         $this->Res->setKeys(array(array('attribute_identifier', $this->ContentObjectAttribute->attribute('contentclass_attribute_identifier'))));
     }
     $this->Document = new DOMDocument('1.0', 'utf-8');
     $success = $this->Document->loadXML($this->XMLData);
     if (!$success) {
         $this->Output = '';
         return $this->Output;
     }
     $this->prefetch();
     $this->XMLSchema = eZXMLSchema::instance();
     // Add missing elements to the OutputTags array
     foreach ($this->XMLSchema->availableElements() as $element) {
         if (!isset($this->OutputTags[$element])) {
             $this->OutputTags[$element] = array();
         }
     }
     $this->NestingLevel = 0;
     $params = array();
     $output = $this->outputTag($this->Document->documentElement, $params);
     $this->Output = $output[1];
     unset($this->Document);
     $this->Res->removeKey('attribute_identifier');
     return $this->Output;
 }
Пример #11
0
$i = 0;
foreach ( $parameters as $param )
{
    if ( $i > 0 )
        $template .= "/";
    $template .= "$param";
    $i++;
}

$siteAccess = $Params['SiteAccess'];
if( $siteAccess )
    $http->setSessionVariable( 'eZTemplateAdminCurrentSiteAccess', $siteAccess );
else
    $siteAccess = $http->sessionVariable( 'eZTemplateAdminCurrentSiteAccess' );

$overrideArray = eZTemplateDesignResource::overrideArray( $siteAccess );

// Check if template already exists
$isExistingTemplate = false;
foreach ( $overrideArray as $overrideSetting )
{
    if ( $overrideSetting['base_dir'] . $overrideSetting['template'] == $template )
    {
        $isExistingTemplate = true;
        break;
    }
    elseif ( isset( $overrideSetting['custom_match'] ) )
    {
        foreach ( $overrideSetting['custom_match'] as $customMatch )
        {
            if ( $customMatch['match_file'] == $template )
 static function generateStatistics($as_html = true)
 {
     $stats = '';
     if (!eZTemplate::isTemplatesUsageStatisticsEnabled()) {
         return $stats;
     }
     if ($as_html) {
         $stats .= "<h3>Templates used to render the page:</h3>";
         $stats .= "<table id='templateusage' class='debug_resource_usage' title='List of used templates'>" . "<tr><th title='Usage count of this particular template'>Usage</th>" . "<th>Requested template</th>" . "<th>Template</th>" . "<th>Template loaded</th>" . "<th>Edit</th>" . "<th>Override</th></tr>";
     } else {
         $formatString = "%-40s%-40s%-40s\n";
         $stats .= "Templates usage statistics\n";
         $stats .= sprintf($formatString, 'Templates', 'Requested template', 'Template loaded');
     }
     if ($as_html) {
         $iconSizeX = 16;
         $iconSizeY = 16;
         $templateViewFunction = 'visual/templateview';
         eZURI::transformURI($templateViewFunction);
         $templateEditFunction = 'visual/templateedit';
         eZURI::transformURI($templateEditFunction);
         $templateOverrideFunction = 'visual/templatecreate';
         eZURI::transformURI($templateOverrideFunction);
         $std_base = eZTemplateDesignResource::designSetting('standard');
         $wwwDir = htmlspecialchars(eZSys::wwwDir(), ENT_COMPAT, 'UTF-8');
         $editIconFile = "{$wwwDir}/design/{$std_base}/images/edit.gif";
         $overrideIconFile = "{$wwwDir}/design/{$std_base}/images/override-template.gif";
         $tdClass = 'used_templates_stats1';
         $j = 0;
         $currentSiteAccess = $GLOBALS['eZCurrentAccess']['name'];
     }
     $templatesUsageStatistics = eZTemplate::templatesUsageStatistics();
     $alreadyListedTemplate = $templateCounts = array();
     //Generate usage count for each unique template first.
     foreach ($templatesUsageStatistics as $templateInfo) {
         $actualTemplateName = $templateInfo['actual-template-name'];
         if (!array_key_exists($actualTemplateName, $templateCounts)) {
             $templateCounts[$actualTemplateName] = 1;
         } else {
             ++$templateCounts[$actualTemplateName];
         }
     }
     //Then create the actual listing
     foreach ($templatesUsageStatistics as $templateInfo) {
         $actualTemplateName = $templateInfo['actual-template-name'];
         $requestedTemplateName = $templateInfo['requested-template-name'];
         $templateFileName = $templateInfo['template-filename'];
         if (!in_array($actualTemplateName, $alreadyListedTemplate)) {
             $alreadyListedTemplate[] = $actualTemplateName;
             if ($as_html) {
                 $requestedTemplateViewURI = $templateViewFunction . '/' . $requestedTemplateName;
                 $actualTemplateViewURI = $templateViewFunction . '/' . $actualTemplateName;
                 $templateEditURI = $templateEditFunction . '/' . $templateFileName;
                 $templateOverrideURI = $templateOverrideFunction . '/' . $actualTemplateName;
                 $actualTemplateNameOutput = $actualTemplateName == $requestedTemplateName ? "<em>&lt;No override&gt;</em>" : $actualTemplateName;
                 $stats .= "<tr class='data'><td>{$templateCounts[$actualTemplateName]}</td>" . "<td><a href=\"{$requestedTemplateViewURI}\">{$requestedTemplateName}</a></td>" . "<td>{$actualTemplateNameOutput}</td>" . "<td>{$templateFileName}</td>" . "<td><a href=\"{$templateEditURI}/(siteAccess)/{$currentSiteAccess}\"><img src=\"{$editIconFile}\" width=\"{$iconSizeX}\" height=\"{$iconSizeY}\" alt=\"Edit template\" title=\"Edit template\" /></a></td>" . "<td><a href=\"{$templateOverrideURI}/(siteAccess)/{$currentSiteAccess}\"><img src=\"{$overrideIconFile}\" width=\"{$iconSizeX}\" height=\"{$iconSizeY}\" alt=\"Override template\" title=\"Override template\" /></a></td></tr>";
                 $j++;
             } else {
                 $stats .= sprintf($formatString, $requestedTemplateName, $actualTemplateName, $templateFileName);
             }
         }
     }
     $totalTemplatesCount = count($templatesUsageStatistics);
     $totalUniqueTemplatesCopunt = count(array_keys($alreadyListedTemplate));
     if ($as_html) {
         $stats .= "<tr><td colspan=\"6\"><b>&nbsp;Number of times templates used: {$totalTemplatesCount}<br />&nbsp;Number of unique templates used: {$totalUniqueTemplatesCopunt}</b></td></tr>";
         $stats .= "</table>";
     } else {
         $stats .= "\nTotal templates count: " . $totalTemplatesCount . "\n" . "Total unique templates count: " . $totalUniqueTemplatesCopunt . "\n";
     }
     return $stats;
 }
 /**
  * Merges a collection of files togheter and returns array of paths to the files.
  * js /css content is returned as string if packlevel is 0 and you use a js/ css generator.
  * $fileArray can also be array of array of files, like array(  'file.js', 'file2.js', array( 'file5.js' ) )
  * The name of the cached file is a md5 hash consistant of the file paths
  * of the valid files in $file_array and the packlevel.
  * The whole argument is used instead of file path on js/ css generators in the cache hash.
  *
  * @param array|string $fileArray Either array of file paths, or string with file path
  * @param string $subPath In witch sub path of design folder to look for files.
  * @param string $fileExtension File extension name (for use on cache file)
  * @param int $packLevel Level of packing, values: 0-3
  * @param bool $indexDirInCacheHash To add index path in cache hash or not
  * @param string $filePostName Extra file name part, example "_screen" in case of medai use for css
  *
  * @return array List of css files
  */
 static function packFiles($fileArray, $subPath = '', $fileExtension = '.js', $packLevel = 2, $indexDirInCacheHash = false, $filePostName = '')
 {
     if (!$fileArray) {
         return array();
     } else {
         if (!is_array($fileArray)) {
             $fileArray = array($fileArray);
         }
     }
     $ezjscINI = eZINI::instance('ezjscore.ini');
     $bases = eZTemplateDesignResource::allDesignBases();
     $customHosts = $ezjscINI->variable('Packer', 'CustomHosts');
     $data = array('http' => array(), 'www' => array(), 'locale' => array(), 'cache_name' => '', 'cache_hash' => '', 'cache_path' => '', 'last_modified' => 0, 'file_extension' => $fileExtension, 'file_post_name' => $filePostName, 'pack_level' => $packLevel, 'sub_path' => $subPath, 'cache_dir' => self::getCacheDir(), 'www_dir' => htmlspecialchars(self::getWwwDir(), ENT_COMPAT, 'UTF-8'), 'index_dir' => self::getIndexDir(), 'custom_host' => isset($customHosts[$fileExtension]) ? $customHosts[$fileExtension] : '');
     // Only pack files if Packer is enabled and if not set DevelopmentMode is disabled
     if ($ezjscINI->hasVariable('eZJSCore', 'Packer')) {
         $packerIniValue = $ezjscINI->variable('eZJSCore', 'Packer');
         if ($packerIniValue === 'disabled') {
             $data['pack_level'] = 0;
         } else {
             if (is_numeric($packerIniValue)) {
                 $data['pack_level'] = (int) $packerIniValue;
             }
         }
     } else {
         if (eZINI::instance()->variable('TemplateSettings', 'DevelopmentMode') === 'enabled') {
             $data['pack_level'] = 0;
         }
     }
     // Needed for image includes to work on ezp installs with mixed access methods (virtualhost + url based setup)
     if ($indexDirInCacheHash) {
         $data['cache_name'] = $data['index_dir'];
     }
     $originalFileArray = $fileArray;
     while (!empty($fileArray)) {
         $file = array_shift($fileArray);
         // if $file is array, concat it to the file array and continue
         if ($file && is_array($file)) {
             $fileArray = array_merge($file, $fileArray);
             continue;
         } else {
             if (!$file) {
                 continue;
             } else {
                 if (strpos($file, '::') !== false) {
                     $server = self::serverCallHelper(explode('::', $file));
                     if (!$server instanceof ezjscServerRouter) {
                         continue;
                     }
                     $fileTime = $server->getCacheTime($data);
                     // Generate content straight away if packing is disabled
                     if ($data['pack_level'] === 0) {
                         $data['www'][] = $server->call($fileArray);
                     } else {
                         if ($fileTime === -1) {
                             $data['http'][] = $server->call($fileArray);
                         } else {
                             $data['locale'][] = $server;
                             $data['cache_name'] .= $file . '_';
                         }
                     }
                     $data['last_modified'] = max($data['last_modified'], $fileTime);
                     continue;
                 } else {
                     if (strpos($file, 'http://') === 0 || strpos($file, 'https://') === 0) {
                         $data['http'][] = $file;
                         continue;
                     } else {
                         if (strpos($file, '://') === 0) {
                             if (!isset($protocol)) {
                                 $protocol = eZSys::serverProtocol();
                             }
                             $data['http'][] = $protocol . $file;
                             continue;
                         } else {
                             if (strpos($file, 'var/') === 0) {
                                 if (substr($file, 0, 2) === '//' || preg_match("#^[a-zA-Z0-9]+:#", $file)) {
                                     $file = '/';
                                 } else {
                                     if (strlen($file) > 0 && $file[0] !== '/') {
                                         $file = '/' . $file;
                                     }
                                 }
                                 eZURI::transformURI($file, true, 'relative');
                                 // Get file time and continue if it return false
                                 $file = str_replace('//' . $data['www_dir'], '', '//' . $file);
                                 $fileTime = file_exists($file) ? filemtime($file) : false;
                                 $wwwFile = $data['www_dir'] . $file;
                             } else {
                                 // Allow path to be outside subpath if it starts with '/'
                                 if ($file[0] === '/') {
                                     $file = ltrim($file, '/');
                                 } else {
                                     $file = $subPath . $file;
                                 }
                                 $triedFiles = array();
                                 $match = eZTemplateDesignResource::fileMatch($bases, '', $file, $triedFiles);
                                 if ($match === false) {
                                     eZDebug::writeWarning("Could not find: {$file}", __METHOD__);
                                     continue;
                                 }
                                 $file = htmlspecialchars($match['path']);
                                 $fileTime = file_exists($file) ? filemtime($file) : false;
                                 $wwwFile = $data['www_dir'] . $file;
                             }
                         }
                     }
                 }
             }
         }
         if ($fileTime === false) {
             eZDebug::writeWarning("Could not get modified time of file: {$file}", __METHOD__);
             continue;
         }
         // Calculate last modified time and store in arrays
         $data['last_modified'] = max($data['last_modified'], $fileTime);
         $data['locale'][] = $file;
         $data['www'][] = $wwwFile;
         $data['cache_name'] .= $file . '_';
     }
     if ($data['pack_level'] === 0) {
         self::$log[] = $data;
         // if packing is disabled, return the valid paths / content we have generated
         return array_merge($data['http'], $data['www']);
     } else {
         if (empty($data['locale']) && !empty($data['http'])) {
             self::$log[] = $data;
             // return if there are only external scripts and no local files to cache
             return array_merge($data['http'], $data['www']);
         } else {
             if (empty($data['locale'])) {
                 eZDebug::writeWarning("Could not find any files: " . var_export($originalFileArray, true), __METHOD__);
                 return array();
             }
         }
     }
     // See if cahe file exists and if it has expired (only if time is not part of name)
     if ($ezjscINI->variable('Packer', 'AppendLastModifiedTime') === 'enabled') {
         $data['cache_hash'] = md5($data['cache_name'] . $data['pack_level']) . '_' . $data['last_modified'] . $data['file_post_name'] . $data['file_extension'];
         $data['cache_path'] = $data['cache_dir'] . $subPath . $data['cache_hash'];
         $clusterFileHandler = eZClusterFileHandler::instance($data['cache_path']);
         if ($clusterFileHandler->fileExists($data['cache_path'])) {
             $data['http'][] = $data['custom_host'] . $data['www_dir'] . $data['cache_path'];
             self::$log[] = $data;
             return $data['http'];
         }
     } else {
         $data['cache_hash'] = md5($data['cache_name'] . $data['pack_level']) . $data['file_post_name'] . $data['file_extension'];
         $data['cache_path'] = $data['cache_dir'] . $subPath . $data['cache_hash'];
         $clusterFileHandler = eZClusterFileHandler::instance($data['cache_path']);
         // Check last modified time and return path to cache file if valid
         if ($clusterFileHandler->fileExists($data['cache_path']) && $data['last_modified'] <= $clusterFileHandler->mtime($data['cache_path'])) {
             $data['http'][] = $data['custom_host'] . $data['www_dir'] . $data['cache_path'];
             self::$log[] = $data;
             return $data['http'];
         }
     }
     // Merge file content and create new cache file
     $content = '';
     $isCSS = $data['file_extension'] === '.css';
     foreach ($data['locale'] as $i => $file) {
         // if this is a js / css generator, call to get content
         if ($file instanceof ezjscServerRouter) {
             $content .= $file->call($data['locale']);
             continue;
         } else {
             if (!$file) {
                 continue;
             }
         }
         // else, get content of normal file
         $fileContent = file_get_contents($file);
         if (!trim($fileContent)) {
             $content .= "/* empty: {$file} */\r\n";
             continue;
         }
         if ($isCSS) {
             // We need to fix relative background image paths if this is a css file
             $fileContent = ezjscPacker::fixImgPaths($fileContent, $file);
             // Remove @charset if this is not the first file (some browsers will ignore css after a second occurance of this)
             if ($i) {
                 $fileContent = preg_replace('/^@charset[^;]+;/i', '', $fileContent);
             }
         }
         $content .= "/* start: {$file} */\r\n";
         $content .= $fileContent;
         $content .= "\r\n/* end: {$file} */\r\n\r\n";
     }
     // Pack all files to save bandwidth
     if ($data['pack_level'] > 1) {
         foreach ($ezjscINI->variable('eZJSCore', $isCSS ? 'CssOptimizer' : 'JavaScriptOptimizer') as $optimizer) {
             if (is_callable(array($optimizer, 'optimize'))) {
                 $content = call_user_func(array($optimizer, 'optimize'), $content, $data['pack_level']);
             } else {
                 eZDebug::writeWarning("Could not call optimizer '{$optimizer}'", __METHOD__);
             }
         }
     }
     // Save cache file and return path
     $clusterFileHandler->fileStoreContents($data['cache_path'], $content, 'ezjscore', $isCSS ? 'text/css' : 'text/javascript');
     $data['http'][] = $data['custom_host'] . $data['www_dir'] . $data['cache_path'];
     self::$log[] = $data;
     return $data['http'];
 }
Пример #14
0
 /**
  * Returns a shared instance of the eZTemplate class with
  * default settings applied, like:
  * - Autoload operators loaded
  * - Debug mode set
  * - eZTemplateDesignResource::instance registered
  *
  * @since 4.3
  * @return eZTemplate
  */
 public static function factory()
 {
     if (self::$factory === false) {
         $instance = self::instance();
         $ini = eZINI::instance();
         if (!isset($GLOBALS['eZTemplateDebugInternalsEnabled']) && $ini->variable('TemplateSettings', 'Debug') == 'enabled') {
             eZTemplate::setIsDebugEnabled(true);
         }
         $compatAutoLoadPath = $ini->variableArray('TemplateSettings', 'AutoloadPath');
         $autoLoadPathList = $ini->variable('TemplateSettings', 'AutoloadPathList');
         $extensionAutoloadPath = $ini->variable('TemplateSettings', 'ExtensionAutoloadPath');
         $extensionPathList = eZExtension::expandedPathList($extensionAutoloadPath, 'autoloads/');
         $autoLoadPathList = array_unique(array_merge($compatAutoLoadPath, $autoLoadPathList, $extensionPathList));
         $instance->setAutoloadPathList($autoLoadPathList);
         $instance->autoload();
         $instance->registerResource(eZTemplateDesignResource::instance());
         self::$factory = true;
     }
     return self::instance();
 }
Пример #15
0
 /**
  * Merges a collection of files togheter and returns array of paths to the files.
  * js /css content is returned as string if packlevel is 0 and you use a js/ css generator.
  * $fileArray can also be array of array of files, like array(  'file.js', 'file2.js', array( 'file5.js' ) )
  * The name of the cached file is a md5 hash consistant of the file paths
  * of the valid files in $file_array and the packlevel. 
  * The whole argument is used instead of file path on js/ css generators in the cache hash.
  *
  * @param array|string $fileArray Either array of file paths, or string with file path
  * @param string $subPath In witch sub path of design folder to look for files.
  * @param string $fileExtension File extension name (for use on cache file)
  * @param int $packLevel Level of packing, values: 0-3
  * @param bool $wwwInCacheHash To add www path in cahce hash or not
  * @return array List of css files
  */
 static function packFiles($fileArray, $subPath = '', $fileExtension = '.js', $packLevel = 2, $wwwInCacheHash = false)
 {
     if (!$fileArray) {
         return array();
     } else {
         if (!is_array($fileArray)) {
             $fileArray = array($fileArray);
         }
     }
     $cacheName = '';
     $lastmodified = 0;
     $httpFiles = array();
     $validFiles = array();
     $validWWWFiles = array();
     $bases = eZTemplateDesignResource::allDesignBases();
     // Only pack files if Packer is enabled and if not set DevelopmentMode is disabled
     $ezjscINI = eZINI::instance('ezjscore.ini');
     if ($ezjscINI->hasVariable('eZJSCore', 'Packer')) {
         $packerIniValue = $ezjscINI->variable('eZJSCore', 'Packer');
         if ($packerIniValue === 'disabled') {
             $packLevel = 0;
         } else {
             if (is_numeric($packerIniValue)) {
                 $packLevel = (int) $packerIniValue;
             }
         }
     } else {
         $ini = eZINI::instance();
         if ($ini->variable('TemplateSettings', 'DevelopmentMode') === 'enabled') {
             $packLevel = 0;
         }
     }
     $packerInfo = array('file_extension' => $fileExtension, 'pack_level' => $packLevel, 'sub_path' => $subPath, 'cache_dir' => self::getCacheDir(), 'www_dir' => self::getWwwDir());
     // needed for image includes to work on ezp installs with mixed access methods (virtualhost + url based setup)
     if ($wwwInCacheHash) {
         $cacheName = $packerInfo['www_dir'];
     }
     while (count($fileArray) > 0) {
         $file = array_shift($fileArray);
         // if $file is array, concat it to the file array and continue
         if ($file && is_array($file)) {
             $fileArray = array_merge($file, $fileArray);
             continue;
         } else {
             if (!$file) {
                 continue;
             } else {
                 if (strpos($file, '::') !== false) {
                     $server = self::serverCallHelper(explode('::', $file));
                     $fileTime = $server->getCacheTime($packerInfo);
                     // generate content straight away if packing is disabled
                     if ($packLevel === 0) {
                         $validWWWFiles[] = $server->call($fileArray);
                     } else {
                         if ($fileTime === -1) {
                             $validFiles[] = $server->call($fileArray);
                         } else {
                             $validFiles[] = $server;
                             $cacheName .= $file . '_';
                         }
                     }
                     $lastmodified = max($lastmodified, $fileTime);
                     continue;
                 } else {
                     if (strpos($file, 'http://') === 0 || strpos($file, 'https://') === 0) {
                         $httpFiles[] = $file;
                         continue;
                     } else {
                         if (strpos($file, 'var/') === 0) {
                             if (substr($file, 0, 2) === '//' || preg_match("#^[a-zA-Z0-9]+:#", $file)) {
                                 $file = '/';
                             } else {
                                 if (strlen($file) > 0 && $file[0] !== '/') {
                                     $file = '/' . $file;
                                 }
                             }
                             eZURI::transformURI($file, true, 'relative');
                             // get file time and continue if it return false
                             $file = str_replace('//' . $packerInfo['www_dir'], '', '//' . $file);
                             $fileTime = file_exists($file) ? filemtime($file) : false;
                             $wwwFile = $packerInfo['www_dir'] . $file;
                         } else {
                             // allow path to be outside subpath if it starts with '/'
                             if ($file[0] === '/') {
                                 $file = ltrim($file, '/');
                             } else {
                                 $file = $subPath . $file;
                             }
                             $triedFiles = array();
                             $match = eZTemplateDesignResource::fileMatch($bases, '', $file, $triedFiles);
                             if ($match === false) {
                                 eZDebug::writeWarning("Could not find: {$file}", __METHOD__);
                                 continue;
                             }
                             $file = htmlspecialchars($match['path']);
                             $fileTime = file_exists($file) ? filemtime($file) : false;
                             $wwwFile = $packerInfo['www_dir'] . $file;
                         }
                     }
                 }
             }
         }
         if ($fileTime === false) {
             eZDebug::writeWarning("Could not get modified time of file: {$file}", __METHOD__);
             continue;
         }
         // calculate last modified time and store in arrays
         $lastmodified = max($lastmodified, $fileTime);
         $validFiles[] = $file;
         $validWWWFiles[] = $wwwFile;
         // STEVO
         $cacheName .= $file . '_' . $fileTime . '_';
     }
     // if packing is disabled, return the valid paths / content we have generated
     if ($packLevel === 0) {
         return array_merge($httpFiles, $validWWWFiles);
     }
     if (!$validFiles) {
         eZDebug::writeWarning("Could not find any files: " . var_export($fileArray, true), __METHOD__);
         return array();
     }
     // generate cache file name and path
     $cacheName = md5($cacheName . $packLevel) . $fileExtension;
     $cachePath = $packerInfo['cache_dir'] . $subPath;
     if (file_exists($cachePath . $cacheName)) {
         // check last modified time and return path to cache file if valid
         if ($lastmodified <= filemtime($cachePath . $cacheName)) {
             $httpFiles[] = $packerInfo['www_dir'] . $cachePath . $cacheName;
             return $httpFiles;
         }
     }
     // Merge file content and create new cache file
     $content = '';
     foreach ($validFiles as $file) {
         // if this is a js / css generator, call to get content
         if ($file instanceof ezjscServerRouter) {
             $content .= $file->call($validFiles);
             continue;
         } else {
             if (!$file) {
                 continue;
             }
         }
         // else, get content of normal file
         $fileContent = file_get_contents($file);
         if (!trim($fileContent)) {
             $content .= "/* empty: {$file} */\r\n";
             continue;
         }
         // we need to fix relative background image paths if this is a css file
         if (strpos($fileExtension, '.css') !== false) {
             $fileContent = ezjscPacker::fixImgPaths($fileContent, $file);
         }
         $content .= "/* start: {$file} */\r\n";
         $content .= $fileContent;
         $content .= "\r\n/* end: {$file} */\r\n\r\n";
     }
     // Pack the file to save bandwidth
     if ($packLevel > 1) {
         if (strpos($fileExtension, '.css') !== false) {
             $content = ezjscPacker::optimizeCSS($content, $packLevel);
         } else {
             $content = ezjscPacker::optimizeScript($content, $packLevel);
         }
     }
     // save file and return path if sucsessfull
     if (eZFile::create($cacheName, $cachePath, $content)) {
         $httpFiles[] = $packerInfo['www_dir'] . $cachePath . $cacheName;
         return $httpFiles;
     }
     return array();
 }
 public static function filter($module, $node, $tpl, $viewMode)
 {
     //Make it compatable with patches before 5.2 and 5.2(no patch) because a patch reverse
     //Ref.https://github.com/ezsystems/ezpublish-legacy/commit/85ab7fb8374f31c5cba00450e71d27e456552878
     if (!$module instanceof eZModule) {
         $viewMode = $tpl;
         $tpl = $node;
         $node = $module;
         $module = null;
     }
     //End of compatability fix
     $ini = eZINI::instance('override.ini');
     $conditions = $ini->groups();
     $nodeID = $node->attribute('node_id');
     $object = $node->attribute('object');
     $classIdentifier = $object->attribute('class_identifier');
     $overrideClass = null;
     foreach ($conditions as $condition) {
         if (isset($condition['Match'])) {
             $matches = $condition['Match'];
             // node condition
             $matchNode = null;
             if (isset($matches['node'])) {
                 if ($matches['node'] == $nodeID) {
                     $matchNode = true;
                 } else {
                     $matchNode = false;
                 }
             }
             // class_identifier condition
             $matchClass = null;
             if (isset($matches['class_identifier'])) {
                 if ($matches['class_identifier'] == $classIdentifier) {
                     $matchClass = true;
                 } else {
                     $matchClass = false;
                 }
             }
             // view mode condition
             $matchViewmode = null;
             if (isset($matches['viewmode'])) {
                 if ($matches['viewmode'] == $viewMode) {
                     $matchViewmode = true;
                 } else {
                     $matchViewmode = false;
                 }
             }
             $useIt = false;
             // When viewmode is not set or viewmode matches
             if (!isset($matchViewmode) || $matchViewmode === true) {
                 // When class_identifier is not set or class_identifier matches
                 if (!isset($matchClass) || $matchClass === true) {
                     // When node(id) is not set or node(id) matches
                     if (!isset($matchNode) || $matchNode === true) {
                         if (isset($condition['Class'])) {
                             $overrideClass = $condition['Class'];
                             break;
                         }
                     }
                 }
             }
         }
     }
     //Support Match[attribute_<attribute_identifier>]=<value> in override.ini
     $object = $node->attribute('object');
     $dataMap = $object->dataMap();
     $ini = eZINI::instance('xoverride.ini');
     $siteAccessesMatch = false;
     if (!$ini->hasVariable('TemplateOverride', 'AvailableSiteAccess')) {
         $siteAccessesMatch = true;
     } else {
         $siteAccesses = $ini->variable('TemplateOverride', 'AvailableSiteAccess');
         $currentSiteAccessArray = eZSiteAccess::current();
         $currentSiteAccess = $currentSiteAccessArray['name'];
         if (is_array($siteAccesses) && (in_array($currentSiteAccess, $siteAccesses) or in_array('*', $siteAccesses))) {
             $siteAccessesMatch = true;
         }
     }
     if ($siteAccessesMatch) {
         $supportedDatatype = $ini->variable('General', 'SupportedDatatype');
         $keys = array();
         foreach ($dataMap as $attributeId => $attribute) {
             $dataType = $attribute->attribute('data_type_string');
             if (in_array($dataType, $supportedDatatype)) {
                 $value = $attribute->attribute('content');
                 $keys[] = array('attribute_' . $attributeId, $value);
             }
         }
         $res = eZTemplateDesignResource::instance();
         $res->setKeys($keys);
         if (!empty($overrideClass)) {
             $overrideView = new $overrideClass();
             $http = eZHTTPTool::instance();
             eZDebug::writeNotice("Loading nodeview render {$overrideClass}, node id: {$nodeID}", __METHOD__);
             $overrideView->initNodeview($module, $node, $tpl, $viewMode);
         }
     }
 }
Пример #17
0
 /**
  * Internal function to get current index dir
  *
  * @return string
  */
 protected static function getDesignFile($file)
 {
     static $bases = null;
     static $wwwDir = null;
     if ($bases === null) {
         $bases = eZTemplateDesignResource::allDesignBases();
     }
     if ($wwwDir === null) {
         $wwwDir = eZSys::wwwDir() . '/';
     }
     $triedFiles = array();
     $match = eZTemplateDesignResource::fileMatch($bases, '', $file, $triedFiles);
     if ($match === false) {
         eZDebug::writeWarning("Could not find: {$file}", __METHOD__);
         return false;
     }
     return $wwwDir . htmlspecialchars($match['path']);
 }
function generateDefaultTemplate( $http, $template, $fileName )
{
    $templateCode = "";
    // Check what kind of contents we should create in the template
    switch ( $http->postVariable( 'TemplateContent' ) )
    {
        case 'DefaultCopy' :
        {
            $siteAccess = $http->sessionVariable( 'eZTemplateAdminCurrentSiteAccess' );
            $overrideArray = eZTemplateDesignResource::overrideArray( $siteAccess );
            $fileName = $overrideArray[$template]['base_dir'] . $overrideArray[$template]['template'];
            $fp = fopen( $fileName, 'rb' );
            if ( $fp )
            {
                $codeFromFile = fread( $fp, filesize( $fileName ) );

                // Remove the "{* DO NOT EDIT... *}" first line (if exists).
                $templateCode = preg_replace('@^{\*\s*DO\sNOT\sEDIT.*?\*}\n(.*)@s', '$1', $codeFromFile);
            }
            else
            {
                eZDebug::writeError( "Could not open file $fileName, check read permissions" );
            }
            fclose( $fp );
        }break;

        default:
        case 'EmptyFile' :
        {
            $templateCode = '{*?template charset=latin1?*}' .
                 '<!DOCTYPE html>' . "\n" .
                 '<html lang="en">' .
                 '<head>' . "\n" .
                 '    <link rel="stylesheet" type="text/css" href={"stylesheets/core.css"|ezdesign} />' . "\n" .
                 '    <link rel="stylesheet" type="text/css" href={"stylesheets/debug.css"|ezdesign} />' . "\n" .
                 '    {include uri="design:page_head.tpl"}' . "\n" .
                 '</head>' . "\n" .
                 '<body>' . "\n" .
                 '{$module_result.content}' . "\n" .
                 '<!--DEBUG_REPORT-->' . "\n" .
                 '</body>' . "\n" .
                 '</html>' . "\n";
        }break;
    }
    return $templateCode;
}
Пример #19
0
 /**
  * Retrieve content view data
  *
  * @see contentViewGenerate()
  *
  * @param string $file
  * @param int $mtime File modification time
  * @param array $args Hash containing arguments, the used ones are:
  *  - ini
  *
  * @return \eZClusterFileFailure
  */
 public static function contentViewRetrieve($file, $mtime, $args)
 {
     extract($args);
     $cacheExpired = false;
     // Read Cache file
     if (!eZContentObject::isCacheExpired($mtime)) {
         //        $contents = $cacheFile->fetchContents();
         $contents = file_get_contents($file);
         $Result = unserialize($contents);
         if (!is_array($Result)) {
             $expiryReason = 'Unexpected cache file content';
             $cacheExpired = true;
         }
         // Check if a no_cache key has been set in the viewcache, and
         // return an eZClusterFileFailure if it has
         if (isset($Result['no_cache'])) {
             return new eZClusterFileFailure(3, "Cache has been disabled for this node");
         }
         // Check if cache has expired when cache_ttl is set
         $cacheTTL = isset($Result['cache_ttl']) ? $Result['cache_ttl'] : -1;
         if ($cacheTTL > 0) {
             $expiryTime = $mtime + $cacheTTL;
             if (time() > $expiryTime) {
                 $cacheExpired = true;
                 $expiryReason = 'Content cache is expired by cache_ttl=' . $cacheTTL;
             }
         }
         // Check if template source files are newer, but only if the cache is not expired
         if (!$cacheExpired) {
             $developmentModeEnabled = $ini->variable('TemplateSettings', 'DevelopmentMode') == 'enabled';
             // Only do filemtime checking when development mode is enabled.
             if ($developmentModeEnabled && isset($Result['template_list'])) {
                 foreach ($Result['template_list'] as $templateFile) {
                     if (!file_exists($templateFile)) {
                         $cacheExpired = true;
                         $expiryReason = "Content cache is expired by template file '" . $templateFile . "', it does not exist anymore";
                         break;
                     } else {
                         if (filemtime($templateFile) > $mtime) {
                             $cacheExpired = true;
                             $expiryReason = "Content cache is expired by template file '" . $templateFile . "'";
                             break;
                         }
                     }
                 }
             }
         }
         if (!$cacheExpired) {
             if (!isset($Result['content_info'])) {
                 // set error type & number for kernel errors (see https://jira.ez.no/browse/EZP-23046)
                 if (isset($Result['errorType']) && isset($Result['errorNumber'])) {
                     $res = eZTemplateDesignResource::instance();
                     $res->setKeys(array(array('error_type', $Result['errorType']), array('error_number', $Result['errorNumber'])));
                 }
                 return $Result;
             }
             $keyArray = array(array('object', $Result['content_info']['object_id']), array('node', $Result['content_info']['node_id']), array('parent_node', $Result['content_info']['parent_node_id']), array('parent_node_remote_id', $Result['content_info']['parent_node_remote_id']), array('parent_object_remote_id', $Result['content_info']['parent_object_remote_id']), array('class', $Result['content_info']['class_id']), array('view_offset', $Result['content_info']['offset']), array('navigation_part_identifier', $Result['content_info']['navigation_part_identifier']), array('viewmode', $Result['content_info']['viewmode']), array('depth', $Result['content_info']['node_depth']), array('remote_id', $Result['content_info']['remote_id']), array('node_remote_id', $Result['content_info']['node_remote_id']), array('url_alias', $Result['content_info']['url_alias']), array('persistent_variable', $Result['content_info']['persistent_variable']), array('class_group', $Result['content_info']['class_group']), array('parent_class_id', $Result['content_info']['parent_class_id']), array('parent_class_identifier', $Result['content_info']['parent_class_identifier']), array('state', $Result['content_info']['state']), array('state_identifier', $Result['content_info']['state_identifier']), array('section', $Result['section_id']));
             if (isset($Result['content_info']['class_identifier'])) {
                 $keyArray[] = array('class_identifier', $Result['content_info']['class_identifier']);
             }
             $res = eZTemplateDesignResource::instance();
             $res->setKeys($keyArray);
             return $Result;
         }
     } else {
         $expiryReason = 'Content cache is expired by eZContentObject::isCacheExpired(' . $mtime . ")";
     }
     // Cache is expired so return specialized cluster object
     if (!isset($expiryReason)) {
         $expiryReason = 'Content cache is expired';
     }
     return new eZClusterFileFailure(1, $expiryReason);
 }
Пример #20
0
    function templateNodeTransformation( $functionName, &$node,
                                         $tpl, $parameters, $privateData )
    {
        if ( !isset( $this->Rules[$functionName] ) )
            return false;
        $rule = $this->Rules[$functionName];
        $resourceData = $privateData['resource-data'];

        $parameters = eZTemplateNodeTool::extractFunctionNodeParameters( $node );
        $inputName = $rule['input_name'];
        if ( !isset( $parameters[$inputName] ) )
        {
            return false;
        }
        $inputData = $parameters[$inputName];
        $outputName = $rule['output_name'];

        $newNodes = array();

        $viewDir = '';
        $renderMode = false;
        if ( isset( $rule["render_mode"] ) )
        {
            $renderMode = $rule["render_mode"];
        }
        if ( isset( $parameters['render-mode'] ) )
        {
            $renderData = $parameters['render-mode'];
            if ( !eZTemplateNodeTool::isConstantElement( $renderData ) )
            {
                return false;
            }
            $renderMode = eZTemplateNodeTool::elementConstantValue( $renderData );
        }
        if ( $renderMode )
            $view_dir .= "/render-$renderMode";

        $viewValue = false;
        $viewName = false;
        if ( $rule['use_views'] )
        {
            $viewName = $rule['use_views'];
            if ( isset( $parameters[$viewName] ) )
            {
                $viewData = $parameters[$viewName];
                if ( !eZTemplateNodeTool::isConstantElement( $viewData ) )
                {
                    return false;
                }
                $viewValue = eZTemplateNodeTool::elementConstantValue( $viewData );
                $viewDir .= '/' . $viewValue;
            }
            else
            {
                if ( !( isset( $rule['optional_views'] ) && $rule['optional_views'] ) )
                {
                    return false;
                }
            }
        }

        $namespaceValue = false;
        if ( isset( $rule['namespace'] ) )
        {
            $namespaceValue = $rule['namespace'];
        }

        $variableList = array();

        $newNodes[] = eZTemplateNodeTool::createVariableNode( false, $inputData, false, array(),
                                                              array( $namespaceValue, eZTemplate::NAMESPACE_SCOPE_RELATIVE, $outputName ) );
        $variableList[] = $outputName;

        foreach ( array_keys( $parameters ) as $parameterName )
        {
            if ( $parameterName == $inputName or
                 $parameterName == $outputName or
                 $parameterName == $viewName )
                continue;

            $newNodes[] = eZTemplateNodeTool::createVariableNode( false, $parameters[$parameterName], false, array(),
                                                                  array( $namespaceValue, eZTemplate::NAMESPACE_SCOPE_RELATIVE, $parameterName ) );
            $variableList[] = $parameterName;
        }

        $templateRoot = $rule["template_root"];
        $matchFileArray = eZTemplateDesignResource::overrideArray();

        if ( is_string( $templateRoot ) )
        {
            $resourceNodes = $this->resourceAcquisitionTransformation( $functionName, $node, $rule, $inputData,
                                                                       $outputName, $namespaceValue,
                                                                       $templateRoot, $viewDir, $viewValue,
                                                                       $matchFileArray, 0, $resourceData );
            // If the transformation failed we return false to invoke interpreted mode
            if ( $resourceNodes === false )
                return false;
            $newNodes = array_merge( $newNodes, $resourceNodes );
        }
        else
        {
            if ( isset( $templateRoot['type'] ) and
                 $templateRoot['type'] == 'multi_match' and
                 isset( $templateRoot['attributes'] ) and
                 isset( $templateRoot['matches'] ) )
            {
                $attributeAccessData = array();
                $attributeAccessData[] = eZTemplateNodeTool::createVariableElement( $outputName, $namespaceValue, eZTemplate::NAMESPACE_SCOPE_RELATIVE );
                foreach ( $templateRoot['attributes'] as $rootAttributeName )
                {
                    $attributeAccessData[] = eZTemplateNodeTool::createAttributeLookupElement( $rootAttributeName );
                }
                $newNodes[] = eZTemplateNodeTool::createVariableNode( false, $attributeAccessData, false,
                                                                      array( 'spacing' => 0 ), 'templateRootMatch' );
                $rootMatchCounter = 0;
                foreach ( $templateRoot['matches'] as $rootMatch )
                {
                    $templateRoot = $rootMatch[1];

                    if ( is_array( $templateRoot ) )
                    {
                        $templateRoot = $templateRoot[0];
                    }

                    $resourceNodes = $this->resourceAcquisitionTransformation( $functionName, $node, $rule, $inputData,
                                                                               $outputName, $namespaceValue,
                                                                               $templateRoot, $viewDir, $viewValue,
                                                                               $matchFileArray, 4, $resourceData );

                    // If this transformation failed we continue to the next root match
                    if ( $resourceNodes === false )
                        continue;

                    $rootMatchValueText = eZPHPCreator::variableText( $rootMatch[0], 0, 0, false );
                    $code = '';
                    if ( $rootMatchCounter > 0 )
                    {
                        $code .= "else " . ( $resourceData['use-comments'] ? ( "/*OF:" . __LINE__ . "*/" ) : "" ) . "";
                    }
                    $code .= "if " . ( $resourceData['use-comments'] ? ( "/*OF:" . __LINE__ . "*/" ) : "" ) . "( \$templateRootMatch == $rootMatchValueText )\n{";
                    $newNodes[] = eZTemplateNodeTool::createCodePieceNode( $code );
                    $newNodes = array_merge( $newNodes, $resourceNodes );
                    $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "}" );
                    ++$rootMatchCounter;
                }

                // If the transformation failed we invoke interpreted mode
                if ( $rootMatchCounter == 0 )
                {
                    return false;
                }

                $newNodes[] = eZTemplateNodeTool::createVariableUnsetNode( 'templateRootMatch' );
            }
        }

        foreach ( $variableList as $variableName )
        {
            $newNodes[] = eZTemplateNodeTool::createVariableUnsetNode( array( $namespaceValue, eZTemplate::NAMESPACE_SCOPE_RELATIVE, $variableName ) );
        }

        return $newNodes;
    }
    function installTemplates( $templateList, $package, $subdirectory, &$installParameters )
    {
        if ( !$templateList )
        {
            return true;
        }
        $siteAccessDesignPathArray = array();
        $templateRootPath = $package->path() . '/' . $subdirectory;
        foreach( $templateList->getElementsByTagName( 'file' ) as $fileNode )
        {
            $originalSiteAccess = $fileNode->getAttribute( 'site-access' );
            if ( isset( $installParameters['site_access_map'][$originalSiteAccess] ) )
            {
                $newSiteAccess = $installParameters['site_access_map'][$originalSiteAccess];
            }
            else
            {
                $newSiteAccess = $installParameters['site_access_map']['*'];
            }

            if ( !isset( $siteAccessDesignPathArray[$newSiteAccess] ) )
            {
                $ini = eZINI::instance( 'site.ini', 'settings', null, null, true );
                $ini->prependOverrideDir( "siteaccess/$newSiteAccess", false, 'siteaccess' );
                $ini->loadCache();

                if ( isset( $installParameters['design_map'] ) )
                {
                    $designMap = $installParameters['design_map'];
                    if ( isset( $designMap[$originalSiteAccess] ) )
                        $siteAccessDesignPathArray[$newSiteAccess] = eZTemplateDesignResource::designStartPath() . '/' . $designMap[$originalSiteAccess];
                    else
                        $siteAccessDesignPathArray[$newSiteAccess] = eZTemplateDesignResource::designStartPath() . '/' . $designMap['*'];
                }
                else
                {
                    $siteAccessDesignPathArray[$newSiteAccess] = eZTemplateDesignResource::designStartPath() . '/' . $ini->variable( "DesignSettings", "StandardDesign" );
                }
            }

            $path = '';
            foreach( $fileNode->childNodes as $pathNode )
            {
                if ( $pathNode->nodeName == 'path' )
                {
                    $path = $pathNode->nodeValue;
                    break;
                }
            }

            $sourcePath = $templateRootPath . $path;
            $destinationPath = $siteAccessDesignPathArray[$newSiteAccess] . $path;

            eZDir::mkdir( eZDir::dirpath( $destinationPath ), false, true );
            if ( !eZFileHandler::copy( $sourcePath, $destinationPath ) )
                return false;

//             eZDebug::writeNotice( 'Copied: "' . $sourcePath . '" to: "' . $destinationPath . '"', __METHOD__ );
        }
        return true;
    }
Пример #22
0
    function checkContentActions( $module, $class, $object, $version, $contentObjectAttributes, $EditVersion, $EditLanguage, $FromLanguage, &$Result )
    {
        if ( $module->isCurrentAction( 'Preview' ) )
        {
            $module->redirectToView( 'versionview', array( $object->attribute('id'), $EditVersion, $EditLanguage, $FromLanguage ) );
            return eZModule::HOOK_STATUS_CANCEL_RUN;
        }

        if ( $module->isCurrentAction( 'Translate' ) )
        {
            $module->redirectToView( 'translate', array( $object->attribute( 'id' ), $EditVersion, $EditLanguage, $FromLanguage ) );
            return eZModule::HOOK_STATUS_CANCEL_RUN;
        }

        if ( $module->isCurrentAction( 'VersionEdit' ) )
        {
            if ( isset( $GLOBALS['eZRequestedURI'] ) and is_object( $GLOBALS['eZRequestedURI'] ) )
            {
                $uri = $GLOBALS['eZRequestedURI'];
                $uri = $uri->originalURIString();
                $http = eZHTTPTool::instance();
                $http->setSessionVariable( 'LastAccessesVersionURI', $uri );
            }
            $module->redirectToView( 'history', array( $object->attribute( 'id' ), $EditVersion, $EditLanguage ) );
            return eZModule::HOOK_STATUS_CANCEL_RUN;
        }

        if ( $module->isCurrentAction( 'EditLanguage' ) )
        {
            if ( $module->hasActionParameter( 'SelectedLanguage' ) )
            {
                $EditLanguage = $module->actionParameter( 'SelectedLanguage' );
                // We reset the from language to disable the translation look
                $FromLanguage = false;
                $module->redirectToView( 'edit', array( $object->attribute('id'), $EditVersion, $EditLanguage, $FromLanguage ) );
                return eZModule::HOOK_STATUS_CANCEL_RUN;
            }
        }

        if ( $module->isCurrentAction( 'TranslateLanguage' ) )
        {
            if ( $module->hasActionParameter( 'SelectedLanguage' ) )
            {
                $FromLanguage = $EditLanguage;
                $EditLanguage = $module->actionParameter( 'SelectedLanguage' );
                $module->redirectToView( 'edit', array( $object->attribute('id'), $EditVersion, $EditLanguage, $FromLanguage ) );
                return eZModule::HOOK_STATUS_CANCEL_RUN;
            }
        }

        if ( $module->isCurrentAction( 'FromLanguage' ) )
        {
            $FromLanguage = $module->actionParameter( 'FromLanguage' );
            $module->redirectToView( 'edit', array( $object->attribute('id'), $EditVersion, $EditLanguage, $FromLanguage ) );
            return eZModule::HOOK_STATUS_CANCEL_RUN;
        }

        if ( $module->isCurrentAction( 'Discard' ) )
        {
            $http = eZHTTPTool::instance();
            $objectID = $object->attribute( 'id' );
            $discardConfirm = true;
            if ( $http->hasPostVariable( 'DiscardConfirm' ) )
                $discardConfirm = $http->postVariable( 'DiscardConfirm' );
            $http->setSessionVariable( 'DiscardObjectID', $objectID );
            $http->setSessionVariable( 'DiscardObjectVersion', $EditVersion );
            $http->setSessionVariable( 'DiscardObjectLanguage', $EditLanguage );
            $http->setSessionVariable( 'DiscardConfirm', $discardConfirm );
            $module->redirectTo( $module->functionURI( 'removeeditversion' ) . '/' );
            return eZModule::HOOK_STATUS_CANCEL_RUN;
        }

        // helper function which computes the redirect after
        // publishing and final store of a draft.
        function computeRedirect( $module, $object, $version, $EditLanguage = false )
        {
            $http = eZHTTPTool::instance();

            $node = $object->mainNode();

            if ( $http->hasSessionVariable( 'RedirectIfDiscarded' ) )
            {
                $http->removeSessionVariable( 'RedirectIfDiscarded' );
            }

            $hasRedirected = false;
            if ( $http->hasSessionVariable( 'ParentObject' ) && $http->sessionVariable( 'NewObjectID' ) == $object->attribute( 'id' ) )
            {
                $parentArray = $http->sessionVariable( 'ParentObject' );
                $parentURL = $module->redirectionURI( 'content', 'edit', $parentArray );
                $parentObject = eZContentObject::fetch( $parentArray[0] );
                $db = eZDB::instance();
                $db->begin();
                $parentObject->addContentObjectRelation( $object->attribute( 'id' ), $parentArray[1] );
                $db->commit();
                $http->removeSessionVariable( 'ParentObject' );
                $http->removeSessionVariable( 'NewObjectID' );
                $module->redirectTo( $parentURL );
                $hasRedirected = true;
            }
            if ( $http->hasSessionVariable( 'RedirectURIAfterPublish' ) && !$hasRedirected )
            {
                $uri = $http->sessionVariable( 'RedirectURIAfterPublish' );
                $http->removeSessionVariable( 'RedirectURIAfterPublish' );
                $module->redirectTo( $uri );
                $hasRedirected = true;
            }
            if ( $http->hasPostVariable( 'RedirectURIAfterPublish' )  && !$hasRedirected )
            {
                $uri = $http->postVariable( 'RedirectURIAfterPublish' );
                $module->redirectTo( $uri );
                $hasRedirected = true;
            }
            if ( $http->hasPostVariable( "BackToEdit" ) && $http->postVariable( "BackToEdit" ) )
            {
                $uri = $module->redirectionURI( 'content', 'edit', array( $object->attribute( 'id'), 'f', $EditLanguage ) );
                $module->redirectTo( $uri );
                eZDebug::writeDebug( $uri, "uri  " .  $object->attribute( 'id')  );
                $hasRedirected = true;
            }

            if ( !$hasRedirected )
            {
                if ( $http->hasPostVariable( 'RedirectURI' ) )
                {
                    $uri = $http->postVariable( 'RedirectURI' );
                    $module->redirectTo( $uri );
                }
                else if ( $node !== null )
                {
                    $parentNode = $node->attribute( 'parent_node_id' );
                    if ( $parentNode == 1 )
                    {
                        $parentNode = $node->attribute( 'node_id' );
                    }
                    $module->redirectToView( 'view', array( 'full', $parentNode ) );
                }
                else
                {
                    $module->redirectToView( 'view', array( 'full', $version->attribute( 'main_parent_node_id' ) ) );
                }
            }

        }

        if( $module->isCurrentAction( 'StoreExit' ) )
        {
            computeRedirect( $module, $object, $version, $EditLanguage );
            return eZModule::HOOK_STATUS_CANCEL_RUN;
        }

        if ( $module->isCurrentAction( 'Publish' ) )
        {
            // Checking the source and destination language from the url,
            // if they are the same no confirmation is needed.
            if ( $EditLanguage != $FromLanguage )
            {
                $conflictingVersions = $version->hasConflicts( $EditLanguage );
                if ( $conflictingVersions )
                {
                    $tpl = eZTemplate::factory();
                    $res = eZTemplateDesignResource::instance();
                    $res->setKeys( array( array( 'object', $object->attribute( 'id' ) ),
                                        array( 'remote_id', $object->attribute( 'remote_id' ) ),
                                        array( 'class', $class->attribute( 'id' ) ),
                                        array( 'class_identifier', $class->attribute( 'identifier' ) ),
                                        array( 'class_group', $class->attribute( 'match_ingroup_id_list' ) ) ) );

                    $tpl->setVariable( 'edit_language', $EditLanguage );
                    $tpl->setVariable( 'current_version', $version->attribute( 'version' ) );
                    $tpl->setVariable( 'object', $object );
                    $tpl->setVariable( 'draft_versions', $conflictingVersions );

                    $Result = array();
                    $Result['content'] = $tpl->fetch( 'design:content/edit_conflict.tpl' );
                    return eZModule::HOOK_STATUS_CANCEL_RUN;
                }
            }

            eZDebug::accumulatorStart( 'publish', '', 'publish' );
            $oldObjectName = $object->name();

            $behaviour = new ezpContentPublishingBehaviour();
            $behaviour->isTemporary = true;
            $behaviour->disableAsynchronousPublishing = false;
            ezpContentPublishingBehaviour::setBehaviour( $behaviour );

            $operationResult = eZOperationHandler::execute( 'content', 'publish', array( 'object_id' => $object->attribute( 'id' ),
                                                                                         'version' => $version->attribute( 'version' ) ) );
            eZDebug::accumulatorStop( 'publish' );

            if ( ( array_key_exists( 'status', $operationResult ) && $operationResult['status'] != eZModuleOperationInfo::STATUS_CONTINUE ) )
            {
                eZDebug::writeDebug( $operationResult, __FILE__ );
                switch( $operationResult['status'] )
                {
                    case eZModuleOperationInfo::STATUS_REPEAT:
                    {
                        eZContentOperationCollection::setVersionStatus( $object->attribute( 'id' ),
                            $version->attribute( 'version' ), eZContentObjectVersion::STATUS_REPEAT );
                    }
                    case eZModuleOperationInfo::STATUS_HALTED:
                    {
                        if ( isset( $operationResult['redirect_url'] ) )
                        {
                            $module->redirectTo( $operationResult['redirect_url'] );
                            return;
                        }
                        else if ( isset( $operationResult['result'] ) )
                        {
                            $result = $operationResult['result'];
                            $resultContent = false;
                            if ( is_array( $result ) )
                            {
                                if ( isset( $result['content'] ) )
                                {
                                    $resultContent = $result['content'];
                                }
                                if ( isset( $result['path'] ) )
                                {
                                    $Result['path'] = $result['path'];
                                }
                            }
                            else
                            {
                                $resultContent = $result;
                            }
                            // Temporary fix to make approval workflow work with edit.
                            if ( strpos( $resultContent, 'Deffered to cron' ) === 0 )
                            {
                                $Result = null;
                            }
                            else
                            {
                                $Result['content'] = $resultContent;
                            }
                        }
                    }break;
                    case eZModuleOperationInfo::STATUS_CANCELLED:
                    {
                        $Result = array();
                        $Result['content'] = "Content publish cancelled<br/>";
                    }
                }

                /* If we already have a correct module result
                 * we don't need to continue module execution.
                 */
                if ( is_array( $Result ) )
                    return eZModule::HOOK_STATUS_CANCEL_RUN;
            }

            // update content object attributes array by refetching them from database
            $object = eZContentObject::fetch( $object->attribute( 'id' ) );
            $contentObjectAttributes = $object->attribute( 'contentobject_attributes' );

            // set chosen hidden/invisible attributes for object nodes
            $http          = eZHTTPTool::instance();
            $assignedNodes = $object->assignedNodes( true );
            foreach ( $assignedNodes as $node )
            {
                $nodeID               = $node->attribute( 'node_id' );
                $parentNodeID         = $node->attribute( 'parent_node_id' );
                $updateNodeVisibility =  false;
                $postVarName          = "FutureNodeHiddenState_$parentNodeID";

                if ( !$http->hasPostVariable( $postVarName ) )
                    $updateNodeVisibility = true;
                else
                {
                    $futureNodeHiddenState = $http->postVariable( $postVarName );
                    $db = eZDB::instance();
                    $db->begin();
                    if ( $futureNodeHiddenState == 'hidden' )
                        eZContentObjectTreeNode::hideSubTree( $node );
                    else if ( $futureNodeHiddenState == 'visible' )
                        eZContentObjectTreeNode::unhideSubTree( $node );
                    else if ( $futureNodeHiddenState == 'unchanged' )
                        $updateNodeVisibility = true;
                    else
                        eZDebug::writeWarning( "Unknown value for the future node hidden state: '$futureNodeHiddenState'" );
                    $db->commit();
                }

                if ( $updateNodeVisibility )
                {
                    // this might be redundant
                    $db = eZDB::instance();
                    $db->begin();
                    $parentNode = eZContentObjectTreeNode::fetch( $parentNodeID );
                    eZContentObjectTreeNode::updateNodeVisibility( $node, $parentNode, /* $recursive = */ false );
                    $db->commit();
                    unset( $node, $parentNode );
                }
            }
            unset( $assignedNodes );

            $object = eZContentObject::fetch( $object->attribute( 'id' ) );

            $newObjectName = $object->name();

            $http = eZHTTPTool::instance();

            computeRedirect( $module, $object, $version, $EditLanguage );
            // we have set redirection URI for module so we don't need to continue module execution
            return eZModule::HOOK_STATUS_CANCEL_RUN;
        }
    }
Пример #23
0
 static function eZImage($tpl, $operatorValue, $operatorName, $skipSlash = false)
 {
     $sys = eZSys::instance();
     if ($skipSlash && strlen($sys->wwwDir()) != 0) {
         $skipSlash = false;
     }
     $bases = eZTemplateDesignResource::allDesignBases();
     $triedFiles = array();
     $fileInfo = eZTemplateDesignResource::fileMatch($bases, 'images', $operatorValue, $triedFiles);
     if (!$fileInfo) {
         $tpl->warning($operatorName, "Image '{$operatorValue}' does not exist in any design");
         $tpl->warning($operatorName, "Tried files: " . implode(', ', $triedFiles));
         $siteDesign = eZTemplateDesignResource::designSetting('site');
         $imgPath = "design/{$siteDesign}/images/{$operatorValue}";
     } else {
         $imgPath = $fileInfo['path'];
     }
     $operatorValue = $skipSlash ? $imgPath : $sys->wwwDir() . '/' . $imgPath;
     $operatorValue = htmlspecialchars($operatorValue);
     return $operatorValue;
 }
Пример #24
0
 /**
  * This function is only a helpfunction
  *
  * @param $mailTemplate
  * @return unknown_type
  */
 function sendSubcriptionMail($mailTemplate)
 {
     $tplResource = eZTemplateDesignResource::instance();
     $ini = eZINI::instance('site.ini');
     $cjwNewsletterIni = eZINI::instance('cjw_newsletter.ini');
     $hostName = eZSys::hostname();
     // $template = 'design:newsletter/mail/subscription_confirmation.tpl';
     $template = $mailTemplate;
     $newsletterUser = $this;
     include_once 'kernel/common/template.php';
     $tpl = templateInit();
     $tpl->setVariable('newsletter_user', $newsletterUser);
     $tpl->setVariable('hostname', $hostName);
     $templateResult = $tpl->fetch($template);
     // get subject from template var definition
     if ($tpl->hasVariable('subject')) {
         $subject = $tpl->variable('subject');
     }
     $emailSender = $cjwNewsletterIni->variable('NewsletterMailSettings', 'EmailSender');
     $emailSenderName = $cjwNewsletterIni->variable('NewsletterMailSettings', 'EmailSenderName');
     $emailReceiver = $newsletterUser->attribute('email');
     $emailReplyTo = $cjwNewsletterIni->variable('NewsletterMailSettings', 'EmailReplyTo');
     $emailReturnPath = $cjwNewsletterIni->variable('NewsletterMailSettings', 'EmailReturnPath');
     // TODO Namen extrahieren
     $emailReceiverName = '';
     $emailSubject = $subject;
     $emailBody['text'] = $templateResult;
     $cjwMail = new CjwNewsletterMail();
     // x header set for current user
     $cjwMail->setExtraMailHeadersByNewsletterUser($this);
     $cjwMail->setTransportMethodDirectlyFromIni();
     // trigger_error("test error", E_USER_ERROR);
     $sendResult = $cjwMail->sendEmail($emailSender, $emailSenderName, $emailReceiver, $emailReceiverName, $emailSubject, $emailBody, false, 'utf-8', $emailReplyTo, $emailReturnPath);
     return $sendResult;
 }
Пример #25
0
    public static function getDesignFile( $file, $triedFiles = array() )
    {
        if ( self::$designBases === null )
        {
            self::$designBases = eZTemplateDesignResource::allDesignBases();
        }

        $match = eZTemplateDesignResource::fileMatch( self::$designBases, '', $file, $triedFiles );

        if ( $match === false )
        {
            eZDebug::writeWarning( "Could not find: $file", __METHOD__ );
            return $file;
        }
        return htmlspecialchars( self::getServerURL() . '/' . $match['path'] );
    }
Пример #26
0
    static function restore( $siteDesign, $nodeID, $viewMode, $language, $offset, $roleList, $discountList, $layout,
                      $parameters = array() )
    {
        $result = array();
        $cachePathInfo = eZContentCache::cachePathInfo( $siteDesign, $nodeID, $viewMode, $language, $offset, $roleList, $discountList,
                                                        $layout, false, $parameters );
        $cacheDir = $cachePathInfo['dir'];
        $cacheFile = $cachePathInfo['file'];
        $cachePath = $cachePathInfo['path'];
        $timestamp = false;

        $cacheFile = eZClusterFileHandler::instance( $cachePath );

        if ( $cacheFile->exists() )
        {
            $timestamp = $cacheFile->mtime();
            if ( eZContentObject::isCacheExpired( $timestamp ) )
            {
                eZDebugSetting::writeDebug( 'kernel-content-view-cache', 'cache expired #2' );
                return false;
            }
            eZDebugSetting::writeDebug( 'kernel-content-view-cache', "checking viewmode '$viewMode' #1" );
            if ( eZContentObject::isComplexViewModeCacheExpired( $viewMode, $timestamp ) )
            {
                eZDebugSetting::writeDebug( 'kernel-content-view-cache', "viewmode '$viewMode' cache expired #2" );
                return false;
            }

        }

        if ( $viewMode == 'pdf' )
        {
            return $cachePath;
        }

        eZDebugSetting::writeDebug( 'kernel-content-view-cache', 'cache used #2' );

        $fileName = $cacheDir . "/" . $cacheFile;

        $cacheFile = eZClusterFileHandler::instance( $fileName );
        $contents = $cacheFile->fetchContents();

        $cachedArray = unserialize( $contents );

        $cacheTTL = $cachedArray['cache_ttl'];

        // Check if cache has expired
        if ( $cacheTTL > 0 )
        {
            $expiryTime = $timestamp + $cacheTTL;
            if ( time() > $expiryTime )
            {
                return false;
            }
        }

        // Check for template language timestamp
        $cacheCodeDate = $cachedArray['cache_code_date'];
        if ( $cacheCodeDate != self::CODE_DATE )
            return false;

        $viewMode = $cachedArray['content_info']['viewmode'];

        $res = eZTemplateDesignResource::instance();
        $res->setKeys( array( array( 'node', $nodeID ),
                              array( 'view_offset', $offset ),
                              array( 'viewmode', $viewMode ),
                              array( 'section', $cachedArray['section_id'] )
                              ) );
        $result['content_info'] = $cachedArray['content_info'];
        $result['content'] = $cachedArray['content'];

        $result['view_parameters'] = $cachedArray['content_info']['view_parameters'];

        foreach ( array( 'path', 'node_id', 'section_id', 'navigation_part' ) as $item )
        {
            if ( isset( $cachedArray[$item] ) )
            {
                $result[$item] = $cachedArray[$item];
            }
        }

        return $result;
    }
 /**
  * Clear in memory override array cache
  *
  * @static
  * @since 4.2
  */
 public static function clearInMemoryOverrideArray()
 {
     self::$overrideArrayCache = null;
     unset($GLOBALS['eZOverrideTemplateCacheMap']);
 }
Пример #28
0
function generatePDF($pdfExport, $toFile = false)
{
    if ($pdfExport == null) {
        return;
    }
    $node = $pdfExport->attribute('source_node');
    if ($node) {
        $object = $node->attribute('object');
        $tpl = eZTemplate::factory();
        $tpl->setVariable('node', $node);
        $tpl->setVariable('generate_toc', 1);
        $tpl->setVariable('tree_traverse', $pdfExport->attribute('export_structure') == 'tree' ? 1 : 0);
        $tpl->setVariable('class_array', explode(':', $pdfExport->attribute('export_classes')));
        $tpl->setVariable('show_frontpage', $pdfExport->attribute('show_frontpage'));
        if ($pdfExport->attribute('show_frontpage') == 1) {
            $tpl->setVariable('intro_text', $pdfExport->attribute('intro_text'));
            $tpl->setVariable('sub_intro_text', $pdfExport->attribute('sub_text'));
        }
        if ($toFile === false) {
            $tpl->setVariable('generate_stream', 1);
        } else {
            $tpl->setVariable('generate_file', 1);
            $tpl->setVariable('filename', $toFile);
        }
        $res = eZTemplateDesignResource::instance();
        $res->setKeys(array(array('object', $object->attribute('id')), array('node', $node->attribute('node_id')), array('parent_node', $node->attribute('parent_node_id')), array('class', $object->attribute('contentclass_id')), array('class_identifier', $object->attribute('class_identifier')), array('depth', $node->attribute('depth')), array('url_alias', $node->attribute('url_alias'))));
        $textElements = array();
        $uri = 'design:node/view/pdf.tpl';
        $tpl->setVariable('pdf_root_template', 1);
        eZTemplateIncludeFunction::handleInclude($textElements, $uri, $tpl, '', '');
        $pdf_definition = implode('', $textElements);
        $pdf_definition = str_replace(array(' ', "\r\n", "\t", "\n"), '', $pdf_definition);
        $tpl->setVariable('pdf_definition', $pdf_definition);
        $uri = 'design:node/view/execute_pdf.tpl';
        $textElements = '';
        eZTemplateIncludeFunction::handleInclude($textElements, $uri, $tpl, '', '');
    }
}
Пример #29
0
    } else {
        $subTreeList = array($http->variable("SubTreeArray"));
    }
    foreach ($subTreeList as $subTreeItem) {
        if ($subTreeItem > 0) {
            $subTreeArray[] = $subTreeItem;
        }
    }
}
$Module->setTitle("Search for: {$searchText}");
if ($useSearchCode) {
    $sortArray = array(array('attribute', true, 153), array('priority', true));
    $searchResult = eZSearch::search($searchText, array("SearchType" => $searchType, "SearchSectionID" => $searchSectionID, "SearchSubTreeArray" => $subTreeArray, 'SearchTimestamp' => $searchTimestamp, "SearchLimit" => $pageLimit, "SearchOffset" => $Offset));
}
if ($searchSectionID != -1) {
    $res = eZTemplateDesignResource::instance();
    $section = eZSection::fetch($searchSectionID);
    $keyArray = array(array('section', $searchSectionID), array('section_identifier', $section->attribute('identifier')));
    $res->setKeys($keyArray);
}
$viewParameters = array('offset' => $Offset);
$searchData = false;
$tpl->setVariable("search_data", $searchData);
$tpl->setVariable("search_section_id", $searchSectionID);
$tpl->setVariable("search_subtree_array", $subTreeArray);
$tpl->setVariable('search_timestamp', $searchTimestamp);
$tpl->setVariable("search_text", $searchText);
$tpl->setVariable('search_page_limit', $searchPageLimit);
$tpl->setVariable("view_parameters", $viewParameters);
$tpl->setVariable('use_template_search', !$useSearchCode);
if ($http->hasVariable('Mode') && $http->variable('Mode') == 'browse') {
Пример #30
0
 /**
  * Removes all template override cache files, subtree entries
  * and clears in memory override cache.
  *
  * @since 4.2
  */
 static function clearTemplateOverrideCache($cacheItem)
 {
     $cachePath = eZSys::cacheDirectory() . '/' . $cacheItem['path'];
     eZDir::recursiveDelete($cachePath);
     eZTemplateDesignResource::clearInMemoryOverrideArray();
 }