Ejemplo n.º 1
0
 public function getTimeline($pageID = false, $limit = 20, $type = 'feed')
 {
     $result = array('result' => array());
     $accumulator = $this->debugAccumulatorGroup . '_facebook_timeline';
     eZDebug::accumulatorStart($accumulator, $this->debugAccumulatorGroup, 'timeline');
     $cacheFileHandler = $this->getCacheFileHandler('_timeline', array($pageID, $limit, $type));
     try {
         if ($this->isCacheExpired($cacheFileHandler)) {
             eZDebug::writeDebug(array('page_id' => $pageID, 'limit' => $limit), self::$debugMessagesGroup);
             $response = $this->API->api(($pageID === false ? 'me/home' : '/' . $pageID) . '/' . $type, array('access_token' => $this->acessToken, 'limit' => $limit));
             $messages = array();
             $currentTime = time();
             foreach ($response['data'] as $message) {
                 $createdAt = strtotime($message['created_time']);
                 $message['created_ago'] = self::getCreatedAgoString($createdAt, $currentTime);
                 $message['created_timestamp'] = $createdAt;
                 if (isset($message['message'])) {
                     $message['message'] = self::fixMessageLinks($message['message']);
                 }
                 $messages[] = $message;
             }
             $cacheFileHandler->fileStoreContents($cacheFileHandler->filePath, serialize($messages));
         } else {
             $messages = unserialize($cacheFileHandler->fetchContents());
         }
         eZDebug::accumulatorStop($accumulator);
         $result['result'] = $messages;
         return $result;
     } catch (Exception $e) {
         eZDebug::accumulatorStop($accumulator);
         eZDebug::writeError($e->getMessage(), self::$debugMessagesGroup);
         return $result;
     }
 }
    function parse( $tpl, $sourceText, &$rootElement, $rootNamespace, &$resourceData )
    {
        $relatedResource = $resourceData['resource'];
        $relatedTemplateName = $resourceData['template-filename'];

        $currentRoot =& $rootElement;
        $leftDelimiter = $tpl->LDelim;
        $rightDelimiter = $tpl->RDelim;
        $sourceLength = strlen( $sourceText );
        $sourcePosition = 0;

        eZDebug::accumulatorStart( 'template_multi_parser_1', 'template_total', 'Template parser: create text elements' );
        $textElements = $this->parseIntoTextElements( $tpl, $sourceText, $sourcePosition,
                                                      $leftDelimiter, $rightDelimiter, $sourceLength,
                                                      $relatedTemplateName );
        eZDebug::accumulatorStop( 'template_multi_parser_1' );

        eZDebug::accumulatorStart( 'template_multi_parser_2', 'template_total', 'Template parser: remove whitespace' );
        $textElements = $this->parseWhitespaceRemoval( $tpl, $textElements );
        eZDebug::accumulatorStop( 'template_multi_parser_2' );

        eZDebug::accumulatorStart( 'template_multi_parser_3', 'template_total', 'Template parser: construct tree' );
        $this->parseIntoTree( $tpl, $textElements, $currentRoot,
                              $rootNamespace, $relatedResource, $relatedTemplateName );
        eZDebug::accumulatorStop( 'template_multi_parser_3' );
    }
Ejemplo n.º 3
0
    /**
     * Helper for solr raw searches.
     * Deals with the language, meta_installation, section and visibility filters + solr sharding if any
     * @param array $params
     * @param string $requestType
     * @param bool $useDefaultFilters
     * @return array
     */
    public static function rawSearch( $params, $requestType = 'php', $useDefaultFilters = true, $includeIsInvisible = true )
    {
        eZDebug::accumulatorStart( __CLASS__ . '::' . __FUNCTION__, 'Merck' );

        $findINI = eZINI::instance( 'ezfind.ini' );
        $solrINI = eZINI::instance( 'solr.ini' );
        $siteINI = eZINI::instance();
        $currentLanguage = $siteINI->variable( 'RegionalSettings', 'ContentObjectLocale' );

        // always use extended Dismax query handler when available
        if( isset($params['qt']) && $params['qt'] == 'ezpublish' )
            $params['defType'] = 'edismax';

        if ( $useDefaultFilters )
        {
            if ( !isset( $params['fq'] ) )
                $params['fq'] = '';
            else
                $params['fq'] .= ' AND ';
            $params['fq'] .= implode( ' AND ', array(
                'meta_installation_id_ms:' . eZSolr::installationID(),
                '(attr_offline_date_dt:"1970-01-01T01:00:00Z" OR attr_offline_date_dt:[NOW TO *])',
                '( meta_section_id_si:1 OR meta_section_id_si:3 )',
            ) );
            if ($includeIsInvisible) {
                $params['fq'] .= ' AND ' . 'attr_is_invisible_' . ClusterTool::clusterIdentifier() . '_b:false';
            }
        }

        if ( $findINI->variable( 'LanguageSearch', 'MultiCore' ) == 'enabled' )
        {
            $languageMapping = $findINI->variable( 'LanguageSearch', 'LanguagesCoresMap' );
            $shardMapping = $solrINI->variable( 'SolrBase', 'Shards' );
            $fullSolrURI = $shardMapping[$languageMapping[$currentLanguage]];
        }
        else
        {
            $fullSolrURI = $solrINI->variable( 'SolrBase', 'SearchServerURI' );
            // Autocomplete search should be done in current language and fallback languages
            $validLanguages = array_unique(
                array_merge(
                    LocaleTool::languageList(),
                    array( $currentLanguage )
                )
            );
            if( $useDefaultFilters )
                $params['fq'] .= ' AND meta_language_code_ms:(' . implode( ' OR ', $validLanguages ) . ')';
        }

        solrTool::solrStopWordsFilter( $params );    //excluding stopwords
        self::parseBooleanOperators( $params );      // translations for bookean operators
        $solrBase = new eZSolrBase( $fullSolrURI );
        $result = $solrBase->rawSolrRequest( '/select', $params, $requestType );
        if ( !$result )
            self::addNoCacheHeaders();
        
        eZDebug::accumulatorStop( __CLASS__ . '::' . __FUNCTION__ );

        return $result;
    }
Ejemplo n.º 4
0
 public function searchActivities($query, $limit = 20, $sorting = 'best')
 {
     $result = array('result' => array());
     $accumulator = $this->debugAccumulatorGroup . '_google_activities_search';
     eZDebug::accumulatorStart($accumulator, $this->debugAccumulatorGroup, 'activities/search');
     $cacheFileHandler = $this->getCacheFileHandler('_activities_search', array($query, $limit, $sorting));
     try {
         if ($this->isCacheExpired($cacheFileHandler)) {
             eZDebug::writeDebug(array('query' => $query, 'limit' => $limit, 'sorting' => $sorting), self::$debugMessagesGroup);
             $response = $this->API->activities->search($query, array('maxResults' => $limit, 'orderBy' => $sorting));
             $activities = array();
             $currentTime = time();
             foreach ($response['items'] as $activity) {
                 $createdAt = strtotime($activity['published']);
                 $activity['created_ago'] = self::getCreatedAgoString($createdAt, $currentTime);
                 $activity['created_timestamp'] = $createdAt;
                 $activities[] = $activity;
             }
             $cacheFileHandler->fileStoreContents($cacheFileHandler->filePath, serialize($activities));
         } else {
             $activities = unserialize($cacheFileHandler->fetchContents());
         }
         eZDebug::accumulatorStop($accumulator);
         $result['result'] = $activities;
         return $result;
     } catch (Exception $e) {
         eZDebug::accumulatorStop($accumulator);
         eZDebug::writeError($e, self::$debugMessagesGroup);
         return $result;
     }
 }
Ejemplo n.º 5
0
 function get_html($url, $args = '', $asArray = false)
 {
     eZDebug::createAccumulator('get_html ' . $url, 'OCoembed', $url);
     eZDebug::accumulatorStart('get_html ' . $url, 'OCoembed', $url, false);
     $provider = false;
     if (!isset($args['discover'])) {
         $args['discover'] = false;
     }
     foreach ($this->providers as $matchmask => $data) {
         list($providerurl, $regex) = $data;
         // Turn the asterisk-type provider URLs into regex
         if (!$regex) {
             $matchmask = '#' . str_replace('___wildcard___', '(.+)', preg_quote(str_replace('*', '___wildcard___', $matchmask), '#')) . '#i';
         }
         if (preg_match($matchmask, $url)) {
             $provider = str_replace('{format}', 'json', $providerurl);
             // JSON is easier to deal with than XML
             break;
         }
     }
     if (!$provider && $args['discover']) {
         $provider = $this->discover($url);
     }
     if (!$provider || false === ($data = $this->fetch($provider, $url, $args))) {
         eZDebug::accumulatorStop('get_html ' . $url, false);
         return false;
     }
     if ($asArray) {
         eZDebug::accumulatorStop('get_html ' . $url, false);
         return get_object_vars($data);
     }
     eZDebug::accumulatorStop('get_html ' . $url, false);
     return $this->data2html($data, $url);
 }
Ejemplo n.º 6
0
 function search($searchText, $params = array(), $searchTypes = array())
 {
     eZDebug::createAccumulator('Search', 'eZ Find');
     eZDebug::accumulatorStart('Search');
     $error = 'Server not running';
     $asObjects = isset($params['AsObjects']) ? $params['AsObjects'] : true;
     //distributed search: fields to return can be specified in 2 parameters
     $params['FieldsToReturn'] = isset($params['FieldsToReturn']) ? $params['FieldsToReturn'] : array();
     if (isset($params['DistributedSearch']['returnfields'])) {
         $params['FieldsToReturn'] = array_merge($params['FieldsToReturn'], $params['DistributedSearch']['returnfields']);
     }
     $coreToUse = null;
     $shardQueryPart = null;
     if ($this->UseMultiLanguageCores === true) {
         $languages = $this->SiteINI->variable('RegionalSettings', 'SiteLanguageList');
         if (array_key_exists($languages[0], $this->SolrLanguageShards)) {
             $coreToUse = $this->SolrLanguageShards[$languages[0]];
             if ($this->FindINI->variable('LanguageSearch', 'SearchMainLanguageOnly') != 'enabled') {
                 $shardQueryPart = array('shards' => implode(',', $this->SolrLanguageShardURIs));
             }
         }
         //eZDebug::writeNotice( $languages, __METHOD__ . ' languages' );
         eZDebug::writeNotice($shardQueryPart, __METHOD__ . ' shards');
         //eZDebug::writeNotice( $this->SolrLanguageShardURIs, __METHOD__ . ' this languagesharduris' );
     } else {
         $coreToUse = $this->Solr;
     }
     if ($this->SiteINI->variable('SearchSettings', 'AllowEmptySearch') == 'disabled' && trim($searchText) == '') {
         $error = 'Empty search is not allowed.';
         eZDebug::writeNotice($error, __METHOD__);
         $resultArray = null;
     } else {
         eZDebug::createAccumulator('Query build', 'eZ Find');
         eZDebug::accumulatorStart('Query build');
         $queryBuilder = new ezfeZPSolrQueryBuilder($this);
         $queryParams = $queryBuilder->buildSearch($searchText, $params, $searchTypes);
         if (!$shardQueryPart == null) {
             $queryParams = array_merge($shardQueryPart, $queryParams);
         }
         eZDebug::accumulatorStop('Query build');
         eZDebugSetting::writeDebug('extension-ezfind-query', $queryParams, 'Final query parameters sent to Solr backend');
         eZDebug::createAccumulator('Engine time', 'eZ Find');
         eZDebug::accumulatorStart('Engine time');
         $resultArray = $coreToUse->rawSearch($queryParams);
         eZDebug::accumulatorStop('Engine time');
     }
     if ($resultArray) {
         $searchCount = $resultArray['response']['numFound'];
         $objectRes = $this->buildResultObjects($resultArray, $searchCount, $asObjects, $params);
         $stopWordArray = array();
         eZDebug::accumulatorStop('Search');
         return array('SearchResult' => $objectRes, 'SearchCount' => $searchCount, 'StopWordArray' => $stopWordArray, 'SearchExtras' => new ezfSearchResultInfo($resultArray));
     } else {
         eZDebug::accumulatorStop('Search');
         return array('SearchResult' => false, 'SearchCount' => 0, 'StopWordArray' => array(), 'SearchExtras' => new ezfSearchResultInfo(array('error' => ezpI18n::tr('ezfind', $error))));
     }
 }
 /**
  * Test scenario for issue #13956: eZDebug::accumulatorStop( $key, true ) does not remove the recursive counter
  *
  * @link http://issues.ez.no/13956
  * @group issue_13956
  */
 function testAccumulatorStartMultipleResursiveCounter()
 {
     self::markTestSkipped("Pending bugfix");
     eZDebug::accumulatorStart(__METHOD__, false, false, true);
     eZDebug::accumulatorStart(__METHOD__, false, false, true);
     eZDebug::accumulatorStop(__METHOD__, true);
     eZDebug::accumulatorStop(__METHOD__, true);
     eZDebug::accumulatorStart(__METHOD__, false, false, true);
     $debug = eZDebug::instance();
     $this->assertEquals(0, $debug->TimeAccumulatorList[__METHOD__]['recursive_counter']);
 }
Ejemplo n.º 8
0
 /**
  * Parses CSV File
  * @throws SQLICSVException
  * @return SQLICSVDoc
  */
 public function parse()
 {
     eZDebug::accumulatorStart('sqlicsvdoc_loading', 'sqlicsvdoc', 'Loading CSV file in memory');
     $this->csvFile = @fopen($this->options['csv_path'], 'r');
     if (!$this->csvFile) {
         throw new SQLICSVException("Cannot open CSV file '{$this->options['csv_path']}' for reading");
     }
     $this->rows = SQLICSVRowSet::fromCSVFile($this->csvFile, $this->options);
     eZDebug::accumulatorStop('sqlicsvdoc_loading');
     return $this;
 }
 public function execute($process, $event)
 {
     eZDebug::createAccumulatorGroup('nxc_social_networks_publish', 'NXC Social Networks Publish');
     $processParams = $process->attribute('parameter_list');
     $classIDs = unserialize($event->attribute('data_text1'));
     $object = eZContentObject::fetch($processParams['object_id']);
     if (in_array($object->attribute('contentclass_id'), $classIDs) === false) {
         return eZWorkflowType::STATUS_ACCEPTED;
     }
     $dataMap = $object->attribute('data_map');
     $handlers = $event->attribute('handlers');
     foreach ($handlers as $handler) {
         $options = $handler->getOptions();
         if (isset($options['publish_only_on_create']) && (bool) $options['publish_only_on_create'] === true && $object->attribute('current_version') != 1) {
             continue;
         }
         $classAttributeIDs = $handler->attribute('classattribute_ids');
         foreach ($classAttributeIDs as $classAttributeID) {
             $classAttribute = eZContentClassAttribute::fetch($classAttributeID, false);
             if ($classAttribute['contentclass_id'] != $object->attribute('contentclass_id')) {
                 continue;
             }
             $attributeContent = false;
             foreach ($dataMap as $objectAttribute) {
                 if ($objectAttribute->attribute('contentclassattribute_id') == $classAttributeID) {
                     $attributeContent = $objectAttribute->attribute('content');
                     break;
                 }
             }
             if ($attributeContent === false) {
                 continue;
             }
             $accumulator = 'nxc_social_networks_publish_to_' . $handler->attribute('type');
             eZDebug::accumulatorStart($accumulator, 'nxc_social_networks_publish', 'Publishing message to ' . $handler->attribute('name'));
             try {
                 $handler->publish($object, $attributeContent);
             } catch (Exception $e) {
                 eZDebug::writeError($e->getMessage(), 'NXC Social Networks Publish');
             }
             eZDebug::accumulatorStop($accumulator);
         }
     }
     return eZWorkflowType::STATUS_ACCEPTED;
 }
 public function generateNodeListCache($nodeList)
 {
     eZDebug::accumulatorStart('StaticCacheMugo', '', 'StaticCacheMugo');
     if (!empty($nodeList)) {
         foreach ($nodeList as $nodeId) {
             $urls = $this->nodeId2Urls($nodeId);
             foreach ($urls as $url) {
                 if ($this->pathPrefixModifier) {
                     $this->applyPreFixModifier($url);
                 }
                 $key = md5($url);
                 if (!isset(self::$urlsToPurge[$key])) {
                     if ($this->uriTransformation) {
                         eZURI::transformURI($url);
                     }
                     if ($this->urlModifierMatch) {
                         $url = preg_replace($this->urlModifierMatch, $this->urlModifierReplace, $url);
                     }
                     // exclude URLs based on configured patterns
                     if (!empty($this->omitUrlPatterns)) {
                         $matched = false;
                         foreach ($this->omitUrlPatterns as $pattern) {
                             $matched = preg_match($pattern, $purgeUrl);
                         }
                         // skip it and process next URL
                         if ($matched) {
                             continue;
                         }
                     }
                     // add final version of URL to list
                     self::$urlsToPurge[$key] = $url;
                 }
             }
         }
     }
     eZDebug::accumulatorStop('StaticCacheMugo', '', 'StaticCacheMugo');
 }
 function handleResource($tpl, &$resourceData, $method, &$extraParameters)
 {
     $path = $resourceData['template-name'];
     $matchKeys = $this->Keys;
     if (isset($GLOBALS['eZDesignKeys'])) {
         $matchKeys = array_merge($matchKeys, $GLOBALS['eZDesignKeys']);
         unset($GLOBALS['eZDesignKeys']);
         $this->Keys = $matchKeys;
     }
     if (is_array($extraParameters) and isset($extraParameters['ezdesign:keys'])) {
         $this->mergeKeys($matchKeys, $extraParameters['ezdesign:keys']);
     }
     $this->KeyStack[] = $this->Keys;
     $this->Keys = $matchKeys;
     eZDebug::accumulatorStart('override_cache', 'Override', 'Cache load');
     if (!isset($GLOBALS['eZOverrideTemplateCacheMap'])) {
         $overrideCacheFile = $this->createOverrideCache();
         if ($overrideCacheFile) {
             include_once $overrideCacheFile;
         }
     }
     if (isset($GLOBALS['eZOverrideTemplateCacheMap'])) {
         if (isset($GLOBALS['eZOverrideTemplateCacheMap'][md5('/' . $path)])) {
             $cacheMap = $GLOBALS['eZOverrideTemplateCacheMap'][md5('/' . $path)];
             if (!is_string($cacheMap) and trim($cacheMap['code'])) {
                 eval("\$matchFile = " . $cacheMap['code'] . ";");
             } else {
                 $matchFile = $cacheMap;
             }
             $match['file'] = $matchFile;
         }
     } else {
         $template = "/" . $path;
         $matchFileArray = eZTemplateDesignResource::overrideArray($this->OverrideSiteAccess);
         $matchFile = $matchFileArray[$template];
         if (isset($matchFile['custom_match'])) {
             $matchFound = false;
             foreach ($matchFile['custom_match'] as $customMatch) {
                 $matchOverride = true;
                 if (count($customMatch['conditions']) > 0) {
                     foreach (array_keys($customMatch['conditions']) as $conditionKey) {
                         // Create special substring match for subtree override
                         if ($conditionKey == 'url_alias') {
                             if (strpos($matchKeys['url_alias'], $customMatch['conditions'][$conditionKey]) === 0) {
                             } else {
                                 $matchOverride = false;
                             }
                         } else {
                             if (isset($matchKeys[$conditionKey]) and isset($customMatch['conditions'][$conditionKey])) {
                                 if (is_array($matchKeys[$conditionKey])) {
                                     if (!in_array($customMatch['conditions'][$conditionKey], $matchKeys[$conditionKey])) {
                                         $matchOverride = false;
                                     }
                                 } else {
                                     if ($matchKeys[$conditionKey] != $customMatch['conditions'][$conditionKey]) {
                                         $matchOverride = false;
                                     }
                                 }
                             } else {
                                 $matchOverride = false;
                             }
                         }
                     }
                     if ($matchOverride == true) {
                         $match['file'] = $customMatch['match_file'];
                         $matchFound = true;
                         break;
                     } else {
                     }
                 } else {
                     // Default match without conditions
                     $match['file'] = $customMatch['match_file'];
                     $matchFound = true;
                 }
             }
             if (!$matchFound) {
                 $match['file'] = $matchFile['base_dir'] . $matchFile['template'];
             }
         } else {
             $match['file'] = $matchFile['base_dir'] . $matchFile['template'];
         }
     }
     eZDebug::accumulatorStop('override_cache');
     if (isset($match)) {
         $file = $match["file"];
         $matchedKeys = array();
         $usedKeys = array();
         foreach ($matchKeys as $matchKeyName => $matchKeyValue) {
             $usedKeys[$matchKeyName] = $matchKeyValue;
         }
         $extraParameters['ezdesign:used_keys'] = $usedKeys;
         $extraParameters['ezdesign:matched_keys'] = $matchedKeys;
         $tpl->setVariable('used', $usedKeys, 'DesignKeys');
         $tpl->setVariable('matched', $matchedKeys, 'DesignKeys');
         $resourceData['template-filename'] = $file;
         $result = eZTemplateFileResource::handleResourceData($tpl, $this, $resourceData, $method, $extraParameters);
     } else {
         $result = false;
     }
     $this->Keys = array_pop($this->KeyStack);
     return $result;
 }
Ejemplo n.º 12
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;
        }
    }
 function process($tpl, &$textElements, $functionName, $functionChildren, $functionParameters, $functionPlacement, $rootNamespace, $currentNamespace)
 {
     switch ($functionName) {
         case $this->TimingPointName:
             $children = $functionChildren;
             $parameters = $functionParameters;
             $id = false;
             if (isset($parameters["id"])) {
                 $id = $tpl->elementValue($parameters["id"], $rootNamespace, $currentNamespace, $functionPlacement);
             }
             $startDescription = "debug-timing-point START: {$id}";
             eZDebug::addTimingPoint($startDescription);
             if (is_array($children)) {
                 foreach (array_keys($children) as $childKey) {
                     $child =& $children[$childKey];
                     $tpl->processNode($child, $textElements, $rootNamespace, $currentNamespace);
                 }
             }
             $endDescription = "debug-timing-point END: {$id}";
             eZDebug::addTimingPoint($endDescription);
             break;
         case $this->AccumulatorName:
             $children = $functionChildren;
             $parameters = $functionParameters;
             $id = false;
             if (isset($parameters["id"])) {
                 $id = $tpl->elementValue($parameters["id"], $rootNamespace, $currentNamespace, $functionPlacement);
             }
             $name = false;
             if (isset($parameters["name"])) {
                 $name = $tpl->elementValue($parameters["name"], $rootNamespace, $currentNamespace, $functionPlacement);
             }
             // Assign a name (as $functionName) which will be used in the debug output.
             $name = ($name === false and $id === false) ? $functionName : $name;
             // To uniquely identify this accumulator.
             $id = $id === false ? uniqID($functionName . '_') : $id;
             eZDebug::accumulatorStart($id, 'Debug-Accumulator', $name);
             if (is_array($children)) {
                 foreach (array_keys($children) as $childKey) {
                     $child =& $children[$childKey];
                     $tpl->processNode($child, $textElements, $rootNamespace, $currentNamespace);
                 }
             }
             eZDebug::accumulatorStop($id);
             break;
         case $this->LogName:
             $parameters = $functionParameters;
             if (isset($parameters['var'])) {
                 $var = $tpl->elementValue($parameters['var'], $rootNamespace, $currentNamespace, $functionPlacement);
             }
             if (isset($parameters['msg'])) {
                 $msg = $tpl->elementValue($parameters['msg'], $rootNamespace, $currentNamespace, $functionPlacement);
             }
             if (isset($var) && isset($msg)) {
                 eZDebug::writeDebug($var, $msg);
             } elseif (isset($msg)) {
                 eZDebug::writeDebug($msg);
             } elseif (isset($var)) {
                 eZDebug::writeDebug($var);
             }
             break;
         case $this->TraceName:
             $children = $functionChildren;
             $id = false;
             // If we have XDebug we start the trace, execute children and stop it
             // if not we just execute the children as normal
             if (extension_loaded('xdebug')) {
                 $parameters = $functionParameters;
                 if (isset($parameters["id"])) {
                     $id = $tpl->elementValue($parameters["id"], $rootNamespace, $currentNamespace, $functionPlacement);
                 }
                 if (!$id) {
                     $id = 'template-debug';
                 }
                 // If we already have a file, make sure it is truncated
                 if (file_exists($id . '.xt')) {
                     $fd = fopen($id, '.xt', 'w');
                     fclose($fd);
                 }
                 xdebug_start_trace($id);
                 if (is_array($children)) {
                     foreach (array_keys($children) as $childKey) {
                         $child =& $children[$childKey];
                         $tpl->processNode($child, $textElements, $rootNamespace, $currentNamespace);
                     }
                 }
                 xdebug_stop_trace();
             } elseif (is_array($children)) {
                 foreach (array_keys($children) as $childKey) {
                     $child =& $children[$childKey];
                     $tpl->processNode($child, $textElements, $rootNamespace, $currentNamespace);
                 }
             }
             break;
     }
 }
Ejemplo n.º 14
0
 protected function accumulatorStop()
 {
     eZDebug::accumulatorStop('mysql_cluster_dfs_operations');
 }
    public function suggestedTerms()
    {
        if ( mb_strlen($this->searchQuery, 'UTF-8') < 3 )
        {
            return array();
        }

        eZDebug::accumulatorStart(__CLASS__.'::'.__FUNCTION__, 'Merck' );

        $solrHighlightParams = $this->solrHighlightParams();
        $suggestions         = array();
        $filters             = array();
        $solrFilter          = $this->solrFilter();
        $solrFacetsFiler     = $this->solrFacetsFilter();

        if( $solrFilter )
            $filters[] = $solrFilter;
        if( $solrFacetsFiler )
            $filters[] = $solrFacetsFiler;

        $queries = array();
        $terms   = MMGlobalSearchDictionaryTerm::fetchSolrTerms( $this->searchQuery, null, $this->suggestedTermsLimit() * 3 );

        foreach( $terms as $term )
        {
            $query = array();

            foreach( explode( ' ', $solrHighlightParams['hl.fl'] ) as $field )
                $query[] = $field.':"'.addslashes( $term ).'"';

            $queries[] = implode( ' OR ', $query );
        }

        $params = array(
                'start'	        => 0,
                'rows'	        => 0,
                'q'		        => '*:*',
                'fq'	        => implode(' AND ' , $filters),
                'facet'	        => 'true',
                'facet.query'   => $queries,
        );
        $solrResults = SolrTool::rawSearch( $params );

        $i = 0;
        foreach( $solrResults['facet_counts']['facet_queries'] as $solrTerm => $solrTermCount )
        {
            if( $solrTermCount )
            {
                $term = $terms[$i];
                if( strtolower( trim( $term ) ) != strtolower( trim( $this->searchQuery, ' "' ) ) )
                {
                    $suggestions[] = array(
                        't'	=> $term,
                        'c'	=> $solrTermCount);

                    if( count( $suggestions ) >= $this->suggestedTermsLimit() )
                        break;
                }
            }
            $i++;
        }


        // sort
        usort( $suggestions, function($a, $b){
            return ($a['c'] < $b['c']);
        } );

        eZDebug::accumulatorStop( __CLASS__.'::'.__FUNCTION__ );

        return $suggestions;
    }
Ejemplo n.º 16
0
 public static function accumulatorStop($val)
 {
     // allow 3rd party code to leave in perf. measuring hooks with minimal speed loss
     if (!self::$activated) {
         return false;
     }
     $stopTime = microtime(true);
     if (eZPerfLoggerDebug::isDebugEnabled()) {
         eZDebug::accumulatorStop($val);
     }
     if (!isset(self::$timeAccumulatorList[$val]['count'])) {
         self::$timeAccumulatorList[$val]['count'] = 1;
     } else {
         self::$timeAccumulatorList[$val]['count'] = self::$timeAccumulatorList[$val]['count'] + 1;
     }
     $thisTime = $stopTime - self::$timeAccumulatorList[$val]['temp_time'];
     unset(self::$timeAccumulatorList[$val]['temp_time']);
     self::$timeAccumulatorList[$val]['time'] = $thisTime + self::$timeAccumulatorList[$val]['time'];
     if ($thisTime > self::$timeAccumulatorList[$val]['maxtime']) {
         self::$timeAccumulatorList[$val]['maxtime'] = $thisTime;
     }
 }
Ejemplo n.º 17
0
    function arrayQuery( $sql, $params = array(), $server = false )
    {
        $retArray = array();
        if ( $this->IsConnected )
        {
            $limit = false;
            $offset = 0;
            $column = false;
            // check for array parameters
            if ( is_array( $params ) )
            {
                if ( isset( $params["limit"] ) and is_numeric( $params["limit"] ) )
                    $limit = $params["limit"];

                if ( isset( $params["offset"] ) and is_numeric( $params["offset"] ) )
                    $offset = $params["offset"];

                if ( isset( $params["column"] ) and ( is_numeric( $params["column"] ) or is_string( $params["column"] ) ) )
                    $column = $params["column"];
            }

            if ( $limit !== false and is_numeric( $limit ) )
            {
                $sql .= "\nLIMIT $offset, $limit ";
            }
            else if ( $offset !== false and is_numeric( $offset ) and $offset > 0 )
            {
                $sql .= "\nLIMIT $offset, 18446744073709551615"; // 2^64-1
            }
            $result = $this->query( $sql, $server );

            if ( $result == false )
            {
                $this->reportQuery( __CLASS__, $sql, false, false );
                return false;
            }

            $numRows = mysql_num_rows( $result );
            if ( $numRows > 0 )
            {
                if ( !is_string( $column ) )
                {
                    eZDebug::accumulatorStart( 'mysql_loop', 'mysql_total', 'Looping result' );
                    for ( $i=0; $i < $numRows; $i++ )
                    {
                        if ( $this->InputTextCodec )
                        {
                            $tmpRow = mysql_fetch_array( $result, MYSQL_ASSOC );
                            $convRow = array();
                            foreach( $tmpRow as $key => $row )
                            {
                                eZDebug::accumulatorStart( 'mysql_conversion', 'mysql_total', 'String conversion in mysql' );
                                $convRow[$key] = $this->OutputTextCodec->convertString( $row );
                                eZDebug::accumulatorStop( 'mysql_conversion' );
                            }
                            $retArray[$i + $offset] = $convRow;
                        }
                        else
                            $retArray[$i + $offset] = mysql_fetch_array( $result, MYSQL_ASSOC );
                    }
                    eZDebug::accumulatorStop( 'mysql_loop' );

                }
                else
                {
                    eZDebug::accumulatorStart( 'mysql_loop', 'mysql_total', 'Looping result' );
                    for ( $i=0; $i < $numRows; $i++ )
                    {
                        $tmp_row = mysql_fetch_array( $result, MYSQL_ASSOC );
                        if ( $this->InputTextCodec )
                        {
                            eZDebug::accumulatorStart( 'mysql_conversion', 'mysql_total', 'String conversion in mysql' );
                            $retArray[$i + $offset] = $this->OutputTextCodec->convertString( $tmp_row[$column] );
                            eZDebug::accumulatorStop( 'mysql_conversion' );
                        }
                        else
                            $retArray[$i + $offset] =& $tmp_row[$column];
                    }
                    eZDebug::accumulatorStop( 'mysql_loop' );
                }
            }
        }
        return $retArray;
    }
Ejemplo n.º 18
0
    /**
     * Checks if the given $path exists.
     *
     * @param string $path
     * @return bool
     */
    function fileExists( $path )
    {
        eZDebugSetting::writeDebug( 'kernel-clustering', "fs::fileExists( '$path' )", __METHOD__ );

        eZDebug::accumulatorStart( 'dbfile', false, 'dbfile' );
        $rc = file_exists( $path ) && ( filemtime( $path ) != self::EXPIRY_TIMESTAMP );
        eZDebug::accumulatorStop( 'dbfile' );

        return $rc;
    }
Ejemplo n.º 19
0
 function contentClassAttributeCanTranslate()
 {
     if ($this->ContentClassAttributeCanTranslate === null) {
         eZDebug::accumulatorStart('class_a_can_translate', 'Sytem overhead', 'Fetch class attribute can translate value');
         $classAttribute = eZContentClassAttribute::fetch($this->ContentClassAttributeID);
         $dataType = $classAttribute->dataType();
         if ($dataType && $dataType->Attributes["properties"]["translation_allowed"] && $classAttribute->attribute('can_translate')) {
             $this->ContentClassAttributeCanTranslate = 1;
         } else {
             $this->ContentClassAttributeCanTranslate = 0;
         }
         eZDebug::accumulatorStop('class_a_can_translate');
     }
     return $this->ContentClassAttributeCanTranslate;
 }
Ejemplo n.º 20
0
 /**
  * Clears content cache for specified object: view cache, template-block cache, template-block with subtree_expiry parameter cache
  * without checking of ini settings.
  *
  * @param int|array $objectID (list of) object ID
  * @param bool|int $versionNum
  * @param bool|array $additionalNodeList
  */
 static function clearContentCache($objectID, $versionNum = true, $additionalNodeList = false)
 {
     eZDebug::accumulatorStart('check_cache', '', 'Check cache');
     if (is_array($objectID)) {
         if ($versionNum !== true || $additionalNodeList !== false) {
             trigger_error("This method does not support second and third parameters when operating on many objects!");
             return false;
         }
         self::clearObjectViewCacheArray($objectID);
     } else {
         self::clearObjectViewCache($objectID, $versionNum, $additionalNodeList);
     }
     self::clearTemplateBlockCache($objectID);
     // Clear cached path strings of content SSL zones.
     eZSSLZone::clearCache();
     eZDebug::accumulatorStop('check_cache');
     return true;
 }
Ejemplo n.º 21
0
    /**
     * Performs mysql query and returns mysql result.
     * Times the sql execution, adds accumulator timings and reports SQL to
     * debug.
     * @param string $fname The function name that started the query, should
     *                      contain relevant arguments in the text.
     */
    protected function _query( $query, $fname = false, $reportError = true )
    {
        eZDebug::accumulatorStart( 'mysql_cluster_query', 'MySQL Cluster', 'DB queries' );
        $time = microtime( true );

        $res = mysqli_query( $this->db, $query );
        if ( !$res && $reportError )
        {
            $this->_error( $query, $fname );
        }

        $numRows = mysqli_affected_rows( $this->db );

        $time = microtime( true ) - $time;
        eZDebug::accumulatorStop( 'mysql_cluster_query' );

        $this->_report( $query, $fname, $time, $numRows );
        return $res;
    }
Ejemplo n.º 22
0
 /**
  * Loads a translation file
  * Will load from cache if possible, or generate cache if needed
  *
  * Also checks for translation files expiry based on mtime if RegionalSettings.TranslationCheckMTime is enabled
  *
  * @access private
  * @param string $locale
  * @param string $filename
  * @param string $requestedContext
  *
  * @return bool The operation status, true or false
  */
 function loadTranslationFile($locale, $filename, $requestedContext)
 {
     // First try for current charset
     $charset = eZTextCodec::internalCharset();
     $tsTimeStamp = false;
     $ini = eZINI::instance();
     $checkMTime = $ini->variable('RegionalSettings', 'TranslationCheckMTime') === 'enabled';
     if (!$this->RootCache) {
         $roots = array($ini->variable('RegionalSettings', 'TranslationRepository'));
         $extensionBase = eZExtension::baseDirectory();
         $translationExtensions = $ini->variable('RegionalSettings', 'TranslationExtensions');
         foreach ($translationExtensions as $translationExtension) {
             $extensionPath = $extensionBase . '/' . $translationExtension . '/translations';
             if (!$checkMTime || file_exists($extensionPath)) {
                 $roots[] = $extensionPath;
             }
         }
         $this->RootCache = array('roots' => $roots);
     } else {
         $roots = $this->RootCache['roots'];
         if (isset($this->RootCache['timestamp'])) {
             $tsTimeStamp = $this->RootCache['timestamp'];
         }
     }
     // Load cached translations if possible
     if ($this->UseCache == true) {
         if (!$tsTimeStamp) {
             $expiry = eZExpiryHandler::instance();
             $globalTsTimeStamp = $expiry->getTimestamp(self::EXPIRY_KEY, 0);
             $localeTsTimeStamp = $expiry->getTimestamp(self::EXPIRY_KEY . '-' . $locale, 0);
             $tsTimeStamp = max($globalTsTimeStamp, $localeTsTimeStamp);
             if ($checkMTime && $tsTimeStamp < time()) {
                 // iterate over each known TS file, and get the highest timestamp
                 // this value will be used to check for cache validity
                 foreach ($roots as $root) {
                     $path = eZDir::path(array($root, $locale, $charset, $filename));
                     if (file_exists($path)) {
                         $timestamp = filemtime($path);
                         if ($timestamp > $tsTimeStamp) {
                             $tsTimeStamp = $timestamp;
                         }
                     } else {
                         $path = eZDir::path(array($root, $locale, $filename));
                         if (file_exists($path)) {
                             $timestamp = filemtime($path);
                             if ($timestamp > $tsTimeStamp) {
                                 $tsTimeStamp = $timestamp;
                             }
                         }
                     }
                 }
             }
             $this->RootCache['timestamp'] = $tsTimeStamp;
         }
         $key = 'cachecontexts';
         if ($this->HasRestoredCache or eZTranslationCache::canRestoreCache($key, $tsTimeStamp)) {
             eZDebug::accumulatorStart('tstranslator_cache_load', 'tstranslator', 'TS cache load');
             if (!$this->HasRestoredCache) {
                 if (!eZTranslationCache::restoreCache($key)) {
                     $this->BuildCache = true;
                 }
                 $contexts = eZTranslationCache::contextCache($key);
                 if (!is_array($contexts)) {
                     $contexts = array();
                 }
                 $this->HasRestoredCache = $contexts;
             } else {
                 $contexts = $this->HasRestoredCache;
             }
             if (!$this->BuildCache) {
                 $contextName = $requestedContext;
                 if (!isset($this->CachedMessages[$contextName])) {
                     eZDebug::accumulatorStart('tstranslator_context_load', 'tstranslator', 'TS context load');
                     if (eZTranslationCache::canRestoreCache($contextName, $tsTimeStamp)) {
                         if (!eZTranslationCache::restoreCache($contextName)) {
                             $this->BuildCache = true;
                         }
                         $this->CachedMessages[$contextName] = eZTranslationCache::contextCache($contextName);
                         foreach ($this->CachedMessages[$contextName] as $key => $msg) {
                             $this->Messages[$key] = $msg;
                         }
                     }
                     eZDebug::accumulatorStop('tstranslator_context_load');
                 }
             }
             eZDebugSetting::writeNotice('i18n-tstranslator', "Loading cached translation", __METHOD__);
             eZDebug::accumulatorStop('tstranslator_cache_load');
             if (!$this->BuildCache) {
                 return true;
             }
         }
         eZDebugSetting::writeNotice('i18n-tstranslator', "Translation cache has expired. Will rebuild it from source.", __METHOD__);
         $this->BuildCache = true;
     }
     $status = false;
     // first process country translation files
     // then process country variation translation files
     $localeParts = explode('@', $locale);
     $triedPaths = array();
     $loadedPaths = array();
     $ini = eZINI::instance("i18n.ini");
     $fallbacks = $ini->variable('TranslationSettings', 'FallbackLanguages');
     foreach ($localeParts as $localePart) {
         $localeCodeToProcess = isset($localeCodeToProcess) ? $localeCodeToProcess . '@' . $localePart : $localePart;
         // array with alternative subdirs to check
         $alternatives = array(array($localeCodeToProcess, $charset, $filename), array($localeCodeToProcess, $filename));
         if (isset($fallbacks[$localeCodeToProcess]) && $fallbacks[$localeCodeToProcess]) {
             if ($fallbacks[$localeCodeToProcess] === 'eng-GB') {
                 $fallbacks[$localeCodeToProcess] = 'untranslated';
             }
             $alternatives[] = array($fallbacks[$localeCodeToProcess], $charset, $filename);
             $alternatives[] = array($fallbacks[$localeCodeToProcess], $filename);
         }
         foreach ($roots as $root) {
             if (!file_exists($root)) {
                 continue;
             }
             unset($path);
             foreach ($alternatives as $alternative) {
                 $pathParts = $alternative;
                 array_unshift($pathParts, $root);
                 $pathToTry = eZDir::path($pathParts);
                 $triedPaths[] = $pathToTry;
                 if (file_exists($pathToTry)) {
                     $path = $pathToTry;
                     break;
                 }
             }
             if (!isset($path)) {
                 continue;
             }
             eZDebug::accumulatorStart('tstranslator_load', 'tstranslator', 'TS load');
             $doc = new DOMDocument('1.0', 'utf-8');
             $success = $doc->load($path);
             if (!$success) {
                 eZDebug::writeWarning("Unable to load XML from file {$path}", __METHOD__);
                 continue;
             }
             if (!$this->validateDOMTree($doc)) {
                 eZDebug::writeWarning("XML text for file {$path} did not validate", __METHOD__);
                 continue;
             }
             $loadedPaths[] = $path;
             $status = true;
             $treeRoot = $doc->documentElement;
             $children = $treeRoot->childNodes;
             for ($i = 0; $i < $children->length; $i++) {
                 $child = $children->item($i);
                 if ($child->nodeType == XML_ELEMENT_NODE) {
                     if ($child->tagName == "context") {
                         $this->handleContextNode($child);
                     }
                 }
             }
             eZDebug::accumulatorStop('tstranslator_load');
         }
     }
     eZDebugSetting::writeDebug('i18n-tstranslator', implode(PHP_EOL, $triedPaths), __METHOD__ . ': tried paths');
     eZDebugSetting::writeDebug('i18n-tstranslator', implode(PHP_EOL, $loadedPaths), __METHOD__ . ': loaded paths');
     // Save translation cache
     if ($this->UseCache == true && $this->BuildCache == true) {
         eZDebug::accumulatorStart('tstranslator_store_cache', 'tstranslator', 'TS store cache');
         if (eZTranslationCache::contextCache('cachecontexts') == null) {
             $contexts = array_keys($this->CachedMessages);
             eZTranslationCache::setContextCache('cachecontexts', $contexts);
             eZTranslationCache::storeCache('cachecontexts');
             $this->HasRestoredCache = $contexts;
         }
         foreach ($this->CachedMessages as $contextName => $context) {
             if (eZTranslationCache::contextCache($contextName) == null) {
                 eZTranslationCache::setContextCache($contextName, $context);
             }
             eZTranslationCache::storeCache($contextName);
         }
         $this->BuildCache = false;
         eZDebug::accumulatorStop('tstranslator_store_cache');
     }
     return $status;
 }
Ejemplo n.º 23
0
 function arrayQuery($sql, $params = array(), $server = false)
 {
     $retArray = array();
     if ($this->isConnected()) {
         $limit = -1;
         $offset = 0;
         // check for array parameters
         if (is_array($params)) {
             //                $params = $min;
             $column = false;
             if (isset($params["limit"]) and is_numeric($params["limit"])) {
                 $limit = $params["limit"];
             }
             if (isset($params["offset"]) and is_numeric($params["offset"])) {
                 $offset = $params["offset"];
             }
             if (isset($params["column"]) and (is_numeric($params["column"]) or is_string($params["column"]))) {
                 $column = $params["column"];
             }
         }
         if ($limit != -1) {
             $sql .= "\nLIMIT {$limit}";
         }
         if ($offset > 0) {
             if ($limit == -1) {
                 $sql .= "\n";
             } else {
                 $sql .= " ";
             }
             $sql .= "OFFSET {$offset}";
         }
         eZDebug::accumulatorStart('postgresql_query', 'postgresql_total', 'Postgresql queries');
         $result = $this->query($sql);
         eZDebug::accumulatorStop('postgresql_query');
         if ($result == false) {
             return false;
         }
         if (pg_numrows($result) > 0) {
             eZDebug::accumulatorStart('postgresql_loop', 'postgresql_total', 'Looping result');
             if (!is_string($column)) {
                 for ($i = 0; $i < pg_numrows($result); $i++) {
                     $retArray[$i + $offset] = pg_fetch_array($result, $i, PGSQL_ASSOC);
                 }
             } else {
                 for ($i = 0; $i < pg_numrows($result); $i++) {
                     $tmp_row = pg_fetch_array($result, $i, PGSQL_ASSOC);
                     $retArray[$i + $offset] =& $tmp_row[$column];
                 }
             }
             eZDebug::accumulatorStart('postgresql_loop');
         }
         pg_free_result($result);
     }
     return $retArray;
 }
    /**
     * @return array
     */
    function stateIdentifierArray()
    {
        if ( !$this->ID )
            return array();

        eZDebug::accumulatorStart( 'state_identifier_array', 'states' );
        $return = array();
        $sql = "SELECT l.contentobject_state_id, s.identifier AS state_identifier, g.identifier AS state_group_identifier
                FROM ezcobj_state_link l, ezcobj_state s, ezcobj_state_group g
                WHERE l.contentobject_id={$this->ID} AND
                      s.id=l.contentobject_state_id AND
                      g.id=s.group_id";
        $db = eZDB::instance();
        $rows = $db->arrayQuery( $sql );
        foreach ( $rows as $row )
        {
            $return[] = $row['state_group_identifier'] . '/' . $row['state_identifier'];
        }
        eZDebug::accumulatorStop( 'state_identifier_array' );
        return $return;
    }
Ejemplo n.º 25
0
 /**
  * Get an array of class attribute identifiers based on either a class attribute
  * list, or a content classes list
  *
  * @param array $classIDArray
  *        Classes to search in. Either an array of class ID, class identifiers,
  *        a class ID or a class identifier.
  *        Using numerical attribute/class identifiers for $classIDArray is more efficient.
  * @param array $classAttributeID
  *        Class attributes to search in. Either an array of class attribute id,
  *        or a single class attribute. Literal identifiers are not allowed.
  * @param array $fieldTypeExcludeList
  *        filter list. List of field types to exclude. ( set to empty array by default ).
  *
  * @return array List of solr field names.
  */
 protected function getClassAttributes($classIDArray = false, $classAttributeIDArray = false, $fieldTypeExcludeList = null)
 {
     eZDebug::createAccumulator('Class attribute list', 'eZ Find');
     eZDebug::accumulatorStart('Class attribute list');
     $fieldArray = array();
     $classAttributeArray = array();
     // classAttributeIDArray = simple integer (content class attribute ID)
     if (is_numeric($classAttributeIDArray) and $classAttributeIDArray > 0) {
         $classAttributeArray[] = eZContentClassAttribute::fetch($classAttributeIDArray);
     } else {
         if (is_array($classAttributeIDArray)) {
             foreach ($classAttributeIDArray as $classAttributeID) {
                 $classAttributeArray[] = eZContentClassAttribute::fetch($classAttributeID);
             }
         }
     }
     // no class attribute list given, we need a class list
     // this block will create the class attribute array based on $classIDArray
     if (empty($classAttributeArray)) {
         // Fetch class list.
         $condArray = array("is_searchable" => 1, "version" => eZContentClass::VERSION_STATUS_DEFINED);
         if (!$classIDArray) {
             $classIDArray = array();
         } else {
             if (!is_array($classIDArray)) {
                 $classIDArray = array($classIDArray);
             }
         }
         // literal class identifiers are converted to numerical ones
         $tmpClassIDArray = $classIDArray;
         $classIDArray = array();
         foreach ($tmpClassIDArray as $key => $classIdentifier) {
             if (!is_numeric($classIdentifier)) {
                 if (!($contentClass = eZContentClass::fetchByIdentifier($classIdentifier, false))) {
                     eZDebug::writeWarning("Unknown content class identifier '{$classIdentifier}'", __METHOD__);
                 } else {
                     $classIDArray[] = $contentClass['id'];
                 }
             } else {
                 $classIDArray[] = $classIdentifier;
             }
         }
         if (!empty($classIDArray)) {
             $condArray['contentclass_id'] = array($classIDArray);
         }
         $classAttributeArray = eZContentClassAttribute::fetchFilteredList($condArray);
     }
     // $classAttributeArray now contains a list of eZContentClassAttribute
     // we can use to construct the list of fields solr should search in
     // @TODO : retrieve sub attributes here. Mind the types !
     foreach ($classAttributeArray as $classAttribute) {
         $fieldArray = array_merge(ezfSolrDocumentFieldBase::getFieldNameList($classAttribute, $fieldTypeExcludeList), $fieldArray);
     }
     // the array is unified + sorted in order to make it consistent
     $fieldArray = array_unique($fieldArray);
     sort($fieldArray);
     eZDebug::accumulatorStop('Class attribute list');
     return $fieldArray;
 }
Ejemplo n.º 26
0
 function _query($query, $fname = false, $reportError = true)
 {
     eZDebug::accumulatorStart('mysql_cluster_query', 'mysql_cluster_total', 'Mysql_cluster_queries');
     $time = microtime(true);
     $res = mysqli_query($this->db, $query);
     if (!$res && $reportError) {
         $this->_error($query, $fname);
     }
     $numRows = 0;
     if (is_object($res)) {
         $numRows = mysqli_num_rows($res);
     }
     $time = microtime(true) - $time;
     eZDebug::accumulatorStop('mysql_cluster_query');
     $this->_report($query, $fname, $time, $numRows);
     return $res;
 }
 /**
  * Registers the object in search engine.
  *
  * @note Transaction unsafe. If you call several transaction unsafe methods you must enclose
  *       the calls within a db transaction; thus within db->begin and db->commit.
  *
  * @param int $objectID Id of the object.
  */
 public static function registerSearchObject($objectID)
 {
     $objectID = (int) $objectID;
     eZDebug::createAccumulatorGroup('search_total', 'Search Total');
     $ini = eZINI::instance('site.ini');
     $insertPendingAction = false;
     $object = null;
     switch ($ini->variable('SearchSettings', 'DelayedIndexing')) {
         case 'enabled':
             $insertPendingAction = true;
             break;
         case 'classbased':
             $classList = $ini->variable('SearchSettings', 'DelayedIndexingClassList');
             $object = eZContentObject::fetch($objectID);
             if (is_array($classList) && in_array($object->attribute('class_identifier'), $classList)) {
                 $insertPendingAction = true;
             }
     }
     if ($insertPendingAction) {
         eZDB::instance()->query("INSERT INTO ezpending_actions( action, param ) VALUES ( 'index_object', '{$objectID}' )");
         return;
     }
     if ($object === null) {
         $object = eZContentObject::fetch($objectID);
     }
     // Register the object in the search engine.
     $needCommit = eZSearch::needCommit();
     if (eZSearch::needRemoveWithUpdate()) {
         eZDebug::accumulatorStart('remove_object', 'search_total', 'remove object');
         eZSearch::removeObject($object, $needCommit);
         eZDebug::accumulatorStop('remove_object');
     }
     eZDebug::accumulatorStart('add_object', 'search_total', 'add object');
     if (!eZSearch::addObject($object, $needCommit)) {
         eZDebug::writeError("Failed adding object ID {$object->attribute('id')} in the search engine", __METHOD__);
     }
     eZDebug::accumulatorStop('add_object');
 }
Ejemplo n.º 28
0
 function parseFile($file, $placement = false)
 {
     if (eZINI::isDebugEnabled()) {
         eZDebug::writeNotice("Parsing file '{$file}'", __METHOD__);
     }
     $contents = file_get_contents($file);
     if ($contents === false) {
         eZDebug::writeError("Failed opening file '{$file}' for reading", __METHOD__);
         return false;
     }
     $contents = str_replace("\r", '', $contents);
     $endOfLine = strpos($contents, "\n");
     $line = substr($contents, 0, $endOfLine);
     $currentBlock = "";
     if ($line) {
         // check for charset
         if (preg_match("/#\\?ini(.+)\\?/", $line, $ini_arr)) {
             $args = explode(" ", trim($ini_arr[1]));
             foreach ($args as $arg) {
                 $vars = explode('=', trim($arg));
                 if ($vars[0] == "charset") {
                     $val = $vars[1];
                     if ($val[0] == '"' and strlen($val) > 0 and $val[strlen($val) - 1] == '"') {
                         $val = substr($val, 1, strlen($val) - 2);
                     }
                     $this->Charset = $val;
                 }
             }
         }
     }
     unset($this->Codec);
     if ($this->UseTextCodec) {
         $this->Codec = eZTextCodec::instance($this->Charset, false, false);
         if ($this->Codec) {
             eZDebug::accumulatorStart('ini_conversion', false, 'INI string conversion');
             $contents = $this->Codec->convertString($contents);
             eZDebug::accumulatorStop('ini_conversion', false, 'INI string conversion');
         }
     } else {
         $this->Codec = null;
     }
     foreach (explode("\n", $contents) as $line) {
         if ($line == '' or $line[0] == '#') {
             continue;
         }
         if (preg_match("/^(.+)##.*/", $line, $regs)) {
             $line = $regs[1];
         }
         if (trim($line) == '') {
             continue;
         }
         // check for new block
         if (preg_match("#^\\[(.+)\\]\\s*\$#", $line, $newBlockNameArray)) {
             $newBlockName = trim($newBlockNameArray[1]);
             $currentBlock = $newBlockName;
             continue;
         }
         // check for variable
         if (preg_match("#^([\\w_*@-]+)\\[\\]\$#", $line, $valueArray)) {
             $varName = trim($valueArray[1]);
             if ($placement) {
                 if (isset($this->BlockValuesPlacement[$currentBlock][$varName]) && !is_array($this->BlockValuesPlacement[$currentBlock][$varName])) {
                     eZDebug::writeError("Wrong operation on the ini setting array '{$varName}'", __METHOD__);
                     continue;
                 }
                 $this->BlockValuesPlacement[$currentBlock][$varName][] = $file;
             } else {
                 $this->BlockValues[$currentBlock][$varName] = array();
                 // In direct access mode we create empty elements at the beginning of an array
                 // in case it is redefined in this ini file. So when we will save it, definition
                 // will be created as well.
                 if ($this->AddArrayDefinition) {
                     $this->BlockValues[$currentBlock][$varName][] = "";
                 }
             }
         } else {
             if (preg_match("#^([\\w_*@-]+)(\\[([^\\]]*)\\])?=(.*)\$#", $line, $valueArray)) {
                 $varName = trim($valueArray[1]);
                 $varValue = $valueArray[4];
                 if ($valueArray[2]) {
                     if ($valueArray[3]) {
                         $keyName = $valueArray[3];
                         if ($placement) {
                             $this->BlockValuesPlacement[$currentBlock][$varName][$keyName] = $file;
                         } else {
                             $this->BlockValues[$currentBlock][$varName][$keyName] = $varValue;
                         }
                     } else {
                         if ($placement) {
                             $this->BlockValuesPlacement[$currentBlock][$varName][] = $file;
                         } else {
                             $this->BlockValues[$currentBlock][$varName][] = $varValue;
                         }
                     }
                 } else {
                     if ($placement) {
                         $this->BlockValuesPlacement[$currentBlock][$varName] = $file;
                     } else {
                         $this->BlockValues[$currentBlock][$varName] = $varValue;
                     }
                 }
             }
         }
     }
 }
 /**
  * Move file.
  *
  * \public
  */
 function move($dstPath)
 {
     $srcPath = $this->filePath;
     eZDebugSetting::writeDebug('kernel-clustering', "fs::move( '{$srcPath}', '{$dstPath}' )", __METHOD__);
     eZDebug::accumulatorStart('dbfile', false, 'dbfile');
     eZFileHandler::move($srcPath, $dstPath);
     eZDebug::accumulatorStop('dbfile');
 }
 function handleResourceData($tpl, $handler, &$resourceData, $method, &$extraParameters)
 {
     // &$templateRoot, &$text, &$tstamp, $uri, $resourceName, &$path, &$keyData
     $templateRoot =& $resourceData['root-node'];
     $text =& $resourceData['text'];
     $tstamp =& $resourceData['time-stamp'];
     $uri =& $resourceData['uri'];
     $resourceName =& $resourceData['resource'];
     $path =& $resourceData['template-filename'];
     $keyData =& $resourceData['key-data'];
     $localeData =& $resourceData['locales'];
     if (!file_exists($path)) {
         return false;
     }
     $tstamp = filemtime($path);
     $result = false;
     $canCache = true;
     $templateRoot = null;
     if (!$handler->servesStaticData()) {
         $canCache = false;
     }
     if (!$tpl->isCachingAllowed()) {
         $canCache = false;
     }
     $keyData = 'file:' . $path;
     if ($method == eZTemplate::RESOURCE_FETCH) {
         if ($canCache) {
             if ($handler->hasCompiledTemplate($keyData, $uri, $resourceData, $path, $extraParameters, $tstamp)) {
                 $resourceData['compiled-template'] = true;
                 return true;
             }
         }
         if ($canCache) {
             $templateRoot = $handler->cachedTemplateTree($keyData, $uri, $resourceName, $path, $extraParameters, $tstamp);
         }
         if ($templateRoot !== null) {
             return true;
         }
         if (is_readable($path)) {
             $text = file_get_contents($path);
             $text = preg_replace("/\n|\r\n|\r/", "\n", $text);
             $tplINI = $tpl->ini();
             $charset = $tplINI->variable('CharsetSettings', 'DefaultTemplateCharset');
             $locales = array();
             $pos = strpos($text, "\n");
             if ($pos !== false) {
                 $line = substr($text, 0, $pos);
                 if (preg_match("/^\\{\\*\\?template(.+)\\?\\*\\}/", $line, $tpl_arr)) {
                     $args = explode(" ", trim($tpl_arr[1]));
                     foreach ($args as $arg) {
                         $vars = explode('=', trim($arg));
                         switch ($vars[0]) {
                             case 'charset':
                                 $val = $vars[1];
                                 if ($val[0] == '"' and strlen($val) > 0 and $val[strlen($val) - 1] == '"') {
                                     $val = substr($val, 1, strlen($val) - 2);
                                 }
                                 $charset = $val;
                                 break;
                             case 'locale':
                                 $val = $vars[1];
                                 if ($val[0] == '"' and strlen($val) > 0 and $val[strlen($val) - 1] == '"') {
                                     $val = substr($val, 1, strlen($val) - 2);
                                 }
                                 $locales = explode(',', $val);
                                 break;
                         }
                     }
                 }
             }
             /* Setting locale to allow standard PHP functions to handle
              * strtoupper/lower() */
             $defaultLocale = trim($tplINI->variable('CharsetSettings', 'DefaultTemplateLocale'));
             if ($defaultLocale != '') {
                 $locales = array_merge($locales, explode(',', $defaultLocale));
             }
             $localeData = $locales;
             if ($locales && count($locales)) {
                 setlocale(LC_CTYPE, $locales);
             }
             if (eZTemplate::isDebugEnabled()) {
                 eZDebug::writeNotice("{$path}, {$charset}");
             }
             $codec = eZTextCodec::instance($charset, false, false);
             if ($codec) {
                 eZDebug::accumulatorStart('template_resource_conversion', 'template_total', 'String conversion in template resource');
                 $text = $codec->convertString($text);
                 eZDebug::accumulatorStop('template_resource_conversion');
             }
             $result = true;
         }
     } else {
         if ($method == eZTemplate::RESOURCE_QUERY) {
             $result = true;
         }
     }
     return $result;
 }