* (bug 24563) Entries on Special:WhatLinksHere now have a link to their history
[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 Boolean
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 * @return String
94 */
95 function getName() {
96 return '';
97 }
98
99 /**
100 * Return title object representing this page
101 *
102 * @return Title
103 */
104 function getTitle() {
105 return SpecialPage::getTitleFor( $this->getName() );
106 }
107
108 /**
109 * Subclasses return an SQL query here.
110 *
111 * Note that the query itself should return the following four columns:
112 * 'type' (your special page's name), 'namespace', 'title', and 'value'
113 * *in that order*. 'value' is used for sorting.
114 *
115 * These may be stored in the querycache table for expensive queries,
116 * and that cached data will be returned sometimes, so the presence of
117 * extra fields can't be relied upon. The cached 'value' column will be
118 * an integer; non-numeric values are useful only for sorting the initial
119 * query.
120 *
121 * Don't include an ORDER or LIMIT clause, this will be added.
122 */
123 function getSQL() {
124 return "SELECT 'sample' as type, 0 as namespace, 'Sample result' as title, 42 as value";
125 }
126
127 /**
128 * Override to sort by increasing values
129 *
130 * @return Boolean
131 */
132 function sortDescending() {
133 return true;
134 }
135
136 function getOrder() {
137 return ' ORDER BY value ' .
138 ($this->sortDescending() ? 'DESC' : '');
139 }
140
141 /**
142 * Is this query expensive (for some definition of expensive)? Then we
143 * don't let it run in miser mode. $wgDisableQueryPages causes all query
144 * pages to be declared expensive. Some query pages are always expensive.
145 *
146 * @return Boolean
147 */
148 function isExpensive() {
149 global $wgDisableQueryPages;
150 return $wgDisableQueryPages;
151 }
152
153 /**
154 * Whether or not the output of the page in question is retrived from
155 * the database cache.
156 *
157 * @return Boolean
158 */
159 function isCached() {
160 global $wgMiserMode;
161
162 return $this->isExpensive() && $wgMiserMode;
163 }
164
165 /**
166 * Sometime we dont want to build rss / atom feeds.
167 *
168 * @return Boolean
169 */
170 function isSyndicated() {
171 return true;
172 }
173
174 /**
175 * Formats the results of the query for display. The skin is the current
176 * skin; you can use it for making links. The result is a single row of
177 * result data. You should be able to grab SQL results off of it.
178 * If the function return "false", the line output will be skipped.
179 *
180 * @param $skin Skin object
181 * @param $result Object: database row
182 */
183 function formatResult( $skin, $result ) {
184 return '';
185 }
186
187 /**
188 * The content returned by this function will be output before any result
189 *
190 * @return String
191 */
192 function getPageHeader() {
193 return '';
194 }
195
196 /**
197 * If using extra form wheely-dealies, return a set of parameters here
198 * as an associative array. They will be encoded and added to the paging
199 * links (prev/next/lengths).
200 *
201 * @return Array
202 */
203 function linkParameters() {
204 return array();
205 }
206
207 /**
208 * Some special pages (for example SpecialListusers) might not return the
209 * current object formatted, but return the previous one instead.
210 * Setting this to return true, will call one more time wfFormatResult to
211 * be sure that the very last result is formatted and shown.
212 */
213 function tryLastResult() {
214 return false;
215 }
216
217 /**
218 * Clear the cache and save new results
219 *
220 * @param $limit Integer: limit for SQL statement
221 * @param $ignoreErrors Boolean: whether to ignore database errors
222 */
223 function recache( $limit, $ignoreErrors = true ) {
224 $fname = get_class( $this ) . '::recache';
225 $dbw = wfGetDB( DB_MASTER );
226 $dbr = wfGetDB( DB_SLAVE, array( $this->getName(), __METHOD__, 'vslow' ) );
227 if ( !$dbw || !$dbr ) {
228 return false;
229 }
230
231 $querycache = $dbr->tableName( 'querycache' );
232
233 if ( $ignoreErrors ) {
234 $ignoreW = $dbw->ignoreErrors( true );
235 $ignoreR = $dbr->ignoreErrors( true );
236 }
237
238 # Clear out any old cached data
239 $dbw->delete( 'querycache', array( 'qc_type' => $this->getName() ), $fname );
240 # Do query
241 $sql = $this->getSQL() . $this->getOrder();
242 if ( $limit !== false )
243 $sql = $dbr->limitResult( $sql, $limit, 0 );
244 $res = $dbr->query( $sql, $fname );
245 $num = false;
246 if ( $res ) {
247 $num = $dbr->numRows( $res );
248 # Fetch results
249 $vals = array();
250 while ( $res && $row = $dbr->fetchObject( $res ) ) {
251 if ( isset( $row->value ) ) {
252 $value = intval( $row->value ); // @bug 14414
253 } else {
254 $value = 0;
255 }
256
257 $vals[] = array('qc_type' => $row->type,
258 'qc_namespace' => $row->namespace,
259 'qc_title' => $row->title,
260 'qc_value' => $value);
261 }
262
263 # Save results into the querycache table on the master
264 if ( count( $vals ) ) {
265 if ( !$dbw->insert( 'querycache', $vals, __METHOD__ ) ) {
266 // Set result to false to indicate error
267 $dbr->freeResult( $res );
268 $res = false;
269 }
270 }
271 if ( $res ) {
272 $dbr->freeResult( $res );
273 }
274 if ( $ignoreErrors ) {
275 $dbw->ignoreErrors( $ignoreW );
276 $dbr->ignoreErrors( $ignoreR );
277 }
278
279 # Update the querycache_info record for the page
280 $dbw->delete( 'querycache_info', array( 'qci_type' => $this->getName() ), $fname );
281 $dbw->insert( 'querycache_info', array( 'qci_type' => $this->getName(), 'qci_timestamp' => $dbw->timestamp() ), $fname );
282
283 }
284 return $num;
285 }
286
287 /**
288 * This is the actual workhorse. It does everything needed to make a
289 * real, honest-to-gosh query page.
290 *
291 * @param $offset database query offset
292 * @param $limit database query limit
293 * @param $shownavigation show navigation like "next 200"?
294 */
295 function doQuery( $offset, $limit, $shownavigation=true ) {
296 global $wgUser, $wgOut, $wgLang, $wgContLang;
297
298 $this->offset = $offset;
299 $this->limit = $limit;
300
301 $sname = $this->getName();
302 $fname = get_class($this) . '::doQuery';
303 $dbr = wfGetDB( DB_SLAVE );
304
305 $wgOut->setSyndicated( $this->isSyndicated() );
306
307 if ( !$this->isCached() ) {
308 $sql = $this->getSQL();
309 } else {
310 # Get the cached result
311 $querycache = $dbr->tableName( 'querycache' );
312 $type = $dbr->strencode( $sname );
313 $sql =
314 "SELECT qc_type as type, qc_namespace as namespace,qc_title as title, qc_value as value
315 FROM $querycache WHERE qc_type='$type'";
316
317 if( !$this->listoutput ) {
318
319 # Fetch the timestamp of this update
320 $tRes = $dbr->select( 'querycache_info', array( 'qci_timestamp' ), array( 'qci_type' => $type ), $fname );
321 $tRow = $dbr->fetchObject( $tRes );
322
323 if( $tRow ) {
324 $updated = $wgLang->timeanddate( $tRow->qci_timestamp, true, true );
325 $updateddate = $wgLang->date( $tRow->qci_timestamp, true, true );
326 $updatedtime = $wgLang->time( $tRow->qci_timestamp, true, true );
327 $wgOut->addMeta( 'Data-Cache-Time', $tRow->qci_timestamp );
328 $wgOut->addInlineScript( "var dataCacheTime = '{$tRow->qci_timestamp}';" );
329 $wgOut->addWikiMsg( 'perfcachedts', $updated, $updateddate, $updatedtime );
330 } else {
331 $wgOut->addWikiMsg( 'perfcached' );
332 }
333
334 # If updates on this page have been disabled, let the user know
335 # that the data set won't be refreshed for now
336 global $wgDisableQueryPageUpdate;
337 if( is_array( $wgDisableQueryPageUpdate ) && in_array( $this->getName(), $wgDisableQueryPageUpdate ) ) {
338 $wgOut->addWikiMsg( 'querypage-no-updates' );
339 }
340
341 }
342
343 }
344
345 $sql .= $this->getOrder();
346 $sql = $dbr->limitResult($sql, $limit, $offset);
347 $res = $dbr->query( $sql );
348 $num = $dbr->numRows($res);
349
350 $this->preprocessResults( $dbr, $res );
351
352 $wgOut->addHTML( Xml::openElement( 'div', array('class' => 'mw-spcontent') ) );
353
354 # Top header and navigation
355 if( $shownavigation ) {
356 $wgOut->addHTML( $this->getPageHeader() );
357 if( $num > 0 ) {
358 $wgOut->addHTML( '<p>' . wfShowingResults( $offset, $num ) . '</p>' );
359 # Disable the "next" link when we reach the end
360 $paging = wfViewPrevNext( $offset, $limit, $wgContLang->specialPage( $sname ),
361 wfArrayToCGI( $this->linkParameters() ), ( $num < $limit ) );
362 $wgOut->addHTML( '<p>' . $paging . '</p>' );
363 } else {
364 # No results to show, so don't bother with "showing X of Y" etc.
365 # -- just let the user know and give up now
366 $wgOut->addHTML( '<p>' . wfMsgHtml( 'specialpage-empty' ) . '</p>' );
367 $wgOut->addHTML( Xml::closeElement( 'div' ) );
368 return;
369 }
370 }
371
372 # The actual results; specialist subclasses will want to handle this
373 # with more than a straight list, so we hand them the info, plus
374 # an OutputPage, and let them get on with it
375 $this->outputResults( $wgOut,
376 $wgUser->getSkin(),
377 $dbr, # Should use a ResultWrapper for this
378 $res,
379 $dbr->numRows( $res ),
380 $offset );
381
382 # Repeat the paging links at the bottom
383 if( $shownavigation ) {
384 $wgOut->addHTML( '<p>' . $paging . '</p>' );
385 }
386
387 $wgOut->addHTML( Xml::closeElement( 'div' ) );
388
389 return $num;
390 }
391
392 /**
393 * Format and output report results using the given information plus
394 * OutputPage
395 *
396 * @param $out OutputPage to print to
397 * @param $skin Skin: user skin to use
398 * @param $dbr Database (read) connection to use
399 * @param $res Integer: result pointer
400 * @param $num Integer: number of available result rows
401 * @param $offset Integer: paging offset
402 */
403 protected function outputResults( $out, $skin, $dbr, $res, $num, $offset ) {
404 global $wgContLang;
405
406 if( $num > 0 ) {
407 $html = array();
408 if( !$this->listoutput )
409 $html[] = $this->openList( $offset );
410
411 # $res might contain the whole 1,000 rows, so we read up to
412 # $num [should update this to use a Pager]
413 for( $i = 0; $i < $num && $row = $dbr->fetchObject( $res ); $i++ ) {
414 $line = $this->formatResult( $skin, $row );
415 if( $line ) {
416 $attr = ( isset( $row->usepatrol ) && $row->usepatrol && $row->patrolled == 0 )
417 ? ' class="not-patrolled"'
418 : '';
419 $html[] = $this->listoutput
420 ? $line
421 : "<li{$attr}>{$line}</li>\n";
422 }
423 }
424
425 # Flush the final result
426 if( $this->tryLastResult() ) {
427 $row = null;
428 $line = $this->formatResult( $skin, $row );
429 if( $line ) {
430 $attr = ( isset( $row->usepatrol ) && $row->usepatrol && $row->patrolled == 0 )
431 ? ' class="not-patrolled"'
432 : '';
433 $html[] = $this->listoutput
434 ? $line
435 : "<li{$attr}>{$line}</li>\n";
436 }
437 }
438
439 if( !$this->listoutput )
440 $html[] = $this->closeList();
441
442 $html = $this->listoutput
443 ? $wgContLang->listToText( $html )
444 : implode( '', $html );
445
446 $out->addHTML( $html );
447 }
448 }
449
450 function openList( $offset ) {
451 return "\n<ol start='" . ( $offset + 1 ) . "' class='special'>\n";
452 }
453
454 function closeList() {
455 return "</ol>\n";
456 }
457
458 /**
459 * Do any necessary preprocessing of the result object.
460 */
461 function preprocessResults( $db, $res ) {}
462
463 /**
464 * Similar to above, but packaging in a syndicated feed instead of a web page
465 */
466 function doFeed( $class = '', $limit = 50 ) {
467 global $wgFeed, $wgFeedClasses;
468
469 if ( !$wgFeed ) {
470 global $wgOut;
471 $wgOut->addWikiMsg( 'feed-unavailable' );
472 return;
473 }
474
475 global $wgFeedLimit;
476 if( $limit > $wgFeedLimit ) {
477 $limit = $wgFeedLimit;
478 }
479
480 if( isset($wgFeedClasses[$class]) ) {
481 $feed = new $wgFeedClasses[$class](
482 $this->feedTitle(),
483 $this->feedDesc(),
484 $this->feedUrl() );
485 $feed->outHeader();
486
487 $dbr = wfGetDB( DB_SLAVE );
488 $sql = $this->getSQL() . $this->getOrder();
489 $sql = $dbr->limitResult( $sql, $limit, 0 );
490 $res = $dbr->query( $sql, 'QueryPage::doFeed' );
491 while( $obj = $dbr->fetchObject( $res ) ) {
492 $item = $this->feedResult( $obj );
493 if( $item ) $feed->outItem( $item );
494 }
495 $dbr->freeResult( $res );
496
497 $feed->outFooter();
498 return true;
499 } else {
500 return false;
501 }
502 }
503
504 /**
505 * Override for custom handling. If the titles/links are ok, just do
506 * feedItemDesc()
507 */
508 function feedResult( $row ) {
509 if( !isset( $row->title ) ) {
510 return null;
511 }
512 $title = Title::MakeTitle( intval( $row->namespace ), $row->title );
513 if( $title ) {
514 $date = isset( $row->timestamp ) ? $row->timestamp : '';
515 $comments = '';
516 if( $title ) {
517 $talkpage = $title->getTalkPage();
518 $comments = $talkpage->getFullURL();
519 }
520
521 return new FeedItem(
522 $title->getPrefixedText(),
523 $this->feedItemDesc( $row ),
524 $title->getFullURL(),
525 $date,
526 $this->feedItemAuthor( $row ),
527 $comments);
528 } else {
529 return null;
530 }
531 }
532
533 function feedItemDesc( $row ) {
534 return isset( $row->comment ) ? htmlspecialchars( $row->comment ) : '';
535 }
536
537 function feedItemAuthor( $row ) {
538 return isset( $row->user_text ) ? $row->user_text : '';
539 }
540
541 function feedTitle() {
542 global $wgContLanguageCode, $wgSitename;
543 $page = SpecialPage::getPage( $this->getName() );
544 $desc = $page->getDescription();
545 return "$wgSitename - $desc [$wgContLanguageCode]";
546 }
547
548 function feedDesc() {
549 return wfMsgExt( 'tagline', 'parsemag' );
550 }
551
552 function feedUrl() {
553 $title = SpecialPage::getTitleFor( $this->getName() );
554 return $title->getFullURL();
555 }
556 }
557
558 /**
559 * Class definition for a wanted query page like
560 * WantedPages, WantedTemplates, etc
561 */
562 abstract class WantedQueryPage extends QueryPage {
563
564 function isExpensive() {
565 return true;
566 }
567
568 function isSyndicated() {
569 return false;
570 }
571
572 /**
573 * Cache page existence for performance
574 */
575 function preprocessResults( $db, $res ) {
576 $batch = new LinkBatch;
577 while ( $row = $db->fetchObject( $res ) )
578 $batch->add( $row->namespace, $row->title );
579 $batch->execute();
580
581 // Back to start for display
582 if ( $db->numRows( $res ) > 0 )
583 // If there are no rows we get an error seeking.
584 $db->dataSeek( $res, 0 );
585 }
586
587 /**
588 * Format an individual result
589 *
590 * @param $skin Skin to use for UI elements
591 * @param $result Result row
592 * @return string
593 */
594 public function formatResult( $skin, $result ) {
595 $title = Title::makeTitleSafe( $result->namespace, $result->title );
596 if( $title instanceof Title ) {
597 if( $this->isCached() ) {
598 $pageLink = $title->exists()
599 ? '<del>' . $skin->link( $title ) . '</del>'
600 : $skin->link(
601 $title,
602 null,
603 array(),
604 array(),
605 array( 'broken' )
606 );
607 } else {
608 $pageLink = $skin->link(
609 $title,
610 null,
611 array(),
612 array(),
613 array( 'broken' )
614 );
615 }
616 return wfSpecialList( $pageLink, $this->makeWlhLink( $title, $skin, $result ) );
617 } else {
618 $tsafe = htmlspecialchars( $result->title );
619 return wfMsgHtml( 'wantedpages-badtitle', $tsafe );
620 }
621 }
622
623 /**
624 * Make a "what links here" link for a given title
625 *
626 * @param $title Title to make the link for
627 * @param $skin Skin object to use
628 * @param $result Object: result row
629 * @return string
630 */
631 private function makeWlhLink( $title, $skin, $result ) {
632 global $wgLang;
633 $wlh = SpecialPage::getTitleFor( 'Whatlinkshere' );
634 $label = wfMsgExt( 'nlinks', array( 'parsemag', 'escape' ),
635 $wgLang->formatNum( $result->value ) );
636 return $skin->link( $wlh, $label, array(), array( 'target' => $title->getPrefixedText() ) );
637 }
638 }