]> scripts.mit.edu Git - autoinstallsdev/mediawiki.git/blob - includes/specialpage/QueryPage.php
MediaWiki 1.30.2
[autoinstallsdev/mediawiki.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 Wikimedia\Rdbms\ResultWrapper;
25 use Wikimedia\Rdbms\IDatabase;
26 use Wikimedia\Rdbms\DBError;
27
28 /**
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
33  */
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;
37
38         /** @var int The offset and limit in use, as passed to the query() function */
39         protected $offset = 0;
40
41         /** @var int */
42         protected $limit = 0;
43
44         /**
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().
48          */
49         protected $numRows;
50
51         protected $cachedTimestamp = null;
52
53         /**
54          * Whether to show prev/next links
55          */
56         protected $shownavigation = true;
57
58         /**
59          * Get a list of query page classes and their associated special pages,
60          * for periodic updates.
61          *
62          * DO NOT CHANGE THIS LIST without testing that
63          * maintenance/updateSpecialPages.php still works.
64          * @return array
65          */
66         public static function getPages() {
67                 static $qp = null;
68
69                 if ( $qp === null ) {
70                         // QueryPage subclass, Special page name
71                         $qp = [
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' ],
106                         ];
107                         Hooks::run( 'wgQueryPages', [ &$qp ] );
108                 }
109
110                 return $qp;
111         }
112
113         /**
114          * A mutator for $this->listoutput;
115          *
116          * @param bool $bool
117          */
118         function setListoutput( $bool ) {
119                 $this->listoutput = $bool;
120         }
121
122         /**
123          * Subclasses return an SQL query here, formatted as an array with the
124          * following keys:
125          *    tables => Table(s) for passing to Database::select()
126          *    fields => Field(s) for passing to Database::select(), may be *
127          *    conds => WHERE conditions
128          *    options => options
129          *    join_conds => JOIN conditions
130          *
131          * Note that the query itself should return the following three columns:
132          * 'namespace', 'title', and 'value'. 'value' is used for sorting.
133          *
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()).
139          *
140          * Don't include an ORDER or LIMIT clause, they will be added.
141          *
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.
145          * @return array
146          * @since 1.18
147          */
148         public function getQueryInfo() {
149                 return null;
150         }
151
152         /**
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
156          * @return string
157          */
158         function getSQL() {
159                 /* Implement getQueryInfo() instead */
160                 throw new MWException( "Bug in a QueryPage: doesn't implement getQueryInfo() nor "
161                         . "getQuery() properly" );
162         }
163
164         /**
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.
168          * @return array
169          * @since 1.18
170          */
171         function getOrderFields() {
172                 return [ 'value' ];
173         }
174
175         /**
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()
182          * @return bool
183          * @since 1.18
184          */
185         public function usesTimestamps() {
186                 return false;
187         }
188
189         /**
190          * Override to sort by increasing values
191          *
192          * @return bool
193          */
194         function sortDescending() {
195                 return true;
196         }
197
198         /**
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.
202          *
203          * @return bool
204          */
205         public function isExpensive() {
206                 return $this->getConfig()->get( 'DisableQueryPages' );
207         }
208
209         /**
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.
213          * @return bool
214          * @since 1.18
215          */
216         public function isCacheable() {
217                 return true;
218         }
219
220         /**
221          * Whether or not the output of the page in question is retrieved from
222          * the database cache.
223          *
224          * @return bool
225          */
226         public function isCached() {
227                 return $this->isExpensive() && $this->getConfig()->get( 'MiserMode' );
228         }
229
230         /**
231          * Sometime we don't want to build rss / atom feeds.
232          *
233          * @return bool
234          */
235         function isSyndicated() {
236                 return true;
237         }
238
239         /**
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.
244          * @param Skin $skin
245          * @param object $result Result row
246          * @return string|bool String or false to skip
247          */
248         abstract function formatResult( $skin, $result );
249
250         /**
251          * The content returned by this function will be output before any result
252          *
253          * @return string
254          */
255         function getPageHeader() {
256                 return '';
257         }
258
259         /**
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
262          * show.
263          *
264          * @since 1.26
265          */
266         protected function showEmptyText() {
267                 $this->getOutput()->addWikiMsg( 'specialpage-empty' );
268         }
269
270         /**
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).
274          *
275          * @return array
276          */
277         function linkParameters() {
278                 return [];
279         }
280
281         /**
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
286          * as well.
287          *
288          * @deprecated since 1.27
289          *
290          * @return bool
291          */
292         function tryLastResult() {
293                 return false;
294         }
295
296         /**
297          * Clear the cache and save new results
298          *
299          * @param int|bool $limit Limit for SQL statement
300          * @param bool $ignoreErrors Whether to ignore database errors
301          * @throws DBError|Exception
302          * @return bool|int
303          */
304         public function recache( $limit, $ignoreErrors = true ) {
305                 if ( !$this->isCacheable() ) {
306                         return 0;
307                 }
308
309                 $fname = static::class . '::recache';
310                 $dbw = wfGetDB( DB_MASTER );
311                 if ( !$dbw ) {
312                         return false;
313                 }
314
315                 try {
316                         # Do query
317                         $res = $this->reallyDoQuery( $limit, false );
318                         $num = false;
319                         if ( $res ) {
320                                 $num = $res->numRows();
321                                 # Fetch results
322                                 $vals = [];
323                                 foreach ( $res as $row ) {
324                                         if ( isset( $row->value ) ) {
325                                                 if ( $this->usesTimestamps() ) {
326                                                         $value = wfTimestamp( TS_UNIX,
327                                                                 $row->value );
328                                                 } else {
329                                                         $value = intval( $row->value ); // T16414
330                                                 }
331                                         } else {
332                                                 $value = 0;
333                                         }
334
335                                         $vals[] = [
336                                                 'qc_type' => $this->getName(),
337                                                 'qc_namespace' => $row->namespace,
338                                                 'qc_title' => $row->title,
339                                                 'qc_value' => $value
340                                         ];
341                                 }
342
343                                 $dbw->doAtomicSection(
344                                         __METHOD__,
345                                         function ( IDatabase $dbw, $fname ) use ( $vals ) {
346                                                 # Clear out any old cached data
347                                                 $dbw->delete( 'querycache',
348                                                         [ 'qc_type' => $this->getName() ],
349                                                         $fname
350                                                 );
351                                                 # Save results into the querycache table on the master
352                                                 if ( count( $vals ) ) {
353                                                         $dbw->insert( 'querycache', $vals, $fname );
354                                                 }
355                                                 # Update the querycache_info record for the page
356                                                 $dbw->delete( 'querycache_info',
357                                                         [ 'qci_type' => $this->getName() ],
358                                                         $fname
359                                                 );
360                                                 $dbw->insert( 'querycache_info',
361                                                         [ 'qci_type' => $this->getName(),
362                                                                 'qci_timestamp' => $dbw->timestamp() ],
363                                                         $fname
364                                                 );
365                                         }
366                                 );
367                         }
368                 } catch ( DBError $e ) {
369                         if ( !$ignoreErrors ) {
370                                 throw $e; // report query error
371                         }
372                         $num = false; // set result to false to indicate error
373                 }
374
375                 return $num;
376         }
377
378         /**
379          * Get a DB connection to be used for slow recache queries
380          * @return IDatabase
381          */
382         function getRecacheDB() {
383                 return wfGetDB( DB_REPLICA, [ $this->getName(), 'QueryPage::recache', 'vslow' ] );
384         }
385
386         /**
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
391          * @since 1.18
392          */
393         public function reallyDoQuery( $limit, $offset = false ) {
394                 $fname = static::class . '::reallyDoQuery';
395                 $dbr = $this->getRecacheDB();
396                 $query = $this->getQueryInfo();
397                 $order = $this->getOrderFields();
398
399                 if ( $this->sortDescending() ) {
400                         foreach ( $order as &$field ) {
401                                 $field .= ' DESC';
402                         }
403                 }
404
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'] : [];
411
412                         if ( $order ) {
413                                 $options['ORDER BY'] = $order;
414                         }
415
416                         if ( $limit !== false ) {
417                                 $options['LIMIT'] = intval( $limit );
418                         }
419
420                         if ( $offset !== false ) {
421                                 $options['OFFSET'] = intval( $offset );
422                         }
423
424                         $res = $dbr->select( $tables, $fields, $conds, $fname,
425                                         $options, $join_conds
426                         );
427                 } else {
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 );
433                 }
434
435                 return $res;
436         }
437
438         /**
439          * Somewhat deprecated, you probably want to be using execute()
440          * @param int|bool $offset
441          * @param int|bool $limit
442          * @return ResultWrapper
443          */
444         public function doQuery( $offset = false, $limit = false ) {
445                 if ( $this->isCached() && $this->isCacheable() ) {
446                         return $this->fetchFromCache( $limit, $offset );
447                 } else {
448                         return $this->reallyDoQuery( $limit, $offset );
449                 }
450         }
451
452         /**
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
457          * @since 1.18
458          */
459         public function fetchFromCache( $limit, $offset = false ) {
460                 $dbr = wfGetDB( DB_REPLICA );
461                 $options = [];
462
463                 if ( $limit !== false ) {
464                         $options['LIMIT'] = intval( $limit );
465                 }
466
467                 if ( $offset !== false ) {
468                         $options['OFFSET'] = intval( $offset );
469                 }
470
471                 $order = $this->getCacheOrderFields();
472                 if ( $this->sortDescending() ) {
473                         foreach ( $order as &$field ) {
474                                 $field .= " DESC";
475                         }
476                 }
477                 if ( $order ) {
478                         $options['ORDER BY'] = $order;
479                 }
480
481                 return $dbr->select( 'querycache',
482                                 [ 'qc_type',
483                                 'namespace' => 'qc_namespace',
484                                 'title' => 'qc_title',
485                                 'value' => 'qc_value' ],
486                                 [ 'qc_type' => $this->getName() ],
487                                 __METHOD__,
488                                 $options
489                 );
490         }
491
492         /**
493          * Return the order fields for fetchFromCache. Default is to always use
494          * "ORDER BY value" which was the default prior to this function.
495          * @return array
496          * @since 1.29
497          */
498         function getCacheOrderFields() {
499                 return [ 'value' ];
500         }
501
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 );
508                 }
509                 return $this->cachedTimestamp;
510         }
511
512         /**
513          * Returns limit and offset, as returned by $this->getRequest()->getLimitOffset().
514          * Subclasses may override this to further restrict or modify limit and offset.
515          *
516          * @note Restricts the offset parameter, as most query pages have inefficient paging
517          *
518          * Its generally expected that the returned limit will not be 0, and the returned
519          * offset will be less than the max results.
520          *
521          * @since 1.26
522          * @return int[] list( $limit, $offset )
523          */
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 );
532                 }
533                 return [ $limit, $offset ];
534         }
535
536         /**
537          * What is limit to fetch from DB
538          *
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)
543          */
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 );
549                 } else {
550                         return $uiLimit + 1;
551                 }
552         }
553
554         /**
555          * Get max number of results we can return in miser mode.
556          *
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
559          *
560          * @since 1.27
561          * @return int
562          */
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 );
566         }
567
568         /**
569          * This is the actual workhorse. It does everything needed to make a
570          * real, honest-to-gosh query page.
571          * @param string $par
572          */
573         public function execute( $par ) {
574                 $user = $this->getUser();
575                 if ( !$this->userCanExecute( $user ) ) {
576                         $this->displayRestrictionError();
577                         return;
578                 }
579
580                 $this->setHeaders();
581                 $this->outputHeader();
582
583                 $out = $this->getOutput();
584
585                 if ( $this->isCached() && !$this->isCacheable() ) {
586                         $out->addWikiMsg( 'querypage-disabled' );
587                         return;
588                 }
589
590                 $out->setSyndicated( $this->isSyndicated() );
591
592                 if ( $this->limit == 0 && $this->offset == 0 ) {
593                         list( $this->limit, $this->offset ) = $this->getLimitOffset();
594                 }
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 );
600                 } else {
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' ) );
608
609                                 if ( $ts ) {
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 );
616                                 } else {
617                                         $out->addWikiMsg( 'perfcached', $maxResults );
618                                 }
619
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' ) )
624                                 ) {
625                                         $out->wrapWikiMsg(
626                                                 "<div class=\"mw-querypage-no-updates\">\n$1\n</div>",
627                                                 'querypage-no-updates'
628                                         );
629                                 }
630                         }
631                 }
632
633                 $this->numRows = $res->numRows();
634
635                 $dbr = $this->getRecacheDB();
636                 $this->preprocessResults( $dbr, $res );
637
638                 $out->addHTML( Xml::openElement( 'div', [ 'class' => 'mw-spcontent' ] ) );
639
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>' );
654                         } else {
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' ) );
659                                 return;
660                         }
661                 }
662
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,
667                         $this->getSkin(),
668                         $dbr, # Should use a ResultWrapper for this
669                         $res,
670                         min( $this->numRows, $this->limit ), # do not format the one extra row, if exist
671                         $this->offset );
672
673                 # Repeat the paging links at the bottom
674                 if ( $this->shownavigation ) {
675                         $out->addHTML( '<p>' . $paging . '</p>' );
676                 }
677
678                 $out->addHTML( Xml::closeElement( 'div' ) );
679         }
680
681         /**
682          * Format and output report results using the given information plus
683          * OutputPage
684          *
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
691          */
692         protected function outputResults( $out, $skin, $dbr, $res, $num, $offset ) {
693                 global $wgContLang;
694
695                 if ( $num > 0 ) {
696                         $html = [];
697                         if ( !$this->listoutput ) {
698                                 $html[] = $this->openList( $offset );
699                         }
700
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 );
707                                 if ( $line ) {
708                                         $html[] = $this->listoutput
709                                                 ? $line
710                                                 : "<li>{$line}</li>\n";
711                                 }
712                         }
713
714                         # Flush the final result
715                         if ( $this->tryLastResult() ) {
716                                 $row = null;
717                                 $line = $this->formatResult( $skin, $row );
718                                 if ( $line ) {
719                                         $html[] = $this->listoutput
720                                                 ? $line
721                                                 : "<li>{$line}</li>\n";
722                                 }
723                         }
724
725                         if ( !$this->listoutput ) {
726                                 $html[] = $this->closeList();
727                         }
728
729                         $html = $this->listoutput
730                                 ? $wgContLang->listToText( $html )
731                                 : implode( '', $html );
732
733                         $out->addHTML( $html );
734                 }
735         }
736
737         /**
738          * @param int $offset
739          * @return string
740          */
741         function openList( $offset ) {
742                 return "\n<ol start='" . ( $offset + 1 ) . "' class='special'>\n";
743         }
744
745         /**
746          * @return string
747          */
748         function closeList() {
749                 return "</ol>\n";
750         }
751
752         /**
753          * Do any necessary preprocessing of the result object.
754          * @param IDatabase $db
755          * @param ResultWrapper $res
756          */
757         function preprocessResults( $db, $res ) {
758         }
759
760         /**
761          * Similar to above, but packaging in a syndicated feed instead of a web page
762          * @param string $class
763          * @param int $limit
764          * @return bool
765          */
766         function doFeed( $class = '', $limit = 50 ) {
767                 if ( !$this->getConfig()->get( 'Feed' ) ) {
768                         $this->getOutput()->addWikiMsg( 'feed-unavailable' );
769                         return false;
770                 }
771
772                 $limit = min( $limit, $this->getConfig()->get( 'FeedLimit' ) );
773
774                 $feedClasses = $this->getConfig()->get( 'FeedClasses' );
775                 if ( isset( $feedClasses[$class] ) ) {
776                         /** @var RSSFeed|AtomFeed $feed */
777                         $feed = new $feedClasses[$class](
778                                 $this->feedTitle(),
779                                 $this->feedDesc(),
780                                 $this->feedUrl() );
781                         $feed->outHeader();
782
783                         $res = $this->reallyDoQuery( $limit, 0 );
784                         foreach ( $res as $obj ) {
785                                 $item = $this->feedResult( $obj );
786                                 if ( $item ) {
787                                         $feed->outItem( $item );
788                                 }
789                         }
790
791                         $feed->outFooter();
792                         return true;
793                 } else {
794                         return false;
795                 }
796         }
797
798         /**
799          * Override for custom handling. If the titles/links are ok, just do
800          * feedItemDesc()
801          * @param object $row
802          * @return FeedItem|null
803          */
804         function feedResult( $row ) {
805                 if ( !isset( $row->title ) ) {
806                         return null;
807                 }
808                 $title = Title::makeTitle( intval( $row->namespace ), $row->title );
809                 if ( $title ) {
810                         $date = isset( $row->timestamp ) ? $row->timestamp : '';
811                         $comments = '';
812                         if ( $title ) {
813                                 $talkpage = $title->getTalkPage();
814                                 $comments = $talkpage->getFullURL();
815                         }
816
817                         return new FeedItem(
818                                 $title->getPrefixedText(),
819                                 $this->feedItemDesc( $row ),
820                                 $title->getFullURL(),
821                                 $date,
822                                 $this->feedItemAuthor( $row ),
823                                 $comments );
824                 } else {
825                         return null;
826                 }
827         }
828
829         function feedItemDesc( $row ) {
830                 return isset( $row->comment ) ? htmlspecialchars( $row->comment ) : '';
831         }
832
833         function feedItemAuthor( $row ) {
834                 return isset( $row->user_text ) ? $row->user_text : '';
835         }
836
837         function feedTitle() {
838                 $desc = $this->getDescription();
839                 $code = $this->getConfig()->get( 'LanguageCode' );
840                 $sitename = $this->getConfig()->get( 'Sitename' );
841                 return "$sitename - $desc [$code]";
842         }
843
844         function feedDesc() {
845                 return $this->msg( 'tagline' )->text();
846         }
847
848         function feedUrl() {
849                 return $this->getPageTitle()->getFullURL();
850         }
851
852         /**
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.
856          *
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.
861          */
862         protected function executeLBFromResultWrapper( ResultWrapper $res, $ns = null ) {
863                 if ( !$res->numRows() ) {
864                         return;
865                 }
866
867                 $batch = new LinkBatch;
868                 foreach ( $res as $row ) {
869                         $batch->add( $ns !== null ? $ns : $row->namespace, $row->title );
870                 }
871                 $batch->execute();
872
873                 $res->seek( 0 );
874         }
875 }