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 * List of query page classes and their associated special pages,
26 * for periodic updates.
28 * DO NOT CHANGE THIS LIST without testing that
29 * maintenance/updateSpecialPages.php still works.
31 global $wgQueryPages; // not redundant
32 $wgQueryPages = array(
33 // QueryPage subclass, Special page name, Limit (false for none, none for the default)
34 // ----------------------------------------------------------------------------
35 array( 'AncientPagesPage', 'Ancientpages' ),
36 array( 'BrokenRedirectsPage', 'BrokenRedirects' ),
37 array( 'DeadendPagesPage', 'Deadendpages' ),
38 array( 'DoubleRedirectsPage', 'DoubleRedirects' ),
39 array( 'FileDuplicateSearchPage', 'FileDuplicateSearch' ),
40 array( 'LinkSearchPage', 'LinkSearch' ),
41 array( 'ListredirectsPage', 'Listredirects' ),
42 array( 'LonelyPagesPage', 'Lonelypages' ),
43 array( 'LongPagesPage', 'Longpages' ),
44 array( 'MIMEsearchPage', 'MIMEsearch' ),
45 array( 'MostcategoriesPage', 'Mostcategories' ),
46 array( 'MostimagesPage', 'Mostimages' ),
47 array( 'MostinterwikisPage', 'Mostinterwikis' ),
48 array( 'MostlinkedCategoriesPage', 'Mostlinkedcategories' ),
49 array( 'MostlinkedtemplatesPage', 'Mostlinkedtemplates' ),
50 array( 'MostlinkedPage', 'Mostlinked' ),
51 array( 'MostrevisionsPage', 'Mostrevisions' ),
52 array( 'FewestrevisionsPage', 'Fewestrevisions' ),
53 array( 'ShortPagesPage', 'Shortpages' ),
54 array( 'UncategorizedCategoriesPage', 'Uncategorizedcategories' ),
55 array( 'UncategorizedPagesPage', 'Uncategorizedpages' ),
56 array( 'UncategorizedImagesPage', 'Uncategorizedimages' ),
57 array( 'UncategorizedTemplatesPage', 'Uncategorizedtemplates' ),
58 array( 'UnusedCategoriesPage', 'Unusedcategories' ),
59 array( 'UnusedimagesPage', 'Unusedimages' ),
60 array( 'WantedCategoriesPage', 'Wantedcategories' ),
61 array( 'WantedFilesPage', 'Wantedfiles' ),
62 array( 'WantedPagesPage', 'Wantedpages' ),
63 array( 'WantedTemplatesPage', 'Wantedtemplates' ),
64 array( 'UnwatchedPagesPage', 'Unwatchedpages' ),
65 array( 'UnusedtemplatesPage', 'Unusedtemplates' ),
66 array( 'WithoutInterwikiPage', 'Withoutinterwiki' ),
68 wfRunHooks( 'wgQueryPages', array( &$wgQueryPages ) );
70 global $wgDisableCounters;
71 if ( !$wgDisableCounters ) {
72 $wgQueryPages[] = array( 'PopularPagesPage', 'Popularpages' );
76 * This is a class for doing query pages; since they're almost all the same,
77 * we factor out some of the functionality into a superclass, and let
78 * subclasses derive from it.
79 * @ingroup SpecialPage
81 abstract class QueryPage
extends SpecialPage
{
83 * Whether or not we want plain listoutput rather than an ordered list
87 var $listoutput = false;
90 * The offset and limit in use, as passed to the query() function
98 * The number of rows returned by the query. Reading this variable
99 * only makes sense in functions that are run after the query has been
100 * done, such as preprocessResults() and formatRow().
104 protected $cachedTimestamp = null;
107 * Wheter to show prev/next links
109 protected $shownavigation = true;
112 * A mutator for $this->listoutput;
116 function setListoutput( $bool ) {
117 $this->listoutput
= $bool;
121 * Subclasses return an SQL query here, formatted as an array with the
123 * tables => Table(s) for passing to Database::select()
124 * fields => Field(s) for passing to Database::select(), may be *
125 * conds => WHERE conditions
127 * join_conds => JOIN conditions
129 * Note that the query itself should return the following three columns:
130 * 'namespace', 'title', and 'value'. 'value' is used for sorting.
132 * These may be stored in the querycache table for expensive queries,
133 * and that cached data will be returned sometimes, so the presence of
134 * extra fields can't be relied upon. The cached 'value' column will be
135 * an integer; non-numeric values are useful only for sorting the
136 * initial query (except if they're timestamps, see usesTimestamps()).
138 * Don't include an ORDER or LIMIT clause, they will be added.
140 * If this function is not overridden or returns something other than
141 * an array, getSQL() will be used instead. This is for backwards
142 * compatibility only and is strongly deprecated.
146 function getQueryInfo() {
151 * For back-compat, subclasses may return a raw SQL query here, as a string.
152 * This is strongly deprecated; getQueryInfo() should be overridden instead.
153 * @throws MWException
157 /* Implement getQueryInfo() instead */
158 throw new MWException( "Bug in a QueryPage: doesn't implement getQueryInfo() nor "
159 . "getQuery() properly" );
163 * Subclasses return an array of fields to order by here. Don't append
164 * DESC to the field names, that'll be done automatically if
165 * sortDescending() returns true.
169 function getOrderFields() {
170 return array( 'value' );
174 * Does this query return timestamps rather than integers in its
175 * 'value' field? If true, this class will convert 'value' to a
176 * UNIX timestamp for caching.
177 * NOTE: formatRow() may get timestamps in TS_MW (mysql), TS_DB (pgsql)
178 * or TS_UNIX (querycache) format, so be sure to always run them
179 * through wfTimestamp()
183 function usesTimestamps() {
188 * Override to sort by increasing values
192 function sortDescending() {
197 * Is this query expensive (for some definition of expensive)? Then we
198 * don't let it run in miser mode. $wgDisableQueryPages causes all query
199 * pages to be declared expensive. Some query pages are always expensive.
203 function isExpensive() {
204 global $wgDisableQueryPages;
205 return $wgDisableQueryPages;
209 * Is the output of this query cacheable? Non-cacheable expensive pages
210 * will be disabled in miser mode and will not have their results written
211 * to the querycache table.
215 public function isCacheable() {
220 * Whether or not the output of the page in question is retrieved from
221 * the database cache.
225 function isCached() {
228 return $this->isExpensive() && $wgMiserMode;
232 * Sometime we don't want to build rss / atom feeds.
236 function isSyndicated() {
241 * Formats the results of the query for display. The skin is the current
242 * skin; you can use it for making links. The result is a single row of
243 * result data. You should be able to grab SQL results off of it.
244 * If the function returns false, the line output will be skipped.
246 * @param object $result Result row
247 * @return string|bool String or false to skip
249 abstract function formatResult( $skin, $result );
252 * The content returned by this function will be output before any result
256 function getPageHeader() {
261 * If using extra form wheely-dealies, return a set of parameters here
262 * as an associative array. They will be encoded and added to the paging
263 * links (prev/next/lengths).
267 function linkParameters() {
272 * Some special pages (for example SpecialListusers) might not return the
273 * current object formatted, but return the previous one instead.
274 * Setting this to return true will ensure formatResult() is called
275 * one more time to make sure that the very last result is formatted
279 function tryLastResult() {
284 * Clear the cache and save new results
286 * @param int|bool $limit Limit for SQL statement
287 * @param bool $ignoreErrors Whether to ignore database errors
288 * @throws DBError|Exception
291 function recache( $limit, $ignoreErrors = true ) {
292 if ( !$this->isCacheable() ) {
296 $fname = get_class( $this ) . '::recache';
297 $dbw = wfGetDB( DB_MASTER
);
303 # Clear out any old cached data
304 $dbw->delete( 'querycache', array( 'qc_type' => $this->getName() ), $fname );
306 $res = $this->reallyDoQuery( $limit, false );
309 $num = $res->numRows();
312 foreach ( $res as $row ) {
313 if ( isset( $row->value
) ) {
314 if ( $this->usesTimestamps() ) {
315 $value = wfTimestamp( TS_UNIX
,
318 $value = intval( $row->value
); // @bug 14414
324 $vals[] = array( 'qc_type' => $this->getName(),
325 'qc_namespace' => $row->namespace,
326 'qc_title' => $row->title
,
327 'qc_value' => $value );
330 # Save results into the querycache table on the master
331 if ( count( $vals ) ) {
332 $dbw->insert( 'querycache', $vals, __METHOD__
);
334 # Update the querycache_info record for the page
335 $dbw->delete( 'querycache_info', array( 'qci_type' => $this->getName() ), $fname );
336 $dbw->insert( 'querycache_info',
337 array( 'qci_type' => $this->getName(), 'qci_timestamp' => $dbw->timestamp() ),
340 } catch ( DBError
$e ) {
341 if ( !$ignoreErrors ) {
342 throw $e; // report query error
344 $num = false; // set result to false to indicate error
351 * Get a DB connection to be used for slow recache queries
353 function getRecacheDB() {
354 return wfGetDB( DB_SLAVE
, array( $this->getName(), 'QueryPage::recache', 'vslow' ) );
358 * Run the query and return the result
359 * @param int|bool $limit Numerical limit or false for no limit
360 * @param int|bool $offset Numerical offset or false for no offset
361 * @return ResultWrapper
364 function reallyDoQuery( $limit, $offset = false ) {
365 $fname = get_class( $this ) . "::reallyDoQuery";
366 $dbr = $this->getRecacheDB();
367 $query = $this->getQueryInfo();
368 $order = $this->getOrderFields();
370 if ( $this->sortDescending() ) {
371 foreach ( $order as &$field ) {
376 if ( is_array( $query ) ) {
377 $tables = isset( $query['tables'] ) ?
(array)$query['tables'] : array();
378 $fields = isset( $query['fields'] ) ?
(array)$query['fields'] : array();
379 $conds = isset( $query['conds'] ) ?
(array)$query['conds'] : array();
380 $options = isset( $query['options'] ) ?
(array)$query['options'] : array();
381 $join_conds = isset( $query['join_conds'] ) ?
(array)$query['join_conds'] : array();
383 if ( count( $order ) ) {
384 $options['ORDER BY'] = $order;
387 if ( $limit !== false ) {
388 $options['LIMIT'] = intval( $limit );
391 if ( $offset !== false ) {
392 $options['OFFSET'] = intval( $offset );
395 $res = $dbr->select( $tables, $fields, $conds, $fname,
396 $options, $join_conds
399 // Old-fashioned raw SQL style, deprecated
400 $sql = $this->getSQL();
401 $sql .= ' ORDER BY ' . implode( ', ', $order );
402 $sql = $dbr->limitResult( $sql, $limit, $offset );
403 $res = $dbr->query( $sql, $fname );
406 return $dbr->resultObject( $res );
410 * Somewhat deprecated, you probably want to be using execute()
411 * @param int|bool $offset
412 * @oaram int|bool $limit
413 * @return ResultWrapper
415 function doQuery( $offset = false, $limit = false ) {
416 if ( $this->isCached() && $this->isCacheable() ) {
417 return $this->fetchFromCache( $limit, $offset );
419 return $this->reallyDoQuery( $limit, $offset );
424 * Fetch the query results from the query cache
425 * @param int|bool $limit Numerical limit or false for no limit
426 * @param int|bool $offset Numerical offset or false for no offset
427 * @return ResultWrapper
430 function fetchFromCache( $limit, $offset = false ) {
431 $dbr = wfGetDB( DB_SLAVE
);
433 if ( $limit !== false ) {
434 $options['LIMIT'] = intval( $limit );
436 if ( $offset !== false ) {
437 $options['OFFSET'] = intval( $offset );
439 if ( $this->sortDescending() ) {
440 $options['ORDER BY'] = 'qc_value DESC';
442 $options['ORDER BY'] = 'qc_value ASC';
444 $res = $dbr->select( 'querycache', array( 'qc_type',
445 'namespace' => 'qc_namespace',
446 'title' => 'qc_title',
447 'value' => 'qc_value' ),
448 array( 'qc_type' => $this->getName() ),
451 return $dbr->resultObject( $res );
454 public function getCachedTimestamp() {
455 if ( is_null( $this->cachedTimestamp
) ) {
456 $dbr = wfGetDB( DB_SLAVE
);
457 $fname = get_class( $this ) . '::getCachedTimestamp';
458 $this->cachedTimestamp
= $dbr->selectField( 'querycache_info', 'qci_timestamp',
459 array( 'qci_type' => $this->getName() ), $fname );
461 return $this->cachedTimestamp
;
465 * This is the actual workhorse. It does everything needed to make a
466 * real, honest-to-gosh query page.
470 function execute( $par ) {
471 global $wgQueryCacheLimit, $wgDisableQueryPageUpdate;
473 $user = $this->getUser();
474 if ( !$this->userCanExecute( $user ) ) {
475 $this->displayRestrictionError();
480 $this->outputHeader();
482 $out = $this->getOutput();
484 if ( $this->isCached() && !$this->isCacheable() ) {
485 $out->addWikiMsg( 'querypage-disabled' );
489 $out->setSyndicated( $this->isSyndicated() );
491 if ( $this->limit
== 0 && $this->offset
== 0 ) {
492 list( $this->limit
, $this->offset
) = $this->getRequest()->getLimitOffset();
495 // TODO: Use doQuery()
496 if ( !$this->isCached() ) {
497 # select one extra row for navigation
498 $res = $this->reallyDoQuery( $this->limit +
1, $this->offset
);
500 # Get the cached result, select one extra row for navigation
501 $res = $this->fetchFromCache( $this->limit +
1, $this->offset
);
502 if ( !$this->listoutput
) {
504 # Fetch the timestamp of this update
505 $ts = $this->getCachedTimestamp();
506 $lang = $this->getLanguage();
507 $maxResults = $lang->formatNum( $wgQueryCacheLimit );
510 $updated = $lang->userTimeAndDate( $ts, $user );
511 $updateddate = $lang->userDate( $ts, $user );
512 $updatedtime = $lang->userTime( $ts, $user );
513 $out->addMeta( 'Data-Cache-Time', $ts );
514 $out->addJsConfigVars( 'dataCacheTime', $ts );
515 $out->addWikiMsg( 'perfcachedts', $updated, $updateddate, $updatedtime, $maxResults );
517 $out->addWikiMsg( 'perfcached', $maxResults );
520 # If updates on this page have been disabled, let the user know
521 # that the data set won't be refreshed for now
522 if ( is_array( $wgDisableQueryPageUpdate )
523 && in_array( $this->getName(), $wgDisableQueryPageUpdate )
526 "<div class=\"mw-querypage-no-updates\">\n$1\n</div>",
527 'querypage-no-updates'
533 $this->numRows
= $res->numRows();
535 $dbr = wfGetDB( DB_SLAVE
);
536 $this->preprocessResults( $dbr, $res );
538 $out->addHTML( Xml
::openElement( 'div', array( 'class' => 'mw-spcontent' ) ) );
540 # Top header and navigation
541 if ( $this->shownavigation
) {
542 $out->addHTML( $this->getPageHeader() );
543 if ( $this->numRows
> 0 ) {
544 $out->addHTML( $this->msg( 'showingresults' )->numParams(
545 min( $this->numRows
, $this->limit
), # do not show the one extra row, if exist
546 $this->offset +
1 )->parseAsBlock() );
547 # Disable the "next" link when we reach the end
548 $paging = $this->getLanguage()->viewPrevNext( $this->getTitle( $par ), $this->offset
,
549 $this->limit
, $this->linkParameters(), ( $this->numRows
<= $this->limit
) );
550 $out->addHTML( '<p>' . $paging . '</p>' );
552 # No results to show, so don't bother with "showing X of Y" etc.
553 # -- just let the user know and give up now
554 $out->addWikiMsg( 'specialpage-empty' );
555 $out->addHTML( Xml
::closeElement( 'div' ) );
560 # The actual results; specialist subclasses will want to handle this
561 # with more than a straight list, so we hand them the info, plus
562 # an OutputPage, and let them get on with it
563 $this->outputResults( $out,
565 $dbr, # Should use a ResultWrapper for this
567 min( $this->numRows
, $this->limit
), # do not format the one extra row, if exist
570 # Repeat the paging links at the bottom
571 if ( $this->shownavigation
) {
572 $out->addHTML( '<p>' . $paging . '</p>' );
575 $out->addHTML( Xml
::closeElement( 'div' ) );
577 return min( $this->numRows
, $this->limit
); # do not return the one extra row, if exist
581 * Format and output report results using the given information plus
584 * @param OutputPage $out OutputPage to print to
585 * @param Skin $skin User skin to use
586 * @param DatabaseBase $dbr Database (read) connection to use
587 * @param int $res Result pointer
588 * @param int $num Number of available result rows
589 * @param int $offset Paging offset
591 protected function outputResults( $out, $skin, $dbr, $res, $num, $offset ) {
596 if ( !$this->listoutput
) {
597 $html[] = $this->openList( $offset );
600 # $res might contain the whole 1,000 rows, so we read up to
601 # $num [should update this to use a Pager]
602 for ( $i = 0; $i < $num && $row = $res->fetchObject(); $i++
) {
603 $line = $this->formatResult( $skin, $row );
605 $attr = ( isset( $row->usepatrol
) && $row->usepatrol
&& $row->patrolled
== 0 )
606 ?
' class="not-patrolled"'
608 $html[] = $this->listoutput
610 : "<li{$attr}>{$line}</li>\n";
614 # Flush the final result
615 if ( $this->tryLastResult() ) {
617 $line = $this->formatResult( $skin, $row );
619 $attr = ( isset( $row->usepatrol
) && $row->usepatrol
&& $row->patrolled
== 0 )
620 ?
' class="not-patrolled"'
622 $html[] = $this->listoutput
624 : "<li{$attr}>{$line}</li>\n";
628 if ( !$this->listoutput
) {
629 $html[] = $this->closeList();
632 $html = $this->listoutput
633 ?
$wgContLang->listToText( $html )
634 : implode( '', $html );
636 $out->addHTML( $html );
644 function openList( $offset ) {
645 return "\n<ol start='" . ( $offset +
1 ) . "' class='special'>\n";
651 function closeList() {
656 * Do any necessary preprocessing of the result object.
657 * @param DatabaseBase $db
658 * @param ResultWrapper $res
660 function preprocessResults( $db, $res ) {}
663 * Similar to above, but packaging in a syndicated feed instead of a web page
664 * @param string $class
668 function doFeed( $class = '', $limit = 50 ) {
669 global $wgFeed, $wgFeedClasses, $wgFeedLimit;
672 $this->getOutput()->addWikiMsg( 'feed-unavailable' );
676 $limit = min( $limit, $wgFeedLimit );
678 if ( isset( $wgFeedClasses[$class] ) ) {
679 $feed = new $wgFeedClasses[$class](
685 $res = $this->reallyDoQuery( $limit, 0 );
686 foreach ( $res as $obj ) {
687 $item = $this->feedResult( $obj );
689 $feed->outItem( $item );
701 * Override for custom handling. If the titles/links are ok, just do
704 * @return FeedItem|null
706 function feedResult( $row ) {
707 if ( !isset( $row->title
) ) {
710 $title = Title
::makeTitle( intval( $row->namespace ), $row->title
);
712 $date = isset( $row->timestamp
) ?
$row->timestamp
: '';
715 $talkpage = $title->getTalkPage();
716 $comments = $talkpage->getFullURL();
720 $title->getPrefixedText(),
721 $this->feedItemDesc( $row ),
722 $title->getFullURL(),
724 $this->feedItemAuthor( $row ),
731 function feedItemDesc( $row ) {
732 return isset( $row->comment
) ?
htmlspecialchars( $row->comment
) : '';
735 function feedItemAuthor( $row ) {
736 return isset( $row->user_text
) ?
$row->user_text
: '';
739 function feedTitle() {
740 global $wgLanguageCode, $wgSitename;
741 $desc = $this->getDescription();
742 return "$wgSitename - $desc [$wgLanguageCode]";
745 function feedDesc() {
746 return $this->msg( 'tagline' )->text();
750 return $this->getTitle()->getFullURL();
755 * Class definition for a wanted query page like
756 * WantedPages, WantedTemplates, etc
758 abstract class WantedQueryPage
extends QueryPage
{
759 function isExpensive() {
763 function isSyndicated() {
768 * Cache page existence for performance
769 * @param DatabaseBase $db
770 * @param ResultWrapper $res
772 function preprocessResults( $db, $res ) {
773 if ( !$res->numRows() ) {
777 $batch = new LinkBatch
;
778 foreach ( $res as $row ) {
779 $batch->add( $row->namespace, $row->title
);
783 // Back to start for display
788 * Should formatResult() always check page existence, even if
789 * the results are fresh? This is a (hopefully temporary)
790 * kluge for Special:WantedFiles, which may contain false
791 * positives for files that exist e.g. in a shared repo (bug
795 function forceExistenceCheck() {
800 * Format an individual result
802 * @param Skin $skin Skin to use for UI elements
803 * @param object $result Result row
806 public function formatResult( $skin, $result ) {
807 $title = Title
::makeTitleSafe( $result->namespace, $result->title
);
808 if ( $title instanceof Title
) {
809 if ( $this->isCached() ||
$this->forceExistenceCheck() ) {
810 $pageLink = $title->isKnown()
811 ?
'<del>' . Linker
::link( $title ) . '</del>'
820 $pageLink = Linker
::link(
828 return $this->getLanguage()->specialList( $pageLink, $this->makeWlhLink( $title, $result ) );
830 return $this->msg( 'wantedpages-badtitle', $result->title
)->escaped();
835 * Make a "what links here" link for a given title
837 * @param Title $title Title to make the link for
838 * @param object $result Result row
841 private function makeWlhLink( $title, $result ) {
842 $wlh = SpecialPage
::getTitleFor( 'Whatlinkshere', $title->getPrefixedText() );
843 $label = $this->msg( 'nlinks' )->numParams( $result->value
)->escaped();
844 return Linker
::link( $wlh, $label );