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