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 MediaWiki\MediaWikiServices
;
25 use Wikimedia\Rdbms\IResultWrapper
;
26 use Wikimedia\Rdbms\IDatabase
;
27 use Wikimedia\Rdbms\DBError
;
30 * This is a class for doing query pages; since they're almost all the same,
31 * we factor out some of the functionality into a superclass, and let
32 * subclasses derive from it.
33 * @ingroup SpecialPage
35 abstract class QueryPage
extends SpecialPage
{
36 /** @var bool Whether or not we want plain listoutput rather than an ordered list */
37 protected $listoutput = false;
39 /** @var int The offset and limit in use, as passed to the query() function */
40 protected $offset = 0;
46 * The number of rows returned by the query. Reading this variable
47 * only makes sense in functions that are run after the query has been
48 * done, such as preprocessResults() and formatRow().
57 protected $cachedTimestamp = null;
60 * @var bool Whether to show prev/next links
62 protected $shownavigation = true;
65 * Get a list of query page classes and their associated special pages,
66 * for periodic updates.
68 * DO NOT CHANGE THIS LIST without testing that
69 * maintenance/updateSpecialPages.php still works.
73 public static function getPages() {
77 // QueryPage subclass, Special page name
79 [ AncientPagesPage
::class, 'Ancientpages' ],
80 [ BrokenRedirectsPage
::class, 'BrokenRedirects' ],
81 [ DeadendPagesPage
::class, 'Deadendpages' ],
82 [ DoubleRedirectsPage
::class, 'DoubleRedirects' ],
83 [ FileDuplicateSearchPage
::class, 'FileDuplicateSearch' ],
84 [ ListDuplicatedFilesPage
::class, 'ListDuplicatedFiles' ],
85 [ LinkSearchPage
::class, 'LinkSearch' ],
86 [ ListredirectsPage
::class, 'Listredirects' ],
87 [ LonelyPagesPage
::class, 'Lonelypages' ],
88 [ LongPagesPage
::class, 'Longpages' ],
89 [ MediaStatisticsPage
::class, 'MediaStatistics' ],
90 [ MIMEsearchPage
::class, 'MIMEsearch' ],
91 [ MostcategoriesPage
::class, 'Mostcategories' ],
92 [ MostimagesPage
::class, 'Mostimages' ],
93 [ MostinterwikisPage
::class, 'Mostinterwikis' ],
94 [ MostlinkedCategoriesPage
::class, 'Mostlinkedcategories' ],
95 [ MostlinkedTemplatesPage
::class, 'Mostlinkedtemplates' ],
96 [ MostlinkedPage
::class, 'Mostlinked' ],
97 [ MostrevisionsPage
::class, 'Mostrevisions' ],
98 [ FewestrevisionsPage
::class, 'Fewestrevisions' ],
99 [ ShortPagesPage
::class, 'Shortpages' ],
100 [ UncategorizedCategoriesPage
::class, 'Uncategorizedcategories' ],
101 [ UncategorizedPagesPage
::class, 'Uncategorizedpages' ],
102 [ UncategorizedImagesPage
::class, 'Uncategorizedimages' ],
103 [ UncategorizedTemplatesPage
::class, 'Uncategorizedtemplates' ],
104 [ UnusedCategoriesPage
::class, 'Unusedcategories' ],
105 [ UnusedimagesPage
::class, 'Unusedimages' ],
106 [ WantedCategoriesPage
::class, 'Wantedcategories' ],
107 [ WantedFilesPage
::class, 'Wantedfiles' ],
108 [ WantedPagesPage
::class, 'Wantedpages' ],
109 [ WantedTemplatesPage
::class, 'Wantedtemplates' ],
110 [ UnwatchedpagesPage
::class, 'Unwatchedpages' ],
111 [ UnusedtemplatesPage
::class, 'Unusedtemplates' ],
112 [ WithoutInterwikiPage
::class, 'Withoutinterwiki' ],
114 Hooks
::run( 'wgQueryPages', [ &$qp ] );
121 * A mutator for $this->listoutput;
125 function setListoutput( $bool ) {
126 $this->listoutput
= $bool;
130 * Subclasses return an SQL query here, formatted as an array with the
132 * tables => Table(s) for passing to Database::select()
133 * fields => Field(s) for passing to Database::select(), may be *
134 * conds => WHERE conditions
136 * join_conds => JOIN conditions
138 * Note that the query itself should return the following three columns:
139 * 'namespace', 'title', and 'value'. 'value' is used for sorting.
141 * These may be stored in the querycache table for expensive queries,
142 * and that cached data will be returned sometimes, so the presence of
143 * extra fields can't be relied upon. The cached 'value' column will be
144 * an integer; non-numeric values are useful only for sorting the
145 * initial query (except if they're timestamps, see usesTimestamps()).
147 * Don't include an ORDER or LIMIT clause, they will be added.
149 * If this function is not overridden or returns something other than
150 * an array, getSQL() will be used instead. This is for backwards
151 * compatibility only and is strongly deprecated.
155 public function getQueryInfo() {
160 * For back-compat, subclasses may return a raw SQL query here, as a string.
161 * This is strongly deprecated; getQueryInfo() should be overridden instead.
162 * @throws MWException
166 /* Implement getQueryInfo() instead */
167 throw new MWException( "Bug in a QueryPage: doesn't implement getQueryInfo() nor "
168 . "getQuery() properly" );
172 * Subclasses return an array of fields to order by here. Don't append
173 * DESC to the field names, that'll be done automatically if
174 * sortDescending() returns true.
178 function getOrderFields() {
183 * Does this query return timestamps rather than integers in its
184 * 'value' field? If true, this class will convert 'value' to a
185 * UNIX timestamp for caching.
186 * NOTE: formatRow() may get timestamps in TS_MW (mysql), TS_DB (pgsql)
187 * or TS_UNIX (querycache) format, so be sure to always run them
188 * through wfTimestamp()
192 public function usesTimestamps() {
197 * Override to sort by increasing values
201 function sortDescending() {
206 * Is this query expensive (for some definition of expensive)? Then we
207 * don't let it run in miser mode. $wgDisableQueryPages causes all query
208 * pages to be declared expensive. Some query pages are always expensive.
212 public function isExpensive() {
213 return $this->getConfig()->get( 'DisableQueryPages' );
217 * Is the output of this query cacheable? Non-cacheable expensive pages
218 * will be disabled in miser mode and will not have their results written
219 * to the querycache table.
223 public function isCacheable() {
228 * Whether or not the output of the page in question is retrieved from
229 * the database cache.
233 public function isCached() {
234 return $this->isExpensive() && $this->getConfig()->get( 'MiserMode' );
238 * Sometime we don't want to build rss / atom feeds.
242 function isSyndicated() {
247 * Formats the results of the query for display. The skin is the current
248 * skin; you can use it for making links. The result is a single row of
249 * result data. You should be able to grab SQL results off of it.
250 * If the function returns false, the line output will be skipped.
252 * @param object $result Result row
253 * @return string|bool String or false to skip
255 abstract function formatResult( $skin, $result );
258 * The content returned by this function will be output before any result
262 function getPageHeader() {
267 * Outputs some kind of an informative message (via OutputPage) to let the
268 * user know that the query returned nothing and thus there's nothing to
273 protected function showEmptyText() {
274 $this->getOutput()->addWikiMsg( 'specialpage-empty' );
278 * If using extra form wheely-dealies, return a set of parameters here
279 * as an associative array. They will be encoded and added to the paging
280 * links (prev/next/lengths).
284 function linkParameters() {
289 * Clear the cache and save new results
291 * @param int|bool $limit Limit for SQL statement
292 * @param bool $ignoreErrors Whether to ignore database errors
293 * @throws DBError|Exception
296 public function recache( $limit, $ignoreErrors = true ) {
297 if ( !$this->isCacheable() ) {
301 $fname = static::class . '::recache';
302 $dbw = wfGetDB( DB_MASTER
);
309 $res = $this->reallyDoQuery( $limit, false );
312 $num = $res->numRows();
315 foreach ( $res as $row ) {
316 if ( isset( $row->value
) ) {
317 if ( $this->usesTimestamps() ) {
318 $value = wfTimestamp( TS_UNIX
,
321 $value = intval( $row->value
); // T16414
328 'qc_type' => $this->getName(),
329 'qc_namespace' => $row->namespace,
330 'qc_title' => $row->title
,
335 $dbw->doAtomicSection(
337 function ( IDatabase
$dbw, $fname ) use ( $vals ) {
338 # Clear out any old cached data
339 $dbw->delete( 'querycache',
340 [ 'qc_type' => $this->getName() ],
343 # Save results into the querycache table on the master
344 if ( count( $vals ) ) {
345 $dbw->insert( 'querycache', $vals, $fname );
347 # Update the querycache_info record for the page
348 $dbw->delete( 'querycache_info',
349 [ 'qci_type' => $this->getName() ],
352 $dbw->insert( 'querycache_info',
353 [ 'qci_type' => $this->getName(),
354 'qci_timestamp' => $dbw->timestamp() ],
360 } catch ( DBError
$e ) {
361 if ( !$ignoreErrors ) {
362 throw $e; // report query error
364 $num = false; // set result to false to indicate error
371 * Get a DB connection to be used for slow recache queries
374 function getRecacheDB() {
375 return wfGetDB( DB_REPLICA
, [ $this->getName(), 'QueryPage::recache', 'vslow' ] );
379 * Run the query and return the result
380 * @param int|bool $limit Numerical limit or false for no limit
381 * @param int|bool $offset Numerical offset or false for no offset
382 * @return IResultWrapper
385 public function reallyDoQuery( $limit, $offset = false ) {
386 $fname = static::class . '::reallyDoQuery';
387 $dbr = $this->getRecacheDB();
388 $query = $this->getQueryInfo();
389 $order = $this->getOrderFields();
391 if ( $this->sortDescending() ) {
392 foreach ( $order as &$field ) {
397 if ( is_array( $query ) ) {
398 $tables = isset( $query['tables'] ) ?
(array)$query['tables'] : [];
399 $fields = isset( $query['fields'] ) ?
(array)$query['fields'] : [];
400 $conds = isset( $query['conds'] ) ?
(array)$query['conds'] : [];
401 $options = isset( $query['options'] ) ?
(array)$query['options'] : [];
402 $join_conds = isset( $query['join_conds'] ) ?
(array)$query['join_conds'] : [];
405 $options['ORDER BY'] = $order;
408 if ( $limit !== false ) {
409 $options['LIMIT'] = intval( $limit );
412 if ( $offset !== false ) {
413 $options['OFFSET'] = intval( $offset );
416 $res = $dbr->select( $tables, $fields, $conds, $fname,
417 $options, $join_conds
420 // Old-fashioned raw SQL style, deprecated
421 $sql = $this->getSQL();
422 $sql .= ' ORDER BY ' . implode( ', ', $order );
423 $sql = $dbr->limitResult( $sql, $limit, $offset );
424 $res = $dbr->query( $sql, $fname );
431 * Somewhat deprecated, you probably want to be using execute()
432 * @param int|bool $offset
433 * @param int|bool $limit
434 * @return IResultWrapper
436 public function doQuery( $offset = false, $limit = false ) {
437 if ( $this->isCached() && $this->isCacheable() ) {
438 return $this->fetchFromCache( $limit, $offset );
440 return $this->reallyDoQuery( $limit, $offset );
445 * Fetch the query results from the query cache
446 * @param int|bool $limit Numerical limit or false for no limit
447 * @param int|bool $offset Numerical offset or false for no offset
448 * @return IResultWrapper
451 public function fetchFromCache( $limit, $offset = false ) {
452 $dbr = wfGetDB( DB_REPLICA
);
455 if ( $limit !== false ) {
456 $options['LIMIT'] = intval( $limit );
459 if ( $offset !== false ) {
460 $options['OFFSET'] = intval( $offset );
463 $order = $this->getCacheOrderFields();
464 if ( $this->sortDescending() ) {
465 foreach ( $order as &$field ) {
470 $options['ORDER BY'] = $order;
473 return $dbr->select( 'querycache',
475 'namespace' => 'qc_namespace',
476 'title' => 'qc_title',
477 'value' => 'qc_value' ],
478 [ 'qc_type' => $this->getName() ],
485 * Return the order fields for fetchFromCache. Default is to always use
486 * "ORDER BY value" which was the default prior to this function.
490 function getCacheOrderFields() {
497 public function getCachedTimestamp() {
498 if ( is_null( $this->cachedTimestamp
) ) {
499 $dbr = wfGetDB( DB_REPLICA
);
500 $fname = static::class . '::getCachedTimestamp';
501 $this->cachedTimestamp
= $dbr->selectField( 'querycache_info', 'qci_timestamp',
502 [ 'qci_type' => $this->getName() ], $fname );
504 return $this->cachedTimestamp
;
508 * Returns limit and offset, as returned by $this->getRequest()->getLimitOffset().
509 * Subclasses may override this to further restrict or modify limit and offset.
511 * @note Restricts the offset parameter, as most query pages have inefficient paging
513 * Its generally expected that the returned limit will not be 0, and the returned
514 * offset will be less than the max results.
517 * @return int[] list( $limit, $offset )
519 protected function getLimitOffset() {
520 list( $limit, $offset ) = $this->getRequest()->getLimitOffset();
521 if ( $this->getConfig()->get( 'MiserMode' ) ) {
522 $maxResults = $this->getMaxResults();
523 // Can't display more than max results on a page
524 $limit = min( $limit, $maxResults );
525 // Can't skip over more than the end of $maxResults
526 $offset = min( $offset, $maxResults +
1 );
528 return [ $limit, $offset ];
532 * What is limit to fetch from DB
534 * Used to make it appear the DB stores less results then it actually does
535 * @param int $uiLimit Limit from UI
536 * @param int $uiOffset Offset from UI
537 * @return int Limit to use for DB (not including extra row to see if at end)
539 protected function getDBLimit( $uiLimit, $uiOffset ) {
540 $maxResults = $this->getMaxResults();
541 if ( $this->getConfig()->get( 'MiserMode' ) ) {
542 $limit = min( $uiLimit +
1, $maxResults - $uiOffset );
543 return max( $limit, 0 );
550 * Get max number of results we can return in miser mode.
552 * Most QueryPage subclasses use inefficient paging, so limit the max amount we return
553 * This matters for uncached query pages that might otherwise accept an offset of 3 million
558 protected function getMaxResults() {
559 // Max of 10000, unless we store more than 10000 in query cache.
560 return max( $this->getConfig()->get( 'QueryCacheLimit' ), 10000 );
564 * This is the actual workhorse. It does everything needed to make a
565 * real, honest-to-gosh query page.
566 * @param string|null $par
568 public function execute( $par ) {
569 $user = $this->getUser();
570 if ( !$this->userCanExecute( $user ) ) {
571 $this->displayRestrictionError();
576 $this->outputHeader();
578 $out = $this->getOutput();
580 if ( $this->isCached() && !$this->isCacheable() ) {
581 $out->addWikiMsg( 'querypage-disabled' );
585 $out->setSyndicated( $this->isSyndicated() );
587 if ( $this->limit
== 0 && $this->offset
== 0 ) {
588 list( $this->limit
, $this->offset
) = $this->getLimitOffset();
590 $dbLimit = $this->getDBLimit( $this->limit
, $this->offset
);
591 // @todo Use doQuery()
592 if ( !$this->isCached() ) {
593 # select one extra row for navigation
594 $res = $this->reallyDoQuery( $dbLimit, $this->offset
);
596 # Get the cached result, select one extra row for navigation
597 $res = $this->fetchFromCache( $dbLimit, $this->offset
);
598 if ( !$this->listoutput
) {
599 # Fetch the timestamp of this update
600 $ts = $this->getCachedTimestamp();
601 $lang = $this->getLanguage();
602 $maxResults = $lang->formatNum( $this->getConfig()->get( 'QueryCacheLimit' ) );
605 $updated = $lang->userTimeAndDate( $ts, $user );
606 $updateddate = $lang->userDate( $ts, $user );
607 $updatedtime = $lang->userTime( $ts, $user );
608 $out->addMeta( 'Data-Cache-Time', $ts );
609 $out->addJsConfigVars( 'dataCacheTime', $ts );
610 $out->addWikiMsg( 'perfcachedts', $updated, $updateddate, $updatedtime, $maxResults );
612 $out->addWikiMsg( 'perfcached', $maxResults );
615 # If updates on this page have been disabled, let the user know
616 # that the data set won't be refreshed for now
617 if ( is_array( $this->getConfig()->get( 'DisableQueryPageUpdate' ) )
618 && in_array( $this->getName(), $this->getConfig()->get( 'DisableQueryPageUpdate' ) )
621 "<div class=\"mw-querypage-no-updates\">\n$1\n</div>",
622 'querypage-no-updates'
628 $this->numRows
= $res->numRows();
630 $dbr = $this->getRecacheDB();
631 $this->preprocessResults( $dbr, $res );
633 $out->addHTML( Xml
::openElement( 'div', [ 'class' => 'mw-spcontent' ] ) );
635 # Top header and navigation
636 if ( $this->shownavigation
) {
637 $out->addHTML( $this->getPageHeader() );
638 if ( $this->numRows
> 0 ) {
639 $out->addHTML( $this->msg( 'showingresultsinrange' )->numParams(
640 min( $this->numRows
, $this->limit
), # do not show the one extra row, if exist
641 $this->offset +
1, ( min( $this->numRows
, $this->limit
) +
$this->offset
) )->parseAsBlock() );
642 # Disable the "next" link when we reach the end
643 $miserMaxResults = $this->getConfig()->get( 'MiserMode' )
644 && ( $this->offset +
$this->limit
>= $this->getMaxResults() );
645 $atEnd = ( $this->numRows
<= $this->limit
) ||
$miserMaxResults;
646 $paging = $this->buildPrevNextNavigation( $this->offset
,
647 $this->limit
, $this->linkParameters(), $atEnd, $par );
648 $out->addHTML( '<p>' . $paging . '</p>' );
650 # No results to show, so don't bother with "showing X of Y" etc.
651 # -- just let the user know and give up now
652 $this->showEmptyText();
653 $out->addHTML( Xml
::closeElement( 'div' ) );
658 # The actual results; specialist subclasses will want to handle this
659 # with more than a straight list, so we hand them the info, plus
660 # an OutputPage, and let them get on with it
661 $this->outputResults( $out,
663 $dbr, # Should use IResultWrapper for this
665 min( $this->numRows
, $this->limit
), # do not format the one extra row, if exist
668 # Repeat the paging links at the bottom
669 if ( $this->shownavigation
) {
670 $out->addHTML( '<p>' . $paging . '</p>' );
673 $out->addHTML( Xml
::closeElement( 'div' ) );
677 * Format and output report results using the given information plus
680 * @param OutputPage $out OutputPage to print to
681 * @param Skin $skin User skin to use
682 * @param IDatabase $dbr Database (read) connection to use
683 * @param IResultWrapper $res Result pointer
684 * @param int $num Number of available result rows
685 * @param int $offset Paging offset
687 protected function outputResults( $out, $skin, $dbr, $res, $num, $offset ) {
690 if ( !$this->listoutput
) {
691 $html[] = $this->openList( $offset );
694 # $res might contain the whole 1,000 rows, so we read up to
695 # $num [should update this to use a Pager]
696 for ( $i = 0; $i < $num && $row = $res->fetchObject(); $i++
) {
697 $line = $this->formatResult( $skin, $row );
699 $html[] = $this->listoutput
701 : "<li>{$line}</li>\n";
705 if ( !$this->listoutput
) {
706 $html[] = $this->closeList();
709 $html = $this->listoutput
710 ? MediaWikiServices
::getInstance()->getContentLanguage()->listToText( $html )
711 : implode( '', $html );
713 $out->addHTML( $html );
721 function openList( $offset ) {
722 return "\n<ol start='" . ( $offset +
1 ) . "' class='special'>\n";
728 function closeList() {
733 * Do any necessary preprocessing of the result object.
734 * @param IDatabase $db
735 * @param IResultWrapper $res
737 function preprocessResults( $db, $res ) {
741 * Creates a new LinkBatch object, adds all pages from the passed result wrapper (MUST include
742 * title and optional the namespace field) and executes the batch. This operation will pre-cache
743 * LinkCache information like page existence and information for stub color and redirect hints.
745 * @param IResultWrapper $res The result wrapper to process. Needs to include the title
746 * field and namespace field, if the $ns parameter isn't set.
747 * @param null $ns Use this namespace for the given titles in the result wrapper,
748 * instead of the namespace value of $res.
750 protected function executeLBFromResultWrapper( IResultWrapper
$res, $ns = null ) {
751 if ( !$res->numRows() ) {
755 $batch = new LinkBatch
;
756 foreach ( $res as $row ) {
757 $batch->add( $ns ??
$row->namespace, $row->title
);