static function remove($objectID, $removeSubtrees = true)
 {
     eZContentCacheManager::clearContentCacheIfNeeded($objectID);
     $object = eZContentObject::fetch($objectID);
     if (!is_object($object)) {
         return false;
     }
     // TODO: Is content cache cleared for all objects in subtree ??
     if ($removeSubtrees) {
         $assignedNodes = $object->attribute('assigned_nodes');
         if (count($assignedNodes) == 0) {
             $object->purge();
             eZContentObject::expireAllViewCache();
             return true;
         }
         $assignedNodeIDArray = array();
         foreach ($assignedNodes as $node) {
             $assignedNodeIDArray[] = $node->attribute('node_id');
         }
         eZContentObjectTreeNode::removeSubtrees($assignedNodeIDArray, false);
     } else {
         $object->purge();
     }
     return true;
 }
예제 #2
0
function sectionEditActionCheck($module, $class, $object, $version, $contentObjectAttributes, $editVersion, $editLanguage, $fromLanguage)
{
    if (!$module->isCurrentAction('SectionEdit')) {
        return;
    }
    $http = eZHTTPTool::instance();
    if (!$http->hasPostVariable('SelectedSectionId')) {
        return;
    }
    $selectedSection = eZSection::fetch((int) $http->postVariable('SelectedSectionId'));
    if (!$selectedSection instanceof eZSection) {
        return;
    }
    $selectedSection->applyTo($object);
    eZContentCacheManager::clearContentCacheIfNeeded($object->attribute('id'));
    $module->redirectToView('edit', array($object->attribute('id'), $editVersion, $editLanguage, $fromLanguage));
}
예제 #3
0
파일: index.php 프로젝트: truffo/eep
 private function clearSubtreeCache($nodeId)
 {
     $node = eZContentObjectTreeNode::fetch($nodeId);
     $limit = 50;
     $offset = 0;
     $params = array('AsObject' => false, 'Depth' => false, 'Limitation' => array());
     // Empty array means no permission checking
     $subtreeCount = $node->subTreeCount($params);
     while ($offset < $subtreeCount) {
         $params['Offset'] = $offset;
         $params['Limit'] = $limit;
         $subtree = $node->subTree($params);
         $offset += count($subtree);
         if (count($subtree) == 0) {
             break;
         }
         $objectIDList = array();
         foreach ($subtree as $subtreeNode) {
             $objectIDList[] = $subtreeNode['contentobject_id'];
         }
         $objectIDList = array_unique($objectIDList);
         unset($subtree);
         foreach ($objectIDList as $objectID) {
             eZContentCacheManager::clearContentCacheIfNeeded($objectID);
         }
     }
 }
예제 #4
0
 static function setFailedLoginAttempts($userID, $value = false, $setByForce = false)
 {
     $trustedUser = eZUser::isTrusted();
     // If user is trusted we should stop processing
     if ($trustedUser and !$setByForce) {
         return true;
     }
     $maxNumberOfFailedLogin = eZUser::maxNumberOfFailedLogin();
     if ($maxNumberOfFailedLogin == '0' and !$setByForce) {
         return true;
     }
     $userID = (int) $userID;
     $userObject = eZUser::fetch($userID);
     if (!$userObject) {
         return true;
     }
     $isEnabled = $userObject->isEnabled();
     // If current user is disabled we should not continue
     if (!$isEnabled and !$setByForce) {
         return true;
     }
     $db = eZDB::instance();
     $db->begin();
     $userVisitArray = $db->arrayQuery("SELECT 1 FROM ezuservisit WHERE user_id={$userID}");
     if (isset($userVisitArray[0])) {
         if ($value === false) {
             $failedLoginAttempts = $userObject->failedLoginAttempts();
             $failedLoginAttempts += 1;
         } else {
             $failedLoginAttempts = (int) $value;
         }
         $db->query("UPDATE ezuservisit SET failed_login_attempts={$failedLoginAttempts} WHERE user_id={$userID}");
     } else {
         if ($value === false) {
             $failedLoginAttempts = 1;
         } else {
             $failedLoginAttempts = (int) $value;
         }
         $db->query("INSERT INTO ezuservisit ( failed_login_attempts, user_id ) VALUES ( {$failedLoginAttempts}, {$userID} )");
     }
     $db->commit();
     eZContentCacheManager::clearContentCacheIfNeeded($userID);
     eZContentCacheManager::generateObjectViewCache($userID);
 }
예제 #5
0
        // Sort objectDepthList by depth to apply updatechildren in the right order
        if (!array_multisort($objectDepthList[0], SORT_ASC, $objectDepthList[1], SORT_ASC)) {
            eZDebug::writeError('Error in array_multisort', 'ezmbpaex_updatechildren.php');
        } else {
            // Generate array of paex objects to update
            $paexObjectArray = array();
            foreach ($objectDepthList[1] as $contentobjectId) {
                if (isset($pendingList[$contentobjectId])) {
                    // Generate update children data for every pending object in pendingIDList
                    $paexObjectArray = $pendingList[$contentobjectId]->generateUpdateChildren($paexObjectArray);
                } else {
                    eZDebug::writeError('Found contentobject_id [' . $contentobjectId . '] not present in the pendingIDList', 'ezmbpaex_updatechildren.php');
                }
            }
            // Reset pending object updatechildren attribute in pendingIDList objects and add to the array of paex objects to update
            foreach ($pendingList as $pendingObject) {
                $pendingObject->setAttribute('updatechildren', 0);
                $paexObjectArray[$pendingObject->attribute('contentobject_id')] = $pendingObject;
            }
            // Store updated paex objects in the DB
            $db = eZDB::instance();
            $db->begin();
            foreach ($paexObjectArray as $paexObject) {
                $paexObject->store();
                eZContentCacheManager::clearContentCacheIfNeeded($paexObject->attribute('contentobject_id'));
            }
            $db->commit();
        }
    }
    $cli->output("eZPaEx: Update children process end");
}
    /**
     * Rate content object attribute id
     *
     * @param array $args ( 0 => contentobjectattribute_id,  1 => contentobject_version, 2 => rating )
     * @return array
     */
    public static function rate( $args )
    {
        $ret = array( 'id' => 0, 'rated' => false, 'already_rated' => false, 'stats' => false );
        if ( !isset( $args[2] ) )
            throw new LengthException( 'Rating expects 3 arguments: attr_id, version, rating' );
        else if ( !is_numeric( $args[0] ) )
            throw new InvalidArgumentException( 'Rating argument[0] attr_id must be a number' );
        else if ( !is_numeric( $args[1] ) )
            throw new InvalidArgumentException( 'Rating argument[1] version must be a number' );
        else if ( !is_numeric( $args[2] ) )
            throw new InvalidArgumentException( 'Rating argument[2] rating must be a number' );
        else if ( $args[2] > 5 || $args[2] < 1 )
            throw new UnexpectedValueException( 'Rating argument[2] rating must be between 1 and 5' );

        $ret['id'] = (int) $args[0];

        // Provide extra session protection on 4.1 (not possible on 4.0) by expecting user
        // to have an existing session (new session = mostlikely a spammer / hacker trying to manipulate rating)
        if (
            eZSession::userHasSessionCookie() !== true
            && eZINI::instance()->variable( 'eZStarRating', 'AllowAnonymousRating' ) === 'disabled'
        )
            return $ret;

        // Return if parameters are not valid attribute id + version numbers
        $contentobjectAttribute = eZContentObjectAttribute::fetch( $ret['id'], $args[1] );
        if ( !$contentobjectAttribute instanceof eZContentObjectAttribute )
            return $ret;

        // Return if attribute is not a rating attribute
        if ( $contentobjectAttribute->attribute('data_type_string') !== ezsrRatingType::DATA_TYPE_STRING )
            return $ret;

        // Return if rating has been disabled on current attribute
        if ( $contentobjectAttribute->attribute('data_int') )
            return $ret;

        // Return if user does not have access to object
        $contentobject = $contentobjectAttribute->attribute('object');
        if ( !$contentobject instanceof eZContentObject || !$contentobject->attribute('can_read') )
            return $ret;

        $rateDataObj = ezsrRatingDataObject::create( array( 'contentobject_id' => $contentobjectAttribute->attribute('contentobject_id'),
                                                    'contentobject_attribute_id' =>  $ret['id'],
                                                    'rating' => $args[2]
        ));

        $proiorRating = $rateDataObj->userHasRated( true );

        if ( $proiorRating === true )
        {
            $ret['already_rated'] = true;
        }
        else if ( $proiorRating instanceof ezsrRatingDataObject )
        {
            $rateDataObj = $proiorRating;
            $rateDataObj->setAttribute( 'rating', $args[2] );
            $ret['already_rated'] = true;
            $proiorRating = false;// just to reuse code bellow
        }

        if ( !$proiorRating )
        {
            $rateDataObj->store();
            $avgRateObj = $rateDataObj->getAverageRating();
            $avgRateObj->updateFromRatingData();
            $avgRateObj->store();
            eZContentCacheManager::clearContentCacheIfNeeded( $rateDataObj->attribute('contentobject_id') );
            $ret['rated'] = true;
            $ret['stats'] = array(
               'rating_count' => $avgRateObj->attribute('rating_count'),
               'rating_average' => $avgRateObj->attribute('rating_average'),
               'rounded_average' => $avgRateObj->attribute('rounded_average'),
            );
        }
        return $ret;
    }
예제 #7
0
파일: add.php 프로젝트: legende91/ez
                if ($existingNotification) {
                    $tpl->setVariable('success_message', ezpI18n::tr('ezcomments/comment/add', 'You have already subscribed to comment updates on this content.'));
                } else {
                    $tpl->setVariable('success_message', ezpI18n::tr('ezcomments/comment/add', 'You will receive comment updates on the content.'));
                }
            } else {
                $tpl->setVariable('success_message', ezpI18n::tr('ezcomments/comment/add', 'A confirmation email has been sent to your email address. You will receive comment updates after confirmation.'));
            }
        }
        //remember cookies
        $cookieManager = ezcomCookieManager::instance();
        if ($http->postVariable('CommentRememberme', false) !== false || !$user->isAnonymous()) {
            $cookieManager->storeCookie($comment);
        } else {
            $cookieManager->clearCookie();
        }
        eZContentCacheManager::clearContentCacheIfNeeded($contentObjectId);
        if (!$changeNotification) {
            $commentINI = eZINI::instance('ezcomments.ini');
            if ($commentINI->variable('GlobalSettings', 'RedirectAfterCommenting') === 'true') {
                $module->redirectTo($redirectURI);
            }
        } else {
            $tpl->setVariable('redirect_uri', $redirectURI);
        }
    }
} else {
    $tpl->setVariable('error_message', ezpI18n::tr('ezcomments/comment/add', 'You should not access this view directly.'));
}
$Result['content'] = $tpl->fetch('design:comment/add.tpl');
return $Result;
 /**
  * Create a ezsrRatingDataObject and store it.
  * Note: No access checks or input validation is done other then on rating
  *
  * @param int $contentobjectId
  * @param int $contentobjectAttributeId
  * @param int $rate (above 0 and  bellow or equal 5)
  * @param bool $onlyStoreIfUserNotAlreadyRated
  * @return null|ezsrRatingDataObject
  */
 static function rate($contentobjectId, $contentobjectAttributeId, $rate)
 {
     $rating = null;
     if (is_numeric($contentobjectId) && is_numeric($contentobjectAttributeId) && is_numeric($rate) && $rate <= 5 && $rate > 0) {
         $row = array('contentobject_attribute_id' => $contentobjectAttributeId, 'contentobject_id' => $contentobjectId, 'rating' => $rate);
         $rating = self::create($row);
         if (!$rating->userHasRated()) {
             $rating->store();
             $avgRating = $rating->getAverageRating();
             $avgRating->updateFromRatingData();
             $avgRating->store();
             // clear the cache for all nodes associated with this object
             eZContentCacheManager::clearContentCacheIfNeeded($contentobjectId, true, false);
         }
     }
     return $rating;
 }
예제 #9
0
파일: index.php 프로젝트: truffo/eep
 private function clearObjectCache($objectId)
 {
     // todo: the first one is suspect:
     //eZContentObject::clearCache( array( $objectId ) );
     // ... so, todo: does this work any better?
     eZContentCacheManager::clearContentCacheIfNeeded($objectId);
 }
예제 #10
0
 /**
  * Attempt to remove content object 'image' attribute image variations by content object attribute
  *
  * @param object $contentClassImageAttribute object of objects of class eZContentObjectAttribute
  * @param array $class Array of object class identifiers to remove aliases for only these classes. Optional. Defaults to false
  * @param array $attributes Array of object image attribute identifiers to remove aliases from. Optional. Defaults to false
  * @param array $aliases Array of object image attribute image aliases to remove. Optional. Defaults to false
  *
  * @return bool true if successful, false otherwise
  * @static
  */
 static function removeByAttribute($contentObjectAttribute = false, $classes = false, $attributes = false, $aliases = false)
 {
     if (!is_object($contentObjectAttribute)) {
         return false;
     }
     // Test that content object class attribute identifier matches provided classes
     if ($classes != false && is_array($classes) && !in_array($contentObjectAttribute->attribute('object')->attribute('class_identifier'), $classes)) {
         return false;
     }
     // Test that content object class attribute identifier matches provided classes
     if ($attributes != false && is_array($attributes) && !in_array($contentObjectAttribute->attribute('contentclass_attribute_identifier'), $attributes)) {
         return false;
     }
     // Default datatypes to create image alias variations
     $imageDataTypeStrings = eZINI::instance('bcimagealias.ini')->variable('BCImageAliasSettings', 'ImageDataTypeStringList');
     // Check that content object attribute data type string matches allowed datatype settings
     if (!in_array($contentObjectAttribute->attribute('data_type_string'), $imageDataTypeStrings) || !$contentObjectAttribute->attribute('has_content')) {
         return false;
     }
     $filePaths = array();
     $results = array();
     $executionOptions = self::executionOptions();
     $messageCount = 0;
     $imageHandler = $contentObjectAttribute->attribute('content');
     $aliasList = $imageHandler->aliasList(false);
     // Do not process the orginal image alias
     unset($aliasList['original']);
     if (count($aliasList) == 0) {
         return false;
     }
     // Optional debug output
     if ($executionOptions['troubleshoot'] && $executionOptions['verboseLevel'] >= 2) {
         if ($executionOptions['verboseLevel'] >= 3) {
             self::displayMessage('All attribute image aliases stored in content data text field:', false);
             self::displayMessage($contentObjectAttribute->attribute('data_text'), "\n");
         }
         if ($executionOptions['verboseLevel'] >= 4) {
             self::displayMessage('All attribute image aliases stored in content alias list:', false);
             print_r($aliasList);
             self::displayMessage('', "\n\n");
         } elseif ($executionOptions['verboseLevel'] >= 3) {
             self::displayMessage('All attribute image aliases stored in content alias list:', false);
             print_r(array_keys($aliasList));
             self::displayMessage('', "\n");
         }
     }
     $contentObjectID = $contentObjectAttribute->attribute('contentobject_id');
     $contentObjectAttributeID = $contentObjectAttribute->attribute('id');
     $contentObjectAttributeVersion = $contentObjectAttribute->attribute('version');
     if ($contentObjectAttributeVersion === null) {
         $files = eZImageFile::fetchForContentObjectAttribute($contentObjectAttributeID, true);
         $dirs = array();
         $count = 0;
         // Iterate over files
         foreach ($files as $filepath) {
             // Test $filepath from $files is in contains one of the $aliases items
             if ($aliases != false && is_array($aliases)) {
                 foreach ($aliases as $alias) {
                     if (!stristr('_' . $alias, $filepath)) {
                         continue 1;
                     }
                 }
             }
             $file = eZClusterFileHandler::instance($filepath);
             if ($file->exists()) {
                 $filePaths[] = $filepath;
                 if (!$executionOptions['dry']) {
                     $file->fileDelete($filepath);
                     $dirs[] = eZDir::dirpath($filepath);
                 }
                 $count++;
             }
         }
         if (!$executionOptions['dry']) {
             $dirs = array_unique($dirs);
             foreach ($dirs as $dirpath) {
                 eZDir::cleanupEmptyDirectories($dirpath);
             }
             eZImageFile::removeForContentObjectAttribute($contentObjectAttributeID);
             $message = "Removed datatype " . $contentObjectAttribute->attribute('data_type_string') . "type image alias variation " . $filePaths[$messageCount] . "\n";
         } else {
             $message = "Dry run: Remove datatype " . $contentObjectAttribute->attribute('data_type_string') . "type image alias variation " . $filePaths[$messageCount] . "\n";
         }
         while ($messageCount < $count) {
             self::scriptIterate($message);
             $messageCount++;
             $result = true;
         }
     } else {
         // We loop over each image alias, and look up the file in ezcontentobject_attribute
         // Only images referenced by one version will be removed
         foreach ($aliasList as $aliasName => $aliasListAliasItem) {
             // Test $aliasListAliasItem from $aliasList is in $aliases array
             if ($aliases != false && is_array($aliases) && !in_array($aliasListAliasItem['name'], $aliases)) {
                 continue;
             }
             if ($aliasListAliasItem['is_valid'] && $aliasListAliasItem['name'] != 'original') {
                 $filepath = $aliasListAliasItem['url'];
                 // Calculate appropriate message to Alert user with
                 if (!$executionOptions['dry']) {
                     // Remove the alias variation image file from the attribute dom tree
                     $doc = $imageHandler->ContentObjectAttributeData['DataTypeCustom']['dom_tree'];
                     foreach ($doc->getElementsByTagName('alias') as $aliasNode) {
                         if ($aliasListAliasItem['name'] == $aliasNode->getAttribute('name')) {
                             // Optional debug output
                             if ($executionOptions['troubleshoot']) {
                                 self::displayMessage('Removing image alias image variation ' . "'" . $aliasNode->getAttribute('name') . "'" . ' from attribute dom document');
                             }
                             $aliasNode->parentNode->removeChild($aliasNode);
                         }
                     }
                     $imageHandler->ContentObjectAttributeData['DataTypeCustom']['dom_tree'] = $doc;
                     unset($imageHandler->ContentObjectAttributeData['DataTypeCustom']['alias_list']);
                     $imageHandler->storeDOMTree($doc, true, $contentObjectAttribute);
                 }
                 // Calculate appropriate message to Alert user with
                 if ($executionOptions['dry']) {
                     $message = "Dry run: Calculating removal of datatype " . $contentObjectAttribute->attribute('data_type_string') . "type image alias variation file " . $filepath;
                 } else {
                     $message = "Removed standard datatype " . $contentObjectAttribute->attribute('data_type_string') . "type image alias variation file " . $filepath;
                 }
                 if (!$executionOptions['dry']) {
                     $dirpath = $aliasListAliasItem['dirpath'];
                     $file = eZClusterFileHandler::instance($filepath);
                     if ($file->exists()) {
                         $file->purge();
                         eZImageFile::removeFilepath($contentObjectAttributeID, $filepath);
                         eZDir::cleanupEmptyDirectories($dirpath);
                         self::scriptIterate($message);
                         $results[] = true;
                     } else {
                         eZDebug::writeError("Image file {$filepath} for alias {$aliasName} does not exist, could not remove from disk", __METHOD__);
                         self::displayMessage("Image file {$filepath} for alias {$aliasName} does not exist, could not remove from disk: " . __METHOD__);
                     }
                     eZContentCacheManager::clearContentCacheIfNeeded($contentObjectID);
                 } else {
                     self::scriptIterate($message);
                     $results[] = true;
                 }
             }
         }
     }
     // Calculate return results based on execution options and results comparison
     if (in_array(true, $results) && count($aliasList) == count($results) && !$executionOptions['dry']) {
         return true;
     }
     return false;
 }
 /**
  * (non-PHPdoc)
  * @see extension/sqliimport/classes/sourcehandlers/ISQLIImportHandler::process()
  */
 public function process($row)
 {
     // $row is a SimpleXMLElement object
     $this->currentGUID = $row->id;
     $contentOptions = new SQLIContentOptions(array('class_identifier' => 'blog_post', 'remote_id' => (string) $row->id));
     $content = SQLIContent::create($contentOptions);
     $published = (string) $row->published;
     $updated = (string) $row->updated;
     $skipUpdated = false;
     if ($published && $published != '' && $published != 0) {
         $content->setAttribute('published', strtotime($published));
         $content->store();
     } elseif ((!$published || ${$published} == '' || $published == 0) && ($updated && $updated != '' && $updated != 0)) {
         $content->setAttribute('published', strtotime($updated));
         $content->setAttribute('modified', strtotime($updated));
         $content->store();
         $skipUpdated = true;
     }
     if (!$skipUpdated && $updated && $updated != '' && $updated != 0) {
         $content->setAttribute('modified', strtotime($updated));
         $content->store();
     } elseif (!$skipUpdated && (!$updated || ${$updated} == '' || $updated == 0) && ($published && $published != '' && $published != 0)) {
         $content->setAttribute('published', strtotime($published));
         $content->setAttribute('modified', strtotime($published));
         $content->store();
     }
     $defaultParentNodeID = $this->handlerConfArray['DefaultParentNodeID'];
     $title = (string) $row->title;
     $content->fields->title = $title;
     $content->fields->blog_post_author = (string) $row->author->name;
     $content->fields->blog_post_url = (string) $row->link["href"];
     $content->fields->publication_date = strtotime((string) $row->updated);
     // Handle HTML content
     $message = (string) $row->content;
     $content->fields->blog_post_description_text_block = str_replace('href="/', 'href="http://github.com/', $message);
     // Proxy method to SQLIContentUtils::getRichContent()
     $issueTicketID = $this->getIssueFromGitCommitMessage($title, strip_tags($message));
     // echo "\n\n"; print_r($issueTicketID); echo "\n\n";
     $content->fields->tags = $issueTicketID;
     //echo "\n\nCorrupt-ObjectID: "; print_r( $content->attribute( 'id' ) ); echo "\n\n";
     // Now publish content
     $content->addLocation(SQLILocation::fromNodeID($defaultParentNodeID));
     $publisher = SQLIContentPublisher::getInstance();
     $publisher->publish($content);
     // Clear cache
     $defaultParentNodeID = $this->handlerConfArray['DefaultParentNodeID'];
     $parentNode = eZContentObjectTreeNode::fetch($defaultParentNodeID, 'eng-US');
     if ($parentNode != false) {
         $objectID = $parentNode->attribute('object')->attribute('id');
         eZContentCacheManager::clearContentCacheIfNeeded($objectID);
     }
     // Free some memory. Internal methods eZContentObject::clearCache() and eZContentObject::resetDataMap() will be called
     // @see SQLIContent::__destruct()
     unset($content);
 }
예제 #12
0
 * @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
 *
 */
$Module = $Params['Module'];
$http = eZHTTPTool::instance();
if ($http->hasPostVariable('ConfirmButton')) {
    $deleteIDArray = $http->hasSessionVariable('DeleteCommentsIDArray') ? $http->sessionVariable('DeleteCommentsIDArray') : array();
    if (is_array($deleteIDArray) && !empty($deleteIDArray)) {
        $db = eZDB::instance();
        $db->begin();
        $commentManager = ezcomCommentManager::instance();
        foreach ($deleteIDArray as $deleteID) {
            $commentToRemove = ezcomComment::fetch($deleteID);
            $deleteResult = $commentManager->deleteComment($commentToRemove);
            if ($deleteResult === true) {
                eZContentCacheManager::clearContentCacheIfNeeded($commentToRemove->attribute('contentobject_id'));
            }
        }
        $db->commit();
    }
    $Module->redirectTo('/comment/list/');
}
if ($http->hasPostVariable('CancelButton')) {
    $Module->redirectTo('/comment/list/');
}
$contentInfoArray = array();
$tpl = eZTemplate::factory();
$tpl->setVariable('persistent_variable', false);
$Result = array();
$Result['content'] = $tpl->fetch('design:comment/removecomments.tpl');
$Result['path'] = array(array('text' => ezpI18n::tr('ezcomments/comment/removecomments', 'Remove comments'), 'url' => false));
 /**
  * Workflow Event Type execute method
  */
 function execute($process, $event)
 {
     /**
      * Fetch workflow process parameters
      */
     $parameters = $process->attribute('parameter_list');
     $objectID = $parameters['object_id'];
     self::writeDebug('writeNotice', "Start '" . self::WORKFLOW_TYPE_STRING . "' workflow event execute method");
     $ini = eZINI::instance('site.ini');
     $bcUserRegisterUserPlacementINI = eZINI::instance('bcuserregisteruserplacement.ini');
     /**
      * Reading the default user class id as it is required to check that we only
      * perform the workflow event on user class content and not other class of objects
      */
     $defaultUserClassID = $ini->hasVariable('UserSettings', 'UserClassID') == true ? $ini->variable('UserSettings', 'UserClassID') : false;
     /**
      * Reading the default user placement nodeID as it is the default location where new users are stored
      */
     $userGroupID = $ini->hasVariable('UserSettings', 'DefaultUserPlacement') == true ? $ini->variable('UserSettings', 'DefaultUserPlacement') : 0;
     self::writeDebug('writeNotice', "User class id is: " . $defaultUserClassID . ' Default user group is: ' . $userGroupID);
     $userGroups = $bcUserRegisterUserPlacementINI->hasVariable('BCUserRegisterUserPlacement', 'MoveToUserGroupId') == true ? $bcUserRegisterUserPlacementINI->variable('BCUserRegisterUserPlacement', 'MoveToUserGroupId') : array();
     $objectSelectionAttributeIdentifier = $bcUserRegisterUserPlacementINI->hasVariable('BCUserRegisterUserPlacement', 'UserAttributeSelectionIdentifier') == true ? $bcUserRegisterUserPlacementINI->variable('BCUserRegisterUserPlacement', 'UserAttributeSelectionIdentifier') : false;
     $move = $bcUserRegisterUserPlacementINI->hasVariable('BCUserRegisterUserPlacement', 'Move') == true && strtolower($bcUserRegisterUserPlacementINI->variable('BCUserRegisterUserPlacement', 'Move')) == 'enabled' ? true : false;
     $setMainNode = $bcUserRegisterUserPlacementINI->hasVariable('BCUserRegisterUserPlacement', 'SetMainNode') == true && strtolower($bcUserRegisterUserPlacementINI->variable('BCUserRegisterUserPlacement', 'SetMainNode')) == 'enabled' ? true : false;
     $selectedNodeID = false;
     // Fetch content object from the workflow process provided object_id
     $object = eZContentObject::fetch($objectID);
     // Fetch content object attributes required
     $objectName = $object->attribute('name');
     self::writeDebug('writeNotice', "Object name: " . $objectName);
     $objectContentClass = $object->attribute('class_name');
     self::writeDebug('writeNotice', "Content Class is: " . $objectContentClass);
     $objectContentClassID = $object->attribute('contentclass_id');
     self::writeDebug('writeNotice', "Default user class id is: " . $defaultUserClassID . ". This object class id is: " . $objectContentClassID);
     /**
      * Test if content object class ID matches ini settings default user content object class ID
      * Only perform workflow event operations on content objects of the correct content class
      */
     if ($objectContentClassID == $defaultUserClassID) {
         // Fetch content object attributes needed
         $assignedNodes = $object->attribute('assigned_nodes');
         $objectDataMap = $object->attribute('data_map');
         $objectNodeAssignments = eZNodeAssignment::fetchForObject($objectID, $object->attribute('current_version'), 0, false);
         //$objectNodeAssignments = $object->attribute( 'assigned_nodes' );
         // Get the selection content
         $objectSelectionAttributeContent = $objectDataMap[$objectSelectionAttributeIdentifier]->attribute('content');
         $objectSelectionAttributeContentString = implode(',', $objectSelectionAttributeContent);
         self::writeDebug('writeNotice', "User object attribute " . $objectSelectionAttributeIdentifier . " content is set to: " . $objectSelectionAttributeContentString);
         /**
          * Test to ensure that object selection attribute content is greater than 0 (no selection) or
          * that object selection attribute count is less than the count of userGroups (defined in ini settings)
          */
         if ($objectSelectionAttributeContent > 0 || $objectSelectionAttributeContent < count($userGroups)) {
             // Set userGroupID from ini defined user groups based on content object selection attribute content
             $userGroupID = $userGroups[$objectSelectionAttributeContentString];
             $selectedNodeID = $userGroupID;
         }
         $parentNodeIDs = array();
         $ourNode = false;
         /**
          * Iterate over object assigned nodes and object node assignements
          * test for parent node id matches and build array of parent_node_ids
          * test for user content object selection attribute content selected node id
          * and set node to move based on match
          */
         foreach ($assignedNodes as $assignedNode) {
             $append = false;
             foreach ($objectNodeAssignments as $nodeAssignment) {
                 if ($nodeAssignment['parent_node'] == $assignedNode->attribute('parent_node_id')) {
                     $append = true;
                     break;
                 }
             }
             if ($append) {
                 $parentNodeIDs[] = $assignedNode->attribute('parent_node_id');
             }
             if ($assignedNode->attribute('parent_node_id') == $selectedNodeID) {
                 $ourNode = $assignedNode;
             }
         }
         /**
          * Test if we are to move the current main node to the selected location
          */
         if ($move) {
             self::writeDebug('writeDebug', 'Moving tactic');
             if (!is_object($ourNode)) {
                 self::writeDebug('writeDebug', 'Node not found, so moving existing main node...');
                 eZContentObjectTreeNodeOperations::move($object->attribute('main_node_id'), $selectedNodeID);
             }
         } else {
             /**
              * Create a new node location assignment
              */
             self::writeDebug('writeDebug', 'New node tactic');
             if (!is_object($ourNode)) {
                 self::writeDebug('writeDebug', 'Node not found, so creating a new one ...');
                 $parentNode = eZContentObjectTreeNode::fetch($selectedNodeID);
                 $parentNodeObject = $parentNode->attribute('object');
                 // Add user content object location
                 $ourNode = $object->addLocation($selectedNodeID, true);
                 // Now set node as published and fix main_node_id
                 $ourNode->setAttribute('contentobject_is_published', 1);
                 $ourNode->setAttribute('main_node_id', $object->attribute('main_node_id'));
                 $ourNode->setAttribute('contentobject_version', $object->attribute('current_version'));
                 // Make sure the node's path_identification_string is set correctly
                 $ourNode->updateSubTreePath();
                 $ourNode->sync();
                 eZUser::cleanupCache();
             }
             if ($setMainNode) {
                 self::writeDebug('writeDebug', "'Setting as main node is enabled'", "", true);
                 if ($object->attribute('main_node_id') != $ourNode->attribute('node_id')) {
                     self::writeDebug('writeDebug', 'Existing main node is not our node, so updating main node', "", true);
                     eZContentObjectTreeNode::updateMainNodeID($ourNode->attribute('node_id'), $objectID, false, $selectedNodeID);
                     eZContentCacheManager::clearContentCacheIfNeeded($objectID);
                 }
             }
         }
     } else {
         self::writeDebug('writeNotice', $objectName . ' is not a user class object');
     }
     if (self::WORKFLOW_TYPE_DEBUG_STOP_EXECUTION === true) {
         die("<hr />\n\nWorkflow: " . self::WORKFLOW_TYPE_STRING . " execution has been ended before normal completion for debugging");
     }
     /**
      * Return default succesful workflow event status code, by default, regardless of results of execution, always.
      * Image alias image variation image files may not always need to be created. Also returning any other status
      * will result in problems with the succesfull and normal completion of the workflow event process
      */
     return eZWorkflowType::STATUS_ACCEPTED;
 }
예제 #14
0
 /**
  * Clears view cache for imported content objects.
  * ObjectIDs are stored in 'ezpending_actions' table, with {@link SQLIContent::ACTION_CLEAR_CACHE} action
  */
 public static function viewCacheClear()
 {
     $db = eZDB::instance();
     $isCli = isset($_SERVER['argv']);
     $output = null;
     $progressBar = null;
     $i = 0;
     $conds = array('action' => SQLIContent::ACTION_CLEAR_CACHE);
     $limit = array('offset' => 0, 'length' => 50);
     $count = (int) eZPersistentObject::count(eZPendingActions::definition(), $conds);
     if ($isCli && $count > 0) {
         // Progress bar implementation
         $output = new ezcConsoleOutput();
         $output->outputLine('Starting to clear view cache for imported objects...');
         $progressBarOptions = array('emptyChar' => ' ', 'barChar' => '=');
         $progressBar = new ezcConsoleProgressbar($output, $count, $progressBarOptions);
         $progressBar->start();
     }
     /*
      * To avoid fatal errors due to memory exhaustion, pending actions are fetched by packets
      */
     do {
         $aObjectsToClear = eZPendingActions::fetchObjectList(eZPendingActions::definition(), null, $conds, null, $limit);
         $jMax = count($aObjectsToClear);
         if ($jMax > 0) {
             for ($j = 0; $j < $jMax; ++$j) {
                 if ($isCli) {
                     $progressBar->advance();
                 }
                 $db->begin();
                 eZContentCacheManager::clearContentCacheIfNeeded((int) $aObjectsToClear[$j]->attribute('param'));
                 $aObjectsToClear[$j]->remove();
                 $db->commit();
                 $i++;
             }
         }
         unset($aObjectsToClear);
         eZContentObject::clearCache();
         if (eZINI::instance('site.ini')->variable('ContentSettings', 'StaticCache') == 'enabled') {
             $optionArray = array('iniFile' => 'site.ini', 'iniSection' => 'ContentSettings', 'iniVariable' => 'StaticCacheHandler');
             $options = new ezpExtensionOptions($optionArray);
             $staticCacheHandler = eZExtension::getHandlerClass($options);
             $staticCacheHandler::executeActions();
         }
     } while ($i < $count);
     if ($isCli && $count > 0) {
         $progressBar->finish();
         $output->outputLine();
     }
 }
    function execute( $xmlNode )
    {
        $xmlObjectID = $xmlNode->getAttribute( 'contentObject' );
        $xmlParentNodeID = $xmlNode->getAttribute( 'addToNode' );
        $setReferenceID = $xmlNode->getAttribute( 'setReference' );
        $priority = $xmlNode->getAttribute( 'priority' );

        $objectID = $this->getReferenceID( $xmlObjectID );
        $parentNodeID = $this->getReferenceID( $xmlParentNodeID );

        if ( !$objectID )
        {
            $this->writeMessage( "\tNo object defined.", 'error' );
            return false;
        }
        if ( !$parentNodeID )
        {
            $this->writeMessage( "\tNo location defined.", 'error' );
            return false;
        }

        $object = eZContentObject::fetch( $objectID );
        if ( !$object )
        {
            $this->writeMessage( "\tObject not found.", 'error' );
            return false;
        }

        $parentNode =  eZContentObjectTreeNode::fetch( $parentNodeID );
        if ( !$parentNode )
        {
            $this->writeMessage( "\tparent node not found.", 'error' );
            return false;
        }
        $node = $object->attribute( 'main_node' );

        $nodeAssignmentList = eZNodeAssignment::fetchForObject( $objectID, $object->attribute( 'current_version' ), 0, false );
        $assignedNodes = $object->assignedNodes();

        $parentNodeIDArray = array();
        $setMainNode = false;
        $hasMainNode = false;
        foreach ( $assignedNodes as $assignedNode )
        {
            if ( $assignedNode->attribute( 'is_main' ) )
                $hasMainNode = true;
            $append = false;
            foreach ( $nodeAssignmentList as $nodeAssignment )
            {
                if ( $nodeAssignment['parent_node'] == $assignedNode->attribute( 'parent_node_id' ) )
                {
                    $append = true;
                    break;
                }
            }
            if ( $append )
            {
                $parentNodeIDArray[] = $assignedNode->attribute( 'parent_node_id' );
            }
        }
        if ( !$hasMainNode )
            $setMainNode = true;

        $mainNodeID = $parentNode->attribute( 'main_node_id' );
        $objectName = $object->attribute( 'name' );

        $db = eZDB::instance();
        $db->begin();
        $locationAdded = false;
        $destNode = null;
        if ( !in_array( $parentNodeID, $parentNodeIDArray ) )
        {
            $parentNodeObject = $parentNode->attribute( 'object' );

            $insertedNode = $object->addLocation( $parentNodeID, true );

            // Now set is as published and fix main_node_id
            $insertedNode->setAttribute( 'contentobject_is_published', 1 );
            $insertedNode->setAttribute( 'main_node_id', $node->attribute( 'main_node_id' ) );
            $insertedNode->setAttribute( 'contentobject_version', $node->attribute( 'contentobject_version' ) );
            // Make sure the url alias is set updated.
            $insertedNode->updateSubTreePath();
            $insertedNode->sync();

            $locationAdded = true;
        }
        if ( $locationAdded )
        {
            $ini = eZINI::instance();
            $userClassID = $ini->variable( "UserSettings", "UserClassID" );
            if ( $object->attribute( 'contentclass_id' ) == $userClassID )
            {
                eZUser::cleanupCache();
            }
            $this->writeMessage( "\tAdded location of " . $object->attribute( 'name' ) . "  to Node $parentNodeID", 'notice' );

            $destNode = $insertedNode;
        }
        else
        {
            $this->writeMessage( "\tLocation of " . $object->attribute( 'name' ) . "  to Node $parentNodeID already exists.", 'notice' );

            $destNode = eZContentObjectTreeNode::fetchObject( eZContentObjectTreeNode::definition(), null, array( 'parent_node_id' => $parentNodeID, 'contentobject_id' => $objectID ) );
        }
        $db->commit();

        if( $destNode && $priority )
        {
            $destNode->setAttribute( 'priority', $priority );
            $destNode->store();
        }

        if( $destNode && $setReferenceID )
        {
            $this->addReference( array( $setReferenceID => $destNode->attribute( 'node_id' ) ) );
        }

        eZContentCacheManager::clearContentCacheIfNeeded( $objectID );
    }
예제 #16
0
 static function clearContentCacheIfNeededBySectionID($sectionID)
 {
     // fetch all objects of this section
     $objectList = eZContentObject::fetchList(false, array('section_id' => "{$sectionID}"));
     // Clear cache
     foreach ($objectList as $object) {
         eZContentCacheManager::clearContentCacheIfNeeded($object['id']);
     }
     return true;
 }
예제 #17
0
 public function applyTo(eZContentObject $object)
 {
     $sectionID = $this->attribute("id");
     $currentUser = eZUser::currentUser();
     if (!$currentUser->canAssignSectionToObject($sectionID, $object)) {
         eZDebug::writeError("You do not have permissions to assign the section <" . $selectedSection->attribute("name") . "> to the object <" . $object->attribute("name") . ">.");
         return false;
     }
     $db = eZDB::instance();
     $db->begin();
     $assignedNodes = $object->attribute("assigned_nodes");
     if (!empty($assignedNodes)) {
         if (eZOperationHandler::operationIsAvailable("content_updatesection")) {
             foreach ($assignedNodes as $node) {
                 eZOperationHandler::execute("content", "updatesection", array("node_id" => $node->attribute("node_id"), "selected_section_id" => $sectionID), null, true);
             }
         } else {
             foreach ($assignedNodes as $node) {
                 eZContentOperationCollection::updateSection($node->attribute("node_id"), $sectionID);
             }
         }
     } else {
         // If there are no assigned nodes we should update db for the current object.
         $objectID = $object->attribute("id");
         $db->query("UPDATE ezcontentobject SET section_id='{$sectionID}' WHERE id = '{$objectID}'");
         $db->query("UPDATE ezsearch_object_word_link SET section_id='{$sectionID}' WHERE  contentobject_id = '{$objectID}'");
     }
     eZContentCacheManager::clearContentCacheIfNeeded($object->attribute("id"));
     $object->expireAllViewCache();
     $db->commit();
 }
    static function move( $nodeID, $newParentNodeID )
    {
        $result = false;

        if ( !is_numeric( $nodeID ) || !is_numeric( $newParentNodeID ) )
            return false;

        $node = eZContentObjectTreeNode::fetch( $nodeID );
        if ( !$node )
            return false;

        $object = $node->object();
        if ( !$object )
            return false;

        $objectID = $object->attribute( 'id' );
        $oldParentNode = $node->fetchParent();
        $oldParentObject = $oldParentNode->object();

        // clear user policy cache if this is a user object
        if ( in_array( $object->attribute( 'contentclass_id' ), eZUser::contentClassIDs() ) )
        {
            eZUser::purgeUserCacheByUserId( $object->attribute( 'id' ) );
        }

        // clear cache for old placement.
        eZContentCacheManager::clearContentCacheIfNeeded( $objectID );

        $db = eZDB::instance();
        $db->begin();

        $node->move( $newParentNodeID );

        $newNode = eZContentObjectTreeNode::fetchNode( $objectID, $newParentNodeID );

        if ( $newNode )
        {
            $newNode->updateSubTreePath( true, true );
            if ( $newNode->attribute( 'main_node_id' ) == $newNode->attribute( 'node_id' ) )
            {
                // If the main node is moved we need to check if the section ID must change
                $newParentNode = $newNode->fetchParent();
                $newParentObject = $newParentNode->object();
                if ( $object->attribute( 'section_id' ) != $newParentObject->attribute( 'section_id' ) )
                {

                    eZContentObjectTreeNode::assignSectionToSubTree( $newNode->attribute( 'main_node_id' ),
                                                                     $newParentObject->attribute( 'section_id' ),
                                                                     $oldParentObject->attribute( 'section_id' ) );
                }
            }

            // modify assignment
            $curVersion     = $object->attribute( 'current_version' );
            $nodeAssignment = eZNodeAssignment::fetch( $objectID, $curVersion, $oldParentNode->attribute( 'node_id' ) );

            if ( $nodeAssignment )
            {
                $nodeAssignment->setAttribute( 'parent_node', $newParentNodeID );
                $nodeAssignment->setAttribute( 'op_code', eZNodeAssignment::OP_CODE_MOVE );
                $nodeAssignment->store();

                // update search index
                $nodeIDList = array( $nodeID );
                eZSearch::removeNodeAssignment( $node->attribute( 'main_node_id' ), $newNode->attribute( 'main_node_id' ), $object->attribute( 'id' ), $nodeIDList );
                eZSearch::addNodeAssignment( $newNode->attribute( 'main_node_id' ), $object->attribute( 'id' ), $nodeIDList );
            }

            $result = true;
        }
        else
        {
            eZDebug::writeError( "Node $nodeID was moved to $newParentNodeID but fetching the new node failed" );
        }

        $db->commit();

        // clear cache for new placement.
        eZContentCacheManager::clearContentCacheIfNeeded( $objectID );

        return $result;
    }
예제 #19
0
    function swapNodes( $params )
    {
        $nodeInfo1 = $params['src_node'];
        $nodeInfo2 = $params['dst_node'];

        //init vars
        $node1 = $this->nodeIdByName( $nodeInfo1 );
        $node2 = $this->nodeIdByName( $nodeInfo2 );

        $nodeID = $node1;
        $node = eZContentObjectTreeNode::fetch( $nodeID );

        if( !is_object( $node ) )
        {
            $this->reportError( "Can't fetch node '$nodeID'", 'eZSiteInstaller::swapNodes' );
            return false;
        }

        if( !$node->canSwap() )
        {
            $this->reportError( "Cannot swap node '$nodeID' (no edit permission)", 'eZSiteInstaller::swapNodes' );
            return false;
        }

        $nodeParentNodeID = $node->attribute( 'parent_node_id' );

        $object = $node->object();
        if( !is_object( $object ) )
        {
            $this->reportError( "Cannot fetch object for node '$nodeID'", 'eZSiteInstaller::swapNodes' );
            return false;
        }

        $objectID = $object->attribute( 'id' );
        $objectVersion = $object->attribute( 'current_version' );
        $class = $object->contentClass();
        $classID = $class->attribute( 'id' );

        $selectedNodeID = $node2;

        $selectedNode = eZContentObjectTreeNode::fetch( $selectedNodeID );

        if( !is_object( $selectedNode ) )
        {
            $this->reportError( "Cannot fetch node '$selectedNodeID'", 'eZSiteInstaller::swapNodes' );
            return false;
        }

        if( !$selectedNode->canSwap() )
        {
            $this->reportError( "Cannot use node $selectedNodeID as the exchanging node for $nodeID, the current user does not have edit permission for it",
                                'eZSiteInstaller::swapNodes' );
            return false;
        }

        // clear cache.
        eZContentCacheManager::clearContentCacheIfNeeded( $objectID );

        $selectedObject = $selectedNode->object();
        $selectedObjectID = $selectedObject->attribute( 'id' );
        $selectedObjectVersion = $selectedObject->attribute( 'current_version' );
        $selectedNodeParentNodeID = $selectedNode->attribute( 'parent_node_id' );


        /* In order to swap node1 and node2 a user should have the following permissions:
         * 1. move_from: move node1
         * 2. move_from: move node2
         * 3. move_to: move an object of the same class as node2 under parent of node1
         * 4. move_to: move an object of the same class as node1 under parent of node2
         *
         * The First two has already been checked. Let's check the rest.
         */
        $nodeParent            = $node->attribute( 'parent' );
        $selectedNodeParent    = $selectedNode->attribute( 'parent' );
        $objectClassID         = $object->attribute( 'contentclass_id' );
        $selectedObjectClassID = $selectedObject->attribute( 'contentclass_id' );

        if( !$nodeParent || !$selectedNodeParent )
        {
            $this->reportError( "No $nodeParent or no !$selectedNodeParent received.",
                                'eZSiteInstaller::swapNodes' );
            return false;
        }

        if( !$nodeParent->canMoveTo( $selectedObjectClassID ) )
        {
            $this->reportError( "Cannot move an object of class $selectedObjectClassID to node $nodeParentNodeID (no create permission)",
                                'eZSiteInstaller::swapNodes' );
            return false;
        }

        if( !$selectedNodeParent->canMoveTo( $objectClassID ) )
        {
            $this->reportError( "Cannot move an object of class $objectClassID to node $selectedNodeParentNodeID (no create permission)",
                                'eZSiteInstaller::swapNodes' );
            return false;
        }

        // exchange contentobject ids and versions.
        $node->setAttribute( 'contentobject_id', $selectedObjectID );
        $node->setAttribute( 'contentobject_version', $selectedObjectVersion );

        $db = eZDB::instance();
        $db->begin();
        $node->store();
        $selectedNode->setAttribute( 'contentobject_id', $objectID );
        $selectedNode->setAttribute( 'contentobject_version', $objectVersion );
        $selectedNode->store();

        // modify path string
        $changedOriginalNode = eZContentObjectTreeNode::fetch( $nodeID );
        $changedOriginalNode->updateSubTreePath();
        $changedTargetNode = eZContentObjectTreeNode::fetch( $selectedNodeID );
        $changedTargetNode->updateSubTreePath();

        // modify section
        if( $changedOriginalNode->attribute( 'main_node_id' ) == $changedOriginalNode->attribute( 'node_id' ) )
        {
            $changedOriginalObject = $changedOriginalNode->object();
            $parentObject = $nodeParent->object();
            if( $changedOriginalObject->attribute( 'section_id' ) != $parentObject->attribute( 'section_id' ) )
            {

                eZContentObjectTreeNode::assignSectionToSubTree( $changedOriginalNode->attribute( 'main_node_id' ),
                                                                 $parentObject->attribute( 'section_id' ),
                                                                 $changedOriginalObject->attribute( 'section_id' ) );
            }
        }
        if( $changedTargetNode->attribute( 'main_node_id' ) == $changedTargetNode->attribute( 'node_id' ) )
        {
            $changedTargetObject = $changedTargetNode->object();
            $selectedParentObject = $selectedNodeParent->object();
            if( $changedTargetObject->attribute( 'section_id' ) != $selectedParentObject->attribute( 'section_id' ) )
            {

                eZContentObjectTreeNode::assignSectionToSubTree( $changedTargetNode->attribute( 'main_node_id' ),
                                                                 $selectedParentObject->attribute( 'section_id' ),
                                                                 $changedTargetObject->attribute( 'section_id' ) );
            }
        }

        $db->commit();

        // clear cache for new placement.
        eZContentCacheManager::clearContentCacheIfNeeded( $objectID );

        return true;
    }
 /**
  * Updating priority sorting for given node
  *
  * @since 1.2
  * @param mixed $args
  * @return array
  */
 public static function updatePriority($args)
 {
     $http = eZHTTPTool::instance();
     if (!$http->hasPostVariable('ContentNodeID') || !$http->hasPostVariable('PriorityID') || !$http->hasPostVariable('Priority')) {
         return array();
     }
     $contentNodeID = $http->postVariable('ContentNodeID');
     $priorityArray = $http->postVariable('Priority');
     $priorityIDArray = $http->postVariable('PriorityID');
     $contentNode = eZContentObjectTreeNode::fetch($contentNodeID);
     if (!$contentNode instanceof eZContentObjectTreeNode) {
         throw new InvalidArgumentException("Argument ContentNodeID: '{$contentNodeID}' does not exist");
     } else {
         if (!$contentNode->canEdit()) {
             throw new InvalidArgumentException("Argument ContentNodeIDs: '{$contentNodeID}' is not available");
         }
     }
     if (eZOperationHandler::operationIsAvailable('content_updatepriority')) {
         $operationResult = eZOperationHandler::execute('content', 'updatepriority', array('node_id' => $contentNodeID, 'priority' => $priorityArray, 'priority_id' => $priorityIDArray), null, true);
     } else {
         eZContentOperationCollection::updatePriority($contentNodeID, $priorityArray, $priorityIDArray);
     }
     if ($http->hasPostVariable('ContentObjectID')) {
         $objectID = $http->postVariable('ContentObjectID');
         eZContentCacheManager::clearContentCacheIfNeeded($objectID);
     }
 }
예제 #21
0
 * @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
 * @version  2012.8
 * @package kernel
 */
// Check for extension
require_once 'kernel/common/ezincludefunctions.php';
eZExtension::activateExtensions();
// Extension check end
$ini = eZINI::instance('content.ini');
$unpublishClasses = $ini->variable('UnpublishSettings', 'ClassList');
$rootNodeIDList = $ini->variable('UnpublishSettings', 'RootNodeList');
$currentDate = time();
foreach ($rootNodeIDList as $nodeID) {
    $rootNode = eZContentObjectTreeNode::fetch($nodeID);
    $articleNodeArray = $rootNode->subTree(array('ClassFilterType' => 'include', 'ClassFilterArray' => $unpublishClasses));
    foreach ($articleNodeArray as $articleNode) {
        $article = $articleNode->attribute('object');
        $dataMap = $article->attribute('data_map');
        $dateAttribute = $dataMap['unpublish_date'];
        if ($dateAttribute === null) {
            continue;
        }
        $date = $dateAttribute->content();
        $articleRetractDate = $date->attribute('timestamp');
        if ($articleRetractDate > 0 && $articleRetractDate < $currentDate) {
            // Clean up content cache
            eZContentCacheManager::clearContentCacheIfNeeded($article->attribute('id'));
            $article->removeThis($articleNode->attribute('node_id'));
        }
    }
}
예제 #22
0
    $comment->setAttribute('modified', $time);
    // update comments
    $commentManager = ezcomCommentManager::instance();
    $clientNotified = $formTool->fieldValue('notificationField');
    $updateResult = null;
    // if notified and clientNotified are not null and different, change notification
    if ($notificationEnabled && $emailEnabled && $comment->attribute('email') != '' && $notified != $clientNotified) {
        $updateResult = $commentManager->updateComment($comment, null, $time, $clientNotified);
    } else {
        $updateResult = $commentManager->updateComment($comment, null, $time);
    }
    if ($updateResult !== true) {
        $tpl->setVariable('error_message', ezpI18n::tr('ezcomments/comment/edit', 'Updating failed.') . $updateResult);
    } else {
        //clean up cache
        eZContentCacheManager::clearContentCacheIfNeeded($contentObject->attribute('id'));
        $redirectionURI = $http->postVariable('ezcomments_comment_redirect_uri');
        return $Module->redirectTo($redirectionURI);
    }
    return showComment($comment, $tpl);
} else {
    if ($Module->isCurrentAction('Cancel')) {
        $redirectionURI = $http->postVariable('ezcomments_comment_redirect_uri');
        return $Module->redirectTo($redirectionURI);
    } else {
        $redirectURI = null;
        if ($http->hasSessionVariable("LastAccessesURI")) {
            $redirectURI = $http->sessionVariable('LastAccessesURI');
        } else {
            $redirectURI = '/comment/view/' . $comment->attribute('contentobject_id');
            $redirectURI = eZURI::transformURI($redirectURI);
 /**
  * Clears the view cache for a subtree
  *
  * @param eZContentObjectTreeNode $node
  * @param bool $clearForRootNode
  * @return bool
  */
 static function clearViewCacheForSubtree(eZContentObjectTreeNode $node, $clearForRootNode = true)
 {
     // Max nodes to fetch at a time
     static $limit = 200;
     if ($clearForRootNode) {
         $objectID = $node->attribute('contentobject_id');
         eZContentCacheManager::clearContentCacheIfNeeded($objectID);
     }
     $offset = 0;
     $params = array('AsObject' => false, 'Depth' => false, 'Limitation' => array());
     // Empty array means no permission checking
     $subtreeCount = $node->subTreeCount($params);
     while ($offset < $subtreeCount) {
         $params['Offset'] = $offset;
         $params['Limit'] = $limit;
         $subtreeChunk = $node->subTree($params);
         $nNodesInChunk = count($subtreeChunk);
         $offset += $nNodesInChunk;
         if ($nNodesInChunk == 0) {
             break;
         }
         $objectIDList = array();
         foreach ($subtreeChunk as $curNode) {
             $objectIDList[] = $curNode['id'];
         }
         unset($subtreeChunk);
         eZContentCacheManager::clearContentCacheIfNeeded(array_unique($objectIDList));
     }
     return true;
 }
 /**
  * Rate content object attribute id
  *
  * @param array $args ( 0 => contentobjectattribute_id,  1 => contentobject_version, 2 => rating )
  * @return array
  */
 public static function rate($args)
 {
     $ret = array('id' => 0, 'rated' => false, 'already_rated' => false, 'stats' => false);
     if (isset($args[0])) {
         $ret['id'] = $args[0];
     }
     if (!isset($args[2]) || !is_numeric($args[0]) || !is_numeric($args[1]) || !is_numeric($args[2]) || $args[2] > 5 || $args[2] < 1) {
         return $ret;
     }
     // Provide extra session protection on 4.1 (not possible on 4.0) by expecting user
     // to have an existing session (new session = mostlikely a spammer / hacker trying to manipulate rating)
     if (class_exists('eZSession') && eZSession::userHasSessionCookie() !== true) {
         return $ret;
     }
     // Return if parameters are not valid attribute id + version numbers
     $contentobjectAttribute = eZContentObjectAttribute::fetch($ret['id'], $args[1]);
     if (!$contentobjectAttribute instanceof eZContentObjectAttribute) {
         return $ret;
     }
     // Return if attribute is not a rating attribute
     if ($contentobjectAttribute->attribute('data_type_string') !== ezsrRatingType::DATA_TYPE_STRING) {
         return $ret;
     }
     // Return if rating has been disabled on current attribute
     if ($contentobjectAttribute->attribute('data_int')) {
         return $ret;
     }
     // Return if user does not have access to object
     $contentobject = $contentobjectAttribute->attribute('object');
     if (!$contentobject instanceof eZContentObject || !$contentobject->attribute('can_read')) {
         return $ret;
     }
     $rateDataObj = ezsrRatingDataObject::create(array('contentobject_id' => $contentobjectAttribute->attribute('contentobject_id'), 'contentobject_attribute_id' => $ret['id'], 'rating' => $args[2]));
     $proiorRating = $rateDataObj->userHasRated(true);
     if ($proiorRating === true) {
         $ret['already_rated'] = true;
     } else {
         if ($proiorRating instanceof ezsrRatingDataObject) {
             $rateDataObj = $proiorRating;
             $rateDataObj->setAttribute('rating', $args[2]);
             $ret['already_rated'] = true;
             $proiorRating = false;
             // just to reuse code bellow
         }
     }
     if (!$proiorRating) {
         $rateDataObj->store();
         $avgRateObj = $rateDataObj->getAverageRating();
         $avgRateObj->updateFromRatingData();
         $avgRateObj->store();
         eZContentCacheManager::clearContentCacheIfNeeded($rateDataObj->attribute('contentobject_id'));
         $ret['rated'] = true;
         $ret['stats'] = array('rating_count' => $avgRateObj->attribute('rating_count'), 'rating_average' => $avgRateObj->attribute('rating_average'), 'rounded_average' => $avgRateObj->attribute('rounded_average'));
     }
     return $ret;
 }
 /**
  * Activate user with user or deactivate and create new eZUserAccountKey with user hash
  * depending on $enableUser being true or not.
  *
  * @param int $userID
  * @param string $userHash
  * @param bool $enableUser
  *
  * @return array An array with operation status, always true if userID is ok
  */
 public static function activation($userID, $userHash, $enableUser = false)
 {
     $user = eZUser::fetch($userID);
     $userSetting = eZUserSetting::fetch($userID);
     if ($user && $userSetting) {
         $userChange = $userSetting->attribute('is_enabled') != $enableUser;
         if ($enableUser) {
             $userSetting->setAttribute('is_enabled', 1);
             $userSetting->store();
             eZUserAccountKey::removeByUserID($userID);
         } else {
             $userSetting->setAttribute('is_enabled', 0);
             $userSetting->store();
             $accountKey = eZUserAccountKey::createNew($userID, $userHash, time());
             $accountKey->store();
         }
         if ($userChange) {
             if (!$enableUser) {
                 eZUser::removeSessionData($userID);
             }
             eZContentCacheManager::clearContentCacheIfNeeded($userID);
         }
         return array('status' => true);
     } else {
         eZDebug::writeError("Failed to activate user {$userID} (could not fetch)", __METHOD__);
         return array('status' => false);
     }
 }
 static function move($nodeID, $newParentNodeID)
 {
     $result = false;
     if (!is_numeric($nodeID) || !is_numeric($newParentNodeID)) {
         return false;
     }
     $node = eZContentObjectTreeNode::fetch($nodeID);
     if (!$node) {
         return false;
     }
     $object = $node->object();
     if (!$object) {
         return false;
     }
     $objectID = $object->attribute('id');
     $oldParentNode = $node->fetchParent();
     $oldParentObject = $oldParentNode->object();
     // clear user policy cache if this is a user object
     if (in_array($object->attribute('contentclass_id'), eZUser::contentClassIDs())) {
         eZUser::purgeUserCacheByUserId($object->attribute('id'));
     }
     // clear cache for old placement.
     // If child count exceeds threshold, do nothing here, and instead clear all view cache at the end.
     $childCountInThresholdRange = eZContentCache::inCleanupThresholdRange($node->childrenCount(false));
     if ($childCountInThresholdRange) {
         eZContentCacheManager::clearContentCacheIfNeeded($objectID);
     }
     $db = eZDB::instance();
     $db->begin();
     $node->move($newParentNodeID);
     $newNode = eZContentObjectTreeNode::fetchNode($objectID, $newParentNodeID);
     if ($newNode) {
         $newNode->updateSubTreePath(true, true);
         if ($newNode->attribute('main_node_id') == $newNode->attribute('node_id')) {
             // If the main node is moved we need to check if the section ID must change
             $newParentNode = $newNode->fetchParent();
             $newParentObject = $newParentNode->object();
             if ($object->attribute('section_id') != $newParentObject->attribute('section_id')) {
                 eZContentObjectTreeNode::assignSectionToSubTree($newNode->attribute('main_node_id'), $newParentObject->attribute('section_id'), $oldParentObject->attribute('section_id'));
             }
         }
         // modify assignment
         $curVersion = $object->attribute('current_version');
         $nodeAssignment = eZNodeAssignment::fetch($objectID, $curVersion, $oldParentNode->attribute('node_id'));
         if ($nodeAssignment) {
             $nodeAssignment->setAttribute('parent_node', $newParentNodeID);
             $nodeAssignment->setAttribute('op_code', eZNodeAssignment::OP_CODE_MOVE);
             $nodeAssignment->store();
             // update search index specifying we are doing a move operation
             $nodeIDList = array($nodeID);
             eZSearch::removeNodeAssignment($node->attribute('main_node_id'), $newNode->attribute('main_node_id'), $object->attribute('id'), $nodeIDList);
             eZSearch::addNodeAssignment($newNode->attribute('main_node_id'), $object->attribute('id'), $nodeIDList, true);
         }
         $result = true;
     } else {
         eZDebug::writeError("Node {$nodeID} was moved to {$newParentNodeID} but fetching the new node failed");
     }
     $db->commit();
     // clear cache for new placement.
     // If child count exceeds threshold, clear all view cache instead.
     if ($childCountInThresholdRange) {
         eZContentCacheManager::clearContentCacheIfNeeded($objectID);
     } else {
         eZContentCacheManager::clearAllContentCache();
     }
     return $result;
 }
예제 #27
0
         eZDebug::writeError("Missing NodeID parameter for action " . $module->currentAction(), 'content/action');
         return $module->redirectToView('view', array('full', 2));
     }
     $objectID = $module->actionParameter('ObjectID');
     $nodeID = $module->actionParameter('NodeID');
     $object = eZContentObject::fetch($objectID);
     if (!$object) {
         return $module->handleError(eZError::KERNEL_NOT_AVAILABLE, 'kernel');
     }
     $user = eZUser::currentUser();
     $result = $user->hasAccessTo('setup', 'managecache');
     if ($result['accessWord'] != 'yes') {
         return $module->handleError(eZError::KERNEL_ACCESS_DENIED, 'kernel');
     }
     if ($module->isCurrentAction('ClearViewCache')) {
         eZContentCacheManager::clearContentCacheIfNeeded($objectID);
     } else {
         $node = eZContentObjectTreeNode::fetch($nodeID);
         if (!$node) {
             return $module->handleError(eZError::KERNEL_NOT_AVAILABLE, 'kernel');
         }
         eZContentObjectTreeNode::clearViewCacheForSubtree($node);
     }
     if ($module->hasActionParameter('CurrentURL')) {
         $currentURL = $module->actionParameter('CurrentURL');
         return $module->redirectTo($currentURL);
     }
     return $module->redirectToView('view', array($viewMode, $nodeID, $languageCode));
 } else {
     if ($module->isCurrentAction('UploadFile')) {
         if (!$module->hasActionParameter('UploadActionName')) {
예제 #28
0
 static function clearCacheForObjectLink($urlID)
 {
     $urlObjectLinkList = eZPersistentObject::fetchObjectList(eZURLObjectLink::definition(), null, array('url_id' => $urlID), null, null, true);
     foreach ($urlObjectLinkList as $urlObjectLink) {
         $objectAttributeID = $urlObjectLink->attribute('contentobject_attribute_id');
         $objectAttributeVersion = $urlObjectLink->attribute('contentobject_attribute_version');
         $objectAttribute = eZContentObjectAttribute::fetch($objectAttributeID, $objectAttributeVersion);
         if ($objectAttribute) {
             $objectID = $objectAttribute->attribute('contentobject_id');
             $objectVersion = $objectAttribute->attribute('version');
             eZContentCacheManager::clearContentCacheIfNeeded($objectID, $objectVersion);
         }
     }
 }
 /**
  * Removes a RSS/ATOM Feed export for a node
  *
  * @param int $nodeID Node ID
  *
  * @since 4.3
  */
 public static function removeFeedForNode($nodeID)
 {
     $rssExport = eZPersistentObject::fetchObject(eZRSSExport::definition(), null, array('node_id' => $nodeID, 'status' => eZRSSExport::STATUS_VALID), true);
     if (!$rssExport instanceof eZRSSExport) {
         eZDebug::writeError('DisableRSS: There is no rss/atom feeds left to delete for this node: ' . $nodeID, __METHOD__);
         return array('status' => false);
     }
     $node = eZContentObjectTreeNode::fetch($nodeID);
     if (!$node instanceof eZContentObjectTreeNode) {
         eZDebug::writeError('DisableRSS: Could not fetch node: ' . $nodeID, __METHOD__);
         return array('status' => false);
     }
     $objectID = $node->attribute('contentobject_id');
     $rssExport->removeThis();
     eZContentCacheManager::clearContentCacheIfNeeded($objectID);
     return array('status' => true);
 }
// you.
//
$Module = $Params['Module'];
$http = eZHTTPTool::instance();
if ($http->hasPostVariable('RecurrenceButton')) {
    $newsletterID = $http->postVariable('NewsletterID');
    if ($newsletterID) {
        $newsletter = eZNewsletter::fetch($newsletterID);
        if ($newsletter === null) {
            return $Module->handleError(eZError::KERNEL_NOT_AVAILABLE, 'kernel');
        }
        if ($http->hasPostVariable('Action')) {
            if ($http->postVariable('Action') === 'activate') {
                $newsletter->setAttribute('send_status', eZNewsletter::SendStatusNone);
            } else {
                if ($http->postVariable('Action') === 'stop') {
                    $newsletter->setAttribute('send_status', eZNewsletter::SendStatusStopped);
                }
            }
            $newsletter->sync();
            eZContentCacheManager::clearContentCacheIfNeeded($newsletter->attribute('contentobject_id'));
        }
    } else {
        return $Module->handleError(eZError::KERNEL_NOT_AVAILABLE, 'kernel');
    }
    $nodeID = $http->postVariable('NodeID');
    if ($nodeID === null) {
        return $Module->handleError(eZError::KERNEL_NOT_AVAILABLE, 'kernel');
    }
    return $Module->redirectTo('/content/view/full/' . $nodeID);
}