public static function fetchContentNode($nodeID, $nodePath, $languageCode, $remoteID = false)
 {
     $contentNode = null;
     if ($nodeID) {
         if (!isset($languageCode)) {
             $languageCode = false;
         }
         $contentNode = eZContentObjectTreeNode::fetch($nodeID, $languageCode);
     } else {
         if ($nodePath) {
             $nodeID = eZURLAliasML::fetchNodeIDByPath($nodePath);
             if ($nodeID) {
                 $contentNode = eZContentObjectTreeNode::fetch($nodeID);
             }
         } else {
             if ($remoteID) {
                 $contentNode = eZContentObjectTreeNode::fetchByRemoteID($remoteID);
             }
         }
     }
     if ($contentNode === null) {
         $retVal = array('error' => array('error_type' => 'kernel', 'error_code' => eZError::KERNEL_NOT_FOUND));
     } else {
         $retVal = array('result' => $contentNode);
     }
     return $retVal;
 }
 function modify($tpl, $operatorName, $operatorParameters, $rootNamespace, $currentNamespace, &$operatorValue, $namedParameters)
 {
     switch ($operatorName) {
         case 'ngurl':
             if (empty($namedParameters['siteaccess'])) {
                 return;
             }
             $ini = eZSiteAccess::getIni($namedParameters['siteaccess'], 'site.ini');
             $destinationLocale = $ini->variable('RegionalSettings', 'ContentObjectLocale');
             $siteLanguageList = $ini->variable('RegionalSettings', 'SiteLanguageList');
             $nodeID = eZURLAliasML::fetchNodeIDByPath($operatorValue);
             $destinationElement = eZURLAliasML::fetchByAction('eznode', $nodeID, $destinationLocale, false);
             if (empty($destinationElement) || !isset($destinationElement[0]) && !$destinationElement[0] instanceof eZURLAliasML) {
                 if ($this->isModuleUrl($operatorValue) || $this->isCurrentLocaleAvailable($siteLanguageList)) {
                     $destinationUrl = $operatorValue;
                 } else {
                     $destinationUrl = '';
                 }
             } else {
                 $destinationUrl = $destinationElement[0]->getPath($destinationLocale, $siteLanguageList);
             }
             $siteaccessUrlMapping = eZINI::instance('nglanguageswitcher.ini')->variable('LanguageSwitcher', 'SiteAccessUrlMapping');
             $destinationUrl = eZURI::encodeURL($destinationUrl);
             $operatorValue = rtrim($siteaccessUrlMapping[$namedParameters['siteaccess']], '/') . '/' . ltrim($destinationUrl, '/');
             break;
     }
 }
 public function fetchUrlAlias($nodeId = null, $path = null, $locale)
 {
     if (!$nodeId && !$path) {
         return array('result' => false);
     }
     if (empty($locale) || !is_string($locale)) {
         return array('result' => false);
     }
     if (is_numeric($nodeId)) {
         $destinationElement = eZURLAliasML::fetchByAction('eznode', $nodeId, $locale, false);
     } else {
         if (is_string($path)) {
             $nodeId = eZURLAliasML::fetchNodeIDByPath($path);
             $destinationElement = eZURLAliasML::fetchByAction('eznode', $nodeId, $locale, false);
         }
     }
     if (empty($destinationElement) || !isset($destinationElement[0]) && !$destinationElement[0] instanceof eZURLAliasML) {
         // Either no translation exists for $locale or $path was not pointing to a node
         return array('result' => false);
     }
     $currentLanguageCodes = eZContentLanguage::prioritizedLanguageCodes();
     array_unshift($currentLanguageCodes, $locale);
     $currentLanguageCodes = array_unique($currentLanguageCodes);
     $urlAlias = $destinationElement[0]->getPath($locale, $currentLanguageCodes);
     return array('result' => $urlAlias);
 }
 function runOperation(&$node)
 {
     $target_parent_node_id = $this->target_id;
     if (empty($target_parent_node_id)) {
         if ($this->move_to_depth >= $node->attribute('depth')) {
             return false;
         }
         // Find the correct target node for the specified depth
         $path_array = $node->attribute('path_array');
         $target_parent_node_id = $path_array[$this->move_to_depth - 1];
     }
     $assigned_nodes = $node->attribute('object')->attribute('assigned_nodes');
     // Find the target node
     foreach ($assigned_nodes as $target_node) {
         if ($target_node->attribute('parent_node_id') == $target_parent_node_id) {
             $target_node_id = $target_node->attribute('node_id');
             // Make sure target node is not us
             if ($node->attribute('node_id') == $target_node_id) {
                 return false;
             }
             $urlalias_list = eZURLAliasML::fetchByAction('eznode', $node->attribute('node_id'));
             $target_node_urlalias_list = eZURLAliasML::fetchByAction('eznode', $target_node_id);
             // Sanity check, this should never happen
             if (!isset($target_node_urlalias_list[0])) {
                 eZDebug::writeError('Found no url alias records for node with id ' . $target_node_id, 'batchtool/nodemerge');
                 return false;
             }
             $target_node_urlalias_id = $target_node_urlalias_list[0]->attribute('id');
             $target_parent_urlalias_id = $target_node_urlalias_list[0]->attribute('parent');
             $db = eZDB::instance();
             $db->begin();
             // Make sure any children nodes are moved to the new node
             foreach ($node->attribute('children') as $child) {
                 moveNode($child, $target_node_id);
             }
             // Make sure any bookmarks are moved to the new node
             $bookmark_list = eZPersistentObject::fetchObjectList(eZContentBrowseBookmark::definition(), null, array('node_id' => $node->attribute('node_id')));
             foreach ($bookmark_list as $bookmark) {
                 $bookmark->setAttribute('node_id', $target_node_id);
                 $bookmark->store();
             }
             // Remove the node in question
             $node->removeNodeFromTree(true);
             // Set up url alias redirects to the new node
             foreach ($urlalias_list as $url_alias) {
                 $url_alias->setAttribute('action', 'eznode:' . $target_node_id);
                 $url_alias->setAttribute('action_type', 'eznode');
                 $url_alias->setAttribute('link', $target_node_urlalias_id);
                 $url_alias->setAttribute('is_original', 0);
                 $url_alias->store();
             }
             $db->commit();
             return true;
         }
     }
     return false;
 }
 /**
  * Returns URL alias for the specified <var>$locale</var>
  *
  * @param string $url
  * @param string $locale
  * @return void
  */
 public function destinationUrl()
 {
     $nodeId = $this->origUrl;
     $urlAlias = '';
     if (!is_numeric($this->origUrl)) {
         if (!$this->isUrlPointingToModule($this->origUrl)) {
             $this->origUrl = self::addPathPrefixIfNeeded($this->origUrl);
         }
         $nodeId = eZURLAliasML::fetchNodeIDByPath($this->origUrl);
     }
     $siteLanguageList = $this->getSiteAccessIni()->variable('RegionalSettings', 'SiteLanguageList');
     // set prioritized languages of destination SA, and fetch corresponding (prioritized) URL alias
     eZContentLanguage::setPrioritizedLanguages($siteLanguageList);
     $destinationElement = eZURLAliasML::fetchByAction('eznode', $nodeId, false, true);
     eZContentLanguage::clearPrioritizedLanguages();
     if (empty($destinationElement) || !isset($destinationElement[0]) && !$destinationElement[0] instanceof eZURLAliasML) {
         // If the return of fetchByAction is empty, it can mean a couple
         // of different things:
         // Either we are looking at a module, and we should pass the
         // original URL on
         //
         // Or we are looking at URL which does not exist in the
         // destination siteaccess, for instance an untranslated object. In
         // which case we will point to the root of the site, unless it is
         // available as a fallback.
         if ($nodeId) {
             $urlAlias = $this->origUrl;
             // if applicable, remove destination PathPrefix from url
             if (!self::removePathPrefixIfNeeded($this->getSiteAccessIni(), $urlAlias)) {
                 // If destination siteaccess has a PathPrefix but url is not matched,
                 // also check current SA's prefix, and remove if it matches.
                 self::removePathPrefixIfNeeded(eZINI::instance('site.ini'), $urlAlias);
             }
         } else {
             if ($this->isUrlPointingToModule($this->origUrl)) {
                 $urlAlias = $this->origUrl;
             }
         }
     } else {
         // Translated object found, forwarding to new URL.
         $urlAlias = $destinationElement[0]->getPath($this->destinationLocale, $siteLanguageList);
         // if applicable, remove destination PathPrefix from url
         self::removePathPrefixIfNeeded($this->getSiteAccessIni(), $urlAlias);
         $urlAlias .= $this->userParamString;
     }
     $this->baseDestinationUrl = rtrim($this->baseDestinationUrl, '/');
     $ini = eZINI::instance();
     if ($GLOBALS['eZCurrentAccess']['type'] === eZSiteAccess::TYPE_URI && !($ini->variable('SiteAccessSettings', 'RemoveSiteAccessIfDefaultAccess') === "enabled" && $ini->variable('SiteSettings', 'DefaultAccess') == $this->destinationSiteAccess)) {
         $finalUrl = $this->baseDestinationUrl . '/' . $this->destinationSiteAccess . '/' . $urlAlias;
     } else {
         $finalUrl = $this->baseDestinationUrl . '/' . $urlAlias;
     }
     if ($this->queryString != '') {
         $finalUrl .= '?' . $this->queryString;
     }
     return $finalUrl;
 }
Exemple #6
0
 if (count($existingElements) > 0) {
     $parentID = (int) $existingElements[0]->attribute('parent');
     $linkID = (int) $existingElements[0]->attribute('id');
 }
 if ($parentIsRoot) {
     $parentID = 0;
     // Start from the top
 }
 $mask = $language->attribute('id');
 $obj = $node->object();
 $alwaysMask = $obj->attribute('language_mask') & 1;
 $mask |= $alwaysMask;
 $origAliasText = $aliasText;
 $result = eZURLAliasML::storePath($aliasText, 'eznode:' . $node->attribute('node_id'), $language, $linkID, $alwaysMask, $parentID, true, false, false, $aliasRedirects);
 if ($result['status'] === eZURLAliasML::LINK_ALREADY_TAKEN) {
     $lastElements = eZURLAliasML::fetchByPath($result['path']);
     if (count($lastElements) > 0) {
         $lastElement = $lastElements[0];
         $infoCode = "feedback-alias-exists";
         $infoData['new_alias'] = $aliasText;
         $infoData['url'] = $lastElement->attribute('path');
         $infoData['action_url'] = $lastElement->actionURL();
         $aliasText = $origAliasText;
     }
 } else {
     if ($result['status'] === true) {
         $aliasText = $result['path'];
         if (strcmp($aliasText, $origAliasText) != 0) {
             $infoCode = "feedback-alias-cleanup";
             $infoData['orig_alias'] = $origAliasText;
             $infoData['new_alias'] = $aliasText;
            }
        }
        fclose($handle);
    } else {
        $cli->output("Warning: Cannot open apache log-file '{$logFilePath}' for reading, please check permissions and try again.");
    }
} else {
    $cli->output("Warning: apache log-file '{$logFilePath}' doesn't exist, please check your ini-settings and try again.");
}
// Process the content of $pathHashCounter to transform it into $nodeIDHashCounter
foreach ($pathHashCounter as $path => $count) {
    $nodeID = eZURLAliasML::fetchNodeIDByPath($path);
    // Support for PathPrefix
    for ($pathPrefixIndex = 0; !$nodeID && $pathPrefixIndex < $pathPrefixesCount; ++$pathPrefixIndex) {
        // Try prepending each of the existing pathPrefixes, to see if one of them matches an existing node
        $nodeID = eZURLAliasML::fetchNodeIDByPath($pathPrefixes[$pathPrefixIndex] . $path);
    }
    if ($nodeID) {
        if (!isset($nodeIDHashCounter[$nodeID])) {
            $nodeIDHashCounter[$nodeID] = $count;
        } else {
            $nodeIDHashCounter[$nodeID] += $count;
        }
    }
}
foreach ($nodeIDHashCounter as $nodeID => $count) {
    if (eZContentObjectTreeNode::fetch($nodeID) != null) {
        $counter = eZViewCounter::fetch($nodeID);
        if ($counter == null) {
            $counter = eZViewCounter::create($nodeID);
            $counter->setAttribute('count', $count);
 /**
  * Returns URL alias for the specified <var>$locale</var>
  *
  * @param string $url
  * @param string $locale
  * @return void
  */
 public function destinationUrl()
 {
     $nodeId = $this->origUrl;
     if (!is_numeric($this->origUrl)) {
         $nodeId = eZURLAliasML::fetchNodeIDByPath($this->origUrl);
     }
     $destinationElement = eZURLAliasML::fetchByAction('eznode', $nodeId, $this->destinationLocale, false);
     if (empty($destinationElement) || !isset($destinationElement[0]) && !$destinationElement[0] instanceof eZURLAliasML) {
         // If the return of fetchByAction is empty, it can mean a couple
         // of different things:
         // Either we are looking at a module, and we should pass the
         // original URL on
         //
         // Or we are looking at URL which does not exist in the
         // destination siteaccess, for instance an untranslated object. In
         // which case we will point to the root of the site, unless it is
         // available as a fallback.
         if ($this->isUrlPointingToModule($this->origUrl) || $this->isLocaleAvailableAsFallback()) {
             // We have a module, we're keeping the orignal url.
             $urlAlias = $this->origUrl;
         } else {
             // We probably have an untranslated object, which is not
             // available with SiteLanguageList setting, we direct to root.
             $urlAlias = '';
         }
     } else {
         // Translated object found, forwarding to new URL.
         $saIni = $this->getSiteAccessIni();
         $siteLanguageList = $saIni->variable('RegionalSettings', 'SiteLanguageList');
         $urlAlias = $destinationElement[0]->getPath($this->destinationLocale, $siteLanguageList);
         $urlAlias .= $this->userParamString;
     }
     $this->baseDestinationUrl = rtrim($this->baseDestinationUrl, '/');
     if ($GLOBALS['eZCurrentAccess']['type'] === eZSiteAccess::TYPE_URI) {
         $finalUrl = $this->baseDestinationUrl . '/' . $this->destinationSiteAccess . '/' . $urlAlias;
     } else {
         $finalUrl = $this->baseDestinationUrl . '/' . $urlAlias;
     }
     return $finalUrl;
 }
 /**
  * Returns the node's url alias
  *
  * @return string
  */
 function urlAlias()
 {
     $useURLAlias =& $GLOBALS['eZContentObjectTreeNodeUseURLAlias'];
     $ini = eZINI::instance();
     $cleanURL = '';
     if (!isset($useURLAlias)) {
         $useURLAlias = $ini->variable('URLTranslator', 'Translation') == 'enabled';
     }
     if ($useURLAlias) {
         $path = $this->pathWithNames();
         if ($ini->hasVariable('SiteAccessSettings', 'PathPrefix') && $ini->variable('SiteAccessSettings', 'PathPrefix') != '') {
             $prepend = $ini->variable('SiteAccessSettings', 'PathPrefix');
             $pathIdenStr = substr($prepend, strlen($prepend) - 1) == '/' ? $path . '/' : $path;
             if (strncasecmp($pathIdenStr, $prepend, strlen($prepend)) == 0) {
                 $cleanURL = eZURLAliasML::cleanURL(substr($path, strlen($prepend)));
             } else {
                 $cleanURL = eZURLAliasML::cleanURL($path);
             }
         } else {
             $cleanURL = eZURLAliasML::cleanURL($path);
         }
     } else {
         $cleanURL = eZURLAliasML::cleanURL('content/view/full/' . $this->NodeID);
     }
     return $cleanURL;
 }
 /**
  * Attempts to fetch a possible node by translating the provided
  * string/path to a node-number.
  *
  * The last section of the path is removed before the actual
  * translation: hence, the PARENT node is returned.
  *
  * @param string $nodePathString Eg. 'Folder1/file1.txt'
  * @return eZContentObject Eg. the node of 'Folder1'
  */
 protected function fetchParentNodeByTranslation($nodePathString)
 {
     // Strip extensions. E.g. .jpg
     $nodePathString = $this->fileBasename($nodePathString);
     // Strip away last slash
     if (strlen($nodePathString) > 0 and $nodePathString[strlen($nodePathString) - 1] === '/') {
         $nodePathString = substr($nodePathString, 0, strlen($nodePathString) - 1);
     }
     $nodePathString = $this->splitLastPathElement($nodePathString, $element);
     if (strlen($nodePathString) === 0) {
         $nodePathString = '/';
     }
     $nodePathString = eZURLAliasML::convertPathToAlias($nodePathString);
     // Attempt to translate the URL to something like "/content/view/full/84".
     $translateResult = eZURLAliasML::translate($nodePathString);
     // handle redirects
     while ($nodePathString === 'error/301') {
         $nodePathString = $translateResult;
         $translateResult = eZURLAliasML::translate($nodePathString);
     }
     // Get the ID of the node (which is the last part of the translated path).
     if (preg_match("#^content/view/full/([0-9]+)\$#", $nodePathString, $matches)) {
         $nodeID = $matches[1];
     } else {
         $ini = eZINI::instance('webdav.ini');
         if ($ini->hasVariable('GeneralSettings', 'StartNode')) {
             $nodeID = $ini->variable('GeneralSettings', 'StartNode');
         }
     }
     // Attempt to fetch the node.
     $node = eZContentObjectTreeNode::fetch($nodeID);
     // Return the node.
     return $node;
 }
Exemple #11
0
 /**
  * \static
  * Load content SSL zones definitions.
  * Substitute URIs with corresponding path strings
  * (e.g. "/news" would be subsituted with "/1/2/50").
  * The result is cached in memory to save time on multiple invocations.
  * It is also saved in a cache file that is usually updated by eZContentCacheManager along with content cache.
  */
 static function getSSLZones()
 {
     if (!isset($GLOBALS['eZSSLZonesCachedPathStrings'])) {
         $cacheFileName = eZSSLZone::cacheFileName();
         $cacheDirName = eZSys::cacheDirectory();
         // if file cache does not exist then create it
         if (!is_readable($cacheFileName)) {
             $ini = eZINI::instance();
             $sslSubtrees = $ini->variable('SSLZoneSettings', 'SSLSubtrees');
             if (!isset($sslSubtrees) || !$sslSubtrees) {
                 return array();
             }
             // if there are some content SSL zones defined in the ini settings
             // then let's calculate path strings for them
             $pathStringsArray = array();
             foreach ($sslSubtrees as $uri) {
                 $elements = eZURLAliasML::fetchByPath($uri);
                 if (count($elements) == 0) {
                     eZDebug::writeError("Cannot fetch URI '{$uri}'", __METHOD__);
                     continue;
                 }
                 $action = $elements[0]->attribute('action');
                 if (!preg_match("#^eznode:(.+)#", $action, $matches)) {
                     eZDebug::writeError("Cannot decode action '{$action}' for URI '{$uri}'", __METHOD__);
                     continue;
                 }
                 $nodeID = (int) $matches[1];
                 $node = eZContentObjectTreeNode::fetch($nodeID);
                 if (!$node instanceof eZContentObjectTreeNode) {
                     eZDebug::writeError("cannot fetch node by URI '{$uri}'", __METHOD__);
                     continue;
                 }
                 $pathStringsArray[$uri] = $node->attribute('path_string');
                 unset($node);
             }
             // write calculated path strings to the file
             if (!file_exists($cacheDirName)) {
                 eZDir::mkdir($cacheDirName, false, true);
             }
             $fh = fopen($cacheFileName, 'w');
             if ($fh) {
                 fwrite($fh, "<?php\n\$pathStringsArray = " . var_export($pathStringsArray, true) . ";\n?>");
                 fclose($fh);
                 $perm = eZINI::instance()->variable('FileSettings', 'StorageFilePermissions');
                 chmod($cacheFileName, octdec($perm));
             }
             return $GLOBALS['eZSSLZonesCachedPathStrings'] = $pathStringsArray;
         } else {
             // let's read its contents and return them
             include_once $cacheFileName;
             // stores array to $pathStringsArray
             return $GLOBALS['eZSSLZonesCachedPathStrings'] = $pathStringsArray;
         }
     }
     // else if in-memory cache already exists then return its contents
     $pathStringsArray = $GLOBALS['eZSSLZonesCachedPathStrings'];
     return $pathStringsArray;
 }
                 if ($isValid) {
                     eZURL::setIsValid($linkID, false);
                 }
                 $cli->output($cli->stylize('warning', "invalid"));
             } else {
                 if (!$isValid) {
                     eZURL::setIsValid($linkID, true);
                 }
                 $cli->output($cli->stylize('success', "valid"));
             }
         } else {
             $cli->output("Couldn't check https protocol");
         }
     }
 } else {
     $translateResult = eZURLAliasML::translate($url);
     if (!$translateResult) {
         $isInternal = false;
         // Check if it is a valid internal link.
         foreach ($siteURLs as $siteURL) {
             $siteURL = preg_replace("/\\/\$/e", "", $siteURL);
             $fp = @fopen($siteURL . "/" . $url, "r");
             if (!$fp) {
                 // do nothing
             } else {
                 $isInternal = true;
                 fclose($fp);
             }
         }
         $translateResult = $isInternal;
     }
    /**
     * @param bool $stats
     * @return array
     */
    public static function fetchSectionsInformations($stats = true)
    {
        $cluster = ClusterTool::clusterIdentifier();
        if ( isset(self::$sectionsInformations[$cluster][(int) $stats]) )
        {
            return array('result' => self::$sectionsInformations[$cluster][(int) $stats]);
        }

        $trigramRemoteToName = FacetFilteringTool::getTaxonomyTranslation('trigram_section');
        $sectionRemoteToName = FacetFilteringTool::getTaxonomyTranslation('section');

        uasort( $sectionRemoteToName, function($a, $b) {
            return strcmp( StringTool::CJK2Pinyin($a), StringTool::CJK2Pinyin($b) );
        });

        $informations = array();
        foreach ( $sectionRemoteToName as $remote => $name )
        {
            $trigram = false;
            if ( isset($trigramRemoteToName['trigram_' . $remote]) )
            {
                $trigram = $trigramRemoteToName['trigram_' . $remote];
            }

            $url = eZURLAliasML::convertToAlias($name);
            if ( $url == '_1' )
            {
                $url = str_replace('section_v', '', $remote);
            }
            $informations[$remote] = array(
                'remote'        => $remote,
                'url'           => $url,
                'name'          => $name,
                'trigram'       => $trigram,
                'topic_count'   => 0,
                'chapter_count' => 0
            );
        }

        if ( $stats )
        {
            $rootNodeId         = MerckManualShowcase::rootNodeId();

            $fields = array('subattr_section___source_id____s', 'subattr_symptom___source_id____s');
            $fq = array(
                'meta_class_identifier_ms:"article"',
                'meta_path_si:' . $rootNodeId,
            );

            $defaultsParams = array(
                'q'              => '',
                'start'          => 0,
                'rows'           => 0,
                'fq'             => implode(' AND ', $fq),
                'fl'             => implode(',', $fields),
                'qt'             => 'ezpublish',
                'explainOther'   => '',
                'hl'             => 'false',
                'facet'          => 'true',
                'facet.field'    => array('subattr_section___source_id____s'),
                'facet.limit'    => array(-1),
                'facet.mincount' => array(1),
                'facet.sort'     => array('alpha')
            );

            // Count chapter
            $params = $defaultsParams;
            $params['fq'] .= ' AND attr_relative_depth_i:0';
            $result = SolrTool::rawSearch($params);

            foreach ( $result['facet_counts']['facet_fields']['subattr_section___source_id____s'] as $section => $count )
                if ( isset($informations[$section]) )
                    $informations[$section]['chapter_count'] = $count;

            // Count topic
            $params = $defaultsParams;
            $params['fq'] .= ' AND attr_relative_depth_i:1';
            $result = self::rawSearch($params);

            foreach ( $result['facet_counts']['facet_fields']['subattr_section___source_id____s'] as $section => $count )
                if ( isset($informations[$section]) )
                    $informations[$section]['topic_count'] = $count;
        }

        if ( !isset(self::$sectionsInformations[$cluster]) )
            self::$sectionsInformations[$cluster] = array();

        self::$sectionsInformations[$cluster][(int) $stats] = $informations;

        return array('result' => $informations);
    }
 /**
  * Test that store path does not reparent children of entries with same action
  * if they are custom aliases
  */
 public function testStorePathReparentAliasEntries()
 {
     // Create a real folder
     $r = mt_rand();
     $theRealFolder = new ezpObject("folder", 2);
     $theRealFolder->name = __FUNCTION__ . $r;
     $theRealFolder->publish();
     // Create a real article in real folder
     $myNode = new ezpObject("article", $theRealFolder->mainNode->node_id);
     $myNode->title = "MyNode";
     $myNode->publish();
     // We fetch the url path element of our real folder entry,
     // in order to create an alias to it
     $realFolderUrl = eZURLAliasML::fetchByAction("eznode", $theRealFolder->mainNode->node_id);
     $realFolderUrlId = $realFolderUrl[0]->attribute('id');
     $myNodeUrl = eZURLAliasML::fetchByAction("eznode", $myNode->mainNode->node_id);
     $myNodeUrlId = $myNodeUrl[0]->attribute('id');
     // We create a custom url alias for the real folder under $realFolderAliasPath
     // Note the first path element will be a virtual nop:
     $realFolderAliasPath = "VirtualPath/AliasToTheRealFolder{$r}";
     $action = "eznode:" . $theRealFolder->mainNode->node_id;
     $realFolderAlias = eZURLAliasML::storePath($realFolderAliasPath, $action, false, $realFolderUrlId);
     $realFolderAliasId = $realFolderAlias['element']->attribute('id');
     /*
                We create a custom url alias for MyNode, which is located underneath
                the alias for real folder, in the url path
        \
                |-- TheRealFolder                (node a)
                |   `-- MyNode                   (node b)
                `-- VirtualPath                  (nop:)
                    `-- AliasToTheRealFolder     (node a)
                        `-- AliasToMyNode        (node b)
     */
     // $myNodeAliasPath = "{$realFolderAliasPath}/AliasToMyNode{$r}";
     $myNodeAliasPath = "AliasToMyNode{$r}";
     $myNodeAction = "eznode:" . $myNode->mainNode->node_id;
     $myNodeAlias = eZURLAliasML::storePath($myNodeAliasPath, $myNodeAction, false, $myNodeUrlId, false, $realFolderAliasId);
     $myNodeAliasOriginalParent = $myNodeAlias['element']->attribute('parent');
     // We republish the real folder, not strictly necessary to change the
     // but it is more illustrative.
     $theRealFolder->name = __FUNCTION__ . $r . "Renamed";
     $theRealFolder->publish();
     // Assert that our alias to MyNode was indeed placed underneath $realFolderAliasPath
     self::assertEquals($realFolderAliasId, $myNodeAliasOriginalParent);
     $db = eZDB::instance();
     $q = self::buildSql(array($myNode->mainNode->node_id), false, array('is_alias' => 1, 'is_original' => 1));
     $myNodeAliasPostChange = $db->arrayQuery($q);
     $myNodeAliasPostChangeParent = $myNodeAliasPostChange[0]['parent'];
     // Make sure the the alias to MyNode have not been moved in the url path
     // after publishing the parent of the real node.
     self::assertEquals($myNodeAliasOriginalParent, $myNodeAliasPostChangeParent, "Parent have custom url alias have been changed inadvertently.");
 }
    /**
     * @param string $path
     * @param MerckManualShowcase $app
     * @return bool|eZContentObjectTreeNode
     */
    public static function findNodeFromPath( $path, &$app )
    {
        /* We remove the publisher folder id at the beginning of the url as we already have it */
        $path                  = preg_replace('#^/\d+/#', '/', $path );

        $manualAppNode         = eZContentObjectTreeNode::fetch( self::rootNodeId() );
        $manualAppNodePathName = $manualAppNode->pathWithNames();
        $tabNodePath           = explode('/', substr($path, 1));
        $remoteId              = end($tabNodePath);

        if(preg_match('/^[a-f0-9]{32}$/', $remoteId))
        {
            $nodeRemote = eZContentObjectTreeNode::fetchByRemoteID($remoteId);

            if($nodeRemote instanceof eZContentObjectTreeNode)
            {
                $app->fullContext = 'topic';
                return $nodeRemote;
            }
        }

        $pathParts = explode('/', substr($path, 1));

        if ( $pathParts[0] == 'table' )
        {
            $app->fullContext = 'table';
            return eZContentObjectTreeNode::fetch($pathParts[1]);
        }

        // Url with topic
        list($sectionName, $chapterName, $topicName, $mediaType, $mediaName, $other) = $pathParts;

        // Url without topic
        $matches = array();

        if ( preg_match('/media-([a-z]+)/', $topicName, $matches) )
        {
            list($sectionName, $chapterName, $mediaType, $mediaName, $other) = $pathParts;
            $topicName = null;
        }

        // Full section
        if ( $sectionName != null && is_null( $chapterName ) && is_null( $topicName ) )
        {
            $app->fullContext = 'section';
            $app->section = MerckManualFunctionCollection::fetchSection('url', $sectionName);
            return eZContentObjectTreeNode::fetch(MerckManualShowcase::rootNodeId());
        }
        if ( $sectionName == 'about-us' )
        {
            list($chapterName, $topicName, $mediaType, $mediaName, $other) = $pathParts;
        }

        $path = $manualAppNodePathName;
        // Full of chapter
        if ( $chapterName )
        {
            $app->fullContext = 'chapter';
            $path .= '/' . $chapterName;
        }

        // Full of topic
        if ( $topicName )
        {
            $app->fullContext = 'topic';
            $path .= '/' . $topicName;
        }

        $nodeId = eZURLAliasML::fetchNodeIDByPath($path);

        if ( $nodeId )
        {
            if ( $mediaName )
            {
                $mediaType = str_replace('media-', '', $mediaType);

                // Get media node
                // Full of html table image
                // /topic_name/(media-image-file)/oscar2/filename
                if ( $mediaType == 'image-file' )
                {
                    $app->fullContext = $mediaType;
                    $app->oscarFolder = $mediaName;
                    $app->mediaName = $other;
                }

                // Full of inline audio, video, image
                elseif ( $mediaType )
                {
                    // Construct the remote_id of the media folder
                    /* @type $dataMap eZContentObjectAttribute[] */
                    $contentObject        = eZContentObject::fetchByNodeID($nodeId);
                    $dataMap              = $contentObject->dataMap();
                    $publisherAttrContent = $dataMap['publisher']->content();

                    if ( isset($publisherAttrContent['relation_list'][0]['contentobject_remote_id']) )
                    {
                        // Get media folder
                        $mediaFolderRemoteId = sprintf('%s_media_%s', $publisherAttrContent['relation_list'][0]['contentobject_remote_id'], $mediaType);
                        $mediaFolder = eZContentObject::fetchByRemoteID($mediaFolderRemoteId);

                        if ( $mediaFolder )
                        {
                            // Get media
                            $mediaFolderPathName = $mediaFolder->mainNode()->pathWithNames();
                            $nodeId = eZURLAliasML::fetchNodeIDByPath($mediaFolderPathName . '/' . $mediaName);
                            $app->fullContext = $mediaType;
                        }
                    }
                }
            }
        }

        if ( $nodeId )
        {
            // Full of chapter must not be accessible, show first topic
            if ( $app->fullContext == 'chapter' )
            {
                $params = array(
                    'Depth'         => 1,
                    'DepthOperator' => 'eq',
                    'SortBy'        => array(array('priority', 'asc')),
                    'Limit'         => 1
                );
                $children = eZContentObjectTreeNode::subTreeByNodeID($params, $nodeId);

                if ( isset($children[0]) && $children[0] instanceof eZContentObjectTreeNode )
                {
                    $node = $children[0];
                    $app->fullContext = 'topic';
                }
                else
                    $node = null;
            }
            else
            {
                $node = eZContentObjectTreeNode::fetch($nodeId);
            }

            return $node;
        }

        return false;
    }
    /**
     * @param int $languageID
     * @param int|bool $version
     */
    function setAlwaysAvailableLanguageID( $languageID, $version = false )
    {
        $db = eZDB::instance();
        $db->begin();

        if ( $version == false )
        {
            $version = $this->currentVersion();
            if ( $languageID )
            {
                $this->setAttribute( 'language_mask', (int)$this->attribute( 'language_mask' ) | 1 );
            }
            else
            {
                $this->setAttribute( 'language_mask', (int)$this->attribute( 'language_mask' ) & ~1 );
            }
            $this->store();
        }

        $objectID = $this->attribute( 'id' );
        $versionID = $version->attribute( 'version' );

        // reset 'always available' flag
        $sql = "UPDATE ezcontentobject_name SET language_id=";
        if ( $db->databaseName() == 'oracle' )
        {
            $sql .= "bitand( language_id, -2 )";
        }
        else
        {
            $sql .= "language_id & ~1";
        }
        $sql .= " WHERE contentobject_id = '$objectID' AND content_version = '$versionID'";
        $db->query( $sql );

        if ( $languageID != false )
        {
            $newLanguageID = $languageID | 1;
            $sql = "UPDATE ezcontentobject_name
                    SET language_id='$newLanguageID'
                    WHERE language_id='$languageID' AND contentobject_id = '$objectID' AND content_version = '$versionID'";
            $db->query( $sql );
        }

        $version->setAlwaysAvailableLanguageID( $languageID );

        // Update url alias for all locations
        $nodeRows = eZContentObjectTreeNode::fetchByContentObjectID( $objectID, false );
        $actions = array();
        foreach ( $nodeRows as $nodeRow )
        {
            $nodeID = (int)$nodeRow['node_id'];
            $actions[] = array( 'eznode', $nodeID );
        }
        eZURLAliasML::setLangMaskAlwaysAvailable( $languageID, $actions, null );

        $db->commit();
    }
    function fetchParentNodeByTranslation( $nodePathString )
    {
        // Strip extensions. E.g. .jpg
        $nodePathString = $this->fileBasename( $nodePathString );

        // Strip away last slash
        if ( strlen( $nodePathString ) > 0 and
             $nodePathString[strlen( $nodePathString ) - 1] == '/' )
        {
            $nodePathString = substr( $nodePathString, 0, strlen( $nodePathString ) - 1 );
        }

        $nodePathString = $this->splitLastPathElement( $nodePathString, $element );

        if ( strlen( $nodePathString ) == 0 )
            $nodePathString = '/';

        $nodePathString = eZURLAliasML::convertPathToAlias( $nodePathString );

        // Attempt to translate the URL to something like "/content/view/full/84".
        $translateResult = eZURLAliasML::translate( $nodePathString );

        // handle redirects
        while ( $nodePathString == 'error/301' )
        {
            $nodePathString = $translateResult;

            $translateResult = eZURLAliasML::translate( $nodePathString );
        }

        // Get the ID of the node (which is the last part of the translated path).
        if ( preg_match( "#^content/view/full/([0-9]+)$#", $nodePathString, $matches ) )
        {
            $nodeID = $matches[1];
            $this->appendLogEntry( "NodeID: $nodeID", 'CS:fetchParentNodeByTranslation' );
        }
        else
        {
            $this->appendLogEntry( "Root node", 'CS:fetchParentNodeByTranslation' );
            $nodeID = 2;
        }

        // Attempt to fetch the node.
        $node = eZContentObjectTreeNode::fetch( $nodeID );

        // Return the node.
        return $node;
    }
    }
} else {
    $cli->output("Warning: apache log-file '{$logFilePath}' doesn't exist, please check your ini-settings and try again.");
}
foreach ($nodeIDArray as $nodeID) {
    $nodeObject = eZContentObjectTreeNode::fetch($nodeID);
    if ($nodeObject != null) {
        $counter = eZViewCounter::fetch($nodeID);
        if ($counter == null) {
            $counter = eZViewCounter::create($nodeID);
        }
        $counter->increase();
    }
}
foreach ($pathArray as $path) {
    $nodeID = eZURLAliasML::fetchNodeIDByPath($path);
    if ($nodeID) {
        $counter = eZViewCounter::fetch($nodeID);
        if ($counter == null) {
            $counter = eZViewCounter::create($nodeID);
        }
        $counter->increase();
    }
}
$dt = new eZDateTime();
$fh = fopen($updateViewLogPath, "w");
if ($fh) {
    fwrite($fh, "# Finished at " . $dt->toString() . "\n");
    fwrite($fh, "# Last updated entry:" . "\n");
    fwrite($fh, $lastLine . "\n");
    fclose($fh);
Exemple #19
0
         // Referenced url does not exist
         logError("The referenced path '{$toPath}' can not be found among the new URL alias entries, url entry ID is " . $row['id']);
         list($column, $counter) = displayProgress('E', $urlImportStartTime, $counter, $urlCount, $column);
         continue;
     }
     // Fetch the ID of the element to redirect to.
     $linkID = $elements[0]->attribute('id');
     $action = $elements[0]->attribute('action');
     if ($action == 'nop:') {
         // Cannot redirect to nops
         logError("The referenced path '{$toPath}' with ID " . $elements[0]->attribute('id') . " is a 'nop:' entry and cannot be used");
         list($column, $counter) = displayProgress('E', $urlImportStartTime, $counter, $urlCount, $column);
         continue;
     }
     $alwaysAvailable = $elements[0]->attribute('lang_mask') & 1;
     $res = eZURLAliasML::storePath($fromPath, $action, false, $linkID, $alwaysAvailable);
     if (!$res || $res['status'] == 3) {
         logError("The wildcard url " . var_export($fromPath, true) . " cannot be created since the path already exists");
         list($column, $counter) = displayProgress('s', $urlImportStartTime, $counter, $urlCount, $column);
         continue;
     }
     if (!$res || $res['status'] !== true) {
         logStoreError($res, "eZURLAliasML::storePath", array($fromPath, $action, false, $linkID, $alwaysAvailable));
         list($column, $counter) = displayProgress('E', $urlImportStartTime, $counter, $urlCount, $column);
         continue;
     }
     logStore($res, "eZURLAliasML::storePath", array($fromPath, $action, false, $linkID, $alwaysAvailable));
     $result = '.';
     verifyData($result, $source, $row['id']);
     list($column, $counter) = displayProgress($result, $urlImportStartTime, $counter, $urlCount, $column);
 }
Exemple #20
0
         $uri->toBeginning();
         foreach ($redirUris as $redirUri) {
             $redirUri = new eZURI($redirUri);
             if ($redirUri->matchBase($uri)) {
                 $automatic_redir = false;
                 break;
             }
         }
     }
 }
 $redirectURI = eZSys::indexDir();
 $moduleRedirectUri = $module->redirectURI();
 $redirectStatus = $module->redirectStatus();
 $translatedModuleRedirectUri = $moduleRedirectUri;
 if ($ini->variable('URLTranslator', 'Translation') == 'enabled' && eZURLAliasML::urlTranslationEnabledByUri(new eZURI($moduleRedirectUri))) {
     if (eZURLAliasML::translate($translatedModuleRedirectUri, true)) {
         $moduleRedirectUri = $translatedModuleRedirectUri;
         if (strlen($moduleRedirectUri) > 0 and $moduleRedirectUri[0] != '/') {
             $moduleRedirectUri = '/' . $moduleRedirectUri;
         }
     }
 }
 if (preg_match('#^(\\w+:)|^//#', $moduleRedirectUri)) {
     $redirectURI = $moduleRedirectUri;
 } else {
     $leftSlash = false;
     $rightSlash = false;
     if (strlen($redirectURI) > 0 and $redirectURI[strlen($redirectURI) - 1] == '/') {
         $leftSlash = true;
     }
     if (strlen($moduleRedirectUri) > 0 and $moduleRedirectUri[0] == '/') {
 public function testNodeIDFromAction()
 {
     $action1 = "eznod:2";
     // not valid action
     $action2 = " ";
     // not valid action
     $action3 = "eznode;2";
     // not valid action
     $action4 = "ezblaa:2";
     // not valid action
     $action5 = "eznode:2";
     // valid action
     self::assertEquals(false, eZURLAliasML::nodeIDFromAction($action1));
     self::assertEquals(false, eZURLAliasML::nodeIDFromAction($action2));
     self::assertEquals(false, eZURLAliasML::nodeIDFromAction($action3));
     self::assertEquals(false, eZURLAliasML::nodeIDFromAction($action4));
     self::assertEquals((int) 2, eZURLAliasML::nodeIDFromAction($action5));
 }
Exemple #22
0
 function normalizeImageName($imageName)
 {
     // Initialize transformation system
     $trans = eZCharTransform::instance();
     $imageName = eZURLAliasML::convertToAlias($imageName);
     return $imageName;
 }
    static function headerOverrideArray( $uri )
    {
        $headerArray = array();

        if ( !eZHTTPHeader::enabled() )
        {
            return $headerArray;
        }

        $contentView = false;

        $uriString = eZURLAliasML::cleanURL( $uri->uriString() );

        // If content/view used, get url alias for node
        if ( strpos( $uriString, 'content/view/' ) === 0 )
        {
            $urlParts = explode( '/', $uriString );
            $nodeID = $urlParts[3];
            if ( !$nodeID )
            {
                return $headerArray;
            }

            $node = eZContentObjectTreeNode::fetch( $nodeID );
            if ( !$node )
            {
                return $headerArray;
            }

            $uriString = $node->pathWithNames();
            $contentView = true;
        }
        else
        {
            $uriCopy = clone $uri;
            eZURLAliasML::translate( $uriCopy );
            if ( strpos( $uriCopy->uriString(), 'content/view' ) === 0 )
            {
                $contentView = true;
            }
        }

        $uriString = '/' . eZURLAliasML::cleanURL( $uriString );
        $ini = eZINI::instance();

        foreach( $ini->variable( 'HTTPHeaderSettings', 'HeaderList' ) as $header )
        {
            foreach( $ini->variable( 'HTTPHeaderSettings', $header ) as $path => $value )
            {
                $path = '/' . eZURLAliasML::cleanURL( $path );
                if ( strlen( $path ) == 1 &&
                     ( !$contentView && ( $ini->variable( 'HTTPHeaderSettings', 'OnlyForContent' ) === 'enabled' ) ) &&
                     $uriString != '/' )
                {
                    continue;
                }

                if ( strpos( $uriString, $path ) === 0 )
                {
                    @list( $headerValue, $depth, $level ) = explode( ';', $value );

                    if ( $header == 'Expires' )
                    {
                        $headerValue = gmdate( 'D, d M Y H:i:s', time() + $headerValue ) . ' GMT';
                    }

                    if ( $depth === null )
                    {
                        $headerArray[$header] = $headerValue;
                    }
                    else
                    {
                        $pathLevel = count( explode( '/', $path ) );
                        $uriLevel = count( explode( '/', $uriString ) );
                        if ( $level === null )
                        {
                            if ( $uriLevel <= $pathLevel + $depth )
                            {
                                $headerArray[$header] = $headerValue;
                            }
                        }
                        else
                        {
                            if ( $uriLevel <= $pathLevel + $depth &&
                                 $uriLevel >= $pathLevel + $level )
                            {
                                $headerArray[$header] = $headerValue;
                            }
                        }
                    }
                }
            }
        }

        return $headerArray;
    }
Exemple #24
0
 /**
  * @see http://issues.ez.no/19062
  * @group issue19062
  * @covers eZURLAliasML::translate
  */
 public function testTranslateWildcardNopUri()
 {
     $folder = new ezpObject('folder', 2);
     $folder->name = 'foo';
     $folder->publish();
     // By creating following URL alias, "test/single-page" will be registered as a NOP URI segment
     $uriFirstSegment = 'test19062';
     $uriWildcard = "{$uriFirstSegment}/single-page";
     $res = eZURLAliasML::storePath("{$uriWildcard}/article.html", "eznode:{$folder->mainNode->node_id}", $this->englishLanguage, 0, true);
     $wildcard = eZURLWildcardTest::createWildcard($uriWildcard, 'foo', eZURLWildcard::TYPE_FORWARD);
     // Translating the wildcard URL should return false in order to be then translated by eZURLWildcard in index.php
     self::assertFalse(eZURLAliasML::translate($uriWildcard));
     // Here no wildcard and test19062 should be a nop segment (points to nothing.
     // Default behaviour is to return true and redirect to root ("/")
     self::assertTrue(eZURLAliasML::translate($uriFirstSegment));
     $folder->remove();
     $wildcard->remove();
 }
Exemple #25
0
    /**
     * Transforms the URI if there exists an alias for it.
     *
     * @param eZURI|string $uri
     * @return mixed The translated URI if the resource has moved, or true|false
     *               if translation was (un)successful
     */
    public static function translate( &$uri )
    {
        $result = false;

        // get uri string
        $uriString = ( $uri instanceof eZURI ) ? $uri->elements() : $uri;
        $uriString = eZURLAliasML::cleanURL( $uriString );

        eZDebugSetting::writeDebug( 'kernel-urltranslator', "input uriString: '$uriString'", __METHOD__ );

        if ( !$wildcards = self::wildcardsIndex() )
        {
            eZDebugSetting::writeDebug( 'kernel-urltranslator', "no match callbacks", __METHOD__ );
            return false;
        }

        $ini = eZINI::instance();
        $iteration = $ini->variable( 'URLTranslator', 'MaximumWildcardIterations' );

        eZDebugSetting::writeDebug( 'kernel-urltranslator', "MaximumWildcardIterations: '$iteration'", __METHOD__ );

        // translate
        $urlTranslated = false;
        while ( !$urlTranslated && $iteration >= 0 )
        {
            foreach ( $wildcards as $wildcardNum => $wildcard )
            {
                if ( preg_match( $wildcard, $uriString ) )
                {
                    eZDebugSetting::writeDebug( 'kernel-urltranslator', "matched with: '$wildcard'", __METHOD__ );

                    // get new $uriString from wildcard
                    self::translateWithCache( $wildcardNum, $uriString, $wildcardInfo, $wildcard );

                    eZDebugSetting::writeDebug( 'kernel-urltranslator', "new uri string: '$uriString'", __METHOD__ );

                    // optimization: don't try further translation if wildcard type is 'forward'
                    if ( $wildcardInfo['type'] == self::TYPE_FORWARD )
                    {
                        $urlTranslated = true;
                        break;
                    }

                    // try to tranlsate
                    if ( $urlTranslated = eZURLAliasML::translate( $uriString ) )
                    {
                        // success
                        eZDebugSetting::writeDebug( 'kernel-urltranslator', "uri is translated to '$uriString' with result '$urlTranslated'", __METHOD__ );
                        break;
                    }

                    eZDebugSetting::writeDebug( 'kernel-urltranslator', "uri is not translated, trying another wildcard", __METHOD__ );

                    // translation failed. Try to match new $uriString with another wildcard.
                    --$iteration;
                    continue 2;
                }
            }

            // we here if non of the wildcards is matched
            break;
        }

        // check translation result
        // NOTE: 'eZURLAliasML::translate'(see above) can return 'true', 'false' or new url(in case of 'error/301').
        //       $urlTranslated can also be 'false' if no wildcard is matched.
        if ( $urlTranslated )
        {
            // check wildcard type and set appropriate $result and $uriString
            $wildcardType = $wildcardInfo['type'];

            eZDebugSetting::writeDebug( 'kernel-urltranslator', "wildcard type: $wildcardType", __METHOD__ );

            switch ( $wildcardType )
            {
                case self::TYPE_FORWARD:
                {
                    // do redirect:
                    //   => set $result to translated uri
                    //   => set uri string to a MOVED PERMANENTLY HTTP code
                    $result = $uriString;
                    $uriString = 'error/301';
                }
                break;

                default:
                {
                    eZDebug::writeError( 'Invalid wildcard type.', __METHOD__ );
                    // no break, using eZURLWildcard::TYPE_DIRECT as fallback
                }
                case self::TYPE_DIRECT:
                {
                    $result = $urlTranslated;
                    // $uriString already has correct value
                    break;
                }
            }
        }
        else
        {
            // we are here if:
            // - input url is not matched with any wildcard;
            // - url is matched with wildcard and:
            //   - points to module
            //   - invalide url
            eZDebugSetting::writeDebug( 'kernel-urltranslator', "wildcard is not translated", __METHOD__ );
            $result = false;
        }

        // set value back to $uri
        if ( $uri instanceof eZURI )
        {
            $uri->setURIString( $uriString, false );
        }
        else
        {
            $uri = $uriString;
        }

        eZDebugSetting::writeDebug( 'kernel-urltranslator', "finished with url '$uriString' and result '$result'", __METHOD__ );

        return $result;
    }
 /**
  * Performs a redirection
  */
 protected function redirect()
 {
     $GLOBALS['eZRedirection'] = true;
     $ini = eZINI::instance();
     $automaticRedirect = true;
     if ($GLOBALS['eZDebugAllowed'] && ($redirUri = $ini->variable('DebugSettings', 'DebugRedirection')) !== 'disabled') {
         if ($redirUri == "enabled") {
             $automaticRedirect = false;
         } else {
             $uri = eZURI::instance(eZSys::requestURI());
             $uri->toBeginning();
             foreach ($ini->variableArray("DebugSettings", "DebugRedirection") as $redirUri) {
                 $redirUri = new eZURI($redirUri);
                 if ($redirUri->matchBase($uri)) {
                     $automaticRedirect = false;
                     break;
                 }
             }
         }
     }
     $redirectURI = eZSys::indexDir();
     $moduleRedirectUri = $this->module->redirectURI();
     if ($ini->variable('URLTranslator', 'Translation') === 'enabled' && eZURLAliasML::urlTranslationEnabledByUri(new eZURI($moduleRedirectUri))) {
         $translatedModuleRedirectUri = $moduleRedirectUri;
         if (eZURLAliasML::translate($translatedModuleRedirectUri, true)) {
             $moduleRedirectUri = $translatedModuleRedirectUri;
             if (strlen($moduleRedirectUri) > 0 && $moduleRedirectUri[0] !== '/') {
                 $moduleRedirectUri = '/' . $moduleRedirectUri;
             }
         }
     }
     if (preg_match('#^(\\w+:)|^//#', $moduleRedirectUri)) {
         $redirectURI = $moduleRedirectUri;
     } else {
         $leftSlash = strlen($redirectURI) > 0 && $redirectURI[strlen($redirectURI) - 1] === '/';
         $rightSlash = strlen($moduleRedirectUri) > 0 && $moduleRedirectUri[0] === '/';
         if (!$leftSlash && !$rightSlash) {
             // Both are without a slash, so add one
             $moduleRedirectUri = '/' . $moduleRedirectUri;
         } else {
             if ($leftSlash && $rightSlash) {
                 // Both are with a slash, so we remove one
                 $moduleRedirectUri = substr($moduleRedirectUri, 1);
             }
         }
         $redirectURI .= $moduleRedirectUri;
     }
     eZStaticCache::executeActions();
     eZDB::checkTransactionCounter();
     if ($automaticRedirect) {
         eZHTTPTool::redirect($redirectURI, array(), $this->module->redirectStatus());
     } else {
         // Make sure any errors or warnings are reported
         if ($ini->variable('DebugSettings', 'DisplayDebugWarnings') === 'enabled') {
             if (isset($GLOBALS['eZDebugError']) && $GLOBALS['eZDebugError']) {
                 eZAppendWarningItem(array('error' => array('type' => 'error', 'number' => 1, 'count' => $GLOBALS['eZDebugErrorCount']), 'identifier' => 'ezdebug-first-error', 'text' => ezpI18n::tr('index.php', 'Some errors occurred, see debug for more information.')));
             }
             if (isset($GLOBALS['eZDebugWarning']) && $GLOBALS['eZDebugWarning']) {
                 eZAppendWarningItem(array('error' => array('type' => 'warning', 'number' => 1, 'count' => $GLOBALS['eZDebugWarningCount']), 'identifier' => 'ezdebug-first-warning', 'text' => ezpI18n::tr('index.php', 'Some general warnings occured, see debug for more information.')));
             }
         }
         $tpl = eZTemplate::factory();
         $tpl->setVariable('site', $this->site);
         $tpl->setVariable('warning_list', !empty($this->warningList) ? $this->warningList : false);
         $tpl->setVariable('redirect_uri', eZURI::encodeURL($redirectURI));
         $templateResult = $tpl->fetch('design:redirect.tpl');
         eZDebug::addTimingPoint("Script end");
         eZDisplayResult($templateResult);
     }
     eZExecution::cleanExit();
 }
 function getPathArray()
 {
     if ($this->PathArray !== null) {
         return $this->PathArray;
     }
     // Fetch path 'text' elements of correct parent path
     $path = array($this);
     $id = (int) $this->Parent;
     $db = eZDB::instance();
     while ($id != 0) {
         $query = "SELECT * FROM ezurlalias_ml WHERE id={$id}";
         $rows = $db->arrayQuery($query);
         if (count($rows) == 0) {
             break;
         }
         $result = eZURLAliasML::choosePrioritizedRow($rows);
         if (!$result) {
             $result = $rows[0];
         }
         $id = (int) $result['parent'];
         array_unshift($path, new eZPathElement($result));
     }
     $this->PathArray = $path;
     return $this->PathArray;
 }
    /**
     * Generates the static cache from the configured INI settings.
     *
     * @param bool $force If true then it will create all static caches even if it is not outdated.
     * @param bool $quiet If true then the function will not output anything.
     * @param eZCLI|false $cli The eZCLI object or false if no output can be done.
     * @param bool $delay
     */
    public function generateCache( $force = false, $quiet = false, $cli = false, $delay = true )
    {
        $staticURLArray = $this->cachedURLArray();
        $db = eZDB::instance();
        $configSettingCount = count( $staticURLArray );
        $currentSetting = 0;

        // This contains parent elements which must checked to find new urls and put them in $generateList
        // Each entry contains:
        // - url - Url of parent
        // - glob - A glob string to filter direct children based on name
        // - org_url - The original url which was requested
        // - parent_id - The element ID of the parent (optional)
        // The parent_id will be used to quickly fetch the children, if not it will use the url
        $parentList = array();
        // A list of urls which must generated, each entry is a string with the url
        $generateList = array();
        foreach ( $staticURLArray as $url )
        {
            $currentSetting++;
            if ( strpos( $url, '*') === false )
            {
                $generateList[] = $url;
            }
            else
            {
                $queryURL = ltrim( str_replace( '*', '', $url ), '/' );
                $dir = dirname( $queryURL );
                if ( $dir == '.' )
                    $dir = '';
                $glob = basename( $queryURL );
                $parentList[] = array( 'url' => $dir,
                                       'glob' => $glob,
                                       'org_url' => $url );
            }
        }

        // As long as we have urls to generate or parents to check we loop
        while ( count( $generateList ) > 0 || count( $parentList ) > 0 )
        {
            // First generate single urls
            foreach ( $generateList as $generateURL )
            {
                if ( !$quiet and $cli )
                    $cli->output( "caching: $generateURL ", false );
                $this->cacheURL( $generateURL, false, !$force, $delay );
                if ( !$quiet and $cli )
                    $cli->output( "done" );
            }
            $generateList = array();

            // Then check for more data
            $newParentList = array();
            foreach ( $parentList as $parentURL )
            {
                if ( isset( $parentURL['parent_id'] ) )
                {
                    $elements = eZURLAliasML::fetchByParentID( $parentURL['parent_id'], true, true, false );
                    foreach ( $elements as $element )
                    {
                        $path = '/' . $element->getPath();
                        $generateList[] = $path;
                        $newParentList[] = array( 'parent_id' => $element->attribute( 'id' ) );
                    }
                }
                else
                {
                    if ( !$quiet and $cli and $parentURL['glob'] )
                        $cli->output( "wildcard cache: " . $parentURL['url'] . '/' . $parentURL['glob'] . "*" );
                    $elements = eZURLAliasML::fetchByPath( $parentURL['url'], $parentURL['glob'] );
                    foreach ( $elements as $element )
                    {
                        $path = '/' . $element->getPath();
                        $generateList[] = $path;
                        $newParentList[] = array( 'parent_id' => $element->attribute( 'id' ) );
                    }
                }
            }
            $parentList = $newParentList;
        }
    }
 private static function md5($db, $text, $escape = true)
 {
     // Special case for Oracle since it cannot calculate MD5 for empty strings
     if (strlen($text) == 0 && $db->databaseName() == 'oracle') {
         return "'" . $db->escapeString(md5($text)) . "'";
     }
     if ($escape) {
         $text = $db->escapeString(eZURLAliasML::strtolower($text));
     }
     return $db->md5("'" . $text . "'");
 }
 static function decodeNodeID($subtreeExpiryParameter)
 {
     $nodeID = false;
     if (!is_numeric($subtreeExpiryParameter)) {
         $nodePathString = '';
         // clean up $subtreeExpiryParameter
         $subtreeExpiryParameter = trim($subtreeExpiryParameter, '/');
         $nodeID = false;
         $subtree = $subtreeExpiryParameter;
         if ($subtree == '') {
             // 'subtree_expiry' is empty => use root node.
             $nodeID = 2;
         } else {
             $nonAliasPath = 'content/view/full/';
             if (strpos($subtree, $nonAliasPath) === 0) {
                 // 'subtree_expiry' is like 'content/view/full/2'
                 $nodeID = (int) substr($subtree, strlen($nonAliasPath));
             } else {
                 // 'subtree_expiry' is url_alias
                 $nodeID = eZURLAliasML::fetchNodeIDByPath($subtree);
                 if (!$nodeID) {
                     eZDebug::writeError("Could not find path_string '{$subtree}' for 'subtree_expiry' node.", 'eZTemplateCacheBlock::subtreeExpiryCacheDir()');
                 } else {
                     $nodeID = (int) $nodeID;
                 }
             }
         }
     } else {
         $nodeID = (int) $subtreeExpiryParameter;
     }
     return $nodeID;
 }