コード例 #1
0
ファイル: ocembed.php プロジェクト: rantoniazzi/ocembed
 function run($url = '', $args = array())
 {
     if (empty($url)) {
         return '';
     }
     $args = array_merge($this->embed_defaults, $args);
     foreach ($this->handlers as $handler) {
         if (in_array('OCCustomEmbedHandlerInterface', class_implements($handler))) {
             if ($regex = call_user_func(array($handler, 'regex'))) {
                 if (preg_match($regex, $url, $matches)) {
                     if (false !== ($result = call_user_func(array($handler, 'callback'), $matches, $url, $args))) {
                         eZDebugSetting::writeNotice('ocembed', 'Autoembed has found url "' . $url . '" in ' . $handler, __METHOD__);
                         return $result;
                     }
                 }
             }
         }
     }
     $oembed = new OCoEmbed();
     $result = $oembed->get_html($url, $args);
     if ($result) {
         eZDebugSetting::writeNotice('ocembed', 'Autoembed has found url "' . $url . '" in a OEmbed provider', __METHOD__);
         if (!eZINI::instance('ocembed.ini')->hasVariable('Settings', 'DisableFixHttps')) {
             $result = str_replace('http://', '//', $result);
         }
         return $result;
     }
     // Still unknown
     eZDebugSetting::writeNotice('ocembed', 'Autoembed did not find url "' . $url . '"', __METHOD__);
     return array($this->maybe_make_link($url));
 }
コード例 #2
0
ファイル: eztidy.php プロジェクト: philandteds/eztidy
 /**
  * Show tidy warning
  */
 private function reportWarning()
 {
     $warning = tidy_get_error_buffer($this->tidy);
     if (!empty($warning)) {
         eZDebugSetting::writeWarning("extension-eztidy", "{$warning}", 'eZTidy::tidyCleaner()');
     }
 }
コード例 #3
0
 /**
  * Goes trough the directory path and removes empty directories, starting at
  * the leaf and deleting down until a non empty directory is reached.
  * If the path is not a directory, nothing will happen.
  *
  * @param string $path
  */
 public static function cleanupEmptyDirectories($path)
 {
     $dirpath = eZDir::dirpath($path);
     eZDebugSetting::writeDebug('kernel-clustering', "eZClusterFileHandler::cleanupEmptyDirectories( '{$dirpath}' )");
     if (is_dir($dirpath)) {
         eZDir::cleanupEmptyDirectories($dirpath);
     }
 }
コード例 #4
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))));
     }
 }
コード例 #5
0
 function modify(&$tpl, &$operatorName, &$operatorParameters, &$rootNamespace, &$currentNamespace, &$operatorValue, &$namedParameters)
 {
     switch ($operatorName) {
         case 'tidy_output':
             eZDebugSetting::writeNotice("extension-eztidy", "Use 'tidy_output' template operator", "eZTidy::tidyCleaner()");
             $tidy = eZTidy::instance('OutputFilter');
             $operatorValue = $tidy->tidyCleaner($operatorValue);
             break;
     }
 }
コード例 #6
0
    function execute( $process, $event )
    {
        $parameters = $process->attribute( 'parameter_list' );
        $object = eZContentObject::fetch( $parameters['object_id'] );

        if ( !$object )
        {
            eZDebugSetting::writeError( 'kernel-workflow-waituntildate','The object with ID '.$parameters['object_id'].' does not exist.', 'eZApproveType::execute() object is unavailable' );
            return eZWorkflowType::STATUS_WORKFLOW_CANCELLED;
        }

        $version = $object->version( $parameters['version'] );
        $objectAttributes = $version->attribute( 'contentobject_attributes' );
        $waitUntilDateObject = $this->workflowEventContent( $event );
        $waitUntilDateEntryList = $waitUntilDateObject->attribute( 'classattribute_id_list' );
        $modifyPublishDate = $event->attribute( 'data_int1' );

        foreach ( array_keys( $objectAttributes ) as $key )
        {
            $objectAttribute = $objectAttributes[$key];
            $contentClassAttributeID = $objectAttribute->attribute( 'contentclassattribute_id' );
            if ( in_array( $objectAttribute->attribute( 'contentclassattribute_id' ), $waitUntilDateEntryList ) )
            {
                $dateTime = $objectAttribute->attribute( 'content' );
                if ( $dateTime instanceof eZDateTime or
                     $dateTime instanceof eZTime or
                     $dateTime instanceof eZDate )
                {
                    if ( time() < $dateTime->timeStamp() )
                    {
                        $this->setInformation( "Event delayed until " . $dateTime->toString( true ) );
                        $this->setActivationDate( $dateTime->timeStamp() );
                        return eZWorkflowType::STATUS_DEFERRED_TO_CRON_REPEAT;
                    }
                    else if ( $dateTime->isValid() and $modifyPublishDate )
                    {
                        $object->setAttribute( 'published', $dateTime->timeStamp() );
                        $object->store();
                    }
                    else
                    {
                        return eZWorkflowType::STATUS_ACCEPTED;
//                        return eZWorkflowType::STATUS_WORKFLOW_DONE;
                    }
                }
                else
                {
                    return eZWorkflowType::STATUS_ACCEPTED;
//                   return eZWorkflowType::STATUS_WORKFLOW_DONE;
                }
            }
        }
        return eZWorkflowType::STATUS_ACCEPTED;
//        return eZWorkflowType::STATUS_WORKFLOW_DONE;
    }
コード例 #7
0
 function initializeEvent($event, $params)
 {
     eZDebugSetting::writeDebug('kernel-notification', $params, 'params for type');
     $time = 0;
     if (array_key_exists('time', $params)) {
         $time = $params['time'];
     } else {
         $time = time();
     }
     $event->setAttribute('data_int1', $time);
 }
コード例 #8
0
 /**
  * Writes audit information and redirects the user to the password change form.
  *
  * @param eZUser $user
  */
 protected static function passwordHasExpired($user)
 {
     $userID = $user->attribute('contentobject_id');
     // Password expired
     eZDebugSetting::writeDebug('kernel-user', $user, 'user password expired');
     // Failed login attempts should be logged
     $userIDAudit = isset($userID) ? $userID : 'null';
     $loginEscaped = eZDB::instance()->escapeString($user->attribute('login'));
     eZAudit::writeAudit('user-failed-login', array('User id' => $userIDAudit, 'User login' => $loginEscaped, 'Comment' => 'Failed login attempt: Password Expired. eZPaExUser::loginUser()'));
     // Redirect user to password change form
     self::redirectToChangePasswordForm($userID);
 }
コード例 #9
0
 function doSeek($offset, $whence)
 {
     if ($whence == SEEK_SET) {
         $offset = $offset - gztell($this->File);
     } else {
         if ($whence == SEEK_END) {
             eZDebugSetting::writeError('lib-ezfile-gziplibz', "Seeking from end is not supported for gzipped files");
             return false;
         }
     }
     return @gzseek($this->File, $offset);
 }
 /**
  * Execute sending process in Email
  * @see extension/ezcomments/classes/ezcomNotificationManager#executeSending($subject, $body, $subscriber)
  */
 public function executeSending($subject, $body, $subscriber)
 {
     $email = $subscriber->attribute('email');
     $parameters = array();
     $parameters['content_type'] = $this->emailContentType;
     $parameters['from'] = $this->emailFrom;
     $transport = eZNotificationTransport::instance('ezmail');
     $result = $transport->send(array($email), $subject, $body, null, $parameters);
     if ($result === false) {
         throw new Exception('Send email error! Subscriber id:' . $subscriber->attribute('id'));
     }
     eZDebugSetting::writeNotice('extension-ezcomments', "An email has been sent to '{$email}' (subject: {$subject})", __METHOD__);
 }
コード例 #11
0
 static function cachedTree($key, $uri, $res, $templatePath, &$extraParameters)
 {
     $templateCache =& eZTemplateTreeCache::cacheTable();
     $key = eZTemplateTreeCache::internalKey($key);
     $root = null;
     if (isset($templateCache[$key])) {
         $root =& $templateCache[$key]['root'];
         eZDebugSetting::writeDebug('eztemplate-tree-cache', "Cache hit for uri '{$uri}' with key '{$key}'", 'eZTemplateTreeCache::cachedTree');
     } else {
         eZDebugSetting::writeDebug('eztemplate-tree-cache', "Cache miss for uri '{$uri}' with key '{$key}'", 'eZTemplateTreeCache::cachedTree');
     }
     return $root;
 }
コード例 #12
0
 function handle($event)
 {
     eZDebugSetting::writeDebug('kernel-notification', $event, "trying to handle event");
     if ($event->attribute('event_type_string') == 'ezcollaboration') {
         $parameters = array();
         $status = $this->handleCollaborationEvent($event, $parameters);
         if ($status == eZNotificationEventHandler::EVENT_HANDLED) {
             $this->sendMessage($event, $parameters);
         } else {
             return false;
         }
     }
     return true;
 }
コード例 #13
0
 static function create($notificationEventTypeString)
 {
     $types =& $GLOBALS["eZNotificationEventTypes"];
     if (!isset($types[$notificationEventTypeString])) {
         eZDebugSetting::writeDebug('kernel-notification', $types, 'notification types');
         eZNotificationEventType::loadAndRegisterType($notificationEventTypeString);
         eZDebugSetting::writeDebug('kernel-notification', $types, 'notification types 2');
     }
     $def = null;
     if (isset($types[$notificationEventTypeString])) {
         $className = $types[$notificationEventTypeString];
         $def =& $GLOBALS["eZNotificationEventTypeObjects"][$notificationEventTypeString];
         if (!is_object($def) || strtolower(get_class($def)) != $className) {
             $def = new $className();
         }
     }
     return $def;
 }
コード例 #14
0
 static function setDateForItem($item, $settings)
 {
     if (!is_array($settings)) {
         return false;
     }
     $dayNum = isset($settings['day']) ? $settings['day'] : false;
     $hour = $settings['hour'];
     $currentDate = getdate();
     $hoursDiff = $hour - $currentDate['hours'];
     switch ($settings['frequency']) {
         case 'day':
             if ($hoursDiff <= 0) {
                 $hoursDiff += 24;
             }
             $secondsDiff = 3600 * $hoursDiff - $currentDate['seconds'] - 60 * $currentDate['minutes'];
             break;
         case 'week':
             $daysDiff = $dayNum - $currentDate['wday'];
             if ($daysDiff < 0 or $daysDiff == 0 and $hoursDiff <= 0) {
                 $daysDiff += 7;
             }
             $secondsDiff = 3600 * ($daysDiff * 24 + $hoursDiff) - $currentDate['seconds'] - 60 * $currentDate['minutes'];
             break;
         case 'month':
             // If the daynum the user has chosen is larger than the number of days in this month,
             // then reduce it to the number of days in this month.
             $daysInMonth = intval(date('t', mktime(0, 0, 0, $currentDate['mon'], 1, $currentDate['year'])));
             if ($dayNum > $daysInMonth) {
                 $dayNum = $daysInMonth;
             }
             $daysDiff = $dayNum - $currentDate['mday'];
             if ($daysDiff < 0 or $daysDiff == 0 and $hoursDiff <= 0) {
                 $daysDiff += $daysInMonth;
             }
             $secondsDiff = 3600 * ($daysDiff * 24 + $hoursDiff) - $currentDate['seconds'] - 60 * $currentDate['minutes'];
             break;
     }
     $sendDate = time() + $secondsDiff;
     eZDebugSetting::writeDebug('kernel-notification', getdate($sendDate), "item date");
     $item->setAttribute('send_date', $sendDate);
     return $sendDate;
 }
コード例 #15
0
 /**
  * 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');
 }
コード例 #16
0
ファイル: ezsearch.php プロジェクト: nottavi/ezpublish
    static function getEngine()
    {
        // Get instance if already created.
        $instanceName = "eZSearchPlugin_" . $GLOBALS["eZCurrentAccess"]["name"];
        if ( isset( $GLOBALS[$instanceName] ) )
        {
            return $GLOBALS[$instanceName];
        }

        $ini = eZINI::instance();

        $searchEngineString = 'ezsearch';
        if ( $ini->hasVariable( 'SearchSettings', 'SearchEngine' ) == true )
        {
            $searchEngineString = $ini->variable( 'SearchSettings', 'SearchEngine' );
        }

        $directoryList = array();
        if ( $ini->hasVariable( 'SearchSettings', 'ExtensionDirectories' ) )
        {
            $extensionDirectories = $ini->variable( 'SearchSettings', 'ExtensionDirectories' );
            if ( is_array( $extensionDirectories ) )
            {
                $directoryList = eZExtension::expandedPathList( $extensionDirectories, 'search/plugins' );
            }
        }

        $kernelDir = array( 'kernel/search/plugins' );
        $directoryList = array_merge( $kernelDir, $directoryList );

        foreach( $directoryList as $directory )
        {
            $searchEngineFile = implode( '/', array( $directory, strtolower( $searchEngineString ), strtolower( $searchEngineString ) ) ) . '.php';

            if ( file_exists( $searchEngineFile ) )
            {
                eZDebugSetting::writeDebug( 'kernel-search-ezsearch', 'Loading search engine from ' . $searchEngineFile, 'eZSearch::getEngine' );

                include_once( $searchEngineFile );
                $GLOBALS[$instanceName] = new $searchEngineString();
                return $GLOBALS[$instanceName];
            }
        }

        eZDebug::writeDebug( 'Unable to find the search engine:' . $searchEngineString, 'eZSearch' );
        eZDebug::writeDebug( 'Tried paths: ' . implode( ', ', $directoryList ), 'eZSearch' );
        return false;
    }
コード例 #17
0
 /**
  * Sends the published object/version for publishing to the queue
  * Used by the content/publish operation
  * @param int $objectId
  * @param int $version
  *
  * @return array( status => int )
  * @since 4.5
  */
 public static function sendToPublishingQueue($objectId, $version)
 {
     $behaviour = ezpContentPublishingBehaviour::getBehaviour();
     if ($behaviour->disableAsynchronousPublishing) {
         $asyncEnabled = false;
     } else {
         $asyncEnabled = eZINI::instance('content.ini')->variable('PublishingSettings', 'AsynchronousPublishing') == 'enabled';
     }
     $accepted = true;
     if ($asyncEnabled === true) {
         // Filter handlers
         $ini = eZINI::instance('content.ini');
         $filterHandlerClasses = $ini->variable('PublishingSettings', 'AsynchronousPublishingFilters');
         if (count($filterHandlerClasses)) {
             $versionObject = eZContentObjectVersion::fetchVersion($version, $objectId);
             foreach ($filterHandlerClasses as $filterHandlerClass) {
                 if (!class_exists($filterHandlerClass)) {
                     eZDebug::writeError("Unknown asynchronous publishing filter handler class '{$filterHandlerClass}'", __METHOD__);
                     continue;
                 }
                 $handler = new $filterHandlerClass($versionObject);
                 if (!$handler instanceof ezpAsynchronousPublishingFilterInterface) {
                     eZDebug::writeError("Asynchronous publishing filter handler class '{$filterHandlerClass}' does not implement ezpAsynchronousPublishingFilterInterface", __METHOD__);
                     continue;
                 }
                 $accepted = $handler->accept();
                 if (!$accepted) {
                     eZDebugSetting::writeDebug("Object #{$objectId}/{$version} was excluded from asynchronous publishing by {$filterHandlerClass}", __METHOD__);
                     break;
                 }
             }
         }
         unset($filterHandlerClasses, $handler);
     }
     if ($asyncEnabled && $accepted) {
         // if the object is already in the process queue, we move ahead
         // this test should NOT be necessary since http://issues.ez.no/17840 was fixed
         if (ezpContentPublishingQueue::isQueued($objectId, $version)) {
             return array('status' => eZModuleOperationInfo::STATUS_CONTINUE);
         } else {
             ezpContentPublishingQueue::add($objectId, $version);
             return array('status' => eZModuleOperationInfo::STATUS_HALTED, 'redirect_url' => "content/queued/{$objectId}/{$version}");
         }
     } else {
         return array('status' => eZModuleOperationInfo::STATUS_CONTINUE);
     }
 }
コード例 #18
0
 static function createHash($user, $password, $site, $type, $hash = false)
 {
     $user = self::trimAuthString($user);
     $password = self::trimAuthString($password);
     $str = '';
     if ($type == self::PASSWORD_HASH_MD5_USER) {
         $str = md5("{$user}\n{$password}");
     } else {
         if ($type == self::PASSWORD_HASH_MD5_SITE) {
             $str = md5("{$user}\n{$password}\n{$site}");
         } else {
             if ($type == self::PASSWORD_HASH_MYSQL) {
                 $db = eZDB::instance();
                 $hash = $db->escapeString($password);
                 $str = $db->arrayQuery("SELECT PASSWORD( '{$hash}' )");
                 $hashes = array_values($str[0]);
                 $str = $hashes[0];
             } else {
                 if ($type == self::PASSWORD_HASH_PLAINTEXT) {
                     $str = $password;
                 } else {
                     $str = md5($password);
                 }
             }
         }
     }
     eZDebugSetting::writeDebug('kernel-user', $str, "ezuser({$type})");
     return $str;
 }
コード例 #19
0
 static function hasCompiledTemplate($key, $timestamp, &$resourceData)
 {
     if (!eZTemplateCompiler::isCompilationEnabled()) {
         return false;
     }
     if (eZTemplateCompiler::alwaysGenerate()) {
         return false;
     }
     $cacheFileName = eZTemplateCompiler::compilationFilename($key, $resourceData);
     $php = new eZPHPCreator(eZTemplateCompiler::compilationDirectory(), $cacheFileName, eZTemplateCompiler::TemplatePrefix());
     $canRestore = $php->canRestore($timestamp);
     $uri = false;
     if ($canRestore) {
         eZDebugSetting::writeDebug('eztemplate-compile', "Cache hit for uri '{$uri}' with key '{$key}'", 'eZTemplateCompiler::hasCompiledTemplate');
     } else {
         eZDebugSetting::writeDebug('eztemplate-compile', "Cache miss for uri '{$uri}' with key '{$key}'", 'eZTemplateCompiler::hasCompiledTemplate');
     }
     return $canRestore;
 }
コード例 #20
0
 /**
  * Same code as parent, with one extra eZPerfLogger::accumulatorStart/Stop call
  */
 function processCache($retrieveCallback, $generateCallback = null, $ttl = null, $expiry = null, $extraData = null)
 {
     $forceDB = false;
     $curtime = time();
     $tries = 0;
     $noCache = false;
     if ($expiry < 0) {
         $expiry = null;
     }
     if ($ttl < 0) {
         $ttl = null;
     }
     // Main loop
     while (true) {
         // Start read checks
         // Note: The while loop is used to make it easier to break out of the "read" code
         while (true) {
             // No retrieve method so go directly to generate+store
             if ($retrieveCallback === null || !$this->filePath) {
                 break;
             }
             if (!self::LOCAL_CACHE) {
                 $forceDB = true;
             } else {
                 if ($this->isLocalFileExpired($expiry, $curtime, $ttl)) {
                     // if we are in stale cache mode, we only forceDB if the
                     // file does not exist at all
                     if ($this->useStaleCache) {
                         if (!file_exists($this->filePath)) {
                             eZDebugSetting::writeDebug('kernel-clustering', "Local file '{$this->filePath}' does not exist and can not be used for stale cache. Checking with DB", __METHOD__);
                             $forceDB = true;
                             // forceDB + useStaleCache means that we should check for the DB file.
                         }
                     } else {
                         // Local file is older than global timestamp, check with DB
                         eZDebugSetting::writeDebug('kernel-clustering', "Local file (mtime=" . @filemtime($this->filePath) . ") is older than timestamp ({$expiry}) and ttl({$ttl}), check with DB", __METHOD__);
                         $forceDB = true;
                     }
                 }
             }
             if (!$forceDB) {
                 // check if DB file is deleted
                 if (!$this->useStaleCache && ($this->metaData === false || $this->metaData['mtime'] < 0)) {
                     if ($generateCallback !== false) {
                         eZDebugSetting::writeDebug('kernel-clustering', "Database file is deleted, need to regenerate data", __METHOD__);
                     } else {
                         eZDebugSetting::writeDebug('kernel-clustering', "Database file is deleted, cannot get data", __METHOD__);
                     }
                     break;
                 }
                 // check if FS file is older than DB file
                 if (!$this->useStaleCache && $this->isLocalFileExpired($this->metaData['mtime'], $curtime, $ttl)) {
                     eZDebugSetting::writeDebug('kernel-clustering', "Local file (mtime=" . @filemtime($this->filePath) . ") is older than DB, checking with DB", __METHOD__);
                     $forceDB = true;
                 } else {
                     if ($this->useStaleCache) {
                         // to get the retrieve callback to accept the cache file,
                         // we force its mtime to the current time
                         $mtime = $curtime;
                         eZDebugSetting::writeDebug('kernel-clustering', "Processing local stale cache file {$this->filePath}", __METHOD__);
                     } else {
                         $mtime = filemtime($this->filePath);
                         eZDebugSetting::writeDebug('kernel-clustering', "Processing local cache file {$this->filePath}", __METHOD__);
                     }
                     $args = array($this->filePath, $mtime);
                     if ($extraData !== null) {
                         $args[] = $extraData;
                     }
                     $retval = call_user_func_array($retrieveCallback, $args);
                     if ($retval instanceof eZClusterFileFailure) {
                         break;
                     }
                     return $retval;
                 }
             }
             if ($forceDB) {
                 // stale cache, and no DB or FS file available
                 if ($this->useStaleCache && $this->metaData === false) {
                     // configuration says we have to generate our own version
                     if ($this->nonExistantStaleCacheHandling[$this->cacheType] == 'generate') {
                         // no cache available, but a generate callback exists, skip to generation
                         if ($generateCallback !== false) {
                             eZDebugSetting::writeDebug('kernel-clustering', "Database file is deleted, need to regenerate data");
                             break;
                         } else {
                             eZDebugSetting::writeDebug('kernel-clustering', "Database file is deleted, cannot get data");
                             break 2;
                         }
                     } else {
                         eZPerfLogger::accumulatorStart('mysql_cluster_cache_waits', 'MySQL Cluster', 'Cache waits');
                         while ($this->remainingCacheGenerationTime-- >= 0) {
                             // we don't know if the file gets generated on the current
                             // frontend or not. However, we can still try the FS cache
                             // first, then the DB cache if FS is not found, since this
                             // will be much more efficient
                             if (!file_exists($this->filePath)) {
                                 $this->loadMetaData(true);
                                 if ($this->metaData === false) {
                                     sleep(1);
                                     continue;
                                 } else {
                                     break;
                                 }
                             } else {
                                 break;
                             }
                         }
                         eZPerfLogger::accumulatorStop('mysql_cluster_cache_waits');
                         // if we reached this point, it means that we are over the estimated timeout value
                         // we try to take the generation over by starting the cache generation. IF this
                         // fails again, it is probably because another waiting process has taken the generation
                         // over. Maybe add a counter here to prevent some kind of death loop ?
                         eZDebugSetting::writeDebug('kernel-clustering', "Checking if {$this->filePath} was generating during the wait loop", __METHOD__);
                         $this->loadMetaData(true);
                         $this->useStaleCache = false;
                         $this->remainingCacheGenerationTime = false;
                         $forceDB = false;
                         // this continues to the main loop 'while (true)'
                         continue 2;
                     }
                 } elseif (!$this->useStaleCache && ($this->metaData === false || $this->isDBFileExpired($expiry, $curtime, $ttl))) {
                     // no cache available, but a generate callback exists, skip to generation
                     if ($generateCallback !== false) {
                         eZDebugSetting::writeDebug('kernel-clustering', "Database file is deleted, need to regenerate data", __METHOD__);
                         // we break out of one loop so that the generateCallback is called
                         break;
                     } else {
                         eZDebugSetting::writeDebug('kernel-clustering', "Database file is deleted, cannot get data", __METHOD__);
                         // we break out of two loops so that we directly exit the method and have
                         // the rest of execution generate the data
                         break 2;
                     }
                 } else {
                     eZDebugSetting::writeDebug('kernel-clustering', "Callback from DB file {$this->filePath}", __METHOD__);
                     if (self::LOCAL_CACHE) {
                         $this->fetch();
                         // Figure out which mtime to use for new file, must be larger than
                         // mtime in DB at least.
                         $mtime = $this->metaData['mtime'] + 1;
                         $localmtime = @filemtime($this->filePath);
                         $mtime = max($mtime, $localmtime);
                         touch($this->filePath, $mtime, $mtime);
                         clearstatcache();
                         // Needed because of touch() call
                         $args = array($this->filePath, $mtime);
                         if ($extraData !== null) {
                             $args[] = $extraData;
                         }
                         $retval = call_user_func_array($retrieveCallback, $args);
                         if ($retval instanceof eZClusterFileFailure) {
                             break;
                         }
                         return $retval;
                     } else {
                         $uniquePath = $this->fetchUnique();
                         $args = array($uniquePath, $this->metaData['mtime']);
                         if ($extraData !== null) {
                             $args[] = $extraData;
                         }
                         $retval = call_user_func_array($retrieveCallback, $args);
                         $this->fileDeleteLocal($uniquePath);
                         if ($retval instanceof eZClusterFileFailure) {
                             break;
                         }
                         return $retval;
                     }
                 }
                 eZDebugSetting::writeDebug('kernel-clustering', "Database file does not exist, need to regenerate data", __METHOD__);
                 break;
             }
         }
         if ($tries >= 2) {
             eZDebugSetting::writeDebug('kernel-clustering', "Reading was retried {$tries} times and reached the maximum, returning null", __METHOD__);
             return null;
         }
         // Generation part starts here
         if (isset($retval) && $retval instanceof eZClusterFileFailure) {
             // This error means that the retrieve callback told
             // us NOT to enter generation mode and therefore NOT to store this
             // cache.
             // This parameter will then be passed to the generate callback,
             // and this will set store to false
             if ($retval->errno() == 3) {
                 $noCache = true;
             } elseif ($retval->errno() != 1) {
                 eZDebug::writeError("Failed to retrieve data from callback", __METHOD__);
                 return null;
             }
             $message = $retval->message();
             if (strlen($message) > 0) {
                 eZDebugSetting::writeDebug('kernel-clustering', $retval->message(), __METHOD__);
             }
             // the retrieved data was expired so we need to generate it, let's continue
         }
         // We need to lock if we have a generate-callback or
         // the generation is deferred to the caller.
         // Note: false means no generation, while null means that generation
         // is deferred to the processing that follows (f.i. cache-blocks)
         if ($generateCallback !== false && $this->filePath) {
             if (!$this->useStaleCache && !$noCache) {
                 $res = $this->startCacheGeneration();
                 if ($res !== true) {
                     eZDebugSetting::writeDebug('kernel-clustering', "{$this->filePath} is being generated, switching to staleCache mode", __METHOD__);
                     $this->useStaleCache = true;
                     $this->remainingCacheGenerationTime = $res;
                     $forceDB = false;
                     continue;
                 }
             }
             // File in DB is outdated or non-existing, call write-callback to generate content
             if ($generateCallback) {
                 $args = array($this->filePath);
                 if ($noCache) {
                     $extraData['noCache'] = $noCache;
                 }
                 if ($extraData !== null) {
                     $args[] = $extraData;
                 }
                 $fileData = call_user_func_array($generateCallback, $args);
                 return $this->storeCache($fileData);
             }
         }
         break;
     }
     // End main loop
     return new eZClusterFileFailure(2, "Manual generation of file data is required, calling storeCache is required");
 }
コード例 #21
0
 /**
  * Create policy limitation query.
  *
  * @param array $limitation Override the limitation of the user. Same format as the return of eZUser::hasAccessTo()
  * @param boolean $ignoreVisibility Set to true for the visibility to be ignored
  * @return string Lucene/Solr query string which can be used as filter query for Solr
  */
 protected function policyLimitationFilterQuery($limitation = null, $ignoreVisibility = null)
 {
     $eZFindIni = eZINI::instance('ezfind.ini');
     $filterQuery = false;
     $policies = array();
     $pathFieldName = $ignoreVisibility ? eZSolr::getMetaFieldName('path') : eZSolr::getMetaFieldName('visible_path');
     if (is_array($limitation)) {
         if (empty($limitation)) {
             $limitation['accessWord'] = 'yes';
         }
     } else {
         $limitation = eZUser::currentUser()->hasAccessTo('content', 'read');
     }
     if (isset($limitation['accessWord'])) {
         switch ($limitation['accessWord']) {
             case 'limited':
                 if (isset($limitation['policies'])) {
                     $policies = $limitation['policies'];
                     break;
                 }
                 // break omitted, "limited" without policies == "no"
             // break omitted, "limited" without policies == "no"
             case 'no':
                 return ' NOT *:* ';
             case 'yes':
                 break;
             default:
                 return false;
         }
     }
     // Add limitations for filter query based on local permissions.
     $limitationHash = array('Class' => eZSolr::getMetaFieldName('contentclass_id'), 'Section' => eZSolr::getMetaFieldName('section_id'), 'User_Section' => eZSolr::getMetaFieldName('section_id'), 'Subtree' => eZSolr::getMetaFieldName('path_string'), 'User_Subtree' => eZSolr::getMetaFieldName('path_string'), 'Node' => eZSolr::getMetaFieldName('main_node_id'), 'Owner' => eZSolr::getMetaFieldName('owner_id'), 'Group' => eZSolr::getMetaFieldName('owner_group_id'), 'ObjectStates' => eZSolr::getMetaFieldName('object_states'));
     $filterQueryPolicies = array();
     // policies are concatenated with OR
     foreach ($policies as $limitationList) {
         // policy limitations are concatenated with AND
         // except for locations policity limitations, concatenated with OR
         $filterQueryPolicyLimitations = array();
         $policyLimitationsOnLocations = array();
         foreach ($limitationList as $limitationType => $limitationValues) {
             // limitation values of one type in a policy are concatenated with OR
             $filterQueryPolicyLimitationParts = array();
             switch ($limitationType) {
                 case 'User_Subtree':
                 case 'Subtree':
                     foreach ($limitationValues as $limitationValue) {
                         $pathString = trim($limitationValue, '/');
                         $pathArray = explode('/', $pathString);
                         // we only take the last node ID in the path identification string
                         $subtreeNodeID = array_pop($pathArray);
                         $policyLimitationsOnLocations[] = $pathFieldName . ':' . $subtreeNodeID;
                         if (isset($this->searchPluginInstance->postSearchProcessingData['subtree_limitations'])) {
                             $this->searchPluginInstance->postSearchProcessingData['subtree_limitations'][] = $subtreeNodeID;
                         } else {
                             $this->searchPluginInstance->postSearchProcessingData['subtree_limitations'] = array($subtreeNodeID);
                         }
                     }
                     break;
                 case 'Node':
                     foreach ($limitationValues as $limitationValue) {
                         $pathString = trim($limitationValue, '/');
                         $pathArray = explode('/', $pathString);
                         // we only take the last node ID in the path identification string
                         $nodeID = array_pop($pathArray);
                         $policyLimitationsOnLocations[] = $limitationHash[$limitationType] . ':' . $nodeID;
                         if (isset($this->searchPluginInstance->postSearchProcessingData['subtree_limitations'])) {
                             $this->searchPluginInstance->postSearchProcessingData['subtree_limitations'][] = $nodeID;
                         } else {
                             $this->searchPluginInstance->postSearchProcessingData['subtree_limitations'] = array($nodeID);
                         }
                     }
                     break;
                 case 'Group':
                     foreach (eZUser::currentUser()->attribute('contentobject')->attribute('parent_nodes') as $groupID) {
                         $filterQueryPolicyLimitationParts[] = $limitationHash[$limitationType] . ':' . $groupID;
                     }
                     break;
                 case 'Owner':
                     $filterQueryPolicyLimitationParts[] = $limitationHash[$limitationType] . ':' . eZUser::currentUser()->attribute('contentobject_id');
                     break;
                 case 'Class':
                 case 'Section':
                 case 'User_Section':
                     foreach ($limitationValues as $limitationValue) {
                         $filterQueryPolicyLimitationParts[] = $limitationHash[$limitationType] . ':' . $limitationValue;
                     }
                     break;
                 default:
                     //hacky, object state limitations reference the state group name in their
                     //limitation
                     //hence the following match on substring
                     if (strpos($limitationType, 'StateGroup') !== false) {
                         foreach ($limitationValues as $limitationValue) {
                             $filterQueryPolicyLimitationParts[] = $limitationHash['ObjectStates'] . ':' . $limitationValue;
                         }
                     } else {
                         eZDebug::writeDebug($limitationType, __METHOD__ . ' unknown limitation type: ' . $limitationType);
                         continue;
                     }
             }
             if (!empty($filterQueryPolicyLimitationParts)) {
                 $filterQueryPolicyLimitations[] = '( ' . implode(' OR ', $filterQueryPolicyLimitationParts) . ' )';
             }
         }
         // Policy limitations on locations (node and/or subtree) need to be concatenated with OR
         // unlike the other types of limitation
         if (!empty($policyLimitationsOnLocations)) {
             $filterQueryPolicyLimitations[] = '( ' . implode(' OR ', $policyLimitationsOnLocations) . ')';
         }
         if (!empty($filterQueryPolicyLimitations)) {
             $filterQueryPolicies[] = '( ' . implode(' AND ', $filterQueryPolicyLimitations) . ')';
         }
     }
     if (!empty($filterQueryPolicies)) {
         $filterQuery = implode(' OR ', $filterQueryPolicies);
     }
     // Add limitations for allowing search of other installations.
     $anonymousPart = '';
     if ($eZFindIni->variable('SiteSettings', 'SearchOtherInstallations') == 'enabled') {
         $anonymousPart = ' OR ' . eZSolr::getMetaFieldName('anon_access') . ':true ';
     }
     if (!empty($filterQuery)) {
         $filterQuery = '((' . eZSolr::getMetaFieldName('installation_id') . ':' . eZSolr::installationID() . ' AND (' . $filterQuery . ')) ' . $anonymousPart . ' )';
     } else {
         $filterQuery = '(' . eZSolr::getMetaFieldName('installation_id') . ':' . eZSolr::installationID() . $anonymousPart . ')';
     }
     // Add ignore visibility condition, either explicitely set to boolean false or not specified
     if ($ignoreVisibility === false || $ignoreVisibility === null) {
         $filterQuery .= ' AND ' . eZSolr::getMetaFieldName('is_invisible') . ':false';
     }
     eZDebugSetting::writeDebug('extension-ezfind-query', $filterQuery, __METHOD__);
     return $filterQuery;
 }
コード例 #22
0
 /**
  * Add comment into ezcomment table and do action
  * The adding doesn't validate the data in http
  * @param $comment: ezcomComment object which has not been stored
  *        title, name, url, email, created, modified, text, notification
  * @param $user: user object
  * @param $time: comment time
  * @return  true : if adding succeeds
  *          false otherwise
  *
  */
 public function addComment($comment, $user, $time = null, $notification = null)
 {
     if ($time === null) {
         $time = time();
     }
     $beforeAddingResult = $this->beforeAddingComment($comment, $user, $notification);
     if ($beforeAddingResult !== true) {
         return $beforeAddingResult;
     }
     $comment->store();
     eZDebugSetting::writeNotice('extension-ezcomments', 'Comment has been added', __METHOD__);
     $this->afterAddingComment($comment, $notification);
     return true;
 }
コード例 #23
0
    function &inputParagraphXML( &$paragraph,
                                  $currentSectionLevel,
                                  $tdSectionLevel = null,
                                  $noRender = false )
    {
        $output = '';
        $children = $paragraph->childNodes;
        if ( $noRender )
        {
            foreach ( $children as $child )
            {
                $output .= $this->inputTagXML( $child, $currentSectionLevel, $tdSectionLevel );
            }
            return $output;
        }

        $paragraphClassName = $paragraph->getAttribute( 'class' );
        $paragraphAlign = $paragraph->getAttribute( 'align' );
        $customAttributePart = self::getCustomAttrPart( $paragraph, $styleString );

        if ( $paragraphAlign )
        {
            $customAttributePart .= ' align="' . $paragraphAlign . '"';
        }

        if ( $paragraphClassName )
        {
            $customAttributePart .= ' class="' . $paragraphClassName . '"';
        }

        $openPara = "<p$customAttributePart$styleString>";
        $closePara = '</p>';

        if ( $children->length == 0 )
        {
            $output = $openPara . $closePara;
            return $output;
        }

        $lastChildInline = null;
        $innerContent = '';
        foreach ( $children as $child )
        {
            $childOutput = $this->inputTagXML( $child, $currentSectionLevel, $tdSectionLevel );

            // Some tags in xhtml aren't allowed as child of paragraph
            $inline = !( $child->nodeName === 'ul'
                      || $child->nodeName === 'ol'
                      || $child->nodeName === 'literal'
                      || ( $child->nodeName === 'custom'
                        && !self::customTagIsInline( $child->getAttribute( 'name' ) ) )
                      || ( $child->nodeName === 'embed'
                        && !self::embedTagIsCompatibilityMode()
                        && !self::embedTagIsImageByNode( $child ) )
                      );
            if ( $inline )
            {
                $innerContent .= $childOutput;
            }


            if ( ( !$inline && $lastChildInline ) ||
                 ( $inline && !$child->nextSibling ) )
            {
                $output .= $openPara . $innerContent . $closePara;
                $innerContent = '';
            }

            if ( !$inline )
            {
                $output .= $childOutput;
            }

            $lastChildInline = $inline;
        }

        eZDebugSetting::writeDebug( 'kernel-datatype-ezxmltext', $output, __METHOD__ . ' output' );
        return $output;
    }
コード例 #24
0
ファイル: ezpostgresqldb.php プロジェクト: legende91/ez
 function eZPostgreSQLDB($parameters)
 {
     $this->eZDBInterface($parameters);
     if (!extension_loaded('pgsql')) {
         if (function_exists('eZAppendWarningItem')) {
             eZAppendWarningItem(array('error' => array('type' => 'ezdb', 'number' => eZDBInterface::ERROR_MISSING_EXTENSION), 'text' => 'PostgreSQL extension was not found, the DB handler will not be initialized.'));
             $this->IsConnected = false;
         }
         eZDebug::writeWarning('PostgreSQL extension was not found, the DB handler will not be initialized.', 'eZPostgreSQLDB');
         return;
     }
     eZDebug::createAccumulatorGroup('postgresql_total', 'Postgresql Total');
     $ini = eZINI::instance();
     $server = $this->Server;
     $port = $this->Port;
     $db = $this->DB;
     $user = $this->User;
     $password = $this->Password;
     $connectString = self::connectString($this->Server, $this->Port, $this->DB, $this->User, $this->Password);
     if ($ini->variable("DatabaseSettings", "UsePersistentConnection") == "enabled" && function_exists("pg_pconnect")) {
         eZDebugSetting::writeDebug('kernel-db-postgresql', $ini->variable("DatabaseSettings", "UsePersistentConnection"), "using persistent connection");
         // avoid automatic SQL errors
         $oldHandling = eZDebug::setHandleType(eZDebug::HANDLE_EXCEPTION);
         eZDebug::accumulatorStart('postgresql_connection', 'postgresql_total', 'Database connection');
         try {
             $this->DBConnection = pg_pconnect($connectString);
         } catch (ErrorException $e) {
         }
         eZDebug::accumulatorStop('postgresql_connection');
         eZDebug::setHandleType($oldHandling);
         $maxAttempts = $this->connectRetryCount();
         $waitTime = $this->connectRetryWaitTime();
         $numAttempts = 1;
         while ($this->DBConnection == false and $numAttempts <= $maxAttempts) {
             sleep($waitTime);
             $oldHandling = eZDebug::setHandleType(eZDebug::HANDLE_EXCEPTION);
             eZDebug::accumulatorStart('postgresql_connection', 'postgresql_total', 'Database connection');
             try {
                 $this->DBConnection = pg_pconnect($connectString);
             } catch (ErrorException $e) {
             }
             eZDebug::accumulatorStop('postgresql_connection');
             eZDebug::setHandleType($oldHandling);
             $numAttempts++;
         }
         if ($this->DBConnection) {
             $this->IsConnected = true;
         } else {
             throw new eZDBNoConnectionException($server, $this->ErrorMessage, $this->ErrorNumber);
         }
     } else {
         if (function_exists("pg_connect")) {
             eZDebugSetting::writeDebug('kernel-db-postgresql', "using real connection", "using real connection");
             $oldHandling = eZDebug::setHandleType(eZDebug::HANDLE_EXCEPTION);
             eZDebug::accumulatorStart('postgresql_connection', 'postgresql_total', 'Database connection');
             try {
                 $this->DBConnection = pg_connect($connectString);
             } catch (ErrorException $e) {
             }
             eZDebug::accumulatorStop('postgresql_connection');
             eZDebug::setHandleType($oldHandling);
             $maxAttempts = $this->connectRetryCount();
             $waitTime = $this->connectRetryWaitTime();
             $numAttempts = 1;
             while ($this->DBConnection == false and $numAttempts <= $maxAttempts) {
                 sleep($waitTime);
                 $oldHandling = eZDebug::setHandleType(eZDebug::HANDLE_EXCEPTION);
                 eZDebug::accumulatorStart('postgresql_connection', 'postgresql_total', 'Database connection');
                 try {
                     $this->DBConnection = pg_connect($connectString);
                 } catch (ErrorException $e) {
                 }
                 eZDebug::accumulatorStop('postgresql_connection');
                 eZDebug::setHandleType($oldHandling);
                 $numAttempts++;
             }
             if ($this->DBConnection) {
                 $this->IsConnected = true;
             } else {
                 $this->setError();
                 throw new eZDBNoConnectionException($server, $this->ErrorMessage, $this->ErrorNumber);
             }
         } else {
             $this->IsConnected = false;
             eZDebug::writeError("PostgreSQL support not compiled into PHP, contact your system administrator", "eZPostgreSQLDB");
         }
     }
 }
コード例 #25
0
 static function fetchListTool($parameters = array(), $asCount)
 {
     $parameters = array_merge(array('as_object' => true, 'offset' => false, 'parent_group_id' => false, 'limit' => false, 'is_active' => null, 'is_read' => null, 'status' => false, 'sort_by' => false), $parameters);
     $asObject = $parameters['as_object'];
     $offset = $parameters['offset'];
     $limit = $parameters['limit'];
     $statusTypes = $parameters['status'];
     $isRead = $parameters['is_read'];
     $isActive = $parameters['is_active'];
     $parentGroupID = $parameters['parent_group_id'];
     $sortText = '';
     if (!$asCount) {
         $sortCount = 0;
         $sortList = $parameters['sort_by'];
         if (is_array($sortList) and count($sortList) > 0) {
             if (count($sortList) > 1 and !is_array($sortList[0])) {
                 $sortList = array($sortList);
             }
         }
         if ($sortList !== false) {
             $sortingFields = '';
             foreach ($sortList as $sortBy) {
                 if (is_array($sortBy) and count($sortBy) > 0) {
                     if ($sortCount > 0) {
                         $sortingFields .= ', ';
                     }
                     $sortField = $sortBy[0];
                     switch ($sortField) {
                         case 'created':
                             $sortingFields .= 'ezcollab_item_group_link.created';
                             break;
                         case 'modified':
                             $sortingFields .= 'ezcollab_item_group_link.modified';
                             break;
                         default:
                             eZDebug::writeWarning('Unknown sort field: ' . $sortField, __METHOD__);
                             continue;
                     }
                     $sortOrder = true;
                     // true is ascending
                     if (isset($sortBy[1])) {
                         $sortOrder = $sortBy[1];
                     }
                     $sortingFields .= $sortOrder ? ' ASC' : ' DESC';
                     ++$sortCount;
                 }
             }
         }
         if ($sortCount == 0) {
             $sortingFields = ' ezcollab_item_group_link.modified DESC';
         }
         $sortText = "ORDER BY {$sortingFields}";
     }
     $parentGroupText = '';
     if ($parentGroupID > 0) {
         $parentGroupText = "ezcollab_item_group_link.group_id = '{$parentGroupID}' AND";
     }
     $isReadText = '';
     if ($isRead !== null) {
         $isReadValue = $isRead ? 1 : 0;
         $isReadText = "ezcollab_item_status.is_read = '{$isReadValue}' AND";
     }
     $isActiveText = '';
     if ($isActive !== null) {
         $isActiveValue = $isActive ? 1 : 0;
         $isActiveText = "ezcollab_item_status.is_active = '{$isActiveValue}' AND";
     }
     $userID = eZUser::currentUserID();
     $statusText = '';
     if ($statusTypes === false) {
         $statusTypes = array(self::STATUS_ACTIVE, self::STATUS_INACTIVE);
     }
     $statusText = implode(', ', $statusTypes);
     if ($asCount) {
         $selectText = 'count( ezcollab_item.id ) as count';
     } else {
         $selectText = 'ezcollab_item.*, ezcollab_item_status.is_read, ezcollab_item_status.is_active, ezcollab_item_status.last_read';
     }
     $sql = "SELECT {$selectText}\n                FROM\n                       ezcollab_item,\n                       ezcollab_item_status,\n                       ezcollab_item_group_link\n                WHERE  ezcollab_item.status IN ( {$statusText} ) AND\n                       {$isReadText}\n                       {$isActiveText}\n                       ezcollab_item.id = ezcollab_item_status.collaboration_id AND\n                       ezcollab_item.id = ezcollab_item_group_link.collaboration_id AND\n                       {$parentGroupText}\n                       ezcollab_item_status.user_id = '{$userID}' AND\n                       ezcollab_item_group_link.user_id = '{$userID}'\n                {$sortText}";
     $db = eZDB::instance();
     if (!$asCount) {
         $sqlParameters = array();
         if ($offset !== false and $limit !== false) {
             $sqlParameters['offset'] = $offset;
             $sqlParameters['limit'] = $limit;
         }
         $itemListArray = $db->arrayQuery($sql, $sqlParameters);
         foreach ($itemListArray as $key => $value) {
             $itemData =& $itemListArray[$key];
             $statusObject = eZCollaborationItemStatus::create($itemData['id'], $userID);
             $statusObject->setAttribute('is_read', $itemData['is_read']);
             $statusObject->setAttribute('is_active', $itemData['is_active']);
             $statusObject->setAttribute('last_read', $itemData['last_read']);
             $statusObject->updateCache();
         }
         $returnItemList = eZPersistentObject::handleRows($itemListArray, 'eZCollaborationItem', $asObject);
         eZDebugSetting::writeDebug('collaboration-item-list', $returnItemList);
         return $returnItemList;
     } else {
         $itemCount = $db->arrayQuery($sql);
         return $itemCount[0]['count'];
     }
 }
コード例 #26
0
 /**
  * Logs $errMsg.
  *
  * @param string $errMsg Error message to be logged
  * @param string $context Context where the error occurred
  * @return void
  */
 public function logError($errMsg, $context = null)
 {
     eZDebugSetting::writeError('kernel-clustering', $errMsg, $context);
 }
コード例 #27
0
    /**
     * Changes the site access to what's defined in $access. It will change the
     * access path in eZSys and prepend an override dir to eZINI
     * Note: does not load extensions, use {@link eZSiteAccess::load()} if you want that
     *
     * @since 4.4
     * @param array $access An associative array with 'name' (string), 'type' (int) and 'uri_part' (array).
     *                      See {@link eZSiteAccess::match()} for array structure definition
     * @param eZINI|null $siteINI Optional parameter to be able to only do change on specific instance of site.ini
     *                   hence skip changing eZSys access paths (but not siteaccess, see {@link eZSiteAccess::load()})
     * @return array The $access parameter
     */
    static function change( array $access, eZINI $siteINI = null )
    {
        $name = $access['name'];
        $GLOBALS['eZCurrentAccess'] =& $access;
        if ( $siteINI !== null )
        {
            $ini = $siteINI;
        }
        else
        {
            $ini = eZINI::instance();
        }

        $ini->prependOverrideDir( "siteaccess/$name", false, 'siteaccess', 'siteaccess' );

        /* Make sure extension siteaccesses are prepended */
        eZExtension::prependExtensionSiteAccesses( $name, $ini );

        $ini->loadCache();

        // change some global settings if $siteINI is null
        if ( $siteINI === null )
        {
            eZSys::clearAccessPath();
            if ( !isset( $access['uri_part'] ) || $access['uri_part'] === null )
            {
                if ( $ini->hasVariable('SiteSettings', 'SiteUriParts') )
                    $access['uri_part'] = $ini->variable('SiteSettings', 'SiteUriParts');
                else if ( isset( $access['type'] ) && $access['type'] === eZSiteAccess::TYPE_URI )
                    $access['uri_part'] = array( $access['name'] );
                else
                    $access['uri_part'] = array();
            }
            eZSys::setAccessPath( $access['uri_part'], $name );

            eZUpdateDebugSettings();
            eZDebugSetting::writeDebug( 'kernel-siteaccess', "Updated settings to use siteaccess '$name'", __METHOD__ );
        }

        return $access;
    }
コード例 #28
0
 /**
  *  Send the notification after registeration
  */
 public static function sendUserNotification($userID)
 {
     eZDebugSetting::writeNotice('Sending approval notification to the user.', 'kernel-user', 'user register');
     $user = eZUser::fetch($userID);
     $ini = eZINI::instance();
     // Send mail
     $tpl = eZTemplate::factory();
     $tpl->setVariable('user', $user);
     $templateResult = $tpl->fetch('design:user/registrationapproved.tpl');
     $mail = new eZMail();
     if ($tpl->hasVariable('content_type')) {
         $mail->setContentType($tpl->variable('content_type'));
     }
     $emailSender = $ini->variable('MailSettings', 'EmailSender');
     if ($tpl->hasVariable('email_sender')) {
         $emailSender = $tpl->variable('email_sender');
     } else {
         if (!$emailSender) {
             $emailSender = $ini->variable('MailSettings', 'AdminEmail');
         }
     }
     if ($tpl->hasVariable('subject')) {
         $subject = $tpl->variable('subject');
     } else {
         $subject = ezpI18n::tr('kernel/user/register', 'User registration approved');
     }
     $mail->setSender($emailSender);
     $receiver = $user->attribute('email');
     $mail->setReceiver($receiver);
     $mail->setSubject($subject);
     $mail->setBody($templateResult);
     $mailResult = eZMailTransport::send($mail);
     return array('status' => eZModuleOperationInfo::STATUS_CONTINUE);
 }
コード例 #29
0
 function checkApproveCollaboration( $process, $event )
 {
     $db = eZDb::instance();
     $taskResult = $db->arrayQuery( 'select workflow_process_id, collaboration_id from ezapprove_items where workflow_process_id = ' . $process->attribute( 'id' )  );
     $collaborationID = $taskResult[0]['collaboration_id'];
     $collaborationItem = eZCollaborationItem::fetch( $collaborationID );
     $contentObjectVersion = eZApproveCollaborationHandler::contentObjectVersion( $collaborationItem );
     $approvalStatus = eZApproveCollaborationHandler::checkApproval( $collaborationID );
     if ( $approvalStatus == eZApproveCollaborationHandler::STATUS_WAITING )
     {
         eZDebugSetting::writeDebug( 'kernel-workflow-approve', $event, 'approval still waiting' );
         return eZWorkflowType::STATUS_DEFERRED_TO_CRON_REPEAT;
     }
     else if ( $approvalStatus == eZApproveCollaborationHandler::STATUS_ACCEPTED )
     {
         eZDebugSetting::writeDebug( 'kernel-workflow-approve', $event, 'approval was accepted' );
         $status = eZWorkflowType::STATUS_ACCEPTED;
     }
     else if ( $approvalStatus == eZApproveCollaborationHandler::STATUS_DENIED or
               $approvalStatus == eZApproveCollaborationHandler::STATUS_DEFERRED )
     {
         eZDebugSetting::writeDebug( 'kernel-workflow-approve', $event, 'approval was denied' );
         $contentObjectVersion->setAttribute( 'status', eZContentObjectVersion::STATUS_DRAFT );
         $status = eZWorkflowType::STATUS_WORKFLOW_CANCELLED;
     }
     else
     {
         eZDebugSetting::writeDebug( 'kernel-workflow-approve', $event, "approval unknown status '$approvalStatus'" );
         $contentObjectVersion->setAttribute( 'status', eZContentObjectVersion::STATUS_REJECTED );
         $status = eZWorkflowType::STATUS_WORKFLOW_CANCELLED;
     }
     $contentObjectVersion->sync();
     if ( $approvalStatus != eZApproveCollaborationHandler::STATUS_DEFERRED )
         $db->query( 'DELETE FROM ezapprove_items WHERE workflow_process_id = ' . $process->attribute( 'id' )  );
     return $status;
 }
コード例 #30
0
 static function canInstantiateClassList($asObject = false, $includeFilter = true, $groupList = false, $fetchID = false)
 {
     $ini = eZINI::instance();
     $groupArray = array();
     $enableCaching = $ini->variable('RoleSettings', 'EnableCaching') == 'true';
     if (is_array($groupList)) {
         if ($fetchID == false) {
             $enableCaching = false;
         }
     }
     if ($enableCaching) {
         $http = eZHTTPTool::instance();
         eZExpiryHandler::registerShutdownFunction();
         $handler = eZExpiryHandler::instance();
         $expiredTimeStamp = 0;
         if ($handler->hasTimestamp('user-class-cache')) {
             $expiredTimeStamp = $handler->timestamp('user-class-cache');
         }
         $classesCachedForUser = $http->sessionVariable('ClassesCachedForUser');
         $classesCachedTimestamp = $http->sessionVariable('ClassesCachedTimestamp');
         $cacheVar = 'CanInstantiateClassList';
         if (is_array($groupList) and $fetchID !== false) {
             $cacheVar = 'CanInstantiateClassListGroup';
         }
         $user = eZUser::currentUser();
         $userID = $user->id();
         if ($classesCachedTimestamp >= $expiredTimeStamp && $classesCachedForUser == $userID) {
             if ($http->hasSessionVariable($cacheVar)) {
                 if ($fetchID !== false) {
                     // Check if the group contains our ID, if not we need to fetch from DB
                     $groupArray = $http->sessionVariable($cacheVar);
                     if (isset($groupArray[$fetchID])) {
                         return $groupArray[$fetchID];
                     }
                 } else {
                     return $http->sessionVariable($cacheVar);
                 }
             }
         } else {
             $http->setSessionVariable('ClassesCachedForUser', $userID);
             $http->setSessionVariable('ClassesCachedTimestamp', time());
         }
     }
     $languageCodeList = eZContentLanguage::fetchLocaleList();
     $allowedLanguages = array('*' => array());
     $user = eZUser::currentUser();
     $accessResult = $user->hasAccessTo('content', 'create');
     $accessWord = $accessResult['accessWord'];
     $classIDArray = array();
     $classList = array();
     $fetchAll = false;
     if ($accessWord == 'yes') {
         $fetchAll = true;
         $allowedLanguages['*'] = $languageCodeList;
     } else {
         if ($accessWord == 'no') {
             // Cannot create any objects, return empty list.
             return $classList;
         } else {
             $policies = $accessResult['policies'];
             foreach ($policies as $policyKey => $policy) {
                 $classIDArrayPart = '*';
                 if (isset($policy['Class'])) {
                     $classIDArrayPart = $policy['Class'];
                 }
                 $languageCodeArrayPart = $languageCodeList;
                 if (isset($policy['Language'])) {
                     $languageCodeArrayPart = array_intersect($policy['Language'], $languageCodeList);
                 }
                 // No class limitation for this policy AND no previous limitation(s)
                 if ($classIDArrayPart == '*' && empty($classIDArray)) {
                     $fetchAll = true;
                     $allowedLanguages['*'] = array_unique(array_merge($allowedLanguages['*'], $languageCodeArrayPart));
                 } else {
                     if (is_array($classIDArrayPart)) {
                         $fetchAll = false;
                         foreach ($classIDArrayPart as $class) {
                             if (isset($allowedLanguages[$class])) {
                                 $allowedLanguages[$class] = array_unique(array_merge($allowedLanguages[$class], $languageCodeArrayPart));
                             } else {
                                 $allowedLanguages[$class] = $languageCodeArrayPart;
                             }
                         }
                         $classIDArray = array_merge($classIDArray, array_diff($classIDArrayPart, $classIDArray));
                     }
                 }
             }
         }
     }
     $db = eZDB::instance();
     $filterTableSQL = '';
     $filterSQL = '';
     // Create extra SQL statements for the class group filters.
     if (is_array($groupList)) {
         if (count($groupList) == 0) {
             return $classList;
         }
         $filterTableSQL = ', ezcontentclass_classgroup ccg';
         $filterSQL = " AND" . "      cc.id = ccg.contentclass_id AND" . "      ";
         $filterSQL .= $db->generateSQLINStatement($groupList, 'ccg.group_id', !$includeFilter, true, 'int');
     }
     $classNameFilter = eZContentClassName::sqlFilter('cc');
     $filterSQL .= " AND      cc.id=" . $classNameFilter['from'] . ".contentclass_id";
     if ($fetchAll) {
         // If $asObject is true we fetch all fields in class
         $fields = $asObject ? "cc.*, {$classNameFilter['nameField']}" : "cc.id, {$classNameFilter['nameField']}";
         $rows = $db->arrayQuery("SELECT DISTINCT {$fields} " . "FROM ezcontentclass cc{$filterTableSQL}, {$classNameFilter['from']} " . "WHERE cc.version = " . eZContentClass::VERSION_STATUS_DEFINED . " {$filterSQL} " . "ORDER BY {$classNameFilter['nameField']} ASC");
         $classList = eZPersistentObject::handleRows($rows, 'eZContentClass', $asObject);
     } else {
         // If the constrained class list is empty we are not allowed to create any class
         if (count($classIDArray) == 0) {
             return $classList;
         }
         $classIDCondition = $db->generateSQLINStatement($classIDArray, 'cc.id');
         // If $asObject is true we fetch all fields in class
         $fields = $asObject ? "cc.*, {$classNameFilter['nameField']}" : "cc.id, {$classNameFilter['nameField']}";
         $rows = $db->arrayQuery("SELECT DISTINCT {$fields} " . "FROM ezcontentclass cc{$filterTableSQL}, {$classNameFilter['from']} " . "WHERE {$classIDCondition} AND" . "      cc.version = " . eZContentClass::VERSION_STATUS_DEFINED . " {$filterSQL} " . "ORDER BY {$classNameFilter['nameField']} ASC");
         $classList = eZPersistentObject::handleRows($rows, 'eZContentClass', $asObject);
     }
     if ($asObject) {
         foreach ($classList as $key => $class) {
             $id = $class->attribute('id');
             if (isset($allowedLanguages[$id])) {
                 $languageCodes = array_unique(array_merge($allowedLanguages['*'], $allowedLanguages[$id]));
             } else {
                 $languageCodes = $allowedLanguages['*'];
             }
             $classList[$key]->setCanInstantiateLanguages($languageCodes);
         }
     }
     eZDebugSetting::writeDebug('kernel-content-class', $classList, "class list fetched from db");
     if ($enableCaching) {
         if ($fetchID !== false) {
             $groupArray[$fetchID] = $classList;
             $http->setSessionVariable($cacheVar, $groupArray);
         } else {
             $http->setSessionVariable($cacheVar, $classList);
         }
     }
     return $classList;
 }