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