/**
  * @param IDatabase $db
  * @return mixed
  */
 public function doQuery($db)
 {
     $ids = array_map('intval', $this->ids);
     $queryInfo = ['tables' => ['revision', 'user'], 'fields' => array_merge(Revision::selectFields(), Revision::selectUserFields()), 'conds' => ['rev_page' => $this->title->getArticleID(), 'rev_id' => $ids], 'options' => ['ORDER BY' => 'rev_id DESC'], 'join_conds' => ['page' => Revision::pageJoinCond(), 'user' => Revision::userJoinCond()]];
     ChangeTags::modifyDisplayQuery($queryInfo['tables'], $queryInfo['fields'], $queryInfo['conds'], $queryInfo['join_conds'], $queryInfo['options'], '');
     $live = $db->select($queryInfo['tables'], $queryInfo['fields'], $queryInfo['conds'], __METHOD__, $queryInfo['options'], $queryInfo['join_conds']);
     if ($live->numRows() >= count($ids)) {
         // All requested revisions are live, keeps things simple!
         return $live;
     }
     $archiveQueryInfo = ['tables' => ['archive'], 'fields' => Revision::selectArchiveFields(), 'conds' => ['ar_rev_id' => $ids], 'options' => ['ORDER BY' => 'ar_rev_id DESC'], 'join_conds' => []];
     ChangeTags::modifyDisplayQuery($archiveQueryInfo['tables'], $archiveQueryInfo['fields'], $archiveQueryInfo['conds'], $archiveQueryInfo['join_conds'], $archiveQueryInfo['options'], '');
     // Check if any requested revisions are available fully deleted.
     $archived = $db->select($archiveQueryInfo['tables'], $archiveQueryInfo['fields'], $archiveQueryInfo['conds'], __METHOD__, $archiveQueryInfo['options'], $archiveQueryInfo['join_conds']);
     if ($archived->numRows() == 0) {
         return $live;
     } elseif ($live->numRows() == 0) {
         return $archived;
     } else {
         // Combine the two! Whee
         $rows = [];
         foreach ($live as $row) {
             $rows[$row->rev_id] = $row;
         }
         foreach ($archived as $row) {
             $rows[$row->ar_rev_id] = $row;
         }
         krsort($rows);
         return new FakeResultWrapper(array_values($rows));
     }
 }
 /**
  * @param IDatabase $db
  * @return mixed
  */
 public function doQuery($db)
 {
     $ids = array_map('intval', $this->ids);
     $queryInfo = array('tables' => array('revision', 'user'), 'fields' => array_merge(Revision::selectFields(), Revision::selectUserFields()), 'conds' => array('rev_page' => $this->title->getArticleID(), 'rev_id' => $ids), 'options' => array('ORDER BY' => 'rev_id DESC'), 'join_conds' => array('page' => Revision::pageJoinCond(), 'user' => Revision::userJoinCond()));
     ChangeTags::modifyDisplayQuery($queryInfo['tables'], $queryInfo['fields'], $queryInfo['conds'], $queryInfo['join_conds'], $queryInfo['options'], '');
     return $db->select($queryInfo['tables'], $queryInfo['fields'], $queryInfo['conds'], __METHOD__, $queryInfo['options'], $queryInfo['join_conds']);
 }
 /**
  * @param DatabaseBase $db
  * @return mixed
  */
 public function doQuery($db)
 {
     $ids = array_map('intval', $this->ids);
     $queryInfo = DatabaseLogEntry::getSelectQueryData();
     $queryInfo['conds'] += array('log_id' => $ids);
     $queryInfo['options'] += array('ORDER BY' => 'log_id DESC');
     ChangeTags::modifyDisplayQuery($queryInfo['tables'], $queryInfo['fields'], $queryInfo['conds'], $queryInfo['join_conds'], $queryInfo['options'], '');
     return $db->select($queryInfo['tables'], $queryInfo['fields'], $queryInfo['conds'], __METHOD__, $queryInfo['options'], $queryInfo['join_conds']);
 }
 /**
  * @param IDatabase $db
  * @return mixed
  */
 public function doQuery($db)
 {
     $timestamps = [];
     foreach ($this->ids as $id) {
         $timestamps[] = $db->timestamp($id);
     }
     $tables = ['archive'];
     $fields = Revision::selectArchiveFields();
     $conds = ['ar_namespace' => $this->title->getNamespace(), 'ar_title' => $this->title->getDBkey(), 'ar_timestamp' => $timestamps];
     $join_conds = [];
     $options = ['ORDER BY' => 'ar_timestamp DESC'];
     ChangeTags::modifyDisplayQuery($tables, $fields, $conds, $join_conds, $options, '');
     return $db->select($tables, $fields, $conds, __METHOD__, $options, $join_conds);
 }
Example #5
0
 function getQueryInfo()
 {
     $conds = [];
     $conds['rc_new'] = 1;
     $namespace = $this->opts->getValue('namespace');
     $namespace = $namespace === 'all' ? false : intval($namespace);
     $username = $this->opts->getValue('username');
     $user = Title::makeTitleSafe(NS_USER, $username);
     $rcIndexes = [];
     if ($namespace !== false) {
         if ($this->opts->getValue('invert')) {
             $conds[] = 'rc_namespace != ' . $this->mDb->addQuotes($namespace);
         } else {
             $conds['rc_namespace'] = $namespace;
         }
     }
     if ($user) {
         $conds['rc_user_text'] = $user->getText();
         $rcIndexes = 'rc_user_text';
     } elseif (User::groupHasPermission('*', 'createpage') && $this->opts->getValue('hideliu')) {
         # If anons cannot make new pages, don't "exclude logged in users"!
         $conds['rc_user'] = 0;
     }
     # If this user cannot see patrolled edits or they are off, don't do dumb queries!
     if ($this->opts->getValue('hidepatrolled') && $this->getUser()->useNPPatrol()) {
         $conds['rc_patrolled'] = 0;
     }
     if ($this->opts->getValue('hidebots')) {
         $conds['rc_bot'] = 0;
     }
     if ($this->opts->getValue('hideredirs')) {
         $conds['page_is_redirect'] = 0;
     }
     // Allow changes to the New Pages query
     $tables = ['recentchanges', 'page'];
     $fields = ['rc_namespace', 'rc_title', 'rc_cur_id', 'rc_user', 'rc_user_text', 'rc_comment', 'rc_timestamp', 'rc_patrolled', 'rc_id', 'rc_deleted', 'length' => 'page_len', 'rev_id' => 'page_latest', 'rc_this_oldid', 'page_namespace', 'page_title'];
     $join_conds = ['page' => ['INNER JOIN', 'page_id=rc_cur_id']];
     Hooks::run('SpecialNewpagesConditions', [&$this, $this->opts, &$conds, &$tables, &$fields, &$join_conds]);
     $options = [];
     if ($rcIndexes) {
         $options = ['USE INDEX' => ['recentchanges' => $rcIndexes]];
     }
     $info = ['tables' => $tables, 'fields' => $fields, 'conds' => $conds, 'options' => $options, 'join_conds' => $join_conds];
     // Modify query for tags
     ChangeTags::modifyDisplayQuery($info['tables'], $info['fields'], $info['conds'], $info['join_conds'], $info['options'], $this->opts['tagfilter']);
     return $info;
 }
 /**
  * Process the query
  *
  * @param array $conds
  * @param FormOptions $opts
  * @return bool|ResultWrapper Result or false (for Recentchangeslinked only)
  */
 public function doMainQuery($conds, $opts)
 {
     global $wgAllowCategorizedRecentChanges;
     $dbr = $this->getDB();
     $user = $this->getUser();
     $tables = array('recentchanges');
     $fields = RecentChange::selectFields();
     $query_options = array();
     $join_conds = array();
     // JOIN on watchlist for users
     if ($user->getId() && $user->isAllowed('viewmywatchlist')) {
         $tables[] = 'watchlist';
         $fields[] = 'wl_user';
         $fields[] = 'wl_notificationtimestamp';
         $join_conds['watchlist'] = array('LEFT JOIN', array('wl_user' => $user->getId(), 'wl_title=rc_title', 'wl_namespace=rc_namespace'));
     }
     if ($user->isAllowed('rollback')) {
         $tables[] = 'page';
         $fields[] = 'page_latest';
         $join_conds['page'] = array('LEFT JOIN', 'rc_cur_id=page_id');
     }
     ChangeTags::modifyDisplayQuery($tables, $fields, $conds, $join_conds, $query_options, $opts['tagfilter']);
     if (!wfRunHooks('SpecialRecentChangesQuery', array(&$conds, &$tables, &$join_conds, $opts, &$query_options, &$fields), '1.23')) {
         return false;
     }
     // rc_new is not an ENUM, but adding a redundant rc_new IN (0,1) gives mysql enough
     // knowledge to use an index merge if it wants (it may use some other index though).
     $rows = $dbr->select($tables, $fields, $conds + array('rc_new' => array(0, 1)), __METHOD__, array('ORDER BY' => 'rc_timestamp DESC', 'LIMIT' => $opts['limit']) + $query_options, $join_conds);
     // Build the final data
     if ($wgAllowCategorizedRecentChanges) {
         $this->filterByCategories($rows, $opts);
     }
     return $rows;
 }
Example #7
0
 /**
  * Constructs the most part of the query. Extra conditions are sprinkled in
  * all over this class.
  * @return array
  */
 public function getQueryInfo()
 {
     $basic = DatabaseLogEntry::getSelectQueryData();
     $tables = $basic['tables'];
     $fields = $basic['fields'];
     $conds = $basic['conds'];
     $options = $basic['options'];
     $joins = $basic['join_conds'];
     $index = array();
     # Add log_search table if there are conditions on it.
     # This filters the results to only include log rows that have
     # log_search records with the specified ls_field and ls_value values.
     if (array_key_exists('ls_field', $this->mConds)) {
         $tables[] = 'log_search';
         $index['log_search'] = 'ls_field_val';
         $index['logging'] = 'PRIMARY';
         if (!$this->hasEqualsClause('ls_field') || !$this->hasEqualsClause('ls_value')) {
             # Since (ls_field,ls_value,ls_logid) is unique, if the condition is
             # to match a specific (ls_field,ls_value) tuple, then there will be
             # no duplicate log rows. Otherwise, we need to remove the duplicates.
             $options[] = 'DISTINCT';
         }
         # Avoid usage of the wrong index by limiting
         # the choices of available indexes. This mainly
         # avoids site-breaking filesorts.
     } elseif ($this->title || $this->pattern || $this->performer) {
         $index['logging'] = array('page_time', 'user_time');
         if (count($this->types) == 1) {
             $index['logging'][] = 'log_user_type_time';
         }
     } elseif (count($this->types) == 1) {
         $index['logging'] = 'type_time';
     } else {
         $index['logging'] = 'times';
     }
     $options['USE INDEX'] = $index;
     # Don't show duplicate rows when using log_search
     $joins['log_search'] = array('INNER JOIN', 'ls_log_id=log_id');
     $info = array('tables' => $tables, 'fields' => $fields, 'conds' => array_merge($conds, $this->mConds), 'options' => $options, 'join_conds' => $joins);
     # Add ChangeTags filter query
     ChangeTags::modifyDisplayQuery($info['tables'], $info['fields'], $info['conds'], $info['join_conds'], $info['options'], $this->mTagFilter);
     return $info;
 }
Example #8
0
 public function getQueryInfo()
 {
     $tables = array('logging', 'user');
     $this->mConds[] = 'user_id = log_user';
     $index = array();
     $options = array();
     # Add log_search table if there are conditions on it
     if (array_key_exists('ls_field', $this->mConds)) {
         $tables[] = 'log_search';
         $index['log_search'] = 'ls_field_val';
         $index['logging'] = 'PRIMARY';
         $options[] = 'DISTINCT';
         # Avoid usage of the wrong index by limiting
         # the choices of available indexes. This mainly
         # avoids site-breaking filesorts.
     } else {
         if ($this->title || $this->pattern || $this->user) {
             $index['logging'] = array('page_time', 'user_time');
             if (count($this->types) == 1) {
                 $index['logging'][] = 'log_user_type_time';
             }
         } else {
             if (count($this->types) == 1) {
                 $index['logging'] = 'type_time';
             } else {
                 $index['logging'] = 'times';
             }
         }
     }
     $options['USE INDEX'] = $index;
     # Don't show duplicate rows when using log_search
     $info = array('tables' => $tables, 'fields' => array('log_type', 'log_action', 'log_user', 'log_namespace', 'log_title', 'log_params', 'log_comment', 'log_id', 'log_deleted', 'log_timestamp', 'user_name', 'user_editcount'), 'conds' => $this->mConds, 'options' => $options, 'join_conds' => array('user' => array('INNER JOIN', 'user_id=log_user'), 'log_search' => array('INNER JOIN', 'ls_log_id=log_id')));
     # Add ChangeTags filter query
     ChangeTags::modifyDisplayQuery($info['tables'], $info['fields'], $info['conds'], $info['join_conds'], $info['options'], $this->mTagFilter);
     return $info;
 }
Example #9
0
 /**
  * Process the query
  *
  * @param array $conds
  * @param FormOptions $opts
  * @return bool|ResultWrapper Result or false (for Recentchangeslinked only)
  */
 public function doMainQuery($conds, $opts)
 {
     $dbr = $this->getDB();
     $user = $this->getUser();
     # Toggle watchlist content (all recent edits or just the latest)
     if ($opts['extended']) {
         $limitWatchlist = $user->getIntOption('wllimit');
         $usePage = false;
     } else {
         # Top log Ids for a page are not stored
         $nonRevisionTypes = array(RC_LOG);
         Hooks::run('SpecialWatchlistGetNonRevisionTypes', array(&$nonRevisionTypes));
         if ($nonRevisionTypes) {
             $conds[] = $dbr->makeList(array('rc_this_oldid=page_latest', 'rc_type' => $nonRevisionTypes), LIST_OR);
         }
         $limitWatchlist = 0;
         $usePage = true;
     }
     $tables = array('recentchanges', 'watchlist');
     $fields = RecentChange::selectFields();
     $query_options = array('ORDER BY' => 'rc_timestamp DESC');
     $join_conds = array('watchlist' => array('INNER JOIN', array('wl_user' => $user->getId(), 'wl_namespace=rc_namespace', 'wl_title=rc_title')));
     if ($this->getConfig()->get('ShowUpdatedMarker')) {
         $fields[] = 'wl_notificationtimestamp';
     }
     if ($limitWatchlist) {
         $query_options['LIMIT'] = $limitWatchlist;
     }
     $rollbacker = $user->isAllowed('rollback');
     if ($usePage || $rollbacker) {
         $tables[] = 'page';
         $join_conds['page'] = array('LEFT JOIN', 'rc_cur_id=page_id');
         if ($rollbacker) {
             $fields[] = 'page_latest';
         }
     }
     // Log entries with DELETED_ACTION must not show up unless the user has
     // the necessary rights.
     if (!$user->isAllowed('deletedhistory')) {
         $bitmask = LogPage::DELETED_ACTION;
     } elseif (!$user->isAllowedAny('suppressrevision', 'viewsuppressed')) {
         $bitmask = LogPage::DELETED_ACTION | LogPage::DELETED_RESTRICTED;
     } else {
         $bitmask = 0;
     }
     if ($bitmask) {
         $conds[] = $dbr->makeList(array('rc_type != ' . RC_LOG, $dbr->bitAnd('rc_deleted', $bitmask) . " != {$bitmask}"), LIST_OR);
     }
     ChangeTags::modifyDisplayQuery($tables, $fields, $conds, $join_conds, $query_options, '');
     $this->runMainQueryHook($tables, $fields, $conds, $query_options, $join_conds, $opts);
     return $dbr->select($tables, $fields, $conds, __METHOD__, $query_options, $join_conds);
 }
Example #10
0
 /**
  * Process the query
  *
  * @param array $conds
  * @param FormOptions $opts
  * @return bool|ResultWrapper Result or false (for Recentchangeslinked only)
  */
 public function doMainQuery($conds, $opts)
 {
     $dbr = $this->getDB();
     $user = $this->getUser();
     $tables = array('recentchanges');
     $fields = RecentChange::selectFields();
     $query_options = array();
     $join_conds = array();
     // JOIN on watchlist for users
     if ($user->getId() && $user->isAllowed('viewmywatchlist')) {
         $tables[] = 'watchlist';
         $fields[] = 'wl_user';
         $fields[] = 'wl_notificationtimestamp';
         $join_conds['watchlist'] = array('LEFT JOIN', array('wl_user' => $user->getId(), 'wl_title=rc_title', 'wl_namespace=rc_namespace'));
     }
     if ($user->isAllowed('rollback')) {
         $tables[] = 'page';
         $fields[] = 'page_latest';
         $join_conds['page'] = array('LEFT JOIN', 'rc_cur_id=page_id');
     }
     ChangeTags::modifyDisplayQuery($tables, $fields, $conds, $join_conds, $query_options, $opts['tagfilter']);
     if (!$this->runMainQueryHook($tables, $fields, $conds, $query_options, $join_conds, $opts)) {
         return false;
     }
     // array_merge() is used intentionally here so that hooks can, should
     // they so desire, override the ORDER BY / LIMIT condition(s); prior to
     // MediaWiki 1.26 this used to use the plus operator instead, which meant
     // that extensions weren't able to change these conditions
     $query_options = array_merge(array('ORDER BY' => 'rc_timestamp DESC', 'LIMIT' => $opts['limit']), $query_options);
     $rows = $dbr->select($tables, $fields, $conds + array('rc_new' => array(0, 1)), __METHOD__, $query_options, $join_conds);
     // Build the final data
     if ($this->getConfig()->get('AllowCategorizedRecentChanges')) {
         $this->filterByCategories($rows, $opts);
     }
     return $rows;
 }
 function getQueryInfo()
 {
     $queryInfo = array('tables' => array('revision', 'user'), 'fields' => array_merge(Revision::selectFields(), Revision::selectUserFields()), 'conds' => array_merge(array('rev_page' => $this->getWikiPage()->getId()), $this->conds), 'options' => array('USE INDEX' => array('revision' => 'page_timestamp')), 'join_conds' => array('user' => Revision::userJoinCond()));
     ChangeTags::modifyDisplayQuery($queryInfo['tables'], $queryInfo['fields'], $queryInfo['conds'], $queryInfo['join_conds'], $queryInfo['options'], $this->tagFilter);
     wfRunHooks('PageHistoryPager::getQueryInfo', array(&$this, &$queryInfo));
     return $queryInfo;
 }
Example #12
0
 /**
  * Process the query
  *
  * @param $conds array
  * @param $opts FormOptions
  * @return database result or false (for Recentchangeslinked only)
  */
 public function doMainQuery($conds, $opts)
 {
     global $wgUser;
     $tables = array('recentchanges');
     $join_conds = array();
     $query_options = array('USE INDEX' => array('recentchanges' => 'rc_timestamp'));
     $uid = $wgUser->getId();
     $dbr = wfGetDB(DB_SLAVE);
     $limit = $opts['limit'];
     $namespace = $opts['namespace'];
     $invert = $opts['invert'];
     $join_conds = array();
     // JOIN on watchlist for users
     if ($uid) {
         $tables[] = 'watchlist';
         $join_conds['watchlist'] = array('LEFT JOIN', "wl_user={$uid} AND wl_title=rc_title AND wl_namespace=rc_namespace");
     }
     if ($wgUser->isAllowed("rollback")) {
         $tables[] = 'page';
         $join_conds['page'] = array('LEFT JOIN', 'rc_cur_id=page_id');
     }
     // Tag stuff.
     $fields = array();
     // Fields are * in this case, so let the function modify an empty array to keep it happy.
     ChangeTags::modifyDisplayQuery($tables, $fields, $conds, $join_conds, $query_options, $opts['tagfilter']);
     wfRunHooks('SpecialRecentChangesQuery', array(&$conds, &$tables, &$join_conds, $opts));
     // Is there either one namespace selected or excluded?
     // Tag filtering also has a better index.
     // Also, if this is "all" or main namespace, just use timestamp index.
     if (is_null($namespace) || $invert || $namespace == NS_MAIN || $opts['tagfilter']) {
         $res = $dbr->select($tables, '*', $conds, __METHOD__, array('ORDER BY' => 'rc_timestamp DESC', 'LIMIT' => $limit) + $query_options, $join_conds);
         // We have a new_namespace_time index! UNION over new=(0,1) and sort result set!
     } else {
         // New pages
         $sqlNew = $dbr->selectSQLText($tables, '*', array('rc_new' => 1) + $conds, __METHOD__, array('ORDER BY' => 'rc_timestamp DESC', 'LIMIT' => $limit, 'USE INDEX' => array('recentchanges' => 'new_name_timestamp')), $join_conds);
         // Old pages
         $sqlOld = $dbr->selectSQLText($tables, '*', array('rc_new' => 0) + $conds, __METHOD__, array('ORDER BY' => 'rc_timestamp DESC', 'LIMIT' => $limit, 'USE INDEX' => array('recentchanges' => 'new_name_timestamp')), $join_conds);
         # Join the two fast queries, and sort the result set
         $sql = "({$sqlNew}) UNION ({$sqlOld}) ORDER BY rc_timestamp DESC LIMIT {$limit}";
         $res = $dbr->query($sql, __METHOD__);
     }
     return $res;
 }
 public function doMainQuery($conds, $opts)
 {
     $target = $opts['target'];
     $showlinkedto = $opts['showlinkedto'];
     $limit = $opts['limit'];
     if ($target === '') {
         return false;
     }
     $outputPage = $this->getOutput();
     $title = Title::newFromURL($target);
     if (!$title || $title->isExternal()) {
         $outputPage->addHtml('<div class="errorbox">' . $this->msg('allpagesbadtitle')->parse() . '</div>');
         return false;
     }
     $outputPage->setPageTitle($this->msg('recentchangeslinked-title', $title->getPrefixedText()));
     /*
      * Ordinary links are in the pagelinks table, while transclusions are
      * in the templatelinks table, categorizations in categorylinks and
      * image use in imagelinks.  We need to somehow combine all these.
      * Special:Whatlinkshere does this by firing multiple queries and
      * merging the results, but the code we inherit from our parent class
      * expects only one result set so we use UNION instead.
      */
     $dbr = wfGetDB(DB_SLAVE, 'recentchangeslinked');
     $id = $title->getArticleID();
     $ns = $title->getNamespace();
     $dbkey = $title->getDBkey();
     $tables = array('recentchanges');
     $select = RecentChange::selectFields();
     $join_conds = array();
     $query_options = array();
     // left join with watchlist table to highlight watched rows
     $uid = $this->getUser()->getId();
     if ($uid && $this->getUser()->isAllowed('viewmywatchlist')) {
         $tables[] = 'watchlist';
         $select[] = 'wl_user';
         $join_conds['watchlist'] = array('LEFT JOIN', array('wl_user' => $uid, 'wl_title=rc_title', 'wl_namespace=rc_namespace'));
     }
     if ($this->getUser()->isAllowed('rollback')) {
         $tables[] = 'page';
         $join_conds['page'] = array('LEFT JOIN', 'rc_cur_id=page_id');
         $select[] = 'page_latest';
     }
     ChangeTags::modifyDisplayQuery($tables, $select, $conds, $join_conds, $query_options, $opts['tagfilter']);
     if (!wfRunHooks('SpecialRecentChangesQuery', array(&$conds, &$tables, &$join_conds, $opts, &$query_options, &$select), '1.23')) {
         return false;
     }
     if ($ns == NS_CATEGORY && !$showlinkedto) {
         // special handling for categories
         // XXX: should try to make this less kludgy
         $link_tables = array('categorylinks');
         $showlinkedto = true;
     } else {
         // for now, always join on these tables; really should be configurable as in whatlinkshere
         $link_tables = array('pagelinks', 'templatelinks');
         // imagelinks only contains links to pages in NS_FILE
         if ($ns == NS_FILE || !$showlinkedto) {
             $link_tables[] = 'imagelinks';
         }
     }
     if ($id == 0 && !$showlinkedto) {
         return false;
         // nonexistent pages can't link to any pages
     }
     // field name prefixes for all the various tables we might want to join with
     $prefix = array('pagelinks' => 'pl', 'templatelinks' => 'tl', 'categorylinks' => 'cl', 'imagelinks' => 'il');
     $subsql = array();
     // SELECT statements to combine with UNION
     foreach ($link_tables as $link_table) {
         $pfx = $prefix[$link_table];
         // imagelinks and categorylinks tables have no xx_namespace field,
         // and have xx_to instead of xx_title
         if ($link_table == 'imagelinks') {
             $link_ns = NS_FILE;
         } elseif ($link_table == 'categorylinks') {
             $link_ns = NS_CATEGORY;
         } else {
             $link_ns = 0;
         }
         if ($showlinkedto) {
             // find changes to pages linking to this page
             if ($link_ns) {
                 if ($ns != $link_ns) {
                     continue;
                 }
                 // should never happen, but check anyway
                 $subconds = array("{$pfx}_to" => $dbkey);
             } else {
                 $subconds = array("{$pfx}_namespace" => $ns, "{$pfx}_title" => $dbkey);
             }
             $subjoin = "rc_cur_id = {$pfx}_from";
         } else {
             // find changes to pages linked from this page
             $subconds = array("{$pfx}_from" => $id);
             if ($link_table == 'imagelinks' || $link_table == 'categorylinks') {
                 $subconds["rc_namespace"] = $link_ns;
                 $subjoin = "rc_title = {$pfx}_to";
             } else {
                 $subjoin = array("rc_namespace = {$pfx}_namespace", "rc_title = {$pfx}_title");
             }
         }
         if ($dbr->unionSupportsOrderAndLimit()) {
             $order = array('ORDER BY' => 'rc_timestamp DESC');
         } else {
             $order = array();
         }
         $query = $dbr->selectSQLText(array_merge($tables, array($link_table)), $select, $conds + $subconds, __METHOD__, $order + $query_options, $join_conds + array($link_table => array('INNER JOIN', $subjoin)));
         if ($dbr->unionSupportsOrderAndLimit()) {
             $query = $dbr->limitResult($query, $limit);
         }
         $subsql[] = $query;
     }
     if (count($subsql) == 0) {
         return false;
         // should never happen
     }
     if (count($subsql) == 1 && $dbr->unionSupportsOrderAndLimit()) {
         $sql = $subsql[0];
     } else {
         // need to resort and relimit after union
         $sql = $dbr->unionQueries($subsql, false) . ' ORDER BY rc_timestamp DESC';
         $sql = $dbr->limitResult($sql, $limit, false);
     }
     $res = $dbr->query($sql, __METHOD__);
     if ($res->numRows() == 0) {
         $this->mResultEmpty = true;
     }
     return $res;
 }
Example #14
0
 public function getQueryInfo()
 {
     $this->mConds[] = 'user_id = log_user';
     # Don't use the wrong logging index
     if ($this->title || $this->pattern || $this->user) {
         $index = array('USE INDEX' => array('logging' => array('page_time', 'user_time')));
     } else {
         if ($this->type) {
             $index = array('USE INDEX' => array('logging' => 'type_time'));
         } else {
             $index = array('USE INDEX' => array('logging' => 'times'));
         }
     }
     $info = array('tables' => array('logging', 'user'), 'fields' => array('log_type', 'log_action', 'log_user', 'log_namespace', 'log_title', 'log_params', 'log_comment', 'log_id', 'log_deleted', 'log_timestamp', 'user_name', 'user_editcount'), 'conds' => $this->mConds, 'options' => $index, 'join_conds' => array('user' => array('INNER JOIN', 'user_id=log_user')));
     ChangeTags::modifyDisplayQuery($info['tables'], $info['fields'], $info['conds'], $info['join_conds'], $info['options'], $this->mTagFilter);
     return $info;
 }
 function getQueryInfo()
 {
     global $wgEnableNewpagesUserFilter, $wgGroupPermissions;
     $conds = array();
     $conds['rc_new'] = 1;
     $namespace = $this->opts->getValue('namespace');
     $namespace = $namespace === 'all' ? false : intval($namespace);
     $username = $this->opts->getValue('username');
     $user = Title::makeTitleSafe(NS_USER, $username);
     if ($namespace !== false) {
         $conds['rc_namespace'] = $namespace;
         $rcIndexes = array('new_name_timestamp');
     } else {
         $rcIndexes = array('rc_timestamp');
     }
     # $wgEnableNewpagesUserFilter - temp WMF hack
     if ($wgEnableNewpagesUserFilter && $user) {
         $conds['rc_user_text'] = $user->getText();
         $rcIndexes = 'rc_user_text';
         # If anons cannot make new pages, don't "exclude logged in users"!
     } elseif ($wgGroupPermissions['*']['createpage'] && $this->opts->getValue('hideliu')) {
         $conds['rc_user'] = 0;
     }
     # If this user cannot see patrolled edits or they are off, don't do dumb queries!
     if ($this->opts->getValue('hidepatrolled') && $this->getUser()->useNPPatrol()) {
         $conds['rc_patrolled'] = 0;
     }
     if ($this->opts->getValue('hidebots')) {
         $conds['rc_bot'] = 0;
     }
     if ($this->opts->getValue('hideredirs')) {
         $conds['page_is_redirect'] = 0;
     }
     // Allow changes to the New Pages query
     $tables = array('recentchanges', 'page');
     $fields = array('rc_namespace', 'rc_title', 'rc_cur_id', 'rc_user', 'rc_user_text', 'rc_comment', 'rc_timestamp', 'rc_patrolled', 'rc_id', 'rc_deleted', 'page_len AS length', 'page_latest AS rev_id', 'ts_tags', 'rc_this_oldid', 'page_namespace', 'page_title');
     $join_conds = array('page' => array('INNER JOIN', 'page_id=rc_cur_id'));
     wfRunHooks('SpecialNewpagesConditions', array(&$this, $this->opts, &$conds, &$tables, &$fields, &$join_conds));
     $info = array('tables' => $tables, 'fields' => $fields, 'conds' => $conds, 'options' => array('USE INDEX' => array('recentchanges' => $rcIndexes)), 'join_conds' => $join_conds);
     // Empty array for fields, it'll be set by us anyway.
     $fields = array();
     // Modify query for tags
     ChangeTags::modifyDisplayQuery($info['tables'], $fields, $info['conds'], $info['join_conds'], $info['options'], $this->opts['tagfilter']);
     return $info;
 }
Example #16
0
/**
 * Constructor
 *
 * @param $par Parameter passed to the page
 */
function wfSpecialWatchlist($par)
{
    global $wgUser, $wgOut, $wgLang, $wgRequest;
    global $wgRCShowWatchingUsers, $wgEnotifWatchlist, $wgShowUpdatedMarker;
    // Add feed links
    $wlToken = $wgUser->getOption('watchlisttoken');
    if (!$wlToken) {
        $wlToken = sha1(mt_rand() . microtime(true));
        $wgUser->setOption('watchlisttoken', $wlToken);
        $wgUser->saveSettings();
    }
    global $wgFeedClasses;
    $apiParams = array('action' => 'feedwatchlist', 'allrev' => 'allrev', 'wlowner' => $wgUser->getName(), 'wltoken' => $wlToken);
    $feedTemplate = wfScript('api') . '?';
    foreach ($wgFeedClasses as $format => $class) {
        $theseParams = $apiParams + array('feedformat' => $format);
        $url = $feedTemplate . wfArrayToCGI($theseParams);
        $wgOut->addFeedLink($format, $url);
    }
    $skin = $wgUser->getSkin();
    $specialTitle = SpecialPage::getTitleFor('Watchlist');
    $wgOut->setRobotPolicy('noindex,nofollow');
    # Anons don't get a watchlist
    if ($wgUser->isAnon()) {
        $wgOut->setPageTitle(wfMsg('watchnologin'));
        $llink = $skin->linkKnown(SpecialPage::getTitleFor('Userlogin'), wfMsgHtml('loginreqlink'), array(), array('returnto' => $specialTitle->getPrefixedText()));
        $wgOut->addHTML(wfMsgWikiHtml('watchlistanontext', $llink));
        return;
    }
    $wgOut->setPageTitle(wfMsg('watchlist'));
    $sub = wfMsgExt('watchlistfor2', array('parseinline', 'replaceafter'), $wgUser->getName(), WatchlistEditor::buildTools($wgUser->getSkin()));
    $wgOut->setSubtitle($sub);
    if (($mode = WatchlistEditor::getMode($wgRequest, $par)) !== false) {
        $editor = new WatchlistEditor();
        $editor->execute($wgUser, $wgOut, $wgRequest, $mode);
        return;
    }
    $uid = $wgUser->getId();
    if (($wgEnotifWatchlist || $wgShowUpdatedMarker) && $wgRequest->getVal('reset') && $wgRequest->wasPosted()) {
        $wgUser->clearAllNotifications($uid);
        $wgOut->redirect($specialTitle->getFullUrl());
        return;
    }
    $defaults = array('days' => floatval($wgUser->getOption('watchlistdays')), 'hideMinor' => (int) $wgUser->getBoolOption('watchlisthideminor'), 'hideBots' => (int) $wgUser->getBoolOption('watchlisthidebots'), 'hideAnons' => (int) $wgUser->getBoolOption('watchlisthideanons'), 'hideLiu' => (int) $wgUser->getBoolOption('watchlisthideliu'), 'hidePatrolled' => (int) $wgUser->getBoolOption('watchlisthidepatrolled'), 'hideOwn' => (int) $wgUser->getBoolOption('watchlisthideown'), 'namespace' => 'all', 'invert' => false);
    extract($defaults);
    # Extract variables from the request, falling back to user preferences or
    # other default values if these don't exist
    $prefs['days'] = floatval($wgUser->getOption('watchlistdays'));
    $prefs['hideminor'] = $wgUser->getBoolOption('watchlisthideminor');
    $prefs['hidebots'] = $wgUser->getBoolOption('watchlisthidebots');
    $prefs['hideanons'] = $wgUser->getBoolOption('watchlisthideanons');
    $prefs['hideliu'] = $wgUser->getBoolOption('watchlisthideliu');
    $prefs['hideown'] = $wgUser->getBoolOption('watchlisthideown');
    $prefs['hidepatrolled'] = $wgUser->getBoolOption('watchlisthidepatrolled');
    # Get query variables
    $days = $wgRequest->getVal('days', $prefs['days']);
    $hideMinor = $wgRequest->getBool('hideMinor', $prefs['hideminor']);
    $hideBots = $wgRequest->getBool('hideBots', $prefs['hidebots']);
    $hideAnons = $wgRequest->getBool('hideAnons', $prefs['hideanons']);
    $hideLiu = $wgRequest->getBool('hideLiu', $prefs['hideliu']);
    $hideOwn = $wgRequest->getBool('hideOwn', $prefs['hideown']);
    $hidePatrolled = $wgRequest->getBool('hidePatrolled', $prefs['hidepatrolled']);
    # Get namespace value, if supplied, and prepare a WHERE fragment
    $nameSpace = $wgRequest->getIntOrNull('namespace');
    $invert = $wgRequest->getIntOrNull('invert');
    if (!is_null($nameSpace)) {
        $nameSpace = intval($nameSpace);
        if ($invert && $nameSpace !== 'all') {
            $nameSpaceClause = "rc_namespace != {$nameSpace}";
        } else {
            $nameSpaceClause = "rc_namespace = {$nameSpace}";
        }
    } else {
        $nameSpace = '';
        $nameSpaceClause = '';
    }
    $dbr = wfGetDB(DB_SLAVE, 'watchlist');
    $recentchanges = $dbr->tableName('recentchanges');
    $watchlistCount = $dbr->selectField('watchlist', 'COUNT(*)', array('wl_user' => $uid), __METHOD__);
    // Adjust for page X, talk:page X, which are both stored separately,
    // but treated together
    $nitems = floor($watchlistCount / 2);
    if (is_null($days) || !is_numeric($days)) {
        $big = 1000;
        /* The magical big */
        if ($nitems > $big) {
            # Set default cutoff shorter
            $days = $defaults['days'] = 12.0 / 24.0;
            # 12 hours...
        } else {
            $days = $defaults['days'];
            # default cutoff for shortlisters
        }
    } else {
        $days = floatval($days);
    }
    // Dump everything here
    $nondefaults = array();
    wfAppendToArrayIfNotDefault('days', $days, $defaults, $nondefaults);
    wfAppendToArrayIfNotDefault('hideMinor', (int) $hideMinor, $defaults, $nondefaults);
    wfAppendToArrayIfNotDefault('hideBots', (int) $hideBots, $defaults, $nondefaults);
    wfAppendToArrayIfNotDefault('hideAnons', (int) $hideAnons, $defaults, $nondefaults);
    wfAppendToArrayIfNotDefault('hideLiu', (int) $hideLiu, $defaults, $nondefaults);
    wfAppendToArrayIfNotDefault('hideOwn', (int) $hideOwn, $defaults, $nondefaults);
    wfAppendToArrayIfNotDefault('namespace', $nameSpace, $defaults, $nondefaults);
    wfAppendToArrayIfNotDefault('hidePatrolled', (int) $hidePatrolled, $defaults, $nondefaults);
    if ($nitems == 0) {
        $wgOut->addWikiMsg('nowatchlist');
        return;
    }
    # Possible where conditions
    $conds = array();
    if ($days > 0) {
        $conds[] = "rc_timestamp > '" . $dbr->timestamp(time() - intval($days * 86400)) . "'";
    }
    # If the watchlist is relatively short, it's simplest to zip
    # down its entirety and then sort the results.
    # If it's relatively long, it may be worth our while to zip
    # through the time-sorted page list checking for watched items.
    # Up estimate of watched items by 15% to compensate for talk pages...
    # Toggles
    if ($hideOwn) {
        $conds[] = "rc_user != {$uid}";
    }
    if ($hideBots) {
        $conds[] = 'rc_bot = 0';
    }
    if ($hideMinor) {
        $conds[] = 'rc_minor = 0';
    }
    if ($hideLiu) {
        $conds[] = 'rc_user = 0';
    }
    if ($hideAnons) {
        $conds[] = 'rc_user != 0';
    }
    if ($wgUser->useRCPatrol() && $hidePatrolled) {
        $conds[] = 'rc_patrolled != 1';
    }
    if ($nameSpaceClause) {
        $conds[] = $nameSpaceClause;
    }
    # Toggle watchlist content (all recent edits or just the latest)
    if ($wgUser->getOption('extendwatchlist')) {
        $limitWatchlist = intval($wgUser->getOption('wllimit'));
        $usePage = false;
    } else {
        # Top log Ids for a page are not stored
        $conds[] = 'rc_this_oldid=page_latest OR rc_type=' . RC_LOG;
        $limitWatchlist = 0;
        $usePage = true;
    }
    # Show a message about slave lag, if applicable
    if (($lag = $dbr->getLag()) > 0) {
        $wgOut->showLagWarning($lag);
    }
    # Create output form
    $form = Xml::fieldset(wfMsg('watchlist-options'), false, array('id' => 'mw-watchlist-options'));
    # Show watchlist header
    $form .= wfMsgExt('watchlist-details', array('parseinline'), $wgLang->formatNum($nitems));
    if ($wgUser->getOption('enotifwatchlistpages') && $wgEnotifWatchlist) {
        $form .= wfMsgExt('wlheader-enotif', 'parse') . "\n";
    }
    if ($wgShowUpdatedMarker) {
        $form .= Xml::openElement('form', array('method' => 'post', 'action' => $specialTitle->getLocalUrl(), 'id' => 'mw-watchlist-resetbutton')) . wfMsgExt('wlheader-showupdated', array('parseinline')) . ' ' . Xml::submitButton(wfMsg('enotif_reset'), array('name' => 'dummy')) . Html::hidden('reset', 'all') . Xml::closeElement('form');
    }
    $form .= '<hr />';
    $tables = array('recentchanges', 'watchlist');
    $fields = array("{$recentchanges}.*");
    $join_conds = array('watchlist' => array('INNER JOIN', "wl_user='******' AND wl_namespace=rc_namespace AND wl_title=rc_title"));
    $options = array('ORDER BY' => 'rc_timestamp DESC');
    if ($wgShowUpdatedMarker) {
        $fields[] = 'wl_notificationtimestamp';
    }
    if ($limitWatchlist) {
        $options['LIMIT'] = $limitWatchlist;
    }
    $rollbacker = $wgUser->isAllowed('rollback');
    if ($usePage || $rollbacker) {
        $tables[] = 'page';
        $join_conds['page'] = array('LEFT JOIN', 'rc_cur_id=page_id');
        if ($rollbacker) {
            $fields[] = 'page_latest';
        }
    }
    ChangeTags::modifyDisplayQuery($tables, $fields, $conds, $join_conds, $options, '');
    wfRunHooks('SpecialWatchlistQuery', array(&$conds, &$tables, &$join_conds, &$fields));
    $res = $dbr->select($tables, $fields, $conds, __METHOD__, $options, $join_conds);
    $numRows = $dbr->numRows($res);
    /* Start bottom header */
    $wlInfo = '';
    if ($days >= 1) {
        $wlInfo = wfMsgExt('rcnote', 'parseinline', $wgLang->formatNum($numRows), $wgLang->formatNum($days), $wgLang->timeAndDate(wfTimestampNow(), true), $wgLang->date(wfTimestampNow(), true), $wgLang->time(wfTimestampNow(), true)) . '<br />';
    } elseif ($days > 0) {
        $wlInfo = wfMsgExt('wlnote', 'parseinline', $wgLang->formatNum($numRows), $wgLang->formatNum(round($days * 24))) . '<br />';
    }
    $cutofflinks = "\n" . wlCutoffLinks($days, 'Watchlist', $nondefaults) . "<br />\n";
    $thisTitle = SpecialPage::getTitleFor('Watchlist');
    # Spit out some control panel links
    $links[] = wlShowHideLink($nondefaults, 'rcshowhideminor', 'hideMinor', $hideMinor);
    $links[] = wlShowHideLink($nondefaults, 'rcshowhidebots', 'hideBots', $hideBots);
    $links[] = wlShowHideLink($nondefaults, 'rcshowhideanons', 'hideAnons', $hideAnons);
    $links[] = wlShowHideLink($nondefaults, 'rcshowhideliu', 'hideLiu', $hideLiu);
    $links[] = wlShowHideLink($nondefaults, 'rcshowhidemine', 'hideOwn', $hideOwn);
    if ($wgUser->useRCPatrol()) {
        $links[] = wlShowHideLink($nondefaults, 'rcshowhidepatr', 'hidePatrolled', $hidePatrolled);
    }
    # Namespace filter and put the whole form together.
    $form .= $wlInfo;
    $form .= $cutofflinks;
    $form .= $wgLang->pipeList($links);
    $form .= Xml::openElement('form', array('method' => 'post', 'action' => $thisTitle->getLocalUrl(), 'id' => 'mw-watchlist-form-namespaceselector'));
    $form .= '<hr /><p>';
    $form .= Xml::label(wfMsg('namespace'), 'namespace') . '&#160;';
    $form .= Xml::namespaceSelector($nameSpace, '') . '&#160;';
    $form .= Xml::checkLabel(wfMsg('invert'), 'invert', 'nsinvert', $invert) . '&#160;';
    $form .= Xml::submitButton(wfMsg('allpagessubmit')) . '</p>';
    $form .= Html::hidden('days', $days);
    if ($hideMinor) {
        $form .= Html::hidden('hideMinor', 1);
    }
    if ($hideBots) {
        $form .= Html::hidden('hideBots', 1);
    }
    if ($hideAnons) {
        $form .= Html::hidden('hideAnons', 1);
    }
    if ($hideLiu) {
        $form .= Html::hidden('hideLiu', 1);
    }
    if ($hideOwn) {
        $form .= Html::hidden('hideOwn', 1);
    }
    $form .= Xml::closeElement('form');
    $form .= Xml::closeElement('fieldset');
    $wgOut->addHTML($form);
    # If there's nothing to show, stop here
    if ($numRows == 0) {
        $wgOut->addWikiMsg('watchnochange');
        return;
    }
    /* End bottom header */
    /* Do link batch query */
    $linkBatch = new LinkBatch();
    foreach ($res as $row) {
        $userNameUnderscored = str_replace(' ', '_', $row->rc_user_text);
        if ($row->rc_user != 0) {
            $linkBatch->add(NS_USER, $userNameUnderscored);
        }
        $linkBatch->add(NS_USER_TALK, $userNameUnderscored);
        $linkBatch->add($row->rc_namespace, $row->rc_title);
    }
    $linkBatch->execute();
    $dbr->dataSeek($res, 0);
    $list = ChangesList::newFromUser($wgUser);
    $list->setWatchlistDivs();
    $s = $list->beginRecentChangesList();
    $counter = 1;
    foreach ($res as $obj) {
        # Make RC entry
        $rc = RecentChange::newFromRow($obj);
        $rc->counter = $counter++;
        if ($wgShowUpdatedMarker) {
            $updated = $obj->wl_notificationtimestamp;
        } else {
            $updated = false;
        }
        if ($wgRCShowWatchingUsers && $wgUser->getOption('shownumberswatching')) {
            $rc->numberofWatchingusers = $dbr->selectField('watchlist', 'COUNT(*)', array('wl_namespace' => $obj->rc_namespace, 'wl_title' => $obj->rc_title), __METHOD__);
        } else {
            $rc->numberofWatchingusers = 0;
        }
        $s .= $list->recentChangesLine($rc, $updated, $counter);
    }
    $s .= $list->endRecentChangesList();
    $wgOut->addHTML($s);
}
	/**
	 * Process the query
	 *
	 * @param array $conds
	 * @param FormOptions $opts
	 * @return bool|ResultWrapper Result or false (for Recentchangeslinked only)
	 */
	public function doMainQuery( $conds, $opts ) {
		$tables = array( 'recentchanges' );
		$join_conds = array();
		$query_options = array(
			'USE INDEX' => array( 'recentchanges' => 'rc_timestamp' )
		);

		$uid = $this->getUser()->getId();
		$dbr = wfGetDB( DB_SLAVE );
		$limit = $opts['limit'];
		$namespace = $opts['namespace'];
		$invert = $opts['invert'];
		$associated = $opts['associated'];

		$fields = RecentChange::selectFields();
		// JOIN on watchlist for users
		if ( $uid && $this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
			$tables[] = 'watchlist';
			$fields[] = 'wl_user';
			$fields[] = 'wl_notificationtimestamp';
			$join_conds['watchlist'] = array( 'LEFT JOIN', array(
				'wl_user' => $uid,
				'wl_title=rc_title',
				'wl_namespace=rc_namespace'
			) );
		}
		if ( $this->getUser()->isAllowed( 'rollback' ) ) {
			$tables[] = 'page';
			$fields[] = 'page_latest';
			$join_conds['page'] = array( 'LEFT JOIN', 'rc_cur_id=page_id' );
		}
		// Tag stuff.
		ChangeTags::modifyDisplayQuery(
			$tables,
			$fields,
			$conds,
			$join_conds,
			$query_options,
			$opts['tagfilter']
		);

		if ( !wfRunHooks( 'SpecialRecentChangesQuery',
			array( &$conds, &$tables, &$join_conds, $opts, &$query_options, &$fields ) )
		) {
			return false;
		}

		// rc_new is not an ENUM, but adding a redundant rc_new IN (0,1) gives mysql enough
		// knowledge to use an index merge if it wants (it may use some other index though).
		return $dbr->select(
			$tables,
			$fields,
			$conds + array( 'rc_new' => array( 0, 1 ) ),
			__METHOD__,
			array( 'ORDER BY' => 'rc_timestamp DESC', 'LIMIT' => $limit ) + $query_options,
			$join_conds
		);
	}
 public function doMainQuery($conds, $opts)
 {
     global $wgUser, $wgOut;
     $target = $opts['target'];
     $showlinkedto = $opts['showlinkedto'];
     $limit = $opts['limit'];
     if ($target === '') {
         return false;
     }
     $title = Title::newFromURL($target);
     if (!$title || $title->getInterwiki() != '') {
         $wgOut->wrapWikiMsg('<div class="errorbox">$1</div><br clear="both" />', 'allpagesbadtitle');
         return false;
     }
     $this->mTargetTitle = $title;
     $wgOut->setPageTitle(wfMsg('recentchangeslinked-title', $title->getPrefixedText()));
     /*
      * Ordinary links are in the pagelinks table, while transclusions are
      * in the templatelinks table, categorizations in categorylinks and
      * image use in imagelinks.  We need to somehow combine all these.
      * Special:Whatlinkshere does this by firing multiple queries and
      * merging the results, but the code we inherit from our parent class
      * expects only one result set so we use UNION instead.
      */
     $dbr = wfGetDB(DB_SLAVE, 'recentchangeslinked');
     $id = $title->getArticleId();
     $ns = $title->getNamespace();
     $dbkey = $title->getDBkey();
     $tables = array('recentchanges');
     $select = array($dbr->tableName('recentchanges') . '.*');
     $join_conds = array();
     $query_options = array();
     // left join with watchlist table to highlight watched rows
     if ($uid = $wgUser->getId()) {
         $tables[] = 'watchlist';
         $select[] = 'wl_user';
         $join_conds['watchlist'] = array('LEFT JOIN', "wl_user={$uid} AND wl_title=rc_title AND wl_namespace=rc_namespace");
     }
     ChangeTags::modifyDisplayQuery($tables, $select, $conds, $join_conds, $query_options, $opts['tagfilter']);
     // XXX: parent class does this, should we too?
     // wfRunHooks('SpecialRecentChangesQuery', array( &$conds, &$tables, &$join_conds, $opts ) );
     if ($ns == NS_CATEGORY && !$showlinkedto) {
         // special handling for categories
         // XXX: should try to make this less klugy
         $link_tables = array('categorylinks');
         $showlinkedto = true;
     } else {
         // for now, always join on these tables; really should be configurable as in whatlinkshere
         $link_tables = array('pagelinks', 'templatelinks');
         // imagelinks only contains links to pages in NS_FILE
         if ($ns == NS_FILE || !$showlinkedto) {
             $link_tables[] = 'imagelinks';
         }
     }
     if ($id == 0 && !$showlinkedto) {
         return false;
     }
     // nonexistent pages can't link to any pages
     // field name prefixes for all the various tables we might want to join with
     $prefix = array('pagelinks' => 'pl', 'templatelinks' => 'tl', 'categorylinks' => 'cl', 'imagelinks' => 'il');
     $subsql = array();
     // SELECT statements to combine with UNION
     foreach ($link_tables as $link_table) {
         $pfx = $prefix[$link_table];
         // imagelinks and categorylinks tables have no xx_namespace field, and have xx_to instead of xx_title
         if ($link_table == 'imagelinks') {
             $link_ns = NS_FILE;
         } else {
             if ($link_table == 'categorylinks') {
                 $link_ns = NS_CATEGORY;
             } else {
                 $link_ns = 0;
             }
         }
         if ($showlinkedto) {
             // find changes to pages linking to this page
             if ($link_ns) {
                 if ($ns != $link_ns) {
                     continue;
                 }
                 // should never happen, but check anyway
                 $subconds = array("{$pfx}_to" => $dbkey);
             } else {
                 $subconds = array("{$pfx}_namespace" => $ns, "{$pfx}_title" => $dbkey);
             }
             $subjoin = "rc_cur_id = {$pfx}_from";
         } else {
             // find changes to pages linked from this page
             $subconds = array("{$pfx}_from" => $id);
             if ($link_table == 'imagelinks' || $link_table == 'categorylinks') {
                 $subconds["rc_namespace"] = $link_ns;
                 $subjoin = "rc_title = {$pfx}_to";
             } else {
                 $subjoin = "rc_namespace = {$pfx}_namespace AND rc_title = {$pfx}_title";
             }
         }
         $subsql[] = $dbr->selectSQLText(array_merge($tables, array($link_table)), $select, $conds + $subconds, __METHOD__, array('ORDER BY' => 'rc_timestamp DESC', 'LIMIT' => $limit) + $query_options, $join_conds + array($link_table => array('INNER JOIN', $subjoin)));
     }
     if (count($subsql) == 0) {
         return false;
     }
     // should never happen
     if (count($subsql) == 1) {
         $sql = $subsql[0];
     } else {
         // need to resort and relimit after union
         $sql = "(" . implode(") UNION (", $subsql) . ") ORDER BY rc_timestamp DESC LIMIT {$limit}";
     }
     $res = $dbr->query($sql, __METHOD__);
     if ($res->numRows() == 0) {
         $this->mResultEmpty = true;
     }
     return $res;
 }
 /**
  * Process the query
  *
  * @param array $conds
  * @param FormOptions $opts
  * @return bool|ResultWrapper Result or false (for Recentchangeslinked only)
  */
 public function doMainQuery($conds, $opts)
 {
     $tables = array('recentchanges');
     $join_conds = array();
     $query_options = array('USE INDEX' => array('recentchanges' => 'rc_timestamp'));
     $uid = $this->getUser()->getId();
     $dbr = wfGetDB(DB_SLAVE);
     $limit = $opts['limit'];
     $namespace = $opts['namespace'];
     $invert = $opts['invert'];
     $associated = $opts['associated'];
     $fields = RecentChange::selectFields();
     // JOIN on watchlist for users
     if ($uid) {
         $tables[] = 'watchlist';
         $fields[] = 'wl_user';
         $fields[] = 'wl_notificationtimestamp';
         $join_conds['watchlist'] = array('LEFT JOIN', array('wl_user' => $uid, 'wl_title=rc_title', 'wl_namespace=rc_namespace'));
     }
     if ($this->getUser()->isAllowed('rollback')) {
         $tables[] = 'page';
         $fields[] = 'page_latest';
         $join_conds['page'] = array('LEFT JOIN', 'rc_cur_id=page_id');
     }
     // Tag stuff.
     ChangeTags::modifyDisplayQuery($tables, $fields, $conds, $join_conds, $query_options, $opts['tagfilter']);
     if (!wfRunHooks('SpecialRecentChangesQuery', array(&$conds, &$tables, &$join_conds, $opts, &$query_options, &$fields))) {
         return false;
     }
     // Don't use the new_namespace_time timestamp index if:
     // (a) "All namespaces" selected
     // (b) We want pages in more than one namespace (inverted/associated)
     // (c) There is a tag to filter on (use tag index instead)
     // (d) UNION + sort/limit is not an option for the DBMS
     if ($namespace === '' || ($invert || $associated) || $opts['tagfilter'] != '' || !$dbr->unionSupportsOrderAndLimit()) {
         $res = $dbr->select($tables, $fields, $conds, __METHOD__, array('ORDER BY' => 'rc_timestamp DESC', 'LIMIT' => $limit) + $query_options, $join_conds);
     } else {
         // We have a new_namespace_time index! UNION over new=(0,1) and sort result set!
         // New pages
         $sqlNew = $dbr->selectSQLText($tables, $fields, array('rc_new' => 1) + $conds, __METHOD__, array('ORDER BY' => 'rc_timestamp DESC', 'LIMIT' => $limit, 'USE INDEX' => array('recentchanges' => 'new_name_timestamp')), $join_conds);
         // Old pages
         $sqlOld = $dbr->selectSQLText($tables, $fields, array('rc_new' => 0) + $conds, __METHOD__, array('ORDER BY' => 'rc_timestamp DESC', 'LIMIT' => $limit, 'USE INDEX' => array('recentchanges' => 'new_name_timestamp')), $join_conds);
         # Join the two fast queries, and sort the result set
         $sql = $dbr->unionQueries(array($sqlNew, $sqlOld), false) . ' ORDER BY rc_timestamp DESC';
         $sql = $dbr->limitResult($sql, $limit, false);
         $res = $dbr->query($sql, __METHOD__);
     }
     return $res;
 }
 /**
  * Execute
  * @param $par Parameter passed to the page
  */
 function execute($par)
 {
     global $wgRCShowWatchingUsers, $wgEnotifWatchlist, $wgShowUpdatedMarker;
     $user = $this->getUser();
     $output = $this->getOutput();
     # Anons don't get a watchlist
     if ($user->isAnon()) {
         $output->setPageTitle($this->msg('watchnologin'));
         $output->setRobotPolicy('noindex,nofollow');
         $llink = Linker::linkKnown(SpecialPage::getTitleFor('Userlogin'), $this->msg('loginreqlink')->escaped(), array(), array('returnto' => $this->getTitle()->getPrefixedText()));
         $output->addHTML($this->msg('watchlistanontext')->rawParams($llink)->parse());
         return;
     }
     // Add feed links
     $wlToken = $user->getOption('watchlisttoken');
     if (!$wlToken) {
         $wlToken = MWCryptRand::generateHex(40);
         $user->setOption('watchlisttoken', $wlToken);
         $user->saveSettings();
     }
     $this->addFeedLinks(array('action' => 'feedwatchlist', 'allrev' => 'allrev', 'wlowner' => $user->getName(), 'wltoken' => $wlToken));
     $this->setHeaders();
     $this->outputHeader();
     $output->addSubtitle($this->msg('watchlistfor2', $user->getName())->rawParams(SpecialEditWatchlist::buildTools(null)));
     $request = $this->getRequest();
     $mode = SpecialEditWatchlist::getMode($request, $par);
     if ($mode !== false) {
         # TODO: localise?
         switch ($mode) {
             case SpecialEditWatchlist::EDIT_CLEAR:
                 $mode = 'clear';
                 break;
             case SpecialEditWatchlist::EDIT_RAW:
                 $mode = 'raw';
                 break;
             default:
                 $mode = null;
         }
         $title = SpecialPage::getTitleFor('EditWatchlist', $mode);
         $output->redirect($title->getLocalUrl());
         return;
     }
     $nitems = $this->countItems();
     if ($nitems == 0) {
         $output->addWikiMsg('nowatchlist');
         return;
     }
     // @TODO: use FormOptions!
     $defaults = array('days' => floatval($user->getOption('watchlistdays')), 'hideMinor' => (int) $user->getBoolOption('watchlisthideminor'), 'hideBots' => (int) $user->getBoolOption('watchlisthidebots'), 'hideAnons' => (int) $user->getBoolOption('watchlisthideanons'), 'hideLiu' => (int) $user->getBoolOption('watchlisthideliu'), 'hidePatrolled' => (int) $user->getBoolOption('watchlisthidepatrolled'), 'hideOwn' => (int) $user->getBoolOption('watchlisthideown'), 'namespace' => 'all', 'invert' => false, 'associated' => false);
     $this->customFilters = array();
     wfRunHooks('SpecialWatchlistFilters', array($this, &$this->customFilters));
     foreach ($this->customFilters as $key => $params) {
         $defaults[$key] = $params['msg'];
     }
     # Extract variables from the request, falling back to user preferences or
     # other default values if these don't exist
     $prefs['days'] = floatval($user->getOption('watchlistdays'));
     $prefs['hideminor'] = $user->getBoolOption('watchlisthideminor');
     $prefs['hidebots'] = $user->getBoolOption('watchlisthidebots');
     $prefs['hideanons'] = $user->getBoolOption('watchlisthideanons');
     $prefs['hideliu'] = $user->getBoolOption('watchlisthideliu');
     $prefs['hideown'] = $user->getBoolOption('watchlisthideown');
     $prefs['hidepatrolled'] = $user->getBoolOption('watchlisthidepatrolled');
     # Get query variables
     $values = array();
     $values['days'] = $request->getVal('days', $prefs['days']);
     $values['hideMinor'] = (int) $request->getBool('hideMinor', $prefs['hideminor']);
     $values['hideBots'] = (int) $request->getBool('hideBots', $prefs['hidebots']);
     $values['hideAnons'] = (int) $request->getBool('hideAnons', $prefs['hideanons']);
     $values['hideLiu'] = (int) $request->getBool('hideLiu', $prefs['hideliu']);
     $values['hideOwn'] = (int) $request->getBool('hideOwn', $prefs['hideown']);
     $values['hidePatrolled'] = (int) $request->getBool('hidePatrolled', $prefs['hidepatrolled']);
     foreach ($this->customFilters as $key => $params) {
         $values[$key] = (int) $request->getBool($key);
     }
     # Get namespace value, if supplied, and prepare a WHERE fragment
     $nameSpace = $request->getIntOrNull('namespace');
     $invert = $request->getBool('invert');
     $associated = $request->getBool('associated');
     if (!is_null($nameSpace)) {
         $eq_op = $invert ? '!=' : '=';
         $bool_op = $invert ? 'AND' : 'OR';
         $nameSpace = intval($nameSpace);
         // paranioa
         if (!$associated) {
             $nameSpaceClause = "rc_namespace {$eq_op} {$nameSpace}";
         } else {
             $associatedNS = MWNamespace::getAssociated($nameSpace);
             $nameSpaceClause = "rc_namespace {$eq_op} {$nameSpace} " . $bool_op . " rc_namespace {$eq_op} {$associatedNS}";
         }
     } else {
         $nameSpace = '';
         $nameSpaceClause = '';
     }
     $values['namespace'] = $nameSpace;
     $values['invert'] = $invert;
     $values['associated'] = $associated;
     if (is_null($values['days']) || !is_numeric($values['days'])) {
         $big = 1000;
         /* The magical big */
         if ($nitems > $big) {
             # Set default cutoff shorter
             $values['days'] = $defaults['days'] = 12.0 / 24.0;
             # 12 hours...
         } else {
             $values['days'] = $defaults['days'];
             # default cutoff for shortlisters
         }
     } else {
         $values['days'] = floatval($values['days']);
     }
     // Dump everything here
     $nondefaults = array();
     foreach ($defaults as $name => $defValue) {
         wfAppendToArrayIfNotDefault($name, $values[$name], $defaults, $nondefaults);
     }
     if (($wgEnotifWatchlist || $wgShowUpdatedMarker) && $request->getVal('reset') && $request->wasPosted()) {
         $user->clearAllNotifications();
         $output->redirect($this->getTitle()->getFullUrl($nondefaults));
         return;
     }
     $dbr = wfGetDB(DB_SLAVE, 'watchlist');
     # Possible where conditions
     $conds = array();
     if ($values['days'] > 0) {
         $conds[] = "rc_timestamp > '" . $dbr->timestamp(time() - intval($values['days'] * 86400)) . "'";
     }
     # If the watchlist is relatively short, it's simplest to zip
     # down its entirety and then sort the results.
     # If it's relatively long, it may be worth our while to zip
     # through the time-sorted page list checking for watched items.
     # Up estimate of watched items by 15% to compensate for talk pages...
     # Toggles
     if ($values['hideOwn']) {
         $conds[] = 'rc_user != ' . $user->getId();
     }
     if ($values['hideBots']) {
         $conds[] = 'rc_bot = 0';
     }
     if ($values['hideMinor']) {
         $conds[] = 'rc_minor = 0';
     }
     if ($values['hideLiu']) {
         $conds[] = 'rc_user = 0';
     }
     if ($values['hideAnons']) {
         $conds[] = 'rc_user != 0';
     }
     if ($user->useRCPatrol() && $values['hidePatrolled']) {
         $conds[] = 'rc_patrolled != 1';
     }
     if ($nameSpaceClause) {
         $conds[] = $nameSpaceClause;
     }
     # Toggle watchlist content (all recent edits or just the latest)
     if ($user->getOption('extendwatchlist')) {
         $limitWatchlist = intval($user->getOption('wllimit'));
         $usePage = false;
     } else {
         # Top log Ids for a page are not stored
         $conds[] = 'rc_this_oldid=page_latest OR rc_type=' . RC_LOG;
         $limitWatchlist = 0;
         $usePage = true;
     }
     # Show a message about slave lag, if applicable
     $lag = wfGetLB()->safeGetLag($dbr);
     if ($lag > 0) {
         $output->showLagWarning($lag);
     }
     # Create output form
     $form = Xml::fieldset($this->msg('watchlist-options')->text(), false, array('id' => 'mw-watchlist-options'));
     # Show watchlist header
     $form .= $this->msg('watchlist-details')->numParams($nitems)->parse();
     if ($user->getOption('enotifwatchlistpages') && $wgEnotifWatchlist) {
         $form .= $this->msg('wlheader-enotif')->parseAsBlock() . "\n";
     }
     if ($wgShowUpdatedMarker) {
         $form .= Xml::openElement('form', array('method' => 'post', 'action' => $this->getTitle()->getLocalUrl(), 'id' => 'mw-watchlist-resetbutton')) . $this->msg('wlheader-showupdated')->parse() . ' ' . Xml::submitButton($this->msg('enotif_reset')->text(), array('name' => 'dummy')) . Html::hidden('reset', 'all');
         foreach ($nondefaults as $key => $value) {
             $form .= Html::hidden($key, $value);
         }
         $form .= Xml::closeElement('form');
     }
     $form .= '<hr />';
     $tables = array('recentchanges', 'watchlist');
     $fields = RecentChange::selectFields();
     $join_conds = array('watchlist' => array('INNER JOIN', array('wl_user' => $user->getId(), 'wl_namespace=rc_namespace', 'wl_title=rc_title')));
     $options = array('ORDER BY' => 'rc_timestamp DESC');
     if ($wgShowUpdatedMarker) {
         $fields[] = 'wl_notificationtimestamp';
     }
     if ($limitWatchlist) {
         $options['LIMIT'] = $limitWatchlist;
     }
     $rollbacker = $user->isAllowed('rollback');
     if ($usePage || $rollbacker) {
         $tables[] = 'page';
         $join_conds['page'] = array('LEFT JOIN', 'rc_cur_id=page_id');
         if ($rollbacker) {
             $fields[] = 'page_latest';
         }
     }
     ChangeTags::modifyDisplayQuery($tables, $fields, $conds, $join_conds, $options, '');
     wfRunHooks('SpecialWatchlistQuery', array(&$conds, &$tables, &$join_conds, &$fields));
     $res = $dbr->select($tables, $fields, $conds, __METHOD__, $options, $join_conds);
     $numRows = $res->numRows();
     /* Start bottom header */
     $lang = $this->getLanguage();
     $wlInfo = '';
     if ($values['days'] > 0) {
         $timestamp = wfTimestampNow();
         $wlInfo = $this->msg('wlnote')->numParams($numRows, round($values['days'] * 24))->params($lang->userDate($timestamp, $user), $lang->userTime($timestamp, $user))->parse() . '<br />';
     }
     $cutofflinks = "\n" . $this->cutoffLinks($values['days'], $nondefaults) . "<br />\n";
     # Spit out some control panel links
     $filters = array('hideMinor' => 'rcshowhideminor', 'hideBots' => 'rcshowhidebots', 'hideAnons' => 'rcshowhideanons', 'hideLiu' => 'rcshowhideliu', 'hideOwn' => 'rcshowhidemine', 'hidePatrolled' => 'rcshowhidepatr');
     foreach ($this->customFilters as $key => $params) {
         $filters[$key] = $params['msg'];
     }
     // Disable some if needed
     if (!$user->useNPPatrol()) {
         unset($filters['hidePatrolled']);
     }
     $links = array();
     foreach ($filters as $name => $msg) {
         $links[] = $this->showHideLink($nondefaults, $msg, $name, $values[$name]);
     }
     # Namespace filter and put the whole form together.
     $form .= $wlInfo;
     $form .= $cutofflinks;
     $form .= $lang->pipeList($links);
     $form .= Xml::openElement('form', array('method' => 'post', 'action' => $this->getTitle()->getLocalUrl(), 'id' => 'mw-watchlist-form-namespaceselector'));
     $form .= '<hr /><p>';
     $form .= Html::namespaceSelector(array('selected' => $nameSpace, 'all' => '', 'label' => $this->msg('namespace')->text()), array('name' => 'namespace', 'id' => 'namespace', 'class' => 'namespaceselector')) . '&#160;';
     $form .= Xml::checkLabel($this->msg('invert')->text(), 'invert', 'nsinvert', $invert, array('title' => $this->msg('tooltip-invert')->text())) . '&#160;';
     $form .= Xml::checkLabel($this->msg('namespace_association')->text(), 'associated', 'associated', $associated, array('title' => $this->msg('tooltip-namespace_association')->text())) . '&#160;';
     $form .= Xml::submitButton($this->msg('allpagessubmit')->text()) . '</p>';
     $form .= Html::hidden('days', $values['days']);
     foreach ($filters as $key => $msg) {
         if ($values[$key]) {
             $form .= Html::hidden($key, 1);
         }
     }
     $form .= Xml::closeElement('form');
     $form .= Xml::closeElement('fieldset');
     $output->addHTML($form);
     # If there's nothing to show, stop here
     if ($numRows == 0) {
         $output->addWikiMsg('watchnochange');
         return;
     }
     /* End bottom header */
     /* Do link batch query */
     $linkBatch = new LinkBatch();
     foreach ($res as $row) {
         $userNameUnderscored = str_replace(' ', '_', $row->rc_user_text);
         if ($row->rc_user != 0) {
             $linkBatch->add(NS_USER, $userNameUnderscored);
         }
         $linkBatch->add(NS_USER_TALK, $userNameUnderscored);
         $linkBatch->add($row->rc_namespace, $row->rc_title);
     }
     $linkBatch->execute();
     $dbr->dataSeek($res, 0);
     $list = ChangesList::newFromContext($this->getContext());
     $list->setWatchlistDivs();
     $s = $list->beginRecentChangesList();
     $counter = 1;
     foreach ($res as $obj) {
         # Make RC entry
         $rc = RecentChange::newFromRow($obj);
         $rc->counter = $counter++;
         if ($wgShowUpdatedMarker) {
             $updated = $obj->wl_notificationtimestamp;
         } else {
             $updated = false;
         }
         if ($wgRCShowWatchingUsers && $user->getOption('shownumberswatching')) {
             $rc->numberofWatchingusers = $dbr->selectField('watchlist', 'COUNT(*)', array('wl_namespace' => $obj->rc_namespace, 'wl_title' => $obj->rc_title), __METHOD__);
         } else {
             $rc->numberofWatchingusers = 0;
         }
         $s .= $list->recentChangesLine($rc, $updated, $counter);
     }
     $s .= $list->endRecentChangesList();
     $output->addHTML($s);
 }
 function getQueryInfo()
 {
     list($tables, $index, $userCond, $join_cond) = $this->getUserCond();
     $user = $this->getUser();
     $conds = array_merge($userCond, $this->getNamespaceCond());
     // Paranoia: avoid brute force searches (bug 17342)
     if (!$user->isAllowed('deletedhistory')) {
         $conds[] = $this->mDb->bitAnd('rev_deleted', Revision::DELETED_USER) . ' = 0';
     } elseif (!$user->isAllowed('suppressrevision')) {
         $conds[] = $this->mDb->bitAnd('rev_deleted', Revision::SUPPRESSED_USER) . ' != ' . Revision::SUPPRESSED_USER;
     }
     # Don't include orphaned revisions
     $join_cond['page'] = Revision::pageJoinCond();
     # Get the current user name for accounts
     $join_cond['user'] = Revision::userJoinCond();
     $queryInfo = array('tables' => $tables, 'fields' => array_merge(Revision::selectFields(), Revision::selectUserFields(), array('page_namespace', 'page_title', 'page_is_new', 'page_latest', 'page_is_redirect', 'page_len')), 'conds' => $conds, 'options' => array('USE INDEX' => array('revision' => $index)), 'join_conds' => $join_cond);
     ChangeTags::modifyDisplayQuery($queryInfo['tables'], $queryInfo['fields'], $queryInfo['conds'], $queryInfo['join_conds'], $queryInfo['options'], $this->tagFilter);
     wfRunHooks('ContribsPager::getQueryInfo', array(&$this, &$queryInfo));
     return $queryInfo;
 }
Example #22
0
 /**
  * Process the query
  *
  * @param $conds array
  * @param $opts FormOptions
  * @return database result or false (for Recentchangeslinked only)
  */
 public function doMainQuery($conds, $opts)
 {
     global $wgUser;
     $tables = array('recentchanges');
     $join_conds = array();
     $query_options = array('USE INDEX' => array('recentchanges' => 'rc_timestamp'));
     $uid = $wgUser->getId();
     $dbr = wfGetDB(DB_SLAVE);
     $limit = $opts['limit'];
     $namespace = $opts['namespace'];
     $invert = $opts['invert'];
     // JOIN on watchlist for users
     if ($uid) {
         $tables[] = 'watchlist';
         $join_conds['watchlist'] = array('LEFT JOIN', "wl_user={$uid} AND wl_title=rc_title AND wl_namespace=rc_namespace");
     }
     if ($wgUser->isAllowed("rollback")) {
         $tables[] = 'page';
         $join_conds['page'] = array('LEFT JOIN', 'rc_cur_id=page_id');
     }
     // Tag stuff.
     $fields = array();
     // Fields are * in this case, so let the function modify an empty array to keep it happy.
     ChangeTags::modifyDisplayQuery($tables, $fields, $conds, $join_conds, $query_options, $opts['tagfilter']);
     if (!wfRunHooks('SpecialRecentChangesQuery', array(&$conds, &$tables, &$join_conds, $opts, &$query_options))) {
         return false;
     }
     // Don't use the new_namespace_time timestamp index if:
     // (a) "All namespaces" selected
     // (b) We want all pages NOT in a certain namespaces (inverted)
     // (c) There is a tag to filter on (use tag index instead)
     // (d) UNION + sort/limit is not an option for the DBMS
     if (is_null($namespace) || $invert || $opts['tagfilter'] != '' || !$dbr->unionSupportsOrderAndLimit()) {
         $res = $dbr->select($tables, '*', $conds, __METHOD__, array('ORDER BY' => 'rc_timestamp DESC', 'LIMIT' => $limit) + $query_options, $join_conds);
         // We have a new_namespace_time index! UNION over new=(0,1) and sort result set!
     } else {
         // New pages
         $sqlNew = $dbr->selectSQLText($tables, '*', array('rc_new' => 1) + $conds, __METHOD__, array('ORDER BY' => 'rc_timestamp DESC', 'LIMIT' => $limit, 'USE INDEX' => array('recentchanges' => 'rc_timestamp')), $join_conds);
         // Old pages
         $sqlOld = $dbr->selectSQLText($tables, '*', array('rc_new' => 0) + $conds, __METHOD__, array('ORDER BY' => 'rc_timestamp DESC', 'LIMIT' => $limit, 'USE INDEX' => array('recentchanges' => 'rc_timestamp')), $join_conds);
         # Join the two fast queries, and sort the result set
         $sql = $dbr->unionQueries(array($sqlNew, $sqlOld), false) . ' ORDER BY rc_timestamp DESC';
         $sql = $dbr->limitResult($sql, $limit, false);
         $res = $dbr->query($sql, __METHOD__);
     }
     return $res;
 }
 /**
  * Get watchlist items for feed view
  * @return ResultWrapper
  *
  * @see getNSConditions()
  * @see doPageImages()
  */
 protected function doFeedQuery()
 {
     $user = $this->getUser();
     $dbr = wfGetDB(DB_SLAVE, 'watchlist');
     # Possible where conditions
     $conds = $this->getNSConditions('rc_namespace');
     // snip....
     $tables = array('recentchanges', 'watchlist');
     $fields = array($dbr->tableName('recentchanges') . '.*');
     $join_conds = array('watchlist' => array('INNER JOIN', array('wl_user' => $user->getId(), 'wl_namespace=rc_namespace', 'wl_title=rc_title', 'rc_type!=' . RC_EXTERNAL)));
     $options = array('ORDER BY' => 'rc_timestamp DESC');
     $options['LIMIT'] = self::LIMIT;
     $rollbacker = $user->isAllowed('rollback');
     if ($rollbacker) {
         $tables[] = 'page';
         $join_conds['page'] = array('LEFT JOIN', 'rc_cur_id=page_id');
         if ($rollbacker) {
             $fields[] = 'page_latest';
         }
     }
     ChangeTags::modifyDisplayQuery($tables, $fields, $conds, $join_conds, $options, '');
     // Until 1.22, MediaWiki used an array here. Since 1.23 (Iec4aab87), it uses a FormOptions
     // object (which implements array-like interface ArrayAccess).
     // Let's keep using an array and hope any new extensions are compatible with both styles...
     $values = array();
     Hooks::run('SpecialWatchlistQuery', array(&$conds, &$tables, &$join_conds, &$fields, &$values));
     $res = $dbr->select($tables, $fields, $conds, __METHOD__, $options, $join_conds);
     return $res;
 }
Example #24
0
 function getQueryInfo()
 {
     $queryInfo = array('tables' => array('revision'), 'fields' => Revision::selectFields(), 'conds' => array_merge(array('rev_page' => $this->historyPage->getTitle()->getArticleID()), $this->conds), 'options' => array('USE INDEX' => array('revision' => 'page_timestamp')), 'join_conds' => array('tag_summary' => array('LEFT JOIN', 'ts_rev_id=rev_id')));
     ChangeTags::modifyDisplayQuery($queryInfo['tables'], $queryInfo['fields'], $queryInfo['conds'], $queryInfo['join_conds'], $queryInfo['options'], $this->tagFilter);
     wfRunHooks('PageHistoryPager::getQueryInfo', array(&$this, &$queryInfo));
     return $queryInfo;
 }
 /**
  * List the revisions of the given page. Returns result wrapper with
  * (ar_minor_edit, ar_timestamp, ar_user, ar_user_text, ar_comment) fields.
  *
  * @return ResultWrapper
  */
 function listRevisions()
 {
     $dbr = wfGetDB(DB_SLAVE);
     $tables = array('archive');
     $fields = array('ar_minor_edit', 'ar_timestamp', 'ar_user', 'ar_user_text', 'ar_comment', 'ar_len', 'ar_deleted', 'ar_rev_id', 'ar_sha1');
     if ($this->config->get('ContentHandlerUseDB')) {
         $fields[] = 'ar_content_format';
         $fields[] = 'ar_content_model';
     }
     $conds = array('ar_namespace' => $this->title->getNamespace(), 'ar_title' => $this->title->getDBkey());
     $options = array('ORDER BY' => 'ar_timestamp DESC');
     $join_conds = array();
     ChangeTags::modifyDisplayQuery($tables, $fields, $conds, $join_conds, $options, '');
     return $dbr->select($tables, $fields, $conds, __METHOD__, $options, $join_conds);
 }
Example #26
0
 function getQueryInfo()
 {
     global $wgUser;
     list($tables, $index, $userCond, $join_cond) = $this->getUserCond();
     $conds = array_merge($userCond, $this->getNamespaceCond());
     // Paranoia: avoid brute force searches (bug 17342)
     if (!$wgUser->isAllowed('deletedhistory')) {
         $conds[] = $this->mDb->bitAnd('rev_deleted', Revision::DELETED_USER) . ' = 0';
     } else {
         if (!$wgUser->isAllowed('suppressrevision')) {
             $conds[] = $this->mDb->bitAnd('rev_deleted', Revision::SUPPRESSED_USER) . ' != ' . Revision::SUPPRESSED_USER;
         }
     }
     $join_cond['page'] = array('INNER JOIN', 'page_id=rev_page');
     $queryInfo = array('tables' => $tables, 'fields' => array('page_namespace', 'page_title', 'page_is_new', 'page_latest', 'page_is_redirect', 'page_len', 'rev_id', 'rev_page', 'rev_text_id', 'rev_timestamp', 'rev_comment', 'rev_minor_edit', 'rev_user', 'rev_user_text', 'rev_parent_id', 'rev_deleted'), 'conds' => $conds, 'options' => array('USE INDEX' => array('revision' => $index)), 'join_conds' => $join_cond);
     ChangeTags::modifyDisplayQuery($queryInfo['tables'], $queryInfo['fields'], $queryInfo['conds'], $queryInfo['join_conds'], $queryInfo['options'], $this->tagFilter);
     wfRunHooks('ContribsPager::getQueryInfo', array(&$this, &$queryInfo));
     return $queryInfo;
 }
 /**
  * Process the query
  *
  * @param array $conds
  * @param FormOptions $opts
  * @return bool|ResultWrapper Result or false
  */
 public function doMainQuery($conds, $opts)
 {
     $tables = ['recentchanges'];
     $fields = RecentChange::selectFields();
     $query_options = [];
     $join_conds = [];
     ChangeTags::modifyDisplayQuery($tables, $fields, $conds, $join_conds, $query_options, '');
     if (!$this->runMainQueryHook($tables, $fields, $conds, $query_options, $join_conds, $opts)) {
         return false;
     }
     $dbr = $this->getDB();
     return $dbr->select($tables, $fields, $conds, __METHOD__, $query_options, $join_conds);
 }
Example #28
0
	/**
	 * Execute
	 * @param $par Parameter passed to the page
	 */
	function execute( $par ) {
		global $wgRCShowWatchingUsers, $wgEnotifWatchlist, $wgShowUpdatedMarker;

		$user = $this->getUser();
		$output = $this->getOutput();

		# Anons don't get a watchlist
		if ( $user->isAnon() ) {
			$output->setPageTitle( $this->msg( 'watchnologin' ) );
			$output->setRobotPolicy( 'noindex,nofollow' );
			$llink = Linker::linkKnown(
				SpecialPage::getTitleFor( 'Userlogin' ),
				$this->msg( 'loginreqlink' )->escaped(),
				array(),
				array( 'returnto' => $this->getTitle()->getPrefixedText() )
			);
			$output->addHTML( $this->msg( 'watchlistanontext' )->rawParams( $llink )->parse() );
			return;
		}

		// Check permissions
		$this->checkPermissions();

		// Add feed links
		$wlToken = $user->getTokenFromOption( 'watchlisttoken' );
		if ( $wlToken ) {
			$this->addFeedLinks( array( 'action' => 'feedwatchlist', 'allrev' => 'allrev',
								'wlowner' => $user->getName(), 'wltoken' => $wlToken ) );
		}

		$this->setHeaders();
		$this->outputHeader();

		$output->addSubtitle( $this->msg( 'watchlistfor2', $user->getName()
			)->rawParams( SpecialEditWatchlist::buildTools( null ) ) );

		$request = $this->getRequest();

		$mode = SpecialEditWatchlist::getMode( $request, $par );
		if ( $mode !== false ) {
			# TODO: localise?
			switch ( $mode ) {
				case SpecialEditWatchlist::EDIT_CLEAR:
					$mode = 'clear';
					break;
				case SpecialEditWatchlist::EDIT_RAW:
					$mode = 'raw';
					break;
				default:
					$mode = null;
			}
			$title = SpecialPage::getTitleFor( 'EditWatchlist', $mode );
			$output->redirect( $title->getLocalURL() );
			return;
		}

		$dbr = wfGetDB( DB_SLAVE, 'watchlist' );

		$nitems = $this->countItems( $dbr );
		if ( $nitems == 0 ) {
			$output->addWikiMsg( 'nowatchlist' );
			return;
		}

		// @todo use FormOptions!
		$defaults = array(
		/* float */ 'days' => floatval( $user->getOption( 'watchlistdays' ) ),
		/* bool  */ 'hideMinor' => (int)$user->getBoolOption( 'watchlisthideminor' ),
		/* bool  */ 'hideBots' => (int)$user->getBoolOption( 'watchlisthidebots' ),
		/* bool  */ 'hideAnons' => (int)$user->getBoolOption( 'watchlisthideanons' ),
		/* bool  */ 'hideLiu' => (int)$user->getBoolOption( 'watchlisthideliu' ),
		/* bool  */ 'hidePatrolled' => (int)$user->getBoolOption( 'watchlisthidepatrolled' ),
		/* bool  */ 'hideOwn' => (int)$user->getBoolOption( 'watchlisthideown' ),
		/* bool  */ 'extended' => (int)$user->getBoolOption( 'extendwatchlist' ),
		/* ?     */ 'namespace' => '', //means all
		/* ?     */ 'invert' => false,
		/* bool  */ 'associated' => false,
		);
		$this->customFilters = array();
		wfRunHooks( 'SpecialWatchlistFilters', array( $this, &$this->customFilters ) );
		foreach ( $this->customFilters as $key => $params ) {
			$defaults[$key] = $params['default'];
		}

		# Extract variables from the request, falling back to user preferences or
		# other default values if these don't exist
		$values = array();
		$values['days'] = floatval( $request->getVal( 'days', $defaults['days'] ) );
		$values['hideMinor'] = (int)$request->getBool( 'hideMinor', $defaults['hideMinor'] );
		$values['hideBots'] = (int)$request->getBool( 'hideBots', $defaults['hideBots'] );
		$values['hideAnons'] = (int)$request->getBool( 'hideAnons', $defaults['hideAnons'] );
		$values['hideLiu'] = (int)$request->getBool( 'hideLiu', $defaults['hideLiu'] );
		$values['hideOwn'] = (int)$request->getBool( 'hideOwn', $defaults['hideOwn'] );
		$values['hidePatrolled'] = (int)$request->getBool( 'hidePatrolled', $defaults['hidePatrolled'] );
		$values['extended'] = (int)$request->getBool( 'extended', $defaults['extended'] );
		foreach ( $this->customFilters as $key => $params ) {
			$values[$key] = (int)$request->getBool( $key, $defaults[$key] );
		}

		# Get namespace value, if supplied, and prepare a WHERE fragment
		$nameSpace = $request->getIntOrNull( 'namespace' );
		$invert = $request->getBool( 'invert' );
		$associated = $request->getBool( 'associated' );
		if ( !is_null( $nameSpace ) ) {
			$eq_op = $invert ? '!=' : '=';
			$bool_op = $invert ? 'AND' : 'OR';
			$nameSpace = intval( $nameSpace ); // paranioa
			if ( !$associated ) {
				$nameSpaceClause = "rc_namespace $eq_op $nameSpace";
			} else {
				$associatedNS = MWNamespace::getAssociated( $nameSpace );
				$nameSpaceClause =
					"rc_namespace $eq_op $nameSpace " .
					$bool_op .
					" rc_namespace $eq_op $associatedNS";
			}
		} else {
			$nameSpace = '';
			$nameSpaceClause = '';
		}
		$values['namespace'] = $nameSpace;
		$values['invert'] = $invert;
		$values['associated'] = $associated;

		// Dump everything here
		$nondefaults = array();
		foreach ( $defaults as $name => $defValue ) {
			wfAppendToArrayIfNotDefault( $name, $values[$name], $defaults, $nondefaults );
		}

		if ( ( $wgEnotifWatchlist || $wgShowUpdatedMarker ) && $request->getVal( 'reset' ) &&
			$request->wasPosted() )
		{
			$user->clearAllNotifications();
			$output->redirect( $this->getTitle()->getFullURL( $nondefaults ) );
			return;
		}

		# Possible where conditions
		$conds = array();

		if ( $values['days'] > 0 ) {
			$conds[] = 'rc_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( time() - intval( $values['days'] * 86400 ) ) );
		}

		# Toggles
		if ( $values['hideOwn'] ) {
			$conds[] = 'rc_user != ' . $user->getId();
		}
		if ( $values['hideBots'] ) {
			$conds[] = 'rc_bot = 0';
		}
		if ( $values['hideMinor'] ) {
			$conds[] = 'rc_minor = 0';
		}
		if ( $values['hideLiu'] ) {
			$conds[] = 'rc_user = 0';
		}
		if ( $values['hideAnons'] ) {
			$conds[] = 'rc_user != 0';
		}
		if ( $user->useRCPatrol() && $values['hidePatrolled'] ) {
			$conds[] = 'rc_patrolled != 1';
		}
		if ( $nameSpaceClause ) {
			$conds[] = $nameSpaceClause;
		}

		# Toggle watchlist content (all recent edits or just the latest)
		if ( $values['extended'] ) {
			$limitWatchlist = $user->getIntOption( 'wllimit' );
			$usePage = false;
		} else {
			# Top log Ids for a page are not stored
			$nonRevisionTypes = array( RC_LOG );
			wfRunHooks( 'SpecialWatchlistGetNonRevisionTypes', array( &$nonRevisionTypes ) );
			if ( $nonRevisionTypes ) {
				if ( count( $nonRevisionTypes ) === 1 ) {
					// if only one use an equality instead of IN condition
					$nonRevisionTypes = reset( $nonRevisionTypes );
				}
				$conds[] = $dbr->makeList(
					array(
						'rc_this_oldid=page_latest',
						'rc_type' => $nonRevisionTypes,
					),
					LIST_OR
				);
			}
			$limitWatchlist = 0;
			$usePage = true;
		}

		# Show a message about slave lag, if applicable
		$lag = wfGetLB()->safeGetLag( $dbr );
		if ( $lag > 0 ) {
			$output->showLagWarning( $lag );
		}

		# Create output
		$form = '';

		# Show watchlist header
		$form .= "<p>";
		$form .= $this->msg( 'watchlist-details' )->numParams( $nitems )->parse() . "\n";
		if ( $wgEnotifWatchlist && $user->getOption( 'enotifwatchlistpages' ) ) {
			$form .= $this->msg( 'wlheader-enotif' )->parse() . "\n";
		}
		if ( $wgShowUpdatedMarker ) {
			$form .= $this->msg( 'wlheader-showupdated' )->parse() . "\n";
		}
		$form .= "</p>";

		if ( $wgShowUpdatedMarker ) {
			$form .= Xml::openElement( 'form', array( 'method' => 'post',
				'action' => $this->getTitle()->getLocalURL(),
				'id' => 'mw-watchlist-resetbutton' ) ) . "\n" .
			Xml::submitButton( $this->msg( 'enotif_reset' )->text(), array( 'name' => 'dummy' ) ) . "\n" .
			Html::hidden( 'reset', 'all' ) . "\n";
			foreach ( $nondefaults as $key => $value ) {
				$form .= Html::hidden( $key, $value ) . "\n";
			}
			$form .= Xml::closeElement( 'form' ) . "\n";
		}

		$form .= Xml::openElement( 'form', array(
			'method' => 'post',
			'action' => $this->getTitle()->getLocalURL(),
			'id' => 'mw-watchlist-form'
		) );
		$form .= Xml::fieldset(
			$this->msg( 'watchlist-options' )->text(),
			false,
			array( 'id' => 'mw-watchlist-options' )
		);

		$tables = array( 'recentchanges', 'watchlist' );
		$fields = RecentChange::selectFields();
		$join_conds = array(
			'watchlist' => array(
				'INNER JOIN',
				array(
					'wl_user' => $user->getId(),
					'wl_namespace=rc_namespace',
					'wl_title=rc_title'
				),
			),
		);
		$options = array( 'ORDER BY' => 'rc_timestamp DESC' );
		if ( $wgShowUpdatedMarker ) {
			$fields[] = 'wl_notificationtimestamp';
		}
		if ( $limitWatchlist ) {
			$options['LIMIT'] = $limitWatchlist;
		}

		$rollbacker = $user->isAllowed( 'rollback' );
		if ( $usePage || $rollbacker ) {
			$tables[] = 'page';
			$join_conds['page'] = array( 'LEFT JOIN', 'rc_cur_id=page_id' );
			if ( $rollbacker ) {
				$fields[] = 'page_latest';
			}
		}

		// Log entries with DELETED_ACTION must not show up unless the user has
		// the necessary rights.
		if ( !$user->isAllowed( 'deletedhistory' ) ) {
			$bitmask = LogPage::DELETED_ACTION;
		} elseif ( !$user->isAllowed( 'suppressrevision' ) ) {
			$bitmask = LogPage::DELETED_ACTION | LogPage::DELETED_RESTRICTED;
		} else {
			$bitmask = 0;
		}
		if ( $bitmask ) {
			$conds[] = $dbr->makeList( array(
				'rc_type != ' . RC_LOG,
				$dbr->bitAnd( 'rc_deleted', $bitmask ) . " != $bitmask",
			), LIST_OR );
		}

		ChangeTags::modifyDisplayQuery( $tables, $fields, $conds, $join_conds, $options, '' );
		wfRunHooks( 'SpecialWatchlistQuery', array( &$conds, &$tables, &$join_conds, &$fields, $values ) );

		$res = $dbr->select( $tables, $fields, $conds, __METHOD__, $options, $join_conds );
		$numRows = $res->numRows();

		/* Start bottom header */

		$lang = $this->getLanguage();
		$wlInfo = '';
		if ( $values['days'] > 0 ) {
			$timestamp = wfTimestampNow();
			$wlInfo = $this->msg( 'wlnote' )->numParams( $numRows, round( $values['days'] * 24 ) )->params(
				$lang->userDate( $timestamp, $user ), $lang->userTime( $timestamp, $user ) )->parse() . "<br />\n";
		}

		$cutofflinks = $this->cutoffLinks( $values['days'], $nondefaults ) . "<br />\n";

		# Spit out some control panel links
		$filters = array(
			'hideMinor' => 'rcshowhideminor',
			'hideBots' => 'rcshowhidebots',
			'hideAnons' => 'rcshowhideanons',
			'hideLiu' => 'rcshowhideliu',
			'hideOwn' => 'rcshowhidemine',
			'hidePatrolled' => 'rcshowhidepatr'
		);
		foreach ( $this->customFilters as $key => $params ) {
			$filters[$key] = $params['msg'];
		}
		// Disable some if needed
		if ( !$user->useNPPatrol() ) {
			unset( $filters['hidePatrolled'] );
		}

		$links = array();
		foreach ( $filters as $name => $msg ) {
			$links[] = $this->showHideLink( $nondefaults, $msg, $name, $values[$name] );
		}

		$hiddenFields = $nondefaults;
		unset( $hiddenFields['namespace'] );
		unset( $hiddenFields['invert'] );
		unset( $hiddenFields['associated'] );

		# Namespace filter and put the whole form together.
		$form .= $wlInfo;
		$form .= $cutofflinks;
		$form .= $lang->pipeList( $links ) . "\n";
		$form .= "<hr />\n<p>";
		$form .= Html::namespaceSelector(
			array(
				'selected' => $nameSpace,
				'all' => '',
				'label' => $this->msg( 'namespace' )->text()
			), array(
				'name' => 'namespace',
				'id' => 'namespace',
				'class' => 'namespaceselector',
			)
		) . '&#160;';
		$form .= Xml::checkLabel(
			$this->msg( 'invert' )->text(),
			'invert',
			'nsinvert',
			$invert,
			array( 'title' => $this->msg( 'tooltip-invert' )->text() )
		) . '&#160;';
		$form .= Xml::checkLabel(
			$this->msg( 'namespace_association' )->text(),
			'associated',
			'associated',
			$associated,
			array( 'title' => $this->msg( 'tooltip-namespace_association' )->text() )
		) . '&#160;';
		$form .= Xml::submitButton( $this->msg( 'allpagessubmit' )->text() ) . "</p>\n";
		foreach ( $hiddenFields as $key => $value ) {
			$form .= Html::hidden( $key, $value ) . "\n";
		}
		$form .= Xml::closeElement( 'fieldset' ) . "\n";
		$form .= Xml::closeElement( 'form' ) . "\n";
		$output->addHTML( $form );

		# If there's nothing to show, stop here
		if ( $numRows == 0 ) {
			$output->wrapWikiMsg(
				"<div class='mw-changeslist-empty'>\n$1\n</div>", 'recentchanges-noresult'
			);
			return;
		}

		/* End bottom header */

		/* Do link batch query */
		$linkBatch = new LinkBatch;
		foreach ( $res as $row ) {
			$userNameUnderscored = str_replace( ' ', '_', $row->rc_user_text );
			if ( $row->rc_user != 0 ) {
				$linkBatch->add( NS_USER, $userNameUnderscored );
			}
			$linkBatch->add( NS_USER_TALK, $userNameUnderscored );

			$linkBatch->add( $row->rc_namespace, $row->rc_title );
		}
		$linkBatch->execute();
		$dbr->dataSeek( $res, 0 );

		$list = ChangesList::newFromContext( $this->getContext() );
		$list->setWatchlistDivs();

		$s = $list->beginRecentChangesList();
		$counter = 1;
		foreach ( $res as $obj ) {
			# Make RC entry
			$rc = RecentChange::newFromRow( $obj );
			$rc->counter = $counter++;

			if ( $wgShowUpdatedMarker ) {
				$updated = $obj->wl_notificationtimestamp;
			} else {
				$updated = false;
			}

			if ( $wgRCShowWatchingUsers && $user->getOption( 'shownumberswatching' ) ) {
				$rc->numberofWatchingusers = $dbr->selectField( 'watchlist',
					'COUNT(*)',
					array(
						'wl_namespace' => $obj->rc_namespace,
						'wl_title' => $obj->rc_title,
					),
					__METHOD__ );
			} else {
				$rc->numberofWatchingusers = 0;
			}

			$changeLine = $list->recentChangesLine( $rc, $updated, $counter );
			if ( $changeLine !== false ) {
				$s .= $changeLine;
			}
		}
		$s .= $list->endRecentChangesList();

		$output->addHTML( $s );
	}
 /**
  * Constructs the most part of the query. Extra conditions are sprinkled in
  * all over this class.
  * @return array
  */
 public function getQueryInfo()
 {
     $basic = DatabaseLogEntry::getSelectQueryData();
     $tables = $basic['tables'];
     $fields = $basic['fields'];
     $conds = $basic['conds'];
     $options = $basic['options'];
     $joins = $basic['join_conds'];
     $index = array();
     # Add log_search table if there are conditions on it.
     # This filters the results to only include log rows that have
     # log_search records with the specified ls_field and ls_value values.
     if (array_key_exists('ls_field', $this->mConds)) {
         $tables[] = 'log_search';
         $index['log_search'] = 'ls_field_val';
         $index['logging'] = 'PRIMARY';
         if (!$this->hasEqualsClause('ls_field') || !$this->hasEqualsClause('ls_value')) {
             # Since (ls_field,ls_value,ls_logid) is unique, if the condition is
             # to match a specific (ls_field,ls_value) tuple, then there will be
             # no duplicate log rows. Otherwise, we need to remove the duplicates.
             $options[] = 'DISTINCT';
         }
     }
     if (count($index)) {
         $options['USE INDEX'] = $index;
     }
     # Don't show duplicate rows when using log_search
     $joins['log_search'] = array('INNER JOIN', 'ls_log_id=log_id');
     $info = array('tables' => $tables, 'fields' => $fields, 'conds' => array_merge($conds, $this->mConds), 'options' => $options, 'join_conds' => $joins);
     # Add ChangeTags filter query
     ChangeTags::modifyDisplayQuery($info['tables'], $info['fields'], $info['conds'], $info['join_conds'], $info['options'], $this->mTagFilter);
     return $info;
 }
Example #30
0
 private function buildQuickWatchlist()
 {
     global $wgShowUpdatedMarker, $wgRCShowWatchingUsers;
     $user = $this->getUser();
     // Building the request
     $dbr = wfGetDB(DB_SLAVE, 'watchlist');
     $tables = array('recentchanges', 'watchlist');
     $fields = array($dbr->tableName('recentchanges') . '.*');
     if ($wgShowUpdatedMarker) {
         $fields[] = 'wl_notificationtimestamp';
     }
     $conds = array();
     $conds[] = 'rc_this_oldid=page_latest OR rc_type=' . RC_LOG;
     $limitWatchlist = 0;
     $usePage = true;
     $join_conds = array('watchlist' => array('INNER JOIN', "wl_user='******' AND wl_namespace=rc_namespace AND wl_title=rc_title"));
     $options = array('LIMIT' => 5, 'ORDER BY' => 'rc_timestamp DESC');
     $rollbacker = $user->isAllowed('rollback');
     if ($usePage || $rollbacker) {
         $tables[] = 'page';
         $join_conds['page'] = array('LEFT JOIN', 'rc_cur_id=page_id');
         if ($rollbacker) {
             $fields[] = 'page_latest';
         }
     }
     ChangeTags::modifyDisplayQuery($tables, $fields, $conds, $join_conds, $options, '');
     $res = $dbr->select($tables, $fields, $conds, __METHOD__, $options, $join_conds);
     $numRows = $dbr->numRows($res);
     $s = '<div class="ms-info-wl">' . wfMessage('ms-watchlist')->parse() . '</div>';
     if ($numRows == 0) {
         $s .= '<p class="ms-wl-empty">' . wfMessage('watchnochange')->parse() . '</p>';
     } else {
         /* Do link batch query */
         $linkBatch = new LinkBatch();
         foreach ($res as $row) {
             $userNameUnderscored = str_replace(' ', '_', $row->rc_user_text);
             if ($row->rc_user != 0) {
                 $linkBatch->add(NS_USER, $userNameUnderscored);
             }
             $linkBatch->add(NS_USER_TALK, $userNameUnderscored);
             $linkBatch->add($row->rc_namespace, $row->rc_title);
         }
         $linkBatch->execute();
         $dbr->dataSeek($res, 0);
         $list = ChangesList::newFromContext($this->getContext());
         $list->setWatchlistDivs();
         $s .= $list->beginRecentChangesList();
         $counter = 1;
         foreach ($res as $obj) {
             # Make RC entry
             $rc = RecentChange::newFromRow($obj);
             $rc->counter = $counter++;
             // Updated markers are always shown
             $updated = $obj->wl_notificationtimestamp;
             // We don't display the count of watching users
             $rc->numberofWatchingusers = 0;
             $s .= $list->recentChangesLine($rc, $updated, $counter);
         }
         $s .= $list->endRecentChangesList();
     }
     return $s;
 }