* Add wfReadOnlyReason() to supply the reason for the wiki being read only. Use it...
[lhc/web/wiklou.git] / includes / QueryPage.php
1 <?php
2 /**
3 * Contain a class for special pages
4 */
5
6 /**
7 * List of query page classes and their associated special pages,
8 * for periodic updates.
9 *
10 * DO NOT CHANGE THIS LIST without testing that
11 * maintenance/updateSpecialPages.php still works.
12 */
13 global $wgQueryPages; // not redundant
14 $wgQueryPages = array(
15 // QueryPage subclass Special page name Limit (false for none, none for the default)
16 //----------------------------------------------------------------------------
17 array( 'AncientPagesPage', 'Ancientpages' ),
18 array( 'BrokenRedirectsPage', 'BrokenRedirects' ),
19 array( 'DeadendPagesPage', 'Deadendpages' ),
20 array( 'DisambiguationsPage', 'Disambiguations' ),
21 array( 'DoubleRedirectsPage', 'DoubleRedirects' ),
22 array( 'ListredirectsPage', 'Listredirects' ),
23 array( 'LonelyPagesPage', 'Lonelypages' ),
24 array( 'LongPagesPage', 'Longpages' ),
25 array( 'MostcategoriesPage', 'Mostcategories' ),
26 array( 'MostimagesPage', 'Mostimages' ),
27 array( 'MostlinkedCategoriesPage', 'Mostlinkedcategories' ),
28 array( 'SpecialMostlinkedtemplates', 'Mostlinkedtemplates' ),
29 array( 'MostlinkedPage', 'Mostlinked' ),
30 array( 'MostrevisionsPage', 'Mostrevisions' ),
31 array( 'FewestrevisionsPage', 'Fewestrevisions' ),
32 array( 'NewPagesPage', 'Newpages' ),
33 array( 'ShortPagesPage', 'Shortpages' ),
34 array( 'UncategorizedCategoriesPage', 'Uncategorizedcategories' ),
35 array( 'UncategorizedPagesPage', 'Uncategorizedpages' ),
36 array( 'UncategorizedImagesPage', 'Uncategorizedimages' ),
37 array( 'UncategorizedTemplatesPage', 'Uncategorizedtemplates' ),
38 array( 'UnusedCategoriesPage', 'Unusedcategories' ),
39 array( 'UnusedimagesPage', 'Unusedimages' ),
40 array( 'WantedCategoriesPage', 'Wantedcategories' ),
41 array( 'WantedPagesPage', 'Wantedpages' ),
42 array( 'UnwatchedPagesPage', 'Unwatchedpages' ),
43 array( 'UnusedtemplatesPage', 'Unusedtemplates' ),
44 array( 'WithoutInterwikiPage', 'Withoutinterwiki' ),
45 );
46 wfRunHooks( 'wgQueryPages', array( &$wgQueryPages ) );
47
48 global $wgDisableCounters;
49 if ( !$wgDisableCounters )
50 $wgQueryPages[] = array( 'PopularPagesPage', 'Popularpages' );
51
52
53 /**
54 * This is a class for doing query pages; since they're almost all the same,
55 * we factor out some of the functionality into a superclass, and let
56 * subclasses derive from it.
57 * @addtogroup SpecialPage
58 */
59 class QueryPage {
60 /**
61 * Whether or not we want plain listoutput rather than an ordered list
62 *
63 * @var bool
64 */
65 var $listoutput = false;
66
67 /**
68 * The offset and limit in use, as passed to the query() function
69 *
70 * @var integer
71 */
72 var $offset = 0;
73 var $limit = 0;
74
75 /**
76 * A mutator for $this->listoutput;
77 *
78 * @param bool $bool
79 */
80 function setListoutput( $bool ) {
81 $this->listoutput = $bool;
82 }
83
84 /**
85 * Subclasses return their name here. Make sure the name is also
86 * specified in SpecialPage.php and in Language.php as a language message
87 * param.
88 */
89 function getName() {
90 return '';
91 }
92
93 /**
94 * Return title object representing this page
95 *
96 * @return Title
97 */
98 function getTitle() {
99 return SpecialPage::getTitleFor( $this->getName() );
100 }
101
102 /**
103 * Subclasses return an SQL query here.
104 *
105 * Note that the query itself should return the following four columns:
106 * 'type' (your special page's name), 'namespace', 'title', and 'value'
107 * *in that order*. 'value' is used for sorting.
108 *
109 * These may be stored in the querycache table for expensive queries,
110 * and that cached data will be returned sometimes, so the presence of
111 * extra fields can't be relied upon. The cached 'value' column will be
112 * an integer; non-numeric values are useful only for sorting the initial
113 * query.
114 *
115 * Don't include an ORDER or LIMIT clause, this will be added.
116 */
117 function getSQL() {
118 return "SELECT 'sample' as type, 0 as namespace, 'Sample result' as title, 42 as value";
119 }
120
121 /**
122 * Override to sort by increasing values
123 */
124 function sortDescending() {
125 return true;
126 }
127
128 function getOrder() {
129 return ' ORDER BY value ' .
130 ($this->sortDescending() ? 'DESC' : '');
131 }
132
133 /**
134 * Is this query expensive (for some definition of expensive)? Then we
135 * don't let it run in miser mode. $wgDisableQueryPages causes all query
136 * pages to be declared expensive. Some query pages are always expensive.
137 */
138 function isExpensive( ) {
139 global $wgDisableQueryPages;
140 return $wgDisableQueryPages;
141 }
142
143 /**
144 * Whether or not the output of the page in question is retrived from
145 * the database cache.
146 *
147 * @return bool
148 */
149 function isCached() {
150 global $wgMiserMode;
151
152 return $this->isExpensive() && $wgMiserMode;
153 }
154
155 /**
156 * Sometime we dont want to build rss / atom feeds.
157 */
158 function isSyndicated() {
159 return true;
160 }
161
162 /**
163 * Formats the results of the query for display. The skin is the current
164 * skin; you can use it for making links. The result is a single row of
165 * result data. You should be able to grab SQL results off of it.
166 * If the function return "false", the line output will be skipped.
167 */
168 function formatResult( $skin, $result ) {
169 return '';
170 }
171
172 /**
173 * The content returned by this function will be output before any result
174 */
175 function getPageHeader( ) {
176 return '';
177 }
178
179 /**
180 * If using extra form wheely-dealies, return a set of parameters here
181 * as an associative array. They will be encoded and added to the paging
182 * links (prev/next/lengths).
183 * @return array
184 */
185 function linkParameters() {
186 return array();
187 }
188
189 /**
190 * Some special pages (for example SpecialListusers) might not return the
191 * current object formatted, but return the previous one instead.
192 * Setting this to return true, will call one more time wfFormatResult to
193 * be sure that the very last result is formatted and shown.
194 */
195 function tryLastResult( ) {
196 return false;
197 }
198
199 /**
200 * Clear the cache and save new results
201 */
202 function recache( $limit, $ignoreErrors = true ) {
203 $fname = get_class($this) . '::recache';
204 $dbw = wfGetDB( DB_MASTER );
205 $dbr = wfGetDB( DB_SLAVE, array( $this->getName(), 'QueryPage::recache', 'vslow' ) );
206 if ( !$dbw || !$dbr ) {
207 return false;
208 }
209
210 $querycache = $dbr->tableName( 'querycache' );
211
212 if ( $ignoreErrors ) {
213 $ignoreW = $dbw->ignoreErrors( true );
214 $ignoreR = $dbr->ignoreErrors( true );
215 }
216
217 # Clear out any old cached data
218 $dbw->delete( 'querycache', array( 'qc_type' => $this->getName() ), $fname );
219 # Do query
220 $sql = $this->getSQL() . $this->getOrder();
221 if ($limit !== false)
222 $sql = $dbr->limitResult($sql, $limit, 0);
223 $res = $dbr->query($sql, $fname);
224 $num = false;
225 if ( $res ) {
226 $num = $dbr->numRows( $res );
227 # Fetch results
228 $insertSql = "INSERT INTO $querycache (qc_type,qc_namespace,qc_title,qc_value) VALUES ";
229 $first = true;
230 while ( $res && $row = $dbr->fetchObject( $res ) ) {
231 if ( $first ) {
232 $first = false;
233 } else {
234 $insertSql .= ',';
235 }
236 if ( isset( $row->value ) ) {
237 $value = $row->value;
238 } else {
239 $value = '';
240 }
241
242 $insertSql .= '(' .
243 $dbw->addQuotes( $row->type ) . ',' .
244 $dbw->addQuotes( $row->namespace ) . ',' .
245 $dbw->addQuotes( $row->title ) . ',' .
246 $dbw->addQuotes( $value ) . ')';
247 }
248
249 # Save results into the querycache table on the master
250 if ( !$first ) {
251 if ( !$dbw->query( $insertSql, $fname ) ) {
252 // Set result to false to indicate error
253 $dbr->freeResult( $res );
254 $res = false;
255 }
256 }
257 if ( $res ) {
258 $dbr->freeResult( $res );
259 }
260 if ( $ignoreErrors ) {
261 $dbw->ignoreErrors( $ignoreW );
262 $dbr->ignoreErrors( $ignoreR );
263 }
264
265 # Update the querycache_info record for the page
266 $dbw->delete( 'querycache_info', array( 'qci_type' => $this->getName() ), $fname );
267 $dbw->insert( 'querycache_info', array( 'qci_type' => $this->getName(), 'qci_timestamp' => $dbw->timestamp() ), $fname );
268
269 }
270 return $num;
271 }
272
273 /**
274 * This is the actual workhorse. It does everything needed to make a
275 * real, honest-to-gosh query page.
276 *
277 * @param $offset database query offset
278 * @param $limit database query limit
279 * @param $shownavigation show navigation like "next 200"?
280 */
281 function doQuery( $offset, $limit, $shownavigation=true ) {
282 global $wgUser, $wgOut, $wgLang, $wgContLang;
283
284 $this->offset = $offset;
285 $this->limit = $limit;
286
287 $sname = $this->getName();
288 $fname = get_class($this) . '::doQuery';
289 $dbr = wfGetDB( DB_SLAVE );
290
291 $wgOut->setSyndicated( $this->isSyndicated() );
292
293 if ( !$this->isCached() ) {
294 $sql = $this->getSQL();
295 } else {
296 # Get the cached result
297 $querycache = $dbr->tableName( 'querycache' );
298 $type = $dbr->strencode( $sname );
299 $sql =
300 "SELECT qc_type as type, qc_namespace as namespace,qc_title as title, qc_value as value
301 FROM $querycache WHERE qc_type='$type'";
302
303 if( !$this->listoutput ) {
304
305 # Fetch the timestamp of this update
306 $tRes = $dbr->select( 'querycache_info', array( 'qci_timestamp' ), array( 'qci_type' => $type ), $fname );
307 $tRow = $dbr->fetchObject( $tRes );
308
309 if( $tRow ) {
310 $updated = $wgLang->timeAndDate( $tRow->qci_timestamp, true, true );
311 $wgOut->addMeta( 'Data-Cache-Time', $tRow->qci_timestamp );
312 $wgOut->addInlineScript( "var dataCacheTime = '{$tRow->qci_timestamp}';" );
313 $wgOut->addWikiMsg( 'perfcachedts', $updated );
314 } else {
315 $wgOut->addWikiMsg( 'perfcached' );
316 }
317
318 # If updates on this page have been disabled, let the user know
319 # that the data set won't be refreshed for now
320 global $wgDisableQueryPageUpdate;
321 if( is_array( $wgDisableQueryPageUpdate ) && in_array( $this->getName(), $wgDisableQueryPageUpdate ) ) {
322 $wgOut->addWikiMsg( 'querypage-no-updates' );
323 }
324
325 }
326
327 }
328
329 $sql .= $this->getOrder();
330 $sql = $dbr->limitResult($sql, $limit, $offset);
331 $res = $dbr->query( $sql );
332 $num = $dbr->numRows($res);
333
334 $this->preprocessResults( $dbr, $res );
335
336 $wgOut->addHtml( XML::openElement( 'div', array('class' => 'mw-spcontent') ) );
337
338 # Top header and navigation
339 if( $shownavigation ) {
340 $wgOut->addHtml( $this->getPageHeader() );
341 if( $num > 0 ) {
342 $wgOut->addHtml( '<p>' . wfShowingResults( $offset, $num ) . '</p>' );
343 # Disable the "next" link when we reach the end
344 $paging = wfViewPrevNext( $offset, $limit, $wgContLang->specialPage( $sname ),
345 wfArrayToCGI( $this->linkParameters() ), ( $num < $limit ) );
346 $wgOut->addHtml( '<p>' . $paging . '</p>' );
347 } else {
348 # No results to show, so don't bother with "showing X of Y" etc.
349 # -- just let the user know and give up now
350 $wgOut->addHtml( '<p>' . wfMsgHtml( 'specialpage-empty' ) . '</p>' );
351 $wgOut->addHtml( XML::closeElement( 'div' ) );
352 return;
353 }
354 }
355
356 # The actual results; specialist subclasses will want to handle this
357 # with more than a straight list, so we hand them the info, plus
358 # an OutputPage, and let them get on with it
359 $this->outputResults( $wgOut,
360 $wgUser->getSkin(),
361 $dbr, # Should use a ResultWrapper for this
362 $res,
363 $dbr->numRows( $res ),
364 $offset );
365
366 # Repeat the paging links at the bottom
367 if( $shownavigation ) {
368 $wgOut->addHtml( '<p>' . $paging . '</p>' );
369 }
370
371 $wgOut->addHtml( XML::closeElement( 'div' ) );
372
373 return $num;
374 }
375
376 /**
377 * Format and output report results using the given information plus
378 * OutputPage
379 *
380 * @param OutputPage $out OutputPage to print to
381 * @param Skin $skin User skin to use
382 * @param Database $dbr Database (read) connection to use
383 * @param int $res Result pointer
384 * @param int $num Number of available result rows
385 * @param int $offset Paging offset
386 */
387 protected function outputResults( $out, $skin, $dbr, $res, $num, $offset ) {
388 global $wgContLang;
389
390 if( $num > 0 ) {
391 $html = array();
392 if( !$this->listoutput )
393 $html[] = $this->openList( $offset );
394
395 # $res might contain the whole 1,000 rows, so we read up to
396 # $num [should update this to use a Pager]
397 for( $i = 0; $i < $num && $row = $dbr->fetchObject( $res ); $i++ ) {
398 $line = $this->formatResult( $skin, $row );
399 if( $line ) {
400 $attr = ( isset( $row->usepatrol ) && $row->usepatrol && $row->patrolled == 0 )
401 ? ' class="not-patrolled"'
402 : '';
403 $html[] = $this->listoutput
404 ? $line
405 : "<li{$attr}>{$line}</li>\n";
406 }
407 }
408
409 # Flush the final result
410 if( $this->tryLastResult() ) {
411 $row = null;
412 $line = $this->formatResult( $skin, $row );
413 if( $line ) {
414 $attr = ( isset( $row->usepatrol ) && $row->usepatrol && $row->patrolled == 0 )
415 ? ' class="not-patrolled"'
416 : '';
417 $html[] = $this->listoutput
418 ? $line
419 : "<li{$attr}>{$line}</li>\n";
420 }
421 }
422
423 if( !$this->listoutput )
424 $html[] = $this->closeList();
425
426 $html = $this->listoutput
427 ? $wgContLang->listToText( $html )
428 : implode( '', $html );
429
430 $out->addHtml( $html );
431 }
432 }
433
434 function openList( $offset ) {
435 return "\n<ol start='" . ( $offset + 1 ) . "' class='special'>\n";
436 }
437
438 function closeList() {
439 return "</ol>\n";
440 }
441
442 /**
443 * Do any necessary preprocessing of the result object.
444 */
445 function preprocessResults( $db, $res ) {}
446
447 /**
448 * Similar to above, but packaging in a syndicated feed instead of a web page
449 */
450 function doFeed( $class = '', $limit = 50 ) {
451 global $wgFeed, $wgFeedClasses;
452
453 if ( !$wgFeed ) {
454 global $wgOut;
455 $wgOut->addWikiMsg( 'feed-unavailable' );
456 return;
457 }
458
459 if( isset($wgFeedClasses[$class]) ) {
460 $feed = new $wgFeedClasses[$class](
461 $this->feedTitle(),
462 $this->feedDesc(),
463 $this->feedUrl() );
464 $feed->outHeader();
465
466 $dbr = wfGetDB( DB_SLAVE );
467 $sql = $this->getSQL() . $this->getOrder();
468 $sql = $dbr->limitResult( $sql, $limit, 0 );
469 $res = $dbr->query( $sql, 'QueryPage::doFeed' );
470 while( $obj = $dbr->fetchObject( $res ) ) {
471 $item = $this->feedResult( $obj );
472 if( $item ) $feed->outItem( $item );
473 }
474 $dbr->freeResult( $res );
475
476 $feed->outFooter();
477 return true;
478 } else {
479 return false;
480 }
481 }
482
483 /**
484 * Override for custom handling. If the titles/links are ok, just do
485 * feedItemDesc()
486 */
487 function feedResult( $row ) {
488 if( !isset( $row->title ) ) {
489 return NULL;
490 }
491 $title = Title::MakeTitle( intval( $row->namespace ), $row->title );
492 if( $title ) {
493 $date = isset( $row->timestamp ) ? $row->timestamp : '';
494 $comments = '';
495 if( $title ) {
496 $talkpage = $title->getTalkPage();
497 $comments = $talkpage->getFullURL();
498 }
499
500 return new FeedItem(
501 $title->getPrefixedText(),
502 $this->feedItemDesc( $row ),
503 $title->getFullURL(),
504 $date,
505 $this->feedItemAuthor( $row ),
506 $comments);
507 } else {
508 return NULL;
509 }
510 }
511
512 function feedItemDesc( $row ) {
513 return isset( $row->comment ) ? htmlspecialchars( $row->comment ) : '';
514 }
515
516 function feedItemAuthor( $row ) {
517 return isset( $row->user_text ) ? $row->user_text : '';
518 }
519
520 function feedTitle() {
521 global $wgContLanguageCode, $wgSitename;
522 $page = SpecialPage::getPage( $this->getName() );
523 $desc = $page->getDescription();
524 return "$wgSitename - $desc [$wgContLanguageCode]";
525 }
526
527 function feedDesc() {
528 return wfMsg( 'tagline' );
529 }
530
531 function feedUrl() {
532 $title = SpecialPage::getTitleFor( $this->getName() );
533 return $title->getFullURL();
534 }
535 }
536
537