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;
 }
function feZMetaData_ContentActionHandler( &$module, &$http, &$objectID )
{
	// Action when user clicks on the Add Button
	if( $http->hasPostVariable( 'AddMetaDataButton' ) )
	{
		$link = 'fezmetadata/edit/0/(contentObjectID)/'.$objectID;
		$link .= '/(metaDataName)/'.$_POST['metaDataName'];
		$link .= '/(language)/'.$_POST['language'];
		eZURI::transformURI( $link );
		$http->redirect( $link );
	}

	// Action when user clicks on the Remove Button
	if( $http->hasPostVariable( 'RemoveMetaDataButton' ) and $http->hasPostVariable( 'MetaDataIDSelection' ) )
	{
		$metaDataSelection = $http->postVariable( 'MetaDataIDSelection' );
		foreach( $metaDataSelection as $metaData )
		{
			$metaDataObject = feZMetaData::fetch( $metaData );
			$metaDataObject->remove();
		}
		eZContentCacheManager::clearContentCache( $objectID );
		$ContentObject = eZContentObject::fetch( $objectID );
		$ContentNodeID = $ContentObject->mainNodeID();
		return $module->redirect( 'content', 'view', array( 'full', $ContentNodeID ) );
	}
}
Ejemplo n.º 3
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));
}
 function execute($process, $event)
 {
     // get object being published
     $parameters = $process->attribute('parameter_list');
     $objectId = $parameters['object_id'];
     eZDebug::writeDebug('Expire remote cache event begins execution for object ' . $objectId);
     $ini = eZINI::instance('ezworkflowcollection.ini');
     $object = eZContentObject::fetch($objectId);
     if ($object != null) {
         if ($ini->variable('ExpireRemoteCacheFlowSettings', 'ExpireOnlyObjectNodes') == 'enabled') {
             // basic version
             // get list of nodes this object is published with
             $assigned_nodes = $object->attribute('assigned_nodes');
         } else {
             // smart-cache enabled version
             // get list of nodes whose view-cache is expired
             $assigned_nodes = array();
             eZContentCacheManager::nodeListForObject($object, true, eZContentCacheManager::CLEAR_DEFAULT, $assigned_nodes, $handledObjectList);
             foreach ($assigned_nodes as $i => $nodeID) {
                 $assigned_nodes[$i] = eZContentObjectTreeNode::fetch($nodeID);
             }
         }
         $domains = $ini->variable('ExpireRemoteCacheFlowSettings', 'ExpireDomains');
         foreach ($assigned_nodes as $assigned_node) {
             // for every node, call eZHTTPCacheManager to clean the remote cache
             $url = $assigned_node->urlAlias();
             if (is_array($domains) && (count($domains) > 1 || count($domains) > 0 && $domains[0] != '')) {
                 eZURI::transformURI($url);
                 foreach ($domains as $domain) {
                     eZHTTPCacheManager::execute($domain . $url);
                 }
             } else {
                 eZURI::transformURI($url, false, 'full');
                 eZHTTPCacheManager::execute($url);
             }
         }
     } else {
         eZDebug::writeError('Expire remote cache event triggered for inexisting object: ' . $objectId);
         return eZWorkflowType::STATUS_WORKFLOW_CANCELLED;
     }
     return eZWorkflowType::STATUS_ACCEPTED;
 }
    /**
     * Updating priority sorting for given node
     *
     * @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->attribute( 'can_edit' ) )
        {
            eZDebug::writeError( 'Current user can not update the priorities because he has no permissions to edit the node' );
            return array();
        }

        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::clearContentCache( $objectID );
        }
    }
    /**
     * @param eZWorkflowProcess $process
     * @param eZWorkflowEvent $event
     * @return int
     */
    function execute( $process, $event )
    {
        // Get some information about the object being passed
        $parameters = $process->attribute( 'parameter_list' );
        $object     = eZContentObject::fetch( $parameters['object_id'] );

        if($object->ClassIdentifier != 'article')
            return self::STATUS_ACCEPTED;

        /* @type $dataMap eZContentObjectAttribute[] */
        $dataMap = $object->dataMap();

        if(isset($dataMap['source']))
        {
            $sourceString = MMNewsSource::getSourceString($object);
            if($sourceString)
            {
                $dataMap['source']->setAttribute('data_text', $sourceString);
                $dataMap['source']->store();
            }
            eZContentCacheManager::clearContentCache($object->attribute('id'));
        }
        return self::STATUS_ACCEPTED;
    }
Ejemplo n.º 7
0
function removeRelatedCache($siteAccess)
{
    // Delete compiled template
    $ini = eZINI::instance();
    $iniPath = eZSiteAccess::findPathToSiteAccess($siteAccess);
    $siteINI = eZINI::instance('site.ini.append', $iniPath);
    if ($siteINI->hasVariable('FileSettings', 'CacheDir')) {
        $cacheDir = $siteINI->variable('FileSettings', 'CacheDir');
        if ($cacheDir[0] == "/") {
            $cacheDir = eZDir::path(array($cacheDir));
        } else {
            if ($siteINI->hasVariable('FileSettings', 'VarDir')) {
                $varDir = $siteINI->variable('FileSettings', 'VarDir');
                $cacheDir = eZDir::path(array($varDir, $cacheDir));
            }
        }
    } else {
        if ($siteINI->hasVariable('FileSettings', 'VarDir')) {
            $varDir = $siteINI->variable('FileSettings', 'VarDir');
            $cacheDir = $ini->variable('FileSettings', 'CacheDir');
            $cacheDir = eZDir::path(array($varDir, $cacheDir));
        } else {
            $cacheDir = eZSys::cacheDirectory();
        }
    }
    $compiledTemplateDir = $cacheDir . "/template/compiled";
    eZDir::unlinkWildcard($compiledTemplateDir . "/", "*pagelayout*.*");
    eZCache::clearByTag('template-block');
    // Expire content view cache
    eZContentCacheManager::clearAllContentCache();
}
Ejemplo n.º 8
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);
 }
 function storeObjectAttribute($attribute)
 {
     $ini = eZINI::instance();
     // Delete compiled template
     $siteINI = eZINI::instance();
     if ($siteINI->hasVariable('FileSettings', 'CacheDir')) {
         $cacheDir = $siteINI->variable('FileSettings', 'CacheDir');
         if ($cacheDir[0] == "/") {
             $cacheDir = eZDir::path(array($cacheDir));
         } else {
             if ($siteINI->hasVariable('FileSettings', 'VarDir')) {
                 $varDir = $siteINI->variable('FileSettings', 'VarDir');
                 $cacheDir = eZDir::path(array($varDir, $cacheDir));
             }
         }
     } else {
         if ($siteINI->hasVariable('FileSettings', 'VarDir')) {
             $varDir = $siteINI->variable('FileSettings', 'VarDir');
             $cacheDir = $ini->variable('FileSettings', 'CacheDir');
             $cacheDir = eZDir::path(array($varDir, $cacheDir));
         } else {
             $cacheDir = eZSys::cacheDirectory();
         }
     }
     $compiledTemplateDir = $cacheDir . "/template/compiled";
     eZDir::unlinkWildcard($compiledTemplateDir . "/", "*pagelayout*.*");
     // Expire template block cache
     eZContentCacheManager::clearTemplateBlockCacheIfNeeded(false);
 }
Ejemplo n.º 10
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");
}
 /**
  * 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;
 }
Ejemplo n.º 12
0
 static function generateObjectViewCache($objectID)
 {
     // Generate the view cache
     $ini = eZINI::instance();
     $object = eZContentObject::fetch($objectID);
     $user = eZUser::currentUser();
     eZDebug::accumulatorStart('generate_cache', '', 'Generating view cache');
     if ($ini->variable('ContentSettings', 'PreViewCache') == 'enabled') {
         $preCacheSiteaccessArray = $ini->variable('ContentSettings', 'PreCacheSiteaccessArray');
         $currentSiteAccess = $GLOBALS['eZCurrentAccess'];
         // This is the default view parameters for content/view
         $viewParameters = array('offset' => false, 'year' => false, 'month' => false, 'day' => false, 'namefilter' => false);
         if (is_array($preCacheSiteaccessArray) && count($preCacheSiteaccessArray) > 0) {
             foreach ($preCacheSiteaccessArray as $changeToSiteAccess) {
                 $newSiteAccess = $currentSiteAccess;
                 $newSiteAccess['name'] = $changeToSiteAccess;
                 unset($newSiteAccess['uri_part']);
                 //eZSiteAccess::load() will take care of setting correct one
                 eZSiteAccess::load($newSiteAccess);
                 $tpl = eZTemplate::factory();
                 // Get the sitedesign and cached view preferences for this siteaccess
                 $siteini = eZINI::instance('site.ini');
                 $cachedViewPreferences = $siteini->variable('ContentSettings', 'CachedViewPreferences');
                 $language = false;
                 // Needs to be specified if you want to generate the cache for a specific language
                 $viewMode = 'full';
                 $assignedNodes = $object->assignedNodes();
                 foreach ($assignedNodes as $node) {
                     // We want to generate the cache for the specified user
                     $previewCacheUsers = $ini->variable('ContentSettings', 'PreviewCacheUsers');
                     foreach ($previewCacheUsers as $previewCacheUserID) {
                         // If the text is 'anon' we need to fetch the Anonymous user ID.
                         if ($previewCacheUserID === 'anonymous') {
                             $previewCacheUserID = $siteini->variable("UserSettings", "AnonymousUserID");
                             $previewCacheUser = eZUser::fetch($previewCacheUserID);
                         } else {
                             if ($previewCacheUserID === 'current') {
                                 $previewCacheUser = $user;
                             } else {
                                 $previewCacheUser = eZUser::fetch($previewCacheUserID);
                             }
                         }
                         if (!$previewCacheUser) {
                             continue;
                         }
                         // Before we generate the view cache we must change the currently logged in user to $previewCacheUser
                         // If not the templates might read in wrong personalized data (preferences etc.)
                         eZUser::setCurrentlyLoggedInUser($previewCacheUser, $previewCacheUser->attribute('contentobject_id'), eZUser::NO_SESSION_REGENERATE);
                         // Cache the current node
                         $cacheFileArray = eZNodeviewfunctions::generateViewCacheFile($previewCacheUser, $node->attribute('node_id'), false, false, $language, $viewMode, $viewParameters, $cachedViewPreferences);
                         $tmpRes = eZNodeviewfunctions::generateNodeView($tpl, $node, $node->attribute('object'), $language, $viewMode, false, $cacheFileArray['cache_dir'], $cacheFileArray['cache_path'], true, $viewParameters);
                         // Cache the parent node
                         $parentNode = $node->attribute('parent');
                         $objectID = $parentNode->attribute('contentobject_id');
                         // if parent objectID is null or is 0 we should not create cache.
                         if ($objectID) {
                             $cacheFileArray = eZNodeviewfunctions::generateViewCacheFile($previewCacheUser, $parentNode->attribute('node_id'), 0, false, $language, $viewMode, $viewParameters, $cachedViewPreferences);
                             $tmpRes = eZNodeviewfunctions::generateNodeView($tpl, $parentNode, $parentNode->attribute('object'), $language, $viewMode, 0, $cacheFileArray['cache_dir'], $cacheFileArray['cache_path'], true, $viewParameters);
                         }
                     }
                 }
             }
             // Restore the old user as the current one
             eZUser::setCurrentlyLoggedInUser($user, $user->attribute('contentobject_id'), eZUser::NO_SESSION_REGENERATE);
             // restore siteaccess
             eZSiteAccess::load($currentSiteAccess);
         }
     }
     if ($ini->variable('ContentSettings', 'StaticCache') == 'enabled') {
         $nodes = array();
         $ini = eZINI::instance();
         $useURLAlias =& $GLOBALS['eZContentObjectTreeNodeUseURLAlias'];
         $pathPrefix = $ini->variable('SiteAccessSettings', 'PathPrefix');
         // get staticCacheHandler instance
         $optionArray = array('iniFile' => 'site.ini', 'iniSection' => 'ContentSettings', 'iniVariable' => 'StaticCacheHandler');
         $options = new ezpExtensionOptions($optionArray);
         $staticCacheHandler = eZExtension::getHandlerClass($options);
         if (!isset($useURLAlias)) {
             $useURLAlias = $ini->variable('URLTranslator', 'Translation') == 'enabled';
         }
         eZContentCacheManager::nodeListForObject($object, true, self::CLEAR_DEFAULT, $nodes, $handledObjectList);
         // If no nodes returns it means that ClearCacheMethod = self::CLEAR_NO_CACHE
         if (count($nodes)) {
             foreach ($nodes as $nodeID) {
                 if ($useURLAlias) {
                     $oNode = eZContentObjectTreeNode::fetch($nodeID, false, true);
                     if (!isset($oNode)) {
                         continue;
                     }
                     $urlAlias = $oNode->urlAlias();
                     if ($pathPrefix != '') {
                         $tempAlias = substr($pathPrefix, strlen($pathPrefix) - 1) == '/' ? $urlAlias . '/' : $urlAlias;
                         if (strncmp($tempAlias, $pathPrefix, strlen($tempAlias)) == 0) {
                             $urlAlias = substr($tempAlias, strlen($pathPrefix));
                         }
                     }
                 } else {
                     $urlAlias = 'content/view/full/' . $nodeID;
                 }
                 $staticCacheHandler->cacheURL('/' . $urlAlias, $nodeID);
             }
             $staticCacheHandler->generateAlwaysUpdatedCache();
         }
     }
     eZDebug::accumulatorStop('generate_cache');
 }
Ejemplo n.º 13
0
Archivo: add.php Proyecto: 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;
Ejemplo n.º 14
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;
    }
Ejemplo n.º 15
0
 /**
  * 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;
 }
 /**
  * Forza l'impostazione del colore di base di un site
  * 
  * Ritorna true se il colore è stato modificato
  * 
  * @param int $currentColor
  * @return boolean
  */
 public static function forceSiteColor($currentColor)
 {
     //
     // lettura variabili per individuare file scss
     $designINIinstance = eZINI::instance('design.ini', 'settings', null, FALSE);
     $_stylesheetBaseFile = $designINIinstance->variable('StylesheetSettings', 'StylesheetBaseFile');
     $_stylesheetDestFile = $designINIinstance->variable('StylesheetSettings', 'StylesheetDestinationFile');
     $_stylesheetCluster = $designINIinstance->variable('StylesheetSettings', 'StylesheetCluster');
     // Cicla sui file di origine
     for ($i = 0; $i < count($_stylesheetBaseFile); $i++) {
         foreach ($_stylesheetCluster as $itemCluster) {
             // File da sostituire.
             $curFile = $itemCluster . $_stylesheetBaseFile[$i];
             $curDestinationFile = $itemCluster . $_stylesheetDestFile[$i];
             //print_r('File :<br><b>');
             //print_r($curFile);
             //print_r('<br>in:<br><b>');
             //print_r($curDestinationFile);
             //die();
             // recupera i valori del eZPersistentObject sinet_site_colors
             $colorList = Sinetsitecolors_PstObject::fetchHandlerList();
             $fh = fopen($curFile, 'r');
             $newRow = '';
             // Legge ogni singola riga del file origine
             $arrayOriginalColor = explode("-", $currentColor);
             while (!feof($fh)) {
                 $tmpRow = fgets($fh);
                 $indiceColore = 0;
                 foreach ($colorList as $objColor) {
                     // per ogni riga del pesisten object sostituisce il name_tag con il colore letto
                     $curname_tag = $objColor['name_tag'];
                     if (count($arrayOriginalColor) > $indiceColore) {
                         $tmpRow = PatBaseColorFunctions::replaceCssInLine($tmpRow, $arrayOriginalColor[$indiceColore], $curname_tag);
                     }
                     $indiceColore++;
                 }
                 $newRow .= $tmpRow;
             }
             // set del colore nel persistent object
             $indiceColore = 0;
             foreach ($colorList as $objColor) {
                 $curname_tag = $objColor['name_tag'];
                 $curId = $objColor['id'];
                 if (count($arrayOriginalColor) > $indiceColore) {
                     $simpleObj = Sinetsitecolors_PstObject::fetchById($curId);
                     $simpleObj->setAttribute('color', $arrayOriginalColor[$indiceColore]);
                     $simpleObj->store();
                 }
                 $indiceColore++;
             }
             // Scrive il file di destinazione
             $fw = fopen($curDestinationFile, 'w');
             if (!$fw) {
                 echo '</b><font color=red>Errore Open W</font></pre>';
             } else {
                 $bytes = fwrite($fw, $newRow);
                 fclose($fw);
             }
             fclose($fh);
             // echo('</b><font color=red>OK</font></pre>');
         }
     }
     // Prova la pulizia della cache dei template
     eZContentCacheManager::clearAllContentCache();
     eZContentCacheManager::clearContentCache(2);
     //die();
     return true;
 }
Ejemplo n.º 17
0
        if (preg_match('/(^[^A-Za-z])|\\W/', $sectionIdentifier)) {
            $errorMessage = ezpI18n::tr('design/admin/section/edit', 'Identifier should consist of letters, numbers or \'_\' with letter prefix.');
        } else {
            $conditions = array('identifier' => $sectionIdentifier, 'id' => array('!=', $SectionID));
            $existingSection = eZSection::fetchFilteredList($conditions);
            if (count($existingSection) > 0) {
                $errorMessage = ezpI18n::tr('design/admin/section/edit', 'The identifier has been used in another section.');
            }
        }
    }
    $section->setAttribute('identifier', $sectionIdentifier);
    $section->setAttribute('navigation_part_identifier', $http->postVariable('NavigationPartIdentifier'));
    if ($http->hasPostVariable('Locale')) {
        $section->setAttribute('locale', $http->postVariable('Locale'));
    }
    if ($errorMessage === '') {
        $section->store();
        eZContentCacheManager::clearContentCacheIfNeededBySectionID($section->attribute('id'));
        $Module->redirectTo($Module->functionURI('list'));
        return;
    } else {
        $tpl->setVariable('error_message', $errorMessage);
    }
}
if ($http->hasPostVariable('CancelButton')) {
    $Module->redirectTo($Module->functionURI('list'));
}
$tpl->setVariable("section", $section);
$Result = array();
$Result['content'] = $tpl->fetch("design:section/edit.tpl");
$Result['path'] = array(array('url' => 'section/list', 'text' => ezpI18n::tr('kernel/section', 'Sections')), array('url' => false, 'text' => $section instanceof eZSection ? $section->attribute('name') : $section['name']));
Ejemplo n.º 18
0
 /**
  * Do all time based operations on block pool such as rotation, updating
  * the queue, overflow as well as executes fetch interfaces.
  *
  * @static
  */
 public static function update($nodeArray = array())
 {
     // log in user as anonymous if another user is logged in
     $currentUser = eZUser::currentUser();
     if ($currentUser->isLoggedIn()) {
         $loggedInUser = $currentUser;
         $anonymousUserId = eZUser::anonymousId();
         $anonymousUser = eZUser::instance($anonymousUserId);
         eZUser::setCurrentlyLoggedInUser($anonymousUser, $anonymousUserId);
         unset($currentUser, $anonymousUser, $anonymousUserId);
     }
     include_once 'kernel/classes/ezcontentcache.php';
     $ini = eZINI::instance('block.ini');
     $db = eZDB::instance();
     // Remove the blocks and items for the block if marked for removal
     $res = $db->arrayQuery("SELECT id\n                         FROM ezm_block\n                         WHERE is_removed=1");
     foreach ($res as $row) {
         $blockID = $row['id'];
         $db->begin();
         $db->query("DELETE FROM ezm_pool\n                 WHERE block_id='{$blockID}'");
         $db->query("DELETE FROM ezm_block\n                 WHERE id='{$blockID}'");
         $db->commit();
     }
     if (!$nodeArray) {
         // Update pool and pages for all nodes
         $res = $db->arrayQuery("SELECT DISTINCT node_id FROM ezm_block");
         foreach ($res as $row) {
             $nodeArray[] = $row['node_id'];
         }
     }
     foreach ($nodeArray as $nodeID) {
         $time = time() - 5;
         // a safety margin
         $nodeChanged = false;
         $blocks = $db->arrayQuery("SELECT *\n                                FROM ezm_block\n                                WHERE node_id={$nodeID}");
         $blockByID = array();
         // Determine the order of updating
         $correctOrder = array();
         $next = array();
         foreach ($blocks as $block) {
             $next[$block['id']] = trim($block['overflow_id']);
             // Make sure that block ID does not any have spaces
             $blockByID[$block['id']] = $block;
         }
         $nextIDs = array_keys($next);
         foreach ($nextIDs as $id) {
             if (in_array($id, $correctOrder, true)) {
                 continue;
             }
             if (!$next[$id]) {
                 $correctOrder[] = $id;
                 continue;
             }
             $subCorrectOrder = array($id);
             $currentID = $id;
             while ($nextID = $next[$currentID]) {
                 if (!in_array($nextID, $nextIDs, true)) {
                     eZDebug::writeWarning("Overflow for {$currentID} is {$nextID}, but no such block was found for the given node", __METHOD__);
                     break;
                 }
                 if (in_array($nextID, $subCorrectOrder, true)) {
                     eZDebug::writeWarning("Loop detected, ignoring ({$nextID} should be after {$currentID} and vice versa)", __METHOD__);
                     break;
                 }
                 if (in_array($nextID, $correctOrder, true)) {
                     break;
                 }
                 $subCorrectOrder[] = $nextID;
                 $currentID = $nextID;
             }
             if (!$nextID || !in_array($nextID, $correctOrder, true)) {
                 foreach ($subCorrectOrder as $element) {
                     $correctOrder[] = $element;
                 }
             } else {
                 $newCorrectOrder = array();
                 foreach ($correctOrder as $element) {
                     if ($element === $nextID) {
                         foreach ($subCorrectOrder as $element2) {
                             $newCorrectOrder[] = $element2;
                         }
                     }
                     $newCorrectOrder[] = $element;
                 }
                 $correctOrder = $newCorrectOrder;
             }
         }
         // Loop through all block in determined order
         foreach ($correctOrder as $blockID) {
             if ($blockByID[$blockID]) {
                 $block = $blockByID[$blockID];
             } else {
                 continue;
             }
             // Do we need to update block? No, continue to process next block
             $ttl = 0;
             if ($ini->hasVariable($block['block_type'], 'TTL')) {
                 $ttl = $ini->variable($block['block_type'], 'TTL');
             }
             if ($ttl + $block['last_update'] >= $time) {
                 continue;
             }
             // For "rotating blocks", does the rotation_interval has passed from the last update?
             if ($block['rotation_type'] != self::ROTATION_NONE && $block['last_update'] + $block['rotation_interval'] >= $time) {
                 continue;
             }
             $blockChanged = false;
             // Fetch new objects and add them to the queue of the current block
             eZFlowOperations::updateBlockPoolByBlockID($block, $time);
             $db->begin();
             // We need to find out if there are any items to move from the queue
             $movingFromQueue = $db->arrayQuery("SELECT object_id\n                                             FROM ezm_pool\n                                             WHERE block_id='{$blockID}'\n                                               AND ts_visible=0\n                                               AND ts_hidden=0\n                                               AND ts_publication<={$time}\n                                             ORDER BY ts_publication ASC, priority ASC");
             if ($movingFromQueue) {
                 $blockChanged = true;
                 // Find out a number of items in "valid" state and the max. priority used
                 $countMaxPriorityValid = $db->arrayQuery("SELECT count(*) AS count, max(priority) AS priority\n                                                       FROM ezm_pool\n                                                       WHERE block_id='{$blockID}'\n                                                         AND ts_visible>0\n                                                         AND ts_hidden=0");
                 $countValid = $countMaxPriorityValid[0]['count'];
                 $maxPriorityValid = $countMaxPriorityValid[0]['priority'];
                 if ($countValid == 0) {
                     $maxPriorityValid = 0;
                 }
                 $priority = $maxPriorityValid + 1;
                 // Move objects waiting in queue to the "valid ones"
                 foreach ($movingFromQueue as $itemToMove) {
                     $objectID = $itemToMove['object_id'];
                     $db->query("UPDATE ezm_pool\n                             SET ts_visible={$time}, priority={$priority}\n                             WHERE block_id='{$blockID}'\n                               AND object_id={$objectID}");
                     $priority++;
                 }
                 $countValid += count($movingFromQueue);
                 // Compare this number to the given and archive the oldest (order by ts_visible)
                 $numberOfValidItems = $ini->variable($block['block_type'], 'NumberOfValidItems');
                 if (!$numberOfValidItems) {
                     $numberOfValidItems = 20;
                     eZDebug::writeWarning('Number of valid items for ' . $block['block_type'] . ' is not set; using the default value (' . $numberOfValidItems . ')', __METHOD__);
                 }
                 $countToRemove = $countValid - $numberOfValidItems;
                 if ($countToRemove > 0) {
                     $overflowID = $block['overflow_id'];
                     $items = $db->arrayQuery("SELECT node_id, object_id, rotation_until\n                                           FROM ezm_pool\n                                           WHERE block_id='{$blockID}'\n                                             AND ts_visible>0\n                                             AND ts_hidden=0\n                                           ORDER BY priority ASC", array('limit' => $countToRemove));
                     if ($items) {
                         $itemArray = array();
                         $priority = 0;
                         foreach ($items as $item) {
                             $objectID = $item['object_id'];
                             if ($block['rotation_type'] != self::ROTATION_NONE && ($item['rotation_until'] > $time || $item['rotation_until'] == 0)) {
                                 if ($block['rotation_type'] == self::ROTATION_SIMPLE) {
                                     // Simple rotation
                                     $newPublicationTS = -$time;
                                     $priority++;
                                 } else {
                                     // Random rotation/Shuffle
                                     $newPublicationTS = 0;
                                     $priority = mt_rand();
                                 }
                                 // Move item back to queue
                                 $db->query("UPDATE ezm_pool\n                                         SET ts_visible=0,\n                                             ts_publication=-{$time},\n                                             priority={$priority}\n                                         WHERE block_id='{$blockID}'\n                                           AND object_id={$objectID}");
                             } else {
                                 $itemArray[] = $objectID;
                             }
                         }
                         if ($itemArray) {
                             if ($overflowID) {
                                 // Put $itemArray items into pool of different block
                                 $priority = 0;
                                 foreach ($items as $item) {
                                     $itemObjectID = $item['object_id'];
                                     $itemNodeID = $item['node_id'];
                                     // Check if the object_id is not already in the new block
                                     $duplicityCheck = $db->arrayQuery("SELECT object_id\n                                                                    FROM ezm_pool\n                                                                    WHERE block_id='{$overflowID}'\n                                                                      AND object_id={$itemObjectID}", array('limit' => 1));
                                     if ($duplicityCheck) {
                                         eZDebug::writeNotice("Object {$itemObjectID} is already available in the block {$overflowID}.", __METHOD__);
                                     } else {
                                         $db->query("INSERT INTO ezm_pool(block_id,object_id,node_id,ts_publication,priority)\n                                                 VALUES ('{$overflowID}',{$itemObjectID},{$itemNodeID},{$time},{$priority})");
                                         $priority++;
                                     }
                                 }
                                 $db->query("UPDATE ezm_pool\n                                         SET ts_hidden={$time},\n                                             moved_to='{$overflowID}',\n                                             priority=0\n                                         WHERE block_id='{$blockID}'\n                                           AND " . $db->generateSQLINStatement($itemArray, 'object_id'));
                             } else {
                                 $db->query("UPDATE ezm_pool\n                                         SET ts_hidden={$time},\n                                             priority=0\n                                         WHERE block_id='{$blockID}'\n                                           AND " . $db->generateSQLINStatement($itemArray, 'object_id'));
                             }
                         }
                     }
                 }
                 // Cleanup in archived items
                 $countArchived = $db->arrayQuery("SELECT count(*) AS count\n                                               FROM ezm_pool\n                                               WHERE block_id='{$blockID}'\n                                                 AND ts_hidden>0");
                 $countArchived = $countArchived[0]['count'];
                 // Compare this number to the given and remove the oldest ones
                 $numberOfArchivedItems = $ini->variable($block['block_type'], 'NumberOfArchivedItems');
                 if ($numberOfArchivedItems < 0) {
                     $numberOfArchivedItems = 50;
                     eZDebug::writeWarning('Number of archived items for ' . $block['block_type'] . ' is not set; using the default value (' . $numberOfArchivedItems . ')', __METHOD__);
                 }
                 $countToRemove = $countArchived - $numberOfArchivedItems;
                 if ($countToRemove > 0) {
                     $items = $db->arrayQuery("SELECT object_id\n                                           FROM ezm_pool\n                                           WHERE block_id='{$blockID}'\n                                             AND ts_hidden>0\n                                           ORDER BY ts_hidden ASC", array('limit' => $countToRemove));
                     if ($items) {
                         $itemArray = array();
                         foreach ($items as $item) {
                             $itemArray[] = $item['object_id'];
                         }
                         $db->query("DELETE FROM ezm_pool\n                                 WHERE block_id='{$blockID}'\n                                   AND " . $db->generateSQLINStatement($itemArray, 'object_id'));
                     }
                 }
             }
             // If the block changed, we need to update whole node
             if ($blockChanged) {
                 $nodeChanged = true;
             }
             $db->commit();
         }
         if ($nodeChanged) {
             $contentObject = eZContentObject::fetchByNodeID($nodeID);
             if ($contentObject) {
                 eZContentCacheManager::clearContentCache($contentObject->attribute('id'));
             }
         }
     }
     // log the previously logged in user if it was changed to anonymous earlier
     if (isset($loggedInUser)) {
         eZUser::setCurrentlyLoggedInUser($loggedInUser, $loggedInUser->attribute('contentobject_id'));
     }
 }
 /**
  * Removes the language if there is no object having translation in it.
  *
  * \return True if the language was removed from the site, false otherwise.
  */
 function removeThis()
 {
     if ($this->objectCount() > 0 or $this->classCount() > 0) {
         return false;
     }
     $this->remove();
     eZContentCacheManager::clearAllContentCache();
     eZContentLanguage::fetchList(true);
     return true;
 }
Ejemplo n.º 20
0
            if ($siteINI->hasVariable('FileSettings', 'VarDir')) {
                $varDir = $siteINI->variable('FileSettings', 'VarDir');
                $cacheDir = eZDir::path(array($varDir, $cacheDir));
            }
        }
    } else {
        if ($siteINI->hasVariable('FileSettings', 'VarDir')) {
            $varDir = $siteINI->variable('FileSettings', 'VarDir');
            $cacheDir = $ini->variable('FileSettings', 'CacheDir');
            $cacheDir = eZDir::path(array($varDir, $cacheDir));
        } else {
            $cacheDir = eZSys::cacheDirectory();
        }
    }
    $compiledTemplateDir = $cacheDir . "/template/compiled";
    eZDir::unlinkWildcard($compiledTemplateDir . "/", "*pagelayout*.*");
    // Expire template block cache
    eZContentCacheManager::clearTemplateBlockCacheIfNeeded(false);
}
$availableMenuArray = $menuINI->variable('MenuSettings', 'AvailableMenuArray');
$menuArray = array();
foreach ($availableMenuArray as $menuType) {
    $menuArray[] = array('type' => $menuType, 'settings' => $menuINI->group($menuType));
}
$tpl->setVariable('available_menu_array', $menuArray);
$tpl->setVariable('current_menu', $menuINI->variable('SelectedMenu', 'CurrentMenu'));
$tpl->setVariable('siteaccess_list', $siteAccessList);
$tpl->setVariable('current_siteaccess', $siteAccess);
$Result = array();
$Result['content'] = $tpl->fetch("design:visual/menuconfig.tpl");
$Result['path'] = array(array('url' => false, 'text' => ezpI18n::tr('design/standard/menuconfig', 'Menu management')));
 /**
  * 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);
     }
 }
    /**
     * Fixes reverse relations
     *
     * @see eZObjectRelationListType::fixRelatedObjectItem()
     *
     * @param int $objectID
     * @param string|bool $mode See eZObjectRelationListType::fixRelatedObjectItem() for valid modes
     */
    static function fixReverseRelations( $objectID, $mode = false )
    {
        $db = eZDB::instance();
        $objectID = (int) $objectID;

        // Finds all the attributes that store relations to the given object.
        $result = $db->arrayQuery( "SELECT attr.*
                                    FROM ezcontentobject_link link,
                                         ezcontentobject_attribute attr
                                    WHERE link.from_contentobject_id=attr.contentobject_id AND
                                          link.from_contentobject_version=attr.version AND
                                          link.contentclassattribute_id=attr.contentclassattribute_id AND
                                          link.to_contentobject_id=$objectID" );
        if ( count( $result ) > 0 )
        {
            $objectIDList = array();
            foreach( $result as $row )
            {
                $attr = new eZContentObjectAttribute( $row );
                $dataType = $attr->dataType();
                $dataType->fixRelatedObjectItem( $attr, $objectID, $mode );
                $objectIDList[] = $attr->attribute( 'contentobject_id' );
            }
            if ( eZINI::instance()->variable( 'ContentSettings', 'ViewCaching' ) === 'enabled' )
                eZContentCacheManager::clearObjectViewCacheArray( $objectIDList );
        }
    }
Ejemplo n.º 23
0
 /**
  * Stores the current class as a modified version, updates the contentobject_name
  * attribute and recreates the class group entries.
  *
  * @note It will remove classes in the previous and specified version before storing.
  *
  * @param array $attributes array of attributes
  * @param int $version version status
  * @since Version 4.3
  */
 public function storeVersioned($attributes, $version)
 {
     $previousVersion = $this->attribute('version');
     $db = eZDB::instance();
     $db->begin();
     // Before removing anything from the attributes, load attribute information
     // which might otherwise not accessible when recreating them below.
     // See issue #18164
     foreach ($attributes as $attribute) {
         $attribute->content();
     }
     $this->removeAttributes(false, $version);
     $this->removeAttributes(false, $previousVersion);
     $this->remove(false);
     $this->setVersion($version, $attributes);
     $this->setAttribute("modifier_id", eZUser::currentUser()->attribute("contentobject_id"));
     $this->setAttribute("modified", time());
     $this->adjustAttributePlacements($attributes);
     foreach ($attributes as $attribute) {
         $attribute->storeVersioned($version);
     }
     // Set contentobject_name to something sensible if it is missing
     if (count($attributes) > 0 && trim($this->attribute('contentobject_name')) == '') {
         $this->setAttribute('contentobject_name', '<' . $attributes[0]->attribute('identifier') . '>');
     }
     // Recreate class member entries
     eZContentClassClassGroup::removeClassMembers($this->ID, $version);
     foreach (eZContentClassClassGroup::fetchGroupList($this->ID, $previousVersion) as $classgroup) {
         $classgroup->setAttribute('contentclass_version', $version);
         $classgroup->store();
     }
     eZContentClassClassGroup::removeClassMembers($this->ID, $previousVersion);
     eZExpiryHandler::registerShutdownFunction();
     $handler = eZExpiryHandler::instance();
     $time = time();
     $handler->setTimestamp('user-class-cache', $time);
     $handler->setTimestamp('class-identifier-cache', $time);
     $handler->setTimestamp('sort-key-cache', $time);
     $handler->store();
     eZContentCacheManager::clearAllContentCache();
     $this->setAttribute('serialized_name_list', $this->NameList->serializeNames());
     $this->setAttribute('serialized_description_list', $this->DescriptionList->serializeNames());
     eZPersistentObject::store();
     $this->NameList->store($this);
     $db->commit();
 }
Ejemplo n.º 24
0
        return $Module->handleError(eZError::KERNEL_ACCESS_DENIED, 'kernel');
    }
}
if ($http->hasPostVariable('ConfirmRemoveSectionButton')) {
    $currentUser = eZUser::currentUser();
    $accessResult = $currentUser->hasAccessTo('section', 'edit');
    if ($accessResult['accessWord'] == 'yes') {
        if ($http->hasSessionVariable('SectionIDArray')) {
            $sectionIDArray = $http->sessionVariable('SectionIDArray');
            $db = eZDB::instance();
            $db->begin();
            foreach ($sectionIDArray as $sectionID) {
                $section = eZSection::fetch($sectionID);
                if (is_object($section) and $section->canBeRemoved()) {
                    // Clear content cache if needed
                    eZContentCacheManager::clearContentCacheIfNeededBySectionID($sectionID);
                    $section->remove();
                }
            }
            $db->commit();
        }
    } else {
        return $Module->handleError(eZError::KERNEL_ACCESS_DENIED, 'kernel');
    }
}
$viewParameters = array('offset' => $offset);
$sectionArray = eZSection::fetchByOffset($offset, $limit);
$sectionCount = eZSection::sectionCount();
$currentUser = eZUser::currentUser();
$allowedAssignSectionList = $currentUser->canAssignSectionList();
$tpl->setVariable("limit", $limit);
Ejemplo n.º 25
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')) {
Ejemplo n.º 26
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'));
        }
    }
}
 /**
  * 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);
 }
    /**
     * 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;
    }
    }
    $db->commit();
    // because we changed users, we have to remove content cache
    eZContentCacheManager::clearAllContentCache();
}
if ($http->hasPostVariable("RemoveCustomerButton")) {
    if ($http->hasPostVariable("CustomerIDArray")) {
        $customerIDArray = $http->postVariable("CustomerIDArray");
        $db = eZDB::instance();
        $db->begin();
        foreach ($customerIDArray as $customerID) {
            eZUserDiscountRule::removeUser($customerID);
        }
        $db->commit();
    }
    eZContentCacheManager::clearAllContentCache();
}
$membershipList = eZUserDiscountRule::fetchByRuleID($discountGroupID);
$customers = array();
foreach ($membershipList as $membership) {
    $customers[] = eZContentObject::fetch($membership->attribute('contentobject_id'));
}
$ruleList = eZDiscountSubRule::fetchByRuleID($discountGroupID);
$ruleArray = array();
foreach ($ruleList as $rule) {
    $name = $rule->attribute('name');
    $percent = $rule->attribute('discount_percent');
    $limitation = $rule->attribute('limitation');
    $discountRuleID = $rule->attribute('id');
    if ($limitation != '*') {
        $ruleValues = eZDiscountSubRuleValue::fetchBySubRuleID($discountRuleID);
Ejemplo n.º 30
0
 function runOperation(&$node)
 {
     $datamap = $node->dataMap();
     $object_attribute = $datamap[$this->attribute];
     if (!isset($object_attribute)) {
         echo "Attribute '{$this->attribute}' not found. ";
         return false;
     }
     $old_value = $object_attribute->toString();
     // Set new value to specified attributes
     $arg_array = $this->arguments;
     foreach ($datamap as $key => $object_attribute) {
         $value = $object_attribute->toString();
         $arg_array = str_replace('{' . $key . '}', $value, $arg_array);
     }
     $new_value = call_user_func_array($this->change_function, $arg_array);
     if ($new_value == $old_value) {
         // Nothing to change
         return true;
     }
     $db = eZDB::instance();
     $db->begin();
     // Create new version
     $content_object = $node->object();
     $content_object_id = $content_object->attribute('id');
     $version = $content_object->createNewVersion();
     $version->setAttribute('modified', time());
     $version->setAttribute('status', 'EZ_VERSION_STATUS_DRAFT');
     $version->store();
     $datamap = $version->dataMap();
     $object_attribute = $datamap[$this->attribute];
     $object_attribute->fromString($new_value);
     $object_attribute->store();
     // Publish new version
     $operation_result = eZOperationHandler::execute('content', 'publish', array('object_id' => $content_object_id, 'version' => $version->attribute('version')));
     $db->commit();
     eZContentCacheManager::clearObjectViewCache($content_object_id);
     return $operation_result['status'] == 1;
 }