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