Deprecation: from 4.3, removed in 4.4, use newscoop.cache service
Ejemplo n.º 1
0
 /**
  * Get cache object
  * @return CampCache
  */
 public function getCache()
 {
     if ($this->cache === NULL) {
         $this->cache = CampCache::singleton();
     }
     return $this->cache;
 }
Ejemplo n.º 2
0
 /**
  * Gets an issues list based on the given parameters.
  *
  * @param integer $p_context_id
  *    The Context Box Identifier
  * @param string $p_order
  *    An array of columns and directions to order by
  * @param integer $p_start
  *    The record number to start the list
  * @param integer $p_limit
  *    The offset. How many records from $p_start will be retrieved.
  * @param integer $p_count
  *    The total count of the elements; this count is computed without
  *    applying the start ($p_start) and limit parameters ($p_limit)
  *
  * @return array $issuesList
  *    An array of Issue objects
  */
 public static function GetList(array $params, $p_order = null, $p_start = 0, $p_limit = 0, &$p_count, $p_skipCache = false)
 {
     global $g_ado_db;
     if (!$p_skipCache && CampCache::IsEnabled()) {
         $paramsArray['parameters'] = serialize($params);
         $paramsArray['order'] = is_null($p_order) ? 'id' : $p_order;
         $paramsArray['start'] = $p_start;
         $paramsArray['limit'] = $p_limit;
         $cacheListObj = new CampCacheList($paramsArray, __METHOD__);
         $issuesList = $cacheListObj->fetchFromCache();
         if ($issuesList !== false && is_array($issuesList)) {
             return $issuesList;
         }
     }
     if (isset($params['role']) && $params['role'] == 'child') {
         $sql = 'SELECT b.fk_article_no FROM context_boxes b, Articles a0' . ' WHERE a0.Number = b.fk_article_no AND ' . ' a0.Type = "dossier" AND ' . ' b.id IN (SELECT c.fk_context_id ' . '     FROM Articles a, context_articles c ' . '     WHERE c.fk_article_no = ' . $params['article'] . '     AND a.Number = c.fk_article_no)' . ' ORDER BY a0.PublishDate DESC';
     } else {
         $sql = 'SELECT fk_article_no FROM context_articles' . ' WHERE fk_context_id = ' . $params['context_box'] . ' ORDER BY id';
     }
     if ($p_limit > 0) {
         $sql .= ' LIMIT ' . $p_limit;
     }
     $returnArray = array();
     $rows = $g_ado_db->GetAll($sql);
     if (is_array($rows)) {
         foreach ($rows as $row) {
             $returnArray[] = $row['fk_article_no'];
         }
     }
     $p_count = count($returnArray);
     return $returnArray;
 }
Ejemplo n.º 3
0
 /**
  * Gets an issues list based on the given parameters.
  *
  * @param integer $p_context_id
  *    The Context Box Identifier
  * @param string $p_order
  *    An array of columns and directions to order by
  * @param integer $p_start
  *    The record number to start the list
  * @param integer $p_limit
  *    The offset. How many records from $p_start will be retrieved.
  * @param integer $p_count
  *    The total count of the elements; this count is computed without
  *    applying the start ($p_start) and limit parameters ($p_limit)
  *
  * @return array $issuesList
  *    An array of Issue objects
  */
 public static function GetList($p_context_id, $p_order = null, $p_start = 0, $p_limit = 0, &$p_count, $p_skipCache = false)
 {
     global $g_ado_db;
     if (!$p_skipCache && CampCache::IsEnabled()) {
         $paramsArray['parameters'] = serialize($p_parameters);
         $paramsArray['order'] = is_null($p_order) ? 'id desc' : $p_order;
         $paramsArray['start'] = $p_start;
         $paramsArray['limit'] = $p_limit;
         $cacheListObj = new CampCacheList($paramsArray, __METHOD__);
         $issuesList = $cacheListObj->fetchFromCache();
         if ($issuesList !== false && is_array($issuesList)) {
             return $issuesList;
         }
     }
     $returnArray = array();
     $sql = 'SELECT fk_article_no FROM context_articles
             WHERE fk_context_id = ' . $p_context_id . '
             ORDER BY id desc';
     $rows = $g_ado_db->GetAll($sql);
     if (is_array($rows)) {
         foreach ($rows as $row) {
             $returnArray[] = $row['fk_article_no'];
         }
     }
     $p_count = count($returnArray);
     return array_reverse($returnArray);
 }
Ejemplo n.º 4
0
 /**
  * Legacy admin bootstrap
  */
 protected function _initNewscoop()
 {
     global $ADMIN, $g_user, $prefix, $Campsite;
     defined('WWW_DIR') || define('WWW_DIR', realpath(APPLICATION_PATH . '/../'));
     defined('LIBS_DIR') || define('LIBS_DIR', WWW_DIR . '/admin-files/libs');
     $GLOBALS['g_campsiteDir'] = WWW_DIR;
     require_once $GLOBALS['g_campsiteDir'] . DIRECTORY_SEPARATOR . 'include' . DIRECTORY_SEPARATOR . 'campsite_constants.php';
     require_once CS_PATH_CONFIG . DIR_SEP . 'install_conf.php';
     // goes to install process if configuration files does not exist yet
     if (!file_exists(CS_PATH_CONFIG . DIR_SEP . 'configuration.php') || !file_exists(CS_PATH_CONFIG . DIR_SEP . 'database_conf.php')) {
         header('Location: ' . $Campsite['SUBDIR'] . '/install/');
         exit;
     }
     require_once CS_PATH_CONFIG . DIR_SEP . 'database_conf.php';
     require_once CS_PATH_SITE . DIR_SEP . 'include' . DIR_SEP . 'campsite_init.php';
     require_once CS_PATH_SITE . DIR_SEP . 'classes' . DIR_SEP . 'CampTemplateCache.php';
     // detect extended login/logout files
     $prefix = file_exists(CS_PATH_SITE . DIR_SEP . 'admin-files' . DIR_SEP . 'ext_login.php') ? '/ext_' : '/';
     require_once CS_PATH_SITE . '/admin-files/camp_html.php';
     require_once CS_PATH_CLASSES . DIR_SEP . 'SecurityToken.php';
     if (php_sapi_name() !== 'cli') {
         set_error_handler(function ($p_number, $p_string, $p_file, $p_line) {
             error_log(sprintf('Newscoop error: %s in %s:%d', $p_string, $p_file, $p_line));
             global $Campsite;
             require_once $Campsite['HTML_DIR'] . "/admin-files/bugreporter/bug_handler_main.php";
             camp_bug_handler_main($p_number, $p_string, $p_file, $p_line);
         }, error_reporting());
     }
     if (file_exists($Campsite['HTML_DIR'] . '/reset_cache')) {
         CampCache::singleton()->clear('user');
         unlink($GLOBALS['g_campsiteDir'] . '/reset_cache');
     }
 }
Ejemplo n.º 5
0
 public function delete()
 {
     $deleted = parent::delete();
     $CampCache = CampCache::singleton();
     $CampCache->clear('user');
     return $deleted;
 }
Ejemplo n.º 6
0
 /**
  * Singleton function that returns the global class object.
  *
  * @return CampCache
  */
 public static function singleton()
 {
     if (is_null(self::$m_instance)) {
         $preferencesService = \Zend_Registry::get('container')->getService('system_preferences_service');
         self::$m_instance = new CampCache($preferencesService->DBCacheEngine);
     }
     return self::$m_instance;
 }
Ejemplo n.º 7
0
 /**
  * Legacy admin bootstrap
  */
 protected function _initNewscoop()
 {
     global $ADMIN_DIR, $ADMIN, $g_user, $prefix, $Campsite;
     defined('WWW_DIR') || define('WWW_DIR', realpath(APPLICATION_PATH . '/../'));
     defined('LIBS_DIR') || define('LIBS_DIR', WWW_DIR . '/admin-files/libs');
     $GLOBALS['g_campsiteDir'] = WWW_DIR;
     require_once $GLOBALS['g_campsiteDir'] . DIRECTORY_SEPARATOR . 'include' . DIRECTORY_SEPARATOR . 'campsite_constants.php';
     require_once CS_PATH_CONFIG . DIR_SEP . 'install_conf.php';
     // goes to install process if configuration files does not exist yet
     if (!file_exists(CS_PATH_CONFIG . DIR_SEP . 'configuration.php') || !file_exists(CS_PATH_CONFIG . DIR_SEP . 'database_conf.php')) {
         header('Location: ' . $Campsite['SUBDIR'] . '/install/');
         exit;
     }
     require_once CS_PATH_CONFIG . DIR_SEP . 'database_conf.php';
     require_once CS_PATH_SITE . DIR_SEP . 'include' . DIR_SEP . 'campsite_init.php';
     require_once CS_PATH_SITE . DIR_SEP . 'classes' . DIR_SEP . 'CampTemplateCache.php';
     // detect extended login/logout files
     $prefix = file_exists(CS_PATH_SITE . DIR_SEP . 'admin-files' . DIR_SEP . 'ext_login.php') ? '/ext_' : '/';
     require_once CS_PATH_SITE . DIR_SEP . $ADMIN_DIR . DIR_SEP . 'camp_html.php';
     require_once CS_PATH_CLASSES . DIR_SEP . 'SecurityToken.php';
     // load if possible before setting camp_report_bug error handler
     // to prevent error messages
     include_once 'HTML/QuickForm.php';
     include_once 'HTML/QuickForm/RuleRegistry.php';
     include_once 'HTML/QuickForm/group.php';
     if (!defined('IN_PHPUNIT') && !getenv('PLZSTOPTHISERRORHANDLERBIZNIS')) {
         set_error_handler(function ($p_number, $p_string, $p_file, $p_line) {
             if (($p_number & error_reporting()) === 0) {
                 return;
                 // respect php settings
             }
             global $ADMIN_DIR, $Campsite;
             require_once $Campsite['HTML_DIR'] . "/{$ADMIN_DIR}/bugreporter/bug_handler_main.php";
             camp_bug_handler_main($p_number, $p_string, $p_file, $p_line);
         }, E_ALL);
     }
     camp_load_translation_strings("api");
     $plugins = CampPlugin::GetEnabled(true);
     foreach ($plugins as $plugin) {
         camp_load_translation_strings("plugin_" . $plugin->getName());
     }
     // Load common translation strings
     camp_load_translation_strings('globals');
     require_once APPLICATION_PATH . "/../{$ADMIN_DIR}/init_content.php";
     if (file_exists($Campsite['HTML_DIR'] . '/reset_cache')) {
         CampCache::singleton()->clear('user');
         unlink($GLOBALS['g_campsiteDir'] . '/reset_cache');
     }
 }
Ejemplo n.º 8
0
 public function indexAction()
 {
     global $controller;
     $controller = $this;
     require_once $GLOBALS['g_campsiteDir'] . DIRECTORY_SEPARATOR . 'include' . DIRECTORY_SEPARATOR . 'campsite_constants.php';
     require_once CS_PATH_CONFIG . DIR_SEP . 'install_conf.php';
     $local_path = dirname(__FILE__) . '/include';
     set_include_path($local_path . PATH_SEPARATOR . get_include_path());
     require_once CS_PATH_INCLUDES . DIR_SEP . 'campsite_init.php';
     if (file_exists(CS_PATH_SITE . DIR_SEP . 'reset_cache')) {
         CampCache::singleton()->clear('user');
         @unlink(CS_PATH_SITE . DIR_SEP . 'reset_cache');
     }
     // initializes the campsite object
     $campsite = new CampSite();
     // loads site configuration settings
     $campsite->loadConfiguration(CS_PATH_CONFIG . DIR_SEP . 'configuration.php');
     // starts the session
     $campsite->initSession();
     if (file_exists(CS_PATH_SITE . DIR_SEP . 'conf' . DIR_SEP . 'upgrading.php')) {
         $this->upgrade();
         exit(0);
     }
     // initiates the context
     $campsite->init();
     // dispatches campsite
     $campsite->dispatch();
     // triggers an event before render the page.
     // looks for preview language if any.
     $previewLang = $campsite->event('beforeRender');
     if (!is_null($previewLang)) {
         require_once $GLOBALS['g_campsiteDir'] . '/template_engine/classes/SyntaxError.php';
         set_error_handler('templateErrorHandler');
         // loads translations strings in the proper language for the error messages display
         camp_load_translation_strings('preview', $previewLang);
     } else {
         set_error_handler(create_function('', 'return true;'));
     }
     if ($this->_request->getParam('logout') == 'true') {
         $this->_redirect('/auth/logout/?url=' . urlencode($this->getRequest()->getPathInfo()));
     }
     // renders the site
     $campsite->render();
     // triggers an event after displaying
     $campsite->event('afterRender');
 }
Ejemplo n.º 9
0
 public function deleteFromCache()
 {
     if (CampCache::IsEnabled()) {
         CampCache::singleton()->delete($this->getCacheKey());
     }
 }
Ejemplo n.º 10
0
<tr><td colspan="2"><hr/></td></tr>
<tr><td>init:</td><td style="text-align: right"><?php echo $initTime; ?></td></tr>
<tr><td>template render:</td><td style="text-align: right"><?php echo $renderTemplate; ?></td></tr>
<tr><td>end event:</td><td style="text-align: right"><?php echo $endEvent; ?></td></tr>
<tr><td colspan="2"><hr/></td></tr>
<tr><th>total:</th><th style="text-align: right"><?php echo $totalTime; ?></th></tr>
</table>
</td>

<td style="width: 220px; text-align: left; vertical-align: top">
<table style="border-style: ridge; border-right-style: ridge; border-width: thin; padding: 5px;">
<tr><th colspan="2">Cache</th></tr>
<tr><td colspan="2"><hr/></td></tr>
<tr><td>store requests:</td><td style="text-align: right"><?php echo CampCache::GetStoreRequests(); ?></td></tr>
<tr><td>fetch requests:</td><td style="text-align: right"><?php echo CampCache::GetFetchRequests(); ?></td></tr>
<tr><td>hits:</td><td style="text-align: right"><?php echo CampCache::GetHits(); ?></td></tr>
</table>
</td>

<td style="width: 300px; text-align: left; vertical-align: top">
<table style="border-style: ridge; border-right-style: ridge; border-width: thin; padding: 5px;">
<tr><th>Init Event</th><th>Time (msec)</th></tr>
<tr><td colspan="2"><hr/></td></tr>
<tr><td>load base init:</td><td style="text-align: right"><?php echo $initPaths; ?></td></tr>
<!-- <tr><td>campsite object:</td><td style="text-align: right"><?php echo $initCampsite; ?></td></tr> -->
<tr><td>load config:</td><td style="text-align: right"><?php echo $loadConfig; ?></td></tr>
<!-- <tr><td>session object:</td><td style="text-align: right"><?php echo $initSession; ?></td></tr> -->
<tr><td>context object:</td><td style="text-align: right"><?php echo $initContext; ?></td></tr>
<tr><td>dispatch:</td><td style="text-align: right"><?php echo $dispatch; ?></td></tr>
<tr><td>load translation:</td><td style="text-align: right"><?php echo $loadTranslation; ?></td></tr>
</table>
Ejemplo n.º 11
0
 /**
  * Return an array of Language objects based on the given contraints.
  *
  * @param int $p_id
  * @param string $p_languageCode
  * @param string $p_name
  * @param array $p_excludedLanguages
  * @param array $p_order
  * @return array
  */
 public static function GetLanguages($p_id = null, $p_languageCode = null, $p_name = null, array $p_excludedLanguages = array(), array $p_order = array(), $p_skipCache = false)
 {
     global $g_ado_db;
     if (!$p_skipCache && CampCache::IsEnabled()) {
         $paramsArray['id'] = is_null($p_id) ? 'null' : $p_id;
         $paramsArray['language_code'] = is_null($p_languageCode) ? 'null' : $p_languageCode;
         $paramsArray['name'] = is_null($p_name) ? 'null' : $p_name;
         $paramsArray['excluded_languages'] = $p_excludedLanguages;
         $paramsArray['order'] = $p_order;
         $cacheListObj = new CampCacheList($paramsArray, __METHOD__);
         $languages = $cacheListObj->fetchFromCache();
         if ($languages !== false && is_array($languages)) {
             return $languages;
         }
     }
     $selectClauseObj = new SQLSelectClause();
     $tmpLanguage = new Language();
     $selectClauseObj->setTable($tmpLanguage->getDbTableName());
     if (!is_null($p_id)) {
         $selectClauseObj->addWhere($g_ado_db->escapeKeyVal('Id', (int) $p_id));
     }
     if (!is_null($p_languageCode)) {
         $selectClauseObj->addWhere($g_ado_db->escapeKeyVal('Code', $p_languageCode));
     }
     if (!is_null($p_name)) {
         $selectClauseObj->addWhere($g_ado_db->escapeKeyVal('Name', $p_name));
     }
     if (count($p_excludedLanguages) > 0) {
         $excludedLanguages = array();
         foreach ($p_excludedLanguages as $excludedLanguage) {
             $excludedLanguages[] = (int) $excludedLanguage;
         }
         $selectClauseObj->addWhere("Id NOT IN (" . implode(', ', $excludedLanguages) . ")");
     }
     $order = Language::ProcessLanguageListOrder($p_order);
     foreach ($order as $orderDesc) {
         $selectClauseObj->addOrderBy($orderDesc['field'] . ' ' . $orderDesc['dir']);
     }
     $selectClause = $selectClauseObj->buildQuery();
     $languages = DbObjectArray::Create('Language', $selectClause);
     if (!$p_skipCache && CampCache::IsEnabled()) {
         $cacheListObj->storeInCache($languages);
     }
     return $languages;
 }
Ejemplo n.º 12
0
 /**
  * Delete record from database.
  *
  * @return boolean
  */
 function delete()
 {
     // delete correspondending Attachment object if not used by other DebateAnswers
     $DebateAnswerAttachments = DebateAnswerAttachment::getDebateAnswerAttachments(null, null, $this->getProperty('fk_attachment_id'));
     if (count($DebateAnswerAttachments) === 1) {
         $DebateAnswerAttachment = current($DebateAnswerAttachments);
         $DebateAnswerAttachment->getAttachment()->delete();
     }
     // Delete record from the database
     $deleted = parent::delete();
     /*
     if ($deleted) {
         if (function_exists("camp_load_translation_strings")) {
             camp_load_translation_strings("api");
         }
         $logtext = getGS('Article #$1: "$2" ($3) deleted.',
             $this->m_data['Number'], $this->m_data['Name'],    $this->getLanguageName())
             ." (".getGS("Publication")." ".$this->m_data['IdPublication'].", "
             ." ".getGS("Issue")." ".$this->m_data['NrIssue'].", "
             ." ".getGS("Section")." ".$this->m_data['NrSection'].")";
         Log::Message($logtext, null, 32);
     }
     */
     $CampCache = CampCache::singleton();
     $CampCache->clear('user');
     return $deleted;
 }
Ejemplo n.º 13
0
	private function storeInCache()
	{
        if (CampCache::IsEnabled()) {
            CampCache::singleton()->store($this->getCacheKey(), $this, $this->m_defaultTTL);
        }
	}
Ejemplo n.º 14
0
 /**
  * Returns an articles list based on the given parameters.
  *
  * @param array   $p_parameters
  *                              An array of ComparisonOperation objects
  * @param string  $p_order
  *                              An array of columns and directions to order by
  * @param integer $p_start
  *                              The record number to start the list
  * @param integer $p_limit
  *                              The offset. How many records from $p_start will be retrieved.
  * @param integer $p_count
  *                              The total count of the elements; this count is computed without
  *                              applying the start ($p_start) and limit parameters ($p_limit)
  *
  * @return array $articlesList
  *               An array of Article objects
  */
 public static function GetList(array $p_parameters, $p_order = null, $p_start = 0, $p_limit = 0, &$p_count, $p_skipCache = false, $returnObjs = true)
 {
     global $g_ado_db;
     if (!$p_skipCache && CampCache::IsEnabled()) {
         $paramsArray['parameters'] = serialize($p_parameters);
         $paramsArray['order'] = is_null($p_order) ? 'null' : $p_order;
         $paramsArray['start'] = $p_start;
         $paramsArray['limit'] = $p_limit;
         $cacheListObj = new CampCacheList($paramsArray, __METHOD__);
         $articlesList = $cacheListObj->fetchFromCache();
         if ($articlesList !== false && is_array($articlesList)) {
             return $articlesList;
         }
     }
     $matchAllTopics = false;
     $hasTopics = array();
     $hasNotTopics = array();
     $selectClauseObj = new SQLSelectClause();
     $otherTables = array();
     // sets the name of the table for the this database object
     $tmpArticle = new Article();
     $articleTable = $tmpArticle->getDbTableName();
     $selectClauseObj->setTable($articleTable);
     unset($tmpArticle);
     $languageId = null;
     $em = Zend_Registry::get('container')->getService('em');
     $request = Zend_Registry::get('container')->getService('request');
     $repository = $em->getRepository('Newscoop\\NewscoopBundle\\Entity\\Topic');
     // parses the given parameters in order to build the WHERE part of
     // the SQL SELECT sentence
     foreach ($p_parameters as $param) {
         $comparisonOperation = self::ProcessListParameters($param, $otherTables);
         $leftOperand = strtolower($comparisonOperation['left']);
         if ($leftOperand == 'idlanguage' && $comparisonOperation['symbol'] == '=') {
             $languageId = $comparisonOperation['right'];
         }
         if (array_key_exists($leftOperand, Article::$s_regularParameters)) {
             // regular article field, having a direct correspondent in the
             // Article table fields
             $whereCondition = Article::$s_regularParameters[$leftOperand] . ' ' . $comparisonOperation['symbol'] . " " . $g_ado_db->escape($comparisonOperation['right']) . " ";
             if ($leftOperand == 'reads' && strstr($comparisonOperation['symbol'], '=') !== false && $comparisonOperation['right'] == 0) {
                 $selectClauseObj->addConditionalWhere($whereCondition);
                 $isNullCond = Article::$s_regularParameters[$leftOperand] . ' IS NULL';
                 $selectClauseObj->addConditionalWhere($isNullCond);
             } elseif ($leftOperand == 'type' && $comparisonOperation['symbol'] == '=') {
                 $selectClauseObj->addConditionalWhere($whereCondition);
             } elseif ($leftOperand == 'workflow_status' && isset($comparisonOperation['pending'])) {
                 $selectClauseObj->addConditionalWhere('Articles.NrIssue = 0');
                 $selectClauseObj->addConditionalWhere('Articles.NrSection = 0');
                 $selectClauseObj->addWhere($whereCondition);
             } else {
                 $selectClauseObj->addWhere($whereCondition);
             }
         } elseif ($leftOperand == 'matchalltopics') {
             // set the matchAllTopics flag
             $matchAllTopics = true;
         } elseif ($leftOperand == 'topic') {
             // add the topic to the list of match/do not match topics depending
             // on the operator
             $topic = $repository->getTopicByIdOrName($comparisonOperation['right'], $request->getLocale())->getOneOrNullResult();
             if ($topic) {
                 $topicIds = array();
                 foreach ($topic->getChildren() as $child) {
                     $topicIds[] = $child->getId();
                 }
                 $topicIds[] = $comparisonOperation['right'];
                 if ($comparisonOperation['symbol'] == '=') {
                     $hasTopics[] = $topicIds;
                 } else {
                     $hasNotTopics[] = $topicIds;
                 }
             }
         } elseif ($leftOperand == 'topic_strict') {
             $topic = $repository->getTopicByIdOrName($comparisonOperation['right'], $request->getLocale())->getOneOrNullResult();
             if ($topic) {
                 $topicIds[] = $comparisonOperation['right'];
                 if ($comparisonOperation['symbol'] == '=') {
                     $hasTopics[] = $topicIds;
                 } else {
                     $hasNotTopics[] = $topicIds;
                 }
             }
         } elseif ($leftOperand == 'author') {
             $otherTables['ArticleAuthors'] = array('__JOIN' => ',');
             $author = Author::ReadName($comparisonOperation['right']);
             $symbol = $comparisonOperation['symbol'];
             $valModifier = strtolower($symbol) == 'like' ? '%' : '';
             $firstName = trim(trim($g_ado_db->escape($author['first_name']), "'"));
             $lastName = trim(trim($g_ado_db->escape($author['last_name']), "'"));
             $authors = $g_ado_db->GetAll("\n                    SELECT Authors.id\n                    FROM Authors\n                    WHERE CONCAT(Authors.first_name, ' ', Authors.last_name) {$symbol}\n                         '{$valModifier}{$firstName} {$lastName}{$valModifier}'\n                ");
             $authorsIds = array();
             foreach ($authors as $author) {
                 $authorsIds[] = $author['id'];
             }
             $whereCondition = "ArticleAuthors.fk_author_id IN (" . implode(',', $authorsIds) . ")";
             $selectClauseObj->addWhere($whereCondition);
             $selectClauseObj->addWhere('Articles.Number = ArticleAuthors.fk_article_number');
             $selectClauseObj->addWhere('Articles.IdLanguage = ArticleAuthors.fk_language_id');
         } elseif ($leftOperand == 'search_phrase') {
             $searchQuery = ArticleIndex::SearchQuery($comparisonOperation['right'], $comparisonOperation['symbol']);
             if (!empty($searchQuery)) {
                 $otherTables["({$searchQuery})"] = array('__TABLE_ALIAS' => 'search', '__JOIN' => 'INNER JOIN', 'Number' => 'NrArticle', 'IdLanguage' => 'IdLanguage');
             }
         } elseif ($leftOperand == 'location') {
             $num = '[-+]?[0-9]+(?:\\.[0-9]+)?';
             if (preg_match("/({$num}) ({$num}), ({$num}) ({$num})/", trim($comparisonOperation['right']), $matches)) {
                 $queryLocation = Geo_Map::GetGeoSearchSQLQuery(array(array('latitude' => $matches[1], 'longitude' => $matches[2]), array('latitude' => $matches[3], 'longitude' => $matches[4])));
                 $selectClauseObj->addWhere("Articles.Number IN ({$queryLocation})");
             }
         } elseif ($leftOperand == 'insection') {
             $selectClauseObj->addWhere("Articles.NrSection IN " . $comparisonOperation['right']);
         } elseif ($leftOperand == 'complex_date') {
             /* @var $param ComparisonOperation */
             $fieldName = key($roper = $param->getRightOperand());
             $searchValues = array();
             foreach (explode(",", current($roper)) as $values) {
                 list($key, $value) = explode(":", $values, 2);
                 $searchValues[preg_replace("`(?<=[a-z])(_([a-z]))`e", "strtoupper('\\2')", trim($key))] = trim($value);
             }
             $repo = Zend_Registry::get('container')->getService('em')->getRepository('Newscoop\\Entity\\ArticleDatetime');
             /* @var $repo \Newscoop\Entity\Repository\ArticleRepository */
             $searchValues['fieldName'] = $fieldName;
             $sqlQuery = $repo->findDates((object) $searchValues, true)->getFindDatesSQL('dt.articleId');
             if (!is_null($sqlQuery)) {
                 $whereCondition = "Articles.Number IN (\n{$sqlQuery})";
                 $selectClauseObj->addWhere($whereCondition);
             }
         } else {
             // custom article field; has a correspondence in the X[type]
             // table fields
             $sqlQuery = self::ProcessCustomField($comparisonOperation, $languageId);
             if (!is_null($sqlQuery)) {
                 $whereCondition = "Articles.Number IN (\n{$sqlQuery}        )";
                 $selectClauseObj->addWhere($whereCondition);
             }
         }
     }
     if (count($hasTopics) > 0 || count($hasNotTopics) > 0) {
         $typeAttributes = ArticleTypeField::FetchFields(null, null, 'topic', false, false, false, true, $p_skipCache);
     }
     if (count($hasTopics) > 0) {
         if ($matchAllTopics) {
             foreach ($hasTopics as $topicId) {
                 $sqlQuery = Article::BuildTopicSelectClause($topicId, $typeAttributes);
                 $whereCondition = "Articles.Number IN (\n{$sqlQuery}        )";
                 $selectClauseObj->addWhere($whereCondition);
             }
         } else {
             $sqlQuery = Article::BuildTopicSelectClause($hasTopics, $typeAttributes);
             $whereCondition = "Articles.Number IN (\n{$sqlQuery}        )";
             $selectClauseObj->addWhere($whereCondition);
         }
     }
     if (count($hasNotTopics) > 0) {
         $sqlQuery = Article::BuildTopicSelectClause($hasNotTopics, $typeAttributes);
         $whereCondition = "Articles.Number NOT IN (\n{$sqlQuery}        )";
         $selectClauseObj->addWhere($whereCondition);
     }
     // create the count clause object
     $countClauseObj = clone $selectClauseObj;
     if (!is_array($p_order)) {
         $p_order = array();
     }
     // sets the ORDER BY condition
     $p_order = array_merge($p_order, Article::$s_defaultOrder);
     $order = Article::ProcessListOrder($p_order, $otherTables, $otherWhereConditions);
     foreach ($order as $orderDesc) {
         $orderColumn = $orderDesc['field'];
         $orderDirection = $orderDesc['dir'];
         $selectClauseObj->addOrderBy($orderColumn . ' ' . $orderDirection);
     }
     if (count($otherTables) > 0) {
         foreach ($otherTables as $table => $fields) {
             $joinType = 'LEFT JOIN';
             if (isset($fields['__JOIN'])) {
                 $joinType = $fields['__JOIN'];
             }
             if (isset($fields['__TABLE_ALIAS'])) {
                 $tableAlias = $fields['__TABLE_ALIAS'];
                 $tableJoin = "\n    {$joinType} {$table} AS {$tableAlias} \n";
             } else {
                 $tableAlias = $table;
                 $tableJoin = "\n    {$joinType} {$tableAlias} \n";
             }
             $firstCondition = true;
             foreach ($fields as $parent => $child) {
                 if ($parent == '__TABLE_ALIAS' || $parent == '__JOIN') {
                     continue;
                 }
                 $condOperator = $firstCondition ? ' ON ' : 'AND ';
                 if ($parent == '__CONST') {
                     $constTable = $child['table'];
                     $constField = $child['field'];
                     $value = $child['value'];
                     $negate = isset($child['negate']) ? $child['negate'] : false;
                     if (is_null($value)) {
                         $operator = $negate ? 'IS NOT' : 'IS';
                         $value = 'NULL';
                     } else {
                         $operator = $negate ? '!=' : '=';
                         $value = $g_ado_db->escape($value);
                     }
                     $tableJoin .= "        {$condOperator}`{$constTable}`.`{$constField}` {$operator} {$value}\n";
                 } else {
                     $tableJoin .= "        {$condOperator}`{$articleTable}`.`{$parent}` = `{$tableAlias}`.`{$child}`\n";
                 }
                 $firstCondition = false;
             }
             $selectClauseObj->addJoin($tableJoin);
             $countClauseObj->addJoin($tableJoin);
         }
     }
     // other where conditions needed for certain order options
     foreach ($otherWhereConditions as $whereCondition) {
         $selectClauseObj->addWhere($whereCondition);
         $countClauseObj->addWhere($whereCondition);
     }
     // gets the column list to be retrieved for the database table
     $selectClauseObj->addColumn('Articles.Number');
     $selectClauseObj->addColumn('Articles.IdLanguage');
     $countClauseObj->addColumn('COUNT(*)');
     // sets the LIMIT start and offset values
     $selectClauseObj->setLimit($p_start, $p_limit);
     // builds the SQL query
     $selectQuery = $selectClauseObj->buildQuery();
     $countQuery = $countClauseObj->buildQuery();
     // runs the SQL query
     $articles = $g_ado_db->GetAll($selectQuery);
     if (is_array($articles)) {
         $p_count = $g_ado_db->GetOne($countQuery);
         // builds the array of Article objects
         $articlesList = array();
         foreach ($articles as $article) {
             if ($returnObjs) {
                 $articlesList[] = new Article($article['IdLanguage'], $article['Number']);
             } else {
                 $articlesList[] = array('language_id' => $article['IdLanguage'], 'number' => $article['Number']);
             }
         }
     } else {
         $articlesList = array();
         $p_count = 0;
     }
     // stores articles list in cache
     if (!$p_skipCache && CampCache::IsEnabled()) {
         $cacheListObj->storeInCache($articlesList);
     }
     return $articlesList;
 }
Ejemplo n.º 15
0
 /**
  * Returns an article images list based on the given parameters.
  *
  * @param array $p_parameters
  *    An array of ComparisonOperation objects
  * @param string $p_order
  *    An array of columns and directions to order by
  * @param integer $p_start
  *    The record number to start the list
  * @param integer $p_limit
  *    The offset. How many records from $p_start will be retrieved.
  * @param integer $p_count
  *    The total count of the elements; this count is computed without
  *    applying the start ($p_start) and limit parameters ($p_limit)
  *
  * @return array $articleImagesList
  *    An array of Image objects
  */
 public static function GetList(array $p_parameters, array $p_order = array(), $p_start = 0, $p_limit = 0, &$p_count, $p_skipCache = false)
 {
     global $g_ado_db;
     if (!$p_skipCache && CampCache::IsEnabled()) {
         $paramsArray['parameters'] = serialize($p_parameters);
         $paramsArray['order'] = is_null($p_order) ? 'null' : $p_order;
         $paramsArray['start'] = $p_start;
         $paramsArray['limit'] = $p_limit;
         $cacheListObj = new CampCacheList($paramsArray, __METHOD__);
         $articleImagesList = $cacheListObj->fetchFromCache();
         if ($articleImagesList !== false && is_array($articleImagesList)) {
             return $articleImagesList;
         }
     }
     $hasArticleNr = false;
     $selectClauseObj = new SQLSelectClause();
     $countClauseObj = new SQLSelectClause();
     // sets the where conditions
     foreach ($p_parameters as $param) {
         $comparisonOperation = self::ProcessListParameters($param);
         if (sizeof($comparisonOperation) < 3) {
             break;
         }
         if (strpos($comparisonOperation['left'], 'NrArticle')) {
             $hasArticleNr = true;
         }
         $whereCondition = $g_ado_db->escapeOperation($comparisonOperation);
         $selectClauseObj->addWhere($whereCondition);
         $countClauseObj->addWhere($whereCondition);
     }
     // validates whether article number was given
     if ($hasArticleNr === false) {
         CampTemplate::singleton()->trigger_error('Missing parameter Article ' . 'Number in statement list_article_images');
         return;
     }
     // sets the columns to be fetched
     $tmpImage = new Image();
     $columnNames = $tmpImage->getColumnNames(true);
     foreach ($columnNames as $columnName) {
         $selectClauseObj->addColumn($columnName);
     }
     $countClauseObj->addColumn('COUNT(*)');
     // sets the base table Attachment
     $selectClauseObj->setTable($tmpImage->getDbTableName());
     $countClauseObj->setTable($tmpImage->getDbTableName());
     unset($tmpImage);
     // adds the ArticleImages join and condition to the query
     $selectClauseObj->addTableFrom('ArticleImages');
     $selectClauseObj->addWhere('ArticleImages.IdImage = Images.Id');
     $countClauseObj->addTableFrom('ArticleImages');
     $countClauseObj->addWhere('ArticleImages.IdImage = Images.Id');
     // sets the ORDER BY condition
     $p_order = array_merge($p_order, self::$s_defaultOrder);
     $order = self::ProcessListOrder($p_order);
     foreach ($order as $orderDesc) {
         $orderColumn = $orderDesc['field'];
         $orderDirection = $orderDesc['dir'];
         $selectClauseObj->addOrderBy($orderColumn . ' ' . $orderDirection);
     }
     // sets the limit
     $selectClauseObj->setLimit($p_start, $p_limit);
     // builds the query executes it
     $selectQuery = $selectClauseObj->buildQuery();
     $images = $g_ado_db->GetAll($selectQuery);
     if (is_array($images)) {
         $countQuery = $countClauseObj->buildQuery();
         $p_count = $g_ado_db->GetOne($countQuery);
         // builds the array of image objects
         $articleImagesList = array();
         foreach ($images as $image) {
             $imgObj = new Image($image['Id']);
             if ($imgObj->exists()) {
                 $articleImagesList[] = $imgObj;
             }
         }
     } else {
         $articleImagesList = array();
         $p_count = 0;
     }
     if (!$p_skipCache && CampCache::IsEnabled()) {
         $cacheListObj->storeInCache($articleImagesList);
     }
     return $articleImagesList;
 }
Ejemplo n.º 16
0
    $request = camp_session_get("request_$requestId", '');
    if (!empty($request)) {
        $request = unserialize($request);

        // Update security token.
        $token_field = SecurityToken::SECURITY_TOKEN;
        $request['post'][$token_field] = SecurityToken::GetToken();

        // Set values.
        foreach ($request['post'] as $key => $val) {
            $_POST[$key] = $_REQUEST[$key] = $val;
        }
    }

    if (file_exists($Campsite['HTML_DIR'] . '/reset_cache')) {
        CampCache::singleton()->clear('user');
        unlink($GLOBALS['g_campsiteDir'] . '/reset_cache');
    }
    require_once($Campsite['HTML_DIR'] . "/$ADMIN_DIR/init_content.php");

    // Get the main content
    ob_start();
    require_once($path_name);
    $content = ob_get_clean();

    // We create the top menu AFTER the main content because
    // of the localizer screen.  It will update the strings, which
    // need to be reflected immediately in the menu.
    $_top_menu = '';
    if ($needs_menu) {
        ob_start();
Ejemplo n.º 17
0
    /**
     * Returns an articles list based on the given parameters.
     *
     * @param array $p_parameters
     *    An array of ComparisonOperation objects
     * @param string $p_order
     *    An array of columns and directions to order by
     * @param integer $p_start
     *    The record number to start the list
     * @param integer $p_limit
     *    The offset. How many records from $p_start will be retrieved.
     * @param integer $p_count
     *    The total count of the elements; this count is computed without
     *    applying the start ($p_start) and limit parameters ($p_limit)
     *
     * @return array $articlesList
     *    An array of Article objects
     */
    public static function GetList(array $p_parameters, $p_order = null,
                                   $p_start = 0, $p_limit = 0, &$p_count, $p_skipCache = false)
    {
        global $g_ado_db;

        if (!$p_skipCache && CampCache::IsEnabled()) {
            $paramsArray['parameters'] = serialize($p_parameters);
            $paramsArray['order'] = (is_null($p_order)) ? 'null' : $p_order;
            $paramsArray['start'] = $p_start;
            $paramsArray['limit'] = $p_limit;
            $cacheListObj = new CampCacheList($paramsArray, __METHOD__);
            $articlesList = $cacheListObj->fetchFromCache();
            if ($articlesList !== false && is_array($articlesList)) {
                return $articlesList;
            }
        }

        $matchAllTopics = false;
        $hasTopics = array();
        $hasNotTopics = array();
        $selectClauseObj = new SQLSelectClause();
        $otherTables = array();

        // sets the name of the table for the this database object
        $tmpArticle = new Article();
        $articleTable = $tmpArticle->getDbTableName();
        $selectClauseObj->setTable($articleTable);
        unset($tmpArticle);

        $languageId = null;

        // parses the given parameters in order to build the WHERE part of
        // the SQL SELECT sentence
        foreach ($p_parameters as $param) {
            $comparisonOperation = self::ProcessListParameters($param, $otherTables);
            $leftOperand = strtolower($comparisonOperation['left']);
            if ($leftOperand == 'idlanguage' && $comparisonOperation['symbol'] == '=') {
                $languageId = $comparisonOperation['right'];
            }

            if (array_key_exists($leftOperand, Article::$s_regularParameters)) {
                // regular article field, having a direct correspondent in the
                // Article table fields
                $whereCondition = Article::$s_regularParameters[$leftOperand]
                    . ' ' . $comparisonOperation['symbol']
                    . " '" . $g_ado_db->escape($comparisonOperation['right']) . "' ";
                if ($leftOperand == 'reads'
                && strstr($comparisonOperation['symbol'], '=') !== false
                && $comparisonOperation['right'] == 0) {
                    $selectClauseObj->addConditionalWhere($whereCondition);
                    $isNullCond = Article::$s_regularParameters[$leftOperand]
                                . ' IS NULL';
                    $selectClauseObj->addConditionalWhere($isNullCond);
                } elseif ($leftOperand == 'type' && $comparisonOperation['symbol'] == '=' ) {
					$selectClauseObj->addConditionalWhere($whereCondition);
                } else {
                	$selectClauseObj->addWhere($whereCondition);
                }
            } elseif ($leftOperand == 'matchalltopics') {
                // set the matchAllTopics flag
                $matchAllTopics = true;
            } elseif ($leftOperand == 'topic') {
                // add the topic to the list of match/do not match topics depending
                // on the operator
                $topic = new Topic($comparisonOperation['right']);
                if ($topic->exists()) {
                    $topicIds = $topic->getSubtopics(true, 0);
                    $topicIds[] = $comparisonOperation['right'];
                    if ($comparisonOperation['symbol'] == '=') {
                        $hasTopics[] = $topicIds;
                    } else {
                        $hasNotTopics[] = $topicIds;
                    }
                }
            } elseif ($leftOperand == 'author') {
                $otherTables['ArticleAuthors'] = array('__JOIN' => ',');
                $author = Author::ReadName($comparisonOperation['right']);
                $symbol = $comparisonOperation['symbol'];
                $valModifier = strtolower($symbol) == 'like' ? '%' : '';

                $firstName = $g_ado_db->escape($author['first_name']);
                $lastName = $g_ado_db->escape($author['last_name']);
                $whereCondition = "ArticleAuthors.fk_author_id IN
                    (SELECT Authors.id
                     FROM Authors
                     WHERE CONCAT(Authors.first_name, ' ', Authors.last_name) $symbol
                         '$valModifier$firstName $lastName$valModifier')";
                $selectClauseObj->addWhere($whereCondition);
                $selectClauseObj->addWhere('Articles.Number = ArticleAuthors.fk_article_number');
                $selectClauseObj->addWhere('Articles.IdLanguage = ArticleAuthors.fk_language_id');
            } elseif ($leftOperand == 'search_phrase') {
                $searchQuery = ArticleIndex::SearchQuery($comparisonOperation['right']);
                $mainClauseConstraint = "(Articles.Number, Articles.IdLanguage) IN ( $searchQuery )";
                $selectClauseObj->addWhere($mainClauseConstraint);
            } elseif ($leftOperand == 'location') {
                $num = '[-+]?[0-9]+(?:\.[0-9]+)?';
                if (preg_match("/($num) ($num), ($num) ($num)/",
                    trim($comparisonOperation['right']), $matches)) {
                    $queryLocation = Geo_Map::GetGeoSearchSQLQuery(array(
                        array(
                            'latitude' => $matches[1],
                            'longitude' => $matches[2],
                        ), array(
                            'latitude' => $matches[3],
                            'longitude' => $matches[4],
                        ),
                    ));
                    $selectClauseObj->addWhere("Articles.Number IN ($queryLocation)");
                }
            } else {
                // custom article field; has a correspondence in the X[type]
                // table fields
                $sqlQuery = self::ProcessCustomField($comparisonOperation, $languageId);
                if (!is_null($sqlQuery)) {
                    $whereCondition = "Articles.Number IN (\n$sqlQuery        )";
                    $selectClauseObj->addWhere($whereCondition);
                }
            }
        }

        if (count($hasTopics) > 0 || count($hasNotTopics) > 0) {
            $typeAttributes = ArticleTypeField::FetchFields(null, null, 'topic', false,
            false, false, true, $p_skipCache);
        }
        if (count($hasTopics) > 0) {
            if ($matchAllTopics) {
                foreach ($hasTopics as $topicId) {
                    $sqlQuery = Article::BuildTopicSelectClause($topicId, $typeAttributes);
                    $whereCondition = "Articles.Number IN (\n$sqlQuery        )";
                    $selectClauseObj->addWhere($whereCondition);
                }
            } else {
                $sqlQuery = Article::BuildTopicSelectClause($hasTopics, $typeAttributes);
                $whereCondition = "Articles.Number IN (\n$sqlQuery        )";
                $selectClauseObj->addWhere($whereCondition);
            }
        }
        if (count($hasNotTopics) > 0) {
            $sqlQuery = Article::BuildTopicSelectClause($hasNotTopics, $typeAttributes);
            $whereCondition = "Articles.Number NOT IN (\n$sqlQuery        )";
            $selectClauseObj->addWhere($whereCondition);
        }

        // create the count clause object
        $countClauseObj = clone $selectClauseObj;

        if (!is_array($p_order)) {
            $p_order = array();
        }

        // sets the ORDER BY condition
        $p_order = array_merge($p_order, Article::$s_defaultOrder);
        $order = Article::ProcessListOrder($p_order, $otherTables, $otherWhereConditions);
        foreach ($order as $orderDesc) {
            $orderColumn = $orderDesc['field'];
            $orderDirection = $orderDesc['dir'];
            $selectClauseObj->addOrderBy($orderColumn . ' ' . $orderDirection);
        }
        if (count($otherTables) > 0) {
            foreach ($otherTables as $table=>$fields) {
            	$joinType = 'LEFT JOIN';
            	if (isset($fields['__JOIN'])) {
            		$joinType = $fields['__JOIN'];
            	}
                if (isset($fields['__TABLE_ALIAS'])) {
                    $tableAlias = $fields['__TABLE_ALIAS'];
                    $tableJoin = "\n    $joinType $table AS $tableAlias \n";
                } else {
                    $tableAlias = $table;
                    $tableJoin = "\n    $joinType $tableAlias \n";
                }
                $firstCondition = true;
                foreach ($fields as $parent=>$child) {
                    if ($parent == '__TABLE_ALIAS' || $parent == '__JOIN') {
                        continue;
                    }
                    $condOperator = $firstCondition ? ' ON ' : 'AND ';
                    if ($parent == '__CONST') {
                        $constTable = $child['table'];
                        $constField = $child['field'];
                        $value = $child['value'];
                        $negate = isset($child['negate']) ? $child['negate'] : false;
                        if (is_null($value)) {
                            $operator = $negate ? 'IS NOT' : 'IS';
                            $value = 'NULL';
                        } else {
                            $operator = $negate ? '!=' : '=';
                            $value = "'" . $g_ado_db->escape($value) . "'";
                        }
                        $tableJoin .= "        $condOperator`$constTable`.`$constField` $operator $value\n";
                    } else {
                        $tableJoin .= "        $condOperator`$articleTable`.`$parent` = `$tableAlias`.`$child`\n";
                    }
                    $firstCondition = false;
                }
                $selectClauseObj->addJoin($tableJoin);
                $countClauseObj->addJoin($tableJoin);
            }
        }
        // other where conditions needed for certain order options
        foreach ($otherWhereConditions as $whereCondition) {
            $selectClauseObj->addWhere($whereCondition);
            $countClauseObj->addWhere($whereCondition);
        }

        // gets the column list to be retrieved for the database table
        $selectClauseObj->addColumn('Articles.Number');
        $selectClauseObj->addColumn('Articles.IdLanguage');
        $countClauseObj->addColumn('COUNT(*)');

        // sets the LIMIT start and offset values
        $selectClauseObj->setLimit($p_start, $p_limit);

        // builds the SQL query
        $selectQuery = $selectClauseObj->buildQuery();
        $countQuery = $countClauseObj->buildQuery();

        // runs the SQL query
        $articles = $g_ado_db->GetAll($selectQuery);
        if (is_array($articles)) {
            $p_count = $g_ado_db->GetOne($countQuery);

            // builds the array of Article objects
            $articlesList = array();
            foreach ($articles as $article) {
                $articlesList[] = new Article($article['IdLanguage'], $article['Number']);
            }
        } else {
            $articlesList = array();
            $p_count = 0;
        }

        // stores articles list in cache
        if (!$p_skipCache && CampCache::IsEnabled()) {
            $cacheListObj->storeInCache($articlesList);
        }

        return $articlesList;
    } // fn GetList
Ejemplo n.º 18
0
    /**
     *
     */
    protected function execute()
    {
        $input = CampRequest::GetInput('post');
        $session = CampSession::singleton();

        $this->m_step = (!empty($input['step'])) ? $input['step'] : $this->m_defaultStep;

        switch($this->m_step) {
        case 'precheck':
            break;
        case 'license':
            $session->unsetData('config.db', 'installation');
            $session->unsetData('config.site', 'installation');
            $session->unsetData('config.demo', 'installation');
            $this->preInstallationCheck();
            break;
        case 'database':
            $this->license();
            break;
        case 'mainconfig':
            $prevStep = (isset($input['this_step'])) ? $input['this_step'] : '';
            if ($prevStep != 'loaddemo'
                    && $this->databaseConfiguration($input)) {
                $session->setData('config.db', $this->m_config['database'], 'installation', true);
            }
            break;
        case 'loaddemo':
            $prevStep = (isset($input['this_step'])) ? $input['this_step'] : '';
            if ($prevStep != 'loaddemo'
                    && $this->generalConfiguration($input)) {
                $session->setData('config.site', $this->m_config['mainconfig'], 'installation', true);
            }
            break;
        case 'cronjobs':
            if (isset($input['install_demo'])) {
                $session->setData('config.demo', array('loaddemo' => $input['install_demo']), 'installation', true);
                if ($input['install_demo'] != '0') {
                    if (!$this->loadDemoSite()) {
                        break;
                    }
                }
            }
            break;
        case 'finish':
            if (isset($input['install_demo'])) {
                $session->setData('config.demo', array('loaddemo' => $input['install_demo']), 'installation', true);
                if ($input['install_demo'] != '0') {
                    if (!$this->loadDemoSite()) {
                        break;
                    }
                }
            }
            $this->saveCronJobsScripts();
            if ($this->finish()) {
                $this->saveConfiguration();
                self::InstallPlugins();

                require_once($GLOBALS['g_campsiteDir'].'/classes/SystemPref.php');
                SystemPref::DeleteSystemPrefsFromCache();

                // clear all cache
                require_once($GLOBALS['g_campsiteDir'].'/classes/CampCache.php');
                CampCache::singleton()->clear('user');
                CampCache::singleton()->clear();
                CampTemplate::singleton()->clearCache();
            }
            break;
        }
    } // fn execute
Ejemplo n.º 19
0
// initiates the campsite site
$campsite = new CampSite();
// loads site configuration settings
$campsite->loadConfiguration(CS_PATH_CONFIG . DIR_SEP . 'configuration.php');
// starts the session
$campsite->initSession();
$session = CampSite::GetSessionInstance();
$configDb = array('hostname' => $Campsite['db']['host'], 'hostport' => $Campsite['db']['port'], 'username' => $Campsite['db']['user'], 'userpass' => $Campsite['db']['pass'], 'database' => $Campsite['db']['name']);
$session->setData('config.db', $configDb, 'installation');
// upgrading the database
$res = camp_upgrade_database($Campsite['DATABASE_NAME'], true, true);
if ($res !== 0) {
    display_upgrade_error("While upgrading the database: {$res}");
}
CampCache::singleton()->clear('user');
CampCache::singleton()->clear();
SystemPref::DeleteSystemPrefsFromCache();
// replace $campsite by $gimme
require_once $g_documentRoot . '/classes/TemplateConverterNewscoop.php';
$template_files = camp_read_files($g_documentRoot . '/templates');
$converter = new TemplateConverterNewscoop();
if (!empty($template_files)) {
    foreach ($template_files as $template_file) {
        $converter->read($template_file);
        $converter->parse();
        $converter->write();
    }
}
// update plugins
CampPlugin::OnUpgrade();
CampRequest::SetVar('step', 'finish');
Ejemplo n.º 20
0
 /**
  * Returns an article authors list based on the given parameters.
  *
  * @param array $p_parameters
  *    An array of ComparisonOperation objects
  * @param string $p_order
  *    An array of columns and directions to order by
  * @param integer $p_start
  *    The record number to start the list
  * @param integer $p_limit
  *    The offset. How many records from $p_start will be retrieved.
  * @param integer $p_count
  *    The total count of the elements; this count is computed without
  *    applying the start ($p_start) and limit parameters ($p_limit)
  *
  * @return array $articleAuthorsList
  *    An array of Author objects
  */
 public static function GetList(array $p_parameters, $p_order = null, $p_start = 0, $p_limit = 0, &$p_count, $p_skipCache = false)
 {
     global $g_ado_db;
     if (!$p_skipCache && CampCache::IsEnabled()) {
         $paramsArray['parameters'] = serialize($p_parameters);
         $paramsArray['order'] = is_null($p_order) ? 'order' : $p_order;
         $paramsArray['start'] = $p_start;
         $paramsArray['limit'] = $p_limit;
         $cacheListObj = new CampCacheList($paramsArray, __METHOD__);
         $articleAuthorsList = $cacheListObj->fetchFromCache();
         if ($articleAuthorsList !== false && is_array($articleAuthorsList)) {
             return $articleAuthorsList;
         }
     }
     $hasArticleNr = false;
     $selectClauseObj = new SQLSelectClause();
     $countClauseObj = new SQLSelectClause();
     // sets the where conditions
     foreach ($p_parameters as $param) {
         if ($param->getLeftOperand() == 'type') {
             $whereCondition = 'fk_type_id ' . $param->getOperator()->getSymbol() . ' (SELECT id FROM ' . AuthorType::TABLE . ' WHERE type="' . str_replace("'", "", $param->getRightOperand()) . '")';
             $selectClauseObj->addWhere($whereCondition);
             $countClauseObj->addWhere($whereCondition);
         }
         if ($param->getLeftOperand() == 'id') {
             $whereCondition = 'fk_author_id ' . $param->getOperator()->getSymbol() . ' ' . $param->getRightOperand();
             $selectClauseObj->addWhere($whereCondition);
             $countClauseObj->addWhere($whereCondition);
         }
         $comparisonOperation = self::ProcessListParameters($param);
         if (sizeof($comparisonOperation) < 1) {
             break;
         }
         switch (key($comparisonOperation)) {
             case 'fk_article_number':
                 $whereCondition = 'fk_article_number = ' . $comparisonOperation['fk_article_number'];
                 $hasArticleNr = true;
                 break;
             case 'fk_language_id':
                 $whereCondition = '(fk_language_id IS NULL OR ' . 'fk_language_id = ' . $comparisonOperation['fk_language_id'] . ')';
                 break;
         }
         $selectClauseObj->addWhere($whereCondition);
         $countClauseObj->addWhere($whereCondition);
     }
     // validates whether article number was given
     if ($hasArticleNr === false) {
         CampTemplate::singleton()->trigger_error("missed parameter Article Number in statement list_article_authors");
     }
     // sets the base table ArticleAuthors and the column to be fetched
     $tmpArticleAuthor = new ArticleAuthor();
     $selectClauseObj->setTable($tmpArticleAuthor->getDbTableName());
     $selectClauseObj->addJoin('JOIN ' . Author::TABLE . ' ON fk_author_id = id');
     $selectClauseObj->addColumn('fk_author_id');
     $selectClauseObj->addColumn('fk_type_id');
     $countClauseObj->setTable($tmpArticleAuthor->getDbTableName());
     $countClauseObj->addColumn('COUNT(*)');
     unset($tmpArticleAuthor);
     if (!is_array($p_order)) {
         $p_order = array();
     }
     $order = self::ProcessListOrder($p_order);
     // sets the order condition if any
     foreach ($order as $orderDesc) {
         $orderField = $orderDesc['field'];
         $orderDirection = $orderDesc['dir'];
         $selectClauseObj->addOrderBy($orderField . ' ' . $orderDirection);
     }
     // sets the limit
     $selectClauseObj->setLimit($p_start, $p_limit);
     // builds the query and executes it
     $selectQuery = $selectClauseObj->buildQuery();
     $authors = $g_ado_db->GetAll($selectQuery);
     if (is_array($authors)) {
         $countQuery = $countClauseObj->buildQuery();
         $p_count = $g_ado_db->GetOne($countQuery);
         // builds the array of attachment objects
         $authorsList = array();
         foreach ($authors as $author) {
             $authorObj = new Author($author['fk_author_id'], $author['fk_type_id']);
             if ($authorObj->exists()) {
                 $authorsList[] = $authorObj;
             }
         }
     } else {
         $authorsList = array();
         $p_count = 0;
     }
     if (!$p_skipCache && CampCache::IsEnabled()) {
         $cacheListObj->storeInCache($authorsList);
     }
     return $authorsList;
 }
Ejemplo n.º 21
0
 /**
  * Returns an article attachments list based on the given parameters.
  *
  * @param array $p_parameters
  *    An array of ComparisonOperation objects
  * @param string $p_order
  *    An array of columns and directions to order by
  * @param integer $p_start
  *    The record number to start the list
  * @param integer $p_limit
  *    The offset. How many records from $p_start will be retrieved.
  * @param integer $p_count
  *    The total count of the elements; this count is computed without
  *    applying the start ($p_start) and limit parameters ($p_limit)
  *
  * @return array $articleAttachmentsList
  *    An array of Attachment objects
  */
 public static function GetList(array $p_parameters, $p_order = null, $p_start = 0, $p_limit = 0, &$p_count, $p_skipCache = false)
 {
     global $g_ado_db;
     if (!$p_skipCache && CampCache::IsEnabled()) {
         $paramsArray['parameters'] = serialize($p_parameters);
         $paramsArray['order'] = is_null($p_order) ? 'null' : $p_order;
         $paramsArray['start'] = $p_start;
         $paramsArray['limit'] = $p_limit;
         $cacheListObj = new CampCacheList($paramsArray, __METHOD__);
         $articleAttachmentsList = $cacheListObj->fetchFromCache();
         if ($articleAttachmentsList !== false && is_array($articleAttachmentsList)) {
             return $articleAttachmentsList;
         }
     }
     $hasArticleNr = false;
     $selectClauseObj = new SQLSelectClause();
     $countClauseObj = new SQLSelectClause();
     // sets the where conditions
     foreach ($p_parameters as $param) {
         $comparisonOperation = self::ProcessParameters($param);
         if (sizeof($comparisonOperation) < 1) {
             break;
         }
         if (strpos($comparisonOperation['left'], 'fk_article_number')) {
             $whereCondition = $g_ado_db->escapeOperation($comparisonOperation);
             $hasArticleNr = true;
         } elseif (strpos($comparisonOperation['left'], 'fk_language_id')) {
             $whereCondition = '(' . $comparisonOperation['left'] . ' IS NULL OR ' . $comparisonOperation['left'] . " = " . $g_ado_db->escape($comparisonOperation['right']) . ")";
         } else {
             $whereCondition = $g_ado_db->escapeOperation($comparisonOperation);
         }
         $selectClauseObj->addWhere($whereCondition);
         $countClauseObj->addWhere($whereCondition);
     }
     // validates whether article number was given
     if ($hasArticleNr === false) {
         CampTemplate::singleton()->trigger_error('missed parameter Article ' . 'Number in statement list_article_attachments');
         return;
     }
     // sets the columns to be fetched
     $tmpAttachment = new Attachment();
     $columnNames = $tmpAttachment->getColumnNames(true);
     foreach ($columnNames as $columnName) {
         $selectClauseObj->addColumn($columnName);
     }
     $countClauseObj->addColumn('COUNT(*)');
     // sets the main table for the query
     $selectClauseObj->setTable($tmpAttachment->getDbTableName());
     $countClauseObj->setTable($tmpAttachment->getDbTableName());
     unset($tmpAttachment);
     // adds the ArticleAttachments join and condition to the query
     $selectClauseObj->addTableFrom('ArticleAttachments');
     $selectClauseObj->addWhere('ArticleAttachments.fk_attachment_id = Attachments.id');
     $countClauseObj->addTableFrom('ArticleAttachments');
     $countClauseObj->addWhere('ArticleAttachments.fk_attachment_id = Attachments.id');
     if (!is_array($p_order)) {
         $p_order = array();
     }
     // sets the order condition if any
     foreach ($p_order as $orderColumn => $orderDirection) {
         $selectClauseObj->addOrderBy($orderColumn . ' ' . $orderDirection);
     }
     // sets the limit
     $selectClauseObj->setLimit($p_start, $p_limit);
     // builds the query and executes it
     $selectQuery = $selectClauseObj->buildQuery();
     $attachments = $g_ado_db->GetAll($selectQuery);
     if (is_array($attachments)) {
         $countQuery = $countClauseObj->buildQuery();
         $p_count = $g_ado_db->GetOne($countQuery);
         // builds the array of attachment objects
         $articleAttachmentsList = array();
         foreach ($attachments as $attachment) {
             $attchObj = new Attachment($attachment['id']);
             if ($attchObj->exists()) {
                 $articleAttachmentsList[] = $attchObj;
             }
         }
     } else {
         $articleAttachmentsList = array();
         $p_count = 0;
     }
     if (!$p_skipCache && CampCache::IsEnabled()) {
         $cacheListObj->storeInCache($articleAttachmentsList);
     }
     return $articleAttachmentsList;
 }
Ejemplo n.º 22
0
    /**
     * Gets an issues list based on the given parameters.
     *
     * @param array $p_parameters
     *    An array of ComparisonOperation objects
     * @param string $p_order
     *    An array of columns and directions to order by
     * @param integer $p_start
     *    The record number to start the list
     * @param integer $p_limit
     *    The offset. How many records from $p_start will be retrieved.
     * @param integer $p_count
     *    The total count of the elements; this count is computed without
     *    applying the start ($p_start) and limit parameters ($p_limit)
     *
     * @return array $issuesList
     *    An array of Issue objects
     */
    public static function GetList(array $p_parameters, $p_order = null,
                                   $p_start = 0, $p_limit = 0, &$p_count, $p_skipCache = false)
    {
        global $g_ado_db;

        if (!$p_skipCache && CampCache::IsEnabled()) {
        	$paramsArray['parameters'] = serialize($p_parameters);
        	$paramsArray['order'] = (is_null($p_order)) ? 'null' : $p_order;
        	$paramsArray['start'] = $p_start;
        	$paramsArray['limit'] = $p_limit;
        	$cacheListObj = new CampCacheList($paramsArray, __METHOD__);
        	$issuesList = $cacheListObj->fetchFromCache();
        	if ($issuesList !== false && is_array($issuesList)) {
        		return $issuesList;
        	}
        }

        $hasPublicationId = false;
        $selectClauseObj = new SQLSelectClause();
        $countClauseObj = new SQLSelectClause();

        // sets the where conditions
        foreach ($p_parameters as $param) {
            $comparisonOperation = self::ProcessListParameters($param);
            if (empty($comparisonOperation)) {
                break;
            }
            if (strpos($comparisonOperation['left'], 'IdPublication') !== false) {
                $hasPublicationId = true;
            }

            $whereCondition = $comparisonOperation['left'] . ' '
                . $comparisonOperation['symbol'] . " '"
                . $g_ado_db->escape($comparisonOperation['right']) . "' ";
            $selectClauseObj->addWhere($whereCondition);
            $countClauseObj->addWhere($whereCondition);
        }

        // validates whether publication identifier was given
        if ($hasPublicationId == false) {
            CampTemplate::singleton()->trigger_error('missed parameter Publication '
                .'Identifier in statement list_topics');
            return;
        }

        // sets the columns to be fetched
        $tmpIssue = new Issue();
		$columnNames = $tmpIssue->getColumnNames(true);
        foreach ($columnNames as $columnName) {
            $selectClauseObj->addColumn($columnName);
        }
        $countClauseObj->addColumn('COUNT(*)');

        // sets the main table for the query
        $selectClauseObj->setTable($tmpIssue->getDbTableName());
        $countClauseObj->setTable($tmpIssue->getDbTableName());
        unset($tmpIssue);

        if (is_array($p_order)) {
            $order = Issue::ProcessListOrder($p_order);
            // sets the order condition if any
            foreach ($order as $orderDesc) {
                $orderField = $orderDesc['field'];
                $orderDirection = $orderDesc['dir'];
                $selectClauseObj->addOrderBy($orderField . ' ' . $orderDirection);
            }
        }

        $selectClauseObj->addGroupField('Number');
        $selectClauseObj->addGroupField('IdLanguage');

        // sets the limit
        $selectClauseObj->setLimit($p_start, $p_limit);

        // builds the query and executes it
        $selectQuery = $selectClauseObj->buildQuery();
        $countQuery = $countClauseObj->buildQuery();
        $issues = $g_ado_db->GetAll($selectQuery);
        if (is_array($issues)) {
        	$p_count = $g_ado_db->GetOne($countQuery);

        	// builds the array of issue objects
        	$issuesList = array();
        	foreach ($issues as $issue) {
        		$issObj = new Issue($issue['IdPublication'],
        		$issue['IdLanguage'],
        		$issue['Number']);
        		if ($issObj->exists()) {
        			$issuesList[] = $issObj;
        		}
        	}
        } else {
        	$issuesList = array();
        	$p_count = 0;
        }
        if (!$p_skipCache && CampCache::IsEnabled()) {
        	$cacheListObj->storeInCache($issuesList);
        }

        return $issuesList;
    } // fn GetList
Ejemplo n.º 23
0
 /**
  * Execute all pending actions.
  * @return void
  */
 public static function DoPendingActions()
 {
     $actions = IssuePublish::GetPendingActions();
     foreach ($actions as $issuePublishObj) {
         $issuePublishObj->doAction();
     }
     if (count($actions) > 0) {
         CampCache::singleton()->clear('user');
     }
     return count($actions);
 }
Ejemplo n.º 24
0
 /**
  * Method to call parent::setProperty
  * with clening the cache.
  *
  * @param string $p_name
  * @param sring $p_value
  */
 function setProperty($p_name, $p_value)
 {
     $return = parent::setProperty($p_name, $p_value);
     $CampCache = CampCache::singleton();
     $CampCache->clear('user');
     return $return;
 }
Ejemplo n.º 25
0
 /**
  * Returns an article topics list based on the given parameters.
  *
  * @param array   $p_parameters
  *                              An array of ComparisonOperation objects
  * @param string  $p_order
  *                              An array of columns and directions to order by
  * @param integer $p_start
  *                              The record number to start the list
  * @param integer $p_limit
  *                              The offset. How many records from $p_start will be retrieved.
  * @param integer $p_count
  *                              The total count of the elements; this count is computed without
  *                              applying the start ($p_start) and limit parameters ($p_limit)
  *
  * @return array $articleTopicsList
  *               An array of Topic objects
  */
 public static function GetList(array $p_parameters, $p_order = null, $p_start = 0, $p_limit = 0, &$p_count, $p_skipCache = false)
 {
     global $g_ado_db;
     if (!$p_skipCache && CampCache::IsEnabled()) {
         $paramsArray['parameters'] = serialize($p_parameters);
         $paramsArray['order'] = is_null($p_order) ? 'null' : $p_order;
         $paramsArray['start'] = $p_start;
         $paramsArray['limit'] = $p_limit;
         $cacheListObj = new CampCacheList($paramsArray, __METHOD__);
         $articleTopicsList = $cacheListObj->fetchFromCache();
         if ($articleTopicsList !== false && is_array($articleTopicsList)) {
             return $articleTopicsList;
         }
     }
     $selectClauseObj = new SQLSelectClause();
     $countClauseObj = new SQLSelectClause();
     $rootTopicIds = array();
     // processes the parameters
     $hasArticleNr = false;
     foreach ($p_parameters as $parameter) {
         $comparisonOperation = self::ProcessListParameters($parameter);
         if (sizeof($comparisonOperation) < 1) {
             break;
         }
         if (strpos($comparisonOperation['left'], 'NrArticle') !== false) {
             $hasArticleNr = true;
         }
         if (strpos($comparisonOperation['left'], 'RootTopic') !== false) {
             $rootTopicIds[] = (int) $comparisonOperation['right'];
             continue;
         }
         $whereCondition = $g_ado_db->escapeOperation($comparisonOperation);
         $selectClauseObj->addWhere($whereCondition);
         $countClauseObj->addWhere($whereCondition);
     }
     // validates whether article number was given
     if ($hasArticleNr === false) {
         CampTemplate::singleton()->trigger_error("missed parameter Article Number in statement list_article_topics");
         return array();
     }
     if (count($rootTopicIds) > 0) {
         $subtopicsQuery = Topic::BuildSubtopicsQueryWithoutDepth($rootTopicIds);
         $whereCondition = 'TopicId IN (' . $subtopicsQuery->buildQuery() . ')';
         $selectClauseObj->addWhere($whereCondition);
         $countClauseObj->addWhere($whereCondition);
     }
     // sets the main table and columns to be fetched
     $tmpArticleTopic = new ArticleTopic();
     $selectClauseObj->setTable($tmpArticleTopic->getDbTableName());
     $selectClauseObj->addColumn('TopicId');
     $countClauseObj->setTable($tmpArticleTopic->getDbTableName());
     $countClauseObj->addColumn('COUNT(*)');
     unset($tmpArticleTopic);
     if (!is_array($p_order)) {
         $p_order = array();
     }
     // sets the order condition if any
     foreach ($p_order as $orderColumn => $orderDirection) {
         $selectClauseObj->addOrderBy($orderColumn . ' ' . $orderDirection);
     }
     // sets the limit
     $selectClauseObj->setLimit($p_start, $p_limit);
     // builds the query and executes it
     $selectQuery = $selectClauseObj->buildQuery();
     $topics = $g_ado_db->GetAll($selectQuery);
     if (is_array($topics)) {
         $countQuery = $countClauseObj->buildQuery();
         $p_count = $g_ado_db->GetOne($countQuery);
         // builds the array of topic objects
         $articleTopicsList = array();
         foreach ($topics as $topic) {
             $articleTopicsList[] = $topic['TopicId'];
         }
     } else {
         $articleTopicsList = array();
         $p_count = 0;
     }
     if (!$p_skipCache && CampCache::IsEnabled()) {
         $cacheListObj->storeInCache($articleTopicsList);
     }
     return $articleTopicsList;
 }
Ejemplo n.º 26
0
 public static function DeleteActionsFromCache()
 {
     if (CampCache::IsEnabled()) {
     	return CampCache::singleton()->delete(self::CACHE_KEY_LIST_OF_ACTIONS);
     }
     return false;
 }
Ejemplo n.º 27
0
 /**
  * Returns an array of fields from all article types that match
  * the given conditions.
  *
  * @param $p_name
  *         if specified returns fields with the given name
  * @param $p_articleType
  *         if specified returns fields of the given article type
  * @param $p_dataType
  *         if specified returns the fields having the given data type
  *
  * @return array
  */
 public static function FetchFields($p_name = null, $p_articleType = null, $p_dataType = null, $p_negateName = false, $p_negateArticleType = false, $p_negateDataType = false, $p_selectHidden = true, $p_skipCache = false)
 {
     global $g_ado_db;
     if (!$p_skipCache && CampCache::IsEnabled()) {
         $paramsArray['name'] = is_null($p_name) ? 'null' : $p_name;
         $paramsArray['article_type'] = is_null($p_articleType) ? 'null' : $p_articleType;
         $paramsArray['data_type'] = is_null($p_dataType) ? 'null' : $p_dataType;
         $paramsArray['negate_name'] = $p_negateName == false ? 'false' : 'true';
         $paramsArray['negate_article_type'] = $p_negateArticleType == false ? 'false' : 'true';
         $paramsArray['negate_data_type'] = $p_negateDataType == false ? 'false' : 'true';
         $paramsArray['select_hidden'] = $p_selectHidden == false ? 'false' : 'true';
         $cacheListObj = new CampCacheList($paramsArray, __METHOD__);
         $articleTypeFieldsList = $cacheListObj->fetchFromCache();
         if ($articleTypeFieldsList !== false && is_array($articleTypeFieldsList)) {
             return $articleTypeFieldsList;
         }
     }
     $whereClauses = array();
     if (isset($p_name)) {
         $operator = $p_negateName ? '<>' : '=';
         $whereClauses[] = "field_name {$operator} " . $g_ado_db->escape($p_name);
     }
     if (isset($p_articleType)) {
         $operator = $p_negateArticleType ? '<>' : '=';
         $whereClauses[] = "type_name {$operator} " . $g_ado_db->escape($p_articleType);
     }
     if (isset($p_dataType)) {
         $operator = $p_negateDataType ? '<>' : '=';
         $whereClauses[] = "field_type {$operator} " . $g_ado_db->escape($p_dataType);
     }
     if (!$p_selectHidden) {
         $whereClauses[] = 'is_hidden = false';
     }
     $where = count($whereClauses) > 0 ? ' WHERE ' . implode(' and ', $whereClauses) : null;
     $query = "SELECT * FROM `ArticleTypeMetadata` {$where} ORDER BY type_name ASC, field_weight ASC";
     $rows = $g_ado_db->GetAll($query);
     $fields = array();
     foreach ($rows as $row) {
         $field = new ArticleTypeField($row['type_name'], $row['field_name']);
         if ($field->getPrintName() == '') {
             $field->delete();
             continue;
         }
         $fields[] = $field;
     }
     if (!$p_skipCache && CampCache::IsEnabled()) {
         $cacheListObj->storeInCache($fields);
     }
     return $fields;
 }
Ejemplo n.º 28
0
    /**
     * Returns an images list based on the given parameters.
     *
     * @param array $p_parameters
     *    An array of ComparionOperation objects
     * @param string $p_order
     *    An array of columns and directions to order by
     * @param integer $p_start
     *    The record number to start the list
     * @param integer $p_limit
     *    The offset. How many records from $p_start will be retrieved.
     *
     * @return array $issueList
     *    An array of Issue objects
     */
    public static function GetList(array $p_parameters, array $p_order = array(),
                                   $p_start = 0, $p_limit = 0, &$p_count, $p_skipCache = false)
    {
        global $g_ado_db;

        if (!$p_skipCache && CampCache::IsEnabled()) {
        	$paramsArray['parameters'] = serialize($p_parameters);
        	$paramsArray['order'] = (is_null($p_order)) ? 'null' : $p_order;
        	$paramsArray['start'] = $p_start;
        	$paramsArray['limit'] = $p_limit;
        	$cacheListObj = new CampCacheList($paramsArray, __METHOD__);
        	$imagesList = $cacheListObj->fetchFromCache();
        	if ($imagesList !== false && is_array($imagesList)) {
        		return $imagesList;
        	}
        }

        $selectClauseObj = new SQLSelectClause();
        $countClauseObj = new SQLSelectClause();

        // sets the where conditions
        foreach ($p_parameters as $param) {
            $comparisonOperation = self::ProcessListParameters($param);
            if (sizeof($comparisonOperation) < 1) {
                break;
            }

            if ($comparisonOperation['symbol'] == 'match') {
            	$whereCondition = 'MATCH(' . $comparisonOperation['left'] . ") AGAINST('"
            	    . $g_ado_db->escape($comparisonOperation['right']) . "' IN BOOLEAN MODE)";
            } else {
            	$whereCondition = $comparisonOperation['left'] . ' '
            	    . $comparisonOperation['symbol'] . " '"
            	    . $g_ado_db->escape($comparisonOperation['right']) . "' ";
            }
            $selectClauseObj->addWhere($whereCondition);
            $countClauseObj->addWhere($whereCondition);
        }

        // sets the columns to be fetched
        $tmpImage = new Image();
		$columnNames = $tmpImage->getColumnNames(true);
        foreach ($columnNames as $columnName) {
            $selectClauseObj->addColumn($columnName);
        }
        $countClauseObj->addColumn('COUNT(*)');

        // sets the base table
        $selectClauseObj->setTable($tmpImage->getDbTableName());
        $countClauseObj->setTable($tmpImage->getDbTableName());
        unset($tmpImage);

        // sets the ORDER BY condition
        $p_order = array_merge($p_order, self::$s_defaultOrder);
        $order = self::ProcessListOrder($p_order);
        foreach ($order as $orderDesc) {
            $orderColumn = $orderDesc['field'];
            $orderDirection = $orderDesc['dir'];
            $selectClauseObj->addOrderBy($orderColumn . ' ' . $orderDirection);
        }

        // sets the limit
        $selectClauseObj->setLimit($p_start, $p_limit);

        // builds the query and executes it
        $selectQuery = $selectClauseObj->buildQuery();
        $images = $g_ado_db->GetAll($selectQuery);
        if (is_array($images)) {
        	$countQuery = $countClauseObj->buildQuery();
        	$p_count = $g_ado_db->GetOne($countQuery);

        	// builds the array of image objects
        	$imagesList = array();
        	foreach ($images as $image) {
        		$imgObj = new Image($image['Id']);
        		if ($imgObj->exists()) {
        			$imagesList[] = $imgObj;
        		}
        	}
        } else {
        	$imagesList = array();
        	$p_count = 0;
        }
        if (!$p_skipCache && CampCache::IsEnabled()) {
        	$cacheListObj->storeInCache($imagesList);
        }

        return $imagesList;
    } // fn GetList
Ejemplo n.º 29
0
 /**
  * Delete record from database.
  *
  * @return boolean
  */
 function delete()
 {
     // Delete record from the database
     $deleted = parent::delete();
     /*
     if ($deleted) {
         if (function_exists("camp_load_translation_strings")) {
             camp_load_translation_strings("api");
         }
         $logtext = getGS('Article #$1: "$2" ($3) deleted.',
             $this->m_data['Number'], $this->m_data['Name'],    $this->getLanguageName())
             ." (".getGS("Publication")." ".$this->m_data['IdPublication'].", "
             ." ".getGS("Issue")." ".$this->m_data['NrIssue'].", "
             ." ".getGS("Section")." ".$this->m_data['NrSection'].")";
         Log::Message($logtext, null, 32);
     }
     */
     $CampCache = CampCache::singleton();
     $CampCache->clear('user');
     return $deleted;
 }
Ejemplo n.º 30
0
	public static function RunIndexer($p_timeLimit = null, $p_articlesLimit = null,
	$p_lastModifiedFirst = true)
	{
	    global $g_ado_db;

	    $startTime = microtime(true);

	    $rowsLimit = 0;
	    if (!is_null($p_timeLimit)) {
	        $rowsLimit = (int)$p_timeLimit * 5;
	    }
	    if (!is_null($p_articlesLimit)) {
	        $rowsLimit = $rowsLimit > 0 ? min($rowsLimit, $p_articlesLimit) : $p_articlesLimit;
	    }

	    $lockFile = fopen($GLOBALS['g_campsiteDir'].'/newscoop-indexer.lock', "w+");
	    if ($lockFile === false) {
	        return new PEAR_Error("Unable to create single process lock control!");
	    }
	    if (!flock($lockFile, LOCK_EX | LOCK_NB)) { // do an exclusive lock
            return new PEAR_Error("Another indexer process is already running!");
	    }

	    try {
	        if ($p_lastModifiedFirst) {
	            $order = 'time_updated DESC';
	        } else {
	            $order = 'Number ASC';
	        }
	        $limit = $rowsLimit > 0 ? "LIMIT 0, $rowsLimit" : null;
	        // selects articles not yet indexed
	        $sql_query = 'SELECT art.IdPublication, art.NrIssue, art.NrSection, art.Number, '
	        . "art.IdLanguage, art.Type, art.Keywords, art.Name \n"
	        . "FROM Articles as art \n"
	        . "WHERE art.IsIndexed = 'N' ORDER BY $order $limit";
	        $sql_result = $g_ado_db->GetAll($sql_query);
	        if ($sql_result === false) {
	            throw new Exception('Error selecting articles not yet indexed');
	        }

	        $sql = "SELECT COUNT(*) FROM Articles WHERE IsIndexed = 'N'";
	        $total_art = $g_ado_db->GetOne($sql);

	        $nr_art = 0;
	        $nr_new = 0;
	        $nr_word = 0;
	        $word_cache_hits = 0;
	        $articleWordsBatch = array();
	        $wordInsertQueries = 0;

	        $existing_words = array();
	        foreach ($sql_result as $row) {
	        	$sql = "SELECT GROUP_CONCAT(CONCAT_WS(' ', first_name, last_name) SEPARATOR ', ')"
	        	. "FROM Authors AS au, ArticleAuthors AS aa "
	        	. "WHERE au.id = aa.fk_author_id AND aa.fk_article_number = " . (int)$row['Number']
	        	. " AND aa.fk_language_id = " . (int)$row['IdLanguage'];
	        	$article['AuthorName'] = $g_ado_db->GetOne($sql);

	            $article['IdPublication'] = ($row['IdPublication']) ? (int)$row['IdPublication'] : 0;
	            $article['NrIssue'] = ($row['NrIssue']) ? (int)$row['NrIssue'] : 0;
	            $article['NrSection'] = ($row['NrSection']) ? (int)$row['NrSection'] : 0;
	            $article['Number'] = ($row['Number']) ? (int)$row['Number'] : 0;
	            $article['IdLanguage'] = ($row['IdLanguage']) ? (int)$row['IdLanguage'] : 0;
	            $article['Type'] = ($row['Type']) ? $row['Type'] : '';
	            $article['Keywords'] = ($row['Keywords']) ? $row['Keywords'] : '';
	            $article['Name'] = ($row['Name']) ? $row['Name'] : '';

	            // deletes from index
	            $sql_query = 'DELETE FROM ArticleIndex '
	            . 'WHERE IdPublication = ' . $article['IdPublication']
	            . ' AND IdLanguage = ' . $article['IdLanguage']
	            . ' AND NrIssue = ' . $article['NrIssue']
	            . ' AND NrSection = ' . $article['NrSection']
	            . ' AND NrArticle = ' . $article['Number'];
	            if (!$g_ado_db->Execute($sql_query)) {
	                throw new Exception('Error deleting the old article index');
	            }

	            $nr_art++;

	            $keywordsHash = array();
	            self::BuildKeywordsList($article, $keywordsHash);

	            foreach ($keywordsHash as $keyword=>$isSet) {
	                if (empty($keyword)) {
	                    continue;
	                }

	                $nr_word++;

	                if (isset($existing_words[$keyword])) {
	                    $kwd_id = $existing_words[$keyword];
	                    $word_cache_hits++;
	                } else {
	                    $sql_query = 'SELECT Id FROM KeywordIndex '
	                    . "WHERE Keyword = '" . $g_ado_db->escape($keyword) ."'";
	                    $kwd_id = 0 + $g_ado_db->GetOne($sql_query);
	                    $existing_words[$keyword] = $kwd_id;
	                }
	                if ($kwd_id == 0) {
	                    $sql_query = 'SELECT MAX(Id) AS Id FROM KeywordIndex';
	                    $last_kwd_id = 0 + $g_ado_db->GetOne($sql_query);
	                    $kwd_id = $last_kwd_id + 1;

	                    // inserts in keyword list
	                    $sql_query = 'INSERT IGNORE INTO KeywordIndex '
	                    . "SET Keyword = '" . $g_ado_db->escape($keyword) . "', "
	                    . "Id = $kwd_id";
	                    if (!$g_ado_db->Execute($sql_query)) {
	                        throw new Exception('Error adding keyword');
	                    }
	                    $existing_words[$keyword] = $kwd_id;

	                    $nr_new++;
	                }

	                if (!self::BatchAddArticleWord($articleWordsBatch, $article,
	                $kwd_id, $wordInsertQueries)) {
                        throw new Exception('Error adding article to index');
	                }
	            }
	            self::RunArticleWordBatch($articleWordsBatch, $wordInsertQueries);

	            unset($article['Name']);
	            unset($article['Keywords']);
	            unset($article['Type']);

	            $sql_query = "UPDATE Articles SET IsIndexed = 'Y' "
	            . 'WHERE IdPublication = ' . $article['IdPublication']
	            . ' AND NrIssue = ' . $article['NrIssue']
	            . ' AND NrSection = ' . $article['NrSection']
	            . ' AND Number = ' . $article['Number']
	            . ' AND IdLanguage = ' . $article['IdLanguage'];
	            if (!$g_ado_db->Execute($sql_query)) {
	                throw new Exception('Error updating the article');
	            }

	            if ($p_articlesLimit > 0 && $nr_art >= $p_articlesLimit) {
	                break;
	            }

	            $runTime = microtime(true) - $startTime;
	            $articleTime = $runTime / $nr_art;
	            if ($p_timeLimit > 0 && $runTime >= ($p_timeLimit - $articleTime)) {
	                break;
	            }
	        }
	    } catch (Exception $ex) {
	        CampCache::singleton()->clear('user');
	        flock($lockFile, LOCK_UN); // release the lock
	        return new PEAR_Error($ex->getMessage() . ': ' . $g_ado_db->ErrorMsg());
	    }
	    CampCache::singleton()->clear('user');

	    flock($lockFile, LOCK_UN); // release the lock

	    $totalTime = microtime(true) - $startTime;
        $articleTime = $nr_art > 0 ? $totalTime / $nr_art : 0;
	    return array('articles'=>$nr_art, 'words'=>$nr_word, 'new words'=>$nr_new,
	    'total articles'=>$total_art, 'total time'=>$totalTime, 'article time'=>$articleTime,
	    'word cache hits'=>$word_cache_hits, 'word insert queries'=>$wordInsertQueries);
	} // fn RunIndexer