3 * Contain a class for special pages
9 * List of query page classes and their associated special pages,
10 * for periodic updates.
12 * DO NOT CHANGE THIS LIST without testing that
13 * maintenance/updateSpecialPages.php still works.
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( 'FileDuplicateSearchPage', 'FileDuplicateSearch' ),
25 array( 'LinkSearchPage', 'LinkSearch' ),
26 array( 'ListredirectsPage', 'Listredirects' ),
27 array( 'LonelyPagesPage', 'Lonelypages' ),
28 array( 'LongPagesPage', 'Longpages' ),
29 array( 'MIMEsearchPage', 'MIMEsearch' ),
30 array( 'MostcategoriesPage', 'Mostcategories' ),
31 array( 'MostimagesPage', 'Mostimages' ),
32 array( 'MostlinkedCategoriesPage', 'Mostlinkedcategories' ),
33 array( 'MostlinkedtemplatesPage', 'Mostlinkedtemplates' ),
34 array( 'MostlinkedPage', 'Mostlinked' ),
35 array( 'MostrevisionsPage', 'Mostrevisions' ),
36 array( 'FewestrevisionsPage', 'Fewestrevisions' ),
37 array( 'ShortPagesPage', 'Shortpages' ),
38 array( 'UncategorizedCategoriesPage', 'Uncategorizedcategories' ),
39 array( 'UncategorizedPagesPage', 'Uncategorizedpages' ),
40 array( 'UncategorizedImagesPage', 'Uncategorizedimages' ),
41 array( 'UncategorizedTemplatesPage', 'Uncategorizedtemplates' ),
42 array( 'UnusedCategoriesPage', 'Unusedcategories' ),
43 array( 'UnusedimagesPage', 'Unusedimages' ),
44 array( 'WantedCategoriesPage', 'Wantedcategories' ),
45 array( 'WantedFilesPage', 'Wantedfiles' ),
46 array( 'WantedPagesPage', 'Wantedpages' ),
47 array( 'WantedTemplatesPage', 'Wantedtemplates' ),
48 array( 'UnwatchedPagesPage', 'Unwatchedpages' ),
49 array( 'UnusedtemplatesPage', 'Unusedtemplates' ),
50 array( 'WithoutInterwikiPage', 'Withoutinterwiki' ),
52 wfRunHooks( 'wgQueryPages', array( &$wgQueryPages ) );
54 global $wgDisableCounters;
55 if ( !$wgDisableCounters )
56 $wgQueryPages[] = array( 'PopularPagesPage', 'Popularpages' );
60 * This is a class for doing query pages; since they're almost all the same,
61 * we factor out some of the functionality into a superclass, and let
62 * subclasses derive from it.
63 * @ingroup SpecialPage
65 abstract class QueryPage
extends SpecialPage
{
67 * Whether or not we want plain listoutput rather than an ordered list
71 var $listoutput = false;
74 * The offset and limit in use, as passed to the query() function
82 * The number of rows returned by the query. Reading this variable
83 * only makes sense in functions that are run after the query has been
84 * done, such as preprocessResults() and formatRow().
88 protected $cachedTimestamp = null;
91 * Wheter to show prev/next links
93 protected $shownavigation = true;
96 * A mutator for $this->listoutput;
98 * @param $bool Boolean
100 function setListoutput( $bool ) {
101 $this->listoutput
= $bool;
105 * Subclasses return an SQL query here, formatted as an array with the
107 * tables => Table(s) for passing to Database::select()
108 * fields => Field(s) for passing to Database::select(), may be *
109 * conds => WHERE conditions
111 * join_conds => JOIN conditions
113 * Note that the query itself should return the following three columns:
114 * 'namespace', 'title', and 'value'. 'value' is used for sorting.
116 * These may be stored in the querycache table for expensive queries,
117 * and that cached data will be returned sometimes, so the presence of
118 * extra fields can't be relied upon. The cached 'value' column will be
119 * an integer; non-numeric values are useful only for sorting the
120 * initial query (except if they're timestamps, see usesTimestamps()).
122 * Don't include an ORDER or LIMIT clause, they will be added.
124 * If this function is not overridden or returns something other than
125 * an array, getSQL() will be used instead. This is for backwards
126 * compatibility only and is strongly deprecated.
130 function getQueryInfo() {
135 * For back-compat, subclasses may return a raw SQL query here, as a string.
136 * This is stronly deprecated; getQueryInfo() should be overridden instead.
140 /* Implement getQueryInfo() instead */
141 throw new MWException( "Bug in a QueryPage: doesn't implement getQueryInfo() nor getQuery() properly" );
145 * Subclasses return an array of fields to order by here. Don't append
146 * DESC to the field names, that'll be done automatically if
147 * sortDescending() returns true.
151 function getOrderFields() {
152 return array( 'value' );
156 * Does this query return timestamps rather than integers in its
157 * 'value' field? If true, this class will convert 'value' to a
158 * UNIX timestamp for caching.
159 * NOTE: formatRow() may get timestamps in TS_MW (mysql), TS_DB (pgsql)
160 * or TS_UNIX (querycache) format, so be sure to always run them
161 * through wfTimestamp()
165 function usesTimestamps() {
170 * Override to sort by increasing values
174 function sortDescending() {
179 * Is this query expensive (for some definition of expensive)? Then we
180 * don't let it run in miser mode. $wgDisableQueryPages causes all query
181 * pages to be declared expensive. Some query pages are always expensive.
185 function isExpensive() {
186 global $wgDisableQueryPages;
187 return $wgDisableQueryPages;
191 * Is the output of this query cacheable? Non-cacheable expensive pages
192 * will be disabled in miser mode and will not have their results written
193 * to the querycache table.
197 public function isCacheable() {
202 * Whether or not the output of the page in question is retrieved from
203 * the database cache.
207 function isCached() {
210 return $this->isExpensive() && $wgMiserMode;
214 * Sometime we dont want to build rss / atom feeds.
218 function isSyndicated() {
223 * Formats the results of the query for display. The skin is the current
224 * skin; you can use it for making links. The result is a single row of
225 * result data. You should be able to grab SQL results off of it.
226 * If the function returns false, the line output will be skipped.
228 * @param $result object Result row
229 * @return mixed String or false to skip
231 * @param $skin Skin object
232 * @param $result Object: database row
234 abstract function formatResult( $skin, $result );
237 * The content returned by this function will be output before any result
241 function getPageHeader() {
246 * If using extra form wheely-dealies, return a set of parameters here
247 * as an associative array. They will be encoded and added to the paging
248 * links (prev/next/lengths).
252 function linkParameters() {
257 * Some special pages (for example SpecialListusers) might not return the
258 * current object formatted, but return the previous one instead.
259 * Setting this to return true will ensure formatResult() is called
260 * one more time to make sure that the very last result is formatted
264 function tryLastResult() {
269 * Clear the cache and save new results
271 * @param $limit Integer: limit for SQL statement
272 * @param $ignoreErrors Boolean: whether to ignore database errors
275 function recache( $limit, $ignoreErrors = true ) {
276 if ( !$this->isCacheable() ) {
280 $fname = get_class( $this ) . '::recache';
281 $dbw = wfGetDB( DB_MASTER
);
282 $dbr = wfGetDB( DB_SLAVE
, array( $this->getName(), __METHOD__
, 'vslow' ) );
283 if ( !$dbw ||
!$dbr ) {
287 if ( $ignoreErrors ) {
288 $ignoreW = $dbw->ignoreErrors( true );
289 $ignoreR = $dbr->ignoreErrors( true );
292 # Clear out any old cached data
293 $dbw->delete( 'querycache', array( 'qc_type' => $this->getName() ), $fname );
295 $res = $this->reallyDoQuery( $limit, false );
298 $num = $res->numRows();
301 while ( $res && $row = $dbr->fetchObject( $res ) ) {
302 if ( isset( $row->value
) ) {
303 if ( $this->usesTimestamps() ) {
304 $value = wfTimestamp( TS_UNIX
,
307 $value = intval( $row->value
); // @bug 14414
313 $vals[] = array( 'qc_type' => $this->getName(),
314 'qc_namespace' => $row->namespace,
315 'qc_title' => $row->title
,
316 'qc_value' => $value );
319 # Save results into the querycache table on the master
320 if ( count( $vals ) ) {
321 if ( !$dbw->insert( 'querycache', $vals, __METHOD__
) ) {
322 // Set result to false to indicate error
326 if ( $ignoreErrors ) {
327 $dbw->ignoreErrors( $ignoreW );
328 $dbr->ignoreErrors( $ignoreR );
331 # Update the querycache_info record for the page
332 $dbw->delete( 'querycache_info', array( 'qci_type' => $this->getName() ), $fname );
333 $dbw->insert( 'querycache_info', array( 'qci_type' => $this->getName(), 'qci_timestamp' => $dbw->timestamp() ), $fname );
340 * Run the query and return the result
341 * @param $limit mixed Numerical limit or false for no limit
342 * @param $offset mixed Numerical offset or false for no offset
343 * @return ResultWrapper
346 function reallyDoQuery( $limit, $offset = false ) {
347 $fname = get_class( $this ) . "::reallyDoQuery";
348 $dbr = wfGetDB( DB_SLAVE
);
349 $query = $this->getQueryInfo();
350 $order = $this->getOrderFields();
351 if ( $this->sortDescending() ) {
352 foreach ( $order as &$field ) {
356 if ( is_array( $query ) ) {
357 $tables = isset( $query['tables'] ) ?
(array)$query['tables'] : array();
358 $fields = isset( $query['fields'] ) ?
(array)$query['fields'] : array();
359 $conds = isset( $query['conds'] ) ?
(array)$query['conds'] : array();
360 $options = isset( $query['options'] ) ?
(array)$query['options'] : array();
361 $join_conds = isset( $query['join_conds'] ) ?
(array)$query['join_conds'] : array();
362 if ( count( $order ) ) {
363 $options['ORDER BY'] = implode( ', ', $order );
365 if ( $limit !== false ) {
366 $options['LIMIT'] = intval( $limit );
368 if ( $offset !== false ) {
369 $options['OFFSET'] = intval( $offset );
372 $res = $dbr->select( $tables, $fields, $conds, $fname,
373 $options, $join_conds
376 // Old-fashioned raw SQL style, deprecated
377 $sql = $this->getSQL();
378 $sql .= ' ORDER BY ' . implode( ', ', $order );
379 $sql = $dbr->limitResult( $sql, $limit, $offset );
380 $res = $dbr->query( $sql, $fname );
382 return $dbr->resultObject( $res );
386 * Somewhat deprecated, you probably want to be using execute()
387 * @return ResultWrapper
389 function doQuery( $offset = false, $limit = false ) {
390 if ( $this->isCached() && $this->isCacheable() ) {
391 return $this->fetchFromCache( $limit, $offset );
393 return $this->reallyDoQuery( $limit, $offset );
398 * Fetch the query results from the query cache
399 * @param $limit mixed Numerical limit or false for no limit
400 * @param $offset mixed Numerical offset or false for no offset
401 * @return ResultWrapper
404 function fetchFromCache( $limit, $offset = false ) {
405 $dbr = wfGetDB( DB_SLAVE
);
407 if ( $limit !== false ) {
408 $options['LIMIT'] = intval( $limit );
410 if ( $offset !== false ) {
411 $options['OFFSET'] = intval( $offset );
413 if ( $this->sortDescending() ) {
414 $options['ORDER BY'] = 'qc_value DESC';
416 $options['ORDER BY'] = 'qc_value ASC';
418 $res = $dbr->select( 'querycache', array( 'qc_type',
419 'qc_namespace AS namespace',
421 'qc_value AS value' ),
422 array( 'qc_type' => $this->getName() ),
425 return $dbr->resultObject( $res );
428 public function getCachedTimestamp() {
429 if ( is_null( $this->cachedTimestamp
) ) {
430 $dbr = wfGetDB( DB_SLAVE
);
431 $fname = get_class( $this ) . '::getCachedTimestamp';
432 $this->cachedTimestamp
= $dbr->selectField( 'querycache_info', 'qci_timestamp',
433 array( 'qci_type' => $this->getName() ), $fname );
435 return $this->cachedTimestamp
;
439 * This is the actual workhorse. It does everything needed to make a
440 * real, honest-to-gosh query page.
443 function execute( $par ) {
444 global $wgQueryCacheLimit, $wgDisableQueryPageUpdate;
446 $user = $this->getUser();
447 if ( !$this->userCanExecute( $user ) ) {
448 $this->displayRestrictionError();
453 $this->outputHeader();
455 $out = $this->getOutput();
457 if ( $this->isCached() && !$this->isCacheable() ) {
458 $out->addWikiMsg( 'querypage-disabled' );
462 $out->setSyndicated( $this->isSyndicated() );
464 if ( $this->limit
== 0 && $this->offset
== 0 ) {
465 list( $this->limit
, $this->offset
) = $this->getRequest()->getLimitOffset();
468 // TODO: Use doQuery()
469 if ( !$this->isCached() ) {
470 $res = $this->reallyDoQuery( $this->limit
, $this->offset
);
472 # Get the cached result
473 $res = $this->fetchFromCache( $this->limit
, $this->offset
);
474 if ( !$this->listoutput
) {
476 # Fetch the timestamp of this update
477 $ts = $this->getCachedTimestamp();
478 $lang = $this->getLanguage();
479 $maxResults = $lang->formatNum( $wgQueryCacheLimit );
482 $updated = $lang->userTimeAndDate( $ts, $user );
483 $updateddate = $lang->userDate( $ts, $user );
484 $updatedtime = $lang->userTime( $ts, $user );
485 $out->addMeta( 'Data-Cache-Time', $ts );
486 $out->addInlineScript( "var dataCacheTime = '$ts';" );
487 $out->addWikiMsg( 'perfcachedts', $updated, $updateddate, $updatedtime, $maxResults );
489 $out->addWikiMsg( 'perfcached', $maxResults );
492 # If updates on this page have been disabled, let the user know
493 # that the data set won't be refreshed for now
494 if ( is_array( $wgDisableQueryPageUpdate ) && in_array( $this->getName(), $wgDisableQueryPageUpdate ) ) {
495 $out->addWikiMsg( 'querypage-no-updates' );
500 $this->numRows
= $res->numRows();
502 $dbr = wfGetDB( DB_SLAVE
);
503 $this->preprocessResults( $dbr, $res );
505 $out->addHTML( Xml
::openElement( 'div', array( 'class' => 'mw-spcontent' ) ) );
507 # Top header and navigation
508 if ( $this->shownavigation
) {
509 $out->addHTML( $this->getPageHeader() );
510 if ( $this->numRows
> 0 ) {
511 $out->addHTML( $this->msg( 'showingresults' )->numParams(
512 $this->numRows
, $this->offset +
1 )->parseAsBlock() );
513 # Disable the "next" link when we reach the end
514 $paging = $this->getLanguage()->viewPrevNext( $this->getTitle( $par ), $this->offset
,
515 $this->limit
, $this->linkParameters(), ( $this->numRows
< $this->limit
) );
516 $out->addHTML( '<p>' . $paging . '</p>' );
518 # No results to show, so don't bother with "showing X of Y" etc.
519 # -- just let the user know and give up now
520 $out->addWikiMsg( 'specialpage-empty' );
521 $out->addHTML( Xml
::closeElement( 'div' ) );
526 # The actual results; specialist subclasses will want to handle this
527 # with more than a straight list, so we hand them the info, plus
528 # an OutputPage, and let them get on with it
529 $this->outputResults( $out,
531 $dbr, # Should use a ResultWrapper for this
536 # Repeat the paging links at the bottom
537 if ( $this->shownavigation
) {
538 $out->addHTML( '<p>' . $paging . '</p>' );
541 $out->addHTML( Xml
::closeElement( 'div' ) );
543 return $this->numRows
;
547 * Format and output report results using the given information plus
550 * @param $out OutputPage to print to
551 * @param $skin Skin: user skin to use
552 * @param $dbr Database (read) connection to use
553 * @param $res Integer: result pointer
554 * @param $num Integer: number of available result rows
555 * @param $offset Integer: paging offset
557 protected function outputResults( $out, $skin, $dbr, $res, $num, $offset ) {
562 if ( !$this->listoutput
) {
563 $html[] = $this->openList( $offset );
566 # $res might contain the whole 1,000 rows, so we read up to
567 # $num [should update this to use a Pager]
568 for ( $i = 0; $i < $num && $row = $dbr->fetchObject( $res ); $i++
) {
569 $line = $this->formatResult( $skin, $row );
571 $attr = ( isset( $row->usepatrol
) && $row->usepatrol
&& $row->patrolled
== 0 )
572 ?
' class="not-patrolled"'
574 $html[] = $this->listoutput
576 : "<li{$attr}>{$line}</li>\n";
580 # Flush the final result
581 if ( $this->tryLastResult() ) {
583 $line = $this->formatResult( $skin, $row );
585 $attr = ( isset( $row->usepatrol
) && $row->usepatrol
&& $row->patrolled
== 0 )
586 ?
' class="not-patrolled"'
588 $html[] = $this->listoutput
590 : "<li{$attr}>{$line}</li>\n";
594 if ( !$this->listoutput
) {
595 $html[] = $this->closeList();
598 $html = $this->listoutput
599 ?
$wgContLang->listToText( $html )
600 : implode( '', $html );
602 $out->addHTML( $html );
610 function openList( $offset ) {
611 return "\n<ol start='" . ( $offset +
1 ) . "' class='special'>\n";
617 function closeList() {
622 * Do any necessary preprocessing of the result object.
624 function preprocessResults( $db, $res ) {}
627 * Similar to above, but packaging in a syndicated feed instead of a web page
630 function doFeed( $class = '', $limit = 50 ) {
631 global $wgFeed, $wgFeedClasses;
634 $this->getOutput()->addWikiMsg( 'feed-unavailable' );
639 if ( $limit > $wgFeedLimit ) {
640 $limit = $wgFeedLimit;
643 if ( isset( $wgFeedClasses[$class] ) ) {
644 $feed = new $wgFeedClasses[$class](
650 $res = $this->reallyDoQuery( $limit, 0 );
651 foreach ( $res as $obj ) {
652 $item = $this->feedResult( $obj );
654 $feed->outItem( $item );
666 * Override for custom handling. If the titles/links are ok, just do
668 * @return FeedItem|null
670 function feedResult( $row ) {
671 if ( !isset( $row->title
) ) {
674 $title = Title
::MakeTitle( intval( $row->namespace ), $row->title
);
676 $date = isset( $row->timestamp
) ?
$row->timestamp
: '';
679 $talkpage = $title->getTalkPage();
680 $comments = $talkpage->getFullURL();
684 $title->getPrefixedText(),
685 $this->feedItemDesc( $row ),
686 $title->getFullURL(),
688 $this->feedItemAuthor( $row ),
695 function feedItemDesc( $row ) {
696 return isset( $row->comment
) ?
htmlspecialchars( $row->comment
) : '';
699 function feedItemAuthor( $row ) {
700 return isset( $row->user_text
) ?
$row->user_text
: '';
703 function feedTitle() {
704 global $wgLanguageCode, $wgSitename;
705 $desc = $this->getDescription();
706 return "$wgSitename - $desc [$wgLanguageCode]";
709 function feedDesc() {
710 return $this->msg( 'tagline' )->text();
714 return $this->getTitle()->getFullURL();
719 * Class definition for a wanted query page like
720 * WantedPages, WantedTemplates, etc
722 abstract class WantedQueryPage
extends QueryPage
{
724 function isExpensive() {
728 function isSyndicated() {
733 * Cache page existence for performance
735 function preprocessResults( $db, $res ) {
736 if ( !$res->numRows() ) {
740 $batch = new LinkBatch
;
741 foreach ( $res as $row ) {
742 $batch->add( $row->namespace, $row->title
);
746 // Back to start for display
751 * Should formatResult() always check page existence, even if
752 * the results are fresh? This is a (hopefully temporary)
753 * kluge for Special:WantedFiles, which may contain false
754 * positives for files that exist e.g. in a shared repo (bug
758 function forceExistenceCheck() {
763 * Format an individual result
765 * @param $skin Skin to use for UI elements
766 * @param $result Result row
769 public function formatResult( $skin, $result ) {
770 $title = Title
::makeTitleSafe( $result->namespace, $result->title
);
771 if ( $title instanceof Title
) {
772 if ( $this->isCached() ||
$this->forceExistenceCheck() ) {
773 $pageLink = $title->isKnown()
774 ?
'<del>' . Linker
::link( $title ) . '</del>'
783 $pageLink = Linker
::link(
791 return $this->getLanguage()->specialList( $pageLink, $this->makeWlhLink( $title, $result ) );
793 return $this->msg( 'wantedpages-badtitle', $result->title
)->escaped();
798 * Make a "what links here" link for a given title
800 * @param $title Title to make the link for
801 * @param $result Object: result row
804 private function makeWlhLink( $title, $result ) {
805 $wlh = SpecialPage
::getTitleFor( 'Whatlinkshere', $title->getPrefixedText() );
806 $label = $this->msg( 'nlinks' )->numParams( $result->value
)->escaped();
807 return Linker
::link( $wlh, $label );