*Try to use rev_len first to avoid hitting text table as much
[mediawiki.git] / includes / QueryPage.php
blobf7f90d771cbf0385e8708d840d661466c8207e05
1 <?php
2 /**
3 * Contain a class for special pages
4 */
6 /**
7 * List of query page classes and their associated special pages,
8 * for periodic updates.
10 * DO NOT CHANGE THIS LIST without testing that
11 * maintenance/updateSpecialPages.php still works.
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( 'NewPagesPage', 'Newpages' ),
33 array( 'ShortPagesPage', 'Shortpages' ),
34 array( 'UncategorizedCategoriesPage', 'Uncategorizedcategories' ),
35 array( 'UncategorizedPagesPage', 'Uncategorizedpages' ),
36 array( 'UncategorizedImagesPage', 'Uncategorizedimages' ),
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' ),
45 wfRunHooks( 'wgQueryPages', array( &$wgQueryPages ) );
47 global $wgDisableCounters;
48 if ( !$wgDisableCounters )
49 $wgQueryPages[] = array( 'PopularPagesPage', 'Popularpages' );
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
58 class QueryPage {
59 /**
60 * Whether or not we want plain listoutput rather than an ordered list
62 * @var bool
64 var $listoutput = false;
66 /**
67 * The offset and limit in use, as passed to the query() function
69 * @var integer
71 var $offset = 0;
72 var $limit = 0;
74 /**
75 * A mutator for $this->listoutput;
77 * @param bool $bool
79 function setListoutput( $bool ) {
80 $this->listoutput = $bool;
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.
88 function getName() {
89 return '';
92 /**
93 * Return title object representing this page
95 * @return Title
97 function getTitle() {
98 return SpecialPage::getTitleFor( $this->getName() );
102 * Subclasses return an SQL query here.
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.
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.
114 * Don't include an ORDER or LIMIT clause, this will be added.
116 function getSQL() {
117 return "SELECT 'sample' as type, 0 as namespace, 'Sample result' as title, 42 as value";
121 * Override to sort by increasing values
123 function sortDescending() {
124 return true;
127 function getOrder() {
128 return ' ORDER BY value ' .
129 ($this->sortDescending() ? 'DESC' : '');
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.
137 function isExpensive( ) {
138 global $wgDisableQueryPages;
139 return $wgDisableQueryPages;
143 * Whether or not the output of the page in question is retrived from
144 * the database cache.
146 * @return bool
148 function isCached() {
149 global $wgMiserMode;
151 return $this->isExpensive() && $wgMiserMode;
155 * Sometime we dont want to build rss / atom feeds.
157 function isSyndicated() {
158 return true;
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.
167 function formatResult( $skin, $result ) {
168 return '';
172 * The content returned by this function will be output before any result
174 function getPageHeader( ) {
175 return '';
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
184 function linkParameters() {
185 return array();
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.
194 function tryLastResult( ) {
195 return false;
199 * Clear the cache and save new results
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;
209 $querycache = $dbr->tableName( 'querycache' );
211 if ( $ignoreErrors ) {
212 $ignoreW = $dbw->ignoreErrors( true );
213 $ignoreR = $dbr->ignoreErrors( true );
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 .= ',';
235 if ( isset( $row->value ) ) {
236 $value = $row->value;
237 } else {
238 $value = '';
241 $insertSql .= '(' .
242 $dbw->addQuotes( $row->type ) . ',' .
243 $dbw->addQuotes( $row->namespace ) . ',' .
244 $dbw->addQuotes( $row->title ) . ',' .
245 $dbw->addQuotes( $value ) . ')';
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;
256 if ( $res ) {
257 $dbr->freeResult( $res );
259 if ( $ignoreErrors ) {
260 $dbw->ignoreErrors( $ignoreW );
261 $dbr->ignoreErrors( $ignoreR );
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 );
269 return $num;
273 * This is the actual workhorse. It does everything needed to make a
274 * real, honest-to-gosh query page.
276 * @param $offset database query offset
277 * @param $limit database query limit
278 * @param $shownavigation show navigation like "next 200"?
280 function doQuery( $offset, $limit, $shownavigation=true ) {
281 global $wgUser, $wgOut, $wgLang, $wgContLang;
283 $this->offset = $offset;
284 $this->limit = $limit;
286 $sname = $this->getName();
287 $fname = get_class($this) . '::doQuery';
288 $dbr = wfGetDB( DB_SLAVE );
290 $wgOut->setSyndicated( $this->isSyndicated() );
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'";
302 if( !$this->listoutput ) {
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 );
308 if( $tRow ) {
309 $updated = $wgLang->timeAndDate( $tRow->qci_timestamp, true, true );
310 $cacheNotice = wfMsg( 'perfcachedts', $updated );
311 $wgOut->addMeta( 'Data-Cache-Time', $tRow->qci_timestamp );
312 $wgOut->addInlineScript( "var dataCacheTime = '{$tRow->qci_timestamp}';" );
313 } else {
314 $cacheNotice = wfMsg( 'perfcached' );
317 $wgOut->addWikiText( $cacheNotice );
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->addWikiText( wfMsg( 'querypage-no-updates' ) );
330 $sql .= $this->getOrder();
331 $sql = $dbr->limitResult($sql, $limit, $offset);
332 $res = $dbr->query( $sql );
333 $num = $dbr->numRows($res);
335 $this->preprocessResults( $dbr, $res );
337 $wgOut->addHtml( XML::openElement( 'div', array('class' => 'mw-spcontent') ) );
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;
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 );
367 # Repeat the paging links at the bottom
368 if( $shownavigation ) {
369 $wgOut->addHtml( '<p>' . $paging . '</p>' );
372 $wgOut->addHtml( XML::closeElement( 'div' ) );
374 return $num;
378 * Format and output report results using the given information plus
379 * OutputPage
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
388 protected function outputResults( $out, $skin, $dbr, $res, $num, $offset ) {
389 global $wgContLang;
391 if( $num > 0 ) {
392 $html = array();
393 if( !$this->listoutput )
394 $html[] = $this->openList( $offset );
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 ? $format
406 : "<li{$attr}>{$line}</li>\n";
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 ? $format
420 : "<li{$attr}>{$line}</li>\n";
424 if( !$this->listoutput )
425 $html[] = $this->closeList();
427 $html = $this->listoutput
428 ? $wgContLang->listToText( $html )
429 : implode( '', $html );
431 $out->addHtml( $html );
435 function openList( $offset ) {
436 return "\n<ol start='" . ( $offset + 1 ) . "' class='special'>\n";
439 function closeList() {
440 return "</ol>\n";
444 * Do any necessary preprocessing of the result object.
445 * You should pass this by reference: &$db , &$res [although probably no longer necessary in PHP5]
447 function preprocessResults( &$db, &$res ) {}
450 * Similar to above, but packaging in a syndicated feed instead of a web page
452 function doFeed( $class = '', $limit = 50 ) {
453 global $wgFeedClasses;
455 if( isset($wgFeedClasses[$class]) ) {
456 $feed = new $wgFeedClasses[$class](
457 $this->feedTitle(),
458 $this->feedDesc(),
459 $this->feedUrl() );
460 $feed->outHeader();
462 $dbr = wfGetDB( DB_SLAVE );
463 $sql = $this->getSQL() . $this->getOrder();
464 $sql = $dbr->limitResult( $sql, $limit, 0 );
465 $res = $dbr->query( $sql, 'QueryPage::doFeed' );
466 while( $obj = $dbr->fetchObject( $res ) ) {
467 $item = $this->feedResult( $obj );
468 if( $item ) $feed->outItem( $item );
470 $dbr->freeResult( $res );
472 $feed->outFooter();
473 return true;
474 } else {
475 return false;
480 * Override for custom handling. If the titles/links are ok, just do
481 * feedItemDesc()
483 function feedResult( $row ) {
484 if( !isset( $row->title ) ) {
485 return NULL;
487 $title = Title::MakeTitle( intval( $row->namespace ), $row->title );
488 if( $title ) {
489 $date = isset( $row->timestamp ) ? $row->timestamp : '';
490 $comments = '';
491 if( $title ) {
492 $talkpage = $title->getTalkPage();
493 $comments = $talkpage->getFullURL();
496 return new FeedItem(
497 $title->getPrefixedText(),
498 $this->feedItemDesc( $row ),
499 $title->getFullURL(),
500 $date,
501 $this->feedItemAuthor( $row ),
502 $comments);
503 } else {
504 return NULL;
508 function feedItemDesc( $row ) {
509 return isset( $row->comment ) ? htmlspecialchars( $row->comment ) : '';
512 function feedItemAuthor( $row ) {
513 return isset( $row->user_text ) ? $row->user_text : '';
516 function feedTitle() {
517 global $wgContLanguageCode, $wgSitename;
518 $page = SpecialPage::getPage( $this->getName() );
519 $desc = $page->getDescription();
520 return "$wgSitename - $desc [$wgContLanguageCode]";
523 function feedDesc() {
524 return wfMsg( 'tagline' );
527 function feedUrl() {
528 $title = SpecialPage::getTitleFor( $this->getName() );
529 return $title->getFullURL();