]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/QueryPage.php
MediaWiki 1.17.0
[autoinstalls/mediawiki.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                 if ( $ignoreErrors ) {
232                         $ignoreW = $dbw->ignoreErrors( true );
233                         $ignoreR = $dbr->ignoreErrors( true );
234                 }
235
236                 # Clear out any old cached data
237                 $dbw->delete( 'querycache', array( 'qc_type' => $this->getName() ), $fname );
238                 # Do query
239                 $sql = $this->getSQL() . $this->getOrder();
240                 if ( $limit !== false )
241                         $sql = $dbr->limitResult( $sql, $limit, 0 );
242                 $res = $dbr->query( $sql, $fname );
243                 $num = false;
244                 if ( $res ) {
245                         $num = $dbr->numRows( $res );
246                         # Fetch results
247                         $vals = array();
248                         while ( $res && $row = $dbr->fetchObject( $res ) ) {
249                                 if ( isset( $row->value ) ) {
250                                         $value = intval( $row->value ); // @bug 14414
251                                 } else {
252                                         $value = 0;
253                                 }
254                                 
255                                 $vals[] = array('qc_type' => $row->type,
256                                                 'qc_namespace' => $row->namespace,
257                                                 'qc_title' => $row->title,
258                                                 'qc_value' => $value);
259                         }
260
261                         # Save results into the querycache table on the master
262                         if ( count( $vals ) ) {
263                                 if ( !$dbw->insert( 'querycache', $vals, __METHOD__ ) ) {
264                                         // Set result to false to indicate error
265                                         $res = false;
266                                 }
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                 $this->offset = $offset;
293                 $this->limit = $limit;
294
295                 $sname = $this->getName();
296                 $fname = get_class($this) . '::doQuery';
297                 $dbr = wfGetDB( DB_SLAVE );
298
299                 $wgOut->setSyndicated( $this->isSyndicated() );
300
301                 if ( !$this->isCached() ) {
302                         $sql = $this->getSQL();
303                 } else {
304                         # Get the cached result
305                         $querycache = $dbr->tableName( 'querycache' );
306                         $type = $dbr->strencode( $sname );
307                         $sql =
308                                 "SELECT qc_type as type, qc_namespace as namespace,qc_title as title, qc_value as value
309                                  FROM $querycache WHERE qc_type='$type'";
310
311                         if( !$this->listoutput ) {
312
313                                 # Fetch the timestamp of this update
314                                 $tRes = $dbr->select( 'querycache_info', array( 'qci_timestamp' ), array( 'qci_type' => $type ), $fname );
315                                 $tRow = $dbr->fetchObject( $tRes );
316
317                                 if( $tRow ) {
318                                         $updated = $wgLang->timeanddate( $tRow->qci_timestamp, true, true );
319                                         $updateddate = $wgLang->date( $tRow->qci_timestamp, true, true );
320                                         $updatedtime = $wgLang->time( $tRow->qci_timestamp, true, true );
321                                         $wgOut->addMeta( 'Data-Cache-Time', $tRow->qci_timestamp );
322                                         $wgOut->addInlineScript( "var dataCacheTime = '{$tRow->qci_timestamp}';" );
323                                         $wgOut->addWikiMsg( 'perfcachedts', $updated, $updateddate, $updatedtime );
324                                 } else {
325                                         $wgOut->addWikiMsg( 'perfcached' );
326                                 }
327
328                                 # If updates on this page have been disabled, let the user know
329                                 # that the data set won't be refreshed for now
330                                 global $wgDisableQueryPageUpdate;
331                                 if( is_array( $wgDisableQueryPageUpdate ) && in_array( $this->getName(), $wgDisableQueryPageUpdate ) ) {
332                                         $wgOut->addWikiMsg( 'querypage-no-updates' );
333                                 }
334
335                         }
336
337                 }
338
339                 $sql .= $this->getOrder();
340                 $sql = $dbr->limitResult($sql, $limit, $offset);
341                 $res = $dbr->query( $sql );
342                 $num = $dbr->numRows($res);
343
344                 $this->preprocessResults( $dbr, $res );
345
346                 $wgOut->addHTML( Xml::openElement( 'div', array('class' => 'mw-spcontent') ) );
347
348                 # Top header and navigation
349                 if( $shownavigation ) {
350                         $wgOut->addHTML( $this->getPageHeader() );
351                         if( $num > 0 ) {
352                                 $wgOut->addHTML( '<p>' . wfShowingResults( $offset, $num ) . '</p>' );
353                                 # Disable the "next" link when we reach the end
354                                 $paging = wfViewPrevNext( $offset, $limit, $wgContLang->specialPage( $sname ),
355                                         wfArrayToCGI( $this->linkParameters() ), ( $num < $limit ) );
356                                 $wgOut->addHTML( '<p>' . $paging . '</p>' );
357                         } else {
358                                 # No results to show, so don't bother with "showing X of Y" etc.
359                                 # -- just let the user know and give up now
360                                 $wgOut->addHTML( '<p>' . wfMsgHtml( 'specialpage-empty' ) . '</p>' );
361                                 $wgOut->addHTML( Xml::closeElement( 'div' ) );
362                                 return;
363                         }
364                 }
365
366                 # The actual results; specialist subclasses will want to handle this
367                 # with more than a straight list, so we hand them the info, plus
368                 # an OutputPage, and let them get on with it
369                 $this->outputResults( $wgOut,
370                         $wgUser->getSkin(),
371                         $dbr, # Should use a ResultWrapper for this
372                         $res,
373                         $dbr->numRows( $res ),
374                         $offset );
375
376                 # Repeat the paging links at the bottom
377                 if( $shownavigation ) {
378                         $wgOut->addHTML( '<p>' . $paging . '</p>' );
379                 }
380
381                 $wgOut->addHTML( Xml::closeElement( 'div' ) );
382
383                 return $num;
384         }
385
386         /**
387          * Format and output report results using the given information plus
388          * OutputPage
389          *
390          * @param $out OutputPage to print to
391          * @param $skin Skin: user skin to use
392          * @param $dbr Database (read) connection to use
393          * @param $res Integer: result pointer
394          * @param $num Integer: number of available result rows
395          * @param $offset Integer: paging offset
396          */
397         protected function outputResults( $out, $skin, $dbr, $res, $num, $offset ) {
398                 global $wgContLang;
399
400                 if( $num > 0 ) {
401                         $html = array();
402                         if( !$this->listoutput )
403                                 $html[] = $this->openList( $offset );
404
405                         # $res might contain the whole 1,000 rows, so we read up to
406                         # $num [should update this to use a Pager]
407                         for( $i = 0; $i < $num && $row = $dbr->fetchObject( $res ); $i++ ) {
408                                 $line = $this->formatResult( $skin, $row );
409                                 if( $line ) {
410                                         $attr = ( isset( $row->usepatrol ) && $row->usepatrol && $row->patrolled == 0 )
411                                                 ? ' class="not-patrolled"'
412                                                 : '';
413                                         $html[] = $this->listoutput
414                                                 ? $line
415                                                 : "<li{$attr}>{$line}</li>\n";
416                                 }
417                         }
418
419                         # Flush the final result
420                         if( $this->tryLastResult() ) {
421                                 $row = null;
422                                 $line = $this->formatResult( $skin, $row );
423                                 if( $line ) {
424                                         $attr = ( isset( $row->usepatrol ) && $row->usepatrol && $row->patrolled == 0 )
425                                                 ? ' class="not-patrolled"'
426                                                 : '';
427                                         $html[] = $this->listoutput
428                                                 ? $line
429                                                 : "<li{$attr}>{$line}</li>\n";
430                                 }
431                         }
432
433                         if( !$this->listoutput )
434                                 $html[] = $this->closeList();
435
436                         $html = $this->listoutput
437                                 ? $wgContLang->listToText( $html )
438                                 : implode( '', $html );
439
440                         $out->addHTML( $html );
441                 }
442         }
443
444         function openList( $offset ) {
445                 return "\n<ol start='" . ( $offset + 1 ) . "' class='special'>\n";
446         }
447
448         function closeList() {
449                 return "</ol>\n";
450         }
451
452         /**
453          * Do any necessary preprocessing of the result object.
454          */
455         function preprocessResults( $db, $res ) {}
456
457         /**
458          * Similar to above, but packaging in a syndicated feed instead of a web page
459          */
460         function doFeed( $class = '', $limit = 50 ) {
461                 global $wgFeed, $wgFeedClasses;
462
463                 if ( !$wgFeed ) {
464                         global $wgOut;
465                         $wgOut->addWikiMsg( 'feed-unavailable' );
466                         return;
467                 }
468                 
469                 global $wgFeedLimit;
470                 if( $limit > $wgFeedLimit ) {
471                         $limit = $wgFeedLimit;
472                 }
473
474                 if( isset($wgFeedClasses[$class]) ) {
475                         $feed = new $wgFeedClasses[$class](
476                                 $this->feedTitle(),
477                                 $this->feedDesc(),
478                                 $this->feedUrl() );
479                         $feed->outHeader();
480
481                         $dbr = wfGetDB( DB_SLAVE );
482                         $sql = $this->getSQL() . $this->getOrder();
483                         $sql = $dbr->limitResult( $sql, $limit, 0 );
484                         $res = $dbr->query( $sql, 'QueryPage::doFeed' );
485                         foreach ( $res as $obj ) {
486                                 $item = $this->feedResult( $obj );
487                                 if( $item ) {
488                                         $feed->outItem( $item );
489                                 }
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 $wgLanguageCode, $wgSitename;
538                 $page = SpecialPage::getPage( $this->getName() );
539                 $desc = $page->getDescription();
540                 return "$wgSitename - $desc [$wgLanguageCode]";
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                 foreach ( $res as $row ) {
573                         $batch->add( $row->namespace, $row->title );
574                 }
575                 $batch->execute();
576
577                 // Back to start for display
578                 if ( $db->numRows( $res ) > 0 )
579                         // If there are no rows we get an error seeking.
580                         $db->dataSeek( $res, 0 );
581         }
582         
583         /**
584          * Should formatResult() always check page existence, even if
585          * the results are fresh?  This is a (hopefully temporary)
586          * kluge for Special:WantedFiles, which may contain false
587          * positives for files that exist e.g. in a shared repo (bug
588          * 6220).
589          */
590         function forceExistenceCheck() {
591                 return false;
592         }
593
594         /**
595          * Format an individual result
596          *
597          * @param $skin Skin to use for UI elements
598          * @param $result Result row
599          * @return string
600          */
601         public function formatResult( $skin, $result ) {
602                 $title = Title::makeTitleSafe( $result->namespace, $result->title );
603                 if( $title instanceof Title ) {
604                         if( $this->isCached() || $this->forceExistenceCheck() ) {
605                                 $pageLink = $title->isKnown()
606                                         ? '<del>' . $skin->link( $title ) . '</del>'
607                                         : $skin->link(
608                                                 $title,
609                                                 null,
610                                                 array(),
611                                                 array(),
612                                                 array( 'broken' )
613                                         );
614                         } else {
615                                 $pageLink = $skin->link(
616                                         $title,
617                                         null,
618                                         array(),
619                                         array(),
620                                         array( 'broken' )
621                                 );
622                         }
623                         return wfSpecialList( $pageLink, $this->makeWlhLink( $title, $skin, $result ) );
624                 } else {
625                         $tsafe = htmlspecialchars( $result->title );
626                         return wfMsgHtml( 'wantedpages-badtitle', $tsafe );
627                 }
628         }
629         
630         /**
631          * Make a "what links here" link for a given title
632          *
633          * @param $title Title to make the link for
634          * @param $skin Skin object to use
635          * @param $result Object: result row
636          * @return string
637          */
638         private function makeWlhLink( $title, $skin, $result ) {
639                 global $wgLang;
640                 $wlh = SpecialPage::getTitleFor( 'Whatlinkshere' );
641                 $label = wfMsgExt( 'nlinks', array( 'parsemag', 'escape' ),
642                 $wgLang->formatNum( $result->value ) );
643                 return $skin->link( $wlh, $label, array(), array( 'target' => $title->getPrefixedText() ) );
644         }
645 }