Add 3D filetype for STL files
[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 use Wikimedia\Rdbms\IDatabase;
26
27 /**
28 * This is a class for doing query pages; since they're almost all the same,
29 * we factor out some of the functionality into a superclass, and let
30 * subclasses derive from it.
31 * @ingroup SpecialPage
32 */
33 abstract class QueryPage extends SpecialPage {
34 /** @var bool Whether or not we want plain listoutput rather than an ordered list */
35 protected $listoutput = false;
36
37 /** @var int The offset and limit in use, as passed to the query() function */
38 protected $offset = 0;
39
40 /** @var int */
41 protected $limit = 0;
42
43 /**
44 * The number of rows returned by the query. Reading this variable
45 * only makes sense in functions that are run after the query has been
46 * done, such as preprocessResults() and formatRow().
47 */
48 protected $numRows;
49
50 protected $cachedTimestamp = null;
51
52 /**
53 * Whether to show prev/next links
54 */
55 protected $shownavigation = true;
56
57 /**
58 * Get a list of query page classes and their associated special pages,
59 * for periodic updates.
60 *
61 * DO NOT CHANGE THIS LIST without testing that
62 * maintenance/updateSpecialPages.php still works.
63 * @return array
64 */
65 public static function getPages() {
66 static $qp = null;
67
68 if ( $qp === null ) {
69 // QueryPage subclass, Special page name
70 $qp = [
71 [ 'AncientPagesPage', 'Ancientpages' ],
72 [ 'BrokenRedirectsPage', 'BrokenRedirects' ],
73 [ 'DeadendPagesPage', 'Deadendpages' ],
74 [ 'DoubleRedirectsPage', 'DoubleRedirects' ],
75 [ 'FileDuplicateSearchPage', 'FileDuplicateSearch' ],
76 [ 'ListDuplicatedFilesPage', 'ListDuplicatedFiles' ],
77 [ 'LinkSearchPage', 'LinkSearch' ],
78 [ 'ListredirectsPage', 'Listredirects' ],
79 [ 'LonelyPagesPage', 'Lonelypages' ],
80 [ 'LongPagesPage', 'Longpages' ],
81 [ 'MediaStatisticsPage', 'MediaStatistics' ],
82 [ 'MIMEsearchPage', 'MIMEsearch' ],
83 [ 'MostcategoriesPage', 'Mostcategories' ],
84 [ 'MostimagesPage', 'Mostimages' ],
85 [ 'MostinterwikisPage', 'Mostinterwikis' ],
86 [ 'MostlinkedCategoriesPage', 'Mostlinkedcategories' ],
87 [ 'MostlinkedTemplatesPage', 'Mostlinkedtemplates' ],
88 [ 'MostlinkedPage', 'Mostlinked' ],
89 [ 'MostrevisionsPage', 'Mostrevisions' ],
90 [ 'FewestrevisionsPage', 'Fewestrevisions' ],
91 [ 'ShortPagesPage', 'Shortpages' ],
92 [ 'UncategorizedCategoriesPage', 'Uncategorizedcategories' ],
93 [ 'UncategorizedPagesPage', 'Uncategorizedpages' ],
94 [ 'UncategorizedImagesPage', 'Uncategorizedimages' ],
95 [ 'UncategorizedTemplatesPage', 'Uncategorizedtemplates' ],
96 [ 'UnusedCategoriesPage', 'Unusedcategories' ],
97 [ 'UnusedimagesPage', 'Unusedimages' ],
98 [ 'WantedCategoriesPage', 'Wantedcategories' ],
99 [ 'WantedFilesPage', 'Wantedfiles' ],
100 [ 'WantedPagesPage', 'Wantedpages' ],
101 [ 'WantedTemplatesPage', 'Wantedtemplates' ],
102 [ 'UnwatchedpagesPage', 'Unwatchedpages' ],
103 [ 'UnusedtemplatesPage', 'Unusedtemplates' ],
104 [ 'WithoutInterwikiPage', 'Withoutinterwiki' ],
105 ];
106 Hooks::run( 'wgQueryPages', [ &$qp ] );
107 }
108
109 return $qp;
110 }
111
112 /**
113 * A mutator for $this->listoutput;
114 *
115 * @param bool $bool
116 */
117 function setListoutput( $bool ) {
118 $this->listoutput = $bool;
119 }
120
121 /**
122 * Subclasses return an SQL query here, formatted as an array with the
123 * following keys:
124 * tables => Table(s) for passing to Database::select()
125 * fields => Field(s) for passing to Database::select(), may be *
126 * conds => WHERE conditions
127 * options => options
128 * join_conds => JOIN conditions
129 *
130 * Note that the query itself should return the following three columns:
131 * 'namespace', 'title', and 'value'. 'value' is used for sorting.
132 *
133 * These may be stored in the querycache table for expensive queries,
134 * and that cached data will be returned sometimes, so the presence of
135 * extra fields can't be relied upon. The cached 'value' column will be
136 * an integer; non-numeric values are useful only for sorting the
137 * initial query (except if they're timestamps, see usesTimestamps()).
138 *
139 * Don't include an ORDER or LIMIT clause, they will be added.
140 *
141 * If this function is not overridden or returns something other than
142 * an array, getSQL() will be used instead. This is for backwards
143 * compatibility only and is strongly deprecated.
144 * @return array
145 * @since 1.18
146 */
147 public function getQueryInfo() {
148 return null;
149 }
150
151 /**
152 * For back-compat, subclasses may return a raw SQL query here, as a string.
153 * This is strongly deprecated; getQueryInfo() should be overridden instead.
154 * @throws MWException
155 * @return string
156 */
157 function getSQL() {
158 /* Implement getQueryInfo() instead */
159 throw new MWException( "Bug in a QueryPage: doesn't implement getQueryInfo() nor "
160 . "getQuery() properly" );
161 }
162
163 /**
164 * Subclasses return an array of fields to order by here. Don't append
165 * DESC to the field names, that'll be done automatically if
166 * sortDescending() returns true.
167 * @return array
168 * @since 1.18
169 */
170 function getOrderFields() {
171 return [ 'value' ];
172 }
173
174 /**
175 * Does this query return timestamps rather than integers in its
176 * 'value' field? If true, this class will convert 'value' to a
177 * UNIX timestamp for caching.
178 * NOTE: formatRow() may get timestamps in TS_MW (mysql), TS_DB (pgsql)
179 * or TS_UNIX (querycache) format, so be sure to always run them
180 * through wfTimestamp()
181 * @return bool
182 * @since 1.18
183 */
184 public function usesTimestamps() {
185 return false;
186 }
187
188 /**
189 * Override to sort by increasing values
190 *
191 * @return bool
192 */
193 function sortDescending() {
194 return true;
195 }
196
197 /**
198 * Is this query expensive (for some definition of expensive)? Then we
199 * don't let it run in miser mode. $wgDisableQueryPages causes all query
200 * pages to be declared expensive. Some query pages are always expensive.
201 *
202 * @return bool
203 */
204 public function isExpensive() {
205 return $this->getConfig()->get( 'DisableQueryPages' );
206 }
207
208 /**
209 * Is the output of this query cacheable? Non-cacheable expensive pages
210 * will be disabled in miser mode and will not have their results written
211 * to the querycache table.
212 * @return bool
213 * @since 1.18
214 */
215 public function isCacheable() {
216 return true;
217 }
218
219 /**
220 * Whether or not the output of the page in question is retrieved from
221 * the database cache.
222 *
223 * @return bool
224 */
225 public function isCached() {
226 return $this->isExpensive() && $this->getConfig()->get( 'MiserMode' );
227 }
228
229 /**
230 * Sometime we don't want to build rss / atom feeds.
231 *
232 * @return bool
233 */
234 function isSyndicated() {
235 return true;
236 }
237
238 /**
239 * Formats the results of the query for display. The skin is the current
240 * skin; you can use it for making links. The result is a single row of
241 * result data. You should be able to grab SQL results off of it.
242 * If the function returns false, the line output will be skipped.
243 * @param Skin $skin
244 * @param object $result Result row
245 * @return string|bool String or false to skip
246 */
247 abstract function formatResult( $skin, $result );
248
249 /**
250 * The content returned by this function will be output before any result
251 *
252 * @return string
253 */
254 function getPageHeader() {
255 return '';
256 }
257
258 /**
259 * Outputs some kind of an informative message (via OutputPage) to let the
260 * user know that the query returned nothing and thus there's nothing to
261 * show.
262 *
263 * @since 1.26
264 */
265 protected function showEmptyText() {
266 $this->getOutput()->addWikiMsg( 'specialpage-empty' );
267 }
268
269 /**
270 * If using extra form wheely-dealies, return a set of parameters here
271 * as an associative array. They will be encoded and added to the paging
272 * links (prev/next/lengths).
273 *
274 * @return array
275 */
276 function linkParameters() {
277 return [];
278 }
279
280 /**
281 * Some special pages (for example SpecialListusers used to) might not return the
282 * current object formatted, but return the previous one instead.
283 * Setting this to return true will ensure formatResult() is called
284 * one more time to make sure that the very last result is formatted
285 * as well.
286 *
287 * @deprecated since 1.27
288 *
289 * @return bool
290 */
291 function tryLastResult() {
292 return false;
293 }
294
295 /**
296 * Clear the cache and save new results
297 *
298 * @param int|bool $limit Limit for SQL statement
299 * @param bool $ignoreErrors Whether to ignore database errors
300 * @throws DBError|Exception
301 * @return bool|int
302 */
303 public function recache( $limit, $ignoreErrors = true ) {
304 if ( !$this->isCacheable() ) {
305 return 0;
306 }
307
308 $fname = static::class . '::recache';
309 $dbw = wfGetDB( DB_MASTER );
310 if ( !$dbw ) {
311 return false;
312 }
313
314 try {
315 # Do query
316 $res = $this->reallyDoQuery( $limit, false );
317 $num = false;
318 if ( $res ) {
319 $num = $res->numRows();
320 # Fetch results
321 $vals = [];
322 foreach ( $res as $row ) {
323 if ( isset( $row->value ) ) {
324 if ( $this->usesTimestamps() ) {
325 $value = wfTimestamp( TS_UNIX,
326 $row->value );
327 } else {
328 $value = intval( $row->value ); // T16414
329 }
330 } else {
331 $value = 0;
332 }
333
334 $vals[] = [
335 'qc_type' => $this->getName(),
336 'qc_namespace' => $row->namespace,
337 'qc_title' => $row->title,
338 'qc_value' => $value
339 ];
340 }
341
342 $dbw->doAtomicSection(
343 __METHOD__,
344 function ( IDatabase $dbw, $fname ) use ( $vals ) {
345 # Clear out any old cached data
346 $dbw->delete( 'querycache',
347 [ 'qc_type' => $this->getName() ],
348 $fname
349 );
350 # Save results into the querycache table on the master
351 if ( count( $vals ) ) {
352 $dbw->insert( 'querycache', $vals, $fname );
353 }
354 # Update the querycache_info record for the page
355 $dbw->delete( 'querycache_info',
356 [ 'qci_type' => $this->getName() ],
357 $fname
358 );
359 $dbw->insert( 'querycache_info',
360 [ 'qci_type' => $this->getName(),
361 'qci_timestamp' => $dbw->timestamp() ],
362 $fname
363 );
364 }
365 );
366 }
367 } catch ( DBError $e ) {
368 if ( !$ignoreErrors ) {
369 throw $e; // report query error
370 }
371 $num = false; // set result to false to indicate error
372 }
373
374 return $num;
375 }
376
377 /**
378 * Get a DB connection to be used for slow recache queries
379 * @return IDatabase
380 */
381 function getRecacheDB() {
382 return wfGetDB( DB_REPLICA, [ $this->getName(), 'QueryPage::recache', 'vslow' ] );
383 }
384
385 /**
386 * Run the query and return the result
387 * @param int|bool $limit Numerical limit or false for no limit
388 * @param int|bool $offset Numerical offset or false for no offset
389 * @return ResultWrapper
390 * @since 1.18
391 */
392 public function reallyDoQuery( $limit, $offset = false ) {
393 $fname = static::class . '::reallyDoQuery';
394 $dbr = $this->getRecacheDB();
395 $query = $this->getQueryInfo();
396 $order = $this->getOrderFields();
397
398 if ( $this->sortDescending() ) {
399 foreach ( $order as &$field ) {
400 $field .= ' DESC';
401 }
402 }
403
404 if ( is_array( $query ) ) {
405 $tables = isset( $query['tables'] ) ? (array)$query['tables'] : [];
406 $fields = isset( $query['fields'] ) ? (array)$query['fields'] : [];
407 $conds = isset( $query['conds'] ) ? (array)$query['conds'] : [];
408 $options = isset( $query['options'] ) ? (array)$query['options'] : [];
409 $join_conds = isset( $query['join_conds'] ) ? (array)$query['join_conds'] : [];
410
411 if ( $order ) {
412 $options['ORDER BY'] = $order;
413 }
414
415 if ( $limit !== false ) {
416 $options['LIMIT'] = intval( $limit );
417 }
418
419 if ( $offset !== false ) {
420 $options['OFFSET'] = intval( $offset );
421 }
422
423 $res = $dbr->select( $tables, $fields, $conds, $fname,
424 $options, $join_conds
425 );
426 } else {
427 // Old-fashioned raw SQL style, deprecated
428 $sql = $this->getSQL();
429 $sql .= ' ORDER BY ' . implode( ', ', $order );
430 $sql = $dbr->limitResult( $sql, $limit, $offset );
431 $res = $dbr->query( $sql, $fname );
432 }
433
434 return $res;
435 }
436
437 /**
438 * Somewhat deprecated, you probably want to be using execute()
439 * @param int|bool $offset
440 * @param int|bool $limit
441 * @return ResultWrapper
442 */
443 public function doQuery( $offset = false, $limit = false ) {
444 if ( $this->isCached() && $this->isCacheable() ) {
445 return $this->fetchFromCache( $limit, $offset );
446 } else {
447 return $this->reallyDoQuery( $limit, $offset );
448 }
449 }
450
451 /**
452 * Fetch the query results from the query cache
453 * @param int|bool $limit Numerical limit or false for no limit
454 * @param int|bool $offset Numerical offset or false for no offset
455 * @return ResultWrapper
456 * @since 1.18
457 */
458 public function fetchFromCache( $limit, $offset = false ) {
459 $dbr = wfGetDB( DB_REPLICA );
460 $options = [];
461
462 if ( $limit !== false ) {
463 $options['LIMIT'] = intval( $limit );
464 }
465
466 if ( $offset !== false ) {
467 $options['OFFSET'] = intval( $offset );
468 }
469
470 $order = $this->getCacheOrderFields();
471 if ( $this->sortDescending() ) {
472 foreach ( $order as &$field ) {
473 $field .= " DESC";
474 }
475 }
476 if ( $order ) {
477 $options['ORDER BY'] = $order;
478 }
479
480 return $dbr->select( 'querycache',
481 [ 'qc_type',
482 'namespace' => 'qc_namespace',
483 'title' => 'qc_title',
484 'value' => 'qc_value' ],
485 [ 'qc_type' => $this->getName() ],
486 __METHOD__,
487 $options
488 );
489 }
490
491 /**
492 * Return the order fields for fetchFromCache. Default is to always use
493 * "ORDER BY value" which was the default prior to this function.
494 * @return array
495 * @since 1.29
496 */
497 function getCacheOrderFields() {
498 return [ 'value' ];
499 }
500
501 public function getCachedTimestamp() {
502 if ( is_null( $this->cachedTimestamp ) ) {
503 $dbr = wfGetDB( DB_REPLICA );
504 $fname = static::class . '::getCachedTimestamp';
505 $this->cachedTimestamp = $dbr->selectField( 'querycache_info', 'qci_timestamp',
506 [ 'qci_type' => $this->getName() ], $fname );
507 }
508 return $this->cachedTimestamp;
509 }
510
511 /**
512 * Returns limit and offset, as returned by $this->getRequest()->getLimitOffset().
513 * Subclasses may override this to further restrict or modify limit and offset.
514 *
515 * @note Restricts the offset parameter, as most query pages have inefficient paging
516 *
517 * Its generally expected that the returned limit will not be 0, and the returned
518 * offset will be less than the max results.
519 *
520 * @since 1.26
521 * @return int[] list( $limit, $offset )
522 */
523 protected function getLimitOffset() {
524 list( $limit, $offset ) = $this->getRequest()->getLimitOffset();
525 if ( $this->getConfig()->get( 'MiserMode' ) ) {
526 $maxResults = $this->getMaxResults();
527 // Can't display more than max results on a page
528 $limit = min( $limit, $maxResults );
529 // Can't skip over more than the end of $maxResults
530 $offset = min( $offset, $maxResults + 1 );
531 }
532 return [ $limit, $offset ];
533 }
534
535 /**
536 * What is limit to fetch from DB
537 *
538 * Used to make it appear the DB stores less results then it actually does
539 * @param int $uiLimit Limit from UI
540 * @param int $uiOffset Offset from UI
541 * @return int Limit to use for DB (not including extra row to see if at end)
542 */
543 protected function getDBLimit( $uiLimit, $uiOffset ) {
544 $maxResults = $this->getMaxResults();
545 if ( $this->getConfig()->get( 'MiserMode' ) ) {
546 $limit = min( $uiLimit + 1, $maxResults - $uiOffset );
547 return max( $limit, 0 );
548 } else {
549 return $uiLimit + 1;
550 }
551 }
552
553 /**
554 * Get max number of results we can return in miser mode.
555 *
556 * Most QueryPage subclasses use inefficient paging, so limit the max amount we return
557 * This matters for uncached query pages that might otherwise accept an offset of 3 million
558 *
559 * @since 1.27
560 * @return int
561 */
562 protected function getMaxResults() {
563 // Max of 10000, unless we store more than 10000 in query cache.
564 return max( $this->getConfig()->get( 'QueryCacheLimit' ), 10000 );
565 }
566
567 /**
568 * This is the actual workhorse. It does everything needed to make a
569 * real, honest-to-gosh query page.
570 * @param string $par
571 */
572 public function execute( $par ) {
573 $user = $this->getUser();
574 if ( !$this->userCanExecute( $user ) ) {
575 $this->displayRestrictionError();
576 return;
577 }
578
579 $this->setHeaders();
580 $this->outputHeader();
581
582 $out = $this->getOutput();
583
584 if ( $this->isCached() && !$this->isCacheable() ) {
585 $out->addWikiMsg( 'querypage-disabled' );
586 return;
587 }
588
589 $out->setSyndicated( $this->isSyndicated() );
590
591 if ( $this->limit == 0 && $this->offset == 0 ) {
592 list( $this->limit, $this->offset ) = $this->getLimitOffset();
593 }
594 $dbLimit = $this->getDBLimit( $this->limit, $this->offset );
595 // @todo Use doQuery()
596 if ( !$this->isCached() ) {
597 # select one extra row for navigation
598 $res = $this->reallyDoQuery( $dbLimit, $this->offset );
599 } else {
600 # Get the cached result, select one extra row for navigation
601 $res = $this->fetchFromCache( $dbLimit, $this->offset );
602 if ( !$this->listoutput ) {
603
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 }