0d84235e494981aedf0182b87b09cfb066357d82
[lhc/web/wiklou.git] / includes / QueryPage.php
1 <?php
2 /**
3 * Contain a class for special pages
4 * @file
5 * @ingroup SpecialPages
6 */
7
8 /**
9 * List of query page classes and their associated special pages,
10 * for periodic updates.
11 *
12 * DO NOT CHANGE THIS LIST without testing that
13 * maintenance/updateSpecialPages.php still works.
14 */
15 global $wgQueryPages; // not redundant
16 $wgQueryPages = array(
17 // QueryPage subclass Special page name Limit (false for none, none for the default)
18 //----------------------------------------------------------------------------
19 array( 'AncientPagesPage', 'Ancientpages' ),
20 array( 'BrokenRedirectsPage', 'BrokenRedirects' ),
21 array( 'DeadendPagesPage', 'Deadendpages' ),
22 array( 'DisambiguationsPage', 'Disambiguations' ),
23 array( 'DoubleRedirectsPage', 'DoubleRedirects' ),
24 array( 'LinkSearchPage', 'LinkSearch' ),
25 array( 'ListredirectsPage', 'Listredirects' ),
26 array( 'LonelyPagesPage', 'Lonelypages' ),
27 array( 'LongPagesPage', 'Longpages' ),
28 array( 'MostcategoriesPage', 'Mostcategories' ),
29 array( 'MostimagesPage', 'Mostimages' ),
30 array( 'MostlinkedCategoriesPage', 'Mostlinkedcategories' ),
31 array( 'SpecialMostlinkedtemplates', 'Mostlinkedtemplates' ),
32 array( 'MostlinkedPage', 'Mostlinked' ),
33 array( 'MostrevisionsPage', 'Mostrevisions' ),
34 array( 'FewestrevisionsPage', 'Fewestrevisions' ),
35 array( 'ShortPagesPage', 'Shortpages' ),
36 array( 'UncategorizedCategoriesPage', 'Uncategorizedcategories' ),
37 array( 'UncategorizedPagesPage', 'Uncategorizedpages' ),
38 array( 'UncategorizedImagesPage', 'Uncategorizedimages' ),
39 array( 'UncategorizedTemplatesPage', 'Uncategorizedtemplates' ),
40 array( 'UnusedCategoriesPage', 'Unusedcategories' ),
41 array( 'UnusedimagesPage', 'Unusedimages' ),
42 array( 'WantedCategoriesPage', 'Wantedcategories' ),
43 array( 'WantedFilesPage', 'Wantedfiles' ),
44 array( 'WantedPagesPage', 'Wantedpages' ),
45 array( 'WantedTemplatesPage', 'Wantedtemplates' ),
46 array( 'UnwatchedPagesPage', 'Unwatchedpages' ),
47 array( 'UnusedtemplatesPage', 'Unusedtemplates' ),
48 array( 'WithoutInterwikiPage', 'Withoutinterwiki' ),
49 );
50 wfRunHooks( 'wgQueryPages', array( &$wgQueryPages ) );
51
52 global $wgDisableCounters;
53 if ( !$wgDisableCounters )
54 $wgQueryPages[] = array( 'PopularPagesPage', 'Popularpages' );
55
56
57 /**
58 * This is a class for doing query pages; since they're almost all the same,
59 * we factor out some of the functionality into a superclass, and let
60 * subclasses derive from it.
61 * @ingroup SpecialPage
62 */
63 class QueryPage {
64 /**
65 * Whether or not we want plain listoutput rather than an ordered list
66 *
67 * @var bool
68 */
69 var $listoutput = false;
70
71 /**
72 * The offset and limit in use, as passed to the query() function
73 *
74 * @var integer
75 */
76 var $offset = 0;
77 var $limit = 0;
78
79 /**
80 * A mutator for $this->listoutput;
81 *
82 * @param bool $bool
83 */
84 function setListoutput( $bool ) {
85 $this->listoutput = $bool;
86 }
87
88 /**
89 * Subclasses return their name here. Make sure the name is also
90 * specified in SpecialPage.php and in Language.php as a language message
91 * param.
92 */
93 function getName() {
94 return '';
95 }
96
97 /**
98 * Return title object representing this page
99 *
100 * @return Title
101 */
102 function getTitle() {
103 return SpecialPage::getTitleFor( $this->getName() );
104 }
105
106 /**
107 * Subclasses return an SQL query here.
108 *
109 * Note that the query itself should return the following four columns:
110 * 'type' (your special page's name), 'namespace', 'title', and 'value'
111 * *in that order*. 'value' is used for sorting.
112 *
113 * These may be stored in the querycache table for expensive queries,
114 * and that cached data will be returned sometimes, so the presence of
115 * extra fields can't be relied upon. The cached 'value' column will be
116 * an integer; non-numeric values are useful only for sorting the initial
117 * query.
118 *
119 * Don't include an ORDER or LIMIT clause, this will be added.
120 */
121 function getSQL() {
122 return "SELECT 'sample' as type, 0 as namespace, 'Sample result' as title, 42 as value";
123 }
124
125 /**
126 * Override to sort by increasing values
127 */
128 function sortDescending() {
129 return true;
130 }
131
132 function getOrder() {
133 return ' ORDER BY value ' .
134 ($this->sortDescending() ? 'DESC' : '');
135 }
136
137 /**
138 * Is this query expensive (for some definition of expensive)? Then we
139 * don't let it run in miser mode. $wgDisableQueryPages causes all query
140 * pages to be declared expensive. Some query pages are always expensive.
141 */
142 function isExpensive( ) {
143 global $wgDisableQueryPages;
144 return $wgDisableQueryPages;
145 }
146
147 /**
148 * Whether or not the output of the page in question is retrived from
149 * the database cache.
150 *
151 * @return bool
152 */
153 function isCached() {
154 global $wgMiserMode;
155
156 return $this->isExpensive() && $wgMiserMode;
157 }
158
159 /**
160 * Sometime we dont want to build rss / atom feeds.
161 */
162 function isSyndicated() {
163 return true;
164 }
165
166 /**
167 * Formats the results of the query for display. The skin is the current
168 * skin; you can use it for making links. The result is a single row of
169 * result data. You should be able to grab SQL results off of it.
170 * If the function return "false", the line output will be skipped.
171 */
172 function formatResult( $skin, $result ) {
173 return '';
174 }
175 /**
176 * Formats the result as something that can be understood by the API.
177 * Defaults to setting id, ns and title
178 */
179 function formatApiResult( $row ) {
180 $title = Title::makeTitle( $row->namespace, $row->title );
181 return array(
182 'ns' => intval( $title->getNamespace() ),
183 'title' => $title->getPrefixedText(),
184 );
185 }
186
187 /**
188 * The content returned by this function will be output before any result
189 */
190 function getPageHeader( ) {
191 return '';
192 }
193
194 /**
195 * If using extra form wheely-dealies, return a set of parameters here
196 * as an associative array. They will be encoded and added to the paging
197 * links (prev/next/lengths).
198 * @return array
199 */
200 function linkParameters() {
201 return array();
202 }
203
204 /**
205 * Some special pages (for example SpecialListusers) might not return the
206 * current object formatted, but return the previous one instead.
207 * Setting this to return true, will call one more time wfFormatResult to
208 * be sure that the very last result is formatted and shown.
209 */
210 function tryLastResult( ) {
211 return false;
212 }
213
214 /**
215 * Clear the cache and save new results
216 */
217 function recache( $limit, $ignoreErrors = true ) {
218 $fname = get_class( $this ) . '::recache';
219 $dbw = wfGetDB( DB_MASTER );
220 $dbr = wfGetDB( DB_SLAVE, array( $this->getName(), __METHOD__, 'vslow' ) );
221 if ( !$dbw || !$dbr ) {
222 return false;
223 }
224
225 $querycache = $dbr->tableName( 'querycache' );
226
227 if ( $ignoreErrors ) {
228 $ignoreW = $dbw->ignoreErrors( true );
229 $ignoreR = $dbr->ignoreErrors( true );
230 }
231
232 # Clear out any old cached data
233 $dbw->delete( 'querycache', array( 'qc_type' => $this->getName() ), $fname );
234 # Do query
235 $sql = $this->getSQL() . $this->getOrder();
236 if ( $limit !== false )
237 $sql = $dbr->limitResult( $sql, $limit, 0 );
238 $res = $dbr->query( $sql, $fname );
239 $num = false;
240 if ( $res ) {
241 $num = $dbr->numRows( $res );
242 # Fetch results
243 $vals = array();
244 while ( $res && $row = $dbr->fetchObject( $res ) ) {
245 if ( isset( $row->value ) ) {
246 $value = intval( $row->value ); // @bug 14414
247 } else {
248 $value = 0;
249 }
250
251 $vals[] = array('qc_type' => $row->type,
252 'qc_namespace' => $row->namespace,
253 'qc_title' => $row->title,
254 'qc_value' => $value);
255 }
256
257 # Save results into the querycache table on the master
258 if ( count( $vals ) ) {
259 if ( !$dbw->insert( 'querycache', $vals, __METHOD__ ) ) {
260 // Set result to false to indicate error
261 $dbr->freeResult( $res );
262 $res = false;
263 }
264 }
265 if ( $res ) {
266 $dbr->freeResult( $res );
267 }
268 if ( $ignoreErrors ) {
269 $dbw->ignoreErrors( $ignoreW );
270 $dbr->ignoreErrors( $ignoreR );
271 }
272
273 # Update the querycache_info record for the page
274 $dbw->delete( 'querycache_info', array( 'qci_type' => $this->getName() ), $fname );
275 $dbw->insert( 'querycache_info', array( 'qci_type' => $this->getName(), 'qci_timestamp' => $dbw->timestamp() ), $fname );
276
277 }
278 return $num;
279 }
280
281 /**
282 * This is the actual workhorse. It does everything needed to make a
283 * real, honest-to-gosh query page.
284 *
285 * @param $offset database query offset
286 * @param $limit database query limit
287 * @param $shownavigation show navigation like "next 200"?
288 */
289 function doQuery( $offset, $limit, $shownavigation=true ) {
290 global $wgUser, $wgOut, $wgLang, $wgContLang;
291
292 $wgOut->setSyndicated( $this->isSyndicated() );
293
294 # Really really do the query now
295 $result = $this->reallyDoQuery( $offset, $limit );
296
297 # Tell about cachiness
298 if ( $result['cached'] !== false ) {
299 if ( $result['cached'] === true ) {
300 $wgOut->addWikiMsg( 'perfcached' );
301 } else {
302 $updated = $wgLang->timeAndDate( $result['cached'], true, true );
303 $wgOut->addMeta( 'Data-Cache-Time', $result['cached'] );
304 $wgOut->addInlineScript( "var dataCacheTime = '{$result['cached']}';" );
305 $wgOut->addWikiMsg( 'perfcachedts', $updated );
306 }
307 }
308 if ( $result['disabled'] ) {
309 # If updates on this page have been disabled, let the user know
310 # that the data set won't be refreshed for now
311
312 $wgOut->addWikiMsg( 'querypage-no-updates' );
313 }
314
315 $wgOut->addHTML( XML::openElement( 'div', array('class' => 'mw-spcontent') ) );
316
317 # Top header and navigation
318 if( $shownavigation ) {
319 $wgOut->addHTML( $this->getPageHeader() );
320 if( $result['count'] > 0 ) {
321 $wgOut->addHTML( '<p>' . wfShowingResults( $offset, $result['count'] ) . '</p>' );
322 # Disable the "next" link when we reach the end
323 $paging = wfViewPrevNext( $offset, $limit, $wgContLang->specialPage( $this->getName() ),
324 wfArrayToCGI( $this->linkParameters() ), ( $result['count'] < $limit ) );
325 $wgOut->addHTML( '<p>' . $paging . '</p>' );
326 } else {
327 # No results to show, so don't bother with "showing X of Y" etc.
328 # -- just let the user know and give up now
329 $wgOut->addHTML( '<p>' . wfMsgHtml( 'specialpage-empty' ) . '</p>' );
330 $wgOut->addHTML( XML::closeElement( 'div' ) );
331 return;
332 }
333 }
334
335 # The actual results; specialist subclasses will want to handle this
336 # with more than a straight list, so we hand them the info, plus
337 # an OutputPage, and let them get on with it
338 $this->outputResults( $wgOut,
339 $wgUser->getSkin(),
340 $result['dbr'], # Should use a ResultWrapper for this
341 $result['result'],
342 $result['count'],
343 $offset );
344
345 # Repeat the paging links at the bottom
346 if( $shownavigation ) {
347 $wgOut->addHTML( '<p>' . $paging . '</p>' );
348 }
349
350 $wgOut->addHTML( XML::closeElement( 'div' ) );
351
352 return $result['count'];
353 }
354
355 /**
356 * Really really do the query. Returns an array with:
357 * 'disabled' => true if the data will not be further refreshed,
358 * 'cached' => false if uncached, the timestamp of the last cache if known, else simply true,
359 * 'result' => the real result object,
360 * 'count' => number of results,
361 * 'dbr' => the database used for fetching the data
362 */
363 public function reallyDoQuery( $offset, $limit ) {
364 $result = array( 'disabled' => false );
365
366 $this->offset = $offset;
367 $this->limit = $limit;
368
369 $fname = get_class($this) . '::reallyDoQuery';
370 $dbr = wfGetDB( DB_SLAVE );
371
372
373 if ( !$this->isCached() ) {
374 $sql = $this->getSQL();
375 $result['cached'] = false;
376 } else {
377 # Get the cached result
378 $querycache = $dbr->tableName( 'querycache' );
379 $type = $dbr->strencode( $this->getName() );
380 $sql =
381 "SELECT qc_type as type, qc_namespace as namespace,qc_title as title, qc_value as value
382 FROM $querycache WHERE qc_type='$type'";
383
384 if( !$this->listoutput ) {
385
386 # Fetch the timestamp of this update
387 $tRes = $dbr->select( 'querycache_info', array( 'qci_timestamp' ), array( 'qci_type' => $type ), $fname );
388 $tRow = $dbr->fetchObject( $tRes );
389
390 if( $tRow ) {
391 $result['cached'] = $tRow->qci_timestamp;
392 } else {
393 $result['cached'] = true;
394 }
395
396 # If updates on this page have been disabled, let the user know
397 # that the data set won't be refreshed for now
398 global $wgDisableQueryPageUpdate;
399 if( is_array( $wgDisableQueryPageUpdate ) && in_array( $this->getName(), $wgDisableQueryPageUpdate ) ) {
400 $result['disabled'] = true;
401 }
402 }
403
404 }
405
406 $sql .= $this->getOrder();
407 $sql = $dbr->limitResult($sql, $limit, $offset);
408 $res = $dbr->query( $sql );
409 $num = $dbr->numRows($res);
410
411 $this->preprocessResults( $dbr, $res );
412
413 $result['result'] = $res;
414 $result['count'] = $num;
415 $result['dbr'] = $dbr;
416 return $result;
417 }
418
419 /**
420 * Format and output report results using the given information plus
421 * OutputPage
422 *
423 * @param OutputPage $out OutputPage to print to
424 * @param Skin $skin User skin to use
425 * @param Database $dbr Database (read) connection to use
426 * @param int $res Result pointer
427 * @param int $num Number of available result rows
428 * @param int $offset Paging offset
429 */
430 protected function outputResults( $out, $skin, $dbr, $res, $num, $offset ) {
431 global $wgContLang;
432
433 if( $num > 0 ) {
434 $html = array();
435 if( !$this->listoutput )
436 $html[] = $this->openList( $offset );
437
438 # $res might contain the whole 1,000 rows, so we read up to
439 # $num [should update this to use a Pager]
440 for ( $i = 0; $i < $num && $row = $dbr->fetchObject( $res ); $i++ ) {
441 $line = $this->formatResult( $skin, $row );
442 if( $line ) {
443 $attr = ( isset( $row->usepatrol ) && $row->usepatrol && $row->patrolled == 0 )
444 ? ' class="not-patrolled"'
445 : '';
446 $html[] = $this->listoutput
447 ? $line
448 : "<li{$attr}>{$line}</li>\n";
449 }
450 }
451
452 # Flush the final result
453 if( $this->tryLastResult() ) {
454 $row = null;
455 $line = $this->formatResult( $skin, $row );
456 if( $line ) {
457 $attr = ( isset( $row->usepatrol ) && $row->usepatrol && $row->patrolled == 0 )
458 ? ' class="not-patrolled"'
459 : '';
460 $html[] = $this->listoutput
461 ? $line
462 : "<li{$attr}>{$line}</li>\n";
463 }
464 }
465
466 if( !$this->listoutput )
467 $html[] = $this->closeList();
468
469 $html = $this->listoutput
470 ? $wgContLang->listToText( $html )
471 : implode( '', $html );
472
473 $out->addHTML( $html );
474 }
475 }
476
477
478 function openList( $offset ) {
479 return "\n<ol start='" . ( $offset + 1 ) . "' class='special'>\n";
480 }
481
482 function closeList() {
483 return "</ol>\n";
484 }
485
486 /**
487 * Do any necessary preprocessing of the result object.
488 */
489 function preprocessResults( $db, $res ) {}
490
491 /**
492 * Similar to above, but packaging in a syndicated feed instead of a web page
493 */
494 function doFeed( $class = '', $limit = 50 ) {
495 global $wgFeed, $wgFeedClasses;
496
497 if ( !$wgFeed ) {
498 global $wgOut;
499 $wgOut->addWikiMsg( 'feed-unavailable' );
500 return;
501 }
502
503 global $wgFeedLimit;
504 if( $limit > $wgFeedLimit ) {
505 $limit = $wgFeedLimit;
506 }
507
508 if( isset($wgFeedClasses[$class]) ) {
509 $feed = new $wgFeedClasses[$class](
510 $this->feedTitle(),
511 $this->feedDesc(),
512 $this->feedUrl() );
513 $feed->outHeader();
514
515 $dbr = wfGetDB( DB_SLAVE );
516 $sql = $this->getSQL() . $this->getOrder();
517 $sql = $dbr->limitResult( $sql, $limit, 0 );
518 $res = $dbr->query( $sql, 'QueryPage::doFeed' );
519 while( $obj = $dbr->fetchObject( $res ) ) {
520 $item = $this->feedResult( $obj );
521 if( $item ) $feed->outItem( $item );
522 }
523 $dbr->freeResult( $res );
524
525 $feed->outFooter();
526 return true;
527 } else {
528 return false;
529 }
530 }
531
532 /**
533 * Override for custom handling. If the titles/links are ok, just do
534 * feedItemDesc()
535 */
536 function feedResult( $row ) {
537 if( !isset( $row->title ) ) {
538 return NULL;
539 }
540 $title = Title::MakeTitle( intval( $row->namespace ), $row->title );
541 if( $title ) {
542 $date = isset( $row->timestamp ) ? $row->timestamp : '';
543 $comments = '';
544 if( $title ) {
545 $talkpage = $title->getTalkPage();
546 $comments = $talkpage->getFullURL();
547 }
548
549 return new FeedItem(
550 $title->getPrefixedText(),
551 $this->feedItemDesc( $row ),
552 $title->getFullURL(),
553 $date,
554 $this->feedItemAuthor( $row ),
555 $comments);
556 } else {
557 return NULL;
558 }
559 }
560
561 function feedItemDesc( $row ) {
562 return isset( $row->comment ) ? htmlspecialchars( $row->comment ) : '';
563 }
564
565 function feedItemAuthor( $row ) {
566 return isset( $row->user_text ) ? $row->user_text : '';
567 }
568
569 function feedTitle() {
570 global $wgContLanguageCode, $wgSitename;
571 $page = SpecialPage::getPage( $this->getName() );
572 $desc = $page->getDescription();
573 return "$wgSitename - $desc [$wgContLanguageCode]";
574 }
575
576 function feedDesc() {
577 return wfMsgExt( 'tagline', 'parsemag' );
578 }
579
580 function feedUrl() {
581 $title = SpecialPage::getTitleFor( $this->getName() );
582 return $title->getFullURL();
583 }
584 }
585
586 /**
587 * Class definition for a wanted query page like
588 * WantedPages, WantedTemplates, etc
589 */
590 abstract class WantedQueryPage extends QueryPage {
591
592 function isExpensive() {
593 return true;
594 }
595
596 function isSyndicated() {
597 return false;
598 }
599
600 /**
601 * Cache page existence for performance
602 */
603 function preprocessResults( $db, $res ) {
604 $batch = new LinkBatch;
605 while ( $row = $db->fetchObject( $res ) )
606 $batch->add( $row->namespace, $row->title );
607 $batch->execute();
608
609 // Back to start for display
610 if ( $db->numRows( $res ) > 0 )
611 // If there are no rows we get an error seeking.
612 $db->dataSeek( $res, 0 );
613 }
614
615 /**
616 * Format an individual result
617 *
618 * @param $skin Skin to use for UI elements
619 * @param $result Result row
620 * @return string
621 */
622 public function formatResult( $skin, $result ) {
623 $title = Title::makeTitleSafe( $result->namespace, $result->title );
624 if( $title instanceof Title ) {
625 if( $this->isCached() ) {
626 $pageLink = $title->exists()
627 ? '<s>' . $skin->link( $title ) . '</s>'
628 : $skin->link(
629 $title,
630 null,
631 array(),
632 array(),
633 array( 'broken' )
634 );
635 } else {
636 $pageLink = $skin->link(
637 $title,
638 null,
639 array(),
640 array(),
641 array( 'broken' )
642 );
643 }
644 return wfSpecialList( $pageLink, $this->makeWlhLink( $title, $skin, $result ) );
645 } else {
646 $tsafe = htmlspecialchars( $result->title );
647 return wfMsgHtml( 'wantedpages-badtitle', $tsafe );
648 }
649 }
650
651 /**
652 * Make a "what links here" link for a given title
653 *
654 * @param Title $title Title to make the link for
655 * @param Skin $skin Skin to use
656 * @param object $result Result row
657 * @return string
658 */
659 private function makeWlhLink( $title, $skin, $result ) {
660 global $wgLang;
661 $wlh = SpecialPage::getTitleFor( 'Whatlinkshere' );
662 $label = wfMsgExt( 'nlinks', array( 'parsemag', 'escape' ),
663 $wgLang->formatNum( $result->value ) );
664 return $skin->link( $wlh, $label, array(), array( 'target' => $title->getPrefixedText() ) );
665 }
666 }