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
;
26 use Wikimedia\Rdbms\DBError
;
29 * This is a class for doing query pages; since they're almost all the same,
30 * we factor out some of the functionality into a superclass, and let
31 * subclasses derive from it.
32 * @ingroup SpecialPage
34 abstract class QueryPage
extends SpecialPage
{
35 /** @var bool Whether or not we want plain listoutput rather than an ordered list */
36 protected $listoutput = false;
38 /** @var int The offset and limit in use, as passed to the query() function */
39 protected $offset = 0;
45 * The number of rows returned by the query. Reading this variable
46 * only makes sense in functions that are run after the query has been
47 * done, such as preprocessResults() and formatRow().
51 protected $cachedTimestamp = null;
54 * Whether to show prev/next links
56 protected $shownavigation = true;
59 * Get a list of query page classes and their associated special pages,
60 * for periodic updates.
62 * DO NOT CHANGE THIS LIST without testing that
63 * maintenance/updateSpecialPages.php still works.
66 public static function getPages() {
70 // QueryPage subclass, Special page name
72 [ 'AncientPagesPage', 'Ancientpages' ],
73 [ 'BrokenRedirectsPage', 'BrokenRedirects' ],
74 [ 'DeadendPagesPage', 'Deadendpages' ],
75 [ 'DoubleRedirectsPage', 'DoubleRedirects' ],
76 [ 'FileDuplicateSearchPage', 'FileDuplicateSearch' ],
77 [ 'ListDuplicatedFilesPage', 'ListDuplicatedFiles' ],
78 [ 'LinkSearchPage', 'LinkSearch' ],
79 [ 'ListredirectsPage', 'Listredirects' ],
80 [ 'LonelyPagesPage', 'Lonelypages' ],
81 [ 'LongPagesPage', 'Longpages' ],
82 [ 'MediaStatisticsPage', 'MediaStatistics' ],
83 [ 'MIMEsearchPage', 'MIMEsearch' ],
84 [ 'MostcategoriesPage', 'Mostcategories' ],
85 [ 'MostimagesPage', 'Mostimages' ],
86 [ 'MostinterwikisPage', 'Mostinterwikis' ],
87 [ 'MostlinkedCategoriesPage', 'Mostlinkedcategories' ],
88 [ 'MostlinkedTemplatesPage', 'Mostlinkedtemplates' ],
89 [ 'MostlinkedPage', 'Mostlinked' ],
90 [ 'MostrevisionsPage', 'Mostrevisions' ],
91 [ 'FewestrevisionsPage', 'Fewestrevisions' ],
92 [ 'ShortPagesPage', 'Shortpages' ],
93 [ 'UncategorizedCategoriesPage', 'Uncategorizedcategories' ],
94 [ 'UncategorizedPagesPage', 'Uncategorizedpages' ],
95 [ 'UncategorizedImagesPage', 'Uncategorizedimages' ],
96 [ 'UncategorizedTemplatesPage', 'Uncategorizedtemplates' ],
97 [ 'UnusedCategoriesPage', 'Unusedcategories' ],
98 [ 'UnusedimagesPage', 'Unusedimages' ],
99 [ 'WantedCategoriesPage', 'Wantedcategories' ],
100 [ 'WantedFilesPage', 'Wantedfiles' ],
101 [ 'WantedPagesPage', 'Wantedpages' ],
102 [ 'WantedTemplatesPage', 'Wantedtemplates' ],
103 [ 'UnwatchedpagesPage', 'Unwatchedpages' ],
104 [ 'UnusedtemplatesPage', 'Unusedtemplates' ],
105 [ 'WithoutInterwikiPage', 'Withoutinterwiki' ],
107 Hooks
::run( 'wgQueryPages', [ &$qp ] );
114 * A mutator for $this->listoutput;
118 function setListoutput( $bool ) {
119 $this->listoutput
= $bool;
123 * Subclasses return an SQL query here, formatted as an array with the
125 * tables => Table(s) for passing to Database::select()
126 * fields => Field(s) for passing to Database::select(), may be *
127 * conds => WHERE conditions
129 * join_conds => JOIN conditions
131 * Note that the query itself should return the following three columns:
132 * 'namespace', 'title', and 'value'. 'value' is used for sorting.
134 * These may be stored in the querycache table for expensive queries,
135 * and that cached data will be returned sometimes, so the presence of
136 * extra fields can't be relied upon. The cached 'value' column will be
137 * an integer; non-numeric values are useful only for sorting the
138 * initial query (except if they're timestamps, see usesTimestamps()).
140 * Don't include an ORDER or LIMIT clause, they will be added.
142 * If this function is not overridden or returns something other than
143 * an array, getSQL() will be used instead. This is for backwards
144 * compatibility only and is strongly deprecated.
148 public function getQueryInfo() {
153 * For back-compat, subclasses may return a raw SQL query here, as a string.
154 * This is strongly deprecated; getQueryInfo() should be overridden instead.
155 * @throws MWException
159 /* Implement getQueryInfo() instead */
160 throw new MWException( "Bug in a QueryPage: doesn't implement getQueryInfo() nor "
161 . "getQuery() properly" );
165 * Subclasses return an array of fields to order by here. Don't append
166 * DESC to the field names, that'll be done automatically if
167 * sortDescending() returns true.
171 function getOrderFields() {
176 * Does this query return timestamps rather than integers in its
177 * 'value' field? If true, this class will convert 'value' to a
178 * UNIX timestamp for caching.
179 * NOTE: formatRow() may get timestamps in TS_MW (mysql), TS_DB (pgsql)
180 * or TS_UNIX (querycache) format, so be sure to always run them
181 * through wfTimestamp()
185 public function usesTimestamps() {
190 * Override to sort by increasing values
194 function sortDescending() {
199 * Is this query expensive (for some definition of expensive)? Then we
200 * don't let it run in miser mode. $wgDisableQueryPages causes all query
201 * pages to be declared expensive. Some query pages are always expensive.
205 public function isExpensive() {
206 return $this->getConfig()->get( 'DisableQueryPages' );
210 * Is the output of this query cacheable? Non-cacheable expensive pages
211 * will be disabled in miser mode and will not have their results written
212 * to the querycache table.
216 public function isCacheable() {
221 * Whether or not the output of the page in question is retrieved from
222 * the database cache.
226 public function isCached() {
227 return $this->isExpensive() && $this->getConfig()->get( 'MiserMode' );
231 * Sometime we don't want to build rss / atom feeds.
235 function isSyndicated() {
240 * Formats the results of the query for display. The skin is the current
241 * skin; you can use it for making links. The result is a single row of
242 * result data. You should be able to grab SQL results off of it.
243 * If the function returns false, the line output will be skipped.
245 * @param object $result Result row
246 * @return string|bool String or false to skip
248 abstract function formatResult( $skin, $result );
251 * The content returned by this function will be output before any result
255 function getPageHeader() {
260 * Outputs some kind of an informative message (via OutputPage) to let the
261 * user know that the query returned nothing and thus there's nothing to
266 protected function showEmptyText() {
267 $this->getOutput()->addWikiMsg( 'specialpage-empty' );
271 * If using extra form wheely-dealies, return a set of parameters here
272 * as an associative array. They will be encoded and added to the paging
273 * links (prev/next/lengths).
277 function linkParameters() {
282 * Some special pages (for example SpecialListusers used to) might not return the
283 * current object formatted, but return the previous one instead.
284 * Setting this to return true will ensure formatResult() is called
285 * one more time to make sure that the very last result is formatted
288 * @deprecated since 1.27
292 function tryLastResult() {
297 * Clear the cache and save new results
299 * @param int|bool $limit Limit for SQL statement
300 * @param bool $ignoreErrors Whether to ignore database errors
301 * @throws DBError|Exception
304 public function recache( $limit, $ignoreErrors = true ) {
305 if ( !$this->isCacheable() ) {
309 $fname = static::class . '::recache';
310 $dbw = wfGetDB( DB_MASTER
);
317 $res = $this->reallyDoQuery( $limit, false );
320 $num = $res->numRows();
323 foreach ( $res as $row ) {
324 if ( isset( $row->value
) ) {
325 if ( $this->usesTimestamps() ) {
326 $value = wfTimestamp( TS_UNIX
,
329 $value = intval( $row->value
); // T16414
336 'qc_type' => $this->getName(),
337 'qc_namespace' => $row->namespace,
338 'qc_title' => $row->title
,
343 $dbw->doAtomicSection(
345 function ( IDatabase
$dbw, $fname ) use ( $vals ) {
346 # Clear out any old cached data
347 $dbw->delete( 'querycache',
348 [ 'qc_type' => $this->getName() ],
351 # Save results into the querycache table on the master
352 if ( count( $vals ) ) {
353 $dbw->insert( 'querycache', $vals, $fname );
355 # Update the querycache_info record for the page
356 $dbw->delete( 'querycache_info',
357 [ 'qci_type' => $this->getName() ],
360 $dbw->insert( 'querycache_info',
361 [ 'qci_type' => $this->getName(),
362 'qci_timestamp' => $dbw->timestamp() ],
368 } catch ( DBError
$e ) {
369 if ( !$ignoreErrors ) {
370 throw $e; // report query error
372 $num = false; // set result to false to indicate error
379 * Get a DB connection to be used for slow recache queries
382 function getRecacheDB() {
383 return wfGetDB( DB_REPLICA
, [ $this->getName(), 'QueryPage::recache', 'vslow' ] );
387 * Run the query and return the result
388 * @param int|bool $limit Numerical limit or false for no limit
389 * @param int|bool $offset Numerical offset or false for no offset
390 * @return ResultWrapper
393 public function reallyDoQuery( $limit, $offset = false ) {
394 $fname = static::class . '::reallyDoQuery';
395 $dbr = $this->getRecacheDB();
396 $query = $this->getQueryInfo();
397 $order = $this->getOrderFields();
399 if ( $this->sortDescending() ) {
400 foreach ( $order as &$field ) {
405 if ( is_array( $query ) ) {
406 $tables = isset( $query['tables'] ) ?
(array)$query['tables'] : [];
407 $fields = isset( $query['fields'] ) ?
(array)$query['fields'] : [];
408 $conds = isset( $query['conds'] ) ?
(array)$query['conds'] : [];
409 $options = isset( $query['options'] ) ?
(array)$query['options'] : [];
410 $join_conds = isset( $query['join_conds'] ) ?
(array)$query['join_conds'] : [];
413 $options['ORDER BY'] = $order;
416 if ( $limit !== false ) {
417 $options['LIMIT'] = intval( $limit );
420 if ( $offset !== false ) {
421 $options['OFFSET'] = intval( $offset );
424 $res = $dbr->select( $tables, $fields, $conds, $fname,
425 $options, $join_conds
428 // Old-fashioned raw SQL style, deprecated
429 $sql = $this->getSQL();
430 $sql .= ' ORDER BY ' . implode( ', ', $order );
431 $sql = $dbr->limitResult( $sql, $limit, $offset );
432 $res = $dbr->query( $sql, $fname );
439 * Somewhat deprecated, you probably want to be using execute()
440 * @param int|bool $offset
441 * @param int|bool $limit
442 * @return ResultWrapper
444 public function doQuery( $offset = false, $limit = false ) {
445 if ( $this->isCached() && $this->isCacheable() ) {
446 return $this->fetchFromCache( $limit, $offset );
448 return $this->reallyDoQuery( $limit, $offset );
453 * Fetch the query results from the query cache
454 * @param int|bool $limit Numerical limit or false for no limit
455 * @param int|bool $offset Numerical offset or false for no offset
456 * @return ResultWrapper
459 public function fetchFromCache( $limit, $offset = false ) {
460 $dbr = wfGetDB( DB_REPLICA
);
463 if ( $limit !== false ) {
464 $options['LIMIT'] = intval( $limit );
467 if ( $offset !== false ) {
468 $options['OFFSET'] = intval( $offset );
471 $order = $this->getCacheOrderFields();
472 if ( $this->sortDescending() ) {
473 foreach ( $order as &$field ) {
478 $options['ORDER BY'] = $order;
481 return $dbr->select( 'querycache',
483 'namespace' => 'qc_namespace',
484 'title' => 'qc_title',
485 'value' => 'qc_value' ],
486 [ 'qc_type' => $this->getName() ],
493 * Return the order fields for fetchFromCache. Default is to always use
494 * "ORDER BY value" which was the default prior to this function.
498 function getCacheOrderFields() {
502 public function getCachedTimestamp() {
503 if ( is_null( $this->cachedTimestamp
) ) {
504 $dbr = wfGetDB( DB_REPLICA
);
505 $fname = static::class . '::getCachedTimestamp';
506 $this->cachedTimestamp
= $dbr->selectField( 'querycache_info', 'qci_timestamp',
507 [ 'qci_type' => $this->getName() ], $fname );
509 return $this->cachedTimestamp
;
513 * Returns limit and offset, as returned by $this->getRequest()->getLimitOffset().
514 * Subclasses may override this to further restrict or modify limit and offset.
516 * @note Restricts the offset parameter, as most query pages have inefficient paging
518 * Its generally expected that the returned limit will not be 0, and the returned
519 * offset will be less than the max results.
522 * @return int[] list( $limit, $offset )
524 protected function getLimitOffset() {
525 list( $limit, $offset ) = $this->getRequest()->getLimitOffset();
526 if ( $this->getConfig()->get( 'MiserMode' ) ) {
527 $maxResults = $this->getMaxResults();
528 // Can't display more than max results on a page
529 $limit = min( $limit, $maxResults );
530 // Can't skip over more than the end of $maxResults
531 $offset = min( $offset, $maxResults +
1 );
533 return [ $limit, $offset ];
537 * What is limit to fetch from DB
539 * Used to make it appear the DB stores less results then it actually does
540 * @param int $uiLimit Limit from UI
541 * @param int $uiOffset Offset from UI
542 * @return int Limit to use for DB (not including extra row to see if at end)
544 protected function getDBLimit( $uiLimit, $uiOffset ) {
545 $maxResults = $this->getMaxResults();
546 if ( $this->getConfig()->get( 'MiserMode' ) ) {
547 $limit = min( $uiLimit +
1, $maxResults - $uiOffset );
548 return max( $limit, 0 );
555 * Get max number of results we can return in miser mode.
557 * Most QueryPage subclasses use inefficient paging, so limit the max amount we return
558 * This matters for uncached query pages that might otherwise accept an offset of 3 million
563 protected function getMaxResults() {
564 // Max of 10000, unless we store more than 10000 in query cache.
565 return max( $this->getConfig()->get( 'QueryCacheLimit' ), 10000 );
569 * This is the actual workhorse. It does everything needed to make a
570 * real, honest-to-gosh query page.
573 public function execute( $par ) {
574 $user = $this->getUser();
575 if ( !$this->userCanExecute( $user ) ) {
576 $this->displayRestrictionError();
581 $this->outputHeader();
583 $out = $this->getOutput();
585 if ( $this->isCached() && !$this->isCacheable() ) {
586 $out->addWikiMsg( 'querypage-disabled' );
590 $out->setSyndicated( $this->isSyndicated() );
592 if ( $this->limit
== 0 && $this->offset
== 0 ) {
593 list( $this->limit
, $this->offset
) = $this->getLimitOffset();
595 $dbLimit = $this->getDBLimit( $this->limit
, $this->offset
);
596 // @todo Use doQuery()
597 if ( !$this->isCached() ) {
598 # select one extra row for navigation
599 $res = $this->reallyDoQuery( $dbLimit, $this->offset
);
601 # Get the cached result, select one extra row for navigation
602 $res = $this->fetchFromCache( $dbLimit, $this->offset
);
603 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
);