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 * Some special pages (for example SpecialListusers used to) might not return the
290 * current object formatted, but return the previous one instead.
291 * Setting this to return true will ensure formatResult() is called
292 * one more time to make sure that the very last result is formatted
295 * @deprecated since 1.27
299 function tryLastResult() {
304 * Clear the cache and save new results
306 * @param int|bool $limit Limit for SQL statement
307 * @param bool $ignoreErrors Whether to ignore database errors
308 * @throws DBError|Exception
311 public function recache( $limit, $ignoreErrors = true ) {
312 if ( !$this->isCacheable() ) {
316 $fname = static::class . '::recache';
317 $dbw = wfGetDB( DB_MASTER
);
324 $res = $this->reallyDoQuery( $limit, false );
327 $num = $res->numRows();
330 foreach ( $res as $row ) {
331 if ( isset( $row->value
) ) {
332 if ( $this->usesTimestamps() ) {
333 $value = wfTimestamp( TS_UNIX
,
336 $value = intval( $row->value
); // T16414
343 'qc_type' => $this->getName(),
344 'qc_namespace' => $row->namespace,
345 'qc_title' => $row->title
,
350 $dbw->doAtomicSection(
352 function ( IDatabase
$dbw, $fname ) use ( $vals ) {
353 # Clear out any old cached data
354 $dbw->delete( 'querycache',
355 [ 'qc_type' => $this->getName() ],
358 # Save results into the querycache table on the master
359 if ( count( $vals ) ) {
360 $dbw->insert( 'querycache', $vals, $fname );
362 # Update the querycache_info record for the page
363 $dbw->delete( 'querycache_info',
364 [ 'qci_type' => $this->getName() ],
367 $dbw->insert( 'querycache_info',
368 [ 'qci_type' => $this->getName(),
369 'qci_timestamp' => $dbw->timestamp() ],
375 } catch ( DBError
$e ) {
376 if ( !$ignoreErrors ) {
377 throw $e; // report query error
379 $num = false; // set result to false to indicate error
386 * Get a DB connection to be used for slow recache queries
387 * @return \Wikimedia\Rdbms\Database
389 function getRecacheDB() {
390 return wfGetDB( DB_REPLICA
, [ $this->getName(), 'QueryPage::recache', 'vslow' ] );
394 * Run the query and return the result
395 * @param int|bool $limit Numerical limit or false for no limit
396 * @param int|bool $offset Numerical offset or false for no offset
397 * @return IResultWrapper
400 public function reallyDoQuery( $limit, $offset = false ) {
401 $fname = static::class . '::reallyDoQuery';
402 $dbr = $this->getRecacheDB();
403 $query = $this->getQueryInfo();
404 $order = $this->getOrderFields();
406 if ( $this->sortDescending() ) {
407 foreach ( $order as &$field ) {
412 if ( is_array( $query ) ) {
413 $tables = isset( $query['tables'] ) ?
(array)$query['tables'] : [];
414 $fields = isset( $query['fields'] ) ?
(array)$query['fields'] : [];
415 $conds = isset( $query['conds'] ) ?
(array)$query['conds'] : [];
416 $options = isset( $query['options'] ) ?
(array)$query['options'] : [];
417 $join_conds = isset( $query['join_conds'] ) ?
(array)$query['join_conds'] : [];
420 $options['ORDER BY'] = $order;
423 if ( $limit !== false ) {
424 $options['LIMIT'] = intval( $limit );
427 if ( $offset !== false ) {
428 $options['OFFSET'] = intval( $offset );
431 $res = $dbr->select( $tables, $fields, $conds, $fname,
432 $options, $join_conds
435 // Old-fashioned raw SQL style, deprecated
436 $sql = $this->getSQL();
437 $sql .= ' ORDER BY ' . implode( ', ', $order );
438 $sql = $dbr->limitResult( $sql, $limit, $offset );
439 $res = $dbr->query( $sql, $fname );
446 * Somewhat deprecated, you probably want to be using execute()
447 * @param int|bool $offset
448 * @param int|bool $limit
449 * @return IResultWrapper
451 public function doQuery( $offset = false, $limit = false ) {
452 if ( $this->isCached() && $this->isCacheable() ) {
453 return $this->fetchFromCache( $limit, $offset );
455 return $this->reallyDoQuery( $limit, $offset );
460 * Fetch the query results from the query cache
461 * @param int|bool $limit Numerical limit or false for no limit
462 * @param int|bool $offset Numerical offset or false for no offset
463 * @return IResultWrapper
466 public function fetchFromCache( $limit, $offset = false ) {
467 $dbr = wfGetDB( DB_REPLICA
);
470 if ( $limit !== false ) {
471 $options['LIMIT'] = intval( $limit );
474 if ( $offset !== false ) {
475 $options['OFFSET'] = intval( $offset );
478 $order = $this->getCacheOrderFields();
479 if ( $this->sortDescending() ) {
480 foreach ( $order as &$field ) {
485 $options['ORDER BY'] = $order;
488 return $dbr->select( 'querycache',
490 'namespace' => 'qc_namespace',
491 'title' => 'qc_title',
492 'value' => 'qc_value' ],
493 [ 'qc_type' => $this->getName() ],
500 * Return the order fields for fetchFromCache. Default is to always use
501 * "ORDER BY value" which was the default prior to this function.
505 function getCacheOrderFields() {
512 public function getCachedTimestamp() {
513 if ( is_null( $this->cachedTimestamp
) ) {
514 $dbr = wfGetDB( DB_REPLICA
);
515 $fname = static::class . '::getCachedTimestamp';
516 $this->cachedTimestamp
= $dbr->selectField( 'querycache_info', 'qci_timestamp',
517 [ 'qci_type' => $this->getName() ], $fname );
519 return $this->cachedTimestamp
;
523 * Returns limit and offset, as returned by $this->getRequest()->getLimitOffset().
524 * Subclasses may override this to further restrict or modify limit and offset.
526 * @note Restricts the offset parameter, as most query pages have inefficient paging
528 * Its generally expected that the returned limit will not be 0, and the returned
529 * offset will be less than the max results.
532 * @return int[] list( $limit, $offset )
534 protected function getLimitOffset() {
535 list( $limit, $offset ) = $this->getRequest()->getLimitOffset();
536 if ( $this->getConfig()->get( 'MiserMode' ) ) {
537 $maxResults = $this->getMaxResults();
538 // Can't display more than max results on a page
539 $limit = min( $limit, $maxResults );
540 // Can't skip over more than the end of $maxResults
541 $offset = min( $offset, $maxResults +
1 );
543 return [ $limit, $offset ];
547 * What is limit to fetch from DB
549 * Used to make it appear the DB stores less results then it actually does
550 * @param int $uiLimit Limit from UI
551 * @param int $uiOffset Offset from UI
552 * @return int Limit to use for DB (not including extra row to see if at end)
554 protected function getDBLimit( $uiLimit, $uiOffset ) {
555 $maxResults = $this->getMaxResults();
556 if ( $this->getConfig()->get( 'MiserMode' ) ) {
557 $limit = min( $uiLimit +
1, $maxResults - $uiOffset );
558 return max( $limit, 0 );
565 * Get max number of results we can return in miser mode.
567 * Most QueryPage subclasses use inefficient paging, so limit the max amount we return
568 * This matters for uncached query pages that might otherwise accept an offset of 3 million
573 protected function getMaxResults() {
574 // Max of 10000, unless we store more than 10000 in query cache.
575 return max( $this->getConfig()->get( 'QueryCacheLimit' ), 10000 );
579 * This is the actual workhorse. It does everything needed to make a
580 * real, honest-to-gosh query page.
583 public function execute( $par ) {
584 $user = $this->getUser();
585 if ( !$this->userCanExecute( $user ) ) {
586 $this->displayRestrictionError();
591 $this->outputHeader();
593 $out = $this->getOutput();
595 if ( $this->isCached() && !$this->isCacheable() ) {
596 $out->addWikiMsg( 'querypage-disabled' );
600 $out->setSyndicated( $this->isSyndicated() );
602 if ( $this->limit
== 0 && $this->offset
== 0 ) {
603 list( $this->limit
, $this->offset
) = $this->getLimitOffset();
605 $dbLimit = $this->getDBLimit( $this->limit
, $this->offset
);
606 // @todo Use doQuery()
607 if ( !$this->isCached() ) {
608 # select one extra row for navigation
609 $res = $this->reallyDoQuery( $dbLimit, $this->offset
);
611 # Get the cached result, select one extra row for navigation
612 $res = $this->fetchFromCache( $dbLimit, $this->offset
);
613 if ( !$this->listoutput
) {
614 # Fetch the timestamp of this update
615 $ts = $this->getCachedTimestamp();
616 $lang = $this->getLanguage();
617 $maxResults = $lang->formatNum( $this->getConfig()->get( 'QueryCacheLimit' ) );
620 $updated = $lang->userTimeAndDate( $ts, $user );
621 $updateddate = $lang->userDate( $ts, $user );
622 $updatedtime = $lang->userTime( $ts, $user );
623 $out->addMeta( 'Data-Cache-Time', $ts );
624 $out->addJsConfigVars( 'dataCacheTime', $ts );
625 $out->addWikiMsg( 'perfcachedts', $updated, $updateddate, $updatedtime, $maxResults );
627 $out->addWikiMsg( 'perfcached', $maxResults );
630 # If updates on this page have been disabled, let the user know
631 # that the data set won't be refreshed for now
632 if ( is_array( $this->getConfig()->get( 'DisableQueryPageUpdate' ) )
633 && in_array( $this->getName(), $this->getConfig()->get( 'DisableQueryPageUpdate' ) )
636 "<div class=\"mw-querypage-no-updates\">\n$1\n</div>",
637 'querypage-no-updates'
643 $this->numRows
= $res->numRows();
645 $dbr = $this->getRecacheDB();
646 $this->preprocessResults( $dbr, $res );
648 $out->addHTML( Xml
::openElement( 'div', [ 'class' => 'mw-spcontent' ] ) );
650 # Top header and navigation
651 if ( $this->shownavigation
) {
652 $out->addHTML( $this->getPageHeader() );
653 if ( $this->numRows
> 0 ) {
654 $out->addHTML( $this->msg( 'showingresultsinrange' )->numParams(
655 min( $this->numRows
, $this->limit
), # do not show the one extra row, if exist
656 $this->offset +
1, ( min( $this->numRows
, $this->limit
) +
$this->offset
) )->parseAsBlock() );
657 # Disable the "next" link when we reach the end
658 $miserMaxResults = $this->getConfig()->get( 'MiserMode' )
659 && ( $this->offset +
$this->limit
>= $this->getMaxResults() );
660 $atEnd = ( $this->numRows
<= $this->limit
) ||
$miserMaxResults;
661 $paging = $this->getLanguage()->viewPrevNext( $this->getPageTitle( $par ), $this->offset
,
662 $this->limit
, $this->linkParameters(), $atEnd );
663 $out->addHTML( '<p>' . $paging . '</p>' );
665 # No results to show, so don't bother with "showing X of Y" etc.
666 # -- just let the user know and give up now
667 $this->showEmptyText();
668 $out->addHTML( Xml
::closeElement( 'div' ) );
673 # The actual results; specialist subclasses will want to handle this
674 # with more than a straight list, so we hand them the info, plus
675 # an OutputPage, and let them get on with it
676 $this->outputResults( $out,
678 $dbr, # Should use a ResultWrapper for this
680 min( $this->numRows
, $this->limit
), # do not format the one extra row, if exist
683 # Repeat the paging links at the bottom
684 if ( $this->shownavigation
) {
685 $out->addHTML( '<p>' . $paging . '</p>' );
688 $out->addHTML( Xml
::closeElement( 'div' ) );
692 * Format and output report results using the given information plus
695 * @param OutputPage $out OutputPage to print to
696 * @param Skin $skin User skin to use
697 * @param IDatabase $dbr Database (read) connection to use
698 * @param IResultWrapper $res Result pointer
699 * @param int $num Number of available result rows
700 * @param int $offset Paging offset
702 protected function outputResults( $out, $skin, $dbr, $res, $num, $offset ) {
705 if ( !$this->listoutput
) {
706 $html[] = $this->openList( $offset );
709 # $res might contain the whole 1,000 rows, so we read up to
710 # $num [should update this to use a Pager]
711 for ( $i = 0; $i < $num && $row = $res->fetchObject(); $i++
) {
712 $line = $this->formatResult( $skin, $row );
714 $html[] = $this->listoutput
716 : "<li>{$line}</li>\n";
720 # Flush the final result
721 if ( $this->tryLastResult() ) {
723 $line = $this->formatResult( $skin, $row );
725 $html[] = $this->listoutput
727 : "<li>{$line}</li>\n";
731 if ( !$this->listoutput
) {
732 $html[] = $this->closeList();
735 $html = $this->listoutput
736 ? MediaWikiServices
::getInstance()->getContentLanguage()->listToText( $html )
737 : implode( '', $html );
739 $out->addHTML( $html );
747 function openList( $offset ) {
748 return "\n<ol start='" . ( $offset +
1 ) . "' class='special'>\n";
754 function closeList() {
759 * Do any necessary preprocessing of the result object.
760 * @param IDatabase $db
761 * @param IResultWrapper $res
763 function preprocessResults( $db, $res ) {
767 * Creates a new LinkBatch object, adds all pages from the passed ResultWrapper (MUST include
768 * title and optional the namespace field) and executes the batch. This operation will pre-cache
769 * LinkCache information like page existence and information for stub color and redirect hints.
771 * @param IResultWrapper $res The ResultWrapper object to process. Needs to include the title
772 * field and namespace field, if the $ns parameter isn't set.
773 * @param null $ns Use this namespace for the given titles in the ResultWrapper object,
774 * instead of the namespace value of $res.
776 protected function executeLBFromResultWrapper( IResultWrapper
$res, $ns = null ) {
777 if ( !$res->numRows() ) {
781 $batch = new LinkBatch
;
782 foreach ( $res as $row ) {
783 $batch->add( $ns ??
$row->namespace, $row->title
);