coding style tweaks
[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 $res = false;
268 }
269 }
270 if ( $ignoreErrors ) {
271 $dbw->ignoreErrors( $ignoreW );
272 $dbr->ignoreErrors( $ignoreR );
273 }
274
275 # Update the querycache_info record for the page
276 $dbw->delete( 'querycache_info', array( 'qci_type' => $this->getName() ), $fname );
277 $dbw->insert( 'querycache_info', array( 'qci_type' => $this->getName(), 'qci_timestamp' => $dbw->timestamp() ), $fname );
278
279 }
280 return $num;
281 }
282
283 /**
284 * This is the actual workhorse. It does everything needed to make a
285 * real, honest-to-gosh query page.
286 *
287 * @param $offset database query offset
288 * @param $limit database query limit
289 * @param $shownavigation show navigation like "next 200"?
290 */
291 function doQuery( $offset, $limit, $shownavigation=true ) {
292 global $wgUser, $wgOut, $wgLang, $wgContLang;
293
294 $this->offset = $offset;
295 $this->limit = $limit;
296
297 $sname = $this->getName();
298 $fname = get_class($this) . '::doQuery';
299 $dbr = wfGetDB( DB_SLAVE );
300
301 $wgOut->setSyndicated( $this->isSyndicated() );
302
303 if ( !$this->isCached() ) {
304 $sql = $this->getSQL();
305 } else {
306 # Get the cached result
307 $querycache = $dbr->tableName( 'querycache' );
308 $type = $dbr->strencode( $sname );
309 $sql =
310 "SELECT qc_type as type, qc_namespace as namespace,qc_title as title, qc_value as value
311 FROM $querycache WHERE qc_type='$type'";
312
313 if( !$this->listoutput ) {
314
315 # Fetch the timestamp of this update
316 $tRes = $dbr->select( 'querycache_info', array( 'qci_timestamp' ), array( 'qci_type' => $type ), $fname );
317 $tRow = $dbr->fetchObject( $tRes );
318
319 if( $tRow ) {
320 $updated = $wgLang->timeanddate( $tRow->qci_timestamp, true, true );
321 $updateddate = $wgLang->date( $tRow->qci_timestamp, true, true );
322 $updatedtime = $wgLang->time( $tRow->qci_timestamp, true, true );
323 $wgOut->addMeta( 'Data-Cache-Time', $tRow->qci_timestamp );
324 $wgOut->addInlineScript( "var dataCacheTime = '{$tRow->qci_timestamp}';" );
325 $wgOut->addWikiMsg( 'perfcachedts', $updated, $updateddate, $updatedtime );
326 } else {
327 $wgOut->addWikiMsg( 'perfcached' );
328 }
329
330 # If updates on this page have been disabled, let the user know
331 # that the data set won't be refreshed for now
332 global $wgDisableQueryPageUpdate;
333 if( is_array( $wgDisableQueryPageUpdate ) && in_array( $this->getName(), $wgDisableQueryPageUpdate ) ) {
334 $wgOut->addWikiMsg( 'querypage-no-updates' );
335 }
336
337 }
338
339 }
340
341 $sql .= $this->getOrder();
342 $sql = $dbr->limitResult($sql, $limit, $offset);
343 $res = $dbr->query( $sql );
344 $num = $dbr->numRows($res);
345
346 $this->preprocessResults( $dbr, $res );
347
348 $wgOut->addHTML( Xml::openElement( 'div', array('class' => 'mw-spcontent') ) );
349
350 # Top header and navigation
351 if( $shownavigation ) {
352 $wgOut->addHTML( $this->getPageHeader() );
353 if( $num > 0 ) {
354 $wgOut->addHTML( '<p>' . wfShowingResults( $offset, $num ) . '</p>' );
355 # Disable the "next" link when we reach the end
356 $paging = wfViewPrevNext( $offset, $limit, $wgContLang->specialPage( $sname ),
357 wfArrayToCGI( $this->linkParameters() ), ( $num < $limit ) );
358 $wgOut->addHTML( '<p>' . $paging . '</p>' );
359 } else {
360 # No results to show, so don't bother with "showing X of Y" etc.
361 # -- just let the user know and give up now
362 $wgOut->addHTML( '<p>' . wfMsgHtml( 'specialpage-empty' ) . '</p>' );
363 $wgOut->addHTML( Xml::closeElement( 'div' ) );
364 return;
365 }
366 }
367
368 # The actual results; specialist subclasses will want to handle this
369 # with more than a straight list, so we hand them the info, plus
370 # an OutputPage, and let them get on with it
371 $this->outputResults( $wgOut,
372 $wgUser->getSkin(),
373 $dbr, # Should use a ResultWrapper for this
374 $res,
375 $dbr->numRows( $res ),
376 $offset );
377
378 # Repeat the paging links at the bottom
379 if( $shownavigation ) {
380 $wgOut->addHTML( '<p>' . $paging . '</p>' );
381 }
382
383 $wgOut->addHTML( Xml::closeElement( 'div' ) );
384
385 return $num;
386 }
387
388 /**
389 * Format and output report results using the given information plus
390 * OutputPage
391 *
392 * @param $out OutputPage to print to
393 * @param $skin Skin: user skin to use
394 * @param $dbr Database (read) connection to use
395 * @param $res Integer: result pointer
396 * @param $num Integer: number of available result rows
397 * @param $offset Integer: paging offset
398 */
399 protected function outputResults( $out, $skin, $dbr, $res, $num, $offset ) {
400 global $wgContLang;
401
402 if( $num > 0 ) {
403 $html = array();
404 if( !$this->listoutput )
405 $html[] = $this->openList( $offset );
406
407 # $res might contain the whole 1,000 rows, so we read up to
408 # $num [should update this to use a Pager]
409 for( $i = 0; $i < $num && $row = $dbr->fetchObject( $res ); $i++ ) {
410 $line = $this->formatResult( $skin, $row );
411 if( $line ) {
412 $attr = ( isset( $row->usepatrol ) && $row->usepatrol && $row->patrolled == 0 )
413 ? ' class="not-patrolled"'
414 : '';
415 $html[] = $this->listoutput
416 ? $line
417 : "<li{$attr}>{$line}</li>\n";
418 }
419 }
420
421 # Flush the final result
422 if( $this->tryLastResult() ) {
423 $row = null;
424 $line = $this->formatResult( $skin, $row );
425 if( $line ) {
426 $attr = ( isset( $row->usepatrol ) && $row->usepatrol && $row->patrolled == 0 )
427 ? ' class="not-patrolled"'
428 : '';
429 $html[] = $this->listoutput
430 ? $line
431 : "<li{$attr}>{$line}</li>\n";
432 }
433 }
434
435 if( !$this->listoutput )
436 $html[] = $this->closeList();
437
438 $html = $this->listoutput
439 ? $wgContLang->listToText( $html )
440 : implode( '', $html );
441
442 $out->addHTML( $html );
443 }
444 }
445
446 function openList( $offset ) {
447 return "\n<ol start='" . ( $offset + 1 ) . "' class='special'>\n";
448 }
449
450 function closeList() {
451 return "</ol>\n";
452 }
453
454 /**
455 * Do any necessary preprocessing of the result object.
456 */
457 function preprocessResults( $db, $res ) {}
458
459 /**
460 * Similar to above, but packaging in a syndicated feed instead of a web page
461 */
462 function doFeed( $class = '', $limit = 50 ) {
463 global $wgFeed, $wgFeedClasses;
464
465 if ( !$wgFeed ) {
466 global $wgOut;
467 $wgOut->addWikiMsg( 'feed-unavailable' );
468 return;
469 }
470
471 global $wgFeedLimit;
472 if( $limit > $wgFeedLimit ) {
473 $limit = $wgFeedLimit;
474 }
475
476 if( isset($wgFeedClasses[$class]) ) {
477 $feed = new $wgFeedClasses[$class](
478 $this->feedTitle(),
479 $this->feedDesc(),
480 $this->feedUrl() );
481 $feed->outHeader();
482
483 $dbr = wfGetDB( DB_SLAVE );
484 $sql = $this->getSQL() . $this->getOrder();
485 $sql = $dbr->limitResult( $sql, $limit, 0 );
486 $res = $dbr->query( $sql, 'QueryPage::doFeed' );
487 while( $obj = $dbr->fetchObject( $res ) ) {
488 $item = $this->feedResult( $obj );
489 if( $item ) $feed->outItem( $item );
490 }
491
492 $feed->outFooter();
493 return true;
494 } else {
495 return false;
496 }
497 }
498
499 /**
500 * Override for custom handling. If the titles/links are ok, just do
501 * feedItemDesc()
502 */
503 function feedResult( $row ) {
504 if( !isset( $row->title ) ) {
505 return null;
506 }
507 $title = Title::MakeTitle( intval( $row->namespace ), $row->title );
508 if( $title ) {
509 $date = isset( $row->timestamp ) ? $row->timestamp : '';
510 $comments = '';
511 if( $title ) {
512 $talkpage = $title->getTalkPage();
513 $comments = $talkpage->getFullURL();
514 }
515
516 return new FeedItem(
517 $title->getPrefixedText(),
518 $this->feedItemDesc( $row ),
519 $title->getFullURL(),
520 $date,
521 $this->feedItemAuthor( $row ),
522 $comments);
523 } else {
524 return null;
525 }
526 }
527
528 function feedItemDesc( $row ) {
529 return isset( $row->comment ) ? htmlspecialchars( $row->comment ) : '';
530 }
531
532 function feedItemAuthor( $row ) {
533 return isset( $row->user_text ) ? $row->user_text : '';
534 }
535
536 function feedTitle() {
537 global $wgContLanguageCode, $wgSitename;
538 $page = SpecialPage::getPage( $this->getName() );
539 $desc = $page->getDescription();
540 return "$wgSitename - $desc [$wgContLanguageCode]";
541 }
542
543 function feedDesc() {
544 return wfMsgExt( 'tagline', 'parsemag' );
545 }
546
547 function feedUrl() {
548 $title = SpecialPage::getTitleFor( $this->getName() );
549 return $title->getFullURL();
550 }
551 }
552
553 /**
554 * Class definition for a wanted query page like
555 * WantedPages, WantedTemplates, etc
556 */
557 abstract class WantedQueryPage extends QueryPage {
558
559 function isExpensive() {
560 return true;
561 }
562
563 function isSyndicated() {
564 return false;
565 }
566
567 /**
568 * Cache page existence for performance
569 */
570 function preprocessResults( $db, $res ) {
571 $batch = new LinkBatch;
572 while ( $row = $db->fetchObject( $res ) )
573 $batch->add( $row->namespace, $row->title );
574 $batch->execute();
575
576 // Back to start for display
577 if ( $db->numRows( $res ) > 0 )
578 // If there are no rows we get an error seeking.
579 $db->dataSeek( $res, 0 );
580 }
581
582 /**
583 * Format an individual result
584 *
585 * @param $skin Skin to use for UI elements
586 * @param $result Result row
587 * @return string
588 */
589 public function formatResult( $skin, $result ) {
590 $title = Title::makeTitleSafe( $result->namespace, $result->title );
591 if( $title instanceof Title ) {
592 if( $this->isCached() ) {
593 $pageLink = $title->exists()
594 ? '<del>' . $skin->link( $title ) . '</del>'
595 : $skin->link(
596 $title,
597 null,
598 array(),
599 array(),
600 array( 'broken' )
601 );
602 } else {
603 $pageLink = $skin->link(
604 $title,
605 null,
606 array(),
607 array(),
608 array( 'broken' )
609 );
610 }
611 return wfSpecialList( $pageLink, $this->makeWlhLink( $title, $skin, $result ) );
612 } else {
613 $tsafe = htmlspecialchars( $result->title );
614 return wfMsgHtml( 'wantedpages-badtitle', $tsafe );
615 }
616 }
617
618 /**
619 * Make a "what links here" link for a given title
620 *
621 * @param $title Title to make the link for
622 * @param $skin Skin object to use
623 * @param $result Object: result row
624 * @return string
625 */
626 private function makeWlhLink( $title, $skin, $result ) {
627 global $wgLang;
628 $wlh = SpecialPage::getTitleFor( 'Whatlinkshere' );
629 $label = wfMsgExt( 'nlinks', array( 'parsemag', 'escape' ),
630 $wgLang->formatNum( $result->value ) );
631 return $skin->link( $wlh, $label, array(), array( 'target' => $title->getPrefixedText() ) );
632 }
633 }