3 * Base code for "query" special pages.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup SpecialPage
25 * This is a class for doing query pages; since they're almost all the same,
26 * we factor out some of the functionality into a superclass, and let
27 * subclasses derive from it.
28 * @ingroup SpecialPage
30 abstract class QueryPage
extends SpecialPage
{
32 * Whether or not we want plain listoutput rather than an ordered list
36 var $listoutput = false;
39 * The offset and limit in use, as passed to the query() function
47 * The number of rows returned by the query. Reading this variable
48 * only makes sense in functions that are run after the query has been
49 * done, such as preprocessResults() and formatRow().
53 protected $cachedTimestamp = null;
56 * Whether to show prev/next links
58 protected $shownavigation = true;
61 * Get a list of query page classes and their associated special pages,
62 * for periodic updates.
64 * DO NOT CHANGE THIS LIST without testing that
65 * maintenance/updateSpecialPages.php still works.
68 public static function getPages() {
69 global $wgDisableCounters;
73 // QueryPage subclass, Special page name
75 array( 'AncientPagesPage', 'Ancientpages' ),
76 array( 'BrokenRedirectsPage', 'BrokenRedirects' ),
77 array( 'DeadendPagesPage', 'Deadendpages' ),
78 array( 'DoubleRedirectsPage', 'DoubleRedirects' ),
79 array( 'FileDuplicateSearchPage', 'FileDuplicateSearch' ),
80 array( 'ListDuplicatedFilesPage', 'ListDuplicatedFiles'),
81 array( 'LinkSearchPage', 'LinkSearch' ),
82 array( 'ListredirectsPage', 'Listredirects' ),
83 array( 'LonelyPagesPage', 'Lonelypages' ),
84 array( 'LongPagesPage', 'Longpages' ),
85 array( 'MIMEsearchPage', 'MIMEsearch' ),
86 array( 'MostcategoriesPage', 'Mostcategories' ),
87 array( 'MostimagesPage', 'Mostimages' ),
88 array( 'MostinterwikisPage', 'Mostinterwikis' ),
89 array( 'MostlinkedCategoriesPage', 'Mostlinkedcategories' ),
90 array( 'MostlinkedtemplatesPage', 'Mostlinkedtemplates' ),
91 array( 'MostlinkedPage', 'Mostlinked' ),
92 array( 'MostrevisionsPage', 'Mostrevisions' ),
93 array( 'FewestrevisionsPage', 'Fewestrevisions' ),
94 array( 'ShortPagesPage', 'Shortpages' ),
95 array( 'UncategorizedCategoriesPage', 'Uncategorizedcategories' ),
96 array( 'UncategorizedPagesPage', 'Uncategorizedpages' ),
97 array( 'UncategorizedImagesPage', 'Uncategorizedimages' ),
98 array( 'UncategorizedTemplatesPage', 'Uncategorizedtemplates' ),
99 array( 'UnusedCategoriesPage', 'Unusedcategories' ),
100 array( 'UnusedimagesPage', 'Unusedimages' ),
101 array( 'WantedCategoriesPage', 'Wantedcategories' ),
102 array( 'WantedFilesPage', 'Wantedfiles' ),
103 array( 'WantedPagesPage', 'Wantedpages' ),
104 array( 'WantedTemplatesPage', 'Wantedtemplates' ),
105 array( 'UnwatchedPagesPage', 'Unwatchedpages' ),
106 array( 'UnusedtemplatesPage', 'Unusedtemplates' ),
107 array( 'WithoutInterwikiPage', 'Withoutinterwiki' ),
109 wfRunHooks( 'wgQueryPages', array( &$qp ) );
111 if ( !$wgDisableCounters ) {
112 $qp[] = array( 'PopularPagesPage', 'Popularpages' );
120 * A mutator for $this->listoutput;
124 function setListoutput( $bool ) {
125 $this->listoutput
= $bool;
129 * Subclasses return an SQL query here, formatted as an array with the
131 * tables => Table(s) for passing to Database::select()
132 * fields => Field(s) for passing to Database::select(), may be *
133 * conds => WHERE conditions
135 * join_conds => JOIN conditions
137 * Note that the query itself should return the following three columns:
138 * 'namespace', 'title', and 'value'. 'value' is used for sorting.
140 * These may be stored in the querycache table for expensive queries,
141 * and that cached data will be returned sometimes, so the presence of
142 * extra fields can't be relied upon. The cached 'value' column will be
143 * an integer; non-numeric values are useful only for sorting the
144 * initial query (except if they're timestamps, see usesTimestamps()).
146 * Don't include an ORDER or LIMIT clause, they will be added.
148 * If this function is not overridden or returns something other than
149 * an array, getSQL() will be used instead. This is for backwards
150 * compatibility only and is strongly deprecated.
154 function getQueryInfo() {
159 * For back-compat, subclasses may return a raw SQL query here, as a string.
160 * This is strongly deprecated; getQueryInfo() should be overridden instead.
161 * @throws MWException
165 /* Implement getQueryInfo() instead */
166 throw new MWException( "Bug in a QueryPage: doesn't implement getQueryInfo() nor "
167 . "getQuery() properly" );
171 * Subclasses return an array of fields to order by here. Don't append
172 * DESC to the field names, that'll be done automatically if
173 * sortDescending() returns true.
177 function getOrderFields() {
178 return array( 'value' );
182 * Does this query return timestamps rather than integers in its
183 * 'value' field? If true, this class will convert 'value' to a
184 * UNIX timestamp for caching.
185 * NOTE: formatRow() may get timestamps in TS_MW (mysql), TS_DB (pgsql)
186 * or TS_UNIX (querycache) format, so be sure to always run them
187 * through wfTimestamp()
191 function usesTimestamps() {
196 * Override to sort by increasing values
200 function sortDescending() {
205 * Is this query expensive (for some definition of expensive)? Then we
206 * don't let it run in miser mode. $wgDisableQueryPages causes all query
207 * pages to be declared expensive. Some query pages are always expensive.
211 function isExpensive() {
212 global $wgDisableQueryPages;
213 return $wgDisableQueryPages;
217 * Is the output of this query cacheable? Non-cacheable expensive pages
218 * will be disabled in miser mode and will not have their results written
219 * to the querycache table.
223 public function isCacheable() {
228 * Whether or not the output of the page in question is retrieved from
229 * the database cache.
233 function isCached() {
236 return $this->isExpensive() && $wgMiserMode;
240 * Sometime we don't want to build rss / atom feeds.
244 function isSyndicated() {
249 * Formats the results of the query for display. The skin is the current
250 * skin; you can use it for making links. The result is a single row of
251 * result data. You should be able to grab SQL results off of it.
252 * If the function returns false, the line output will be skipped.
254 * @param object $result Result row
255 * @return string|bool String or false to skip
257 abstract function formatResult( $skin, $result );
260 * The content returned by this function will be output before any result
264 function getPageHeader() {
269 * If using extra form wheely-dealies, return a set of parameters here
270 * as an associative array. They will be encoded and added to the paging
271 * links (prev/next/lengths).
275 function linkParameters() {
280 * Some special pages (for example SpecialListusers) might not return the
281 * current object formatted, but return the previous one instead.
282 * Setting this to return true will ensure formatResult() is called
283 * one more time to make sure that the very last result is formatted
287 function tryLastResult() {
292 * Clear the cache and save new results
294 * @param int|bool $limit Limit for SQL statement
295 * @param bool $ignoreErrors Whether to ignore database errors
296 * @throws DBError|Exception
299 function recache( $limit, $ignoreErrors = true ) {
300 if ( !$this->isCacheable() ) {
304 $fname = get_class( $this ) . '::recache';
305 $dbw = wfGetDB( DB_MASTER
);
312 $res = $this->reallyDoQuery( $limit, false );
315 $num = $res->numRows();
318 foreach ( $res as $row ) {
319 if ( isset( $row->value
) ) {
320 if ( $this->usesTimestamps() ) {
321 $value = wfTimestamp( TS_UNIX
,
324 $value = intval( $row->value
); // @bug 14414
330 $vals[] = array( 'qc_type' => $this->getName(),
331 'qc_namespace' => $row->namespace,
332 'qc_title' => $row->title
,
333 'qc_value' => $value );
336 $dbw->begin( __METHOD__
);
337 # Clear out any old cached data
338 $dbw->delete( 'querycache', array( 'qc_type' => $this->getName() ), $fname );
339 # Save results into the querycache table on the master
340 if ( count( $vals ) ) {
341 $dbw->insert( 'querycache', $vals, __METHOD__
);
343 # Update the querycache_info record for the page
344 $dbw->delete( 'querycache_info', array( 'qci_type' => $this->getName() ), $fname );
345 $dbw->insert( 'querycache_info',
346 array( 'qci_type' => $this->getName(), 'qci_timestamp' => $dbw->timestamp() ),
348 $dbw->commit( __METHOD__
);
350 } catch ( DBError
$e ) {
351 if ( !$ignoreErrors ) {
352 throw $e; // report query error
354 $num = false; // set result to false to indicate error
361 * Get a DB connection to be used for slow recache queries
362 * @return DatabaseBase
364 function getRecacheDB() {
365 return wfGetDB( DB_SLAVE
, array( $this->getName(), 'QueryPage::recache', 'vslow' ) );
369 * Run the query and return the result
370 * @param int|bool $limit Numerical limit or false for no limit
371 * @param int|bool $offset Numerical offset or false for no offset
372 * @return ResultWrapper
375 function reallyDoQuery( $limit, $offset = false ) {
376 $fname = get_class( $this ) . "::reallyDoQuery";
377 $dbr = $this->getRecacheDB();
378 $query = $this->getQueryInfo();
379 $order = $this->getOrderFields();
381 if ( $this->sortDescending() ) {
382 foreach ( $order as &$field ) {
387 if ( is_array( $query ) ) {
388 $tables = isset( $query['tables'] ) ?
(array)$query['tables'] : array();
389 $fields = isset( $query['fields'] ) ?
(array)$query['fields'] : array();
390 $conds = isset( $query['conds'] ) ?
(array)$query['conds'] : array();
391 $options = isset( $query['options'] ) ?
(array)$query['options'] : array();
392 $join_conds = isset( $query['join_conds'] ) ?
(array)$query['join_conds'] : array();
394 if ( count( $order ) ) {
395 $options['ORDER BY'] = $order;
398 if ( $limit !== false ) {
399 $options['LIMIT'] = intval( $limit );
402 if ( $offset !== false ) {
403 $options['OFFSET'] = intval( $offset );
406 $res = $dbr->select( $tables, $fields, $conds, $fname,
407 $options, $join_conds
410 // Old-fashioned raw SQL style, deprecated
411 $sql = $this->getSQL();
412 $sql .= ' ORDER BY ' . implode( ', ', $order );
413 $sql = $dbr->limitResult( $sql, $limit, $offset );
414 $res = $dbr->query( $sql, $fname );
417 return $dbr->resultObject( $res );
421 * Somewhat deprecated, you probably want to be using execute()
422 * @param int|bool $offset
423 * @param int|bool $limit
424 * @return ResultWrapper
426 function doQuery( $offset = false, $limit = false ) {
427 if ( $this->isCached() && $this->isCacheable() ) {
428 return $this->fetchFromCache( $limit, $offset );
430 return $this->reallyDoQuery( $limit, $offset );
435 * Fetch the query results from the query cache
436 * @param int|bool $limit Numerical limit or false for no limit
437 * @param int|bool $offset Numerical offset or false for no offset
438 * @return ResultWrapper
441 function fetchFromCache( $limit, $offset = false ) {
442 $dbr = wfGetDB( DB_SLAVE
);
444 if ( $limit !== false ) {
445 $options['LIMIT'] = intval( $limit );
447 if ( $offset !== false ) {
448 $options['OFFSET'] = intval( $offset );
450 if ( $this->sortDescending() ) {
451 $options['ORDER BY'] = 'qc_value DESC';
453 $options['ORDER BY'] = 'qc_value ASC';
455 $res = $dbr->select( 'querycache', array( 'qc_type',
456 'namespace' => 'qc_namespace',
457 'title' => 'qc_title',
458 'value' => 'qc_value' ),
459 array( 'qc_type' => $this->getName() ),
462 return $dbr->resultObject( $res );
465 public function getCachedTimestamp() {
466 if ( is_null( $this->cachedTimestamp
) ) {
467 $dbr = wfGetDB( DB_SLAVE
);
468 $fname = get_class( $this ) . '::getCachedTimestamp';
469 $this->cachedTimestamp
= $dbr->selectField( 'querycache_info', 'qci_timestamp',
470 array( 'qci_type' => $this->getName() ), $fname );
472 return $this->cachedTimestamp
;
476 * This is the actual workhorse. It does everything needed to make a
477 * real, honest-to-gosh query page.
481 function execute( $par ) {
482 global $wgQueryCacheLimit, $wgDisableQueryPageUpdate;
484 $user = $this->getUser();
485 if ( !$this->userCanExecute( $user ) ) {
486 $this->displayRestrictionError();
491 $this->outputHeader();
493 $out = $this->getOutput();
495 if ( $this->isCached() && !$this->isCacheable() ) {
496 $out->addWikiMsg( 'querypage-disabled' );
500 $out->setSyndicated( $this->isSyndicated() );
502 if ( $this->limit
== 0 && $this->offset
== 0 ) {
503 list( $this->limit
, $this->offset
) = $this->getRequest()->getLimitOffset();
506 // TODO: Use doQuery()
507 if ( !$this->isCached() ) {
508 # select one extra row for navigation
509 $res = $this->reallyDoQuery( $this->limit +
1, $this->offset
);
511 # Get the cached result, select one extra row for navigation
512 $res = $this->fetchFromCache( $this->limit +
1, $this->offset
);
513 if ( !$this->listoutput
) {
515 # Fetch the timestamp of this update
516 $ts = $this->getCachedTimestamp();
517 $lang = $this->getLanguage();
518 $maxResults = $lang->formatNum( $wgQueryCacheLimit );
521 $updated = $lang->userTimeAndDate( $ts, $user );
522 $updateddate = $lang->userDate( $ts, $user );
523 $updatedtime = $lang->userTime( $ts, $user );
524 $out->addMeta( 'Data-Cache-Time', $ts );
525 $out->addJsConfigVars( 'dataCacheTime', $ts );
526 $out->addWikiMsg( 'perfcachedts', $updated, $updateddate, $updatedtime, $maxResults );
528 $out->addWikiMsg( 'perfcached', $maxResults );
531 # If updates on this page have been disabled, let the user know
532 # that the data set won't be refreshed for now
533 if ( is_array( $wgDisableQueryPageUpdate )
534 && in_array( $this->getName(), $wgDisableQueryPageUpdate )
537 "<div class=\"mw-querypage-no-updates\">\n$1\n</div>",
538 'querypage-no-updates'
544 $this->numRows
= $res->numRows();
546 $dbr = wfGetDB( DB_SLAVE
);
547 $this->preprocessResults( $dbr, $res );
549 $out->addHTML( Xml
::openElement( 'div', array( 'class' => 'mw-spcontent' ) ) );
551 # Top header and navigation
552 if ( $this->shownavigation
) {
553 $out->addHTML( $this->getPageHeader() );
554 if ( $this->numRows
> 0 ) {
555 $out->addHTML( $this->msg( 'showingresultsinrange' )->numParams(
556 min( $this->numRows
, $this->limit
), # do not show the one extra row, if exist
557 $this->offset +
1, ( min( $this->numRows
, $this->limit
) +
$this->offset
) )->parseAsBlock() );
558 # Disable the "next" link when we reach the end
559 $paging = $this->getLanguage()->viewPrevNext( $this->getPageTitle( $par ), $this->offset
,
560 $this->limit
, $this->linkParameters(), ( $this->numRows
<= $this->limit
) );
561 $out->addHTML( '<p>' . $paging . '</p>' );
563 # No results to show, so don't bother with "showing X of Y" etc.
564 # -- just let the user know and give up now
565 $out->addWikiMsg( 'specialpage-empty' );
566 $out->addHTML( Xml
::closeElement( 'div' ) );
571 # The actual results; specialist subclasses will want to handle this
572 # with more than a straight list, so we hand them the info, plus
573 # an OutputPage, and let them get on with it
574 $this->outputResults( $out,
576 $dbr, # Should use a ResultWrapper for this
578 min( $this->numRows
, $this->limit
), # do not format the one extra row, if exist
581 # Repeat the paging links at the bottom
582 if ( $this->shownavigation
) {
583 $out->addHTML( '<p>' . $paging . '</p>' );
586 $out->addHTML( Xml
::closeElement( 'div' ) );
588 return min( $this->numRows
, $this->limit
); # do not return the one extra row, if exist
592 * Format and output report results using the given information plus
595 * @param OutputPage $out OutputPage to print to
596 * @param Skin $skin User skin to use
597 * @param DatabaseBase $dbr Database (read) connection to use
598 * @param int $res Result pointer
599 * @param int $num Number of available result rows
600 * @param int $offset Paging offset
602 protected function outputResults( $out, $skin, $dbr, $res, $num, $offset ) {
607 if ( !$this->listoutput
) {
608 $html[] = $this->openList( $offset );
611 # $res might contain the whole 1,000 rows, so we read up to
612 # $num [should update this to use a Pager]
613 for ( $i = 0; $i < $num && $row = $res->fetchObject(); $i++
) {
614 $line = $this->formatResult( $skin, $row );
616 $attr = ( isset( $row->usepatrol
) && $row->usepatrol
&& $row->patrolled
== 0 )
617 ?
' class="not-patrolled"'
619 $html[] = $this->listoutput
621 : "<li{$attr}>{$line}</li>\n";
625 # Flush the final result
626 if ( $this->tryLastResult() ) {
628 $line = $this->formatResult( $skin, $row );
630 $attr = ( isset( $row->usepatrol
) && $row->usepatrol
&& $row->patrolled
== 0 )
631 ?
' class="not-patrolled"'
633 $html[] = $this->listoutput
635 : "<li{$attr}>{$line}</li>\n";
639 if ( !$this->listoutput
) {
640 $html[] = $this->closeList();
643 $html = $this->listoutput
644 ?
$wgContLang->listToText( $html )
645 : implode( '', $html );
647 $out->addHTML( $html );
655 function openList( $offset ) {
656 return "\n<ol start='" . ( $offset +
1 ) . "' class='special'>\n";
662 function closeList() {
667 * Do any necessary preprocessing of the result object.
668 * @param DatabaseBase $db
669 * @param ResultWrapper $res
671 function preprocessResults( $db, $res ) {}
674 * Similar to above, but packaging in a syndicated feed instead of a web page
675 * @param string $class
679 function doFeed( $class = '', $limit = 50 ) {
680 global $wgFeed, $wgFeedClasses, $wgFeedLimit;
683 $this->getOutput()->addWikiMsg( 'feed-unavailable' );
687 $limit = min( $limit, $wgFeedLimit );
689 if ( isset( $wgFeedClasses[$class] ) ) {
690 $feed = new $wgFeedClasses[$class](
696 $res = $this->reallyDoQuery( $limit, 0 );
697 foreach ( $res as $obj ) {
698 $item = $this->feedResult( $obj );
700 $feed->outItem( $item );
712 * Override for custom handling. If the titles/links are ok, just do
715 * @return FeedItem|null
717 function feedResult( $row ) {
718 if ( !isset( $row->title
) ) {
721 $title = Title
::makeTitle( intval( $row->namespace ), $row->title
);
723 $date = isset( $row->timestamp
) ?
$row->timestamp
: '';
726 $talkpage = $title->getTalkPage();
727 $comments = $talkpage->getFullURL();
731 $title->getPrefixedText(),
732 $this->feedItemDesc( $row ),
733 $title->getFullURL(),
735 $this->feedItemAuthor( $row ),
742 function feedItemDesc( $row ) {
743 return isset( $row->comment
) ?
htmlspecialchars( $row->comment
) : '';
746 function feedItemAuthor( $row ) {
747 return isset( $row->user_text
) ?
$row->user_text
: '';
750 function feedTitle() {
751 global $wgLanguageCode, $wgSitename;
752 $desc = $this->getDescription();
753 return "$wgSitename - $desc [$wgLanguageCode]";
756 function feedDesc() {
757 return $this->msg( 'tagline' )->text();
761 return $this->getPageTitle()->getFullURL();
766 * Class definition for a wanted query page like
767 * WantedPages, WantedTemplates, etc
769 abstract class WantedQueryPage
extends QueryPage
{
770 function isExpensive() {
774 function isSyndicated() {
779 * Cache page existence for performance
780 * @param DatabaseBase $db
781 * @param ResultWrapper $res
783 function preprocessResults( $db, $res ) {
784 if ( !$res->numRows() ) {
788 $batch = new LinkBatch
;
789 foreach ( $res as $row ) {
790 $batch->add( $row->namespace, $row->title
);
794 // Back to start for display
799 * Should formatResult() always check page existence, even if
800 * the results are fresh? This is a (hopefully temporary)
801 * kluge for Special:WantedFiles, which may contain false
802 * positives for files that exist e.g. in a shared repo (bug
806 function forceExistenceCheck() {
811 * Format an individual result
813 * @param Skin $skin Skin to use for UI elements
814 * @param object $result Result row
817 public function formatResult( $skin, $result ) {
818 $title = Title
::makeTitleSafe( $result->namespace, $result->title
);
819 if ( $title instanceof Title
) {
820 if ( $this->isCached() ||
$this->forceExistenceCheck() ) {
821 $pageLink = $title->isKnown()
822 ?
'<del>' . Linker
::link( $title ) . '</del>'
831 $pageLink = Linker
::link(
839 return $this->getLanguage()->specialList( $pageLink, $this->makeWlhLink( $title, $result ) );
841 return $this->msg( 'wantedpages-badtitle', $result->title
)->escaped();
846 * Make a "what links here" link for a given title
848 * @param Title $title Title to make the link for
849 * @param object $result Result row
852 private function makeWlhLink( $title, $result ) {
853 $wlh = SpecialPage
::getTitleFor( 'Whatlinkshere', $title->getPrefixedText() );
854 $label = $this->msg( 'nlinks' )->numParams( $result->value
)->escaped();
855 return Linker
::link( $wlh, $label );