示例#1
0
 /**
  * Search
  *
  * do the actual search and display the results
  *
  * @return output the search results
  */
 public function search($args)
 {
     if (!SecurityUtil::checkPermission('EZComments::', '::', ACCESS_READ)) {
         return true;
     }
     $minlen = 3;
     $maxlen = 30;
     if (strlen($args['q']) < $minlen || strlen($args['q']) > $maxlen) {
         return LogUtil::registerStatus($this->__f('The comments can only be searched for words that are longer than %1$s and less than %2$s characters!', array($minlen, $maxlen)));
     }
     ModUtil::dbInfoLoad('Search');
     $tables = DBUtil::getTables();
     // ezcomments tables
     $ezcommentstable = $tables['EZComments'];
     $ezcommentscolumn = $tables['EZComments_column'];
     // our own tables
     $searchTable = $tables['search_result'];
     $searchColumn = $tables['search_result_column'];
     // where
     $where = Search_Api_User::construct_where($args, array($ezcommentscolumn['subject'], $ezcommentscolumn['comment']));
     $where .= " AND " . $ezcommentscolumn['url'] . " != ''";
     $sessionId = session_id();
     $insertSql = "INSERT INTO {$searchTable}\n              ({$searchColumn['title']},\n               {$searchColumn['text']},\n               {$searchColumn['extra']},\n               {$searchColumn['module']},\n               {$searchColumn['created']},\n               {$searchColumn['session']})\n            VALUES\n            ";
     $comments = DBUtil::selectObjectArray('EZComments', $where);
     foreach ($comments as $comment) {
         $sql = $insertSql . '(' . '\'' . DataUtil::formatForStore($comment['subject']) . '\', ' . '\'' . DataUtil::formatForStore($comment['comment']) . '\', ' . '\'' . DataUtil::formatForStore($comment['url']) . '\', ' . '\'' . 'EZComments' . '\', ' . '\'' . DataUtil::formatForStore($comment['date']) . '\', ' . '\'' . DataUtil::formatForStore($sessionId) . '\')';
         $insertResult = DBUtil::executeSQL($sql);
         if (!$insertResult) {
             return LogUtil::registerError($this->__('Error! Could not load items.'));
         }
     }
     return true;
 }
示例#2
0
 /**
  * Performs the actual search processing.
  */
 public function search($args)
 {
     ModUtil::dbInfoLoad('Search');
     $dbtables = DBUtil::getTables();
     $pageTable = $dbtables['content_page'];
     $pageColumn = $dbtables['content_page_column'];
     $contentTable = $dbtables['content_content'];
     $contentColumn = $dbtables['content_content_column'];
     $contentSearchTable = $dbtables['content_searchable'];
     $contentSearchColumn = $dbtables['content_searchable_column'];
     $translatedPageTable = $dbtables['content_translatedpage'];
     $translatedPageColumn = $dbtables['content_translatedpage_column'];
     $sessionId = session_id();
     // check whether we need to search also in translated content
     $multilingual = System::getVar('multilingual');
     $currentLanguage = ZLanguage::getLanguageCode();
     $searchWhereClauses = array();
     $searchWhereClauses[] = '(' . Search_Api_User::construct_where($args, array($pageColumn['title']), $pageColumn['language']) . ')';
     if ($multilingual) {
         $searchWhereClauses[] = '(' . Search_Api_User::construct_where($args, array($translatedPageColumn['title']), $translatedPageColumn['language']) . ')';
     }
     $searchWhereClauses[] = '(' . Search_Api_User::construct_where($args, array($contentSearchColumn['text']), $contentSearchColumn['language']) . ')';
     // add default filters
     $whereClauses = array();
     $whereClauses[] = '(' . implode(' OR ', $searchWhereClauses) . ')';
     $whereClauses[] = $pageColumn['active'] . ' = 1';
     $whereClauses[] = "({$pageColumn['activeFrom']} IS NULL OR {$pageColumn['activeFrom']} <= NOW())";
     $whereClauses[] = "({$pageColumn['activeTo']} IS NULL OR {$pageColumn['activeTo']} >= NOW())";
     $whereClauses[] = $contentColumn['active'] . ' = 1';
     $whereClauses[] = $contentColumn['visiblefor'] . (UserUtil::isLoggedIn() ? ' <= 1' : ' >= 1');
     $titleFields = $pageColumn['title'];
     $additionalJoins = '';
     if ($multilingual) {
         // if searching in non-default languages, we need the translated title
         $titleFields .= ', ' . $translatedPageColumn['title'] . ' AS translatedTitle';
         // join also the translation table if required
         $additionalJoins = "LEFT OUTER JOIN {$translatedPageTable} ON {$translatedPageColumn['pageId']} = {$pageColumn['id']} AND {$translatedPageColumn['language']} = '{$currentLanguage}'";
         // prevent content snippets in other languages
         $whereClauses[] = $contentSearchColumn['language'] . ' = \'' . $currentLanguage . '\'';
     }
     $where = implode(' AND ', $whereClauses);
     $sql = "\n            SELECT DISTINCT {$titleFields},\n            {$contentSearchColumn['text']} AS description,\n            {$pageColumn['id']} AS pageId,\n            {$pageColumn['cr_date']} AS createdDate\n            FROM {$pageTable}\n            JOIN {$contentTable}\n            ON {$contentColumn['pageId']} = {$pageColumn['id']}\n            JOIN {$contentSearchTable}\n            ON {$contentSearchColumn['contentId']} = {$contentColumn['id']}\n            {$additionalJoins}\n            WHERE {$where}\n        ";
     $result = DBUtil::executeSQL($sql);
     if (!$result) {
         return LogUtil::registerError($this->__('Error! Could not load items.'));
     }
     $objectArray = DBUtil::marshallObjects($result);
     foreach ($objectArray as $object) {
         $pageTitle = $object['page_title'];
         if ($object['translatedTitle'] != '') {
             $pageTitle = $object['translatedTitle'];
         }
         $searchItemData = array('title' => $pageTitle, 'text' => $object['description'], 'extra' => $object['pageId'], 'created' => $object['createdDate'], 'module' => 'Content', 'session' => $sessionId);
         if (!\DBUtil::insertObject($searchItemData, 'search_result')) {
             return \LogUtil::registerError($this->__('Error! Could not save the search results.'));
         }
     }
     return true;
 }
示例#3
0
    /**
     * Search plugin main function
     **/
    public function search($args)
    {
        if (!SecurityUtil::checkPermission('Feeds::', '::', ACCESS_READ)) {
            return true;
        }

        ModUtil::dbInfoLoad('Search');
        $pntable = DBUtil::getTables();
        $feedscolumn = $pntable['feeds_column'];
        $searchTable = $pntable['search_result'];
        $searchColumn = $pntable['search_result_column'];

        $where = search_construct_where($args,
                array($feedscolumn['name']),
                null);

        $sessionId = session_id();

        // define the permission filter to apply
        $permFilter = array(array('realm'          => 0,
                        'component_left' => 'Feeds',
                        'instance_left'  => 'fid',
                        'instance_right' => '',
                        'level'          => ACCESS_READ));

        // get the result set
        $objArray = DBUtil::selectObjectArray('feeds', $where, 'fid', 1, -1, '', $permFilter);
        if ($objArray === false) {
            return LogUtil::registerError($this->__('Error! Could not load items.'));
        }

        $insertSql =
                "INSERT INTO $searchTable
  ($searchColumn[title],
                $searchColumn[text],
                $searchColumn[extra],
                $searchColumn[created],
                $searchColumn[module],
                $searchColumn[session])
VALUES ";

        // Process the result set and insert into search result table
        foreach ($objArray as $obj) {
            $sql = $insertSql . '('
                        . '\'' . DataUtil::formatForStore($obj['name']) . '\', '
                        . '\'' . '\', '
                        . '\'' . DataUtil::formatForStore($obj['fid']) . '\', '
                        . '\'' . DataUtil::formatForStore($obj['cr_date']) . '\', '
                        . '\'' . 'Feeds' . '\', '
                        . '\'' . DataUtil::formatForStore($sessionId) . '\')';
            $insertResult = DBUtil::executeSQL($sql);
            if (!$insertResult) {
                return LogUtil::registerError(__('Error! Could not load items.', $dom));
            }
        }

        return true;
    }
/**
 * render plugin for fetching a particular module object
 *
 * Examples
 *   {selectmodobject module="AutoCustomer" objecttype="customer" id=4 assign="myCustomer"}
 *   {selectmodobject module="AutoCocktails" objecttype="recipe" id=12 assign="myRecipe"}
 *   {selectmodobject recordClass="AutoCocktails_Model_Recipe" id=12 assign="myRecipe"}
 *
 * Parameters:
 *  module      Name of the module storing the desired object (in DBObject mode)
 *  objecttype  Name of object type (in DBObject mode)
 *  recordClass Class name of an doctrine record. (in Doctrine mode)
 *  id          Identifier of desired object
 *  prefix      Optional prefix for class names (defaults to PN) (in DBObject mode)
 *  assign      Name of the returned object
 *
 * @param array       $params All attributes passed to this function from the template.
 * @param Zikula_View $view   Reference to the Zikula_View object.
 *
 * @return void
 */
function smarty_function_selectmodobject($params, Zikula_View $view)
{
    if (isset($params['recordClass']) && !empty($params['recordClass'])) {
        $doctrineMode = true;
    } else {
        // DBObject checks
        if (!isset($params['module']) || empty($params['module'])) {
            $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('selectmodobject', 'module')));
        }
        if (!isset($params['objecttype']) || empty($params['objecttype'])) {
            $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('selectmodobject', 'objecttype')));
        }
        if (!isset($params['prefix'])) {
            $params['prefix'] = 'PN';
        }
        $doctrineMode = false;
    }
    if (!isset($params['id']) || empty($params['id']) || !is_numeric($params['id'])) {
        $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('selectmodobject', 'id')));
    }
    if (!isset($params['assign']) || empty($params['assign'])) {
        $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('selectmodobject', 'assign')));
    }
    // load object depending on mode: doctrine or dbobject
    if (!$doctrineMode) {
        if (!ModUtil::available($params['module'])) {
            $view->trigger_error(__f('Invalid %1$s passed to %2$s.', array('module', 'selectmodobject')));
        }
        ModUtil::dbInfoLoad($params['module']);
        $classname = "{$params['module']}_DBObject_" . StringUtil::camelize($params['objecttype']);
        if (!class_exists($classname) && System::isLegacyMode()) {
            // BC check for PNObject old style.
            // load the object class corresponding to $params['objecttype']
            if (!($class = Loader::loadClassFromModule($params['module'], $params['objecttype'], false, false, $params['prefix']))) {
                z_exit(__f('Unable to load class [%s] for module [%s]', array(DataUtil::formatForDisplay($params['objecttype']), DataUtil::formatForDisplay($params['module']))));
            }
        }
        // intantiate object model
        $object = new $class();
        $idField = $object->getIDField();
        // assign object data
        // this performs a new database select operation
        // while the result will be saved within the object, we assign it to a local variable for convenience
        $objectData = $object->get(intval($params['id']), $idField);
        if (!is_array($objectData) || !isset($objectData[$idField]) || !is_numeric($objectData[$idField])) {
            $view->trigger_error(__('Sorry! No such item found.'));
        }
    } else {
        $objectData = Doctrine_Core::getTable($params['recordClass'])->find($params['id']);
        if ($objectData === false) {
            $view->trigger_error(__('Sorry! No such item found.'));
        }
    }
    $view->assign($params['assign'], $objectData);
}
/**
 * render plugin for fetching a particular module object
 *
 * Examples
 *   {selectmodobject module="AutoCustomer" objecttype="customer" id=4 assign="myCustomer"}
 *   {selectmodobject module="AutoCocktails" objecttype="recipe" id=12 assign="myRecipe"}
 *   {selectmodobject recordClass="AutoCocktails_Model_Recipe" id=12 assign="myRecipe"}
 *
 * Parameters:
 *  module      Name of the module storing the desired object (in DBObject mode)
 *  objecttype  Name of object type (in DBObject mode)
 *  recordClass Class name of an doctrine record. (in Doctrine mode)
 *  id          Identifier of desired object
 *  prefix      Optional prefix for class names (defaults to PN) (in DBObject mode)
 *  assign      Name of the returned object
 *
 * @param array       $params All attributes passed to this function from the template.
 * @param Zikula_View $view   Reference to the Zikula_View object.
 *
 * @return void
 */
function smarty_function_selectmodobject($params, Zikula_View $view)
{
    if (isset($params['recordClass']) && !empty($params['recordClass'])) {
        $doctrineMode = true;
    } else {
        // DBObject checks
        if (!isset($params['module']) || empty($params['module'])) {
            $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('selectmodobject', 'module')));
        }
        if (!isset($params['objecttype']) || empty($params['objecttype'])) {
            $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('selectmodobject', 'objecttype')));
        }
        if (!isset($params['prefix'])) {
            $params['prefix'] = 'PN';
        }
        $doctrineMode = false;
    }
    if (!isset($params['id']) || empty($params['id']) || !is_numeric($params['id'])) {
        $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('selectmodobject', 'id')));
    }
    if (!isset($params['assign']) || empty($params['assign'])) {
        $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('selectmodobject', 'assign')));
    }
    // load object depending on mode: doctrine or dbobject
    if (!$doctrineMode) {
        if (!ModUtil::available($params['module'])) {
            $view->trigger_error(__f('Invalid %1$s passed to %2$s.', array('module', 'selectmodobject')));
        }
        ModUtil::dbInfoLoad($params['module']);
        $class = "{$params['module']}_DBObject_" . StringUtil::camelize($params['objecttype']);
        // intantiate object model
        $object = new $class();
        $idField = $object->getIDField();
        // assign object data
        // this performs a new database select operation
        // while the result will be saved within the object, we assign it to a local variable for convenience
        $objectData = $object->get(intval($params['id']), $idField);
        if (!is_array($objectData) || !isset($objectData[$idField]) || !is_numeric($objectData[$idField])) {
            $view->trigger_error(__('Sorry! No such item found.'));
        }
    } else {
        if ($params['recordClass'] instanceof \Doctrine_Record) {
            $objectData = Doctrine_Core::getTable($params['recordClass'])->find($params['id']);
            if ($objectData === false) {
                $view->trigger_error(__('Sorry! No such item found.'));
            }
        } else {
            /** @var $em Doctrine\ORM\EntityManager */
            $em = \ServiceUtil::get('doctrine.entitymanager');
            $result = $em->getRepository($params['recordClass'])->find($params['id']);
            $objectData = $result->toArray();
        }
    }
    $view->assign($params['assign'], $objectData);
}
示例#6
0
 public function getContent()
 {
     ModUtil::dbInfoLoad('Content');
     $dbtables = DBUtil::getTables();
     $query = "SELECT " . $dbtables['content_page_column']['id'] . " , " . $dbtables['content_page_column']['title'] . ", " . $dbtables['content_page_column']['views'] . " \n    \tFROM " . $dbtables['content_page'] . "\n\tWHERE " . $dbtables['content_page_column']['views'] . " >= 0 AND " . $dbtables['content_page_column']['active'] . " >= 0 ORDER BY " . $dbtables['content_page_column']['views'] . " DESC LIMIT 25";
     $dbresult = DBUtil::executeSQL($query);
     $views = DBUtil::marshallObjects($dbresult);
     $view = Zikula_View::getInstance('Content');
     $view->assign('views', $views);
     return $view->fetch('content_widget_top25.tpl');
 }
示例#7
0
 /**
  * Listener for installer.subscriberarea.uninstalled
  *
  * @param Zikula_Event $event
  *
  * @return void
  */
 public static function hookAreaDelete(Zikula_Event $event)
 {
     $areaId = $event['areaid'];
     // Database information
     ModUtil::dbInfoLoad('EZComments');
     $tables = DBUtil::getTables();
     $columns = $tables['EZComments_column'];
     // Get items
     $where = "WHERE {$columns['areaid']} = '" . DataUtil::formatForStore($areaId) . "'";
     DBUtil::deleteWhere('EZComments', $where);
 }
示例#8
0
 public static function pendingContent(Zikula_Event $event)
 {
     $dom = ZLanguage::getModuleDomain('News');
     ModUtil::dbInfoLoad('News');
     $dbtables = DBUtil::getTables();
     $columns = $dbtables['news_column'];
     $count = DBUtil::selectObjectCount('news', "WHERE $columns[published_status]=2");
     if ($count > 0) {
         $collection = new Zikula_Collection_Container('News');
         $collection->add(new Zikula_Provider_AggregateItem('submission', _n('News article', 'News articles', $count, $dom), $count, 'admin', 'view', array('news_status'=>2)));
         $event->getSubject()->add($collection);
     }
 }
示例#9
0
    /**
     * Search plugin main function
     **/
    public function search($args)
    {
        ModUtil::dbInfoLoad('Search');
        $dbtables = DBUtil::getTables();

        $searchTable = $dbtables['search_result'];
        $searchColumn = $dbtables['search_result_column'];
        $pageTable = $dbtables['content_page'];
        $pageColumn = $dbtables['content_page_column'];
        $contentTable = $dbtables['content_content'];
        $contentColumn = $dbtables['content_content_column'];
        $contentSearchTable = $dbtables['content_searchable'];
        $contentSearchColumn = $dbtables['content_searchable_column'];

        $sessionId = session_id();

        $where = Search_Api_User::construct_where($args, 
				array($contentSearchColumn['text']), null);
        $wheretitle = Search_Api_User::construct_where($args, 
				array($pageColumn['title']), $pageColumn['language']);

		// Direct SQL way of searching in titles and searchable content items 
		// for Pages and Content items that are visible/active
		// Optimization and conversion into DBUtil calls should be done
        $sql = "INSERT INTO $searchTable
            ($searchColumn[title],
            $searchColumn[text],
            $searchColumn[module],
            $searchColumn[extra],
            $searchColumn[created],
            $searchColumn[session])
            SELECT DISTINCT $pageColumn[title],
            $contentSearchColumn[text],
            'Content',
            $pageColumn[id],
            $pageColumn[cr_date] AS createdDate,
            '" . DataUtil::formatForStore($sessionId) . "'
            FROM $pageTable
            JOIN $contentTable
            ON $contentColumn[pageId] = $pageColumn[id]
            JOIN $contentSearchTable
            ON $contentSearchColumn[contentId] = $contentColumn[id]
            WHERE ($where or $wheretitle) AND $pageColumn[active] = 1 AND ($pageColumn[activeFrom] IS NULL OR $pageColumn[activeFrom] <= NOW()) AND ($pageColumn[activeTo] IS NULL OR $pageColumn[activeTo] >= NOW()) AND $contentColumn[active] = 1 AND $contentColumn[visiblefor] " . (UserUtil::isLoggedIn() ? '<=1' : '>=1');

        $dbresult = DBUtil::executeSQL($sql);
        if (!$dbresult) {
            return LogUtil::registerError($this->__('Error! Could not load any Content pages or items.'));
        }
        return true;
    }
示例#10
0
    /**
     * Search plugin main function
     **/
    public function search($args)
    {
        if (!SecurityUtil::checkPermission('News::', '::', ACCESS_READ)) {
            return true;
        }

        ModUtil::dbInfoLoad('Search');
        $tables = DBUtil::getTables();
        $newsColumn = $tables['news_column'];

        $where = Search_Api_User::construct_where($args,
                array($newsColumn['title'],
                $newsColumn['hometext'],
                $newsColumn['bodytext']),
                $newsColumn['language']);
        // Only search in published articles that are currently visible
        $where .= " AND ({$newsColumn['published_status']} = '0')";
        $date = DateUtil::getDatetime();
        $where .= " AND ('$date' >= {$newsColumn['from']} AND ({$newsColumn['to']} IS NULL OR '$date' <= {$newsColumn['to']}))";

        $sessionId = session_id();

        ModUtil::loadApi('News', 'user');

        $permChecker = new News_ResultChecker($this->getVar('enablecategorization'), $this->getVar('enablecategorybasedpermissions'));
        $articles = DBUtil::selectObjectArrayFilter('news', $where, null, null, null, '', $permChecker, null);

        foreach ($articles as $article)
        {
            $item = array(
                'title' => $article['title'],
                'text'  => $article['hometext'],
                'extra' => $article['sid'],
                'created' => $article['from'],
                'module'  => 'News',
                'session' => $sessionId
            );
            $insertResult = DBUtil::insertObject($item, 'search_result');
            if (!$insertResult) {
                return LogUtil::registerError($this->__('Error! Could not load any articles.'));
            }
        }

        return true;
    }
示例#11
0
/**
 * Do the migration
 * 
 * With this function, the actual migration is done.
 * 
 * @return   boolean   true on sucessful migration, false else
 */
function EZComments_migrateapi_pnComments()
{
    if (!SecurityUtil::checkPermission('EZComments::', '::', ACCESS_ADMIN)) {
        return LogUtil::registerPermissionError();
    }
    if (!ModUtil::available('pnComments')) {
        return LogUtil::RegisterError('pnComments not available');
    }
    ModUtil::dbInfoLoad('pnComments');
    $comments = DBUtil::SelectObjectArray('pncomments');
    $counter = 0;
    foreach ($comments as $c) {
        $obj = array('modname' => $c['module'], 'objectid' => $c['objectid'], 'comment' => $c['text'], 'replyto' => -1, 'subject' => $c['subject'], 'uid' => $c['uid'], 'date' => $c['date'] . ' 00:00:00');
        if (!DBUtil::insertObject($obj, 'EZComments')) {
            return LogUtil::registerError('error inserting comments in ezcomments table');
        }
        $counter++;
    }
    return LogUtil::registerStatus("Migrated: {$counter} comments successfully.");
}
示例#12
0
/**
 * Do the migration
 * 
 * With this function, the actual migration is done.
 * 
 * @return   boolean   true on sucessful migration, false else
 * @since    0.6
 */
function EZComments_migrateapi_reviews()
{
    // Security check
    if (!SecurityUtil::checkPermission('EZComments::', '::', ACCESS_ADMIN)) {
        return LogUtil::registerError('Reviews migration: Not Admin');
    }
    // Get datbase setup
    ModUtil::dbInfoLoad('Reviews', 'EZComments/migrateapi/Reviews', true);
    $tables = DBUtil::getTables();
    $Commentstable = $tables['reviews_comments'];
    $Commentscolumn = $tables['reviews_comments_column'];
    if (version_compare(PN_VERSION_NUM, '1', '>=')) {
        EZComments_get76xcolumns_reviews($Commentstable, $Commentscolumn);
    }
    if (is_null($Commentstable) || is_null($Commentscolumn)) {
        return LogUtil::registerError('Reviews migration: Comments tables not found');
    }
    $Usertable = $tables['users'];
    $Usercolumn = $tables['users_column'];
    // note: there's nothing we can do with the score......
    $sql = "SELECT {$Commentscolumn['cid']},\n                   {$Commentscolumn['rid']},\n                   {$Commentscolumn['date']}, \n                   {$Usercolumn['uid']}, \n                   {$Commentscolumn['comments']},\n                   {$Commentscolumn['score']}\n              FROM {$Commentstable}\n         LEFT JOIN {$Usertable}\n                ON {$Commentscolumn['userid']} = {$Usercolumn['uname']}";
    $result = DBUtil::executeSQL($sql);
    if ($result == false) {
        return LogUtil::registerError('Reviews migration: DB Error');
    }
    // loop through the old comments and insert them one by one into the DB
    $items = DBUtil::marshalObjects($result, array('cid', 'rid', 'date', 'uid', 'comment', 'score'));
    foreach ($items as $item) {
        // set the correct user id for anonymous users
        if (empty($item['uid'])) {
            $item['uid'] = 1;
        }
        $id = ModUtil::apiFunc('EZComments', 'user', 'create', array('mod' => 'Reviews', 'objectid' => DataUtil::formatForStore($item['rid']), 'url' => ModUtil::url('Reviews', 'user', 'display', array('id' => $item['rid'])), 'comment' => $item['comment'], 'subject' => '', 'uid' => $item['uid'], 'date' => $item['date']));
        if (!$id) {
            return LogUtil::registerError('Reviews migration: Error creating comment');
        }
    }
    // activate the ezcomments hook for the Reviews module
    ModUtil::apiFunc('Modules', 'admin', 'enablehooks', array('callermodname' => 'Reviews', 'hookmodname' => 'EZComments'));
    return LogUtil::registerStatus('Reviews migration successful');
}
示例#13
0
/**
 * Get all admin messages items that match the criteria
 *
 * @author Mark West, Jorn Wildt
 * @param bool args['activeonly'] only show active items
 * @return bool true/false on success/failure
 */
function Admin_Messages_searchapi_search($args)
{
    $dom = ZLanguage::getModuleDomain('Admin_Messages');
    // Security check
    if (!SecurityUtil::checkPermission('Admin_Messages::', '::', ACCESS_READ)) {
        return true;
    }
    // get the db and table info
    ModUtil::dbInfoLoad('Search');
    $pntable = DBUtil::getTables();
    $messagestable = $pntable['message'];
    $messagescolumn = $pntable['message_column'];
    $searchTable =& $pntable['search_result'];
    $searchColumn =& $pntable['search_result_column'];
    // form the where clause
    $where = '';
    if (!ModUtil::getVar('Admin_Messages', 'allowsearchinactive') || isset($args['activeonly']) && (bool) $args['activeonly']) {
        $where .= " {$messagescolumn['active']} = 1 AND ";
    }
    $where .= " ({$messagescolumn['date']}+{$messagescolumn['expire']} > '" . time() . "' OR {$messagescolumn['expire']} = 0) AND";
    $where .= search_construct_where($args, array($messagescolumn['title'], $messagescolumn['content']), $messagescolumn['language']);
    $sessionId = session_id();
    $sql = "\nSELECT\n   {$messagescolumn['mid']} as mid,\n   {$messagescolumn['title']} as title,\n   {$messagescolumn['content']} as text,\n   {$messagescolumn['date']} as date\nFROM {$messagestable}\nWHERE {$where}";
    $result = DBUtil::executeSQL($sql);
    if (!$result) {
        return LogUtil::registerError(__('Error! Could not load data.'));
    }
    $insertSql = "INSERT INTO {$searchTable}\n  ({$searchColumn['title']},\n   {$searchColumn['text']},\n   {$searchColumn['module']},\n   {$searchColumn['created']},\n   {$searchColumn['session']})\nVALUES ";
    // Process the result set and insert into search result table
    for (; !$result->EOF; $result->MoveNext()) {
        $message = $result->GetRowAssoc(2);
        if (SecurityUtil::checkPermission('Admin_Messages::', "{$message['title']}::{$message['mid']}", ACCESS_READ)) {
            $sql = $insertSql . '(' . '\'' . DataUtil::formatForStore($message['title']) . '\', ' . '\'' . DataUtil::formatForStore($message['text']) . '\', ' . '\'' . 'Admin_Messages' . '\', ' . '\'' . DataUtil::formatForStore(DateUtil::getDatetime($message['date'])) . '\', ' . '\'' . DataUtil::formatForStore($sessionId) . '\')';
            $insertResult = DBUtil::executeSQL($sql);
            if (!$insertResult) {
                return LogUtil::registerError(__('Error! Could not load data.', $dom));
            }
        }
    }
    return true;
}
示例#14
0
    /**
     * Performs a user search based on the user name fragment entered so far.
     *
     * Parameters passed via POST:
     * ---------------------------
     * string fragment A partial user name entered by the user.
     *
     * @return string Zikula_Response_Ajax_Plain with list of users matching the criteria.
     */
    public function getUsers()
    {
        $this->checkAjaxToken();
        $view = Zikula_View::getInstance($this->name);

        if (SecurityUtil::checkPermission('Users::', '::', ACCESS_MODERATE)) {
            $fragment = $this->request->query->get('fragment', $this->request->request->get('fragment'));

            ModUtil::dbInfoLoad($this->name);
            $tables = DBUtil::getTables();

            $usersColumn = $tables['users_column'];

            $where = 'WHERE ' . $usersColumn['uname'] . ' REGEXP \'(' . DataUtil::formatForStore($fragment) . ')\'';
            $results = DBUtil::selectObjectArray('users', $where);

            $view->assign('results', $results);
        }

        $output = $view->fetch('users_ajax_getusers.tpl');

        return new Zikula_Response_Ajax_Plain($output);
    }
示例#15
0
 public function getContent()
 {
     ModUtil::dbInfoLoad('EZComments');
     $dbtables = DBUtil::getTables();
     $query = "SELECT " . $dbtables['EZComments_column']['date'] . " , DATE_FORMAT( " . $dbtables['EZComments_column']['date'] . ", '%Y-%m-%d' ) AS dateval, COUNT( DATE_FORMAT( " . $dbtables['EZComments_column']['date'] . ", '%Y-%m-%d' ) ) AS datetotal \n    \tFROM " . $dbtables['EZComments'] . "\n\tWHERE " . $dbtables['EZComments_column']['date'] . " >= ( CURDATE( ) - INTERVAL 1 MONTH ) GROUP BY dateval ORDER BY " . $dbtables['EZComments_column']['date'] . " ASC";
     $dbresult = DBUtil::executeSQL($query);
     $results = DBUtil::marshallObjects($dbresult);
     foreach ($results as $key => $result) {
         $comments[$result['dateval']] = $result['datetotal'];
     }
     $date = new DateTime();
     $date->sub(new DateInterval('P30D'));
     for ($i = 0; $i < 30; $i++) {
         $date->add(new DateInterval('P1D'));
         if (isset($comments[$date->format('Y-m-d')])) {
             $days[$date->format('Y-m-d')] = $comments[$date->format('Y-m-d')];
         } else {
             $days[$date->format('Y-m-d')] = 0;
         }
     }
     $view = Zikula_View::getInstance('EZComments');
     $view->assign('days', $days);
     return $view->fetch('ezcomments_widget_month.tpl');
 }
示例#16
0
 /**
  * Expand an object with it's category data.
  *
  * @param array  &$obj      The object we wish to get the metadata for.
  * @param string $tablename The object's tablename.
  * @param string $idcolumn  The object's idcolumn (optional) (default='id').
  * @param string $assocKey  The field to use for the associative array index (optional) (default='id').
  *
  * @return The object with the meta data filled in. The object passed in is altered in place
  */
 public static function expandObjectWithCategories(&$obj, $tablename, $idcolumn = 'id', $assocKey = '')
 {
     if (!isset($obj[$idcolumn]) || !$obj[$idcolumn]) {
         throw new \Exception(__f('Unable to determine a valid ID in object [%1$s, %2$s]', array($type, $idcolumn)));
     }
     if (!ModUtil::dbInfoLoad('ZikulaCategoriesModule')) {
         return false;
     }
     $cats = self::retrieveObjectCategoriesObjects($obj, $tablename, $idcolumn, $assocKey, false);
     $obj['__CATEGORIES__'] = $cats;
     // now generate the relative paths
     //$module = ModUtil::getName();
     //$rootCatID = CategoryRegistryUtil::getRegisteredModuleCategory (ModUtil::getName(), $tablename, 'main_table', '/__SYSTEM__/Modules/Quotes/Default');
     //postProcessExpandedObjectCategories ($obj, $rootCatID);
     return $obj;
 }
示例#17
0
 /**
  * Selector for a module's tables.
  *
  * @param string  $modname           Module name.
  * @param string  $tablename         Table name.
  * @param string  $name              Select field name.
  * @param string  $selectedValue     Selected value.
  * @param string  $defaultValue      Value for "default" option.
  * @param string  $defaultText       Text for "default" option.
  * @param boolean $submit            Submit on choose.
  * @param boolean $showSystemColumns Whether or not to show the system columns.
  * @param boolean $disabled          Add Disabled attribute to select.
  * @param integer $multipleSize      Size for multiple selects.
  *
  * @return string The rendered output.
  */
 public static function getSelector_TableFields($modname, $tablename, $name, $selectedValue = '', $defaultValue = 0, $defaultText = '', $submit = false, $showSystemColumns = false, $disabled = false, $multipleSize = 1)
 {
     if (!$modname) {
         return z_exit(__f('Invalid %1$s passed to %2$s.', array('modname', 'HtmlUtil::getSelector_TableFields')));
     }
     if (!$tablename) {
         return z_exit(__f('Invalid %1$s passed to %2$s.', array('tablename', 'HtmlUtil::getSelector_TableFields')));
     }
     if (!$name) {
         return z_exit(__f('Invalid %1$s passed to %2$s.', array('name', 'HtmlUtil::getSelector_TableFields')));
     }
     $tables = ModUtil::dbInfoLoad($modname, '', true);
     $colkey = $tablename . '_column';
     $cols = $tables[$colkey];
     if (!$cols) {
         return z_exit(__f('Invalid %1$s [%2$s] in %3$s.', array('column key', $colkey, 'HtmlUtil::getSelector_TableFields')));
     }
     if (!$showSystemColumns) {
         $filtercols = array();
         ObjectUtil::addStandardFieldsToTableDefinition($filtercols, '');
     }
     $data = array();
     foreach ($cols as $k => $v) {
         if ($showSystemColumns) {
             $data[$v] = $k;
         } else {
             if (!$filtercols[$k]) {
                 $data[$v] = $k;
             }
         }
     }
     return self::getSelector_Generic($name, $data, $selectedValue, $defaultValue, $defaultText, $allValue, $allText, $submit, $disabled, $multipleSize);
 }
示例#18
0
 /**
  * Initialise Zikula.
  *
  * Carries out a number of initialisation tasks to get Zikula up and
  * running.
  *
  * @param integer $stage Stage to load.
  *
  * @return boolean True initialisation successful false otherwise.
  */
 public function init($stage = self::STAGE_ALL)
 {
     $coreInitEvent = new Zikula_Event('core.init', $this);
     // store the load stages in a global so other API's can check whats loaded
     $this->stage = $this->stage | $stage;
     if ($stage & self::STAGE_PRE && $this->stage & ~self::STAGE_PRE) {
         ModUtil::flushCache();
         System::flushCache();
         $this->eventManager->notify(new Zikula_Event('core.preinit', $this));
     }
     // Initialise and load configuration
     if ($stage & self::STAGE_CONFIG) {
         if (System::isLegacyMode()) {
             require_once 'lib/legacy/Compat.php';
         }
         // error reporting
         if (!System::isInstalling()) {
             // this is here because it depends on the config.php loading.
             $event = new Zikula_Event('setup.errorreporting', null, array('stage' => $stage));
             $this->eventManager->notify($event);
         }
         // initialise custom event listeners from config.php settings
         $coreInitEvent->setArg('stage', self::STAGE_CONFIG);
         $this->eventManager->notify($coreInitEvent);
     }
     // Check that Zikula is installed before continuing
     if (System::getVar('installed') == 0 && !System::isInstalling()) {
         System::redirect(System::getBaseUrl() . 'install.php?notinstalled');
         System::shutDown();
     }
     if ($stage & self::STAGE_DB) {
         try {
             $dbEvent = new Zikula_Event('core.init', $this, array('stage' => self::STAGE_DB));
             $this->eventManager->notify($dbEvent);
         } catch (PDOException $e) {
             if (!System::isInstalling()) {
                 header('HTTP/1.1 503 Service Unavailable');
                 require_once System::getSystemErrorTemplate('dbconnectionerror.tpl');
                 System::shutDown();
             } else {
                 return false;
             }
         }
     }
     if ($stage & self::STAGE_TABLES) {
         // Initialise dbtables
         ModUtil::dbInfoLoad('Extensions', 'Extensions');
         ModUtil::initCoreVars();
         ModUtil::dbInfoLoad('Settings', 'Settings');
         ModUtil::dbInfoLoad('Theme', 'Theme');
         ModUtil::dbInfoLoad('Users', 'Users');
         ModUtil::dbInfoLoad('Groups', 'Groups');
         ModUtil::dbInfoLoad('Permissions', 'Permissions');
         ModUtil::dbInfoLoad('Categories', 'Categories');
         if (!System::isInstalling()) {
             ModUtil::registerAutoloaders();
         }
         $coreInitEvent->setArg('stage', self::STAGE_TABLES);
         $this->eventManager->notify($coreInitEvent);
     }
     if ($stage & self::STAGE_SESSIONS) {
         SessionUtil::requireSession();
         $coreInitEvent->setArg('stage', self::STAGE_SESSIONS);
         $this->eventManager->notify($coreInitEvent);
     }
     // Have to load in this order specifically since we cant setup the languages until we've decoded the URL if required (drak)
     // start block
     if ($stage & self::STAGE_LANGS) {
         $lang = ZLanguage::getInstance();
     }
     if ($stage & self::STAGE_DECODEURLS) {
         System::queryStringDecode();
         $coreInitEvent->setArg('stage', self::STAGE_DECODEURLS);
         $this->eventManager->notify($coreInitEvent);
     }
     if ($stage & self::STAGE_LANGS) {
         $lang->setup();
         $coreInitEvent->setArg('stage', self::STAGE_LANGS);
         $this->eventManager->notify($coreInitEvent);
     }
     // end block
     if ($stage & self::STAGE_MODS) {
         // Set compression on if desired
         if (System::getVar('UseCompression') == 1) {
             //ob_start("ob_gzhandler");
         }
         ModUtil::load('SecurityCenter');
         $coreInitEvent->setArg('stage', self::STAGE_MODS);
         $this->eventManager->notify($coreInitEvent);
     }
     if ($stage & self::STAGE_THEME) {
         // register default page vars
         PageUtil::registerVar('title');
         PageUtil::setVar('title', System::getVar('defaultpagetitle'));
         PageUtil::registerVar('keywords', true);
         PageUtil::registerVar('stylesheet', true);
         PageUtil::registerVar('javascript', true);
         PageUtil::registerVar('jsgettext', true);
         PageUtil::registerVar('body', true);
         PageUtil::registerVar('header', true);
         PageUtil::registerVar('footer', true);
         $theme = Zikula_View_Theme::getInstance();
         // set some defaults
         // Metadata for SEO
         $this->serviceManager['zikula_view.metatags']['description'] = System::getVar('defaultmetadescription');
         $this->serviceManager['zikula_view.metatags']['keywords'] = System::getVar('metakeywords');
         $coreInitEvent->setArg('stage', self::STAGE_THEME);
         $this->eventManager->notify($coreInitEvent);
     }
     // check the users status, if not 1 then log him out
     if (UserUtil::isLoggedIn()) {
         $userstatus = UserUtil::getVar('activated');
         if ($userstatus != Users_Constant::ACTIVATED_ACTIVE) {
             UserUtil::logout();
             // TODO - When getting logged out this way, the existing session is destroyed and
             //        then a new one is created on the reentry into index.php. The message
             //        set by the registerStatus call below gets lost.
             LogUtil::registerStatus(__('You have been logged out.'));
             System::redirect(ModUtil::url('Users', 'user', 'login'));
         }
     }
     if ($stage & self::STAGE_POST && $this->stage & ~self::STAGE_POST) {
         $this->eventManager->notify(new Zikula_Event('core.postinit', $this, array('stages' => $stage)));
     }
 }
示例#19
0
    /**
     * Create or update a category registry entry.
     *
     * @param string  $modname    The module to create a property for.
     * @param string  $table      The module table to create a property for.
     * @param string  $property   The property name.
     * @param integer $categoryID The category-id to bind this property to.
     * @param integer $entryID    The id of the existing entry we wish to update (optional) (default=null).
     *
     * @return boolean The DB insert operation result code cast to a boolean.
     */
    private static function _processEntry($modname, $table, $property, $categoryID, $entryID=null)
    {
        if (!isset($modname) || !$modname) {
            return z_exit(__f("Error! Received invalid parameter '%s'", 'modname'));
        }
        if (!isset($table) || !$table) {
            return z_exit(__f("Error! Received invalid parameter '%s'", 'table'));
        }
        if (!isset($property) || !$property) {
            return z_exit(__f("Error! Received invalid parameter '%s'", 'property'));
        }
        if (!isset($categoryID) || !$categoryID) {
            return z_exit(__f("Error! Received invalid parameter '%s'", 'categoryID'));
        }

        if (!ModUtil::dbInfoLoad($modname)) {
            return z_exit(__f("Error! Unable to load table information for module '%s'", $modname));
        }

        $data = array();
        $data['modname'] = $modname;
        $data['table'] = $table;
        $data['property'] = $property;
        $data['category_id'] = $categoryID;
        $data['id'] = $entryID ? $entryID : false;

        return self::registerModuleCategory($data);
    }
示例#20
0
$GLOBALS['ZConfig']['System']['multilingual'] = true;
$GLOBALS['ZConfig']['System']['Z_CONFIG_USE_OBJECT_ATTRIBUTION'] = false;
$GLOBALS['ZConfig']['System']['Z_CONFIG_USE_OBJECT_LOGGING'] = false;
$GLOBALS['ZConfig']['System']['Z_CONFIG_USE_OBJECT_META'] = false;
// Lazy load DB connection to avoid testing DSNs that are not yet valid (e.g. no DB created yet)
$dbEvent = new Zikula_Event('doctrine.init_connection', null, array('lazy' => true));
$connection = $eventManager->notify($dbEvent)->getData();
$columns = upgrade_getColumnsForTable($connection, 'modules');
if (in_array('pn_id', array_keys($columns))) {
    upgrade_columns($connection);
}
if (!isset($columns['capabilities'])) {
    Doctrine_Core::createTablesFromArray(array('Zikula_Doctrine_Model_HookArea', 'Zikula_Doctrine_Model_HookProvider', 'Zikula_Doctrine_Model_HookSubscriber', 'Zikula_Doctrine_Model_HookBinding', 'Zikula_Doctrine_Model_HookRuntime'));
    ModUtil::dbInfoLoad('Extensions', 'Extensions', true);
    DBUtil::changeTable('modules');
    ModUtil::dbInfoLoad('Blocks', 'Blocks', true);
    DBUtil::changeTable('blocks');
}
$installedVersion = upgrade_getCurrentInstalledCoreVersion($connection);
if (version_compare($installedVersion, '1.3.0-dev') === -1) {
    $GLOBALS['_ZikulaUpgrader']['_ZikulaUpgradeFrom12x'] = true;
}
$core->init(Zikula_Core::STAGE_ALL);
$action = FormUtil::getPassedValue('action', false, 'GETPOST');
// login to supplied admin credentials for action the following actions
if ($action === 'upgrademodules' || $action === 'convertdb' || $action === 'sanitycheck') {
    $username = FormUtil::getPassedValue('username', null, 'POST');
    $password = FormUtil::getPassedValue('password', null, 'POST');
    $authenticationInfo = array('login_id' => $username, 'pass' => $password);
    $authenticationMethod = array('modname' => 'Users', 'method' => 'uname');
    if (!UserUtil::loginUsing($authenticationMethod, $authenticationInfo)) {
示例#21
0
 /**
  * Get block information.
  *
  * @return array Array of block information.
  */
 public static function getBlocksInfo()
 {
     ModUtil::dbInfoLoad('Blocks', 'Blocks');
     return DBUtil::selectObjectArray('blocks');
 }
示例#22
0
 /**
  * Rebuild the path field for all categories in the database.
  *
  * Note that field and sourceField go in pairs (that is, if you want sensical results)!.
  *
  * @param string  $field       The field which we wish to populate (optional) (default='path').
  * @param string  $sourceField The field we use to build the path with (optional) (default='name').
  * @param integer $leaf_id     The leaf-category category-id (ie: we'll rebuild the path of this category and all it's parents) (optional) (default=0).
  *
  * @return void
  */
 public static function rebuildPaths($field = 'path', $sourceField = 'name', $leaf_id = 0)
 {
     ModUtil::dbInfoLoad('Categories');
     //if ($leaf_id)
     //$cats  = self::getParentCategories ($leaf_id, 'id');
     //else
     $cats = self::getCategories('', '', 'id');
     $paths = self::buildPaths($cats, $sourceField);
     if ($cats && $paths) {
         foreach ($cats as $k => $v) {
             if ($v[$field] != $paths[$k][$field]) {
                 $v[$field] = $paths[$k];
                 // since we're not going through the object layer for this, we must manually serialize the locale fields
                 $v['display_name'] = serialize($v['display_name']);
                 $v['display_desc'] = serialize($v['display_desc']);
                 $res = DBUtil::updateObject($v, 'categories_category');
             }
         }
     }
 }
示例#23
0
 /**
  * Get all user variables, maps new style attributes to old style user data.
  *
  * @param integer $id              The user id of the user (required).
  * @param boolean $force           True to force loading from database and ignore the cache.
  * @param string  $idfield         Field to use as id (possible values: uid, uname or email).
  * @param bool    $getRegistration Indicates whether a "regular" user record or a pending registration
  *                                      is to be returned. False (default) for a user record and true
  *                                      for a registration. If false and the user record is a pending
  *                                      registration, then the record is not returned and false is returned
  *                                      instead; likewise, if true and the user record is not a registration,
  *                                      then false is returned; (Defaults to false).
  *
  * @return array|bool An associative array with all variables for a user (or pending registration);
  *                      false on error.
  */
 public static function getVars($id, $force = false, $idfield = '', $getRegistration = false)
 {
     if (empty($id)) {
         return false;
     }
     // assign a value for the parameter idfield if it is necessary and prevent from possible typing mistakes
     if ($idfield == '' || $idfield != 'uid' && $idfield != 'uname' && $idfield != 'email') {
         $idfield = 'uid';
         if (!is_numeric($id)) {
             $idfield = 'uname';
             if (strpos($id, '@')) {
                 $idfield = 'email';
             }
         }
     }
     static $cache = array(), $unames = array(), $emails = array();
     // caching
     $user = null;
     if ($force == false) {
         if ($idfield == 'uname' && isset($unames[$id])) {
             if ($unames[$id] !== false) {
                 $user = $cache[$unames[$id]];
             } else {
                 return false;
             }
         }
         if ($idfield == 'email' && isset($emails[$id])) {
             if ($emails[$id] !== false) {
                 $user = $cache[$emails[$id]];
             } else {
                 return false;
             }
         }
         if (isset($cache[$id])) {
             $user = $cache[$id];
         }
     }
     if (!isset($user) || $force) {
         // load the Users database information
         ModUtil::dbInfoLoad('Users', 'Users');
         // get user info, don't cache as this information must be up-to-date
         // NOTE: Do not use a permission filter, or you will enter an infinite nesting loop where getVars calls checkPermission (from within
         // DBUtil), which will call getVars to find out who you are, which will call checkPermission, etc., etc.
         // Do your permission check in the API that is using UserUtil.
         $user = DBUtil::selectObjectByID('users', $id, $idfield, null, null, null, false);
         // If $idfield is email, make sure that we are getting a unique record.
         if ($user && $idfield == 'email') {
             $emailCount = self::getEmailUsageCount($id);
             if ($emailCount > 1 || $emailCount === false) {
                 $user = false;
             }
         }
         // update cache
         // user can be false (error) or empty array (no such user)
         if ($user === false || empty($user)) {
             switch ($idfield) {
                 case 'uid':
                     $cache[$id] = false;
                     break;
                 case 'uname':
                     $unames[$id] = false;
                     break;
                 case 'email':
                     $emails[$id] = false;
                     break;
             }
             if ($user === false) {
                 return LogUtil::registerError(__('Error! Could not load data.'));
             }
             return false;
         } else {
             // This check should come at the very end, here, so that if $force is true the vars get
             // reloaded into cache no matter what $getRegistration is set to. If not, and this is
             // called from setVar(), and setVar() changed the 'activated' value, then we'd have trouble.
             if ($getRegistration && $user['activated'] != Users_Constant::ACTIVATED_PENDING_REG || !$getRegistration && $user['activated'] == Users_Constant::ACTIVATED_PENDING_REG) {
                 return false;
             }
             $user = self::postProcessGetRegistration($user);
             $cache[$user['uid']] = $user;
             $unames[$user['uname']] = $user['uid'];
             $emails[$user['email']] = $user['uid'];
         }
     } elseif ($getRegistration && $user['activated'] != Users_Constant::ACTIVATED_PENDING_REG || !$getRegistration && $user['activated'] == Users_Constant::ACTIVATED_PENDING_REG) {
         return false;
     }
     return $user;
 }
示例#24
0
 /**
  * Uninstall Reviews.
  *
  * @return boolean True on success, false otherwise.
  */
 public function uninstall()
 {
     // delete stored object workflows
     $result = Zikula_Workflow_Util::deleteWorkflowsForModule($this->getName());
     if ($result === false) {
         return LogUtil::registerError($this->__f('An error was encountered while removing stored object workflows for the %s extension.', array($this->getName())));
     }
     try {
         DoctrineHelper::dropSchema($this->entityManager, $this->listEntityClasses());
     } catch (\Exception $e) {
         if (System::isDevelopmentMode()) {
             return LogUtil::registerError($this->__('Doctrine Exception: ') . $e->getMessage());
         }
         return LogUtil::registerError($this->__f('An error was encountered while dropping tables for the %s extension.', array($this->name)));
     }
     // unregister persistent event handlers
     EventUtil::unregisterPersistentModuleHandlers($this->name);
     // unregister hook subscriber bundles
     HookUtil::unregisterSubscriberBundles($this->version->getHookSubscriberBundles());
     // remove all module vars
     $this->delVars();
     // remove category registry entries
     ModUtil::dbInfoLoad('Categories');
     DBUtil::deleteWhere('categories_registry', 'modname = \'' . $this->name . '\'');
     // remove all thumbnails
     $manager = $this->getServiceManager()->getService('systemplugin.imagine.manager');
     $manager->setModule($this->name);
     $manager->cleanupModuleThumbs();
     // remind user about upload folders not being deleted
     $uploadPath = FileUtil::getDataDirectory() . '/' . $this->name . '/';
     LogUtil::registerStatus($this->__f('The upload directories at [%s] can be removed manually.', $uploadPath));
     // uninstallation successful
     return true;
 }
示例#25
0
    /**
     * Perform the search.
     *
     * @param string $args['g']           query string to search
     * @param bool   $args['firstPage']   is this first search attempt? is so - basic search is performed
     * @param string $args['searchtype']  (optional) search type (default='AND')
     * @param string $args['searchorder'] (optional) search order (default='newest')
     * @param int    $args['numlimit']    (optional) number of items to return (default value based on Search settings, -1 for no limit)
     * @param int    $args['page']        (optional) page number (default=1)
     * @param array  $args['active']      (optional) array of search plugins to search (if empty all plugins are used)
     * @param array  $args['modvar']      (optional) array with extrainfo for search plugins
     *
     * @return array array of items array and result count, or false on failure
     */
    public function search($args)
    {
        // query string and firstPage params are required
        if (!isset($args['q']) || empty($args['q']) || !isset($args['firstPage'])) {
            return LogUtil::registerArgsError();
        }
        $vars = array();
        $vars['q'] = $args['q'];
        $vars['searchtype'] = isset($args['searchtype']) && !empty($args['searchtype']) ? $args['searchtype'] : 'AND';
        $vars['searchorder'] = isset($args['searchorder']) && !empty($args['searchorder']) ? $args['searchorder'] : 'newest';
        $vars['numlimit'] = isset($args['numlimit']) && !empty($args['numlimit']) ? $args['numlimit'] : $this->getVar('itemsperpage', 25);
        $vars['page'] = isset($args['page']) && !empty($args['page']) ? (int)$args['page'] : 1;

        $firstPage = isset($args['firstPage']) ? $args['firstPage'] : false;

        $active = isset($args['active']) && is_array($args['active']) && !empty($args['active']) ? $args['active'] : array();
        $modvar = isset($args['modvar']) && is_array($args['modvar']) && !empty($args['modvar']) ? $args['modvar'] : array();

        // work out row index from page number
        $vars['startnum'] = $vars['numlimit'] > 0 ? (($vars['page'] - 1) * $vars['numlimit']) + 1 : 1;

        // Load database stuff
        ModUtil::dbInfoLoad('Search');
        $dbtable = DBUtil::getTables();
        $userId = (int)UserUtil::getVar('uid');
        $searchTable = $dbtable['search_result'];
        $searchColumn = $dbtable['search_result_column'];

        // Create restriction on result table (so user only sees own results)
        $userResultWhere = "$searchColumn[session] = '" . session_id() . "'";

        // Do all the heavy database stuff on the first page only
        if ($firstPage) {
            // Clear current search result for current user - before showing the first page
            // Clear also older searches from other users.
            $dbDriverName = strtolower(Doctrine_Manager::getInstance()->getCurrentConnection()->getDriverName());
            $where = $userResultWhere;
            if ($dbDriverName == 'pgsql') {
                $where .= " OR $searchColumn[found] + INTERVAL '8 HOUR' < NOW()";
            } else {
                $where .= " OR DATE_ADD($searchColumn[found], INTERVAL 8 HOUR) < NOW()";
            }

            DBUtil::deleteWhere('search_result', $where);

            // get all the search plugins
            $search_modules = ModUtil::apiFunc('Search', 'user', 'getallplugins');

            // Ask active modules to find their items and put them into $searchTable for the current user
            // At the same time convert modules list from numeric index to modname index

            $searchModulesByName = array();
            foreach ($search_modules as $mod) {
                // check we've a valid search plugin
                if (isset($mod['functions']) && (empty($active) || isset($active[$mod['title']]))) {
                    foreach ($mod['functions'] as $contenttype => $function) {
                        if (isset($modvar[$mod['title']])) {
                            $param = array_merge($vars, $modvar[$mod['title']]);
                        } else {
                            $param = $vars;
                        }
                        $searchModulesByName[$mod['name']] = $mod;
                        $ok = ModUtil::apiFunc($mod['title'], 'search', $function, $param);
                        if (!$ok) {
                            LogUtil::registerError($this->__f('Error! \'%1$s\' module returned false in search function \'%2$s\'.', array($mod['title'], $function)));

                            return System::redirect(ModUtil::url('Search', 'user', 'main'));
                        }
                    }
                }
            }

            // Count number of found results
            $resultCount = DBUtil::selectObjectCount('search_result', $userResultWhere);
            SessionUtil::setVar('searchResultCount', $resultCount);
            SessionUtil::setVar('searchModulesByName', $searchModulesByName);
        } else {
            $resultCount = SessionUtil::getVar('searchResultCount');
            $searchModulesByName = SessionUtil::getVar('searchModulesByName');
        }

        // Fetch search result - do sorting and paging in database
        // Figure out what to sort by
        switch ($args['searchorder']) {
            case 'alphabetical':
                $sort = 'title';
                break;
            case 'oldest':
                $sort = 'created';
                break;
            case 'newest':
                $sort = 'created DESC';
                break;
            default:
                $sort = 'title';
                break;
        }

        // Get next N results from the current user's result set
        // The "checker" object is used to:
        // 1) do secondary access control (deprecated more or less)
        // 2) let the modules add "url" to the found (and viewed) items
        $checker = new search_result_checker($searchModulesByName);
        $sqlResult = DBUtil::selectObjectArrayFilter('search_result', $userResultWhere, $sort,
                        $vars['startnum'] - 1, $vars['numlimit'], '',
                        $checker, null);
        // add displayname of modules found
        $cnt = count($sqlResult);
        for ($i = 0; $i < $cnt; $i++) {
            $modinfo = ModUtil::getInfoFromName($sqlResult[$i]['module']);
            $sqlResult[$i]['displayname'] = $modinfo['displayname'];
        }

        $result = array(
                'resultCount' => $resultCount,
                'sqlResult' => $sqlResult
        );

        return $result;
    }
示例#26
0
 public function processEdit(Zikula_ProcessHook $hook)
 {
     // will need this to update URLs in table
     // get db table and column for where statement
     ModUtil::dbInfoLoad('EZComments');
     $tables = DBUtil::getTables();
     $column = $tables['EZComments_column'];
     $mod = DataUtil::formatForStore($hook->getCaller());
     $objectid = DataUtil::formatForStore($hook->getId());
     $areaid = DataUtil::formatForStore($hook->getAreaId());
     $where = "{$column['modname']} = '{$mod}' AND {$column['objectid']} = '{$objectid}' AND {$column['areaid']} = '{$areaid}'";
     $objUrl = $hook->getUrl()->getUrl(null, null, false, false);
     // objecturl provided by subscriber
     // the fourth arg is forceLang and if left to default (true) then the url is malformed - core bug as of 1.3.0
     $comment = array('url' => System::getHomepageUrl() . DataUtil::formatForStore($objUrl));
     DBUtil::updateObject($comment, 'EZComments', $where);
 }
示例#27
0
    /**
     * Purge the permalink fields in the Feeds table
     * @return bool true on success, false on failure
     */
    public function purgepermalinks($args)
    {
        // Security check
        if (!SecurityUtil::checkPermission('Feeds::', '::', ACCESS_ADMIN)) {
            return LogUtil::registerPermissionError();
        }

        // disable categorization to do this (if enabled)
        $catenabled = ModUtil::getVar('Feeds', 'enablecategorization');
        if ($catenabled) {
            ModUtil::setVar('Feeds', 'enablecategorization', false);
            ModUtil::dbInfoLoad('Feeds', 'Feeds', true);
        }

        // get all the ID and permalink of the table
        $data = DBUtil::selectObjectArray('feeds', '', '', -1, -1, 'fid', null, null, array('fid', 'urltitle'));

        // loop the data searching for non equal permalinks
        $perma = '';
        foreach (array_keys($data) as $fid) {
            $perma = strtolower(DataUtil::formatPermalink($data[$fid]['urltitle']));
            if ($data[$fid]['urltitle'] != $perma) {
                $data[$fid]['urltitle'] = $perma;
            } else {
                unset($data[$fid]);
            }
        }

        // restore the categorization if was enabled
        if ($catenabled) {
            ModUtil::setVar('Feeds', 'enablecategorization', true);
        }

        if (empty($data)) {
            return true;
            // store the modified permalinks
        } elseif (DBUtil::updateObjectArray($data, 'feeds', 'fid')) {
            // Let the calling process know that we have finished successfully
            return true;
        } else {
            return false;
        }
    }
示例#28
0
 /**
  * Executes the actual search process.
  *
  * @param array $args List of arguments.
  *
  * @return boolean
  *
  * @throws RuntimeException Thrown if search results can not be saved
  */
 public function search(array $args = array())
 {
     if (!SecurityUtil::checkPermission($this->name . '::', '::', ACCESS_READ)) {
         return '';
     }
     // ensure that database information of Search module is loaded
     ModUtil::dbInfoLoad('Search');
     // save session id as it is used when inserting search results below
     $sessionId = session_id();
     // retrieve list of activated object types
     $searchTypes = isset($args['objectTypes']) ? (array) $args['objectTypes'] : (array) FormUtil::getPassedValue('reviewsSearchTypes', array(), 'GETPOST');
     $controllerHelper = new Reviews_Util_Controller($this->serviceManager);
     $utilArgs = array('api' => 'search', 'action' => 'search');
     $allowedTypes = $controllerHelper->getObjectTypes('api', $utilArgs);
     $entityManager = ServiceUtil::getService('doctrine.entitymanager');
     $currentPage = 1;
     $resultsPerPage = 50;
     foreach ($searchTypes as $objectType) {
         if (!in_array($objectType, $allowedTypes)) {
             continue;
         }
         $whereArray = array();
         $languageField = null;
         switch ($objectType) {
             case 'review':
                 $whereArray[] = 'tbl.workflowState';
                 $whereArray[] = 'tbl.title';
                 $whereArray[] = 'tbl.text';
                 $whereArray[] = 'tbl.zlanguage';
                 $whereArray[] = 'tbl.reviewer';
                 $whereArray[] = 'tbl.email';
                 $whereArray[] = 'tbl.score';
                 $whereArray[] = 'tbl.url';
                 $whereArray[] = 'tbl.url_title';
                 $whereArray[] = 'tbl.cover';
                 $whereArray[] = 'tbl.coverUpload';
                 $languageField = 'zlanguage';
                 break;
         }
         $where = Search_Api_User::construct_where($args, $whereArray);
         $entityClass = $this->name . '_Entity_' . ucwords($objectType);
         $repository = $entityManager->getRepository($entityClass);
         // get objects from database
         list($entities, $objectCount) = $repository->selectWherePaginated($where, '', $currentPage, $resultsPerPage, false);
         if ($objectCount == 0) {
             continue;
         }
         $idFields = ModUtil::apiFunc($this->name, 'selection', 'getIdFields', array('ot' => $objectType));
         $descriptionField = $repository->getDescriptionFieldName();
         foreach ($entities as $entity) {
             $urlArgs = array('ot' => $objectType);
             // create identifier for permission check
             $instanceId = '';
             foreach ($idFields as $idField) {
                 $urlArgs[$idField] = $entity[$idField];
                 if (!empty($instanceId)) {
                     $instanceId .= '_';
                 }
                 $instanceId .= $entity[$idField];
             }
             $urlArgs['id'] = $instanceId;
             /* commented out as it could exceed the maximum length of the 'extra' field
                if (isset($entity['slug'])) {
                    $urlArgs['slug'] = $entity['slug'];
                }*/
             // perform permission check
             if (!SecurityUtil::checkPermission($this->name . ':' . ucfirst($objectType) . ':', $instanceId . '::', ACCESS_OVERVIEW)) {
                 continue;
             }
             $title = $entity->getTitleFromDisplayPattern();
             $description = !empty($descriptionField) ? $entity[$descriptionField] : '';
             $created = isset($entity['createdDate']) ? $entity['createdDate']->format('Y-m-d H:i:s') : '';
             $searchItemData = array('title' => $title, 'text' => $description, 'extra' => serialize($urlArgs), 'created' => $created, 'module' => $this->name, 'session' => $sessionId);
             if (!DBUtil::insertObject($searchItemData, 'search_result')) {
                 return LogUtil::registerError($this->__('Error! Could not save the search results.'));
             }
         }
     }
     return true;
 }
示例#29
0
 /**
  * Load event handler.
  *
  * @param Zikula_Form_View $view Reference to Zikula_Form_View object.
  * @param array            &$params Parameters passed from the Smarty plugin function.
  *
  * @return void
  */
 public function load(Zikula_Form_View $view, &$params)
 {
     if ($this->showEmptyValue != 0) {
         $this->addItem('- - -', 0);
     }
     // switch between doctrine and dbobject mode
     if ($this->recordClass) {
         $q = Doctrine::getTable($this->recordClass)->createQuery();
         if ($this->where) {
             if (is_array($this->where)) {
                 $q->where($this->where[0], $this->where[1]);
             } else {
                 $q->where($this->where);
             }
         }
         if ($this->orderby) {
             $q->orderBy($this->orderby);
         }
         if ($this->pos >= 0) {
             $q->offset($this->pos);
         }
         if ($this->num > 0) {
             $q->limit($this->num);
         }
         $rows = $q->execute();
         foreach ($rows as $row) {
             $itemLabel = $row[$this->displayField];
             if (!empty($this->displayFieldTwo)) {
                 $itemLabel .= ' (' . $row[$this->displayFieldTwo] . ')';
             }
             $this->addItem($itemLabel, $row[$this->idField]);
         }
     } else {
         ModUtil::dbInfoLoad($this->module);
         // load the object class corresponding to $this->objecttype
         $class = "{$this->module}_DBObject_" . StringUtil::camelize($this->objecttype) . 'Array';
         // instantiate the object-array
         $objectArray = new $class();
         // get() returns the cached object fetched from the DB during object instantiation
         // get() with parameters always performs a new select
         // while the result will be saved in the object, we assign in to a local variable for convenience.
         $objectData = $objectArray->get($this->where, $this->orderby, $this->pos, $this->num);
         foreach ($objectData as $obj) {
             $itemLabel = $obj[$this->displayField];
             if (!empty($this->displayFieldTwo)) {
                 $itemLabel .= ' (' . $obj[$this->displayFieldTwo] . ')';
             }
             $this->addItem($itemLabel, $obj[$this->idField]);
         }
     }
     parent::load($view, $params);
 }
示例#30
0
文件: DBUtil.php 项目: rmaiwald/core
 /**
  * Build a list of objects which are mapped to the specified categories.
  *
  * @param string  $tablename      Treated table reference.
  * @param string  $categoryFilter The category list to use for filtering.
  * @param boolean $returnArray    Whether or not to return an array (optional) (default=false).
  *
  * @return mixed The resulting string or array.
  */
 private static function _generateCategoryFilter($tablename, $categoryFilter, $returnArray = false)
 {
     if (!$categoryFilter) {
         return '';
     }
     if (!ModUtil::dbInfoLoad('ZikulaCategoriesModule')) {
         return '';
     }
     // check the meta data
     if (isset($categoryFilter['__META__']['module'])) {
         $modname = $categoryFilter['__META__']['module'];
     } else {
         $modname = ModUtil::getName();
     }
     // check operator to use
     // when it's AND, the where contains subqueries
     if (isset($categoryFilter['__META__']['operator']) && in_array(strtolower($categoryFilter['__META__']['operator']), array('and', 'or'))) {
         $op = strtoupper($categoryFilter['__META__']['operator']);
     } else {
         $op = 'OR';
     }
     unset($categoryFilter['__META__']);
     // get the properties IDs in the category register
     $propids = CategoryRegistryUtil::getRegisteredModuleCategoriesIds($modname, $tablename);
     // build the where clause
     $n = 1;
     // subquery counter
     $catmapobjtbl = 'categories_mapobj';
     $where = array();
     foreach ($categoryFilter as $property => $category) {
         $prefix = '';
         if ($op == 'AND') {
             $prefix = "table{$n}.";
         }
         // this allows to have an array of categories IDs
         if (is_array($category)) {
             $wherecat = array();
             foreach ($category as $cat) {
                 $wherecat[] = "{$prefix}category_id='" . DataUtil::formatForStore($cat) . "'";
             }
             $wherecat = '(' . implode(' OR ', $wherecat) . ')';
             // if there's only one category ID
         } else {
             $wherecat = "{$prefix}category_id='" . DataUtil::formatForStore($category) . "'";
         }
         // process the where depending of the operator
         if ($op == 'AND') {
             $where[] = "obj_id IN (SELECT {$prefix}obj_id FROM {$catmapobjtbl} table{$n} WHERE {$prefix}reg_id = '" . DataUtil::formatForStore($propids[$property]) . "' AND {$wherecat})";
         } else {
             $where[] = "(reg_id='" . DataUtil::formatForStore($propids[$property]) . "' AND {$wherecat})";
         }
         $n++;
     }
     $where = "tablename='" . DataUtil::formatForStore($tablename) . "' AND (" . implode(" {$op} ", $where) . ')';
     // perform the query
     $objIds = DBUtil::selectFieldArray('categories_mapobj', 'obj_id', $where);
     // this ensures that we return an empty set if no objects are mapped to the requested categories
     if (!$objIds) {
         $objIds[] = -1;
     }
     if ($returnArray) {
         return $objIds;
     }
     return implode(',', $objIds);
 }