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