static function process() { $limit = 100; $offset = 0; $availableHandlers = eZNotificationEventFilter::availableHandlers(); do { $eventList = eZNotificationEvent::fetchUnhandledList(array('offset' => $offset, 'length' => $limit)); foreach ($eventList as $event) { $db = eZDB::instance(); $db->begin(); foreach ($availableHandlers as $handler) { if ($handler === false) { eZDebug::writeError("Notification handler does not exist: {$handlerKey}", __METHOD__); } else { $handler->handle($event); } } $itemCountLeft = eZNotificationCollectionItem::fetchCountForEvent($event->attribute('id')); if ($itemCountLeft == 0) { $event->remove(); } else { $event->setAttribute('status', eZNotificationEvent::STATUS_HANDLED); $event->store(); } $db->commit(); } eZContentObject::clearCache(); } while (count($eventList) == $limit); // If less than limit, we're on the last iteration eZNotificationCollection::removeEmpty(); }
function runOperation(&$node) { $object = $node->attribute('object'); $object_id = $object->attribute('id'); $objectLocales = $object->attribute('available_languages'); // If the alternative locale does not exist for object, create it if (!in_array($this->altLocale, $objectLocales)) { // The only translation is in locate to be removed - create a version in another locale first. echo "Copying the single translation in " . $this->remLocale . " to " . $this->altLocale . " so former could be removed.\n"; $newVersion = $object->createNewVersionIn($this->altLocale, $this->remLocale, false, true, eZContentObjectVersion::STATUS_DRAFT); $publishResult = eZOperationHandler::execute('content', 'publish', array('object_id' => $object_id, 'version' => $newVersion->attribute('version'))); eZContentObject::clearCache(); $object = eZContentObject::fetch($object_id); } // Change objects main language to alternative language, if its current main language is to be removed. if ($object->attribute('initial_language_code') == $this->remLocale) { eZContentObject::clearCache(); $object = eZContentObject::fetch($object_id); echo "Switching initial language to {$this->altLocale} so that " . $this->remLocale . " could be removed.\n"; $updateResult = eZContentOperationCollection::updateInitialLanguage($object_id, $this->altLangID); $object->store(); eZContentObject::clearCache(); $object = eZContentObject::fetch($object_id); } // Now it should be safe to remove translation. return $object->removeTranslation($this->remLangID); }
function runOperation(&$node) { $object = $node->attribute('object'); $object_id = $object->attribute('id'); $objectLocales = $object->attribute('available_languages'); // If the new locale does not exist for object, create it if (!in_array($this->newLocale, $objectLocales)) { // Create a new version of the original in another locale. $cli = eZCLI::instance(); $cli->output("Copying the single translation in {$this->orgLocale} to {$this->newLocale}"); $newVersion = $object->createNewVersionIn($this->newLocale, $this->orgLocale, false, true, eZContentObjectVersion::STATUS_DRAFT); $publishResult = eZOperationHandler::execute('content', 'publish', array('object_id' => $object_id, 'version' => $newVersion->attribute('version'))); eZContentObject::clearCache(); $object = eZContentObject::fetch($object_id); } return true; }
/** * @param array $contentObjectList */ function checkObjectVisibility ($contentObjectList) { foreach ( array_keys($contentObjectList) as $index ) { $contentObjectId = $contentObjectList[$index]['contentobject_id']; echo "Checking visibility of object $contentObjectId\n"; $articleContentObject = eZContentObject::fetch($contentObjectId); if ( $articleContentObject && $articleContentObject->attribute('class_identifier') === "article" ) ObjectVisibilityManager::updateGlobalLimitation($articleContentObject); unset($articleContentObject); eZContentObject::clearCache(); } }
} else { $data['status'] = 'error'; $data['message'] = "Attribute not found"; $data['header'] = "HTTP/1.1 404 Not Found"; } } else { $data['status'] = 'error'; $data['message'] = "Current user can not edit object"; $data['header'] = "HTTP/1.1 403 Forbidden"; } } else { $data['status'] = 'error'; $data['message'] = "Object not found"; $data['header'] = "HTTP/1.1 404 Not Found"; } if ($data['status'] == 'success') { eZContentObject::clearCache(array($objectId)); $object = eZContentObject::fetch($objectId); $attributes = $object->fetchAttributesByIdentifier(array($attributeIdentifier)); $attribute = array_shift($attributes); $tpl = eZTemplate::factory(); $datatypeString = $attribute->attribute('data_type_string'); $tpl->setVariable('attribute', $attribute); $data['newValue'] = $tpl->fetch('design:content/datatype/view/' . $datatypeString . '.tpl'); unset($data['message']); } header($data['header']); unset($data['header']); header('Content-Type: application/json'); echo json_encode($data); eZExecution::cleanExit();
public static function createMobileSitemap() { eZDebug::writeDebug("Generating mobile sitemap ...", __METHOD__); $cli = eZCLI::instance(); if (!$isQuiet) { $cli->output("Generating mobile sitemap for siteaccess " . $GLOBALS['eZCurrentAccess']['name'] . " \n"); } $ini = eZINI::instance('site.ini'); $xrowsitemapINI = eZINI::instance('xrowsitemap.ini'); // Get the Sitemap's root node $rootNode = self::rootNode(); // Settings variables if ($xrowsitemapINI->hasVariable('MobileSitemapSettings', 'ClassFilterType') and $xrowsitemapINI->hasVariable('MobileSitemapSettings', 'ClassFilterArray')) { $params2 = array('ClassFilterType' => $xrowsitemapINI->variable('MobileSitemapSettings', 'ClassFilterType'), 'ClassFilterArray' => $xrowsitemapINI->variable('MobileSitemapSettings', 'ClassFilterArray')); } $max = self::MAX_PER_FILE; $limit = 50; // Fetch the content tree $params = array('SortBy' => array(array('depth', true), array('published', true))); if (isset($params2)) { $params = array_merge($params, $params2); } $subtreeCount = eZContentObjectTreeNode::subTreeCountByNodeID($params, $rootNode->NodeID); if ($subtreeCount == 1) { $cli->output("No Items found under RootNode {$rootNode->NodeID}."); } if (!$isQuiet) { $amount = $subtreeCount + 1; // +1 is root node $cli->output("Adding {$amount} nodes to the sitemap for RootNode {$rootNode->NodeID}."); $output = new ezcConsoleOutput(); $bar = new ezcConsoleProgressbar($output, $amount); } $addPrio = false; if ($xrowsitemapINI->hasVariable('Settings', 'AddPriorityToSubtree') and $xrowsitemapINI->variable('Settings', 'AddPriorityToSubtree') == 'true') { $addPrio = true; } $sitemap = new xrowMobileSitemap(); // Generate Sitemap /** START Adding the root node **/ $object = $rootNode->object(); $meta = xrowMetaDataFunctions::fetchByObject($object); $extensions = array(); $extensions[] = new xrowSitemapItemModified($rootNode->attribute('modified_subnode')); $url = $rootNode->attribute('url_alias'); eZURI::transformURI($url); if ($xrowsitemapINI->hasVariable('SitemapSettings', 'MobileDomainName') && $xrowsitemapINI->hasVariable('SitemapSettings', 'MobileDomainName') != '') { $mobileDomain = $xrowsitemapINI->variable('SitemapSettings', 'MobileDomainName'); } else { $mobileDomain = self::domain(); } $url = 'http://' . $mobileDomain . $url; if ($meta and $meta->sitemap_use != '0') { $extensions[] = new xrowSitemapItemFrequency($meta->change); $extensions[] = new xrowSitemapItemPriority($meta->priority); $sitemap->add($url, $extensions); } elseif ($meta === false and $xrowsitemapINI->variable('Settings', 'AlwaysAdd') == 'enabled') { if ($addPrio) { $extensions[] = new xrowSitemapItemPriority('1'); } $sitemap->add($url, $extensions); } if (isset($bar)) { $bar->advance(); } /** END Adding the root node **/ $max = min($max, $subtreeCount); $params['Limit'] = min($max, $limit); $params['Offset'] = 0; while ($params['Offset'] < $max) { $nodeArray = eZContentObjectTreeNode::subTreeByNodeID($params, $rootNode->NodeID); foreach ($nodeArray as $subTreeNode) { eZContentLanguage::expireCache(); $meta = xrowMetaDataFunctions::fetchByNode($subTreeNode); $extensions = array(); $extensions[] = new xrowSitemapItemModified($subTreeNode->attribute('modified_subnode')); $url = $subTreeNode->attribute('url_alias'); eZURI::transformURI($url); $url = 'http://' . $mobileDomain . $url; if ($meta and $meta->sitemap_use != '0') { $extensions[] = new xrowSitemapItemFrequency($meta->change); $extensions[] = new xrowSitemapItemPriority($meta->priority); $sitemap->add($url, $extensions); } elseif ($meta === false and $xrowsitemapINI->variable('Settings', 'AlwaysAdd') == 'enabled') { if ($addPrio) { $rootDepth = $rootNode->attribute('depth'); $prio = 1 - ($subTreeNode->attribute('depth') - $rootDepth) / 10; if ($prio > 0) { $extensions[] = new xrowSitemapItemPriority($prio); } } $sitemap->add($url, $extensions); } if (isset($bar)) { $bar->advance(); } } eZContentObject::clearCache(); $params['Offset'] += $params['Limit']; } // write XML Sitemap to file $dir = eZSys::storageDirectory() . '/sitemap/' . self::domain(); if (!is_dir($dir)) { mkdir($dir, 0777, true); } $filename = $dir . '/' . xrowSitemap::BASENAME . '_' . self::FILETYP_MOBILE . '_' . $GLOBALS['eZCurrentAccess']['name'] . '.' . xrowSitemap::SUFFIX; $sitemap->save($filename); /** * @TODO How will this work with cluster? if ( function_exists( 'gzencode' ) and $xrowsitemapINI->variable( 'MobileSitemapSettings', 'Gzip' ) == 'enabled' ) { $content = file_get_contents( $filename ); $content = gzencode( $content ); file_put_contents( $filename . '.gz', $content ); unlink( $filename ); $filename .= '.gz'; } **/ if (!$isQuiet) { $cli->output("\n"); $cli->output("Mobile sitemap {$filename} for siteaccess " . $GLOBALS['eZCurrentAccess']['name'] . " has been generated.\n"); } }
$childResponse['url'] = 'content/view/full/' . $childResponse['node_id']; } eZURI::transformURI($childResponse['url']); $childResponse['modified_subnode'] = $child->ModifiedSubNode; $childResponse['languages'] = $childObject->availableLanguages(); $childResponse['is_hidden'] = $child->IsHidden; $childResponse['is_invisible'] = $child->IsInvisible; if ($createHereMenu == 'full') { $childResponse['class_list'] = array(); foreach ($child->canCreateClassList() as $class) { $childResponse['class_list'][] = $class['id']; } } $response['children'][] = $childResponse; unset($object); eZContentObject::clearCache(); } $httpCharset = eZTextCodec::httpCharset(); $jsonText = arrayToJSON($response); $codec = eZTextCodec::instance($httpCharset, 'unicode'); $jsonTextArray = $codec->convertString($jsonText); $jsonText = ''; foreach ($jsonTextArray as $character) { if ($character < 128) { $jsonText .= chr($character); } else { $jsonText .= '\\u' . str_pad(dechex($character), 4, '0000', STR_PAD_LEFT); } } header('Expires: ' . gmdate('D, d M Y H:i:s', time() + MAX_AGE) . ' GMT'); header('Cache-Control: cache, max-age=' . MAX_AGE . ', post-check=' . MAX_AGE . ', pre-check=' . MAX_AGE);
function installContentObjects( $objectNodes, $topNodeListNode, &$installParameters ) { if ( isset( $installParameters['user_id'] ) ) $userID = $installParameters['user_id']; else $userID = eZUser::currentUserID(); $handlerType = $this->handlerType(); $firstInstalledID = null; foreach( $objectNodes as $objectNode ) { $realObjectNode = $this->getRealObjectNode( $objectNode ); // Cycle until we reach an element where error has occured. // If action has been choosen, try install this item again, else skip it. if ( isset( $installParameters['error']['error_code'] ) && !$this->isErrorElement( $realObjectNode->getAttribute( 'remote_id' ), $installParameters ) ) { continue; } //we are here, it means we'll try to install some object. if ( !$firstInstalledID ) { $firstInstalledID = $realObjectNode->getAttribute( 'remote_id' ); } $newObject = eZContentObject::unserialize( $this->Package, $realObjectNode, $installParameters, $userID, $handlerType ); if ( !$newObject ) { return false; } if ( is_object( $newObject ) ) { eZContentObject::clearCache( $newObject->attribute( 'id' ) ); unset( $newObject ); } unset( $realObjectNode ); if ( isset( $installParameters['error'] ) && count( $installParameters['error'] ) ) { $installParameters['error'] = array(); } } $this->installSuspendedNodeAssignment( $installParameters ); $this->installSuspendedObjectRelations( $installParameters ); // Call postUnserialize on all installed objects foreach( $objectNodes as $objectNode ) { if ( $objectNode->localName == 'object' ) { $remoteID = $objectNode->getAttribute( 'remote_id' ); } else { $remoteID = substr( $objectNode->getAttribute( 'filename' ), 7, 32 ); } // Begin from the object that we started from in the previous cycle if ( $firstInstalledID && $remoteID != $firstInstalledID ) { continue; } else { $firstInstalledID = null; } $object = eZContentObject::fetchByRemoteID( $remoteID ); if ( is_object( $object ) ) { $object->postUnserialize( $this->Package ); eZContentObject::clearCache( $object->attribute( 'id' ) ); } unset( $object ); } return true; }
static function removeSubtrees($deleteIDArray, $moveToTrash = true, $infoOnly = false) { $moveToTrashAllowed = true; $deleteResult = array(); $totalChildCount = 0; $totalLoneNodeCount = 0; $canRemoveAll = true; $hasPendingObject = false; $db = eZDB::instance(); $db->begin(); foreach ($deleteIDArray as $deleteID) { $node = eZContentObjectTreeNode::fetch($deleteID); if ($node === null) { continue; } $object = $node->attribute('object'); if ($object === null) { continue; } $class = $object->attribute('content_class'); $canRemove = $node->attribute('can_remove'); $canRemoveSubtree = true; $nodeID = $node->attribute('node_id'); $nodeName = $object->attribute('name'); $childCount = 0; $newMainNodeID = false; $objectNodeCount = 0; $readableChildCount = 0; if ($canRemove) { $moveToTrashAllowed = $node->isNodeTrashAllowed(); $readableChildCount = $node->subTreeCount(array('Limitation' => array())); $childCount = $node->subTreeCount(array('IgnoreVisibility' => true)); $totalChildCount += $childCount; $allAssignedNodes = $object->attribute('assigned_nodes'); $objectNodeCount = count($allAssignedNodes); // We need to find a new main node ID if we are trying // to remove the current main node. if ($node->attribute('main_node_id') == $nodeID) { if (count($allAssignedNodes) > 1) { foreach ($allAssignedNodes as $assignedNode) { $assignedNodeID = $assignedNode->attribute('node_id'); if ($assignedNodeID == $nodeID) { continue; } $newMainNodeID = $assignedNodeID; break; } } } if ($infoOnly) { // Find the number of items in the subtree we are allowed to remove // if this differs from the total count it means we have items we cannot remove // We do this by fetching the limitation list for content/remove // and passing it to the subtree count function. $currentUser = eZUser::currentUser(); $accessResult = $currentUser->hasAccessTo('content', 'remove'); if ($accessResult['accessWord'] == 'limited') { $limitationList = $accessResult['policies']; $removeableChildCount = $node->subTreeCount(array('Limitation' => $limitationList, 'IgnoreVisibility' => true)); $canRemoveSubtree = $removeableChildCount == $childCount; $canRemove = $canRemoveSubtree; } //check if there is sub object in pending status $limitCount = 100; $offset = 0; while (1) { $children = $node->subTree(array('Limitation' => array(), 'SortBy' => array('path', false), 'Offset' => $offset, 'Limit' => $limitCount, 'IgnoreVisibility' => true, 'AsObject' => false)); // fetch pending node assignment(pending object) $idList = array(); //add node itself into idList if ($offset === 0) { $idList[] = $nodeID; } foreach ($children as $child) { $idList[] = $child['node_id']; } if (count($idList) === 0) { break; } $pendingChildCount = eZNodeAssignment::fetchChildCountByVersionStatus($idList, eZContentObjectVersion::STATUS_PENDING); if ($pendingChildCount !== 0) { // there is pending object $hasPendingObject = true; break; } $offset += $limitCount; } } // We will only remove the subtree if are allowed // and are told to do so. if ($canRemove and !$infoOnly) { $moveToTrashTemp = $moveToTrash; if (!$moveToTrashAllowed) { $moveToTrashTemp = false; } // Remove children, fetching them by 100 to avoid memory overflow. // removeNodeFromTree -> removeThis handles cache clearing while (1) { // We should remove the latest subitems first, // so we should fetch subitems sorted by 'path_string' DESC $children = $node->subTree(array('Limitation' => array(), 'SortBy' => array('path', false), 'Limit' => 100, 'IgnoreVisibility' => true)); if (!$children) { break; } foreach ($children as $child) { $child->removeNodeFromTree($moveToTrashTemp); eZContentObject::clearCache(); } } $node->removeNodeFromTree($moveToTrashTemp); } } if (!$canRemove) { $canRemoveAll = false; } // Do not create info list if we are removing subtrees if (!$infoOnly) { continue; } $soleNodeCount = $node->subtreeSoleNodeCount(); $totalLoneNodeCount += $soleNodeCount; if ($objectNodeCount <= 1) { ++$totalLoneNodeCount; } $item = array("nodeName" => $nodeName, "childCount" => $childCount, "additionalWarning" => '', 'node' => $node, 'object' => $object, 'class' => $class, 'node_name' => $nodeName, 'child_count' => $childCount, 'object_node_count' => $objectNodeCount, 'sole_node_count' => $soleNodeCount, 'can_remove' => $canRemove, 'can_remove_subtree' => $canRemoveSubtree, 'real_child_count' => $readableChildCount, 'new_main_node_id' => $newMainNodeID); $deleteResult[] = $item; } $db->commit(); if (!$infoOnly) { return true; } if ($moveToTrashAllowed and $totalLoneNodeCount == 0) { $moveToTrashAllowed = false; } return array('move_to_trash' => $moveToTrashAllowed, 'total_child_count' => $totalChildCount, 'can_remove_all' => $canRemoveAll, 'delete_list' => $deleteResult, 'has_pending_object' => $hasPendingObject, 'reverse_related_count' => eZContentObjectTreeNode::reverseRelatedCount($deleteIDArray)); }
function doDeliveries($quiet = false) { $cli = eZCLI::instance(); $issueLimit = 5; // Number of issues the script will process each time $deliveredCount = 0; $deliveryLimit = 200; // Number of deliveries the script will do each time. Should be multiples of 50 $newsletterIni = eZINI::instance('jajnewsletter.ini'); $newsletterIssuesNodeID = $newsletterIni->variable('ContentSettings', 'NewsletterIssuesNode'); $subscriptionUsersNodeID = $newsletterIni->variable('ContentSettings', 'SubscriptionUsersNode'); $fromName = $newsletterIni->variable('NewsletterSettings', 'FromName'); $fromEmail = $newsletterIni->variable('NewsletterSettings', 'FromEmail'); $replyTo = $newsletterIni->variable('NewsletterSettings', 'ReplyTo'); // Get list of newsletter issues with status In Progress //$newsletterIssues =& eZContentObjectTreeNode::subTreeByNodeID( $newsletterIssues =& eZContentObjectTreeNode::subTree(array('ClassFilterType' => 'include', 'ClassFilterArray' => array('newsletter_issue'), 'AttributeFilter' => array(array('newsletter_issue/status', '=', JAJ_NEWSLETTER_ISSUE_STATUS_PENDING)), 'Limit' => $issueLimit), $newsletterIssuesNodeID); if (!$quiet) { $cli->output('Newsletter issues awating delivery: ' . count($newsletterIssues) . ' (' . $issueLimit . ' max)'); } foreach ($newsletterIssues as $issue) { // Get newsletter and prepare $issueObject = $issue->object(); $issueDatamap = $issueObject->dataMap(); $newsletterSubject = $issueDatamap['subject']->content(); if (!$quiet) { $cli->output(); $cli->output('Delivering newsletter \'' . $newsletterSubject . '\' (Object id: ' . $issueObject->ID . ')'); } $newsletterBody = JAJNewsletterOperations::prepareNewsletterIssue($issueObject); if ($newsletterBody == false) { if (!$quiet) { $cli->notice('Failed to generate newsletter \'' . $newsletterSubject . '\' (Object id: ' . $issueObject->ID . ')'); } continue; } // Go though users in delivery que in batch and deliver newsletter $userLimit = 50; while (true) { // Get users in delivery que for current newsletteer // TODO: Should only get items where jajdelivery.tstamp > 1 hour or something //$userNodes =& eZContentObjectTreeNode::subTreeByNodeID( $userNodes =& eZContentObjectTreeNode::subTree(array('ClassFilterType' => 'include', 'ClassFilterArray' => array('subscription_user'), 'ExtendedAttributeFilter' => array(id => 'jajdeliveryfilter', params => array('newsletter_object_id' => $issueObject->ID, 'status' => array(JAJ_NEWSLETTER_DELIVERY_STATUS_PENDING))), 'Limit' => $userLimit, 'Limitation' => array()), $subscriptionUsersNodeID); $userCount = count($userNodes); if (!$quiet) { $cli->output(' Users found for batch delivery: ' . $userCount . ' (' . $userLimit . ' max in batch)'); } foreach ($userNodes as $userNode) { $userObject = $userNode->object(); $userDatamap = $userObject->dataMap(); $userEmail = $userDatamap['email']->content(); if (!$quiet) { $cli->output(' Delivereing to: ' . $userEmail, false); } $htmlNewsletter = $newsletterBody['html']; $plainNewsletter = $newsletterBody['plain']; $htmlNewsletter = str_replace("__remote_id", $userObject->remoteID(), $htmlNewsletter); $htmlNewsletter = str_replace("__object_id", $userObject->ID, $htmlNewsletter); $plainNewsletter = str_replace("__remote_id", $userObject->remoteID(), $plainNewsletter); $plainNewsletter = str_replace("__object_id", $userObject->ID, $plainNewsletter); $newsletterDeliveryResult = JAJNewsletterOperations::deliver($newsletterSubject, $htmlNewsletter, $plainNewsletter, $fromName, $fromEmail, $replyTo, $userEmail); $deliveryResult = JAJDelivery::fetchDelivery($issueObject->ID, $userObject->ID); $delivery = $deliveryResult['result']; $delivery->setAttribute('tstamp', time()); if ($newsletterDeliveryResult) { if (!$quiet) { $cli->output(' => OK'); } $delivery->setAttribute('status', JAJ_NEWSLETTER_DELIVERY_STATUS_SENT); } else { $tries = $delivery->attribute('tries') + 1; $delivery->setAttribute('tries', $tries); if ($tries >= 3) { $delivery->setAttribute('status', JAJ_NEWSLETTER_DELIVERY_STATUS_FAILED); } if (!$quiet) { $cli->output(' => FAILED, tries: ' . $tries); } } $delivery->sync(); $deliveredCount++; } eZContentObject::clearCache(); if ($userCount < $userLimit || $deliveredCount >= $deliveryLimit) { break; } } if ($deliveredCount >= $deliveryLimit) { if (!$quiet) { $cli->output('Reached delivery limit for script (' . $deliveredCount . '/' . $deliveryLimit . ')'); } break; } // Change status to archived if delivery que for newsletter is empty if (JAJDelivery::emptyDeliveryQue($issueObject->ID)) { if (!$quiet) { $cli->output('Delivery que for newsletter empty, changing status to archived'); } $status = $issueDatamap["status"]; $status->setAttribute('data_text', JAJ_NEWSLETTER_ISSUE_STATUS_ARCHIVED); $status->sync(); } } }
/** * Will clear current content object cache and reset dataMap. * Avoids useless memory consumption and allows to "refresh" content object. * Warning ! Further call to object attributes will do new DB queries. * @see eZContentObject::clearCache() * @see eZContentObject::resetDataMap() */ public function flush() { if ($this->contentObject instanceof eZContentObject) { $objectID = $this->contentObject->attribute('id'); $this->contentObject->resetDataMap(); eZContentObject::clearCache(array($objectID)); } }
public function run($remove = false, $useStateHashes = true, $update = true, $create = true) { $contentClass = $this->config->getContentClass(); $allOjectsInFeedRemoteIDs = array(); $dataList = $this->config->getDataList(); $dataListCount = count($dataList); if ($dataListCount > 0) { foreach ($dataList as $key => &$objectData) { $memoryUsage = number_format(memory_get_usage(true) / (1024 * 1024), 2); $this->debug(number_format($key / $dataListCount * 100, 2) . '% (' . ($key + 1) . '/' . $dataListCount . '), Memory usage: ' . $memoryUsage . ' Mb', array('red')); $objectData['remoteID'] = $this->config->getObjectRemoteID($objectData); $objectData['mainParentNodeID'] = $this->config->getMainParentNodeID($objectData); $objectData['adittionalParentNodeIDs'] = (array) $this->config->getAdittionalParentNodeIDs($objectData); $objectData['attributes'] = (array) $this->config->transformObjectAttributes($objectData); $objectData['language'] = $this->config->getLanguage($objectData); $objectData['versionStatus'] = $this->config->getVersionStatus($objectData); $objectData['mainNodePriority'] = $this->config->getMainNodePriority($objectData); $objectData['visibility'] = $this->config->isVisible($objectData); $currentStateHash = $this->config->getStateHash($objectData); $allOjectsInFeedRemoteIDs[] = $objectData['remoteID']; $object = eZContentObject::fetchByRemoteID($objectData['remoteID']); $result = $this->config->preProcessCallback($object, $objectData); if ($result === false) { $this->debug('[Skipped by preProcessCallback] Remote ID: "' . $objectData['remoteID'] . '"', array('blue')); $this->skip($object, $objectData); continue; } $skipped = false; if ($object instanceof eZContentObject) { if ($update === false) { $this->debug('[Skipped] "' . $object->attribute('name') . '"', array('blue')); $this->skip($object, $objectData); $skipped = true; } else { $storedStateHash = nxcImportStateHash::get($objectData['remoteID']); if ($currentStateHash == $storedStateHash && $useStateHashes === true) { $this->debug('[Skipped] "' . $object->attribute('name') . '" (Node ID: ' . $object->attribute('main_node_id') . ')', array('blue')); $this->skip($object, $objectData); $skipped = true; } else { $parentNode = false; if ($objectData['mainParentNodeID'] !== false) { $parentNode = eZContentObjectTreeNode::fetch($objectData['mainParentNodeID']); } if ($objectData['mainParentNodeID'] !== false && $parentNode instanceof eZContentObjectTreeNode === false) { $this->remove($object, $objectData); nxcImportStateHash::remove($object->attribute('remote_id')); $this->pcHandler->removeObject($object); } else { $params = array('object' => $object, 'attributes' => $objectData['attributes'], 'additionalParentNodeIDs' => $objectData['adittionalParentNodeIDs'], 'visibility' => (bool) $objectData['visibility']); if ($objectData['mainParentNodeID'] !== false) { $params['parentNode'] = $parentNode; } $this->pcHandler->updateObject($params); $this->update($object, $objectData); nxcImportStateHash::update($objectData['remoteID'], $currentStateHash); $object->resetDataMap(); eZContentObject::clearCache($object->attribute('id')); } } } } else { if ($create === false) { $this->debug('[Skipped]', array('blue')); $this->skip($object, $objectData); $skipped = true; } else { $object = $this->pcHandler->createObject(array('class' => $contentClass, 'parentNodeID' => $objectData['mainParentNodeID'], 'attributes' => $objectData['attributes'], 'remoteID' => $objectData['remoteID'], 'additionalParentNodeIDs' => $objectData['adittionalParentNodeIDs'], 'languageLocale' => isset($objectData['language']) ? $objectData['language'] : false, 'visibility' => (bool) $objectData['visibility'])); if ($object instanceof eZContentObject) { $this->create($object, $objectData); nxcImportStateHash::update($objectData['remoteID'], $currentStateHash); if ($objectData['mainNodePriority'] !== false) { $mainNode = $object->attribute('main_node'); $mainNode->setAttribute('priority', $objectData['mainNodePriority']); $mainNode->store(); } $object->resetDataMap(); eZContentObject::clearCache($object->attribute('id')); } } } $this->config->postProcessCallback($object, $objectData, $skipped); } $allOjectsInFeedRemoteIDs = array_unique($allOjectsInFeedRemoteIDs); if ($remove && count($allOjectsInFeedRemoteIDs) > 0) { $publishedObjects = $contentClass->objectList(); foreach ($publishedObjects as $object) { if (in_array($object->attribute('remote_id'), $allOjectsInFeedRemoteIDs) === false) { $this->remove($object, $objectData); nxcImportStateHash::remove($object->attribute('remote_id')); $this->pcHandler->removeObject($object); } } } } }
/** * @param $courseId * @return array */ protected static function fetchNodeAndAppFromCourseId( $courseId ) { $nodeList = eZFunctionHandler::execute( 'content', 'tree', array( 'parent_node_id' => 2, 'attribute_filter' => array( array( 'article/publisher_internal_id', '=', $courseId ) ), 'class_filter_type' => 'include', 'class_filter_array' => array( 'article' ), 'main_node_only' => false, ) ); foreach ( $nodeList as $node ) { $application = NodeTool::getApplicationFromNode($node); if ( $application ) { $isCertificate = SolrSafeOperatorHelper::getCustomParameter( $application, 'HasCertificates', 'application' ); if ( $isCertificate ) { eZContentObject::clearCache(); return array( 'application' => $application, 'node' => $node, ); } } } eZContentObject::clearCache(); return false; }
/** * 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(); } }
/** * @param eZContentObjectTreeNode $parentNode * @param $isParentInvisible */ public static function spreadGlobalLimitationChange( $parentNode, $isParentInvisible ) { $db = eZDB::instance(); $childQuery = "SELECT contentobject_id FROM ezcontentobject_tree where depth='%s' and path_string='%s%%'"; $children = $db->arrayQuery(sprintf( $childQuery, $parentNode->attribute('depth') + 1, $parentNode->attribute('path_string') )); foreach( $children as $child ) { $childObjectId = $child['contentobject_id']; $child = eZContentObject::fetch($childObjectId); if ( $child instanceof eZContentObject ) self::updateGlobalLimitation($childObjectId, $isParentInvisible); unset($child); eZContentObject::clearCache(array($childObjectId)); } }
function transformNode(eZContentObjectTreeNode $node) { set_time_limit(0); $row = array(); $object = $node->attribute('object'); if (!$object instanceof eZContentObject) { return null; } $data_map = $object->dataMap(); //0 //CIG //cig nillable="false" $cig = self::$ERRORS_IN_FIELD; if ($data_map['cig']) { $cig = $data_map['cig']->content(); //deve essere di 10 caratteri if (strlen($cig) != 10) { $cig = self::$ERRORS_IN_FIELD; } } $row[] = $cig; //--------------------------------------------------------------------------- //1 //FLAG_CONTRATTO_SENZA_CIG if ($cig) { $row[] = 'N'; } else { $row[] = 'S'; } //--------------------------------------------------------------------------- //2 //ANNO_PUBBLICAZIONE //nillable="false $anno_pubblicazione = self::$ERRORS_IN_FIELD; if ($this->anno_pubblicazione) { $anno_pubblicazione = $this->anno_pubblicazione; if (strlen($anno_pubblicazione) != 4) { $anno_pubblicazione = self::$ERRORS_IN_FIELD; } } $row[] = $anno_pubblicazione; //--------------------------------------------------------------------------- //3 //OGGETTO //oggetto nillable="false" $oggetto = ''; if ($data_map['oggetto']) { $oggetto = $data_map['oggetto']->content(); //xsd:maxLength value="500" if (strlen($oggetto) > 500) { $oggetto = self::$ERRORS_IN_FIELD; } } $row[] = $oggetto; //--------------------------------------------------------------------------- //4 //SCELTA_CONTRAENTE //sceltaContraente nillable="false" //select a scelta obbligata di valori indicati nella documentazione $scelta_contraente = self::$ERRORS_IN_FIELD; if ($data_map['scelta_contraente']) { if ($data_map['scelta_contraente']->title()) { $scelta_contraente = $data_map['scelta_contraente']->title(); //tengo solo numeri come previsto da documentazione $scelta_contraente = substr($scelta_contraente, 0, 2); } } $row[] = $scelta_contraente; //--------------------------------------------------------------------------- //5 //IMPORTO_GARA $importo_gara = self::$ERRORS_IN_FIELD; if ($data_map['importo_gara']) { if ($data_map['importo_gara']->content()) { $importo_gara = $data_map['importo_gara']->content(); if ($importo_gara instanceof eZPrice) { if (!$this->checkImporti($importo_gara->Price)) { $importo_gara = self::$ERRORS_IN_FIELD; } else { $importo_gara = $importo_gara->Price; } } else { $importo_gara = self::$ERRORS_IN_FIELD; } } } $row[] = $importo_gara; //--------------------------------------------------------------------------- //6 //IMPORTO_AGGIUDICAZIONE $importo_aggiudicazione = ''; if ($data_map['importo_aggiudicazione']) { $importo_aggiudicazione = $data_map['importo_aggiudicazione']->content(); if ($importo_aggiudicazione instanceof eZPrice) { if (!$this->checkImporti($importo_aggiudicazione->Price)) { $importo_aggiudicazione = self::$ERRORS_IN_FIELD; } else { $importo_aggiudicazione = $importo_aggiudicazione->Price; } } else { $importo_aggiudicazione = self::$ERRORS_IN_FIELD; } } $row[] = $importo_aggiudicazione; //--------------------------------------------------------------------------- //7 //DATA_INIZIO $data_inizio = ''; if ($data_map['data_inizio']) { $data_inizio = date('d/m/Y', $data_map['data_inizio']->DataInt); } $row[] = $data_inizio; //--------------------------------------------------------------------------- //8 //DATA_ULTIMAZIONE $data_ultimazione = ''; if ($data_map['data_ultimazione']) { $data_ultimazione = date('d/m/Y', $data_map['data_ultimazione']->DataInt); } $row[] = $data_ultimazione; //--------------------------------------------------------------------------- //9 //IMPORTO_SOMME_LIQUIDATE $importo_somme_liquidate = ''; if ($data_map['importo_somme_liquidate']) { $importo_somme_liquidate = $data_map['importo_somme_liquidate']->content(); if ($importo_somme_liquidate instanceof eZPrice) { if (!$this->checkImporti($importo_somme_liquidate->Price)) { $importo_somme_liquidate = self::$ERRORS_IN_FIELD; } else { $importo_somme_liquidate = $importo_somme_liquidate->Price; } } else { $importo_somme_liquidate = self::$ERRORS_IN_FIELD; } } $row[] = $importo_somme_liquidate; //--------------------------------------------------------------------------- //10 //FLAG_COMPLETAMENTO $flag_completamento = ''; if ($data_map['flag_completamento']) { $flag_completamento = $data_map['flag_completamento']->content(); } if ($flag_completamento == 1) { $row[] = 'S'; } else { $row[] = 'N'; } //valorizzo i campi CF_AZIENDA;ID_GRUPPO;TIPO_PARTECIPAZIONE;ATTRIBUTO_INVITATA;ATRIBUTO_PARTECIPANTE;ATTRIBUTO_AGGIUDICATARIA //ripetendo le righe qualora ci siano più figure dello stesso tipo $anagrafiche = array(); //$this->id_gruppo++; $invitati_matrix = $data_map['invitati']->content(); $partecipanti_matrix = $data_map['partecipanti']->content(); $aggiudicatario_matrix = $data_map['aggiudicatari']->content(); $invitati_matrix_sequential = $invitati_matrix->Matrix['rows']['sequential']; $invitati_partecipanti_matrix = $partecipanti_matrix->Matrix['rows']['sequential']; $invitati_aggiudicatario_matrix = $aggiudicatario_matrix->Matrix['rows']['sequential']; //--------------------------------------------------------------------------- //invitati foreach ($invitati_matrix_sequential as $invitato) { $this->getDataFromMatrix($anagrafiche, $invitato, self::$INVIATO); } //--------------------------------------------------------------------------- //partecipanti foreach ($invitati_partecipanti_matrix as $partecipante) { $this->getDataFromMatrix($anagrafiche, $partecipante, self::$PARTECIPANTE); } //--------------------------------------------------------------------------- //aggiudicatari foreach ($invitati_aggiudicatario_matrix as $aggiudicatario) { $this->getDataFromMatrix($anagrafiche, $aggiudicatario, self::$AGGIUDICATARIO); } //DUPLICAZIONE RIGHE //creo tante righe quanto sono le anagrafiche foreach ($anagrafiche as $key => $anagrafica) { ksort($anagrafica); $values[] = array_merge($row, $anagrafica); } //gestione eventuali errori $this->manageErrors($values, $object); $object->resetDataMap(); eZContentObject::clearCache($object->attribute('id')); unset($data_map); return $values; }
/** * Iterate index counter * * @param int $count */ protected function iterate($count = false) { if (!$count) { $count = $this->Limit; } for ($iterateCount = 0; $iterateCount < $count; ++$iterateCount) { if (++$this->IterateCount > $this->ObjectCount) { break; } $this->Script->iterate($this->CLI, true); if ($this->IterateCount % 1000 === 0) { $this->CLI->output("\n" . 'Comitting and optimizing index ...'); $searchEngine = new eZSolr(); $searchEngine->optimize(); eZContentObject::clearCache(); } } }
public function refresh() { $this->object->clearCache(); $this->object = eZContentObject::fetch($this->id); $this->refreshAttributes(); }
/** * Initialize the attribute in the existing objects. * * @param mixed $objects not used, the existing objects are fetched if * necessary (depending on the datatype of the attribute). */ function initializeObjectAttributes( &$objects = null ) { $classAttributeID = $this->ID; $classID = $this->ContentClassID; $dataType = $this->attribute( 'data_type' ); if ( $dataType->supportsBatchInitializeObjectAttribute() ) { $db = eZDB::instance(); $data = array( 'contentobject_id' => 'a.contentobject_id', 'version' => 'a.version', 'contentclassattribute_id' => $classAttributeID, 'data_type_string' => "'" . $db->escapeString( $this->DataTypeString ) . "'", 'language_code' => 'a.language_code', 'language_id' => 'MAX(a.language_id)' ); $datatypeData = $dataType->batchInitializeObjectAttributeData( $this ); $data = array_merge( $data, $datatypeData ); $cols = implode( ', ', array_keys( $data ) ); $values = implode( ', ', $data ); $sql = "INSERT INTO ezcontentobject_attribute( $cols ) SELECT $values FROM ezcontentobject_attribute a, ezcontentobject o WHERE o.id = a.contentobject_id AND o.contentclass_id=$classID GROUP BY contentobject_id, version, language_code"; $db->query( $sql ); // update ids to keep them same with one attribute for different versions if( $db->databaseName() == 'mysql' ) { $updateSql = "UPDATE ezcontentobject_attribute, ( SELECT contentobject_id, language_code, version, contentclassattribute_id, MIN( id ) AS minid FROM ezcontentobject_attribute WHERE contentclassattribute_id = $classAttributeID GROUP BY contentobject_id, language_code, version, contentclassattribute_id ) t SET ezcontentobject_attribute.id = t.minid WHERE ezcontentobject_attribute.contentobject_id = t.contentobject_id AND ezcontentobject_attribute.language_code = t.language_code AND ezcontentobject_attribute.contentclassattribute_id = $classAttributeID"; } else if( $db->databaseName() == 'postgresql' ) { $updateSql = "UPDATE ezcontentobject_attribute SET id=t.minid FROM ( SELECT contentobject_id, language_code, version, contentclassattribute_id, MIN( id ) AS minid FROM ezcontentobject_attribute WHERE contentclassattribute_id = $classAttributeID GROUP BY contentobject_id, language_code, version, contentclassattribute_id ) t WHERE ezcontentobject_attribute.contentobject_id = t.contentobject_id AND ezcontentobject_attribute.language_code = t.language_code AND ezcontentobject_attribute.contentclassattribute_id = $classAttributeID"; } else if( $db->databaseName() == 'oracle' ) { $updateSql = "UPDATE ezcontentobject_attribute a SET a.id = ( SELECT MIN( id ) FROM ezcontentobject_attribute b WHERE b.contentclassattribute_id = $classAttributeID AND b.contentobject_id = a.contentobject_id AND b.language_code = a.language_code ) WHERE a.contentclassattribute_id = $classAttributeID"; } else { $updateSql = ""; } $db->query( $updateSql ); } else { $limit = 1000; $offset = 0; while ( true ) { $contentObjects = eZContentObject::fetchSameClassList( $classID, true, $offset, $limit ); if ( empty( $contentObjects ) ) { break; } foreach ( $contentObjects as $object ) { $contentobjectID = $object->attribute( 'id' ); $objectVersions = $object->versions(); // the start version ID, to make sure one attribute in different version has same id. $startAttributeID = array(); foreach ( $objectVersions as $objectVersion ) { $translations = $objectVersion->translations( false ); $version = $objectVersion->attribute( 'version' ); foreach ( $translations as $translation ) { $objectAttribute = eZContentObjectAttribute::create( $classAttributeID, $contentobjectID, $version, $translation ); if( array_key_exists( $translation, $startAttributeID ) ) { $objectAttribute->setAttribute( 'id', $startAttributeID[$translation] ); } $objectAttribute->setAttribute( 'language_code', $translation ); $objectAttribute->initialize(); $objectAttribute->store(); if( !array_key_exists( $translation, $startAttributeID ) ) { $startAttributeID[$translation] = $objectAttribute->attribute( 'id' ); } $objectAttribute->postInitialize(); } } } $offset += $limit; eZContentObject::clearCache(); } } }
/** * @see ezfSolrDocumentFieldBase::getData() */ public function getData() { /** @var eZContentClassAttribute $contentClassAttribute */ $contentClassAttribute = $this->ContentObjectAttribute->attribute('contentclass_attribute'); switch ($contentClassAttribute->attribute('data_type_string')) { case 'ezobjectrelation': $returnArray = array(); /** @var eZContentObject $relatedObject */ $relatedObject = $this->ContentObjectAttribute->content(); if ($relatedObject) { $returnArray = $this->getArrayRelatedObject($relatedObject, $contentClassAttribute); eZContentObject::clearCache(array($relatedObject->attribute('id'))); } return $returnArray; break; case 'ezobjectrelationlist': $returnArray = array(); $returnArrayRelatedObject = array(); $content = $this->ContentObjectAttribute->content(); $relationCount = count($content['relation_list']); foreach ($content['relation_list'] as $relationItem) { $subObjectID = $relationItem['contentobject_id']; if (!$subObjectID) { continue; } /** @var eZContentObjectVersion $subObject */ $subObject = eZContentObjectVersion::fetchVersion($relationItem['contentobject_version'], $subObjectID); if (!$subObject instanceof eZContentObjectVersion) { $subObjectWrapper = eZContentObject::fetch($subObjectID); if ($subObjectWrapper instanceof eZContentObject) { $subObject = $subObjectWrapper->currentVersion(); } else { continue; } } /** @var eZContentObject $subContentObject */ $subContentObject = $subObject->attribute('contentobject'); if (intval($subContentObject->attribute('main_node_id')) == 0) { continue; } $metaAttributeValues = eZSolr::getMetaAttributesForObject($subContentObject); foreach ($metaAttributeValues as $metaInfo) { $submetaFieldName = ezfSolrDocumentFieldBase::generateSubmetaFieldName($metaInfo['name'], $contentClassAttribute); if (isset($returnArray[$submetaFieldName])) { $returnArray[$submetaFieldName] = array_merge($returnArray[$submetaFieldName], array(ezfSolrDocumentFieldBase::preProcessValue($metaInfo['value'], $metaInfo['fieldType']))); } else { $returnArray[$submetaFieldName] = array(ezfSolrDocumentFieldBase::preProcessValue($metaInfo['value'], $metaInfo['fieldType'])); } } $nodeAttributeValues = array(); $nodePathArray = array(); /** @var eZContentObjectTreeNode $contentNode */ foreach ($subContentObject->attribute('assigned_nodes') as $contentNode) { foreach (eZSolr::nodeAttributes() as $attributeName => $fieldType) { $nodeAttributeValues[] = array('name' => $attributeName, 'value' => $contentNode->attribute($attributeName), 'fieldType' => $fieldType); } $nodePathArray[] = $contentNode->attribute('path_array'); } //@todo questo non va... occorre correggere schema.xml? //foreach ( $nodeAttributeValues as $metaInfo ) //{ // $submetaFieldName = ezfSolrDocumentFieldBase::generateSubmetaFieldName( $metaInfo['name'], $contentClassAttribute ); // if ( isset( $returnArray[$submetaFieldName] ) ) // { // $returnArray[$submetaFieldName] = array_merge( $returnArray[$submetaFieldName], // array( ezfSolrDocumentFieldBase::preProcessValue( $metaInfo['value'], $metaInfo['fieldType'] ) ) ); // } // else // { // $returnArray[$submetaFieldName] = array( ezfSolrDocumentFieldBase::preProcessValue( $metaInfo['value'], $metaInfo['fieldType'] ) ); // } //} foreach ($nodePathArray as $pathArray) { $submetaFieldName = ezfSolrDocumentFieldBase::generateSubmetaFieldName('path', $contentClassAttribute); foreach ($pathArray as $pathNodeID) { if (isset($returnArray[$submetaFieldName])) { $returnArray[$submetaFieldName] = array_merge($returnArray[$submetaFieldName], array($pathNodeID)); } else { $returnArray[$submetaFieldName] = array($pathNodeID); } } } if ($relationCount < 200) { $returnArrayRelatedObject = $this->getArrayRelatedObject($subContentObject, $contentClassAttribute, $returnArrayRelatedObject); } else { $objectName = $subContentObject->name(false, $this->ContentObjectAttribute->attribute('language_code')); $fieldName = parent::generateSubattributeFieldName($contentClassAttribute, 'name', self::DEFAULT_SUBATTRIBUTE_TYPE); if (isset($returnArrayRelatedObject[$fieldName])) { $returnArrayRelatedObject[$fieldName][] = $objectName; } else { $returnArrayRelatedObject[$fieldName] = array($objectName); } } $returnArray = array_merge_recursive($returnArray, $returnArrayRelatedObject); eZContentObject::clearCache(array($subContentObject->attribute('id'))); } $defaultFieldName = parent::generateAttributeFieldName($contentClassAttribute, self::$subattributesDefinition[self::DEFAULT_SUBATTRIBUTE]); $stringFieldName = parent::generateAttributeFieldName($contentClassAttribute, 'string'); $returnArray[$defaultFieldName] = $this->getPlainTextRepresentation(); $returnArray[$stringFieldName] = $this->getPlainTextRepresentation(); $result = array(); foreach ($returnArray as $key => $value) { if (is_array($value)) { $value = array_unique($value); } $result[$key] = $value; } return $result; break; } return array(); }
/** * Aligns articles published under given publisher folder * @param eZContentObject $publisherObject */ function alignArticle( $publisherObject, $checkModified = false, $checkLocations = false, $checkLanguages = false, $checkHidden = false, $timingDelay = 0, $forceLast = 0, $sleepTime = 1 ) { echo "Starting treatment of publisher folder : " . $publisherObject->name() . "\n"; echo "Fetching solr informations\n"; $eZSolr = eZSearch::getEngine(); $offset = 0; $forced = 0; $limit = 200; $publisherNode = $publisherObject->mainNode(); $doCheck = $checkModified || $checkLocations || $checkLanguages || $checkHidden; $solrInfos = fetchSolrPublisherFolder ( $publisherNode, $checkModified, $checkLocations, $checkLanguages, $checkHidden, $sleepTime ); echo "Solr count : " . count($solrInfos) . "\n"; while ( true ) { $params = array( 'Offset' => $offset, 'Limit' => $limit, 'ClassFilterType' => 'include', 'ClassFilterArray' => array( 'article' ), 'LoadDataMap' => false, 'AsObject' => false, 'MainNodeOnly' => true, ); if ($forceLast > 0) $params['SortBy'] = array ( array('published', false ) ); $nodeList = $publisherNode->subtree( $params ); echo "\neZ Offset : $offset\n"; if ( count( $nodeList ) == 0 ) { break; } foreach ( $nodeList as $mainNode ) { $nodeId = $mainNode['node_id']; $objectId = $mainNode['contentobject_id']; $toUpdate = false; if ( $forceLast > 0 && $forced < $forceLast ) $toUpdate = true; elseif ( isset($solrInfos[$nodeId]) ) { if ( $doCheck ) { if ( $checkLanguages ) { $eZLanguages = eZContentObject::fetch($objectId)->languages(); $toUpdate = compareLanguages( array_keys($eZLanguages), $solrInfos[$nodeId]['languages'] ); showInvalidTranslations(array_keys($eZLanguages), $solrInfos[$nodeId]['languages'], $objectId); } if (!$toUpdate && $checkModified) $toUpdate = compareDates($mainNode['modified'], $solrInfos[$nodeId]['modified'], $timingDelay); if (!$toUpdate && $checkLocations) $toUpdate = compareLocations($objectId, $solrInfos[$nodeId]['locations']); if (!$toUpdate && $checkHidden) $toUpdate = compareHidden($objectId, $solrInfos[$nodeId]['hiddenCount'], $solrInfos[$nodeId]['notHiddenCount']); } unset($solrInfos[$nodeId]); } else $toUpdate = true; if ( $toUpdate ) { $return = $eZSolr->addObject( eZContentObject::fetch($objectId), false ); echo ( !$return ? '!' . $objectId . '!' : '+' ); } else echo '-'; $forced++; } $offset += $limit; eZContentObject::clearCache(); if ( $sleepTime > 0 ) sleep ($sleepTime); } echo "\nArticles in solr but unknown from eZPublish : " . count($solrInfos) . " articles\n"; }
if ($accountKey instanceof eZUserAccountKey) { // run the activation as in kernel/user/activate.php if (eZOperationHandler::operationIsAvailable('user_activation')) { $operationResult = eZOperationHandler::execute('user', 'activation', array('user_id' => $id, 'user_hash' => $accountKey->attribute('hash_key'), 'is_enabled' => true)); } else { eZUserOperationCollection::activation($id, $accountKey->attribute('hash_key'), true); } eZOperationHandler::execute('user', 'register', array('user_id' => $id)); $success[] = $id; } else { eZDebug::writeError("Unable to load the eZUserAccountKey object for user #{$id}", 'user/unactivated'); $errors[] = $id; } } if (!empty($success)) { eZContentObject::clearCache($success); } $tpl->setVariable('success_activate', empty($success) ? false : $success); $tpl->setVariable('errors_activate', empty($errors) ? false : $errors); } else { if ($Module->isCurrentAction('RemoveUsers')) { $UserIDs = (array) $Module->actionParameter('UserIDs'); foreach ($UserIDs as $id) { $object = eZContentObject::fetch($id); if ($object instanceof eZContentObject && eZUserAccountKey::fetchByUserID($id)) { $success[] = $object->attribute('name'); $object->purge(); } else { eZDebug::writeError("Unable to load the object and/or the eZUserAccountKey object for user #{$id}", 'user/unactivated'); $errors[] = $id; }
/** * Purges the image aliases of all ezimage attribute. The original image is * kept. * * @param array $cacheItem * @access public */ static function purgeImageAlias($cacheItem) { // 1. fetch ezcontentclass having an ezimage attribute // 2. fetch objects of these classes // 3. purge image alias for all version $imageContentClassAttributes = eZContentClassAttribute::fetchList(true, array('data_type' => 'ezimage', 'version' => eZContentClass::VERSION_STATUS_DEFINED)); $classIds = array(); $attributeIdentifiersByClass = array(); foreach ($imageContentClassAttributes as $ccAttr) { $identifier = $ccAttr->attribute('identifier'); $ccId = $ccAttr->attribute('contentclass_id'); if (!isset($attributeIdentifiersByClass[$ccId])) { $attributeIdentifiersByClass[$ccId] = array(); } $attributeIdentifiersByClass[$ccId][] = $identifier; $classIds[] = $ccId; } $subTreeParams = array('ClassFilterType' => 'include', 'ClassFilterArray' => $classIds, 'MainNodeOnly' => true, 'IgnoreVisibility' => true, 'LoadDataMap' => false, 'Limit' => 100, 'Offset' => 0); $count = 0; while (true) { $nodes = eZContentObjectTreeNode::subTreeByNodeID($subTreeParams, 1); if (empty($nodes)) { break; } foreach ($nodes as $node) { call_user_func($cacheItem['reporter'], '', $count); $object = $node->attribute('object'); self::purgeImageAliasForObject($cacheItem, $object, $attributeIdentifiersByClass[$object->attribute('contentclass_id')]); $count++; } eZContentObject::clearCache(); $subTreeParams['Offset'] += $subTreeParams['Limit']; } self::clearImageAlias($cacheItem); }
public function store( $fieldFilters = null ) { eZContentObject::clearCache( $this->attribute( 'contentobject_id' ) ); parent::store( $fieldFilters ); }
/** * Executes the purge operation * * @param int|null $iterationLimit Number of trashed objects to treat per iteration, use null to use a default value. * @param int|null $sleep Number of seconds to sleep between two iterations, use null to use a default value. * * @return bool True if the operation succeeded. */ public function run($iterationLimit = 100, $sleep = 1) { if ($iterationLimit === null) { $iterationLimit = 100; } if ($sleep === null) { $sleep = 1; } if ($this->memoryMonitoring) { eZLog::rotateLog($this->logFile); $this->cli->output("Logging memory usage to {$this->logFile}"); } $this->cli->output("Purging trash items:"); $this->monitor("start"); $db = eZDB::instance(); // Get user's ID who can remove subtrees. (Admin by default with userID = 14) $userCreatorID = eZINI::instance()->variable("UserSettings", "UserCreatorID"); $user = eZUser::fetch($userCreatorID); if (!$user) { $this->cli->error("Cannot get user object with userID = '{$userCreatorID}'.\n(See site.ini[UserSettings].UserCreatorID)"); return false; } eZUser::setCurrentlyLoggedInUser($user, $userCreatorID); $trashCount = eZContentObjectTrashNode::trashListCount(false); if (!$this->quiet) { $this->cli->output("Found {$trashCount} object(s) in trash."); } if ($trashCount == 0) { return true; } if ($this->script !== null) { $this->script->resetIteration($trashCount); } while ($trashCount > 0) { $this->monitor("iteration start"); $trashList = eZContentObjectTrashNode::trashList(array('Limit' => $iterationLimit), false); $db->begin(); foreach ($trashList as $trashNode) { $object = $trashNode->attribute('object'); $this->monitor("purge"); $object->purge(); if ($this->script !== null) { $this->script->iterate($this->cli, true); } } if (!$db->commit()) { $this->cli->output(); $this->cli->error('Trash has not been emptied, impossible to commit the whole transaction'); return false; } $trashCount = eZContentObjectTrashNode::trashListCount(false); if ($trashCount > 0) { eZContentObject::clearCache(); if ($sleep > 0) { sleep($sleep); } } $this->monitor("iteration end"); } if (!$this->quiet) { $this->cli->output('Trash successfully emptied'); } $this->monitor("end"); return true; }
public static function createMFSitemap() { eZDebug::writeDebug("Generating Standard Sitemap with images ...", __METHOD__); $cli = $GLOBALS['cli']; global $cli, $isQuiet; if (!$isQuiet) { $cli->output("Generating Sitemap for Siteaccess " . $GLOBALS['eZCurrentAccess']['name'] . " \n"); } $ini = eZINI::instance('site.ini'); $googlesitemapsINI = eZINI::instance('xrowsitemap.ini'); // Get the Sitemap's root node $contentINI = eZINI::instance('content.ini'); $rootNode = eZContentObjectTreeNode::fetch($contentINI->variable('NodeSettings', 'RootNode')); if (!$rootNode instanceof eZContentObjectTreeNode) { $cli->output("Invalid RootNode for Siteaccess " . $GLOBALS['eZCurrentAccess']['name'] . " \n"); continue; } // Settings variables if ($googlesitemapsINI->hasVariable('MFSitemapSettings', 'ClassFilterType') and $googlesitemapsINI->hasVariable('MFSitemapSettings', 'ClassFilterArray')) { $params2 = array('ClassFilterType' => $googlesitemapsINI->variable('MFSitemapSettings', 'ClassFilterType'), 'ClassFilterArray' => $googlesitemapsINI->variable('MFSitemapSettings', 'ClassFilterArray')); } $max = 49997; // max. amount of links in 1 sitemap $limit = 50; // Fetch the content tree $params = array('SortBy' => array(array('depth', true), array('published', false))); if (isset($params2)) { $params = array_merge($params, $params2); } $subtreeCount = eZContentObjectTreeNode::subTreeCountByNodeID($params, $rootNode->NodeID); if ($subtreeCount == 1) { $cli->output("No Items found under node #" . $contentINI->variable('NodeSettings', 'RootNode') . "."); } if (!$isQuiet) { $amount = $subtreeCount + 1; // +1 is root node $cli->output("Adding {$amount} nodes to the sitemap."); $output = new ezcConsoleOutput(); $bar = new ezcConsoleProgressbar($output, $amount); } $addPrio = false; if ($googlesitemapsINI->hasVariable('MFSitemapSettings', 'AddPriorityToSubtree') and $googlesitemapsINI->variable('MFSitemapSettings', 'AddPriorityToSubtree') == 'true') { $addPrio = true; } $sitemap = new xrowSitemap(); // Generate Sitemap /** START Adding the root node **/ $object = $rootNode->object(); $meta = xrowMetaDataFunctions::fetchByObject($object); $extensions = array(); $extensions[] = new xrowSitemapItemModified($rootNode->attribute('modified_subnode')); $url = $rootNode->attribute('url_alias'); eZURI::transformURI($url, true); if ($ini->variable('SiteAccessSettings', 'RemoveSiteAccessIfDefaultAccess') == 'enabled') { $url = 'http://' . xrowSitemapTools::domain() . $url; } else { $url = 'http://' . xrowSitemapTools::domain() . '/' . $GLOBALS['eZCurrentAccess']['name'] . $url; } if ($meta and $meta->googlemap != '0') { $extensions[] = new xrowSitemapItemFrequency($meta->change); $extensions[] = new xrowSitemapItemPriority($meta->priority); $sitemap->add($url, $extensions); } elseif ($meta === false and $googlesitemapsINI->variable('Settings', 'AlwaysAdd') == 'enabled') { if ($addPrio) { $extensions[] = new xrowSitemapItemPriority('1'); } $sitemap->add($url, $extensions); } if (isset($bar)) { $bar->advance(); } /** END Adding the root node **/ $max = min($max, $subtreeCount); $params['Limit'] = min($max, $limit); $params['Offset'] = 0; while ($params['Offset'] < $max) { $nodeArray = eZContentObjectTreeNode::subTreeByNodeID($params, $rootNode->NodeID); foreach ($nodeArray as $subTreeNode) { eZContentLanguage::expireCache(); $object = $subTreeNode->object(); $images = array(); $meta = xrowMetaDataFunctions::fetchByObject($object); $extensions = array(); $extensions[] = new xrowSitemapItemModified($subTreeNode->attribute('modified_subnode')); $url = $subTreeNode->attribute('url_alias'); eZURI::transformURI($url, true); if ($ini->variable('SiteAccessSettings', 'RemoveSiteAccessIfDefaultAccess') == 'enabled') { $url = 'http://' . xrowSitemapTools::domain() . $url; } else { $url = 'http://' . xrowSitemapTools::domain() . '/' . $GLOBALS['eZCurrentAccess']['name'] . $url; } if ($meta and $meta->googlemap != '0') { $extensions[] = new xrowSitemapItemFrequency($meta->change); $extensions[] = new xrowSitemapItemPriority($meta->priority); } elseif ($meta === false and $googlesitemapsINI->variable('Settings', 'AlwaysAdd') == 'enabled') { if ($addPrio) { $rootDepth = $rootNode->attribute('depth'); $prio = 1 - ($subTreeNode->attribute('depth') - $rootDepth) / 10; if ($prio > 0) { $extensions[] = new xrowSitemapItemPriority($prio); } } } $images = self::getSitemapImageItems($object); $sitemap->add($url, array_merge($extensions, $images)); if (isset($bar)) { $bar->advance(); } } eZContentObject::clearCache(); $params['Offset'] += $params['Limit']; } // write XML Sitemap to file $dir = eZSys::storageDirectory() . '/sitemap/' . xrowSitemapTools::domain(); if (!is_dir($dir)) { mkdir($dir, 0777, true); } $filename = $dir . '/' . xrowSitemap::BASENAME . '_standard_' . $GLOBALS['eZCurrentAccess']['name'] . '.' . xrowSitemap::SUFFIX; $sitemap->save($filename); if (!$isQuiet) { $cli->output("\n"); $cli->output("Sitemap {$filename} for siteaccess " . $GLOBALS['eZCurrentAccess']['name'] . " has been generated.\n"); } }
/** * Clears cache for an object and fetches it * * @param eZContentObject $object * * @return eZContentObject */ protected function forceFetchContentObject($contentObjectId) { eZContentObject::clearCache($contentObjectId); return eZContentObject::fetch($contentObjectId); }
/** * Aligns location of the articles published under given publisher folder * @param eZContentObject $publisherObject */ function alignArticleLocation( $publisherObject, $offset = 0 ) { $limit = 200; $continue = true; $publisherNode = $publisherObject->mainNode(); $globalVarName = 'contentServiceMainNodeID'; if ( !isset( $GLOBALS[$globalVarName] ) ) { $GLOBALS[$globalVarName] = array(); } echo "Starting treatment of publisher folder : " . $publisherObject->name() . "\n"; while ( true ) { $params = array( 'Offset' => $offset, 'Limit' => $limit, 'ClassFilterType' => 'include', 'ClassFilterArray' => array( 'article' ), 'LoadDataMap' => false, 'AsObject' => false, 'MainNodeOnly' => true, ); $nodeList = $publisherNode->subtree( $params ); echo " // Offset : $offset // "; if ( count( $nodeList ) == 0 ) { break; } foreach ( $nodeList as $mainNode ) { $object = eZContentObject::fetch( $mainNode["contentobject_id"] ); deploymentType::addListNodesIdToAddLocation($object); } $offset += $limit; eZContentObject::clearCache(); } }
public function tearDown() { eZContentObject::clearCache(); parent::tearDown(); }
function transformNode(eZContentObjectTreeNode $node) { $values = array(); if ($node instanceof eZContentObjectTreeNode) { /** @var eZContentObject $object */ $object = $node->attribute('object'); /** @var eZContentObjectAttribute[] $attributes */ $attributes = $object->attribute('contentobject_attributes'); foreach ($attributes as $attribute) { $attributeIdentifier = $attribute->attribute('contentclass_attribute_identifier'); $datatypeString = $attribute->attribute('data_type_string'); if (isset($this->options['ExcludeAttributeIdentifiers']) && in_array($attributeIdentifier, $this->options['ExcludeAttributeIdentifiers'])) { continue; } if (isset($this->options['ExcludeDatatype']) && in_array($datatypeString, $this->options['ExcludeDatatype'])) { continue; } $attributeName = $attribute->attribute('contentclass_attribute_name'); if (!isset($this->CSVheaders[$attributeIdentifier])) { $this->CSVheaders[$attributeIdentifier] = $attributeName; } switch ($datatypeString) { case 'ezobjectrelation': $attributeStringContent = $attribute->content()->attribute('name'); break; case 'ezobjectrelationlist': $attributeContent = $attribute->content(); $relations = $attributeContent['relation_list']; $relatedNames = array(); foreach ($relations as $relation) { $related = eZContentObject::fetch($relation['contentobject_id']); if ($related) { $relatedNames[] = $related->attribute('name'); eZContentObject::clearCache($related->attribute('id')); } } $attributeStringContent = implode(',', $relatedNames); break; case 'ezxmltext': $text = str_replace('"', "'", $attribute->content()->attribute('output')->outputText()); $text = strip_tags($text); $text = str_replace(';', ',', $text); $text = str_replace(array("\n", "\r"), "", $text); $attributeStringContent = $text; break; case 'ezbinaryfile': $attributeStringContent = ''; if ($attribute->hasContent()) { $file = $attribute->content(); $filePath = "content/download/{$attribute->attribute('contentobject_id')}/{$attribute->attribute('id')}/{$attribute->content()->attribute('original_filename')}"; $attributeStringContent = eZSys::hostname() . '/' . $filePath; } break; case 'ezdatetime': case 'ezdate': $attributeStringContent = ''; if ($attribute->hasContent()) { $attributeStringContent = strftime('%d/%m/%Y', $attribute->toString()); } break; case 'ezuser': $attributeStringContent = ''; if ($attribute->hasContent()) { $login = $attribute->content()->attribute('login'); $email = $attribute->content()->attribute('email'); $attributeStringContent = $login != $email ? $login . '|' . $email : $email; } break; default: $attributeStringContent = ''; if ($attribute->hasContent()) { $attributeStringContent = $attribute->toString(); } break; } $values[] = $attributeStringContent; } eZContentObject::clearCache($object->attribute('id')); } return $values; }