Merge "Improve docs for Title::getInternalURL/getCanonicalURL"
[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\MediaWikiServices;
25 use Wikimedia\Rdbms\IResultWrapper;
26 use Wikimedia\Rdbms\IDatabase;
27 use Wikimedia\Rdbms\DBError;
28
29 /**
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
34 */
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;
38
39 /** @var int The offset and limit in use, as passed to the query() function */
40 protected $offset = 0;
41
42 /** @var int */
43 protected $limit = 0;
44
45 /**
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().
49 *
50 * @var int
51 */
52 protected $numRows;
53
54 /**
55 * @var string|null
56 */
57 protected $cachedTimestamp = null;
58
59 /**
60 * @var bool Whether to show prev/next links
61 */
62 protected $shownavigation = true;
63
64 /**
65 * Get a list of query page classes and their associated special pages,
66 * for periodic updates.
67 *
68 * DO NOT CHANGE THIS LIST without testing that
69 * maintenance/updateSpecialPages.php still works.
70 *
71 * @return string[][]
72 */
73 public static function getPages() {
74 static $qp = null;
75
76 if ( $qp === null ) {
77 // QueryPage subclass, Special page name
78 $qp = [
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' ],
113 ];
114 Hooks::run( 'wgQueryPages', [ &$qp ] );
115 }
116
117 return $qp;
118 }
119
120 /**
121 * A mutator for $this->listoutput;
122 *
123 * @param bool $bool
124 */
125 function setListoutput( $bool ) {
126 $this->listoutput = $bool;
127 }
128
129 /**
130 * Subclasses return an SQL query here, formatted as an array with the
131 * following keys:
132 * tables => Table(s) for passing to Database::select()
133 * fields => Field(s) for passing to Database::select(), may be *
134 * conds => WHERE conditions
135 * options => options
136 * join_conds => JOIN conditions
137 *
138 * Note that the query itself should return the following three columns:
139 * 'namespace', 'title', and 'value'. 'value' is used for sorting.
140 *
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()).
146 *
147 * Don't include an ORDER or LIMIT clause, they will be added.
148 *
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.
152 * @return array
153 * @since 1.18
154 */
155 public function getQueryInfo() {
156 return null;
157 }
158
159 /**
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
163 * @return string
164 */
165 function getSQL() {
166 /* Implement getQueryInfo() instead */
167 throw new MWException( "Bug in a QueryPage: doesn't implement getQueryInfo() nor "
168 . "getQuery() properly" );
169 }
170
171 /**
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.
175 * @return string[]
176 * @since 1.18
177 */
178 function getOrderFields() {
179 return [ 'value' ];
180 }
181
182 /**
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()
189 * @return bool
190 * @since 1.18
191 */
192 public function usesTimestamps() {
193 return false;
194 }
195
196 /**
197 * Override to sort by increasing values
198 *
199 * @return bool
200 */
201 function sortDescending() {
202 return true;
203 }
204
205 /**
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.
209 *
210 * @return bool
211 */
212 public function isExpensive() {
213 return $this->getConfig()->get( 'DisableQueryPages' );
214 }
215
216 /**
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.
220 * @return bool
221 * @since 1.18
222 */
223 public function isCacheable() {
224 return true;
225 }
226
227 /**
228 * Whether or not the output of the page in question is retrieved from
229 * the database cache.
230 *
231 * @return bool
232 */
233 public function isCached() {
234 return $this->isExpensive() && $this->getConfig()->get( 'MiserMode' );
235 }
236
237 /**
238 * Sometime we don't want to build rss / atom feeds.
239 *
240 * @return bool
241 */
242 function isSyndicated() {
243 return true;
244 }
245
246 /**
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.
251 * @param Skin $skin
252 * @param object $result Result row
253 * @return string|bool String or false to skip
254 */
255 abstract function formatResult( $skin, $result );
256
257 /**
258 * The content returned by this function will be output before any result
259 *
260 * @return string
261 */
262 function getPageHeader() {
263 return '';
264 }
265
266 /**
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
269 * show.
270 *
271 * @since 1.26
272 */
273 protected function showEmptyText() {
274 $this->getOutput()->addWikiMsg( 'specialpage-empty' );
275 }
276
277 /**
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).
281 *
282 * @return array
283 */
284 function linkParameters() {
285 return [];
286 }
287
288 /**
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
293 * as well.
294 *
295 * @deprecated since 1.27
296 *
297 * @return bool
298 */
299 function tryLastResult() {
300 return false;
301 }
302
303 /**
304 * Clear the cache and save new results
305 *
306 * @param int|bool $limit Limit for SQL statement
307 * @param bool $ignoreErrors Whether to ignore database errors
308 * @throws DBError|Exception
309 * @return bool|int
310 */
311 public function recache( $limit, $ignoreErrors = true ) {
312 if ( !$this->isCacheable() ) {
313 return 0;
314 }
315
316 $fname = static::class . '::recache';
317 $dbw = wfGetDB( DB_MASTER );
318 if ( !$dbw ) {
319 return false;
320 }
321
322 try {
323 # Do query
324 $res = $this->reallyDoQuery( $limit, false );
325 $num = false;
326 if ( $res ) {
327 $num = $res->numRows();
328 # Fetch results
329 $vals = [];
330 foreach ( $res as $row ) {
331 if ( isset( $row->value ) ) {
332 if ( $this->usesTimestamps() ) {
333 $value = wfTimestamp( TS_UNIX,
334 $row->value );
335 } else {
336 $value = intval( $row->value ); // T16414
337 }
338 } else {
339 $value = 0;
340 }
341
342 $vals[] = [
343 'qc_type' => $this->getName(),
344 'qc_namespace' => $row->namespace,
345 'qc_title' => $row->title,
346 'qc_value' => $value
347 ];
348 }
349
350 $dbw->doAtomicSection(
351 __METHOD__,
352 function ( IDatabase $dbw, $fname ) use ( $vals ) {
353 # Clear out any old cached data
354 $dbw->delete( 'querycache',
355 [ 'qc_type' => $this->getName() ],
356 $fname
357 );
358 # Save results into the querycache table on the master
359 if ( count( $vals ) ) {
360 $dbw->insert( 'querycache', $vals, $fname );
361 }
362 # Update the querycache_info record for the page
363 $dbw->delete( 'querycache_info',
364 [ 'qci_type' => $this->getName() ],
365 $fname
366 );
367 $dbw->insert( 'querycache_info',
368 [ 'qci_type' => $this->getName(),
369 'qci_timestamp' => $dbw->timestamp() ],
370 $fname
371 );
372 }
373 );
374 }
375 } catch ( DBError $e ) {
376 if ( !$ignoreErrors ) {
377 throw $e; // report query error
378 }
379 $num = false; // set result to false to indicate error
380 }
381
382 return $num;
383 }
384
385 /**
386 * Get a DB connection to be used for slow recache queries
387 * @return \Wikimedia\Rdbms\Database
388 */
389 function getRecacheDB() {
390 return wfGetDB( DB_REPLICA, [ $this->getName(), 'QueryPage::recache', 'vslow' ] );
391 }
392
393 /**
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
398 * @since 1.18
399 */
400 public function reallyDoQuery( $limit, $offset = false ) {
401 $fname = static::class . '::reallyDoQuery';
402 $dbr = $this->getRecacheDB();
403 $query = $this->getQueryInfo();
404 $order = $this->getOrderFields();
405
406 if ( $this->sortDescending() ) {
407 foreach ( $order as &$field ) {
408 $field .= ' DESC';
409 }
410 }
411
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'] : [];
418
419 if ( $order ) {
420 $options['ORDER BY'] = $order;
421 }
422
423 if ( $limit !== false ) {
424 $options['LIMIT'] = intval( $limit );
425 }
426
427 if ( $offset !== false ) {
428 $options['OFFSET'] = intval( $offset );
429 }
430
431 $res = $dbr->select( $tables, $fields, $conds, $fname,
432 $options, $join_conds
433 );
434 } else {
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 );
440 }
441
442 return $res;
443 }
444
445 /**
446 * Somewhat deprecated, you probably want to be using execute()
447 * @param int|bool $offset
448 * @param int|bool $limit
449 * @return IResultWrapper
450 */
451 public function doQuery( $offset = false, $limit = false ) {
452 if ( $this->isCached() && $this->isCacheable() ) {
453 return $this->fetchFromCache( $limit, $offset );
454 } else {
455 return $this->reallyDoQuery( $limit, $offset );
456 }
457 }
458
459 /**
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
464 * @since 1.18
465 */
466 public function fetchFromCache( $limit, $offset = false ) {
467 $dbr = wfGetDB( DB_REPLICA );
468 $options = [];
469
470 if ( $limit !== false ) {
471 $options['LIMIT'] = intval( $limit );
472 }
473
474 if ( $offset !== false ) {
475 $options['OFFSET'] = intval( $offset );
476 }
477
478 $order = $this->getCacheOrderFields();
479 if ( $this->sortDescending() ) {
480 foreach ( $order as &$field ) {
481 $field .= " DESC";
482 }
483 }
484 if ( $order ) {
485 $options['ORDER BY'] = $order;
486 }
487
488 return $dbr->select( 'querycache',
489 [ 'qc_type',
490 'namespace' => 'qc_namespace',
491 'title' => 'qc_title',
492 'value' => 'qc_value' ],
493 [ 'qc_type' => $this->getName() ],
494 __METHOD__,
495 $options
496 );
497 }
498
499 /**
500 * Return the order fields for fetchFromCache. Default is to always use
501 * "ORDER BY value" which was the default prior to this function.
502 * @return array
503 * @since 1.29
504 */
505 function getCacheOrderFields() {
506 return [ 'value' ];
507 }
508
509 /**
510 * @return string
511 */
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 );
518 }
519 return $this->cachedTimestamp;
520 }
521
522 /**
523 * Returns limit and offset, as returned by $this->getRequest()->getLimitOffset().
524 * Subclasses may override this to further restrict or modify limit and offset.
525 *
526 * @note Restricts the offset parameter, as most query pages have inefficient paging
527 *
528 * Its generally expected that the returned limit will not be 0, and the returned
529 * offset will be less than the max results.
530 *
531 * @since 1.26
532 * @return int[] list( $limit, $offset )
533 */
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 );
542 }
543 return [ $limit, $offset ];
544 }
545
546 /**
547 * What is limit to fetch from DB
548 *
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)
553 */
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 );
559 } else {
560 return $uiLimit + 1;
561 }
562 }
563
564 /**
565 * Get max number of results we can return in miser mode.
566 *
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
569 *
570 * @since 1.27
571 * @return int
572 */
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 );
576 }
577
578 /**
579 * This is the actual workhorse. It does everything needed to make a
580 * real, honest-to-gosh query page.
581 * @param string|null $par
582 */
583 public function execute( $par ) {
584 $user = $this->getUser();
585 if ( !$this->userCanExecute( $user ) ) {
586 $this->displayRestrictionError();
587 return;
588 }
589
590 $this->setHeaders();
591 $this->outputHeader();
592
593 $out = $this->getOutput();
594
595 if ( $this->isCached() && !$this->isCacheable() ) {
596 $out->addWikiMsg( 'querypage-disabled' );
597 return;
598 }
599
600 $out->setSyndicated( $this->isSyndicated() );
601
602 if ( $this->limit == 0 && $this->offset == 0 ) {
603 list( $this->limit, $this->offset ) = $this->getLimitOffset();
604 }
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 );
610 } else {
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' ) );
618
619 if ( $ts ) {
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 );
626 } else {
627 $out->addWikiMsg( 'perfcached', $maxResults );
628 }
629
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' ) )
634 ) {
635 $out->wrapWikiMsg(
636 "<div class=\"mw-querypage-no-updates\">\n$1\n</div>",
637 'querypage-no-updates'
638 );
639 }
640 }
641 }
642
643 $this->numRows = $res->numRows();
644
645 $dbr = $this->getRecacheDB();
646 $this->preprocessResults( $dbr, $res );
647
648 $out->addHTML( Xml::openElement( 'div', [ 'class' => 'mw-spcontent' ] ) );
649
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->buildPrevNextNavigation( $this->offset,
662 $this->limit, $this->linkParameters(), $atEnd, $par );
663 $out->addHTML( '<p>' . $paging . '</p>' );
664 } else {
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' ) );
669 return;
670 }
671 }
672
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,
677 $this->getSkin(),
678 $dbr, # Should use a ResultWrapper for this
679 $res,
680 min( $this->numRows, $this->limit ), # do not format the one extra row, if exist
681 $this->offset );
682
683 # Repeat the paging links at the bottom
684 if ( $this->shownavigation ) {
685 $out->addHTML( '<p>' . $paging . '</p>' );
686 }
687
688 $out->addHTML( Xml::closeElement( 'div' ) );
689 }
690
691 /**
692 * Format and output report results using the given information plus
693 * OutputPage
694 *
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
701 */
702 protected function outputResults( $out, $skin, $dbr, $res, $num, $offset ) {
703 if ( $num > 0 ) {
704 $html = [];
705 if ( !$this->listoutput ) {
706 $html[] = $this->openList( $offset );
707 }
708
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 );
713 if ( $line ) {
714 $html[] = $this->listoutput
715 ? $line
716 : "<li>{$line}</li>\n";
717 }
718 }
719
720 # Flush the final result
721 if ( $this->tryLastResult() ) {
722 $row = null;
723 $line = $this->formatResult( $skin, $row );
724 if ( $line ) {
725 $html[] = $this->listoutput
726 ? $line
727 : "<li>{$line}</li>\n";
728 }
729 }
730
731 if ( !$this->listoutput ) {
732 $html[] = $this->closeList();
733 }
734
735 $html = $this->listoutput
736 ? MediaWikiServices::getInstance()->getContentLanguage()->listToText( $html )
737 : implode( '', $html );
738
739 $out->addHTML( $html );
740 }
741 }
742
743 /**
744 * @param int $offset
745 * @return string
746 */
747 function openList( $offset ) {
748 return "\n<ol start='" . ( $offset + 1 ) . "' class='special'>\n";
749 }
750
751 /**
752 * @return string
753 */
754 function closeList() {
755 return "</ol>\n";
756 }
757
758 /**
759 * Do any necessary preprocessing of the result object.
760 * @param IDatabase $db
761 * @param IResultWrapper $res
762 */
763 function preprocessResults( $db, $res ) {
764 }
765
766 /**
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.
770 *
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.
775 */
776 protected function executeLBFromResultWrapper( IResultWrapper $res, $ns = null ) {
777 if ( !$res->numRows() ) {
778 return;
779 }
780
781 $batch = new LinkBatch;
782 foreach ( $res as $row ) {
783 $batch->add( $ns ?? $row->namespace, $row->title );
784 }
785 $batch->execute();
786
787 $res->seek( 0 );
788 }
789 }