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