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