]> scripts.mit.edu Git - autoinstallsdev/mediawiki.git/blob - includes/QueryPage.php
MediaWiki 1.15.5
[autoinstallsdev/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 $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         /**
177          * The content returned by this function will be output before any result
178          */
179         function getPageHeader( ) {
180                 return '';
181         }
182
183         /**
184          * If using extra form wheely-dealies, return a set of parameters here
185          * as an associative array. They will be encoded and added to the paging
186          * links (prev/next/lengths).
187          * @return array
188          */
189         function linkParameters() {
190                 return array();
191         }
192
193         /**
194          * Some special pages (for example SpecialListusers) might not return the
195          * current object formatted, but return the previous one instead.
196          * Setting this to return true, will call one more time wfFormatResult to
197          * be sure that the very last result is formatted and shown.
198          */
199         function tryLastResult( ) {
200                 return false;
201         }
202
203         /**
204          * Clear the cache and save new results
205          */
206         function recache( $limit, $ignoreErrors = true ) {
207                 $fname = get_class( $this ) . '::recache';
208                 $dbw = wfGetDB( DB_MASTER );
209                 $dbr = wfGetDB( DB_SLAVE, array( $this->getName(), 'QueryPage::recache', 'vslow' ) );
210                 if ( !$dbw || !$dbr ) {
211                         return false;
212                 }
213
214                 $querycache = $dbr->tableName( 'querycache' );
215
216                 if ( $ignoreErrors ) {
217                         $ignoreW = $dbw->ignoreErrors( true );
218                         $ignoreR = $dbr->ignoreErrors( true );
219                 }
220
221                 # Clear out any old cached data
222                 $dbw->delete( 'querycache', array( 'qc_type' => $this->getName() ), $fname );
223                 # Do query
224                 $sql = $this->getSQL() . $this->getOrder();
225                 if ( $limit !== false )
226                         $sql = $dbr->limitResult( $sql, $limit, 0 );
227                 $res = $dbr->query( $sql, $fname );
228                 $num = false;
229                 if ( $res ) {
230                         $num = $dbr->numRows( $res );
231                         # Fetch results
232                         $insertSql = "INSERT INTO $querycache (qc_type,qc_namespace,qc_title,qc_value) VALUES ";
233                         $first = true;
234                         while ( $res && $row = $dbr->fetchObject( $res ) ) {
235                                 if ( $first ) {
236                                         $first = false;
237                                 } else {
238                                         $insertSql .= ',';
239                                 }
240                                 if ( isset( $row->value ) ) {
241                                         $value = intval( $row->value ); // @bug 14414
242                                 } else {
243                                         $value = 0;
244                                 }
245
246                                 $insertSql .= '(' .
247                                         $dbw->addQuotes( $row->type ) . ',' .
248                                         $dbw->addQuotes( $row->namespace ) . ',' .
249                                         $dbw->addQuotes( $row->title ) . ',' .
250                                         $dbw->addQuotes( $value ) . ')';
251                         }
252
253                         # Save results into the querycache table on the master
254                         if ( !$first ) {
255                                 if ( !$dbw->query( $insertSql, $fname ) ) {
256                                         // Set result to false to indicate error
257                                         $dbr->freeResult( $res );
258                                         $res = false;
259                                 }
260                         }
261                         if ( $res ) {
262                                 $dbr->freeResult( $res );
263                         }
264                         if ( $ignoreErrors ) {
265                                 $dbw->ignoreErrors( $ignoreW );
266                                 $dbr->ignoreErrors( $ignoreR );
267                         }
268
269                         # Update the querycache_info record for the page
270                         $dbw->delete( 'querycache_info', array( 'qci_type' => $this->getName() ), $fname );
271                         $dbw->insert( 'querycache_info', array( 'qci_type' => $this->getName(), 'qci_timestamp' => $dbw->timestamp() ), $fname );
272
273                 }
274                 return $num;
275         }
276
277         /**
278          * This is the actual workhorse. It does everything needed to make a
279          * real, honest-to-gosh query page.
280          *
281          * @param $offset database query offset
282          * @param $limit database query limit
283          * @param $shownavigation show navigation like "next 200"?
284          */
285         function doQuery( $offset, $limit, $shownavigation=true ) {
286                 global $wgUser, $wgOut, $wgLang, $wgContLang;
287
288                 $this->offset = $offset;
289                 $this->limit = $limit;
290
291                 $sname = $this->getName();
292                 $fname = get_class($this) . '::doQuery';
293                 $dbr = wfGetDB( DB_SLAVE );
294
295                 $wgOut->setSyndicated( $this->isSyndicated() );
296
297                 if ( !$this->isCached() ) {
298                         $sql = $this->getSQL();
299                 } else {
300                         # Get the cached result
301                         $querycache = $dbr->tableName( 'querycache' );
302                         $type = $dbr->strencode( $sname );
303                         $sql =
304                                 "SELECT qc_type as type, qc_namespace as namespace,qc_title as title, qc_value as value
305                                  FROM $querycache WHERE qc_type='$type'";
306
307                         if( !$this->listoutput ) {
308
309                                 # Fetch the timestamp of this update
310                                 $tRes = $dbr->select( 'querycache_info', array( 'qci_timestamp' ), array( 'qci_type' => $type ), $fname );
311                                 $tRow = $dbr->fetchObject( $tRes );
312
313                                 if( $tRow ) {
314                                         $updated = $wgLang->timeAndDate( $tRow->qci_timestamp, true, true );
315                                         $wgOut->addMeta( 'Data-Cache-Time', $tRow->qci_timestamp );
316                                         $wgOut->addInlineScript( "var dataCacheTime = '{$tRow->qci_timestamp}';" );
317                                         $wgOut->addWikiMsg( 'perfcachedts', $updated );
318                                 } else {
319                                         $wgOut->addWikiMsg( 'perfcached' );
320                                 }
321
322                                 # If updates on this page have been disabled, let the user know
323                                 # that the data set won't be refreshed for now
324                                 global $wgDisableQueryPageUpdate;
325                                 if( is_array( $wgDisableQueryPageUpdate ) && in_array( $this->getName(), $wgDisableQueryPageUpdate ) ) {
326                                         $wgOut->addWikiMsg( 'querypage-no-updates' );
327                                 }
328
329                         }
330
331                 }
332
333                 $sql .= $this->getOrder();
334                 $sql = $dbr->limitResult($sql, $limit, $offset);
335                 $res = $dbr->query( $sql );
336                 $num = $dbr->numRows($res);
337
338                 $this->preprocessResults( $dbr, $res );
339
340                 $wgOut->addHTML( XML::openElement( 'div', array('class' => 'mw-spcontent') ) );
341
342                 # Top header and navigation
343                 if( $shownavigation ) {
344                         $wgOut->addHTML( $this->getPageHeader() );
345                         if( $num > 0 ) {
346                                 $wgOut->addHTML( '<p>' . wfShowingResults( $offset, $num ) . '</p>' );
347                                 # Disable the "next" link when we reach the end
348                                 $paging = wfViewPrevNext( $offset, $limit, $wgContLang->specialPage( $sname ),
349                                         wfArrayToCGI( $this->linkParameters() ), ( $num < $limit ) );
350                                 $wgOut->addHTML( '<p>' . $paging . '</p>' );
351                         } else {
352                                 # No results to show, so don't bother with "showing X of Y" etc.
353                                 # -- just let the user know and give up now
354                                 $wgOut->addHTML( '<p>' . wfMsgHtml( 'specialpage-empty' ) . '</p>' );
355                                 $wgOut->addHTML( XML::closeElement( 'div' ) );
356                                 return;
357                         }
358                 }
359
360                 # The actual results; specialist subclasses will want to handle this
361                 # with more than a straight list, so we hand them the info, plus
362                 # an OutputPage, and let them get on with it
363                 $this->outputResults( $wgOut,
364                         $wgUser->getSkin(),
365                         $dbr, # Should use a ResultWrapper for this
366                         $res,
367                         $dbr->numRows( $res ),
368                         $offset );
369
370                 # Repeat the paging links at the bottom
371                 if( $shownavigation ) {
372                         $wgOut->addHTML( '<p>' . $paging . '</p>' );
373                 }
374
375                 $wgOut->addHTML( XML::closeElement( 'div' ) );
376
377                 return $num;
378         }
379
380         /**
381          * Format and output report results using the given information plus
382          * OutputPage
383          *
384          * @param OutputPage $out OutputPage to print to
385          * @param Skin $skin User skin to use
386          * @param Database $dbr Database (read) connection to use
387          * @param int $res Result pointer
388          * @param int $num Number of available result rows
389          * @param int $offset Paging offset
390          */
391         protected function outputResults( $out, $skin, $dbr, $res, $num, $offset ) {
392                 global $wgContLang;
393
394                 if( $num > 0 ) {
395                         $html = array();
396                         if( !$this->listoutput )
397                                 $html[] = $this->openList( $offset );
398
399                         # $res might contain the whole 1,000 rows, so we read up to
400                         # $num [should update this to use a Pager]
401                         for( $i = 0; $i < $num && $row = $dbr->fetchObject( $res ); $i++ ) {
402                                 $line = $this->formatResult( $skin, $row );
403                                 if( $line ) {
404                                         $attr = ( isset( $row->usepatrol ) && $row->usepatrol && $row->patrolled == 0 )
405                                                 ? ' class="not-patrolled"'
406                                                 : '';
407                                         $html[] = $this->listoutput
408                                                 ? $line
409                                                 : "<li{$attr}>{$line}</li>\n";
410                                 }
411                         }
412
413                         # Flush the final result
414                         if( $this->tryLastResult() ) {
415                                 $row = null;
416                                 $line = $this->formatResult( $skin, $row );
417                                 if( $line ) {
418                                         $attr = ( isset( $row->usepatrol ) && $row->usepatrol && $row->patrolled == 0 )
419                                                 ? ' class="not-patrolled"'
420                                                 : '';
421                                         $html[] = $this->listoutput
422                                                 ? $line
423                                                 : "<li{$attr}>{$line}</li>\n";
424                                 }
425                         }
426
427                         if( !$this->listoutput )
428                                 $html[] = $this->closeList();
429
430                         $html = $this->listoutput
431                                 ? $wgContLang->listToText( $html )
432                                 : implode( '', $html );
433
434                         $out->addHTML( $html );
435                 }
436         }
437
438         function openList( $offset ) {
439                 return "\n<ol start='" . ( $offset + 1 ) . "' class='special'>\n";
440         }
441
442         function closeList() {
443                 return "</ol>\n";
444         }
445
446         /**
447          * Do any necessary preprocessing of the result object.
448          */
449         function preprocessResults( $db, $res ) {}
450
451         /**
452          * Similar to above, but packaging in a syndicated feed instead of a web page
453          */
454         function doFeed( $class = '', $limit = 50 ) {
455                 global $wgFeed, $wgFeedClasses;
456
457                 if ( !$wgFeed ) {
458                         global $wgOut;
459                         $wgOut->addWikiMsg( 'feed-unavailable' );
460                         return;
461                 }
462                 
463                 global $wgFeedLimit;
464                 if( $limit > $wgFeedLimit ) {
465                         $limit = $wgFeedLimit;
466                 }
467
468                 if( isset($wgFeedClasses[$class]) ) {
469                         $feed = new $wgFeedClasses[$class](
470                                 $this->feedTitle(),
471                                 $this->feedDesc(),
472                                 $this->feedUrl() );
473                         $feed->outHeader();
474
475                         $dbr = wfGetDB( DB_SLAVE );
476                         $sql = $this->getSQL() . $this->getOrder();
477                         $sql = $dbr->limitResult( $sql, $limit, 0 );
478                         $res = $dbr->query( $sql, 'QueryPage::doFeed' );
479                         while( $obj = $dbr->fetchObject( $res ) ) {
480                                 $item = $this->feedResult( $obj );
481                                 if( $item ) $feed->outItem( $item );
482                         }
483                         $dbr->freeResult( $res );
484
485                         $feed->outFooter();
486                         return true;
487                 } else {
488                         return false;
489                 }
490         }
491
492         /**
493          * Override for custom handling. If the titles/links are ok, just do
494          * feedItemDesc()
495          */
496         function feedResult( $row ) {
497                 if( !isset( $row->title ) ) {
498                         return NULL;
499                 }
500                 $title = Title::MakeTitle( intval( $row->namespace ), $row->title );
501                 if( $title ) {
502                         $date = isset( $row->timestamp ) ? $row->timestamp : '';
503                         $comments = '';
504                         if( $title ) {
505                                 $talkpage = $title->getTalkPage();
506                                 $comments = $talkpage->getFullURL();
507                         }
508
509                         return new FeedItem(
510                                 $title->getPrefixedText(),
511                                 $this->feedItemDesc( $row ),
512                                 $title->getFullURL(),
513                                 $date,
514                                 $this->feedItemAuthor( $row ),
515                                 $comments);
516                 } else {
517                         return NULL;
518                 }
519         }
520
521         function feedItemDesc( $row ) {
522                 return isset( $row->comment ) ? htmlspecialchars( $row->comment ) : '';
523         }
524
525         function feedItemAuthor( $row ) {
526                 return isset( $row->user_text ) ? $row->user_text : '';
527         }
528
529         function feedTitle() {
530                 global $wgContLanguageCode, $wgSitename;
531                 $page = SpecialPage::getPage( $this->getName() );
532                 $desc = $page->getDescription();
533                 return "$wgSitename - $desc [$wgContLanguageCode]";
534         }
535
536         function feedDesc() {
537                 return wfMsgExt( 'tagline', 'parsemag' );
538         }
539
540         function feedUrl() {
541                 $title = SpecialPage::getTitleFor( $this->getName() );
542                 return $title->getFullURL();
543         }
544 }