3 * Base code for "query" special pages.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup SpecialPage
24 use Wikimedia\Rdbms\ResultWrapper
;
25 use Wikimedia\Rdbms\IDatabase
;
28 * This is a class for doing query pages; since they're almost all the same,
29 * we factor out some of the functionality into a superclass, and let
30 * subclasses derive from it.
31 * @ingroup SpecialPage
33 abstract class QueryPage
extends SpecialPage
{
34 /** @var bool Whether or not we want plain listoutput rather than an ordered list */
35 protected $listoutput = false;
37 /** @var int The offset and limit in use, as passed to the query() function */
38 protected $offset = 0;
44 * The number of rows returned by the query. Reading this variable
45 * only makes sense in functions that are run after the query has been
46 * done, such as preprocessResults() and formatRow().
50 protected $cachedTimestamp = null;
53 * Whether to show prev/next links
55 protected $shownavigation = true;
58 * Get a list of query page classes and their associated special pages,
59 * for periodic updates.
61 * DO NOT CHANGE THIS LIST without testing that
62 * maintenance/updateSpecialPages.php still works.
65 public static function getPages() {
69 // QueryPage subclass, Special page name
71 [ 'AncientPagesPage', 'Ancientpages' ],
72 [ 'BrokenRedirectsPage', 'BrokenRedirects' ],
73 [ 'DeadendPagesPage', 'Deadendpages' ],
74 [ 'DoubleRedirectsPage', 'DoubleRedirects' ],
75 [ 'FileDuplicateSearchPage', 'FileDuplicateSearch' ],
76 [ 'ListDuplicatedFilesPage', 'ListDuplicatedFiles' ],
77 [ 'LinkSearchPage', 'LinkSearch' ],
78 [ 'ListredirectsPage', 'Listredirects' ],
79 [ 'LonelyPagesPage', 'Lonelypages' ],
80 [ 'LongPagesPage', 'Longpages' ],
81 [ 'MediaStatisticsPage', 'MediaStatistics' ],
82 [ 'MIMEsearchPage', 'MIMEsearch' ],
83 [ 'MostcategoriesPage', 'Mostcategories' ],
84 [ 'MostimagesPage', 'Mostimages' ],
85 [ 'MostinterwikisPage', 'Mostinterwikis' ],
86 [ 'MostlinkedCategoriesPage', 'Mostlinkedcategories' ],
87 [ 'MostlinkedTemplatesPage', 'Mostlinkedtemplates' ],
88 [ 'MostlinkedPage', 'Mostlinked' ],
89 [ 'MostrevisionsPage', 'Mostrevisions' ],
90 [ 'FewestrevisionsPage', 'Fewestrevisions' ],
91 [ 'ShortPagesPage', 'Shortpages' ],
92 [ 'UncategorizedCategoriesPage', 'Uncategorizedcategories' ],
93 [ 'UncategorizedPagesPage', 'Uncategorizedpages' ],
94 [ 'UncategorizedImagesPage', 'Uncategorizedimages' ],
95 [ 'UncategorizedTemplatesPage', 'Uncategorizedtemplates' ],
96 [ 'UnusedCategoriesPage', 'Unusedcategories' ],
97 [ 'UnusedimagesPage', 'Unusedimages' ],
98 [ 'WantedCategoriesPage', 'Wantedcategories' ],
99 [ 'WantedFilesPage', 'Wantedfiles' ],
100 [ 'WantedPagesPage', 'Wantedpages' ],
101 [ 'WantedTemplatesPage', 'Wantedtemplates' ],
102 [ 'UnwatchedpagesPage', 'Unwatchedpages' ],
103 [ 'UnusedtemplatesPage', 'Unusedtemplates' ],
104 [ 'WithoutInterwikiPage', 'Withoutinterwiki' ],
106 Hooks
::run( 'wgQueryPages', [ &$qp ] );
113 * A mutator for $this->listoutput;
117 function setListoutput( $bool ) {
118 $this->listoutput
= $bool;
122 * Subclasses return an SQL query here, formatted as an array with the
124 * tables => Table(s) for passing to Database::select()
125 * fields => Field(s) for passing to Database::select(), may be *
126 * conds => WHERE conditions
128 * join_conds => JOIN conditions
130 * Note that the query itself should return the following three columns:
131 * 'namespace', 'title', and 'value'. 'value' is used for sorting.
133 * These may be stored in the querycache table for expensive queries,
134 * and that cached data will be returned sometimes, so the presence of
135 * extra fields can't be relied upon. The cached 'value' column will be
136 * an integer; non-numeric values are useful only for sorting the
137 * initial query (except if they're timestamps, see usesTimestamps()).
139 * Don't include an ORDER or LIMIT clause, they will be added.
141 * If this function is not overridden or returns something other than
142 * an array, getSQL() will be used instead. This is for backwards
143 * compatibility only and is strongly deprecated.
147 public function getQueryInfo() {
152 * For back-compat, subclasses may return a raw SQL query here, as a string.
153 * This is strongly deprecated; getQueryInfo() should be overridden instead.
154 * @throws MWException
158 /* Implement getQueryInfo() instead */
159 throw new MWException( "Bug in a QueryPage: doesn't implement getQueryInfo() nor "
160 . "getQuery() properly" );
164 * Subclasses return an array of fields to order by here. Don't append
165 * DESC to the field names, that'll be done automatically if
166 * sortDescending() returns true.
170 function getOrderFields() {
175 * Does this query return timestamps rather than integers in its
176 * 'value' field? If true, this class will convert 'value' to a
177 * UNIX timestamp for caching.
178 * NOTE: formatRow() may get timestamps in TS_MW (mysql), TS_DB (pgsql)
179 * or TS_UNIX (querycache) format, so be sure to always run them
180 * through wfTimestamp()
184 public function usesTimestamps() {
189 * Override to sort by increasing values
193 function sortDescending() {
198 * Is this query expensive (for some definition of expensive)? Then we
199 * don't let it run in miser mode. $wgDisableQueryPages causes all query
200 * pages to be declared expensive. Some query pages are always expensive.
204 public function isExpensive() {
205 return $this->getConfig()->get( 'DisableQueryPages' );
209 * Is the output of this query cacheable? Non-cacheable expensive pages
210 * will be disabled in miser mode and will not have their results written
211 * to the querycache table.
215 public function isCacheable() {
220 * Whether or not the output of the page in question is retrieved from
221 * the database cache.
225 public function isCached() {
226 return $this->isExpensive() && $this->getConfig()->get( 'MiserMode' );
230 * Sometime we don't want to build rss / atom feeds.
234 function isSyndicated() {
239 * Formats the results of the query for display. The skin is the current
240 * skin; you can use it for making links. The result is a single row of
241 * result data. You should be able to grab SQL results off of it.
242 * If the function returns false, the line output will be skipped.
244 * @param object $result Result row
245 * @return string|bool String or false to skip
247 abstract function formatResult( $skin, $result );
250 * The content returned by this function will be output before any result
254 function getPageHeader() {
259 * Outputs some kind of an informative message (via OutputPage) to let the
260 * user know that the query returned nothing and thus there's nothing to
265 protected function showEmptyText() {
266 $this->getOutput()->addWikiMsg( 'specialpage-empty' );
270 * If using extra form wheely-dealies, return a set of parameters here
271 * as an associative array. They will be encoded and added to the paging
272 * links (prev/next/lengths).
276 function linkParameters() {
281 * Some special pages (for example SpecialListusers used to) might not return the
282 * current object formatted, but return the previous one instead.
283 * Setting this to return true will ensure formatResult() is called
284 * one more time to make sure that the very last result is formatted
287 * @deprecated since 1.27
291 function tryLastResult() {
296 * Clear the cache and save new results
298 * @param int|bool $limit Limit for SQL statement
299 * @param bool $ignoreErrors Whether to ignore database errors
300 * @throws DBError|Exception
303 public function recache( $limit, $ignoreErrors = true ) {
304 if ( !$this->isCacheable() ) {
308 $fname = static::class . '::recache';
309 $dbw = wfGetDB( DB_MASTER
);
316 $res = $this->reallyDoQuery( $limit, false );
319 $num = $res->numRows();
322 foreach ( $res as $row ) {
323 if ( isset( $row->value
) ) {
324 if ( $this->usesTimestamps() ) {
325 $value = wfTimestamp( TS_UNIX
,
328 $value = intval( $row->value
); // T16414
335 'qc_type' => $this->getName(),
336 'qc_namespace' => $row->namespace,
337 'qc_title' => $row->title
,
342 $dbw->doAtomicSection(
344 function ( IDatabase
$dbw, $fname ) use ( $vals ) {
345 # Clear out any old cached data
346 $dbw->delete( 'querycache',
347 [ 'qc_type' => $this->getName() ],
350 # Save results into the querycache table on the master
351 if ( count( $vals ) ) {
352 $dbw->insert( 'querycache', $vals, $fname );
354 # Update the querycache_info record for the page
355 $dbw->delete( 'querycache_info',
356 [ 'qci_type' => $this->getName() ],
359 $dbw->insert( 'querycache_info',
360 [ 'qci_type' => $this->getName(),
361 'qci_timestamp' => $dbw->timestamp() ],
367 } catch ( DBError
$e ) {
368 if ( !$ignoreErrors ) {
369 throw $e; // report query error
371 $num = false; // set result to false to indicate error
378 * Get a DB connection to be used for slow recache queries
381 function getRecacheDB() {
382 return wfGetDB( DB_REPLICA
, [ $this->getName(), 'QueryPage::recache', 'vslow' ] );
386 * Run the query and return the result
387 * @param int|bool $limit Numerical limit or false for no limit
388 * @param int|bool $offset Numerical offset or false for no offset
389 * @return ResultWrapper
392 public function reallyDoQuery( $limit, $offset = false ) {
393 $fname = static::class . '::reallyDoQuery';
394 $dbr = $this->getRecacheDB();
395 $query = $this->getQueryInfo();
396 $order = $this->getOrderFields();
398 if ( $this->sortDescending() ) {
399 foreach ( $order as &$field ) {
404 if ( is_array( $query ) ) {
405 $tables = isset( $query['tables'] ) ?
(array)$query['tables'] : [];
406 $fields = isset( $query['fields'] ) ?
(array)$query['fields'] : [];
407 $conds = isset( $query['conds'] ) ?
(array)$query['conds'] : [];
408 $options = isset( $query['options'] ) ?
(array)$query['options'] : [];
409 $join_conds = isset( $query['join_conds'] ) ?
(array)$query['join_conds'] : [];
412 $options['ORDER BY'] = $order;
415 if ( $limit !== false ) {
416 $options['LIMIT'] = intval( $limit );
419 if ( $offset !== false ) {
420 $options['OFFSET'] = intval( $offset );
423 $res = $dbr->select( $tables, $fields, $conds, $fname,
424 $options, $join_conds
427 // Old-fashioned raw SQL style, deprecated
428 $sql = $this->getSQL();
429 $sql .= ' ORDER BY ' . implode( ', ', $order );
430 $sql = $dbr->limitResult( $sql, $limit, $offset );
431 $res = $dbr->query( $sql, $fname );
438 * Somewhat deprecated, you probably want to be using execute()
439 * @param int|bool $offset
440 * @param int|bool $limit
441 * @return ResultWrapper
443 public function doQuery( $offset = false, $limit = false ) {
444 if ( $this->isCached() && $this->isCacheable() ) {
445 return $this->fetchFromCache( $limit, $offset );
447 return $this->reallyDoQuery( $limit, $offset );
452 * Fetch the query results from the query cache
453 * @param int|bool $limit Numerical limit or false for no limit
454 * @param int|bool $offset Numerical offset or false for no offset
455 * @return ResultWrapper
458 public function fetchFromCache( $limit, $offset = false ) {
459 $dbr = wfGetDB( DB_REPLICA
);
462 if ( $limit !== false ) {
463 $options['LIMIT'] = intval( $limit );
466 if ( $offset !== false ) {
467 $options['OFFSET'] = intval( $offset );
470 $order = $this->getCacheOrderFields();
471 if ( $this->sortDescending() ) {
472 foreach ( $order as &$field ) {
477 $options['ORDER BY'] = $order;
480 return $dbr->select( 'querycache',
482 'namespace' => 'qc_namespace',
483 'title' => 'qc_title',
484 'value' => 'qc_value' ],
485 [ 'qc_type' => $this->getName() ],
492 * Return the order fields for fetchFromCache. Default is to always use
493 * "ORDER BY value" which was the default prior to this function.
497 function getCacheOrderFields() {
501 public function getCachedTimestamp() {
502 if ( is_null( $this->cachedTimestamp
) ) {
503 $dbr = wfGetDB( DB_REPLICA
);
504 $fname = static::class . '::getCachedTimestamp';
505 $this->cachedTimestamp
= $dbr->selectField( 'querycache_info', 'qci_timestamp',
506 [ 'qci_type' => $this->getName() ], $fname );
508 return $this->cachedTimestamp
;
512 * Returns limit and offset, as returned by $this->getRequest()->getLimitOffset().
513 * Subclasses may override this to further restrict or modify limit and offset.
515 * @note Restricts the offset parameter, as most query pages have inefficient paging
517 * Its generally expected that the returned limit will not be 0, and the returned
518 * offset will be less than the max results.
521 * @return int[] list( $limit, $offset )
523 protected function getLimitOffset() {
524 list( $limit, $offset ) = $this->getRequest()->getLimitOffset();
525 if ( $this->getConfig()->get( 'MiserMode' ) ) {
526 $maxResults = $this->getMaxResults();
527 // Can't display more than max results on a page
528 $limit = min( $limit, $maxResults );
529 // Can't skip over more than the end of $maxResults
530 $offset = min( $offset, $maxResults +
1 );
532 return [ $limit, $offset ];
536 * What is limit to fetch from DB
538 * Used to make it appear the DB stores less results then it actually does
539 * @param int $uiLimit Limit from UI
540 * @param int $uiOffset Offset from UI
541 * @return int Limit to use for DB (not including extra row to see if at end)
543 protected function getDBLimit( $uiLimit, $uiOffset ) {
544 $maxResults = $this->getMaxResults();
545 if ( $this->getConfig()->get( 'MiserMode' ) ) {
546 $limit = min( $uiLimit +
1, $maxResults - $uiOffset );
547 return max( $limit, 0 );
554 * Get max number of results we can return in miser mode.
556 * Most QueryPage subclasses use inefficient paging, so limit the max amount we return
557 * This matters for uncached query pages that might otherwise accept an offset of 3 million
562 protected function getMaxResults() {
563 // Max of 10000, unless we store more than 10000 in query cache.
564 return max( $this->getConfig()->get( 'QueryCacheLimit' ), 10000 );
568 * This is the actual workhorse. It does everything needed to make a
569 * real, honest-to-gosh query page.
572 public function execute( $par ) {
573 $user = $this->getUser();
574 if ( !$this->userCanExecute( $user ) ) {
575 $this->displayRestrictionError();
580 $this->outputHeader();
582 $out = $this->getOutput();
584 if ( $this->isCached() && !$this->isCacheable() ) {
585 $out->addWikiMsg( 'querypage-disabled' );
589 $out->setSyndicated( $this->isSyndicated() );
591 if ( $this->limit
== 0 && $this->offset
== 0 ) {
592 list( $this->limit
, $this->offset
) = $this->getLimitOffset();
594 $dbLimit = $this->getDBLimit( $this->limit
, $this->offset
);
595 // @todo Use doQuery()
596 if ( !$this->isCached() ) {
597 # select one extra row for navigation
598 $res = $this->reallyDoQuery( $dbLimit, $this->offset
);
600 # Get the cached result, select one extra row for navigation
601 $res = $this->fetchFromCache( $dbLimit, $this->offset
);
602 if ( !$this->listoutput
) {
604 # Fetch the timestamp of this update
605 $ts = $this->getCachedTimestamp();
606 $lang = $this->getLanguage();
607 $maxResults = $lang->formatNum( $this->getConfig()->get( 'QueryCacheLimit' ) );
610 $updated = $lang->userTimeAndDate( $ts, $user );
611 $updateddate = $lang->userDate( $ts, $user );
612 $updatedtime = $lang->userTime( $ts, $user );
613 $out->addMeta( 'Data-Cache-Time', $ts );
614 $out->addJsConfigVars( 'dataCacheTime', $ts );
615 $out->addWikiMsg( 'perfcachedts', $updated, $updateddate, $updatedtime, $maxResults );
617 $out->addWikiMsg( 'perfcached', $maxResults );
620 # If updates on this page have been disabled, let the user know
621 # that the data set won't be refreshed for now
622 if ( is_array( $this->getConfig()->get( 'DisableQueryPageUpdate' ) )
623 && in_array( $this->getName(), $this->getConfig()->get( 'DisableQueryPageUpdate' ) )
626 "<div class=\"mw-querypage-no-updates\">\n$1\n</div>",
627 'querypage-no-updates'
633 $this->numRows
= $res->numRows();
635 $dbr = $this->getRecacheDB();
636 $this->preprocessResults( $dbr, $res );
638 $out->addHTML( Xml
::openElement( 'div', [ 'class' => 'mw-spcontent' ] ) );
640 # Top header and navigation
641 if ( $this->shownavigation
) {
642 $out->addHTML( $this->getPageHeader() );
643 if ( $this->numRows
> 0 ) {
644 $out->addHTML( $this->msg( 'showingresultsinrange' )->numParams(
645 min( $this->numRows
, $this->limit
), # do not show the one extra row, if exist
646 $this->offset +
1, ( min( $this->numRows
, $this->limit
) +
$this->offset
) )->parseAsBlock() );
647 # Disable the "next" link when we reach the end
648 $miserMaxResults = $this->getConfig()->get( 'MiserMode' )
649 && ( $this->offset +
$this->limit
>= $this->getMaxResults() );
650 $atEnd = ( $this->numRows
<= $this->limit
) ||
$miserMaxResults;
651 $paging = $this->getLanguage()->viewPrevNext( $this->getPageTitle( $par ), $this->offset
,
652 $this->limit
, $this->linkParameters(), $atEnd );
653 $out->addHTML( '<p>' . $paging . '</p>' );
655 # No results to show, so don't bother with "showing X of Y" etc.
656 # -- just let the user know and give up now
657 $this->showEmptyText();
658 $out->addHTML( Xml
::closeElement( 'div' ) );
663 # The actual results; specialist subclasses will want to handle this
664 # with more than a straight list, so we hand them the info, plus
665 # an OutputPage, and let them get on with it
666 $this->outputResults( $out,
668 $dbr, # Should use a ResultWrapper for this
670 min( $this->numRows
, $this->limit
), # do not format the one extra row, if exist
673 # Repeat the paging links at the bottom
674 if ( $this->shownavigation
) {
675 $out->addHTML( '<p>' . $paging . '</p>' );
678 $out->addHTML( Xml
::closeElement( 'div' ) );
682 * Format and output report results using the given information plus
685 * @param OutputPage $out OutputPage to print to
686 * @param Skin $skin User skin to use
687 * @param IDatabase $dbr Database (read) connection to use
688 * @param ResultWrapper $res Result pointer
689 * @param int $num Number of available result rows
690 * @param int $offset Paging offset
692 protected function outputResults( $out, $skin, $dbr, $res, $num, $offset ) {
697 if ( !$this->listoutput
) {
698 $html[] = $this->openList( $offset );
701 # $res might contain the whole 1,000 rows, so we read up to
702 # $num [should update this to use a Pager]
703 // @codingStandardsIgnoreStart Generic.CodeAnalysis.ForLoopWithTestFunctionCall.NotAllowed
704 for ( $i = 0; $i < $num && $row = $res->fetchObject(); $i++
) {
705 // @codingStandardsIgnoreEnd
706 $line = $this->formatResult( $skin, $row );
708 $html[] = $this->listoutput
710 : "<li>{$line}</li>\n";
714 # Flush the final result
715 if ( $this->tryLastResult() ) {
717 $line = $this->formatResult( $skin, $row );
719 $html[] = $this->listoutput
721 : "<li>{$line}</li>\n";
725 if ( !$this->listoutput
) {
726 $html[] = $this->closeList();
729 $html = $this->listoutput
730 ?
$wgContLang->listToText( $html )
731 : implode( '', $html );
733 $out->addHTML( $html );
741 function openList( $offset ) {
742 return "\n<ol start='" . ( $offset +
1 ) . "' class='special'>\n";
748 function closeList() {
753 * Do any necessary preprocessing of the result object.
754 * @param IDatabase $db
755 * @param ResultWrapper $res
757 function preprocessResults( $db, $res ) {
761 * Similar to above, but packaging in a syndicated feed instead of a web page
762 * @param string $class
766 function doFeed( $class = '', $limit = 50 ) {
767 if ( !$this->getConfig()->get( 'Feed' ) ) {
768 $this->getOutput()->addWikiMsg( 'feed-unavailable' );
772 $limit = min( $limit, $this->getConfig()->get( 'FeedLimit' ) );
774 $feedClasses = $this->getConfig()->get( 'FeedClasses' );
775 if ( isset( $feedClasses[$class] ) ) {
776 /** @var RSSFeed|AtomFeed $feed */
777 $feed = new $feedClasses[$class](
783 $res = $this->reallyDoQuery( $limit, 0 );
784 foreach ( $res as $obj ) {
785 $item = $this->feedResult( $obj );
787 $feed->outItem( $item );
799 * Override for custom handling. If the titles/links are ok, just do
802 * @return FeedItem|null
804 function feedResult( $row ) {
805 if ( !isset( $row->title
) ) {
808 $title = Title
::makeTitle( intval( $row->namespace ), $row->title
);
810 $date = isset( $row->timestamp
) ?
$row->timestamp
: '';
813 $talkpage = $title->getTalkPage();
814 $comments = $talkpage->getFullURL();
818 $title->getPrefixedText(),
819 $this->feedItemDesc( $row ),
820 $title->getFullURL(),
822 $this->feedItemAuthor( $row ),
829 function feedItemDesc( $row ) {
830 return isset( $row->comment
) ?
htmlspecialchars( $row->comment
) : '';
833 function feedItemAuthor( $row ) {
834 return isset( $row->user_text
) ?
$row->user_text
: '';
837 function feedTitle() {
838 $desc = $this->getDescription();
839 $code = $this->getConfig()->get( 'LanguageCode' );
840 $sitename = $this->getConfig()->get( 'Sitename' );
841 return "$sitename - $desc [$code]";
844 function feedDesc() {
845 return $this->msg( 'tagline' )->text();
849 return $this->getPageTitle()->getFullURL();
853 * Creates a new LinkBatch object, adds all pages from the passed ResultWrapper (MUST include
854 * title and optional the namespace field) and executes the batch. This operation will pre-cache
855 * LinkCache information like page existence and information for stub color and redirect hints.
857 * @param ResultWrapper $res The ResultWrapper object to process. Needs to include the title
858 * field and namespace field, if the $ns parameter isn't set.
859 * @param null $ns Use this namespace for the given titles in the ResultWrapper object,
860 * instead of the namespace value of $res.
862 protected function executeLBFromResultWrapper( ResultWrapper
$res, $ns = null ) {
863 if ( !$res->numRows() ) {
867 $batch = new LinkBatch
;
868 foreach ( $res as $row ) {
869 $batch->add( $ns !== null ?
$ns : $row->namespace, $row->title
);