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