function execute($process, $event) { // get object being published $parameters = $process->attribute('parameter_list'); $objectID = $parameters['object_id']; eZDebug::writeDebug('Update object state for object: ' . $objectID); $object = eZContentObject::fetch($objectID); $state_before = $event->attribute('state_before'); $state_after = $event->attribute('state_after'); if ($object == null) { eZDebug::writeError('Update object state failed for inexisting object: ' . $objectID, __METHOD__); return eZWorkflowType::STATUS_WORKFLOW_CANCELLED; } if ($state_before == null || $state_after == null) { eZDebug::writeError('Update object state failed: badly configured states', __METHOD__); return eZWorkflowType::STATUS_WORKFLOW_CANCELLED; } $currentStateIDArray = $object->attribute('state_id_array'); if (in_array($state_before->attribute('id'), $currentStateIDArray)) { $canAssignStateIDList = $object->attribute('allowed_assign_state_id_list'); if (!in_array($state_after->attribute('id'), $canAssignStateIDList)) { eZDebug::writeWarning("Not enough rights to assign state to object {$objectID}: " . $state_after->attribute('id'), __METHOD__); } else { eZDebug::writeDebug('Changing object state from ' . $state_before->attribute('name') . ' to ' . $state_after->attribute('name'), __METHOD__); if (eZOperationHandler::operationIsAvailable('content_updateobjectstate')) { $operationResult = eZOperationHandler::execute('content', 'updateobjectstate', array('object_id' => $objectID, 'state_id_list' => array($state_after->attribute('id')))); } else { eZContentOperationCollection::updateObjectState($objectID, array($state_after->attribute('id'))); } } } return eZWorkflowType::STATUS_ACCEPTED; }
public function searchActivities($query, $limit = 20, $sorting = 'best') { $result = array('result' => array()); $accumulator = $this->debugAccumulatorGroup . '_google_activities_search'; eZDebug::accumulatorStart($accumulator, $this->debugAccumulatorGroup, 'activities/search'); $cacheFileHandler = $this->getCacheFileHandler('_activities_search', array($query, $limit, $sorting)); try { if ($this->isCacheExpired($cacheFileHandler)) { eZDebug::writeDebug(array('query' => $query, 'limit' => $limit, 'sorting' => $sorting), self::$debugMessagesGroup); $response = $this->API->activities->search($query, array('maxResults' => $limit, 'orderBy' => $sorting)); $activities = array(); $currentTime = time(); foreach ($response['items'] as $activity) { $createdAt = strtotime($activity['published']); $activity['created_ago'] = self::getCreatedAgoString($createdAt, $currentTime); $activity['created_timestamp'] = $createdAt; $activities[] = $activity; } $cacheFileHandler->fileStoreContents($cacheFileHandler->filePath, serialize($activities)); } else { $activities = unserialize($cacheFileHandler->fetchContents()); } eZDebug::accumulatorStop($accumulator); $result['result'] = $activities; return $result; } catch (Exception $e) { eZDebug::accumulatorStop($accumulator); eZDebug::writeError($e, self::$debugMessagesGroup); return $result; } }
public function shorten($url) { $call = $this->serviceCallUrl . urlencode($url); $shortUrl = $this->shortenUrl($call); eZDebug::writeDebug("Shortened {$url} to {$shortUrl}", __METHOD__); return $shortUrl; }
function execute($process, $event) { $parameters = $process->attribute('parameter_list'); $object = eZContentObject::fetch($parameters['object_id']); $versionID = $parameters['version']; if (!$object) { return eZWorkflowType::STATUS_WORKFLOW_CANCELLED; } $version = $object->version($versionID); if (!$version) { return eZWorkflowType::STATUS_WORKFLOW_CANCELLED; } $akismetObject = new eZContentObjectAkismet(); $comment = $akismetObject->akismetInformationExtractor($version); if ($comment) { $akismet = new eZAkismet($comment); if ($akismet) { $isSpam = $akismet->isCommentSpam(); eZDebug::writeDebug($comment); eZDebug::writeDebug("this is spam: " . $isSpam); } else { return eZWorkflowType::STATUS_WORKFLOW_CANCELLED; } if (!$isSpam) { $response = $akismet->submitHam(); return eZWorkflowType::STATUS_ACCEPTED; } return eZWorkflowType::STATUS_REJECTED; } }
function addFiles(&$index, $dirname, $dirArray) { try { $dir = new eZClusterDirectoryIterator($dirname); } catch (Exception $e) { if ($e instanceof UnexpectedValueException) { eZDebug::writeDebug("Cannot add {$dirname} to the sitemaps index because it does not exist"); return; } } foreach ($dir as $file) { $f = eZClusterFileHandler::instance($file->name()); if ($f->exists()) { $exists = true; break; } } if (false != $exists) { foreach ($dir as $file) { if (in_array($file->name(), $dirArray)) { continue; } if ($file->size() > 50) { $date = new xrowSitemapItemModified(); $date->date = new DateTime("@" . $file->mtime()); $loc = 'http://' . $_SERVER['HTTP_HOST'] . '/' . $file->name(); if (!in_array($loc, $GLOBALS['loc'])) { $GLOBALS['loc'][] = $loc; $index->add($loc, array($date)); } } } } }
function install($package, $installType, $parameters, $name, $os, $filename, $subdirectory, $content, &$installParameters, &$installData) { $path = $package->path(); $databaseType = false; if (isset($parameters['database-type'])) { $databaseType = $parameters['database-type']; } $path .= '/' . eZDBPackageHandler::sqlDirectory(); if ($databaseType) { $path .= '/' . $databaseType; } if (file_exists($path)) { $db = eZDB::instance(); $canInsert = true; if ($databaseType and $databaseType != $db->databaseName()) { $canInsert = false; } if ($canInsert) { eZDebug::writeDebug("Installing SQL file {$path}/{$filename}"); $db->insertFile($path, $filename, false); return true; } else { eZDebug::writeDebug("Skipping SQL file {$path}/{$filename}"); } } else { eZDebug::writeError("Could not find SQL file {$path}/{$filename}"); } return false; }
/** * Helper function for {@link eZHTTPPersistence::fetch()} * * @param string $base_name * @param array $def Definition for $object, uses the same syntax as {@link eZPersistentObject} * @param object $object * @param eZHTTPTool $http * @param int|string|false $index Index in HTTP POST data corresponding to $object. * Set as string will make use of corresponding field in $def * Set to false if posted data is not an array. * @see eZHTTPPersistence::fetch() * @return void */ static function fetchElement($base_name, array $def, $object, eZHTTPTool $http, $index) { $fields = $def["fields"]; $keys = $def["keys"]; foreach ($fields as $field_name => $field_member) { if (!in_array($field_name, $keys)) { $post_var = $base_name . "_" . $field_name; if ($http->hasPostVariable($post_var)) { $post_value = $http->postVariable($post_var); if ($index === false) { if ($post_value !== null && $field_member['datatype'] === 'string' && array_key_exists('max_length', $field_member) && $field_member['max_length'] > 0 && strlen($post_value) > $field_member['max_length']) { $post_value = substr($post_value, 0, $field_member['max_length']); eZDebug::writeDebug($post_value, "truncation of {$field_name} to max_length=" . $field_member['max_length']); } $object->setAttribute($field_name, $post_value); } else { if (is_string($index)) { $object->setAttribute($field_name, $post_value[$object->attribute($index)]); } else { $object->setAttribute($field_name, $post_value[$index]); } } } } } }
public function getTimeline($pageID = false, $limit = 20, $type = 'feed') { $result = array('result' => array()); $accumulator = $this->debugAccumulatorGroup . '_facebook_timeline'; eZDebug::accumulatorStart($accumulator, $this->debugAccumulatorGroup, 'timeline'); $cacheFileHandler = $this->getCacheFileHandler('_timeline', array($pageID, $limit, $type)); try { if ($this->isCacheExpired($cacheFileHandler)) { eZDebug::writeDebug(array('page_id' => $pageID, 'limit' => $limit), self::$debugMessagesGroup); $response = $this->API->api(($pageID === false ? 'me/home' : '/' . $pageID) . '/' . $type, array('access_token' => $this->acessToken, 'limit' => $limit)); $messages = array(); $currentTime = time(); foreach ($response['data'] as $message) { $createdAt = strtotime($message['created_time']); $message['created_ago'] = self::getCreatedAgoString($createdAt, $currentTime); $message['created_timestamp'] = $createdAt; if (isset($message['message'])) { $message['message'] = self::fixMessageLinks($message['message']); } $messages[] = $message; } $cacheFileHandler->fileStoreContents($cacheFileHandler->filePath, serialize($messages)); } else { $messages = unserialize($cacheFileHandler->fetchContents()); } eZDebug::accumulatorStop($accumulator); $result['result'] = $messages; return $result; } catch (Exception $e) { eZDebug::accumulatorStop($accumulator); eZDebug::writeError($e->getMessage(), self::$debugMessagesGroup); return $result; } }
function modify($tpl, $operatorName, $operatorParameters, $rootNamespace, $currentNamespace, &$operatorValue, $namedParameters) { if ($operatorName == 'ezjssd_cleanup') { $operatorValue = str_replace(array('<p>', '</p>'), '', $operatorValue); $operatorValue = str_replace(array('<br />'), "\n", $operatorValue); eZDebug::writeDebug($operatorValue, __METHOD__); } }
public function getMediaRecent($pageID = false, $limit = 20) { $result = array('result' => array()); $accumulator = $this->debugAccumulatorGroup . '_instagram_media_recent'; eZDebug::accumulatorStart($accumulator, $this->debugAccumulatorGroup, 'media_recent'); $cacheFileHandler = $this->getCacheFileHandler('_media_recent', array($pageID, $limit)); try { if ($this->isCacheExpired($cacheFileHandler)) { eZDebug::writeDebug(array('page_id' => $pageID, 'limit' => $limit), self::$debugMessagesGroup); $items = array(); $userData = eZHTTPTool::getDataByURL('https://api.instagram.com/v1/users/search?' . 'q=' . $pageID . '&' . 'client_id=' . $this->API['key']); $userID = false; if ($userData !== false) { $userDataArray = json_decode($userData, true); if (count($userDataArray['data'])) { foreach ($userDataArray['data'] as $user) { if ($user['username'] == $pageID) { $userID = $user['id']; break; } } } } if ($userID !== false) { $leftLimit = $limit; $feedData = eZHTTPTool::getDataByURL('https://api.instagram.com/v1/users/' . $userID . '/media/recent/?' . 'access_token=' . $this->API['token']); if ($feedData !== false) { $feedDataArray = json_decode($feedData, true); if (isset($feedDataArray['data'])) { $items = array_merge($items, array_slice($feedDataArray['data'], 0, $leftLimit)); $leftLimit = $leftLimit - count($feedDataArray['data']); } $endlessLoopBreaker = 0; while ($endlessLoopBreaker < 50 && $leftLimit > 0 && isset($feedDataArray['pagination']['next_url'])) { $endlessLoopBreaker++; $feedData = eZHTTPTool::getDataByURL($feedDataArray['pagination']['next_url']); if ($feedData !== false) { $feedDataArray = json_decode($feedData, true); $items = array_merge($items, array_slice($feedDataArray['data'], 0, $leftLimit)); } $leftLimit = $leftLimit - count($feedDataArray['data']); } } } $cacheFileHandler->fileStoreContents($cacheFileHandler->filePath, serialize($items)); } else { $items = unserialize($cacheFileHandler->fetchContents()); } eZDebug::accumulatorStop($accumulator); $result['result'] = $items; return $result; } catch (Exception $e) { eZDebug::accumulatorStop($accumulator); eZDebug::writeError($e->getMessage(), self::$debugMessagesGroup); return $result; } }
function exportAttribute(&$attribute, $seperationChar) { eZDebug::writeDebug($attribute, "SMILE"); $content = $attribute->content(); $relation_list = $content['relation_list']; eZDebug::writeDebug($content, "SMILE"); $names = array(); foreach ($relation_list as $relation) { $object = eZContentObject::fetch($relation['contentobject_id']); $names[] = $object->name(); } return $this->escape(join(" ", $names), $seperationChar); }
public function shorten($url) { $shortUrl = false; $owly = OwlyApi::factory(array('key' => eZINI::instance('nxcsocialnetworks.ini')->variable('LinkShortenHandlerOwly', 'ApiKey'))); try { $responseUrl = $owly->shorten($url); if ($responseUrl != '') { $shortUrl = $responseUrl; } } catch (Exception $e) { // Catch any API errors here } eZDebug::writeDebug("Shortened {$url} to {$shortUrl}", __METHOD__); return $shortUrl; }
/** * Saves the xml content * * @param $filename Path to file */ function save($filename = 'sitemap.xml') { $file = eZClusterFileHandler::instance($filename); if ($file->exists()) { eZDebug::writeDebug("Time: " . date('d.m.Y H:i:s') . ". Action: " . $filename . " exists. File will be remove."); if (!$isQuiet) { $cli = eZCLI::instance(); $cli->output("Time: " . date('d.m.Y H:i:s') . ". Action: " . $filename . " exists. File will be remove."); $cli->output("\n"); } $file->delete(); } $xml = $this->dom->saveXML(); return $file->storeContents($xml, 'sitemap', 'text/xml'); }
public function shorten($url) { $shortUrl = false; $bitly = new Bitly(null, null, eZINI::instance('nxcsocialnetworks.ini')->variable('LinkShortenHandlerBitly', 'GenericAccessToken')); try { $response = $bitly->shorten($url); $responseUrl = $response['url']; if ($responseUrl != '') { $shortUrl = $responseUrl; } } catch (Exception $e) { // Catch any API errors here } eZDebug::writeDebug("Shortened {$url} to {$shortUrl}", __METHOD__); return $shortUrl; }
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; }
public function getSearch($query = '', array $parameters = array()) { $result = array('result' => array()); $accumulator = $this->debugAccumulatorGroup . '_twitter_search'; eZDebug::accumulatorStart($accumulator, $this->debugAccumulatorGroup, 'search/tweets'); $parameters = array_merge(array('q' => $query), $parameters); $cacheFileHandler = $this->getCacheFileHandler('search', $parameters); try { if ($this->isCacheExpired($cacheFileHandler)) { eZDebug::writeDebug('search', self::$debugMessagesGroup); eZDebug::writeDebug($parameters, self::$debugMessagesGroup); $response = $this->API->get('search/tweets', $parameters); $errorKeys = array('error', 'errors'); foreach ($errorKeys as $errorKey) { if (isset($response->{$errorKey})) { eZDebug::writeError($response->{$errorKey}, self::$debugMessagesGroup); return $result; } } $statuses = array(); $currentTime = time(); foreach ($response->statuses as $status) { $createdAt = strtotime($status->created_at); $status = self::objectToArray($status); $status['created_timestamp'] = $createdAt; $status['created_ago'] = self::getCreatedAgoString($createdAt, $currentTime); $status['text'] = self::fixStatusLinks($status['text']); $statuses[] = $status; } $cacheFileHandler->fileStoreContents($cacheFileHandler->filePath, serialize($statuses)); } else { $statuses = unserialize($cacheFileHandler->fetchContents()); } eZDebug::accumulatorStop($accumulator); $result['result'] = $statuses; return $result; } catch (Exception $e) { eZDebug::accumulatorStop($accumulator); eZDebug::writeError($e, self::$debugMessagesGroup); return $result; } }
/** * Logs the string $logString to the logfile webservices.log * in the current log directory (usually var/log). * If logging is disabled, nothing is done. * * In dev mode, also writes to the eZP logs to ease debugging (this happens * regardless of the logging level set for the extension itself) */ static function appendLogEntry($logString, $debuglevel) { $ini = eZINI::instance('site.ini'); if ($ini->variable('DebugSettings', 'DebugOutput') == 'enabled' && $ini->variable('TemplateSettings', 'DevelopmentMode') == 'enabled') { switch ($debuglevel) { case 'info': case 'notice': eZDebug::writeNotice($logString, 'ggwebservices'); break; case 'debug': eZDebug::writeDebug($logString, 'ggwebservices'); break; case 'warning': eZDebug::writeWarning($logString, 'ggwebservices'); break; case 'error': case 'critical': eZDebug::writeError($logString, 'ggwebservices'); break; } } if (!self::isLoggingEnabled($debuglevel)) { return false; } $varDir = eZSys::varDirectory(); $logDir = 'log'; $logName = 'webservices.log'; $fileName = $varDir . '/' . $logDir . '/' . $logName; if (!file_exists($varDir . '/' . $logDir)) { //include_once( 'lib/ezfile/classes/ezdir.php' ); eZDir::mkdir($varDir . '/' . $logDir, 0775, true); } if ($logFile = fopen($fileName, 'a')) { $nowTime = date("Y-m-d H:i:s : "); $text = $nowTime . $logString; /*if ( $label ) $text .= ' [' . $label . ']';*/ fwrite($logFile, $text . "\n"); fclose($logFile); } }
/** * Event execution * * @todo currently the alias is created in the 1st language of the version. Use ezontentlanguage::languagesByMask() instead yto make it multilingual... */ public function execute($process, $event) { $params = $process->attribute('parameter_list'); $object_id = $params['object_id']; $object = eZContentObject::fetch($object_id); if (!is_object($object)) { eZDebug::writeError("Unable to fetch object: '{$params['object_id']}'", __METHOD__); return eZWorkflowType::STATUS_WORKFLOW_CANCELLED; } $attrname = $event->attribute('source_attribute'); $data_map = $object->attribute('data_map'); if (!isset($data_map[$attrname])) { eZDebug::writeError("Object has no attribute {$attrname}", __METHOD__); return eZWorkflowType::STATUS_WORKFLOW_CANCELLED; } // we use the same rules as used in generating object titles $url = $data_map[$attrname]->title(); if ($url == '') { return eZWorkflowType::STATUS_ACCEPTED; } $version = $object->currentversion(); $assignedNodes = $object->attribute('assigned_nodes'); if ($assignedNodes) { foreach ($assignedNodes as $assignedNode) { $results = self::addUrlALias($assignedNode, $url, $version->attribute('initial_language_id'), $event->attribute('external_redirect'), $event->attribute('at_root')); if (strpos($results['infoCode'], 'error') === 0) { /// @todo return an error / abend here? eZDebug::writeError("Error: " . $results['infoCode'], __METHOD__); } else { eZDebug::writeDebug($results['infoCode'] . ' Alias: ' . $results['infoData']['new_alias'], __METHOD__); } if ($event->attribute('at_root')) { // if url-alias is to be set at root, create it only once, not once-per-parent-node break; } } } return eZWorkflowType::STATUS_ACCEPTED; }
/** * test if the new node remote id is available (or already used by this node) * @param string $remoteID * @param int $currentNodeID * @param array $errors * @param boolean $allowBlank * @return boolean */ public static function isValidNodeRemoteID($remoteID, $currentNodeID = false, &$errors = array(), $allowBlank = false) { if (!self::isValidRemoteIDText($remoteID, $errors, $allowBlank)) { return false; } if ($existingNode = eZContentObjectTreeNode::fetchByRemoteID($remoteID, false)) { $existingNodeIDList = array(); if (isset($existingNode['node_id'])) { $existingNodeIDList[] = $existingNode['node_id']; } else { foreach ($existingNode as $node) { $existingNodeIDList[] = $node['node_id']; } } if (!in_array($currentNodeID, $existingNodeIDList)) { $errors[] = ezpI18n::tr('remoteid/update', 'Node Remote ID %1 already used by node %2', '', array('%1' => $remoteID, '%2' => join(', ', $existingNodeIDList))); eZDebug::writeDebug('Node Remote ID ' . $remoteID . ' used by node ' . join(', ', $existingNodeIDList), '', __CLASS__); return false; } } return true; }
/** * This method checks if given string does exist in any content object * attributes with the same id, with the exception for those being versions * of the same content object. If given string exists anywhere, in published * or unpublished versions, drafts, trash, this string will be excluded. * * More information in the ini file uniquedatatypes.ini.append.php * * @param string $data * @param object $contentObjectAttribute * @return integer */ private static function validateUniqueStringHTTPInput($data, $contentObjectAttribute) { $contentObjectID = $contentObjectAttribute->ContentObjectID; $contentClassAttributeID = $contentObjectAttribute->ContentClassAttributeID; $db = eZDB::instance(); $ini = eZINI::instance('uniquedatatypes.ini'); $uniqueStringINI = $ini->group('UniqueStringSettings'); if ($uniqueStringINI['CurrentVersionOnly'] == 'true') { $query = "SELECT COUNT(*) AS datacounter\n\t\t\t\tFROM ezcontentobject co, ezcontentobject_attribute coa\n\t\t\t\tWHERE co.id = coa.contentobject_id\n\t\t\t\tAND co.current_version = coa.version\n\t\t\t\tAND coa.contentobject_id <> " . $db->escapeString($contentObjectID) . "\n\t\t\t\tAND coa.contentclassattribute_id = " . $db->escapeString($contentClassAttributeID) . "\n\t\t\t\tAND coa.data_text = '" . $db->escapeString($data) . "'"; } else { $query = "SELECT COUNT(*) AS datacounter\n\t\t\t\tFROM ezcontentobject_attribute\n\t\t\t\tWHERE contentobject_id <> " . $db->escapeString($contentObjectID) . "\n\t\t\t\tAND contentclassattribute_id = " . $db->escapeString($contentClassAttributeID) . "\n\t\t\t\tAND data_text = '" . $db->escapeString($data) . "'"; } if (self::EZUNIQUESTRING_DEBUG) { eZDebug::writeDebug('Query: ' . $query, 'eZUniqueStringType::validateUniqueStringHTTPInput'); } $result = $db->arrayQuery($query); $resultCount = $result[0]['datacounter']; if ($resultCount) { $contentObjectAttribute->setValidationError(ezpI18n::tr('extension/ezuniquedatatypes', 'Given string already exists in another content object of this type!')); return eZInputValidator::STATE_INVALID; } return eZInputValidator::STATE_ACCEPTED; }
static function classDOMTree($class) { if (!$class) { $retValue = false; return $retValue; } $dom = new DOMDocument('1.0', 'utf-8'); $classNode = $dom->createElement('content-class'); $dom->appendChild($classNode); $serializedNameListNode = $dom->createElement('serialized-name-list'); $serializedNameListNode->appendChild($dom->createTextNode($class->attribute('serialized_name_list'))); $classNode->appendChild($serializedNameListNode); $identifierNode = $dom->createElement('identifier'); $identifierNode->appendChild($dom->createTextNode($class->attribute('identifier'))); $classNode->appendChild($identifierNode); $serializedDescriptionListNode = $dom->createElement('serialized-description-list'); $serializedDescriptionListNode->appendChild($dom->createTextNode($class->attribute('serialized_description_list'))); $classNode->appendChild($serializedDescriptionListNode); $remoteIDNode = $dom->createElement('remote-id'); $remoteIDNode->appendChild($dom->createTextNode($class->attribute('remote_id'))); $classNode->appendChild($remoteIDNode); $objectNamePatternNode = $dom->createElement('object-name-pattern'); $objectNamePatternNode->appendChild($dom->createTextNode($class->attribute('contentobject_name'))); $classNode->appendChild($objectNamePatternNode); $urlAliasPatternNode = $dom->createElement('url-alias-pattern'); $urlAliasPatternNode->appendChild($dom->createTextNode($class->attribute('url_alias_name'))); $classNode->appendChild($urlAliasPatternNode); $isContainer = $class->attribute('is_container') ? 'true' : 'false'; $classNode->setAttribute('is-container', $isContainer); $classNode->setAttribute('always-available', $class->attribute('always_available') ? 'true' : 'false'); $classNode->setAttribute('sort-field', eZContentObjectTreeNode::sortFieldName($class->attribute('sort_field'))); $classNode->setAttribute('sort-order', $class->attribute('sort_order')); // Remote data start $remoteNode = $dom->createElement('remote'); $classNode->appendChild($remoteNode); $ini = eZINI::instance(); $siteName = $ini->variable('SiteSettings', 'SiteURL'); $classURL = 'http://' . $siteName . '/class/view/' . $class->attribute('id'); $siteURL = 'http://' . $siteName . '/'; $siteUrlNode = $dom->createElement('site-url'); $siteUrlNode->appendChild($dom->createTextNode($siteURL)); $remoteNode->appendChild($siteUrlNode); $urlNode = $dom->createElement('url'); $urlNode->appendChild($dom->createTextNode($classURL)); $remoteNode->appendChild($urlNode); $classGroupsNode = $dom->createElement('groups'); $classGroupList = eZContentClassClassGroup::fetchGroupList($class->attribute('id'), $class->attribute('version')); foreach ($classGroupList as $classGroupLink) { $classGroup = eZContentClassGroup::fetch($classGroupLink->attribute('group_id')); if ($classGroup) { unset($groupNode); $groupNode = $dom->createElement('group'); $groupNode->setAttribute('id', $classGroup->attribute('id')); $groupNode->setAttribute('name', $classGroup->attribute('name')); $classGroupsNode->appendChild($groupNode); } } $remoteNode->appendChild($classGroupsNode); $idNode = $dom->createElement('id'); $idNode->appendChild($dom->createTextNode($class->attribute('id'))); $remoteNode->appendChild($idNode); $createdNode = $dom->createElement('created'); $createdNode->appendChild($dom->createTextNode($class->attribute('created'))); $remoteNode->appendChild($createdNode); $modifiedNode = $dom->createElement('modified'); $modifiedNode->appendChild($dom->createTextNode($class->attribute('modified'))); $remoteNode->appendChild($modifiedNode); $creatorNode = $dom->createElement('creator'); $remoteNode->appendChild($creatorNode); $creatorIDNode = $dom->createElement('user-id'); $creatorIDNode->appendChild($dom->createTextNode($class->attribute('creator_id'))); $creatorNode->appendChild($creatorIDNode); $creator = $class->attribute('creator'); if ($creator) { $creatorLoginNode = $dom->createElement('user-login'); $creatorLoginNode->appendChild($dom->createTextNode($creator->attribute('login'))); $creatorNode->appendChild($creatorLoginNode); } $modifierNode = $dom->createElement('modifier'); $remoteNode->appendChild($modifierNode); $modifierIDNode = $dom->createElement('user-id'); $modifierIDNode->appendChild($dom->createTextNode($class->attribute('modifier_id'))); $modifierNode->appendChild($modifierIDNode); $modifier = $class->attribute('modifier'); if ($modifier) { $modifierLoginNode = $dom->createElement('user-login'); $modifierLoginNode->appendChild($dom->createTextNode($modifier->attribute('login'))); $modifierNode->appendChild($modifierLoginNode); } // Remote data end $attributesNode = $dom->createElementNS('http://ezpublish/contentclassattribute', 'ezcontentclass-attribute:attributes'); $classNode->appendChild($attributesNode); $attributes = $class->fetchAttributes(); foreach ($attributes as $attribute) { $attributeNode = $dom->createElement('attribute'); $attributeNode->setAttribute('datatype', $attribute->attribute('data_type_string')); $required = $attribute->attribute('is_required') ? 'true' : 'false'; $attributeNode->setAttribute('required', $required); $searchable = $attribute->attribute('is_searchable') ? 'true' : 'false'; $attributeNode->setAttribute('searchable', $searchable); $informationCollector = $attribute->attribute('is_information_collector') ? 'true' : 'false'; $attributeNode->setAttribute('information-collector', $informationCollector); $translatable = $attribute->attribute('can_translate') ? 'true' : 'false'; $attributeNode->setAttribute('translatable', $translatable); $attributeRemoteNode = $dom->createElement('remote'); $attributeNode->appendChild($attributeRemoteNode); $attributeIDNode = $dom->createElement('id'); $attributeIDNode->appendChild($dom->createTextNode($attribute->attribute('id'))); $attributeRemoteNode->appendChild($attributeIDNode); $attributeSerializedNameListNode = $dom->createElement('serialized-name-list'); $attributeSerializedNameListNode->appendChild($dom->createTextNode($attribute->attribute('serialized_name_list'))); $attributeNode->appendChild($attributeSerializedNameListNode); $attributeIdentifierNode = $dom->createElement('identifier'); $attributeIdentifierNode->appendChild($dom->createTextNode($attribute->attribute('identifier'))); $attributeNode->appendChild($attributeIdentifierNode); $attributeSerializedDescriptionListNode = $dom->createElement('serialized-description-list'); $attributeSerializedDescriptionListNode->appendChild($dom->createTextNode($attribute->attribute('serialized_description_list'))); $attributeNode->appendChild($attributeSerializedDescriptionListNode); $attributeCategoryNode = $dom->createElement('category'); $attributeCategoryNode->appendChild($dom->createTextNode($attribute->attribute('category'))); $attributeNode->appendChild($attributeCategoryNode); $attributeSerializedDataTextNode = $dom->createElement('serialized-data-text'); $attributeSerializedDataTextNode->appendChild($dom->createTextNode($attribute->attribute('serialized_data_text'))); $attributeNode->appendChild($attributeSerializedDataTextNode); $attributePlacementNode = $dom->createElement('placement'); $attributePlacementNode->appendChild($dom->createTextNode($attribute->attribute('placement'))); $attributeNode->appendChild($attributePlacementNode); $attributeParametersNode = $dom->createElement('datatype-parameters'); $attributeNode->appendChild($attributeParametersNode); $dataType = $attribute->dataType(); if (is_object($dataType)) { $dataType->serializeContentClassAttribute($attribute, $attributeNode, $attributeParametersNode); } $attributesNode->appendChild($attributeNode); } eZDebug::writeDebug($dom->saveXML(), 'content class package XML'); return $classNode; }
/** * Create policy limitation query. * * @param array $limitation Override the limitation of the user. Same format as the return of eZUser::hasAccessTo() * @param boolean $ignoreVisibility Set to true for the visibility to be ignored * @return string Lucene/Solr query string which can be used as filter query for Solr */ protected function policyLimitationFilterQuery($limitation = null, $ignoreVisibility = null) { $eZFindIni = eZINI::instance('ezfind.ini'); $filterQuery = false; $policies = array(); $pathFieldName = $ignoreVisibility ? eZSolr::getMetaFieldName('path') : eZSolr::getMetaFieldName('visible_path'); if (is_array($limitation)) { if (empty($limitation)) { $limitation['accessWord'] = 'yes'; } } else { $limitation = eZUser::currentUser()->hasAccessTo('content', 'read'); } if (isset($limitation['accessWord'])) { switch ($limitation['accessWord']) { case 'limited': if (isset($limitation['policies'])) { $policies = $limitation['policies']; break; } // break omitted, "limited" without policies == "no" // break omitted, "limited" without policies == "no" case 'no': return ' NOT *:* '; case 'yes': break; default: return false; } } // Add limitations for filter query based on local permissions. $limitationHash = array('Class' => eZSolr::getMetaFieldName('contentclass_id'), 'Section' => eZSolr::getMetaFieldName('section_id'), 'User_Section' => eZSolr::getMetaFieldName('section_id'), 'Subtree' => eZSolr::getMetaFieldName('path_string'), 'User_Subtree' => eZSolr::getMetaFieldName('path_string'), 'Node' => eZSolr::getMetaFieldName('main_node_id'), 'Owner' => eZSolr::getMetaFieldName('owner_id'), 'Group' => eZSolr::getMetaFieldName('owner_group_id'), 'ObjectStates' => eZSolr::getMetaFieldName('object_states')); $filterQueryPolicies = array(); // policies are concatenated with OR foreach ($policies as $limitationList) { // policy limitations are concatenated with AND // except for locations policity limitations, concatenated with OR $filterQueryPolicyLimitations = array(); $policyLimitationsOnLocations = array(); foreach ($limitationList as $limitationType => $limitationValues) { // limitation values of one type in a policy are concatenated with OR $filterQueryPolicyLimitationParts = array(); switch ($limitationType) { case 'User_Subtree': case 'Subtree': foreach ($limitationValues as $limitationValue) { $pathString = trim($limitationValue, '/'); $pathArray = explode('/', $pathString); // we only take the last node ID in the path identification string $subtreeNodeID = array_pop($pathArray); $policyLimitationsOnLocations[] = $pathFieldName . ':' . $subtreeNodeID; if (isset($this->searchPluginInstance->postSearchProcessingData['subtree_limitations'])) { $this->searchPluginInstance->postSearchProcessingData['subtree_limitations'][] = $subtreeNodeID; } else { $this->searchPluginInstance->postSearchProcessingData['subtree_limitations'] = array($subtreeNodeID); } } break; case 'Node': foreach ($limitationValues as $limitationValue) { $pathString = trim($limitationValue, '/'); $pathArray = explode('/', $pathString); // we only take the last node ID in the path identification string $nodeID = array_pop($pathArray); $policyLimitationsOnLocations[] = $limitationHash[$limitationType] . ':' . $nodeID; if (isset($this->searchPluginInstance->postSearchProcessingData['subtree_limitations'])) { $this->searchPluginInstance->postSearchProcessingData['subtree_limitations'][] = $nodeID; } else { $this->searchPluginInstance->postSearchProcessingData['subtree_limitations'] = array($nodeID); } } break; case 'Group': foreach (eZUser::currentUser()->attribute('contentobject')->attribute('parent_nodes') as $groupID) { $filterQueryPolicyLimitationParts[] = $limitationHash[$limitationType] . ':' . $groupID; } break; case 'Owner': $filterQueryPolicyLimitationParts[] = $limitationHash[$limitationType] . ':' . eZUser::currentUser()->attribute('contentobject_id'); break; case 'Class': case 'Section': case 'User_Section': foreach ($limitationValues as $limitationValue) { $filterQueryPolicyLimitationParts[] = $limitationHash[$limitationType] . ':' . $limitationValue; } break; default: //hacky, object state limitations reference the state group name in their //limitation //hence the following match on substring if (strpos($limitationType, 'StateGroup') !== false) { foreach ($limitationValues as $limitationValue) { $filterQueryPolicyLimitationParts[] = $limitationHash['ObjectStates'] . ':' . $limitationValue; } } else { eZDebug::writeDebug($limitationType, __METHOD__ . ' unknown limitation type: ' . $limitationType); continue; } } if (!empty($filterQueryPolicyLimitationParts)) { $filterQueryPolicyLimitations[] = '( ' . implode(' OR ', $filterQueryPolicyLimitationParts) . ' )'; } } // Policy limitations on locations (node and/or subtree) need to be concatenated with OR // unlike the other types of limitation if (!empty($policyLimitationsOnLocations)) { $filterQueryPolicyLimitations[] = '( ' . implode(' OR ', $policyLimitationsOnLocations) . ')'; } if (!empty($filterQueryPolicyLimitations)) { $filterQueryPolicies[] = '( ' . implode(' AND ', $filterQueryPolicyLimitations) . ')'; } } if (!empty($filterQueryPolicies)) { $filterQuery = implode(' OR ', $filterQueryPolicies); } // Add limitations for allowing search of other installations. $anonymousPart = ''; if ($eZFindIni->variable('SiteSettings', 'SearchOtherInstallations') == 'enabled') { $anonymousPart = ' OR ' . eZSolr::getMetaFieldName('anon_access') . ':true '; } if (!empty($filterQuery)) { $filterQuery = '((' . eZSolr::getMetaFieldName('installation_id') . ':' . eZSolr::installationID() . ' AND (' . $filterQuery . ')) ' . $anonymousPart . ' )'; } else { $filterQuery = '(' . eZSolr::getMetaFieldName('installation_id') . ':' . eZSolr::installationID() . $anonymousPart . ')'; } // Add ignore visibility condition, either explicitely set to boolean false or not specified if ($ignoreVisibility === false || $ignoreVisibility === null) { $filterQuery .= ' AND ' . eZSolr::getMetaFieldName('is_invisible') . ':false'; } eZDebugSetting::writeDebug('extension-ezfind-query', $filterQuery, __METHOD__); return $filterQuery; }
function computeRedirect( $module, $object, $version, $EditLanguage = false ) { $http = eZHTTPTool::instance(); $node = $object->mainNode(); if ( $http->hasSessionVariable( 'RedirectIfDiscarded' ) ) { $http->removeSessionVariable( 'RedirectIfDiscarded' ); } $hasRedirected = false; if ( $http->hasSessionVariable( 'ParentObject' ) && $http->sessionVariable( 'NewObjectID' ) == $object->attribute( 'id' ) ) { $parentArray = $http->sessionVariable( 'ParentObject' ); $parentURL = $module->redirectionURI( 'content', 'edit', $parentArray ); $parentObject = eZContentObject::fetch( $parentArray[0] ); $db = eZDB::instance(); $db->begin(); $parentObject->addContentObjectRelation( $object->attribute( 'id' ), $parentArray[1] ); $db->commit(); $http->removeSessionVariable( 'ParentObject' ); $http->removeSessionVariable( 'NewObjectID' ); $module->redirectTo( $parentURL ); $hasRedirected = true; } if ( $http->hasSessionVariable( 'RedirectURIAfterPublish' ) && !$hasRedirected ) { $uri = $http->sessionVariable( 'RedirectURIAfterPublish' ); $http->removeSessionVariable( 'RedirectURIAfterPublish' ); $module->redirectTo( $uri ); $hasRedirected = true; } if ( $http->hasPostVariable( 'RedirectURIAfterPublish' ) && !$hasRedirected ) { $uri = $http->postVariable( 'RedirectURIAfterPublish' ); $module->redirectTo( $uri ); $hasRedirected = true; } if ( $http->hasPostVariable( "BackToEdit" ) && $http->postVariable( "BackToEdit" ) ) { $uri = $module->redirectionURI( 'content', 'edit', array( $object->attribute( 'id'), 'f', $EditLanguage ) ); $module->redirectTo( $uri ); eZDebug::writeDebug( $uri, "uri " . $object->attribute( 'id') ); $hasRedirected = true; } if ( !$hasRedirected ) { if ( $http->hasPostVariable( 'RedirectURI' ) ) { $uri = $http->postVariable( 'RedirectURI' ); $module->redirectTo( $uri ); } else if ( $node !== null ) { $parentNode = $node->attribute( 'parent_node_id' ); if ( $parentNode == 1 ) { $parentNode = $node->attribute( 'node_id' ); } $module->redirectToView( 'view', array( 'full', $parentNode ) ); } else { $module->redirectToView( 'view', array( 'full', $version->attribute( 'main_parent_node_id' ) ) ); } } }
public static function embedTagContentType( $classIdentifier ) { $contentIni = eZINI::instance('content.ini'); foreach ( $contentIni->variable( 'RelationGroupSettings', 'Groups' ) as $group ) { $settingName = ucfirst( $group ) . 'ClassList'; if ( $contentIni->hasVariable( 'RelationGroupSettings', $settingName ) ) { if ( in_array( $classIdentifier, $contentIni->variable( 'RelationGroupSettings', $settingName ) ) ) return $group; } else eZDebug::writeDebug( "Missing content.ini[RelationGroupSettings]$settingName setting.", __METHOD__ ); } return $contentIni->variable( 'RelationGroupSettings', 'DefaultGroup' ); }
/** * Creates the image alias $aliasName if it's not already part of the * existing aliases * * @param string $aliasName Name of the alias to create * @param array $existingAliasList * Reference to the current alias list. The created alias will be * added to the list. * @param array $parameters * Optional array that can be used to specify the image's basename * @return bool true if the alias was created, false if it wasn't */ function createImageAlias( $aliasName, &$existingAliasList, $parameters = array() ) { $fname = "createImageAlias( $aliasName )"; // check for $aliasName validity $aliasList = $this->aliasList(); if ( !isset( $aliasList[$aliasName] ) ) { eZDebug::writeWarning( "Alias name $aliasName does not exist, cannot create it" ); return false; } // check if the reference alias is defined, and if no, use original as ref $currentAliasInfo = $aliasList[$aliasName]; $referenceAlias = $currentAliasInfo['reference']; if ( $referenceAlias and !$this->hasAlias( $referenceAlias ) ) { eZDebug::writeError( "The referenced alias '$referenceAlias' for image alias '$aliasName' does not exist, cannot use it for reference.\n" . "Will use 'original' alias instead.", __METHOD__ ); $referenceAlias = false; } if ( !$referenceAlias ) $referenceAlias = 'original'; // generate the reference alias if it hasn't been generated yet $hasReference = false; if ( array_key_exists( $referenceAlias, $existingAliasList ) ) { $fileHandler = eZClusterFileHandler::instance(); if ( $fileHandler->fileExists( $existingAliasList[$referenceAlias]['url'] ) ) { $hasReference = true; } else { eZDebug::writeError( "The reference alias $referenceAlias file {$existingAliasList[$referenceAlias]['url']} does not exist", __METHOD__ ); } } if ( !$hasReference ) { if ( $referenceAlias == 'original' ) { eZDebug::writeError( "Original alias does not exist, cannot create other aliases without it" ); return false; } if ( !$this->createImageAlias( $referenceAlias, $existingAliasList, $parameters ) ) { eZDebug::writeError( "Failed creating the referenced alias $referenceAlias, cannot create alias $aliasName", __METHOD__ ); return false; } } // from now on, our reference image (either reference or original) // exists $aliasInfo = $existingAliasList[$referenceAlias]; $aliasFilePath = $aliasInfo['url']; $aliasKey = $currentAliasInfo['alias_key']; $sourceMimeData = eZMimeType::findByFileContents( $aliasFilePath ); /** * at first, destinationMimeData (mimedata for the alias we're * generating) is the same as sourceMimeData. It will evolve as * alias generation goes on */ $destinationMimeData = $sourceMimeData; if ( isset( $parameters['basename'] ) ) { $sourceMimeData['basename'] = $parameters['basename']; eZMimeType::changeBasename( $destinationMimeData, $parameters['basename'] ); } /** * Concurrency protection * startCacheGeneration will return true if the file is not * already being generated by another process. If it is, it will * return the maximum time before the generating process enters * generation timeout */ while ( true ) { $convertHandler = eZClusterFileHandler::instance( $sourceMimeData['url'] ); $startGeneration = $convertHandler->startCacheGeneration(); if ( $startGeneration === true ) { $destinationMimeData['is_valid'] = false; if ( $this->convert( $sourceMimeData, $destinationMimeData, $aliasName, $parameters ) ) { /** * At this point, we consider that the image exists and destinationMimeData * has been filled with the proper information * * If we were locked during alias generation, we need to recreate * this structure so that the image can actually be used, but ONLY * if it was the same alias... sounds like a HUGE mess. * * Can we reload the alias list somehow ? */ $currentAliasData = array( 'url' => $destinationMimeData['url'], 'dirpath' => $destinationMimeData['dirpath'], 'filename' => $destinationMimeData['filename'], 'suffix' => $destinationMimeData['suffix'], 'basename' => $destinationMimeData['basename'], 'alternative_text' => $aliasInfo['alternative_text'], 'name' => $aliasName, 'sub_type' => false, 'timestamp' => time(), 'alias_key' => $aliasKey, 'mime_type' => $destinationMimeData['name'], 'override_mime_type' => false, 'info' => false, 'width' => false, 'height' => false, 'is_valid' => true, 'is_new' => true ); if ( isset( $destinationMimeData['override_mime_type'] ) ) $currentAliasData['override_mime_type'] = $destinationMimeData['override_mime_type']; if ( isset( $destinationMimeData['info'] ) ) $currentAliasData['info'] = $destinationMimeData['info']; $currentAliasData['full_path'] = $currentAliasData['url']; if ( function_exists( 'getimagesize' ) ) { /** * we may want to fetch a unique name here, since we won't use * the data for anything else */ $fileHandler = eZClusterFileHandler::instance( $destinationMimeData['url'] ); if ( $tempPath = $fileHandler->fetchUnique() ) { $info = getimagesize( $tempPath ); if ( $info ) { list( $currentAliasData['width'], $currentAliasData['height'] ) = $info; } else { eZDebug::writeError("The size of the generated image {$destinationMimeData['url']} could not be read by getimagesize()", __METHOD__ ); } $fileHandler->fileDeleteLocal( $tempPath ); } else { eZDebug::writeError( "The destination image {$destinationMimeData['url']} does not exist, cannot figure out image size", __METHOD__ ); } } else { eZDebug::writeError( "Unknown function 'getimagesize', cannot get image size", __METHOD__ ); } $existingAliasList[$aliasName] = $currentAliasData; $convertHandler->endCacheGeneration( false ); // Notify about image alias generation. Parameters are alias // url and alias name. ezpEvent::getInstance()->notify( 'image/alias', array( $currentAliasData['url'], $currentAliasData['name'] ) ); return true; } // conversion failed, we abort generation else { $sourceFile = $sourceMimeData['url']; $destinationDir = $destinationMimeData['dirpath']; eZDebug::writeError( "Failed converting $sourceFile to alias '$aliasName' in directory '$destinationDir'", __METHOD__ ); $convertHandler->abortCacheGeneration(); return false; } } // we were not granted file generation (someone else is doing it) // we wait for max. $remainingGenerationTime and check if the // file has been generated in between // Actually, we have no clue if the generated file was the one we were // looking for, and it doesn't seem possible to RELOAD the alias list. // We don't even know what attribute we're using... CRAP else { eZDebug::writeDebug( "An alias is already being generated for this image, let's wait", __METHOD__ ); while ( true ) { $startGeneration = $convertHandler->startCacheGeneration(); // generation lock granted: we can start again by breaking to // the beggining of the while loop if ( $startGeneration === true ) { eZDebug::writeDebug( "Got granted generation permission, restarting !", __METHOD__ ); $convertHandler->abortCacheGeneration(); continue 2; } else { sleep( 1 ); } } } } return false; }
static function getEngine() { // Get instance if already created. $instanceName = "eZSearchPlugin_" . $GLOBALS["eZCurrentAccess"]["name"]; if ( isset( $GLOBALS[$instanceName] ) ) { return $GLOBALS[$instanceName]; } $ini = eZINI::instance(); $searchEngineString = 'ezsearch'; if ( $ini->hasVariable( 'SearchSettings', 'SearchEngine' ) == true ) { $searchEngineString = $ini->variable( 'SearchSettings', 'SearchEngine' ); } $directoryList = array(); if ( $ini->hasVariable( 'SearchSettings', 'ExtensionDirectories' ) ) { $extensionDirectories = $ini->variable( 'SearchSettings', 'ExtensionDirectories' ); if ( is_array( $extensionDirectories ) ) { $directoryList = eZExtension::expandedPathList( $extensionDirectories, 'search/plugins' ); } } $kernelDir = array( 'kernel/search/plugins' ); $directoryList = array_merge( $kernelDir, $directoryList ); foreach( $directoryList as $directory ) { $searchEngineFile = implode( '/', array( $directory, strtolower( $searchEngineString ), strtolower( $searchEngineString ) ) ) . '.php'; if ( file_exists( $searchEngineFile ) ) { eZDebugSetting::writeDebug( 'kernel-search-ezsearch', 'Loading search engine from ' . $searchEngineFile, 'eZSearch::getEngine' ); include_once( $searchEngineFile ); $GLOBALS[$instanceName] = new $searchEngineString(); return $GLOBALS[$instanceName]; } } eZDebug::writeDebug( 'Unable to find the search engine:' . $searchEngineString, 'eZSearch' ); eZDebug::writeDebug( 'Tried paths: ' . implode( ', ', $directoryList ), 'eZSearch' ); return false; }
function copySubtree($srcNodeID, $dstNodeID, &$notifications, $allVersions, $keepCreator, $keepTime) { // 1. Copy subtree and form the arrays of accordance of the old and new nodes and content objects. $sourceSubTreeMainNode = $srcNodeID ? eZContentObjectTreeNode::fetch($srcNodeID) : false; $destinationNode = $dstNodeID ? eZContentObjectTreeNode::fetch($dstNodeID) : false; if (!$sourceSubTreeMainNode) { eZDebug::writeError("Cannot get subtree main node (nodeID = {$srcNodeID}).", "Subtree copy Error!"); $notifications['Errors'][] = ezpI18n::tr('kernel/content/copysubtree', "Fatal error: cannot get subtree main node (ID = %1).", null, array($srcNodeID)); $notifications['Result'] = false; return $notifications; } if (!$destinationNode) { eZDebug::writeError("Cannot get destination node (nodeID = {$dstNodeID}).", "Subtree copy Error!"); $notifications['Errors'][] = ezpI18n::tr('kernel/content/copysubtree', "Fatal error: cannot get destination node (ID = %1).", null, array($dstNodeID)); $notifications['Result'] = false; return $notifications; } $sourceNodeList = array(); $syncNodeIDListSrc = array(); // arrays for synchronizing between source and new IDs of nodes $syncNodeIDListNew = array(); $syncObjectIDListSrc = array(); // arrays for synchronizing between source and new IDs of contentobjects $syncObjectIDListNew = array(); $sourceSubTreeMainNodeID = $sourceSubTreeMainNode->attribute('node_id'); $sourceNodeList[] = $sourceSubTreeMainNode; $syncNodeIDListSrc[] = $sourceSubTreeMainNode->attribute('parent_node_id'); $syncNodeIDListNew[] = (int) $dstNodeID; $nodeIDBlackList = array(); // array of nodes which are unable to copy $objectIDBlackList = array(); // array of contentobjects which are unable to copy in any location inside new subtree $sourceNodeList = array_merge($sourceNodeList, eZContentObjectTreeNode::subTreeByNodeID(array('Limitation' => array()), $sourceSubTreeMainNodeID)); $countNodeList = count($sourceNodeList); $notifications['Notifications'][] = ezpI18n::tr('kernel/content/copysubtree', "Number of nodes of source subtree - %1", null, array($countNodeList)); // Prepare list of source node IDs. We will need it in the future // for checking node is inside or outside of the subtree being copied. $sourceNodeIDList = array(); foreach ($sourceNodeList as $sourceNode) { $sourceNodeIDList[] = $sourceNode->attribute('node_id'); } eZDebug::writeDebug("Source NodeID = {$srcNodeID}, destination NodeID = {$dstNodeID}", "Subtree copy: START!"); // 1. copying and publishing source subtree $k = 0; while (count($sourceNodeList) > 0) { if ($k > $countNodeList) { eZDebug::writeError("Too many loops while copying nodes.", "Subtree Copy Error!"); break; } for ($i = 0; $i < count($sourceNodeList); $i) { $sourceNodeID = $sourceNodeList[$i]->attribute('node_id'); // if node was alreaty copied if (in_array($sourceNodeID, $syncNodeIDListSrc)) { array_splice($sourceNodeList, $i, 1); continue; } //////////// check permissions START // if node is already in black list, then skip current node: if (in_array($sourceNodeID, $nodeIDBlackList)) { array_splice($sourceNodeList, $i, 1); continue; } $sourceObject = $sourceNodeList[$i]->object(); $srcSubtreeNodeIDlist = $sourceNodeID == $sourceSubTreeMainNodeID ? $syncNodeIDListSrc : $sourceNodeIDList; $copyResult = copyPublishContentObject($sourceObject, $srcSubtreeNodeIDlist, $syncNodeIDListSrc, $syncNodeIDListNew, $syncObjectIDListSrc, $syncObjectIDListNew, $objectIDBlackList, $nodeIDBlackList, $notifications, $allVersions, $keepCreator, $keepTime); if ($copyResult === 0) { // if copying successful then remove $sourceNode from $sourceNodeList array_splice($sourceNodeList, $i, 1); } else { $i++; } } $k++; } array_shift($syncNodeIDListSrc); array_shift($syncNodeIDListNew); $countNewNodes = count($syncNodeIDListNew); $countNewObjects = count($syncObjectIDListNew); $notifications['Notifications'][] = ezpI18n::tr('kernel/content/copysubtree', "Number of copied nodes - %1", null, array($countNewNodes)); $notifications['Notifications'][] = ezpI18n::tr('kernel/content/copysubtree', "Number of copied contentobjects - %1", null, array($countNewObjects)); eZDebug::writeDebug(count($syncNodeIDListNew), "Number of copied nodes: "); eZDebug::writeDebug(count($syncObjectIDListNew), "Number of copied contentobjects: "); eZDebug::writeDebug($objectIDBlackList, "Copy subtree: Not copied object IDs list:"); eZDebug::writeDebug($nodeIDBlackList, "Copy subtree: Not copied node IDs list:"); $key = array_search($sourceSubTreeMainNodeID, $syncNodeIDListSrc); if ($key === false) { eZDebug::writeDebug("Root node of given subtree was not copied.", "Subtree copy:"); $notifications['Result'] = false; return $notifications; } // 2. fetch all new subtree $newSubTreeMainNodeID = $syncNodeIDListSrc[$key]; $newSubTreeMainNode = eZContentObjectTreeNode::fetch($newSubTreeMainNodeID); $newNodeList[] = $newSubTreeMainNode; $newNodeList = $sourceNodeList = array_merge($newNodeList, eZContentObjectTreeNode::subTreeByNodeID(false, $newSubTreeMainNodeID)); // 3. fix local links (in ezcontentobject_link) eZDebug::writeDebug("Fixing global and local links...", "Subtree copy:"); $db = eZDB::instance(); if (!$db) { eZDebug::writeError("Cannot create instance of eZDB for fixing local links (related objects).", "Subtree Copy Error!"); $notifications['Errors'][] = ezpI18n::tr('kernel/content/copysubtree', "Cannot create instance of eZDB to fix local links (related objects)."); return $notifications; } $idListINString = $db->generateSQLINStatement($syncObjectIDListNew, 'from_contentobject_id', false, false, 'int'); $relatedRecordsList = $db->arrayQuery("SELECT * FROM ezcontentobject_link WHERE {$idListINString}"); foreach ($relatedRecordsList as $relatedEntry) { $kindex = array_search($relatedEntry['to_contentobject_id'], $syncObjectIDListSrc); if ($kindex !== false) { $newToContentObjectID = (int) $syncObjectIDListNew[$kindex]; $linkID = (int) $relatedEntry['id']; $db->query("UPDATE ezcontentobject_link SET to_contentobject_id={$newToContentObjectID} WHERE id={$linkID}"); } } // 4. duplicating of global links for new contentobjects (in ezurl_object_link) are automatic during copy of contentobject. // it was fixed as bug patch. // 5. fixing node_ids and object_ids in ezxmltext attributes of copied objects $conditions = array('contentobject_id' => '', 'data_type_string' => 'ezxmltext'); foreach ($syncObjectIDListNew as $contentObjectID) { $conditions['contentobject_id'] = $contentObjectID; $attributeList = eZPersistentObject::fetchObjectList(eZContentObjectAttribute::definition(), null, $conditions); if (count($attributeList) == 0) { continue; } foreach ($attributeList as $xmlAttribute) { $xmlText = $xmlAttribute->attribute('data_text'); $xmlTextLen = strlen($xmlText); $isTextModified = false; $curPos = 0; while ($curPos < $xmlTextLen) { $literalTagBeginPos = strpos($xmlText, "<literal", $curPos); if ($literalTagBeginPos) { $literalTagEndPos = strpos($xmlText, "</literal>", $literalTagBeginPos); if ($literalTagEndPos === false) { break; } $curPos = $literalTagEndPos + 9; } if (($tagBeginPos = strpos($xmlText, "<link", $curPos)) !== false or ($tagBeginPos = strpos($xmlText, "<a", $curPos)) !== false or ($tagBeginPos = strpos($xmlText, "<embed", $curPos)) !== false) { $tagEndPos = strpos($xmlText, ">", $tagBeginPos + 1); if ($tagEndPos === false) { break; } $tagText = substr($xmlText, $tagBeginPos, $tagEndPos - $tagBeginPos); if (($nodeIDAttributePos = strpos($tagText, " node_id=\"")) !== false) { $idNumberPos = $nodeIDAttributePos + 10; $quoteEndPos = strpos($tagText, "\"", $idNumberPos); if ($quoteEndPos !== false) { $idNumber = substr($tagText, $idNumberPos, $quoteEndPos - $idNumberPos); $key = array_search((int) $idNumber, $syncNodeIDListSrc); if ($key !== false) { $tagText = substr_replace($tagText, (string) $syncNodeIDListNew[$key], $idNumberPos, $quoteEndPos - $idNumberPos); $xmlText = substr_replace($xmlText, $tagText, $tagBeginPos, $tagEndPos - $tagBeginPos); $isTextModified = true; } } } else { if (($objectIDAttributePos = strpos($tagText, " object_id=\"")) !== false) { $idNumberPos = $objectIDAttributePos + 12; $quoteEndPos = strpos($tagText, "\"", $idNumberPos); if ($quoteEndPos !== false) { $idNumber = substr($tagText, $idNumberPos, $quoteEndPos - $idNumberPos); $key = array_search((int) $idNumber, $syncObjectIDListSrc); if ($key !== false) { $tagText = substr_replace($tagText, (string) $syncObjectIDListNew[$key], $idNumberPos, $quoteEndPos - $idNumberPos); $xmlText = substr_replace($xmlText, $tagText, $tagBeginPos, $tagEndPos - $tagBeginPos); $isTextModified = true; } } } } $curPos = $tagEndPos; } else { if (($tagBeginPos = strpos($xmlText, "<object", $curPos)) !== false) { $tagEndPos = strpos($xmlText, ">", $tagBeginPos + 1); if (!$tagEndPos) { break; } $tagText = substr($xmlText, $tagBeginPos, $tagEndPos - $tagBeginPos); if (($idAttributePos = strpos($tagText, " id=\"")) !== false) { $idNumberPos = $idAttributePos + 5; $quoteEndPos = strpos($tagText, "\"", $idNumberPos); if ($quoteEndPos !== false) { $idNumber = substr($tagText, $idNumberPos, $quoteEndPos - $idNumberPos); $key = array_search((int) $idNumber, $syncObjectIDListSrc); if ($key !== false) { $tagText = substr_replace($tagText, (string) $syncObjectIDListNew[$key], $idNumberPos, $quoteEndPos - $idNumberPos); $xmlText = substr_replace($xmlText, $tagText, $tagBeginPos, $tagEndPos - $tagBeginPos); $isTextModified = true; } } } $curPos = $tagEndPos; } else { break; } } } // while END if ($isTextModified) { $xmlAttribute->setAttribute('data_text', $xmlText); $xmlAttribute->store(); } } // foreach END } // 6. fixing datatype ezobjectrelationlist $conditions = array('contentobject_id' => '', 'data_type_string' => 'ezobjectrelationlist'); foreach ($syncObjectIDListNew as $contentObjectID) { $conditions['contentobject_id'] = $contentObjectID; $attributeList = eZPersistentObject::fetchObjectList(eZContentObjectAttribute::definition(), null, $conditions); if (count($attributeList) == 0) { continue; } foreach ($attributeList as $relationListAttribute) { $relationsXmlText = $relationListAttribute->attribute('data_text'); $relationsDom = eZObjectRelationListType::parseXML($relationsXmlText); $relationItems = $relationsDom->getElementsByTagName('relation-item'); $isRelationModified = false; foreach ($relationItems as $relationItem) { $originalObjectID = $relationItem->getAttribute('contentobject-id'); $key = array_search($originalObjectID, $syncObjectIDListSrc); if ($key !== false) { $newObjectID = $syncObjectIDListNew[$key]; $relationItem->setAttribute('contentobject-id', $newObjectID); $isRelationModified = true; } $originalNodeID = $relationItem->getAttribute('node-id'); if ($originalNodeID) { $key = array_search($originalNodeID, $syncNodeIDListSrc); if ($key !== false) { $newNodeID = $syncNodeIDListNew[$key]; $relationItem->setAttribute('node-id', $newNodeID); $newNode = eZContentObjectTreeNode::fetch($newNodeID); $newParentNodeID = $newNode->attribute('parent_node_id'); $relationItem->setAttribute('parent-node-id', $newParentNodeID); $isRelationModified = true; } } } if ($isRelationModified) { $attributeID = $relationListAttribute->attribute('id'); $attributeVersion = $relationListAttribute->attribute('version'); $changedDomString = $db->escapeString(eZObjectRelationListType::domString($relationsDom)); $db->query("UPDATE ezcontentobject_attribute SET data_text='{$changedDomString}'\n WHERE id={$attributeID} AND version={$attributeVersion}"); } } } eZDebug::writeDebug("Successfuly DONE.", "Copy subtree:"); $notifications['Result'] = true; return $notifications; }
function checkNodeMovements( $module, $class, $object, $version, $contentObjectAttributes, $editVersion, $editLanguage, $FromLanguage, &$validation ) { $http = eZHTTPTool::instance(); // If the object has been previously published we do not allow node assignment operations if ( $object->attribute( 'status' ) != eZContentObject::STATUS_DRAFT ) { return; } // If node assignment handling is diabled we return immedieately $useNodeAssigments = true; if ( $http->hasPostVariable( 'UseNodeAssigments' ) ) $useNodeAssigments = (bool)$http->postVariable( 'UseNodeAssigments' ); if ( !$useNodeAssigments ) return; $ObjectID = $object->attribute( 'id' ); // Move to another node if ( $module->isCurrentAction( 'MoveNodeAssignment' ) ) { $selectedNodeIDArray = eZContentBrowse::result( 'MoveNodeAssignment' ); $fromNodeID = $http->postVariable( "FromNodeID" ); $oldAssignmentParentID = $http->postVariable( 'OldAssignmentParentID' ); if ( $selectedNodeIDArray != null ) { $assignedNodes = $version->nodeAssignments(); $assignedIDArray = array(); foreach ( $assignedNodes as $assignedNode ) { $assignedNodeID = $assignedNode->attribute( 'parent_node' ); $assignedIDArray[] = $assignedNodeID; } foreach ( $selectedNodeIDArray as $nodeID ) { if ( !in_array( $nodeID, $assignedIDArray ) ) { $isPermitted = true; // Check access $newNode = eZContentObjectTreeNode::fetch( $nodeID ); $newNodeObject = $newNode->attribute( 'object' ); $canCreate = $newNodeObject->checkAccess( 'create', $class->attribute( 'id' ), $newNodeObject->attribute( 'contentclass_id' ) ) == 1; eZDebug::writeDebug( $canCreate,"can create"); if ( !$canCreate ) { $isPermitted = false; } else { $canCreateClassList = $newNodeObject->attribute( 'can_create_class_list' ); $canCreateClassIDList = array(); foreach ( array_keys( $canCreateClassList ) as $key ) { $canCreateClassIDList[] = $canCreateClassList[$key]['id']; } $objectClassID = $object->attribute( 'contentclass_id' ); if ( !in_array( $objectClassID, $canCreateClassIDList ) ) $isPermitted = false; } if ( !$isPermitted ) { eZDebug::writeError( $newNode->pathWithNames(), "You are not allowed to place this object under:" ); $validation[ 'placement' ][] = array( 'text' => ezpI18n::tr( 'kernel/content', "You are not allowed to place this object under: %1", null, array( $newNode->pathWithNames() ) ) ); $validation[ 'processed' ] = true; // Error message. } else { $oldAssignment = eZPersistentObject::fetchObject( eZNodeAssignment::definition(), null, array( 'contentobject_id' => $object->attribute( 'id' ), 'parent_node' => $oldAssignmentParentID, 'contentobject_version' => $version->attribute( 'version' ) ), true ); $realNode = eZContentObjectTreeNode::fetchNode( $version->attribute( 'contentobject_id' ), $oldAssignment->attribute( 'parent_node' ) ); $db = eZDB::instance(); $db->begin(); // No longer remove then add assignment, instead change the existing one if ( $realNode === null ) { $fromNodeID = 0; } if ( $oldAssignment->attribute( 'is_main' ) == '1' ) { $oldAssignment->setAttribute( 'parent_node', $nodeID ); $oldAssignment->setAttribute( 'is_main', 1 ); $oldAssignment->setAttribute( 'from_node_id', $fromNodeID ); // $version->assignToNode( $nodeID, 1, $fromNodeID, $oldAssignment->attribute( 'sort_field' ), $oldAssignment->attribute( 'sort_order' ) ); } else { $oldAssignment->setAttribute( 'parent_node', $nodeID ); $oldAssignment->setAttribute( 'is_main', 0 ); $oldAssignment->setAttribute( 'from_node_id', $fromNodeID ); // $version->assignToNode( $nodeID, 0, $fromNodeID, $oldAssignment->attribute( 'sort_field' ), $oldAssignment->attribute( 'sort_order' ) ); } $oldAssignment->setAttribute( 'op_code', eZNodeAssignment::OP_CODE_MOVE ); $oldAssignment->store(); //$version->removeAssignment( $oldAssignmentParentID ); $db->commit(); } } } } } }
/** * Check access to a specific module/function with limitation values. * See eZ Publish documentation on more info on module, function and * limitation values. Example: a user can have content/read permissions * but it can be limited to a specific limitation like a section, a node * or node tree. Limitation: returns false if one of provided values * don't match but ignores limitations not specified in $limitations. * * @param string $module * @param string $function * @param array|null $limitations A hash of limitation keys and values * @return bool */ public static function hasAccessToLimitation($module, $function, $limitations = null, $debug = false) { // Like fetch(user,has_access_to), but with support for limitations $user = eZUser::currentUser(); if (!$user instanceof eZUser) { eZDebug::writeDebug('No user instance', __METHOD__); return false; } $result = $user->hasAccessTo($module, $function); if ($result['accessWord'] !== 'limited') { return $result['accessWord'] === 'yes'; } // Merge limitations before we check access $mergedLimitations = array(); $missingLimitations = array(); foreach ($result['policies'] as $userLimitationArray) { foreach ($userLimitationArray as $userLimitationKey => $userLimitationValues) { if (isset($limitations[$userLimitationKey])) { if (isset($mergedLimitations[$userLimitationKey])) { $mergedLimitations[$userLimitationKey] = array_merge($mergedLimitations[$userLimitationKey], $userLimitationValues); } else { $mergedLimitations[$userLimitationKey] = $userLimitationValues; } } else { $missingLimitations[] = $userLimitationKey; } } } // User has access unless provided limitations don't match foreach ($mergedLimitations as $userLimitationKey => $userLimitationValues) { // Handle subtree matching specifically as we need to match path string if ($userLimitationKey === 'User_Subtree' || $userLimitationKey === 'Subtree') { $pathMatch = false; foreach ($userLimitationValues as $subtreeString) { if (strstr($limitations[$userLimitationKey], $subtreeString)) { $pathMatch = true; break; } } if (!$pathMatch) { if ($debug) { eZDebug::writeDebug("Unmatched[{$module}/{$function}]: " . $userLimitationKey . ' ' . $limitations[$userLimitationKey] . ' != ' . $subtreeString, __METHOD__); } return false; } } else { if (is_array($limitations[$userLimitationKey])) { // All provided limitations must exist in $userLimitationValues foreach ($limitations[$userLimitationKey] as $limitationValue) { if (!in_array($limitationValue, $userLimitationValues)) { if ($debug) { eZDebug::writeDebug("Unmatched[{$module}/{$function}]: " . $userLimitationKey . ' ' . $limitationValue . ' != [' . implode(', ', $userLimitationValues) . ']', __METHOD__); } return false; } } } else { if (!in_array($limitations[$userLimitationKey], $userLimitationValues)) { if ($debug) { eZDebug::writeDebug("Unmatched[{$module}/{$function}]: " . $userLimitationKey . ' ' . $limitations[$userLimitationKey] . ' != [' . implode(', ', $userLimitationValues) . ']', __METHOD__); } return false; } } } } if (!empty($missingLimitations) && $debug) { eZDebug::writeNotice("Matched, but missing limitations[{$module}/{$function}]: " . implode(', ', $missingLimitations), __METHOD__); } return true; }
function setVATType($VATID) { $this->VATType = eZVatType::fetch($VATID); if (!$this->VATType) { eZDebug::writeDebug("VAT type with id '{$VATID}' is unavailable", __METHOD__); $this->VATType = eZVatType::create(); } }