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