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