/** * Performs PDF content generation and caching * * @param $url String URL * @param $denisty Integer * @param $keys Mixed Keys for Cache key(s) - either as a string or an array of strings * @param $subtree_expiry Mixed The parameter $subtreeExpiryParameter is expiry value is usually taken * from the template operator and can be one of: * - A numerical value which represents the node ID (the fastest approach) * - A string containing 'content/view/full/xxx' where xx is the node ID number, * the number will be extracted. * - A string containing a nice url which will be decoded into a node ID using * the database (slowest approach). * @param $expiry Integer The number of seconds that the pdf cache should be allowed to live.A value of * zero will produce a cache block that will never expire * @param $ignore_content_expiry Boolean Disables cache expiry when new content is published. * @return void */ public function getObject($url = '', $density, $keys, $subtree_expiry, $expiry, $ignore_content_expiry = false) { $pngUrl = ''; $obj = false; $mtime = eZDateTime::currentTimeStamp(); $httpExpiry = $this->cacheTTL; if (strpos("://", $url) === false) { $url = eZSys::serverURL() . $url; } //eZDebug::writeError($url, 'sPdf2png::exportPng'); if ($this->cacheEnabled) { $use_global_expiry = !$ignore_content_expiry; //$keys = self::getCacheKeysArray($keys); $expiry = is_numeric($expiry) ? $expiry : $this->cacheTTL; list($handler, $pngUrl) = eZTemplateCacheBlock::retrieve($keys, $subtree_expiry, $expiry, $use_global_expiry); if ($pngUrl instanceof eZClusterFileFailure || !file_get_contents($pngUrl)) { eZDebug::writeError("cache invalid", 'sPdf2png::exportPng'); $obj = $this->generatePng($url, $density, $keys); $handler->storeCache(array('scope' => 'template-block', 'binarydata' => $obj['url'])); } //eZDebug::writeError("cache", 'sPdf2png::exportPng'); } else { $obj = $this->generatePng($url, $density, $keys); } if (!$obj) { $obj = $this->getPngData($pngUrl); } $obj['url'] = self::getWwwDir() . $obj['url']; return $obj; }
/** * Updates user with provided auth data * * @param eZUser $user * @param array $authResult * * @return bool */ public static function updateUser($user, $authResult) { $currentTimeStamp = eZDateTime::currentTimeStamp(); $contentObject = $user->contentObject(); if (!$contentObject instanceof eZContentObject) { return false; } /** @var eZContentObjectVersion $version */ $version = $contentObject->currentVersion(); $db = eZDB::instance(); $db->begin(); $version->setAttribute('modified', $currentTimeStamp); $version->store(); self::fillUserObject($version->dataMap(), $authResult); if ($authResult['email'] != $user->Email) { $userExists = false; if (eZUser::requireUniqueEmail()) { $userExists = eZUser::fetchByEmail($authResult['email']) instanceof eZUser; } if (empty($authResult['email']) || $userExists) { $email = md5('ngconnect_' . $authResult['login_method'] . '_' . $authResult['id']) . '@localhost.local'; } else { $email = $authResult['email']; } $user->setAttribute('email', $email); $user->store(); } $contentObject->setName($contentObject->contentClass()->contentObjectName($contentObject)); $contentObject->store(); $db->commit(); return $user; }
/** * Save article draft for later approval */ public function save() { $user = eZUser::fetchByName('admin'); $params = array('class_identifier' => 'article', 'creator_id' => $user->attribute('contentobject_id'), 'parent_node_id' => $this->location, 'name' => $this->header, 'attributes' => array('title' => $this->header, 'intro' => $this->xmlConvert($this->ingress), 'body' => $this->xmlConvert($this->text))); // Manipulate version (setting state to draft) $contentObject = eZContentFunctions::createAndPublishObject($params); $version = $contentObject->version(1); $version->setAttribute('modified', eZDateTime::currentTimeStamp()); $version->setAttribute('status', eZContentObjectVersion::STATUS_DRAFT); $version->store(); }
/** * Performs PDF content generation and caching * * @param $xhtml String XHTML content * @param $pdf_file_name String Name that will be used when serving the PDF file (not for storage) * @param $keys Mixed Keys for Cache key(s) - either as a string or an array of strings * @param $subtree_expiry Mixed The parameter $subtreeExpiryParameter is expiry value is usually taken * from the template operator and can be one of: * - A numerical value which represents the node ID (the fastest approach) * - A string containing 'content/view/full/xxx' where xx is the node ID number, * the number will be extracted. * - A string containing a nice url which will be decoded into a node ID using * the database (slowest approach). * @param $expiry Integer The number of seconds that the pdf cache should be allowed to live.A value of * zero will produce a cache block that will never expire * @param $ignore_content_expiry Boolean Disables cache expiry when new content is published. * @return void */ public function exportPDF($xhtml = '', $pdf_file_name = '', $keys, $subtree_expiry, $expiry, $ignore_content_expiry = false) { if ($pdf_file_name == '') { $pdf_file_name = 'file'; } $data = ''; $size = 0; $mtime = eZDateTime::currentTimeStamp(); $httpExpiry = $this->cacheTTL; if ($this->cacheEnabled) { $keys = self::getCacheKeysArray($keys); $expiry = is_numeric($expiry) ? $expiry : $this->cacheTTL; if ($expiry > 0) { $httpExpiry = $expiry; } if (isset($subtree_expiry)) { $ignore_content_expiry = true; } list($handler, $data) = eZTemplateCacheBlock::retrieve($keys, $subtree_expiry, $expiry, !$ignore_content_expiry); if ($data instanceof eZClusterFileFailure || $handler->size() == 0) { $data = $this->generatePDF($xhtml); // check if error occurred during pdf generation if ($data === false) { return; } $handler->storeCache(array('scope' => 'template-block', 'binarydata' => $data)); $size = strlen($data); } else { $size = $handler->size(); $mtime = $handler->mtime(); } } else { $data = $this->generatePDF($xhtml); // check if error occurred during pdf generation if ($data === false) { return; } $size = $this->size; } $this->flushPDF($data, $pdf_file_name, $size, $mtime, $httpExpiry); }
function createObject($classIdentifier, $parentNodeID, $name) { $user = eZUser::currentUser(); $Class = eZContentClass::fetchByIdentifier($classIdentifier); if (!$Class) { eZDebug::writeError("No class with identifier {$classIdentifier}", "classCreation"); return false; } $contentObject = $Class->instantiate($user->attribute('contentobject_id')); $nodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $contentObject->attribute('id'), 'contentobject_version' => $contentObject->attribute('current_version'), 'parent_node' => $parentNodeID, 'is_main' => 1)); $nodeAssignment->store(); $version = $contentObject->version(1); $version->setAttribute('modified', eZDateTime::currentTimeStamp()); $version->setAttribute('status', eZContentObjectVersion::STATUS_DRAFT); $version->store(); $contentObjectID = $contentObject->attribute('id'); $attributes = $contentObject->attribute('contentobject_attributes'); $attributes[0]->fromString($name); $attributes[0]->store(); $operationResult = eZOperationHandler::execute('content', 'publish', array('object_id' => $contentObjectID, 'version' => 1)); return true; }
$action = $mode; } else { $action = readline("Remote ID '{$nonUniqueRemoteIDData['remote_id']}' is used for {$nonUniqueRemoteIDData['cnt']} different tree nodes. Do you want to see the details (d) or do you want this inconsistency to be fixed automatically (a) ?"); while (!in_array($action, array('a', 'd'))) { $action = readline('Invalid option. Type either d for details or a to fix automatically.'); } } $treeNodes = eZPersistentObject::fetchObjectList(eZContentObjectTreeNode::definition(), null, array('remote_id' => $nonUniqueRemoteIDData['remote_id']), array('modified_subnode' => 'asc')); switch ($action) { case 'd': $cli->output(''); $cli->output('Select the number of the tree node that you want to keep the current remote ID. The other listed tree nodes will get a new one.'); $cli->output(''); foreach ($treeNodes as $i => $treeNode) { $nodeID = $treeNode->attribute('node_id'); $dateTime = new eZDateTime($treeNode->attribute('modified_subnode')); $formattedDateTime = $dateTime->toString(true); $pathIdentificationString = $treeNode->attribute('path_identification_string'); $cli->output("{$i}) {$pathIdentificationString} (Node ID: {$nodeID}, modified_subnode: {$formattedDateTime} )"); $cli->output(''); } do { $skip = readline('Number of nodes that should keep the current remote ID: '); } while (!array_key_exists($skip, $treeNodes)); break; case 'a': default: $skip = 0; } $cli->output('Fixing...'); foreach ($treeNodes as $i => $treeNode) {
function createSubNode($node, $name) { $namedChildrenArray = $node->childrenByName($name); $subNode = false; //pk if (!$node->canCreate()) { $this->setError(self::ERROR_ACCESSDENIED, ezpI18n::tr('extension/ezodf/import/error', "Folder for images could not be created, access denied.")); return false; } if (empty($namedChildrenArray)) { $class = eZContentClass::fetchByIdentifier("folder"); $creatorID = $this->currentUserID; //$creatorID = 14; // 14 == admin $parentNodeID = $placeNodeID; $contentObject = $class->instantiate($creatorID, 1); $nodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $contentObject->attribute('id'), 'contentobject_version' => $contentObject->attribute('current_version'), 'parent_node' => $node->attribute('node_id'), 'is_main' => 1)); $nodeAssignment->store(); $version = $contentObject->version(1); $version->setAttribute('modified', eZDateTime::currentTimeStamp()); $version->setAttribute('status', eZContentObjectVersion::STATUS_DRAFT); $version->store(); $contentObjectID = $contentObject->attribute('id'); $dataMap = $contentObject->dataMap(); $titleAttribudeIdentifier = 'name'; $dataMap[$titleAttribudeIdentifier]->setAttribute('data_text', $name); $dataMap[$titleAttribudeIdentifier]->store(); $operationResult = eZOperationHandler::execute('content', 'publish', array('object_id' => $contentObjectID, 'version' => 1)); $subNode = $contentObject->mainNode(); } else { if (count($namedChildrenArray) == 1) { $subNode = $namedChildrenArray[0]; } } return $subNode; }
/** * Creates and publishes a new content object. * * This function takes all the variables passes in the $params * argument and creates a new content object out of it. * * Here is an example * <code> * <?php * * // admin user * $creatorID = 14; * * // folder content class * $classIdentifier = 'folder'; * * // root node * $parentNodeID = 2; * * // have a look at the folder content class' definition ;) * // basically the array is the following : * // key : attribute identifier ( not attribute ID !! ) * // value : value for this attribute * // * // Please refer to each fromString/toString function to see * // how to organize your data * * $xmlDeclaration = '<?xml version="1.0" encoding="utf-8"?> * <section xmlns:image="http://ez.no/namespaces/ezpublish3/image/" * xmlns:xhtml="http://ez.no/namespaces/ezpublish3/xhtml/" * xmlns:custom="http://ez.no/namespaces/ezpublish3/custom/">'; * * $attributeList = array( 'name' => 'A newly created folder object', * 'short_name' => 'A new folder', * 'short_description' => $xmlDeclaration .'<paragraph>This is the short description</paragraph></section>', * 'description' => $xmlDeclaration . '<section><section><header>Some header</header><paragraph>Some paragraph * with a <link target="_blank" url_id="1">link</link></paragraph> * </section></section></section>', * 'show_children' => true); * * // Creates the data import array * $params = array(); * $params['creator_id'] = $creatorID; * $params['class_identifier'] = $classIdentifier; * $params['parent_node_id'] = $parentNodeID; * $params['attributes'] = $attributeList; * * $contentObject = eZContentFunctions::createAndPublishObject( $params ); * * if( $contentObject ) * { * // do anything you want here * } * * ?> * </code> * * @param array $params An array with all the informations to store. * This array must contains a strict list of key/value pairs. * The possible keys are the following : * - 'parent_node_id' : The parentNodeID for this new object. * - 'class_identifier' : The classIdentifier for this new object. * using the classID is not possible. * - 'creator_id' : The eZUser::contentObjectID to use as creator * of this new eZContentObject, uses current user * and stores object id in current session if not set * - 'attributes' : The list of attributes to store, in order to now * which values you can use for this key, you have to * read the code of the fromString and toString functions * of the attribute's datatype you use * - 'storage_dir' : * - 'remote_id' : The value for the remoteID (optional) * - 'section_id' : The value for the sectionID (optional) * @return eZContentObject|false An eZContentObject object if success, false otherwise */ static function createAndPublishObject($params) { $parentNodeID = $params['parent_node_id']; $classIdentifier = $params['class_identifier']; $creatorID = isset($params['creator_id']) ? $params['creator_id'] : false; $attributesData = isset($params['attributes']) ? $params['attributes'] : false; $storageDir = isset($params['storage_dir']) ? $params['storage_dir'] : ''; $contentObject = false; $parentNode = eZContentObjectTreeNode::fetch($parentNodeID, false, false); if (is_array($parentNode)) { $contentClass = eZContentClass::fetchByIdentifier($classIdentifier); if ($contentClass instanceof eZContentClass) { $db = eZDB::instance(); $db->begin(); $languageCode = isset($params['language']) ? $params['language'] : false; $sectionID = isset($params['section_id']) ? $params['section_id'] : 0; $contentObject = $contentClass->instantiate($creatorID, $sectionID, false, $languageCode); if (array_key_exists('remote_id', $params)) { $contentObject->setAttribute('remote_id', $params['remote_id']); } $contentObject->store(); $nodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $contentObject->attribute('id'), 'contentobject_version' => $contentObject->attribute('current_version'), 'parent_node' => $parentNodeID, 'is_main' => 1, 'sort_field' => $contentClass->attribute('sort_field'), 'sort_order' => $contentClass->attribute('sort_order'))); $nodeAssignment->store(); $version = $contentObject->version(1); $version->setAttribute('modified', eZDateTime::currentTimeStamp()); $version->setAttribute('status', eZContentObjectVersion::STATUS_DRAFT); $version->store(); if (is_array($attributesData) && !empty($attributesData)) { $attributes = $contentObject->attribute('contentobject_attributes'); foreach ($attributes as $attribute) { $attributeIdentifier = $attribute->attribute('contentclass_attribute_identifier'); if (isset($attributesData[$attributeIdentifier])) { $dataString = $attributesData[$attributeIdentifier]; switch ($datatypeString = $attribute->attribute('data_type_string')) { case 'ezimage': case 'ezbinaryfile': case 'ezmedia': $dataString = $storageDir . $dataString; break; default: } $attribute->fromString($dataString); $attribute->store(); } } } $db->commit(); $operationResult = eZOperationHandler::execute('content', 'publish', array('object_id' => $contentObject->attribute('id'), 'version' => 1)); } else { eZDebug::writeError("Content class with identifier '{$classIdentifier}' doesn't exist.", __METHOD__); } } else { eZDebug::writeError("Node with id '{$parentNodeID}' doesn't exist.", __METHOD__); } return $contentObject; }
if (!$class) { $cli->error("No class with identifier {$createClass}"); $script->shutdown(1); } $fp = @fopen($inputFileName, "r"); if (!$fp) { $cli->error("Can not open file {$inputFileName} for reading"); $script->shutdown(1); } while ($objectData = fgetcsv($fp, $csvLineLength, ';', '"')) { $contentObject = $class->instantiate($creator); $contentObject->store(); $nodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $contentObject->attribute('id'), 'contentobject_version' => $contentObject->attribute('current_version'), 'parent_node' => $nodeID, 'is_main' => 1)); $nodeAssignment->store(); $version = $contentObject->version(1); $version->setAttribute('modified', eZDateTime::currentTimeStamp()); $version->setAttribute('status', eZContentObjectVersion::STATUS_DRAFT); $version->store(); $contentObjectID = $contentObject->attribute('id'); $attributes = $contentObject->attribute('contentobject_attributes'); while (list($key, $attribute) = each($attributes)) { $dataString = $objectData[$key]; switch ($datatypeString = $attribute->attribute('data_type_string')) { case 'ezimage': case 'ezbinaryfile': case 'ezmedia': $dataString = eZDir::path(array($storageDir, $dataString)); break; default: } $attribute->fromString($dataString);
$nodeObject = eZContentObjectTreeNode::fetch($nodeID); if ($nodeObject != null) { $counter = eZViewCounter::fetch($nodeID); if ($counter == null) { $counter = eZViewCounter::create($nodeID); } $counter->increase(); } } foreach ($pathArray as $path) { $nodeID = eZURLAliasML::fetchNodeIDByPath($path); if ($nodeID) { $counter = eZViewCounter::fetch($nodeID); if ($counter == null) { $counter = eZViewCounter::create($nodeID); } $counter->increase(); } } $dt = new eZDateTime(); $fh = fopen($updateViewLogPath, "w"); if ($fh) { fwrite($fh, "# Finished at " . $dt->toString() . "\n"); fwrite($fh, "# Last updated entry:" . "\n"); fwrite($fh, $lastLine . "\n"); fclose($fh); } $cli->output("Finished at " . $dt->toString() . "\n"); if (!$isQuiet) { $cli->output("View count have been updated!\n"); }
// Try prepending each of the existing pathPrefixes, to see if one of them matches an existing node $nodeID = eZURLAliasML::fetchNodeIDByPath($pathPrefixes[$pathPrefixIndex] . $path); } if ($nodeID) { if (!isset($nodeIDHashCounter[$nodeID])) { $nodeIDHashCounter[$nodeID] = $count; } else { $nodeIDHashCounter[$nodeID] += $count; } } } foreach ($nodeIDHashCounter as $nodeID => $count) { if (eZContentObjectTreeNode::fetch($nodeID) != null) { $counter = eZViewCounter::fetch($nodeID); if ($counter == null) { $counter = eZViewCounter::create($nodeID); $counter->setAttribute('count', $count); $counter->store(); } else { $counter->increase($count); } } } $dt = new eZDateTime(); $fh = fopen($updateViewLogPath, "w"); if ($fh) { fwrite($fh, "# Finished at " . $dt->toString() . "\n" . "# Last updated entry:" . "\n" . $lastLine . "\n"); fclose($fh); } $cli->output("Finished at " . $dt->toString() . "\n"); $cli->output("View count have been updated!\n");
/** * Returns current draft for current content object. * If there is no current draft, a new one will be created in provided language. * @param string|bool $lang Valid locale xxx-XX. If not provided, default edit language will be used * @see eZContentObject::createNewVersionIn() * @return eZContentObjectVersion */ public function getCurrentDraft($lang = false) { $currentDraft = null; $db = eZDB::instance(); // First check if we already have a draft $aFilter = array('contentobject_id' => $this->contentObject->attribute('id'), 'status' => array(array(eZContentObjectVersion::STATUS_DRAFT, eZContentObjectVersion::STATUS_INTERNAL_DRAFT))); $res = eZContentObjectVersion::fetchFiltered($aFilter, null, null); if (count($res) > 0 && $res[0] instanceof eZContentObjectVersion) { $currentDraft = $res[0]; // FIXME : Fetch may result several drafts. We should take the last one (highest version) $currentDraft->setAttribute('modified', eZDateTime::currentTimeStamp()); $currentDraft->setAttribute('status', eZContentObjectVersion::STATUS_DRAFT); $currentDraft->store(); } else { $db->begin(); $currentDraft = $this->contentObject->createNewVersionIn($lang, false, $this->contentObject->attribute('current_version')); $currentDraft->store(); $db->commit(); } return $currentDraft; }
* * @copyright Copyright (C) 1999-2010 eZ Systems AS. All rights reserved. * @license http://ez.no/licenses/gnu_gpl GNU GPLv2 * */ /** * Send comment notification to user who subscribed the content * */ $cli = eZCLI::instance(); if (!$isQuiet) { $cli->output("Start sending comment notification..."); } // 1. check ezcomment_notification table $db = eZDB::instance(); $now = new eZDateTime(); $currentTime = $now->toTime()->timeStamp(); $ezcommentsINI = eZINI::instance('ezcomments.ini'); $sendingNumber = $ezcommentsINI->variable('NotificationSettings', 'NotificationNumberPerExecuation'); $mailContentType = $ezcommentsINI->variable('NotificationSettings', 'MailContentType'); $mailFrom = $ezcommentsINI->variable('NotificationSettings', 'MailFrom'); $contentObjectIDList = $db->arrayQuery('SELECT DISTINCT contentobject_id, language_id' . ' FROM ezcomment_notification ' . 'WHERE status=1' . ' AND send_time < ' . $currentTime, array('offset' => 0, 'limit' => $sendingNumber)); $notificationCount = 0; $mailCount = 0; foreach ($contentObjectIDList as $contentObjectArray) { $contentObjectID = $contentObjectArray['contentobject_id']; $contentLanguage = $contentObjectArray['language_id']; $notifications = $db->arrayQuery('SELECT * FROM ezcomment_notification ' . 'WHERE contentobject_id = ' . $contentObjectID); // fetch content object $contentObject = eZContentObject::fetch($contentObjectID, true); $contentLanguageLocale = eZContentLanguage::fetch($contentLanguage)->attribute('locale');
/** * Writes a "token file" * This is useful whenever there are log files which get parse based on cronjobs * and we have to remember the last line which has been found */ protected static function writeUpdateToken($tokenFile, $tokenLine) { $sys = eZSys::instance(); $updateViewLogPath = $sys->varDirectory() . "/" . eZPerfLoggerINI::variable('FileSettings', 'LogDir', 'site.ini') . "/" . $tokenFile; $dt = new eZDateTime(); if (!file_put_contents($updateViewLogPath, "# Finished at " . $dt->toString() . "\n" . "# Last updated entry:" . "\n" . $tokenLine . "\n")) { eZPerfLoggerDebug::writeError("Could not store last date of perf-log file parsing in {$updateViewLogPath}, double-counting might occur", __METHOD__); } }
function batchInitializeObjectAttributeData( $classAttribute ) { $defaultType = $classAttribute->attribute( self::DEFAULT_FIELD ); switch( $defaultType ) { case self::DEFAULT_CURRENT_DATE: { $default = time(); } break; case self::DEFAULT_ADJUSTMENT: { $adjustments = $this->classAttributeContent( $classAttribute ); $value = new eZDateTime(); $secondAdjustment = $classAttribute->attribute( self::USE_SECONDS_FIELD ) == 1 ? $adjustments['second'] : 0; $value->adjustDateTime( $adjustments['hour'], $adjustments['minute'], $secondAdjustment, $adjustments['month'], $adjustments['day'], $adjustments['year'] ); $default = $value->timeStamp(); } break; default: { $default = 0; } } return array( 'data_int' => $default, 'sort_key_int' => $default ); }
/** * Creates a new version for content. * If content is a new one, a new node assignment will be created with 'parent_node_id' option ({@link self::setOptions()}) * @param SQLIContent $content * @internal * @return eZContentObjectVersion */ private function createNewVersion(SQLIContent $content) { eZDebug::accumulatorStart('sqlicontentpublisher_version', 'sqlicontentpublisher', 'Version creation'); $contentObject = $content->getRawContentObject(); if ($content->isNew()) { $nodeAssignment = $this->createNodeAssignmentForContent($content, $this->options['parent_node_id'], true); // Main node assignment for new object $version = $contentObject->currentVersion(); $version->setAttribute('modified', eZDateTime::currentTimeStamp()); $version->setAttribute('status', eZContentObjectVersion::STATUS_DRAFT); $version->store(); } else { $version = $content->getDraft(); } eZDebug::accumulatorStop('sqlicontentpublisher_version'); return $version; }
$scriptFile = $scriptDirectory . '/' . $cronScript; if (file_exists($scriptFile)) { break; } } if (file_exists($scriptFile)) { if ($index > 0) { $cli->output(); } if (!$isQuiet) { $startTime = new eZDateTime(); $cli->output('Running ' . $cli->stylize('emphasize', $scriptFile) . ' at: ' . $startTime->toString(true)); } eZDebug::addTimingPoint("Script {$scriptFile} starting"); eZRunCronjobs::runScript($cli, $scriptFile); eZDebug::addTimingPoint("Script {$scriptFile} done"); ++$index; // The transaction check $transactionCounterCheck = eZDB::checkTransactionCounter(); if (isset($transactionCounterCheck['error'])) { $cli->error($transactionCounterCheck['error']); } if (!$isQuiet) { $endTime = new eZDateTime(); $cli->output('Completing ' . $cli->stylize('emphasize', $scriptFile) . ' at: ' . $endTime->toString(true)); $elapsedTime = new eZTime($endTime->timeStamp() - $startTime->timeStamp()); $cli->output('Elapsed time: ' . sprintf('%02d:%02d:%02d', $elapsedTime->hour(), $elapsedTime->minute(), $elapsedTime->second())); } } } $script->shutdown();
$logFilePath = ''; $plIni = eZINI::instance('ezperformancelogger.ini'); $logTo = $plIni->variable('GeneralSettings', 'LogMethods'); if (in_array('apache', $logTo) && !in_array('logfile', $logTo)) { $logFileIni = eZINI::instance('logfile.ini'); $logFilePath = $logFileIni->variable('AccessLogFileSettings', 'StorageDir') . '/' . $logFileIni->variable('AccessLogFileSettings', 'LogFileName'); } else { if (!in_array('apache', $logTo) && in_array('logfile', $logTo)) { $logFilePath = $plIni->variable('logfileSettings', 'FileName'); } else { $cli->error("Cannot decide which log-file to open for reading, please enable either apache-based logging or file-based logging."); $script->shutdown(1); } } if ($logFilePath != '') { $cli->output("Parsing file " . $logFilePath); $storageClass = $plIni->variable('ParsingSettings', 'StorageClass'); $excludeRegexps = $plIni->variable('ParsingSettings', 'ExcludeUrls'); $ok = eZPerfLoggerLogManager::updateStatsFromLogFile($logFilePath, 'eZPerfLoggerApacheLogger', $storageClass, 'updateperfstats.log', $excludeRegexps); if ($ok === false) { $cli->output("Error parsing file {$logFilePath}. Please run script in debug mode for more info"); } else { $cli->output("{$ok['counted']} lines containing data found"); } } $dt = new eZDateTime(); $cli->output("Finished at " . $dt->toString() . "\n"); if ($script->verboseOutputLevel() > 0) { $cli->output("Perf counters have been updated\n"); } $script->shutdown();
public function search($searchText, $params = array(), $searchTypes = array()) { if (count($searchTypes) == 0) { $searchTypes['general'] = array(); $searchTypes['subtype'] = array(); $searchTypes['and'] = array(); } else { if (!isset($searchTypes['general'])) { $searchTypes['general'] = array(); } } $allowSearch = true; if (trim($searchText) == '') { $ini = eZINI::instance(); if ($ini->variable('SearchSettings', 'AllowEmptySearch') != 'enabled') { $allowSearch = false; } if (isset($params['AllowEmptySearch'])) { $allowSearch = $params['AllowEmptySearch']; } } if ($allowSearch) { $searchText = $this->normalizeText($searchText, false); $db = eZDB::instance(); $nonExistingWordArray = array(); $searchTypeMap = array('class' => 'SearchContentClassID', 'publishdate' => 'SearchDate', 'subtree' => 'SearchSubTreeArray'); foreach ($searchTypes['general'] as $searchType) { $params[$searchTypeMap[$searchType['subtype']]] = $searchType['value']; } if (isset($params['SearchOffset'])) { $searchOffset = $params['SearchOffset']; } else { $searchOffset = 0; } if (isset($params['SearchLimit'])) { $searchLimit = $params['SearchLimit']; } else { $searchLimit = 10; } if (isset($params['SearchContentClassID'])) { $searchContentClassID = $params['SearchContentClassID']; } else { $searchContentClassID = -1; } if (isset($params['SearchSectionID'])) { $searchSectionID = $params['SearchSectionID']; } else { $searchSectionID = -1; } if (isset($params['SearchDate'])) { $searchDate = $params['SearchDate']; } else { $searchDate = -1; } if (isset($params['SearchTimestamp'])) { $searchTimestamp = $params['SearchTimestamp']; } else { $searchTimestamp = false; } if (isset($params['SearchContentClassAttributeID'])) { $searchContentClassAttributeID = $params['SearchContentClassAttributeID']; } else { $searchContentClassAttributeID = -1; } if (isset($params['SearchSubTreeArray'])) { $subTreeArray = $params['SearchSubTreeArray']; } else { $subTreeArray = array(); } if (isset($params['SortArray'])) { $sortArray = $params['SortArray']; } else { $sortArray = array(); } $ignoreVisibility = isset($params['IgnoreVisibility']) ? $params['IgnoreVisibility'] : false; // strip multiple spaces $searchText = preg_replace("(\\s+)", " ", $searchText); // find the phrases /* $numQuotes = substr_count( $searchText, "\"" ); $phraseTextArray = array(); $fullText = $searchText; $nonPhraseText =''; // $fullText = ''; $postPhraseText = $fullText; $pos = 0; if ( ( $numQuotes > 0 ) and ( ( $numQuotes % 2 ) == 0 ) ) { for ( $i = 0; $i < ( $numQuotes / 2 ); $i ++ ) { $quotePosStart = strpos( $searchText, '"', $pos ); $quotePosEnd = strpos( $searchText, '"', $quotePosStart + 1 ); $prePhraseText = substr( $searchText, $pos, $quotePosStart - $pos ); $postPhraseText = substr( $searchText, $quotePosEnd +1 ); $phraseText = substr( $searchText, $quotePosStart + 1, $quotePosEnd - $quotePosStart - 1 ); $phraseTextArray[] = $phraseText; // $fullText .= $prePhraseText; $nonPhraseText .= $prePhraseText; $pos = $quotePosEnd + 1; } } $nonPhraseText .= $postPhraseText; */ $phrasesResult = $this->getPhrases($searchText); $phraseTextArray = $phrasesResult['phrases']; $nonPhraseText = $phrasesResult['nonPhraseText']; $fullText = $phrasesResult['fullText']; $sectionQuery = ''; if (is_numeric($searchSectionID) and $searchSectionID > 0) { $sectionQuery = "ezsearch_object_word_link.section_id = '{$searchSectionID}' AND "; } else { if (is_array($searchSectionID)) { // Build query for searching in an array of sections $sectionQuery = $db->generateSQLINStatement($searchSectionID, 'ezsearch_object_word_link.section_id', false, false, 'int') . " AND "; } } $searchDateQuery = ''; if (is_numeric($searchDate) and $searchDate > 0 or $searchTimestamp) { $date = new eZDateTime(); $timestamp = $date->timeStamp(); $day = $date->attribute('day'); $month = $date->attribute('month'); $year = $date->attribute('year'); $publishedDateStop = false; if ($searchTimestamp) { if (is_array($searchTimestamp)) { $publishedDate = (int) $searchTimestamp[0]; $publishedDateStop = (int) $searchTimestamp[1]; } else { $publishedDate = (int) $searchTimestamp; } } else { switch ($searchDate) { case 1: $adjustment = 24 * 60 * 60; //seconds for one day $publishedDate = $timestamp - $adjustment; break; case 2: $adjustment = 7 * 24 * 60 * 60; //seconds for one week $publishedDate = $timestamp - $adjustment; break; case 3: $adjustment = 31 * 24 * 60 * 60; //seconds for one month $publishedDate = $timestamp - $adjustment; break; case 4: $adjustment = 3 * 31 * 24 * 60 * 60; //seconds for three months $publishedDate = $timestamp - $adjustment; break; case 5: $adjustment = 365 * 24 * 60 * 60; //seconds for one year $publishedDate = $timestamp - $adjustment; break; default: $publishedDate = $date->timeStamp(); } } $searchDateQuery = "ezsearch_object_word_link.published >= '{$publishedDate}' AND "; if ($publishedDateStop) { $searchDateQuery .= "ezsearch_object_word_link.published <= '{$publishedDateStop}' AND "; } $this->GeneralFilter['searchDateQuery'] = $searchDateQuery; } $classQuery = ""; if (is_numeric($searchContentClassID) and $searchContentClassID > 0) { // Build query for searching in one class $classQuery = "ezsearch_object_word_link.contentclass_id = '{$searchContentClassID}' AND "; $this->GeneralFilter['classAttributeQuery'] = $classQuery; } else { if (is_array($searchContentClassID)) { // Build query for searching in a number of classes $classString = $db->generateSQLINStatement($searchContentClassID, 'ezsearch_object_word_link.contentclass_id', false, false, 'int'); $classQuery = "{$classString} AND "; $this->GeneralFilter['classAttributeQuery'] = $classQuery; } } $classAttributeQuery = ""; if (is_numeric($searchContentClassAttributeID) and $searchContentClassAttributeID > 0) { $classAttributeQuery = "ezsearch_object_word_link.contentclass_attribute_id = '{$searchContentClassAttributeID}' AND "; } else { if (is_array($searchContentClassAttributeID)) { // Build query for searching in a number of attributes $classAttributeQuery = $db->generateSQLINStatement($searchContentClassAttributeID, 'ezsearch_object_word_link.contentclass_attribute_id', false, false, 'int') . ' AND '; } } // Get the total number of objects $totalObjectCount = $this->fetchTotalObjectCount(); $searchPartsArray = array(); $wordIDHash = array(); $wildCardCount = 0; if (trim($searchText) != '') { $wordIDArrays = $this->prepareWordIDArrays($searchText); $wordIDArray = $wordIDArrays['wordIDArray']; $wordIDHash = $wordIDArrays['wordIDHash']; $wildIDArray = $wordIDArrays['wildIDArray']; $wildCardCount = $wordIDArrays['wildCardCount']; $searchPartsArray = $this->buildSearchPartArray($phraseTextArray, $nonPhraseText, $wordIDHash, $wildIDArray); } /// OR search, not used in this version $doOrSearch = false; if ($doOrSearch == true) { // build fulltext search SQL part $searchWordArray = $this->splitString($fullText); $fullTextSQL = ""; if (count($searchWordArray) > 0) { $i = 0; // Build the word query string foreach ($searchWordArray as $searchWord) { $wordID = null; if (isset($wordIDHash[$searchWord])) { $wordID = $wordIDHash[$searchWord]['id']; } if (is_numeric($wordID) and $wordID > 0) { if ($i == 0) { $fullTextSQL .= "ezsearch_object_word_link.word_id='{$wordID}' "; } else { $fullTextSQL .= " OR ezsearch_object_word_link.word_id='{$wordID}' "; } } else { $nonExistingWordArray[] = $searchWord; } $i++; } $fullTextSQL = " ( {$fullTextSQL} ) AND "; } } // Search only in specific sub trees $subTreeSQL = ""; $subTreeTable = ""; if (count($subTreeArray) > 0) { // Fetch path_string value to use when searching subtrees $i = 0; $doSubTreeSearch = false; $subTreeNodeSQL = ''; foreach ($subTreeArray as $nodeID) { if (is_numeric($nodeID) and $nodeID > 0) { $subTreeNodeSQL .= " {$nodeID}"; if (isset($subTreeArray[$i + 1]) and is_numeric($subTreeArray[$i + 1])) { $subTreeNodeSQL .= ", "; } $doSubTreeSearch = true; } $i++; } if ($doSubTreeSearch == true) { $subTreeNodeSQL = "( " . $subTreeNodeSQL; // $subTreeTable = ", ezcontentobject_tree "; $subTreeTable = ''; $subTreeNodeSQL .= " ) "; $nodeQuery = "SELECT node_id, path_string FROM ezcontentobject_tree WHERE node_id IN {$subTreeNodeSQL}"; // Build SQL subtre search query $subTreeSQL = " ( "; $nodeArray = $db->arrayQuery($nodeQuery); $i = 0; foreach ($nodeArray as $node) { $pathString = $node['path_string']; $subTreeSQL .= " ezcontentobject_tree.path_string like '{$pathString}%' "; if ($i < count($nodeArray) - 1) { $subTreeSQL .= " OR "; } $i++; } $subTreeSQL .= " ) AND "; $this->GeneralFilter['subTreeTable'] = $subTreeTable; $this->GeneralFilter['subTreeSQL'] = $subTreeSQL; } } $limitation = false; if (isset($params['Limitation'])) { $limitation = $params['Limitation']; } $limitationList = eZContentObjectTreeNode::getLimitationList($limitation); $sqlPermissionChecking = eZContentObjectTreeNode::createPermissionCheckingSQL($limitationList); $this->GeneralFilter['sqlPermissionChecking'] = $sqlPermissionChecking; $versionNameJoins = " AND " . eZContentLanguage::sqlFilter('ezcontentobject_name', 'ezcontentobject'); /// Only support AND search at this time // build fulltext search SQL part $searchWordArray = $this->splitString($fullText); $searchWordCount = count($searchWordArray); $fullTextSQL = ""; $stopWordArray = array(); $ini = eZINI::instance(); $tmpTableCount = 0; $i = 0; foreach ($searchTypes['and'] as $searchType) { $methodName = $this->constructMethodName($searchType); $intermediateResult = $this->callMethod($methodName, array($searchType)); if ($intermediateResult == false) { // cleanup temp tables $db->dropTempTableList($sqlPermissionChecking['temp_tables']); return array("SearchResult" => array(), "SearchCount" => 0, "StopWordArray" => array()); } } // Do not execute search if site.ini:[SearchSettings]->AllowEmptySearch is enabled, but no conditions are set. if (!$searchDateQuery && !$sectionQuery && !$classQuery && !$classAttributeQuery && !$searchPartsArray && !$subTreeSQL) { // cleanup temp tables $db->dropTempTableList($sqlPermissionChecking['temp_tables']); return array("SearchResult" => array(), "SearchCount" => 0, "StopWordArray" => array()); } $i = $this->TempTablesCount; // Loop every word and insert result in temporary table // Determine whether we should search invisible nodes. $showInvisibleNodesCond = eZContentObjectTreeNode::createShowInvisibleSQLString(!$ignoreVisibility); foreach ($searchPartsArray as $searchPart) { $stopWordThresholdValue = 100; if ($ini->hasVariable('SearchSettings', 'StopWordThresholdValue')) { $stopWordThresholdValue = $ini->variable('SearchSettings', 'StopWordThresholdValue'); } $stopWordThresholdPercent = 60; if ($ini->hasVariable('SearchSettings', 'StopWordThresholdPercent')) { $stopWordThresholdPercent = $ini->variable('SearchSettings', 'StopWordThresholdPercent'); } $searchThresholdValue = $totalObjectCount; if ($totalObjectCount > $stopWordThresholdValue) { $searchThresholdValue = (int) ($totalObjectCount * ($stopWordThresholdPercent / 100)); } // do not search words that are too frequent if ($searchPart['object_count'] < $searchThresholdValue) { $tmpTableCount++; $searchPartText = $searchPart['sql_part']; if ($i == 0) { $table = $db->generateUniqueTempTableName('ezsearch_tmp_%', 0); $this->saveCreatedTempTableName(0, $table); $db->createTempTable("CREATE TEMPORARY TABLE {$table} ( contentobject_id int primary key not null, published int )"); $db->query("INSERT INTO {$table} SELECT DISTINCT ezsearch_object_word_link.contentobject_id, ezsearch_object_word_link.published\n FROM ezcontentobject\n INNER JOIN ezsearch_object_word_link ON (ezsearch_object_word_link.contentobject_id = ezcontentobject.id)\n {$subTreeTable}\n INNER JOIN ezcontentclass ON (ezcontentclass.id = ezcontentobject.contentclass_id)\n INNER JOIN ezcontentobject_tree ON (ezcontentobject_tree.contentobject_id = ezcontentobject.id)\n {$sqlPermissionChecking['from']}\n WHERE\n {$searchDateQuery}\n {$sectionQuery}\n {$classQuery}\n {$classAttributeQuery}\n {$searchPartText}\n {$subTreeSQL}\n ezcontentclass.version = '0' AND\n ezcontentobject_tree.node_id = ezcontentobject_tree.main_node_id\n {$showInvisibleNodesCond}\n {$sqlPermissionChecking['where']}", eZDBInterface::SERVER_SLAVE); } else { $table = $db->generateUniqueTempTableName('ezsearch_tmp_%', $i); $this->saveCreatedTempTableName($i, $table); $tmpTable0 = $this->getSavedTempTableName(0); $db->createTempTable("CREATE TEMPORARY TABLE {$table} ( contentobject_id int primary key not null, published int )"); $db->query("INSERT INTO {$table} SELECT DISTINCT ezsearch_object_word_link.contentobject_id, ezsearch_object_word_link.published\n FROM\n ezcontentobject\n INNER JOIN ezsearch_object_word_link ON (ezsearch_object_word_link.contentobject_id = ezcontentobject.id)\n {$subTreeTable}\n INNER JOIN ezcontentclass ON (ezcontentclass.id = ezcontentobject.contentclass_id)\n INNER JOIN ezcontentobject_tree ON (ezcontentobject_tree.contentobject_id = ezcontentobject.id)\n INNER JOIN {$tmpTable0} ON ({$tmpTable0}.contentobject_id = ezsearch_object_word_link.contentobject_id)\n {$sqlPermissionChecking['from']}\n WHERE\n {$searchDateQuery}\n {$sectionQuery}\n {$classQuery}\n {$classAttributeQuery}\n {$searchPartText}\n {$subTreeSQL}\n ezcontentclass.version = '0' AND\n ezcontentobject_tree.node_id = ezcontentobject_tree.main_node_id\n {$showInvisibleNodesCond}\n {$sqlPermissionChecking['where']}", eZDBInterface::SERVER_SLAVE); } $i++; } else { $stopWordArray[] = array('word' => $searchPart['text']); } } if (count($searchPartsArray) === 0 && $this->TempTablesCount == 0) { $table = $db->generateUniqueTempTableName('ezsearch_tmp_%', 0); $this->saveCreatedTempTableName(0, $table); $db->createTempTable("CREATE TEMPORARY TABLE {$table} ( contentobject_id int primary key not null, published int )"); $db->query("INSERT INTO {$table} SELECT DISTINCT ezsearch_object_word_link.contentobject_id, ezsearch_object_word_link.published\n FROM ezcontentobject\n INNER JOIN ezsearch_object_word_link ON (ezsearch_object_word_link.contentobject_id = ezcontentobject.id)\n {$subTreeTable}\n INNER JOIN ezcontentclass ON (ezcontentclass.id = ezcontentobject.contentclass_id)\n INNER JOIN ezcontentobject_tree ON (ezcontentobject_tree.contentobject_id = ezcontentobject.id)\n {$sqlPermissionChecking['from']}\n WHERE\n {$searchDateQuery}\n {$sectionQuery}\n {$classQuery}\n {$classAttributeQuery}\n {$subTreeSQL}\n ezcontentclass.version = '0' AND\n ezcontentobject_tree.node_id = ezcontentobject_tree.main_node_id\n {$showInvisibleNodesCond}\n {$sqlPermissionChecking['where']}", eZDBInterface::SERVER_SLAVE); $this->TempTablesCount = 1; $i = $this->TempTablesCount; } $nonExistingWordCount = count(array_unique($searchWordArray)) - count($wordIDHash) - $wildCardCount; $excludeWordCount = $searchWordCount - count($stopWordArray); if (count($stopWordArray) + $nonExistingWordCount == $searchWordCount && $this->TempTablesCount == 0) { // No words to search for, return empty result // cleanup temp tables $db->dropTempTableList($sqlPermissionChecking['temp_tables']); $db->dropTempTableList($this->getSavedTempTablesList()); return array("SearchResult" => array(), "SearchCount" => 0, "StopWordArray" => $stopWordArray); } $tmpTablesFrom = ""; $tmpTablesWhere = ""; /// tmp tables $tmpTableCount = $i; for ($i = 0; $i < $tmpTableCount; $i++) { $tmpTablesFrom .= $this->getSavedTempTableName($i); if ($i < $tmpTableCount - 1) { $tmpTablesFrom .= ", "; } } $tmpTablesSeparator = ''; if ($tmpTableCount > 0) { $tmpTablesSeparator = ', '; } $tmpTable0 = $this->getSavedTempTableName(0); for ($i = 1; $i < $tmpTableCount; $i++) { $tmpTableI = $this->getSavedTempTableName($i); $tmpTablesWhere .= " {$tmpTable0}.contentobject_id={$tmpTableI}.contentobject_id "; if ($i < $tmpTableCount - 1) { $tmpTablesWhere .= " AND "; } } $tmpTablesWhereExtra = ''; if ($tmpTableCount > 0) { $tmpTablesWhereExtra = "ezcontentobject.id={$tmpTable0}.contentobject_id AND"; } $and = ""; if ($tmpTableCount > 1) { $and = " AND "; } // Generate ORDER BY SQL $orderBySQLArray = $this->buildSortSQL($sortArray); $orderByFieldsSQL = $orderBySQLArray['sortingFields']; $sortWhereSQL = $orderBySQLArray['whereSQL']; $sortFromSQL = $orderBySQLArray['fromSQL']; $sortSelectSQL = $orderBySQLArray['selectSQL']; // Fetch data from table $searchQuery = ''; $searchQuery = "SELECT DISTINCT ezcontentobject.*, ezcontentclass.serialized_name_list as class_serialized_name_list,\n ezcontentobject_tree.*, ezcontentobject_name.name as name,\n ezcontentobject_name.real_translation {$sortSelectSQL}\n FROM\n {$tmpTablesFrom} {$tmpTablesSeparator}\n ezcontentobject\n INNER JOIN ezcontentclass ON (ezcontentclass.id = ezcontentobject.contentclass_id )\n INNER JOIN ezcontentobject_tree ON (ezcontentobject_tree.contentobject_id = ezcontentobject.id)\n INNER JOIN ezcontentobject_name ON (\n ezcontentobject_name.contentobject_id = ezcontentobject_tree.contentobject_id AND\n ezcontentobject_name.content_version = ezcontentobject_tree.contentobject_version\n )\n {$sortFromSQL}\n WHERE\n {$tmpTablesWhere} {$and}\n {$tmpTablesWhereExtra}\n ezcontentclass.version = '0' AND\n ezcontentobject_tree.node_id = ezcontentobject_tree.main_node_id AND\n " . eZContentLanguage::sqlFilter('ezcontentobject_name', 'ezcontentobject') . "\n {$showInvisibleNodesCond}\n {$sortWhereSQL}\n ORDER BY {$orderByFieldsSQL}"; // Count query $languageCond = eZContentLanguage::languagesSQLFilter('ezcontentobject'); if ($tmpTableCount == 0) { $searchCountQuery = "SELECT count( DISTINCT ezcontentobject.id ) AS count\n FROM\n ezcontentobject,\n ezcontentobject_tree\n WHERE\n ezcontentobject.id = ezcontentobject_tree.contentobject_id and\n ezcontentobject_tree.node_id = ezcontentobject_tree.main_node_id\n AND {$languageCond}\n {$showInvisibleNodesCond}"; } else { $searchCountQuery = "SELECT count( DISTINCT ezcontentobject.id ) AS count\n FROM {$tmpTablesFrom} {$tmpTablesSeparator}\n ezcontentobject\n WHERE {$tmpTablesWhere} {$and}\n {$tmpTablesWhereExtra}\n {$languageCond}"; } $objectRes = array(); $searchCount = 0; if ($nonExistingWordCount <= 0) { // execute search query $objectResArray = $db->arrayQuery($searchQuery, array("limit" => $searchLimit, "offset" => $searchOffset), eZDBInterface::SERVER_SLAVE); // execute search count query $objectCountRes = $db->arrayQuery($searchCountQuery, array(), eZDBInterface::SERVER_SLAVE); $objectRes = eZContentObjectTreeNode::makeObjectsArray($objectResArray); $searchCount = $objectCountRes[0]['count']; } else { $objectRes = array(); } // Drop tmp tables $db->dropTempTableList($sqlPermissionChecking['temp_tables']); $db->dropTempTableList($this->getSavedTempTablesList()); return array("SearchResult" => $objectRes, "SearchCount" => $searchCount, "StopWordArray" => $stopWordArray); } else { return array("SearchResult" => array(), "SearchCount" => 0, "StopWordArray" => array()); } }
function getTimestamp($http, $id) { $day = $http->postVariable('newsletter_datetime_day_' . $id); $month = $http->postVariable('newsletter_datetime_month_' . $id); $year = $http->postVariable('newsletter_datetime_year_' . $id); $hour = $http->postVariable('newsletter_datetime_hour_' . $id); $minute = $http->postVariable('newsletter_datetime_minute_' . $id); $dateTime = new eZDateTime(); if ($year == '' and $month == '' and $day == '' and $hour == '' and $minute == '' or !checkdate($month, $day, $year) or $year < 1970) { $dateTime->setTimeStamp(0); } else { $dateTime->setMDYHMS($month, $day, $year, $hour, $minute, 0); } return $dateTime->timeStamp(); }