(bug 14869) Allow access to QueryPage-based special pages via API
[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 //'pageid' => intval( $row->id ),
183 'ns' => intval( $title->getNamespace() ),
184 'title' => $title->getPrefixedText(),
185 );
186 }
187
188 /**
189 * The content returned by this function will be output before any result
190 */
191 function getPageHeader( ) {
192 return '';
193 }
194
195 /**
196 * If using extra form wheely-dealies, return a set of parameters here
197 * as an associative array. They will be encoded and added to the paging
198 * links (prev/next/lengths).
199 * @return array
200 */
201 function linkParameters() {
202 return array();
203 }
204
205 /**
206 * Some special pages (for example SpecialListusers) might not return the
207 * current object formatted, but return the previous one instead.
208 * Setting this to return true, will call one more time wfFormatResult to
209 * be sure that the very last result is formatted and shown.
210 */
211 function tryLastResult( ) {
212 return false;
213 }
214
215 /**
216 * Clear the cache and save new results
217 */
218 function recache( $limit, $ignoreErrors = true ) {
219 $fname = get_class( $this ) . '::recache';
220 $dbw = wfGetDB( DB_MASTER );
221 $dbr = wfGetDB( DB_SLAVE, array( $this->getName(), __METHOD__, 'vslow' ) );
222 if ( !$dbw || !$dbr ) {
223 return false;
224 }
225
226 $querycache = $dbr->tableName( 'querycache' );
227
228 if ( $ignoreErrors ) {
229 $ignoreW = $dbw->ignoreErrors( true );
230 $ignoreR = $dbr->ignoreErrors( true );
231 }
232
233 # Clear out any old cached data
234 $dbw->delete( 'querycache', array( 'qc_type' => $this->getName() ), $fname );
235 # Do query
236 $sql = $this->getSQL() . $this->getOrder();
237 if ( $limit !== false )
238 $sql = $dbr->limitResult( $sql, $limit, 0 );
239 $res = $dbr->query( $sql, $fname );
240 $num = false;
241 if ( $res ) {
242 $num = $dbr->numRows( $res );
243 # Fetch results
244 $vals = array();
245 while ( $res && $row = $dbr->fetchObject( $res ) ) {
246 if ( isset( $row->value ) ) {
247 $value = intval( $row->value ); // @bug 14414
248 } else {
249 $value = 0;
250 }
251
252 $vals[] = array('qc_type' => $row->type,
253 'qc_namespace' => $row->namespace,
254 'qc_title' => $row->title,
255 'qc_value' => $value);
256 }
257
258 # Save results into the querycache table on the master
259 if ( count( $vals ) ) {
260 if ( !$dbw->insert( 'querycache', $vals, __METHOD__ ) ) {
261 // Set result to false to indicate error
262 $dbr->freeResult( $res );
263 $res = false;
264 }
265 }
266 if ( $res ) {
267 $dbr->freeResult( $res );
268 }
269 if ( $ignoreErrors ) {
270 $dbw->ignoreErrors( $ignoreW );
271 $dbr->ignoreErrors( $ignoreR );
272 }
273
274 # Update the querycache_info record for the page
275 $dbw->delete( 'querycache_info', array( 'qci_type' => $this->getName() ), $fname );
276 $dbw->insert( 'querycache_info', array( 'qci_type' => $this->getName(), 'qci_timestamp' => $dbw->timestamp() ), $fname );
277
278 }
279 return $num;
280 }
281
282 /**
283 * This is the actual workhorse. It does everything needed to make a
284 * real, honest-to-gosh query page.
285 *
286 * @param $offset database query offset
287 * @param $limit database query limit
288 * @param $shownavigation show navigation like "next 200"?
289 */
290 function doQuery( $offset, $limit, $shownavigation=true ) {
291 global $wgUser, $wgOut, $wgLang, $wgContLang;
292
293 $wgOut->setSyndicated( $this->isSyndicated() );
294
295 # Really really do the query now
296 $result = $this->reallyDoQuery( $offset, $limit );
297
298 # Tell about cachiness
299 if ( $result['cached'] !== false ) {
300 if ( $result['cached'] === true ) {
301 $wgOut->addWikiMsg( 'perfcached' );
302 } else {
303 $updated = $wgLang->timeAndDate( $result['cached'], true, true );
304 $wgOut->addMeta( 'Data-Cache-Time', $result['cached'] );
305 $wgOut->addInlineScript( "var dataCacheTime = '{$result['cached']}';" );
306 $wgOut->addWikiMsg( 'perfcachedts', $updated );
307 }
308 }
309 if ( $result['disabled'] ) {
310 # If updates on this page have been disabled, let the user know
311 # that the data set won't be refreshed for now
312
313 $wgOut->addWikiMsg( 'querypage-no-updates' );
314 }
315
316 $wgOut->addHTML( XML::openElement( 'div', array('class' => 'mw-spcontent') ) );
317
318 # Top header and navigation
319 if( $shownavigation ) {
320 $wgOut->addHTML( $this->getPageHeader() );
321 if( $result['count'] > 0 ) {
322 $wgOut->addHTML( '<p>' . wfShowingResults( $offset, $result['count'] ) . '</p>' );
323 # Disable the "next" link when we reach the end
324 $paging = wfViewPrevNext( $offset, $limit, $wgContLang->specialPage( $this->getName() ),
325 wfArrayToCGI( $this->linkParameters() ), ( $result['count'] < $limit ) );
326 $wgOut->addHTML( '<p>' . $paging . '</p>' );
327 } else {
328 # No results to show, so don't bother with "showing X of Y" etc.
329 # -- just let the user know and give up now
330 $wgOut->addHTML( '<p>' . wfMsgHtml( 'specialpage-empty' ) . '</p>' );
331 $wgOut->addHTML( XML::closeElement( 'div' ) );
332 return;
333 }
334 }
335
336 # The actual results; specialist subclasses will want to handle this
337 # with more than a straight list, so we hand them the info, plus
338 # an OutputPage, and let them get on with it
339 $this->outputResults( $wgOut,
340 $wgUser->getSkin(),
341 $result['dbr'], # Should use a ResultWrapper for this
342 $result['result'],
343 $result['count'],
344 $offset );
345
346 # Repeat the paging links at the bottom
347 if( $shownavigation ) {
348 $wgOut->addHTML( '<p>' . $paging . '</p>' );
349 }
350
351 $wgOut->addHTML( XML::closeElement( 'div' ) );
352
353 return $result['count'];
354 }
355
356 /**
357 * Really really do the query. Returns an array with:
358 * 'disabled' => true if the data will not be further refreshed,
359 * 'cached' => false if uncached, the timestamp of the last cache if known, else simply true,
360 * 'result' => the real result object,
361 * 'count' => number of results,
362 * 'dbr' => the database used for fetching the data
363 */
364 public function reallyDoQuery( $offset, $limit ) {
365 $result = array( 'disabled' => false );
366
367 $this->offset = $offset;
368 $this->limit = $limit;
369
370 $fname = get_class($this) . '::reallyDoQuery';
371 $dbr = wfGetDB( DB_SLAVE );
372
373
374 if ( !$this->isCached() ) {
375 $sql = $this->getSQL();
376 $result['cached'] = false;
377 } else {
378 # Get the cached result
379 $querycache = $dbr->tableName( 'querycache' );
380 $type = $dbr->strencode( $this->getName() );
381 $sql =
382 "SELECT qc_type as type, qc_namespace as namespace,qc_title as title, qc_value as value
383 FROM $querycache WHERE qc_type='$type'";
384
385 if( !$this->listoutput ) {
386
387 # Fetch the timestamp of this update
388 $tRes = $dbr->select( 'querycache_info', array( 'qci_timestamp' ), array( 'qci_type' => $type ), $fname );
389 $tRow = $dbr->fetchObject( $tRes );
390
391 if( $tRow ) {
392 $result['cached'] = $tRow->qci_timestamp;
393 } else {
394 $result['cached'] = true;
395 }
396
397 # If updates on this page have been disabled, let the user know
398 # that the data set won't be refreshed for now
399 global $wgDisableQueryPageUpdate;
400 if( is_array( $wgDisableQueryPageUpdate ) && in_array( $this->getName(), $wgDisableQueryPageUpdate ) ) {
401 $result['disabled'] = true;
402 }
403 }
404
405 }
406
407 $sql .= $this->getOrder();
408 $sql = $dbr->limitResult($sql, $limit, $offset);
409 $res = $dbr->query( $sql );
410 $num = $dbr->numRows($res);
411
412 $this->preprocessResults( $dbr, $res );
413
414 $result['result'] = $res;
415 $result['count'] = $num;
416 $result['dbr'] = $dbr;
417 return $result;
418 }
419
420 /**
421 * Format and output report results using the given information plus
422 * OutputPage
423 *
424 * @param OutputPage $out OutputPage to print to
425 * @param Skin $skin User skin to use
426 * @param Database $dbr Database (read) connection to use
427 * @param int $res Result pointer
428 * @param int $num Number of available result rows
429 * @param int $offset Paging offset
430 */
431 protected function outputResults( $out, $skin, $dbr, $res, $num, $offset ) {
432 global $wgContLang;
433
434 if( $num > 0 ) {
435 $html = array();
436 if( !$this->listoutput )
437 $html[] = $this->openList( $offset );
438
439 # $res might contain the whole 1,000 rows, so we read up to
440 # $num [should update this to use a Pager]
441 for ( $i = 0; $i < $num && $row = $dbr->fetchObject( $res ); $i++ ) {
442 $line = $this->formatResult( $skin, $row );
443 if( $line ) {
444 $attr = ( isset( $row->usepatrol ) && $row->usepatrol && $row->patrolled == 0 )
445 ? ' class="not-patrolled"'
446 : '';
447 $html[] = $this->listoutput
448 ? $line
449 : "<li{$attr}>{$line}</li>\n";
450 }
451 }
452
453 # Flush the final result
454 if( $this->tryLastResult() ) {
455 $row = null;
456 $line = $this->formatResult( $skin, $row );
457 if( $line ) {
458 $attr = ( isset( $row->usepatrol ) && $row->usepatrol && $row->patrolled == 0 )
459 ? ' class="not-patrolled"'
460 : '';
461 $html[] = $this->listoutput
462 ? $line
463 : "<li{$attr}>{$line}</li>\n";
464 }
465 }
466
467 if( !$this->listoutput )
468 $html[] = $this->closeList();
469
470 $html = $this->listoutput
471 ? $wgContLang->listToText( $html )
472 : implode( '', $html );
473
474 $out->addHTML( $html );
475 }
476 }
477
478
479 function openList( $offset ) {
480 return "\n<ol start='" . ( $offset + 1 ) . "' class='special'>\n";
481 }
482
483 function closeList() {
484 return "</ol>\n";
485 }
486
487 /**
488 * Do any necessary preprocessing of the result object.
489 */
490 function preprocessResults( $db, $res ) {}
491
492 /**
493 * Similar to above, but packaging in a syndicated feed instead of a web page
494 */
495 function doFeed( $class = '', $limit = 50 ) {
496 global $wgFeed, $wgFeedClasses;
497
498 if ( !$wgFeed ) {
499 global $wgOut;
500 $wgOut->addWikiMsg( 'feed-unavailable' );
501 return;
502 }
503
504 global $wgFeedLimit;
505 if( $limit > $wgFeedLimit ) {
506 $limit = $wgFeedLimit;
507 }
508
509 if( isset($wgFeedClasses[$class]) ) {
510 $feed = new $wgFeedClasses[$class](
511 $this->feedTitle(),
512 $this->feedDesc(),
513 $this->feedUrl() );
514 $feed->outHeader();
515
516 $dbr = wfGetDB( DB_SLAVE );
517 $sql = $this->getSQL() . $this->getOrder();
518 $sql = $dbr->limitResult( $sql, $limit, 0 );
519 $res = $dbr->query( $sql, 'QueryPage::doFeed' );
520 while( $obj = $dbr->fetchObject( $res ) ) {
521 $item = $this->feedResult( $obj );
522 if( $item ) $feed->outItem( $item );
523 }
524 $dbr->freeResult( $res );
525
526 $feed->outFooter();
527 return true;
528 } else {
529 return false;
530 }
531 }
532
533 /**
534 * Override for custom handling. If the titles/links are ok, just do
535 * feedItemDesc()
536 */
537 function feedResult( $row ) {
538 if( !isset( $row->title ) ) {
539 return NULL;
540 }
541 $title = Title::MakeTitle( intval( $row->namespace ), $row->title );
542 if( $title ) {
543 $date = isset( $row->timestamp ) ? $row->timestamp : '';
544 $comments = '';
545 if( $title ) {
546 $talkpage = $title->getTalkPage();
547 $comments = $talkpage->getFullURL();
548 }
549
550 return new FeedItem(
551 $title->getPrefixedText(),
552 $this->feedItemDesc( $row ),
553 $title->getFullURL(),
554 $date,
555 $this->feedItemAuthor( $row ),
556 $comments);
557 } else {
558 return NULL;
559 }
560 }
561
562 function feedItemDesc( $row ) {
563 return isset( $row->comment ) ? htmlspecialchars( $row->comment ) : '';
564 }
565
566 function feedItemAuthor( $row ) {
567 return isset( $row->user_text ) ? $row->user_text : '';
568 }
569
570 function feedTitle() {
571 global $wgContLanguageCode, $wgSitename;
572 $page = SpecialPage::getPage( $this->getName() );
573 $desc = $page->getDescription();
574 return "$wgSitename - $desc [$wgContLanguageCode]";
575 }
576
577 function feedDesc() {
578 return wfMsgExt( 'tagline', 'parsemag' );
579 }
580
581 function feedUrl() {
582 $title = SpecialPage::getTitleFor( $this->getName() );
583 return $title->getFullURL();
584 }
585 }
586
587 /**
588 * Class definition for a wanted query page like
589 * WantedPages, WantedTemplates, etc
590 */
591 abstract class WantedQueryPage extends QueryPage {
592
593 function isExpensive() {
594 return true;
595 }
596
597 function isSyndicated() {
598 return false;
599 }
600
601 /**
602 * Cache page existence for performance
603 */
604 function preprocessResults( $db, $res ) {
605 $batch = new LinkBatch;
606 while ( $row = $db->fetchObject( $res ) )
607 $batch->add( $row->namespace, $row->title );
608 $batch->execute();
609
610 // Back to start for display
611 if ( $db->numRows( $res ) > 0 )
612 // If there are no rows we get an error seeking.
613 $db->dataSeek( $res, 0 );
614 }
615
616 /**
617 * Format an individual result
618 *
619 * @param $skin Skin to use for UI elements
620 * @param $result Result row
621 * @return string
622 */
623 public function formatResult( $skin, $result ) {
624 $title = Title::makeTitleSafe( $result->namespace, $result->title );
625 if( $title instanceof Title ) {
626 if( $this->isCached() ) {
627 $pageLink = $title->exists()
628 ? '<s>' . $skin->link( $title ) . '</s>'
629 : $skin->link(
630 $title,
631 null,
632 array(),
633 array(),
634 array( 'broken' )
635 );
636 } else {
637 $pageLink = $skin->link(
638 $title,
639 null,
640 array(),
641 array(),
642 array( 'broken' )
643 );
644 }
645 return wfSpecialList( $pageLink, $this->makeWlhLink( $title, $skin, $result ) );
646 } else {
647 $tsafe = htmlspecialchars( $result->title );
648 return wfMsgHtml( 'wantedpages-badtitle', $tsafe );
649 }
650 }
651
652 /**
653 * Make a "what links here" link for a given title
654 *
655 * @param Title $title Title to make the link for
656 * @param Skin $skin Skin to use
657 * @param object $result Result row
658 * @return string
659 */
660 private function makeWlhLink( $title, $skin, $result ) {
661 global $wgLang;
662 $wlh = SpecialPage::getTitleFor( 'Whatlinkshere' );
663 $label = wfMsgExt( 'nlinks', array( 'parsemag', 'escape' ),
664 $wgLang->formatNum( $result->value ) );
665 return $skin->link( $wlh, $label, array(), array( 'target' => $title->getPrefixedText() ) );
666 }
667 }