Debian Codegraph @

includes/specialpage/QueryPage.php

raw symbols SCIP
1 <?php
2 /**
3 * Base code for "query" special pages.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup SpecialPage
22 */
23
24 namespace MediaWiki\SpecialPage;
25
26 use Exception;
27 use MediaWiki\Cache\LinkBatchFactory;
28 use MediaWiki\Config\Config;
29 use MediaWiki\HookContainer\HookRunner;
30 use MediaWiki\Linker\LinkTarget;
31 use MediaWiki\MainConfigNames;
32 use MediaWiki\MediaWikiServices;
33 use MediaWiki\Output\OutputPage;
34 use MediaWiki\Specials\SpecialAncientPages;
35 use MediaWiki\Specials\SpecialBrokenRedirects;
36 use MediaWiki\Specials\SpecialDeadendPages;
37 use MediaWiki\Specials\SpecialDoubleRedirects;
38 use MediaWiki\Specials\SpecialFewestRevisions;
39 use MediaWiki\Specials\SpecialLinkSearch;
40 use MediaWiki\Specials\SpecialListDuplicatedFiles;
41 use MediaWiki\Specials\SpecialListRedirects;
42 use MediaWiki\Specials\SpecialLonelyPages;
43 use MediaWiki\Specials\SpecialLongPages;
44 use MediaWiki\Specials\SpecialMediaStatistics;
45 use MediaWiki\Specials\SpecialMIMESearch;
46 use MediaWiki\Specials\SpecialMostCategories;
47 use MediaWiki\Specials\SpecialMostImages;
48 use MediaWiki\Specials\SpecialMostInterwikis;
49 use MediaWiki\Specials\SpecialMostLinked;
50 use MediaWiki\Specials\SpecialMostLinkedCategories;
51 use MediaWiki\Specials\SpecialMostLinkedTemplates;
52 use MediaWiki\Specials\SpecialMostRevisions;
53 use MediaWiki\Specials\SpecialShortPages;
54 use MediaWiki\Specials\SpecialUncategorizedCategories;
55 use MediaWiki\Specials\SpecialUncategorizedImages;
56 use MediaWiki\Specials\SpecialUncategorizedPages;
57 use MediaWiki\Specials\SpecialUncategorizedTemplates;
58 use MediaWiki\Specials\SpecialUnusedCategories;
59 use MediaWiki\Specials\SpecialUnusedImages;
60 use MediaWiki\Specials\SpecialUnusedTemplates;
61 use MediaWiki\Specials\SpecialUnwatchedPages;
62 use MediaWiki\Specials\SpecialWantedCategories;
63 use MediaWiki\Specials\SpecialWantedFiles;
64 use MediaWiki\Specials\SpecialWantedPages;
65 use MediaWiki\Specials\SpecialWantedTemplates;
66 use MediaWiki\Specials\SpecialWithoutInterwiki;
67 use MediaWiki\Xml\Xml;
68 use Skin;
69 use stdClass;
70 use Wikimedia\Rdbms\DBError;
71 use Wikimedia\Rdbms\IConnectionProvider;
72 use Wikimedia\Rdbms\IDatabase;
73 use Wikimedia\Rdbms\ILoadBalancer;
74 use Wikimedia\Rdbms\IReadableDatabase;
75 use Wikimedia\Rdbms\IResultWrapper;
76 use Wikimedia\Rdbms\SelectQueryBuilder;
77
78 /**
79 * This is a class for doing query pages; since they're almost all the same,
80 * we factor out some of the functionality into a superclass, and let
81 * subclasses derive from it.
82 *
83 * @stable to extend
84 *
85 * @ingroup SpecialPage
86 */
87 abstract class QueryPage extends SpecialPage {
88 /** @var bool Whether or not we want plain listoutput rather than an ordered list */
89 protected $listoutput = false;
90
91 /** @var int The offset and limit in use, as passed to the query() function */
92 protected $offset = 0;
93
94 /** @var int */
95 protected $limit = 0;
96
97 /**
98 * The number of rows returned by the query. Reading this variable
99 * only makes sense in functions that are run after the query has been
100 * done, such as preprocessResults() and formatRow().
101 *
102 * @var int
103 */
104 protected $numRows;
105
106 /**
107 * @var string|null|false
108 */
109 protected $cachedTimestamp = null;
110
111 /**
112 * @var bool Whether to show prev/next links
113 */
114 protected $shownavigation = true;
115
116 /** @var ILoadBalancer|null */
117 private $loadBalancer = null;
118
119 /** @var IConnectionProvider|null */
120 private $databaseProvider = null;
121
122 /** @var LinkBatchFactory|null */
123 private $linkBatchFactory = null;
124
125 /**
126 * Get a list of query page classes and their associated special pages,
127 * for periodic updates.
128 *
129 * DO NOT CHANGE THIS LIST without testing that
130 * maintenance/updateSpecialPages.php still works.
131 *
132 * @return array[] List of [ string $class, string $specialPageName, ?int $limit (optional) ].
133 * Limit defaults to $wgQueryCacheLimit if not given.
134 */
135 public static function getPages() {
136 static $qp = null;
137
138 if ( $qp === null ) {
139 $qp = [
140 [ SpecialAncientPages::class, 'Ancientpages' ],
141 [ SpecialBrokenRedirects::class, 'BrokenRedirects' ],
142 [ SpecialDeadendPages::class, 'Deadendpages' ],
143 [ SpecialDoubleRedirects::class, 'DoubleRedirects' ],
144 [ SpecialListDuplicatedFiles::class, 'ListDuplicatedFiles' ],
145 [ SpecialLinkSearch::class, 'LinkSearch' ],
146 [ SpecialListRedirects::class, 'Listredirects' ],
147 [ SpecialLonelyPages::class, 'Lonelypages' ],
148 [ SpecialLongPages::class, 'Longpages' ],
149 [ SpecialMediaStatistics::class, 'MediaStatistics', SpecialMediaStatistics::MAX_LIMIT ],
150 [ SpecialMIMESearch::class, 'MIMEsearch' ],
151 [ SpecialMostCategories::class, 'Mostcategories' ],
152 [ SpecialMostImages::class, 'Mostimages' ],
153 [ SpecialMostInterwikis::class, 'Mostinterwikis' ],
154 [ SpecialMostLinkedCategories::class, 'Mostlinkedcategories' ],
155 [ SpecialMostLinkedTemplates::class, 'Mostlinkedtemplates' ],
156 [ SpecialMostLinked::class, 'Mostlinked' ],
157 [ SpecialMostRevisions::class, 'Mostrevisions' ],
158 [ SpecialFewestRevisions::class, 'Fewestrevisions' ],
159 [ SpecialShortPages::class, 'Shortpages' ],
160 [ SpecialUncategorizedCategories::class, 'Uncategorizedcategories' ],
161 [ SpecialUncategorizedPages::class, 'Uncategorizedpages' ],
162 [ SpecialUncategorizedImages::class, 'Uncategorizedimages' ],
163 [ SpecialUncategorizedTemplates::class, 'Uncategorizedtemplates' ],
164 [ SpecialUnusedCategories::class, 'Unusedcategories' ],
165 [ SpecialUnusedImages::class, 'Unusedimages' ],
166 [ SpecialWantedCategories::class, 'Wantedcategories' ],
167 [ SpecialWantedFiles::class, 'Wantedfiles' ],
168 [ SpecialWantedPages::class, 'Wantedpages' ],
169 [ SpecialWantedTemplates::class, 'Wantedtemplates' ],
170 [ SpecialUnwatchedPages::class, 'Unwatchedpages' ],
171 [ SpecialUnusedTemplates::class, 'Unusedtemplates' ],
172 [ SpecialWithoutInterwiki::class, 'Withoutinterwiki' ],
173 ];
174 ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )->onWgQueryPages( $qp );
175 }
176
177 return $qp;
178 }
179
180 /**
181 * @since 1.36
182 * @param LinkBatchFactory $linkBatchFactory
183 */
184 final protected function setLinkBatchFactory( LinkBatchFactory $linkBatchFactory ) {
185 $this->linkBatchFactory = $linkBatchFactory;
186 }
187
188 /**
189 * @since 1.36
190 * @return LinkBatchFactory
191 */
192 final protected function getLinkBatchFactory(): LinkBatchFactory {
193 if ( $this->linkBatchFactory === null ) {
194 // Fallback if not provided
195 // TODO Change to wfWarn in a future release
196 $this->linkBatchFactory = MediaWikiServices::getInstance()->getLinkBatchFactory();
197 }
198 return $this->linkBatchFactory;
199 }
200
201 /**
202 * Get a list of disabled query pages and their run mode
203 * @param Config $config
204 * @return string[]
205 */
206 public static function getDisabledQueryPages( Config $config ) {
207 $disableQueryPageUpdate = $config->get( MainConfigNames::DisableQueryPageUpdate );
208
209 if ( !is_array( $disableQueryPageUpdate ) ) {
210 return [];
211 }
212
213 $pages = [];
214 foreach ( $disableQueryPageUpdate as $name => $runMode ) {
215 if ( is_int( $name ) ) {
216 // The run mode may be omitted
217 $pages[$runMode] = 'disabled';
218 } else {
219 $pages[$name] = $runMode;
220 }
221 }
222 return $pages;
223 }
224
225 /**
226 * A mutator for $this->listoutput;
227 *
228 * @param bool $bool
229 */
230 protected function setListoutput( $bool ) {
231 $this->listoutput = $bool;
232 }
233
234 /**
235 * Subclasses return an SQL query here, formatted as an array with the
236 * following keys:
237 * tables => Table(s) for passing to Database::select()
238 * fields => Field(s) for passing to Database::select(), may be *
239 * conds => WHERE conditions
240 * options => options
241 * join_conds => JOIN conditions
242 *
243 * Note that the query itself should return the following three columns:
244 * 'namespace', 'title', and 'value'. 'value' is used for sorting.
245 *
246 * These may be stored in the querycache table for expensive queries,
247 * and that cached data will be returned sometimes, so the presence of
248 * extra fields can't be relied upon. The cached 'value' column will be
249 * an integer; non-numeric values are useful only for sorting the
250 * initial query (except if they're timestamps, see usesTimestamps()).
251 *
252 * Don't include an ORDER or LIMIT clause, they will be added.
253 *
254 * @return array
255 * @since 1.18, abstract since 1.43
256 */
257 abstract public function getQueryInfo();
258
259 /**
260 * Subclasses return an array of fields to order by here. Don't append
261 * DESC to the field names, that'll be done automatically if
262 * sortDescending() returns true.
263 * @stable to override
264 * @return string[]
265 * @since 1.18
266 */
267 protected function getOrderFields() {
268 return [ 'value' ];
269 }
270
271 /**
272 * Does this query return timestamps rather than integers in its
273 * 'value' field? If true, this class will convert 'value' to a
274 * UNIX timestamp for caching.
275 * NOTE: formatRow() may get timestamps in TS_MW (mysql), TS_DB (pgsql)
276 * or TS_UNIX (querycache) format, so be sure to always run them
277 * through wfTimestamp()
278 * @stable to override
279 * @return bool
280 * @since 1.18
281 */
282 public function usesTimestamps() {
283 return false;
284 }
285
286 /**
287 * Override to sort by increasing values
288 *
289 * @stable to override
290 * @return bool
291 */
292 protected function sortDescending() {
293 return true;
294 }
295
296 /**
297 * Should this query page only be updated offline on large wikis?
298 *
299 * If the query for this page is considered too expensive to run on-demand
300 * for large wikis (e.g. every time the special page is viewed), then
301 * implement this as returning true.
302 *
303 * "Large wikis" are those that enable $wgMiserMode. The value of
304 * ::isExpensive() has no effect by default when $wgMiserMode is off.
305 *
306 * It is expected that such large wikis, periodically run the
307 * UpdateSpecialPages maintenance script to update these query pages.
308 *
309 * By enabling $wgDisableQueryPages, all query pages will be considered
310 * as expensive and updated offline only, even query pages that do not
311 * mark themselves as expensive.
312 *
313 * @stable to override
314 * @return bool
315 */
316 public function isExpensive() {
317 return $this->getConfig()->get( MainConfigNames::DisableQueryPages );
318 }
319
320 /**
321 * Is the output of this query cacheable? Non-cacheable expensive pages
322 * will be disabled in miser mode and will not have their results written
323 * to the querycache table.
324 * @stable to override
325 * @return bool
326 * @since 1.18
327 */
328 public function isCacheable() {
329 return true;
330 }
331
332 /**
333 * Whether or not the output of the page in question is retrieved from
334 * the database cache.
335 *
336 * @stable to override
337 * @return bool
338 */
339 public function isCached() {
340 return $this->isExpensive() && $this->getConfig()->get( MainConfigNames::MiserMode );
341 }
342
343 /**
344 * Sometimes we don't want to build rss / atom feeds.
345 *
346 * @stable to override
347 * @return bool
348 */
349 public function isSyndicated() {
350 return true;
351 }
352
353 /**
354 * Formats the results of the query for display. The skin is the current
355 * skin; you can use it for making links. The result is a single row of
356 * result data. You should be able to grab SQL results from it.
357 * If the function returns false, the line output will be skipped.
358 * @param Skin $skin
359 * @param stdClass $result Result row
360 * @return string|bool String or false to skip
361 */
362 abstract protected function formatResult( $skin, $result );
363
364 /**
365 * The content returned by this function will be output before any result
366 *
367 * @stable to override
368 * @return string
369 */
370 protected function getPageHeader() {
371 return '';
372 }
373
374 /**
375 * Outputs some kind of an informative message (via OutputPage) to let the
376 * user know that the query returned nothing and thus there's nothing to
377 * show.
378 *
379 * @since 1.26
380 */
381 protected function showEmptyText() {
382 $this->getOutput()->addWikiMsg( 'specialpage-empty' );
383 }
384
385 /**
386 * If using extra form wheely-dealies, return a set of parameters here
387 * as an associative array. They will be encoded and added to the paging
388 * links (prev/next/lengths).
389 *
390 * @stable to override
391 * @return array
392 */
393 protected function linkParameters() {
394 return [];
395 }
396
397 /**
398 * Clear the cache and save new results
399 *
400 * @stable to override
401 *
402 * @param int|false $limit Limit for SQL statement or false for no limit
403 * @param bool $unused Unused since 1.43, kept for backwards-compatibility
404 * @throws DBError|Exception
405 * @return bool|int
406 */
407 public function recache( $limit, $unused = true ) {
408 if ( !$this->isCacheable() ) {
409 return 0;
410 }
411
412 $fname = static::class . '::recache';
413 $dbw = $this->getDatabaseProvider()->getPrimaryDatabase();
414
415 // Do query
416 $res = $this->reallyDoQuery( $limit, false );
417 $num = false;
418 if ( $res ) {
419 $num = $res->numRows();
420 // Fetch results
421 $vals = [];
422 foreach ( $res as $i => $row ) {
423 if ( isset( $row->value ) ) {
424 if ( $this->usesTimestamps() ) {
425 $value = (int)wfTimestamp( TS_UNIX, $row->value );
426 } else {
427 $value = intval( $row->value ); // T16414
428 }
429 } else {
430 $value = $i;
431 }
432
433 $vals[] = [
434 'qc_type' => $this->getName(),
435 'qc_namespace' => $row->namespace,
436 'qc_title' => $row->title,
437 'qc_value' => $value
438 ];
439 }
440
441 $dbw->doAtomicSection(
442 $fname,
443 function ( IDatabase $dbw, $fname ) use ( $vals ) {
444 // Clear out any old cached data
445 $dbw->newDeleteQueryBuilder()
446 ->deleteFrom( 'querycache' )
447 ->where( [ 'qc_type' => $this->getName() ] )
448 ->caller( $fname )->execute();
449 // Update the querycache_info record for the page
450 $dbw->newInsertQueryBuilder()
451 ->insertInto( 'querycache_info' )
452 ->row( [ 'qci_type' => $this->getName(), 'qci_timestamp' => $dbw->timestamp() ] )
453 ->onDuplicateKeyUpdate()
454 ->uniqueIndexFields( [ 'qci_type' ] )
455 ->set( [ 'qci_timestamp' => $dbw->timestamp() ] )
456 ->caller( $fname )->execute();
457 }
458 );
459 // Save results into the querycache table on the primary DB
460 if ( count( $vals ) ) {
461 foreach ( array_chunk( $vals, 500 ) as $chunk ) {
462 $dbw->newInsertQueryBuilder()
463 ->insertInto( 'querycache' )
464 ->rows( $chunk )
465 ->caller( $fname )->execute();
466 }
467 }
468 }
469
470 return $num;
471 }
472
473 /**
474 * Get a DB connection to be used for slow recache queries
475 * @stable to override
476 * @return IDatabase
477 */
478 protected function getRecacheDB() {
479 return $this->getDBLoadBalancer()
480 ->getConnection( ILoadBalancer::DB_REPLICA, 'vslow' );
481 }
482
483 /**
484 * Remove a cached result.
485 * Useful for interactive backlogs where the user can fix problems in-place.
486 * @param LinkTarget $title The page to remove.
487 * @since 1.34
488 */
489 public function delete( LinkTarget $title ) {
490 if ( $this->isCached() ) {
491 $dbw = $this->getDatabaseProvider()->getPrimaryDatabase();
492 $dbw->newDeleteQueryBuilder()
493 ->deleteFrom( 'querycache' )
494 ->where( [
495 'qc_type' => $this->getName(),
496 'qc_namespace' => $title->getNamespace(),
497 'qc_title' => $title->getDBkey(),
498 ] )
499 ->caller( __METHOD__ )->execute();
500 }
501 }
502
503 /**
504 * Remove all cached value
505 * This is needed when the page is no longer using the cache
506 * @since 1.36
507 */
508 public function deleteAllCachedData() {
509 $fname = static::class . '::' . __FUNCTION__;
510 $dbw = $this->getDatabaseProvider()->getPrimaryDatabase();
511 $dbw->newDeleteQueryBuilder()
512 ->deleteFrom( 'querycache' )
513 ->where( [ 'qc_type' => $this->getName() ] )
514 ->caller( $fname )->execute();
515 $dbw->newDeleteQueryBuilder()
516 ->deleteFrom( 'querycachetwo' )
517 ->where( [ 'qcc_type' => $this->getName() ] )
518 ->caller( $fname )->execute();
519 $dbw->newDeleteQueryBuilder()
520 ->deleteFrom( 'querycache_info' )
521 ->where( [ 'qci_type' => $this->getName() ] )
522 ->caller( $fname )->execute();
523 }
524
525 /**
526 * Run the query and return the result
527 * @stable to override
528 * @param int|false $limit Numerical limit or false for no limit
529 * @param int|false $offset Numerical offset or false for no offset
530 * @return IResultWrapper
531 * @since 1.18
532 */
533 public function reallyDoQuery( $limit, $offset = false ) {
534 $fname = static::class . '::reallyDoQuery';
535 $dbr = $this->getRecacheDB();
536 $query = $this->getQueryInfo();
537 $order = $this->getOrderFields();
538
539 if ( $this->sortDescending() ) {
540 foreach ( $order as &$field ) {
541 $field .= ' DESC';
542 }
543 }
544
545 $tables = isset( $query['tables'] ) ? (array)$query['tables'] : [];
546 $fields = isset( $query['fields'] ) ? (array)$query['fields'] : [];
547 $conds = isset( $query['conds'] ) ? (array)$query['conds'] : [];
548 $options = isset( $query['options'] ) ? (array)$query['options'] : [];
549 $join_conds = isset( $query['join_conds'] ) ? (array)$query['join_conds'] : [];
550
551 $queryBuilder = $dbr->newSelectQueryBuilder()
552 ->tables( $tables )
553 ->fields( $fields )
554 ->conds( $conds )
555 ->caller( $fname )
556 ->options( $options )
557 ->joinConds( $join_conds );
558 if ( $order ) {
559 $queryBuilder->orderBy( $order );
560 }
561
562 if ( $limit !== false ) {
563 $queryBuilder->limit( intval( $limit ) );
564 }
565
566 if ( $offset !== false ) {
567 $queryBuilder->offset( intval( $offset ) );
568 }
569
570 return $queryBuilder->fetchResultSet();
571 }
572
573 /**
574 * Somewhat deprecated, you probably want to be using execute()
575 * @param int|false $offset
576 * @param int|false $limit
577 * @return IResultWrapper
578 */
579 public function doQuery( $offset = false, $limit = false ) {
580 if ( $this->isCached() && $this->isCacheable() ) {
581 return $this->fetchFromCache( $limit, $offset );
582 } else {
583 return $this->reallyDoQuery( $limit, $offset );
584 }
585 }
586
587 /**
588 * Fetch the query results from the query cache
589 * @stable to override
590 *
591 * @param int|false $limit Numerical limit or false for no limit
592 * @param int|false $offset Numerical offset or false for no offset
593 * @return IResultWrapper
594 * @since 1.18
595 */
596 public function fetchFromCache( $limit, $offset = false ) {
597 $dbr = $this->getDatabaseProvider()->getReplicaDatabase();
598 $queryBuilder = $dbr->newSelectQueryBuilder()
599 ->select( [ 'qc_type', 'namespace' => 'qc_namespace', 'title' => 'qc_title', 'value' => 'qc_value' ] )
600 ->from( 'querycache' )
601 ->where( [ 'qc_type' => $this->getName() ] );
602
603 if ( $limit !== false ) {
604 $queryBuilder->limit( intval( $limit ) );
605 }
606
607 if ( $offset !== false ) {
608 $queryBuilder->offset( intval( $offset ) );
609 }
610
611 $order = $this->getCacheOrderFields();
612 if ( $this->sortDescending() ) {
613 $queryBuilder->orderBy( $order, SelectQueryBuilder::SORT_DESC );
614 } else {
615 $queryBuilder->orderBy( $order );
616 }
617
618 return $queryBuilder->caller( __METHOD__ )->fetchResultSet();
619 }
620
621 /**
622 * Return the order fields for fetchFromCache. Default is to always use
623 * "ORDER BY value" which was the default prior to this function.
624 * @stable to override
625 * @return array
626 * @since 1.29
627 */
628 protected function getCacheOrderFields() {
629 return [ 'value' ];
630 }
631
632 /**
633 * @return string|false
634 */
635 public function getCachedTimestamp() {
636 if ( $this->cachedTimestamp === null ) {
637 $dbr = $this->getDatabaseProvider()->getReplicaDatabase();
638 $fname = static::class . '::getCachedTimestamp';
639 $this->cachedTimestamp = $dbr->newSelectQueryBuilder()
640 ->select( 'qci_timestamp' )
641 ->from( 'querycache_info' )
642 ->where( [ 'qci_type' => $this->getName() ] )
643 ->caller( $fname )->fetchField();
644 }
645 return $this->cachedTimestamp;
646 }
647
648 /**
649 * Returns limit and offset, as returned by $this->getRequest()->getLimitOffsetForUser().
650 * Subclasses may override this to further restrict or modify limit and offset.
651 *
652 * @note Restricts the offset parameter, as most query pages have inefficient paging
653 *
654 * Its generally expected that the returned limit will not be 0, and the returned
655 * offset will be less than the max results.
656 *
657 * @since 1.26
658 * @return int[] list( $limit, $offset )
659 */
660 protected function getLimitOffset() {
661 [ $limit, $offset ] = $this->getRequest()
662 ->getLimitOffsetForUser( $this->getUser() );
663 if ( $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
664 $maxResults = $this->getMaxResults();
665 // Can't display more than max results on a page
666 $limit = min( $limit, $maxResults );
667 // Can't skip over more than the end of $maxResults
668 $offset = min( $offset, $maxResults + 1 );
669 }
670 return [ $limit, $offset ];
671 }
672
673 /**
674 * What is limit to fetch from DB
675 *
676 * Used to make it appear the DB stores less results then it actually does
677 * @param int $uiLimit Limit from UI
678 * @param int $uiOffset Offset from UI
679 * @return int Limit to use for DB (not including extra row to see if at end)
680 */
681 protected function getDBLimit( $uiLimit, $uiOffset ) {
682 $maxResults = $this->getMaxResults();
683 if ( $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
684 $limit = min( $uiLimit + 1, $maxResults - $uiOffset );
685 return max( $limit, 0 );
686 } else {
687 return $uiLimit + 1;
688 }
689 }
690
691 /**
692 * Get max number of results we can return in miser mode.
693 *
694 * Most QueryPage subclasses use inefficient paging, so limit the max amount we return
695 * This matters for uncached query pages that might otherwise accept an offset of 3 million
696 *
697 * @stable to override
698 * @since 1.27
699 * @return int
700 */
701 protected function getMaxResults() {
702 // Max of 10000, unless we store more than 10000 in query cache.
703 return max( $this->getConfig()->get( MainConfigNames::QueryCacheLimit ), 10000 );
704 }
705
706 /**
707 * This is the actual workhorse. It does everything needed to make a
708 * real, honest-to-gosh query page.
709 * @stable to override
710 * @param string|null $par
711 */
712 public function execute( $par ) {
713 $this->checkPermissions();
714
715 $this->setHeaders();
716 $this->outputHeader();
717
718 $out = $this->getOutput();
719
720 if ( $this->isCached() && !$this->isCacheable() ) {
721 $out->addWikiMsg( 'querypage-disabled' );
722 return;
723 }
724
725 $out->setSyndicated( $this->isSyndicated() );
726
727 if ( $this->limit == 0 && $this->offset == 0 ) {
728 [ $this->limit, $this->offset ] = $this->getLimitOffset();
729 }
730 $dbLimit = $this->getDBLimit( $this->limit, $this->offset );
731 // @todo Use doQuery()
732 if ( !$this->isCached() ) {
733 // select one extra row for navigation
734 $res = $this->reallyDoQuery( $dbLimit, $this->offset );
735 } else {
736 // Get the cached result, select one extra row for navigation
737 $res = $this->fetchFromCache( $dbLimit, $this->offset );
738 if ( !$this->listoutput ) {
739 // Fetch the timestamp of this update
740 $ts = $this->getCachedTimestamp();
741 $lang = $this->getLanguage();
742 $maxResults = $lang->formatNum( $this->getConfig()->get(
743 MainConfigNames::QueryCacheLimit ) );
744
745 if ( $ts ) {
746 $user = $this->getUser();
747 $updated = $lang->userTimeAndDate( $ts, $user );
748 $updateddate = $lang->userDate( $ts, $user );
749 $updatedtime = $lang->userTime( $ts, $user );
750 $out->addMeta( 'Data-Cache-Time', $ts );
751 $out->addJsConfigVars( 'dataCacheTime', $ts );
752 $out->addWikiMsg( 'perfcachedts', $updated, $updateddate, $updatedtime, $maxResults );
753 } else {
754 $out->addWikiMsg( 'perfcached', $maxResults );
755 }
756
757 // If updates on this page have been disabled, let the user know
758 // that the data set won't be refreshed for now
759 $disabledQueryPages = self::getDisabledQueryPages( $this->getConfig() );
760 if ( isset( $disabledQueryPages[$this->getName()] ) ) {
761 $runMode = $disabledQueryPages[$this->getName()];
762 if ( $runMode === 'disabled' ) {
763 $out->wrapWikiMsg(
764 "<div class=\"mw-querypage-no-updates\">\n$1\n</div>",
765 'querypage-no-updates'
766 );
767 } else {
768 // Messages used here: querypage-updates-periodical
769 $out->wrapWikiMsg(
770 "<div class=\"mw-querypage-updates-" . $runMode . "\">\n$1\n</div>",
771 'querypage-updates-' . $runMode
772 );
773 }
774 }
775 }
776 }
777
778 $this->numRows = $res->numRows();
779
780 $dbr = $this->getRecacheDB();
781 $this->preprocessResults( $dbr, $res );
782
783 $out->addHTML( Xml::openElement( 'div', [ 'class' => 'mw-spcontent' ] ) );
784
785 // Top header and navigation
786 if ( $this->shownavigation ) {
787 $out->addHTML( $this->getPageHeader() );
788 if ( $this->numRows > 0 ) {
789 $out->addHTML( $this->msg( 'showingresultsinrange' )->numParams(
790 min( $this->numRows, $this->limit ), // do not show the one extra row, if exist
791 $this->offset + 1, ( min( $this->numRows, $this->limit ) + $this->offset ) )->parseAsBlock() );
792 // Disable the "next" link when we reach the end
793 $miserMaxResults = $this->getConfig()->get( MainConfigNames::MiserMode )
794 && ( $this->offset + $this->limit >= $this->getMaxResults() );
795 $atEnd = ( $this->numRows <= $this->limit ) || $miserMaxResults;
796 $paging = $this->buildPrevNextNavigation( $this->offset,
797 $this->limit, $this->linkParameters(), $atEnd, $par );
798 $out->addHTML( '<p>' . $paging . '</p>' );
799 } else {
800 // No results to show, so don't bother with "showing X of Y" etc.
801 // -- just let the user know and give up now
802 $this->showEmptyText();
803 $out->addHTML( Xml::closeElement( 'div' ) );
804 return;
805 }
806 }
807
808 // The actual results; specialist subclasses will want to handle this
809 // with more than a straight list, so we hand them the info, plus
810 // an OutputPage, and let them get on with it
811 $this->outputResults( $out,
812 $this->getSkin(),
813 $dbr, // Should use IResultWrapper for this
814 $res,
815 min( $this->numRows, $this->limit ), // do not format the one extra row, if exist
816 $this->offset );
817
818 // Repeat the paging links at the bottom
819 if ( $this->shownavigation ) {
820 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable paging is set when used here
821 $out->addHTML( '<p>' . $paging . '</p>' );
822 }
823
824 $out->addHTML( Xml::closeElement( 'div' ) );
825 }
826
827 /**
828 * Format and output report results using the given information plus
829 * OutputPage
830 *
831 * @stable to override
832 *
833 * @param OutputPage $out OutputPage to print to
834 * @param Skin $skin User skin to use
835 * @param IReadableDatabase $dbr Database (read) connection to use
836 * @param IResultWrapper $res Result pointer
837 * @param int $num Number of available result rows
838 * @param int $offset Paging offset
839 */
840 protected function outputResults( $out, $skin, $dbr, $res, $num, $offset ) {
841 if ( $num > 0 ) {
842 $html = [];
843 if ( !$this->listoutput ) {
844 $html[] = $this->openList( $offset );
845 }
846
847 // $res might contain the whole 1,000 rows, so we read up to
848 // $num [should update this to use a Pager]
849 // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.Found
850 for ( $i = 0; $i < $num && $row = $res->fetchObject(); $i++ ) {
851 $line = $this->formatResult( $skin, $row );
852 if ( $line ) {
853 $html[] = $this->listoutput
854 ? $line
855 : "<li>{$line}</li>\n";
856 }
857 }
858
859 if ( !$this->listoutput ) {
860 $html[] = $this->closeList();
861 }
862
863 $html = $this->listoutput
864 ? $this->getContentLanguage()->listToText( $html )
865 : implode( '', $html );
866
867 $out->addHTML( $html );
868 }
869 }
870
871 /**
872 * @param int $offset
873 * @return string
874 */
875 protected function openList( $offset ) {
876 return "\n<ol start='" . ( $offset + 1 ) . "' class='special'>\n";
877 }
878
879 /**
880 * @return string
881 */
882 protected function closeList() {
883 return "</ol>\n";
884 }
885
886 /**
887 * Do any necessary preprocessing of the result object.
888 * @stable to override
889 * @param IDatabase $db
890 * @param IResultWrapper $res
891 */
892 protected function preprocessResults( $db, $res ) {
893 }
894
895 /**
896 * Creates a new LinkBatch object, adds all pages from the passed result wrapper (MUST include
897 * title and optional the namespace field) and executes the batch. This operation will pre-cache
898 * LinkCache information like page existence and information for stub color and redirect hints.
899 *
900 * @note Call self::setLinkBatchFactory from special page constructor when use
901 *
902 * @param IResultWrapper $res The result wrapper to process. Needs to include the title
903 * field and namespace field, if the $ns parameter isn't set.
904 * @param int|null $ns Use this namespace for the given titles in the result wrapper,
905 * instead of the namespace value of $res.
906 */
907 protected function executeLBFromResultWrapper( IResultWrapper $res, $ns = null ) {
908 if ( !$res->numRows() ) {
909 return;
910 }
911
912 $batch = $this->getLinkBatchFactory()->newLinkBatch();
913 foreach ( $res as $row ) {
914 $batch->add( $ns ?? (int)$row->namespace, $row->title );
915 }
916 $batch->execute();
917
918 $res->seek( 0 );
919 }
920
921 /**
922 * @since 1.36
923 * @deprecated since 1.43, use self::setDatabaseProvider
924 * @param ILoadBalancer $loadBalancer
925 */
926 final protected function setDBLoadBalancer( ILoadBalancer $loadBalancer ) {
927 $this->loadBalancer = $loadBalancer;
928 }
929
930 /**
931 * @since 1.36
932 * @deprecated since 1.43, use self::getDatabaseProvider
933 * @return ILoadBalancer
934 */
935 final protected function getDBLoadBalancer(): ILoadBalancer {
936 if ( $this->loadBalancer === null ) {
937 // Fallback if not provided
938 // TODO Change to wfWarn in a future release
939 $this->loadBalancer = MediaWikiServices::getInstance()->getDBLoadBalancer();
940 }
941 return $this->loadBalancer;
942 }
943
944 /**
945 * @since 1.41
946 * @param IConnectionProvider $databaseProvider
947 */
948 final protected function setDatabaseProvider( IConnectionProvider $databaseProvider ) {
949 $this->databaseProvider = $databaseProvider;
950 }
951
952 /**
953 * @since 1.41
954 * @return IConnectionProvider
955 */
956 final protected function getDatabaseProvider(): IConnectionProvider {
957 if ( $this->databaseProvider === null ) {
958 $this->databaseProvider = MediaWikiServices::getInstance()->getConnectionProvider();
959 }
960 return $this->databaseProvider;
961 }
962 }
963
964 /** @deprecated class alias since 1.41 */
965 class_alias( QueryPage::class, 'QueryPage' );