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