MediaWiki REL1_33
QueryPage.php
Go to the documentation of this file.
1<?php
28
35abstract class QueryPage extends SpecialPage {
37 protected $listoutput = false;
38
40 protected $offset = 0;
41
43 protected $limit = 0;
44
52 protected $numRows;
53
57 protected $cachedTimestamp = null;
58
62 protected $shownavigation = true;
63
73 public static function getPages() {
74 static $qp = null;
75
76 if ( $qp === null ) {
77 // QueryPage subclass, Special page name
78 $qp = [
79 [ AncientPagesPage::class, 'Ancientpages' ],
80 [ BrokenRedirectsPage::class, 'BrokenRedirects' ],
81 [ DeadendPagesPage::class, 'Deadendpages' ],
82 [ DoubleRedirectsPage::class, 'DoubleRedirects' ],
83 [ FileDuplicateSearchPage::class, 'FileDuplicateSearch' ],
84 [ ListDuplicatedFilesPage::class, 'ListDuplicatedFiles' ],
85 [ LinkSearchPage::class, 'LinkSearch' ],
86 [ ListredirectsPage::class, 'Listredirects' ],
87 [ LonelyPagesPage::class, 'Lonelypages' ],
88 [ LongPagesPage::class, 'Longpages' ],
89 [ MediaStatisticsPage::class, 'MediaStatistics' ],
90 [ MIMEsearchPage::class, 'MIMEsearch' ],
91 [ MostcategoriesPage::class, 'Mostcategories' ],
92 [ MostimagesPage::class, 'Mostimages' ],
93 [ MostinterwikisPage::class, 'Mostinterwikis' ],
94 [ MostlinkedCategoriesPage::class, 'Mostlinkedcategories' ],
95 [ MostlinkedTemplatesPage::class, 'Mostlinkedtemplates' ],
96 [ MostlinkedPage::class, 'Mostlinked' ],
97 [ MostrevisionsPage::class, 'Mostrevisions' ],
98 [ FewestrevisionsPage::class, 'Fewestrevisions' ],
99 [ ShortPagesPage::class, 'Shortpages' ],
100 [ UncategorizedCategoriesPage::class, 'Uncategorizedcategories' ],
101 [ UncategorizedPagesPage::class, 'Uncategorizedpages' ],
102 [ UncategorizedImagesPage::class, 'Uncategorizedimages' ],
103 [ UncategorizedTemplatesPage::class, 'Uncategorizedtemplates' ],
104 [ UnusedCategoriesPage::class, 'Unusedcategories' ],
105 [ UnusedimagesPage::class, 'Unusedimages' ],
106 [ WantedCategoriesPage::class, 'Wantedcategories' ],
107 [ WantedFilesPage::class, 'Wantedfiles' ],
108 [ WantedPagesPage::class, 'Wantedpages' ],
109 [ WantedTemplatesPage::class, 'Wantedtemplates' ],
110 [ UnwatchedpagesPage::class, 'Unwatchedpages' ],
111 [ UnusedtemplatesPage::class, 'Unusedtemplates' ],
112 [ WithoutInterwikiPage::class, 'Withoutinterwiki' ],
113 ];
114 Hooks::run( 'wgQueryPages', [ &$qp ] );
115 }
116
117 return $qp;
118 }
119
125 function setListoutput( $bool ) {
126 $this->listoutput = $bool;
127 }
128
155 public function getQueryInfo() {
156 return null;
157 }
158
165 function getSQL() {
166 /* Implement getQueryInfo() instead */
167 throw new MWException( "Bug in a QueryPage: doesn't implement getQueryInfo() nor "
168 . "getQuery() properly" );
169 }
170
178 function getOrderFields() {
179 return [ 'value' ];
180 }
181
192 public function usesTimestamps() {
193 return false;
194 }
195
201 function sortDescending() {
202 return true;
203 }
204
212 public function isExpensive() {
213 return $this->getConfig()->get( 'DisableQueryPages' );
214 }
215
223 public function isCacheable() {
224 return true;
225 }
226
233 public function isCached() {
234 return $this->isExpensive() && $this->getConfig()->get( 'MiserMode' );
235 }
236
242 function isSyndicated() {
243 return true;
244 }
245
255 abstract function formatResult( $skin, $result );
256
262 function getPageHeader() {
263 return '';
264 }
265
273 protected function showEmptyText() {
274 $this->getOutput()->addWikiMsg( 'specialpage-empty' );
275 }
276
284 function linkParameters() {
285 return [];
286 }
287
299 function tryLastResult() {
300 return false;
301 }
302
311 public function recache( $limit, $ignoreErrors = true ) {
312 if ( !$this->isCacheable() ) {
313 return 0;
314 }
315
316 $fname = static::class . '::recache';
317 $dbw = wfGetDB( DB_MASTER );
318 if ( !$dbw ) {
319 return false;
320 }
321
322 try {
323 # Do query
324 $res = $this->reallyDoQuery( $limit, false );
325 $num = false;
326 if ( $res ) {
327 $num = $res->numRows();
328 # Fetch results
329 $vals = [];
330 foreach ( $res as $row ) {
331 if ( isset( $row->value ) ) {
332 if ( $this->usesTimestamps() ) {
333 $value = wfTimestamp( TS_UNIX,
334 $row->value );
335 } else {
336 $value = intval( $row->value ); // T16414
337 }
338 } else {
339 $value = 0;
340 }
341
342 $vals[] = [
343 'qc_type' => $this->getName(),
344 'qc_namespace' => $row->namespace,
345 'qc_title' => $row->title,
346 'qc_value' => $value
347 ];
348 }
349
350 $dbw->doAtomicSection(
351 __METHOD__,
352 function ( IDatabase $dbw, $fname ) use ( $vals ) {
353 # Clear out any old cached data
354 $dbw->delete( 'querycache',
355 [ 'qc_type' => $this->getName() ],
356 $fname
357 );
358 # Save results into the querycache table on the master
359 if ( count( $vals ) ) {
360 $dbw->insert( 'querycache', $vals, $fname );
361 }
362 # Update the querycache_info record for the page
363 $dbw->delete( 'querycache_info',
364 [ 'qci_type' => $this->getName() ],
365 $fname
366 );
367 $dbw->insert( 'querycache_info',
368 [ 'qci_type' => $this->getName(),
369 'qci_timestamp' => $dbw->timestamp() ],
370 $fname
371 );
372 }
373 );
374 }
375 } catch ( DBError $e ) {
376 if ( !$ignoreErrors ) {
377 throw $e; // report query error
378 }
379 $num = false; // set result to false to indicate error
380 }
381
382 return $num;
383 }
384
389 function getRecacheDB() {
390 return wfGetDB( DB_REPLICA, [ $this->getName(), 'QueryPage::recache', 'vslow' ] );
391 }
392
400 public function reallyDoQuery( $limit, $offset = false ) {
401 $fname = static::class . '::reallyDoQuery';
402 $dbr = $this->getRecacheDB();
403 $query = $this->getQueryInfo();
404 $order = $this->getOrderFields();
405
406 if ( $this->sortDescending() ) {
407 foreach ( $order as &$field ) {
408 $field .= ' DESC';
409 }
410 }
411
412 if ( is_array( $query ) ) {
413 $tables = isset( $query['tables'] ) ? (array)$query['tables'] : [];
414 $fields = isset( $query['fields'] ) ? (array)$query['fields'] : [];
415 $conds = isset( $query['conds'] ) ? (array)$query['conds'] : [];
416 $options = isset( $query['options'] ) ? (array)$query['options'] : [];
417 $join_conds = isset( $query['join_conds'] ) ? (array)$query['join_conds'] : [];
418
419 if ( $order ) {
420 $options['ORDER BY'] = $order;
421 }
422
423 if ( $limit !== false ) {
424 $options['LIMIT'] = intval( $limit );
425 }
426
427 if ( $offset !== false ) {
428 $options['OFFSET'] = intval( $offset );
429 }
430
431 $res = $dbr->select( $tables, $fields, $conds, $fname,
432 $options, $join_conds
433 );
434 } else {
435 // Old-fashioned raw SQL style, deprecated
436 $sql = $this->getSQL();
437 $sql .= ' ORDER BY ' . implode( ', ', $order );
438 $sql = $dbr->limitResult( $sql, $limit, $offset );
439 $res = $dbr->query( $sql, $fname );
440 }
441
442 return $res;
443 }
444
451 public function doQuery( $offset = false, $limit = false ) {
452 if ( $this->isCached() && $this->isCacheable() ) {
453 return $this->fetchFromCache( $limit, $offset );
454 } else {
455 return $this->reallyDoQuery( $limit, $offset );
456 }
457 }
458
466 public function fetchFromCache( $limit, $offset = false ) {
468 $options = [];
469
470 if ( $limit !== false ) {
471 $options['LIMIT'] = intval( $limit );
472 }
473
474 if ( $offset !== false ) {
475 $options['OFFSET'] = intval( $offset );
476 }
477
478 $order = $this->getCacheOrderFields();
479 if ( $this->sortDescending() ) {
480 foreach ( $order as &$field ) {
481 $field .= " DESC";
482 }
483 }
484 if ( $order ) {
485 $options['ORDER BY'] = $order;
486 }
487
488 return $dbr->select( 'querycache',
489 [ 'qc_type',
490 'namespace' => 'qc_namespace',
491 'title' => 'qc_title',
492 'value' => 'qc_value' ],
493 [ 'qc_type' => $this->getName() ],
494 __METHOD__,
496 );
497 }
498
506 return [ 'value' ];
507 }
508
512 public function getCachedTimestamp() {
513 if ( is_null( $this->cachedTimestamp ) ) {
515 $fname = static::class . '::getCachedTimestamp';
516 $this->cachedTimestamp = $dbr->selectField( 'querycache_info', 'qci_timestamp',
517 [ 'qci_type' => $this->getName() ], $fname );
518 }
520 }
521
534 protected function getLimitOffset() {
535 list( $limit, $offset ) = $this->getRequest()->getLimitOffset();
536 if ( $this->getConfig()->get( 'MiserMode' ) ) {
537 $maxResults = $this->getMaxResults();
538 // Can't display more than max results on a page
539 $limit = min( $limit, $maxResults );
540 // Can't skip over more than the end of $maxResults
541 $offset = min( $offset, $maxResults + 1 );
542 }
543 return [ $limit, $offset ];
544 }
545
554 protected function getDBLimit( $uiLimit, $uiOffset ) {
555 $maxResults = $this->getMaxResults();
556 if ( $this->getConfig()->get( 'MiserMode' ) ) {
557 $limit = min( $uiLimit + 1, $maxResults - $uiOffset );
558 return max( $limit, 0 );
559 } else {
560 return $uiLimit + 1;
561 }
562 }
563
573 protected function getMaxResults() {
574 // Max of 10000, unless we store more than 10000 in query cache.
575 return max( $this->getConfig()->get( 'QueryCacheLimit' ), 10000 );
576 }
577
583 public function execute( $par ) {
584 $user = $this->getUser();
585 if ( !$this->userCanExecute( $user ) ) {
587 return;
588 }
589
590 $this->setHeaders();
591 $this->outputHeader();
592
593 $out = $this->getOutput();
594
595 if ( $this->isCached() && !$this->isCacheable() ) {
596 $out->addWikiMsg( 'querypage-disabled' );
597 return;
598 }
599
600 $out->setSyndicated( $this->isSyndicated() );
601
602 if ( $this->limit == 0 && $this->offset == 0 ) {
603 list( $this->limit, $this->offset ) = $this->getLimitOffset();
604 }
605 $dbLimit = $this->getDBLimit( $this->limit, $this->offset );
606 // @todo Use doQuery()
607 if ( !$this->isCached() ) {
608 # select one extra row for navigation
609 $res = $this->reallyDoQuery( $dbLimit, $this->offset );
610 } else {
611 # Get the cached result, select one extra row for navigation
612 $res = $this->fetchFromCache( $dbLimit, $this->offset );
613 if ( !$this->listoutput ) {
614 # Fetch the timestamp of this update
615 $ts = $this->getCachedTimestamp();
616 $lang = $this->getLanguage();
617 $maxResults = $lang->formatNum( $this->getConfig()->get( 'QueryCacheLimit' ) );
618
619 if ( $ts ) {
620 $updated = $lang->userTimeAndDate( $ts, $user );
621 $updateddate = $lang->userDate( $ts, $user );
622 $updatedtime = $lang->userTime( $ts, $user );
623 $out->addMeta( 'Data-Cache-Time', $ts );
624 $out->addJsConfigVars( 'dataCacheTime', $ts );
625 $out->addWikiMsg( 'perfcachedts', $updated, $updateddate, $updatedtime, $maxResults );
626 } else {
627 $out->addWikiMsg( 'perfcached', $maxResults );
628 }
629
630 # If updates on this page have been disabled, let the user know
631 # that the data set won't be refreshed for now
632 if ( is_array( $this->getConfig()->get( 'DisableQueryPageUpdate' ) )
633 && in_array( $this->getName(), $this->getConfig()->get( 'DisableQueryPageUpdate' ) )
634 ) {
635 $out->wrapWikiMsg(
636 "<div class=\"mw-querypage-no-updates\">\n$1\n</div>",
637 'querypage-no-updates'
638 );
639 }
640 }
641 }
642
643 $this->numRows = $res->numRows();
644
645 $dbr = $this->getRecacheDB();
646 $this->preprocessResults( $dbr, $res );
647
648 $out->addHTML( Xml::openElement( 'div', [ 'class' => 'mw-spcontent' ] ) );
649
650 # Top header and navigation
651 if ( $this->shownavigation ) {
652 $out->addHTML( $this->getPageHeader() );
653 if ( $this->numRows > 0 ) {
654 $out->addHTML( $this->msg( 'showingresultsinrange' )->numParams(
655 min( $this->numRows, $this->limit ), # do not show the one extra row, if exist
656 $this->offset + 1, ( min( $this->numRows, $this->limit ) + $this->offset ) )->parseAsBlock() );
657 # Disable the "next" link when we reach the end
658 $miserMaxResults = $this->getConfig()->get( 'MiserMode' )
659 && ( $this->offset + $this->limit >= $this->getMaxResults() );
660 $atEnd = ( $this->numRows <= $this->limit ) || $miserMaxResults;
661 $paging = $this->buildPrevNextNavigation( $this->offset,
662 $this->limit, $this->linkParameters(), $atEnd, $par );
663 $out->addHTML( '<p>' . $paging . '</p>' );
664 } else {
665 # No results to show, so don't bother with "showing X of Y" etc.
666 # -- just let the user know and give up now
667 $this->showEmptyText();
668 $out->addHTML( Xml::closeElement( 'div' ) );
669 return;
670 }
671 }
672
673 # The actual results; specialist subclasses will want to handle this
674 # with more than a straight list, so we hand them the info, plus
675 # an OutputPage, and let them get on with it
676 $this->outputResults( $out,
677 $this->getSkin(),
678 $dbr, # Should use a ResultWrapper for this
679 $res,
680 min( $this->numRows, $this->limit ), # do not format the one extra row, if exist
681 $this->offset );
682
683 # Repeat the paging links at the bottom
684 if ( $this->shownavigation ) {
685 $out->addHTML( '<p>' . $paging . '</p>' );
686 }
687
688 $out->addHTML( Xml::closeElement( 'div' ) );
689 }
690
702 protected function outputResults( $out, $skin, $dbr, $res, $num, $offset ) {
703 if ( $num > 0 ) {
704 $html = [];
705 if ( !$this->listoutput ) {
706 $html[] = $this->openList( $offset );
707 }
708
709 # $res might contain the whole 1,000 rows, so we read up to
710 # $num [should update this to use a Pager]
711 for ( $i = 0; $i < $num && $row = $res->fetchObject(); $i++ ) {
712 $line = $this->formatResult( $skin, $row );
713 if ( $line ) {
714 $html[] = $this->listoutput
715 ? $line
716 : "<li>{$line}</li>\n";
717 }
718 }
719
720 # Flush the final result
721 if ( $this->tryLastResult() ) {
722 $row = null;
723 $line = $this->formatResult( $skin, $row );
724 if ( $line ) {
725 $html[] = $this->listoutput
726 ? $line
727 : "<li>{$line}</li>\n";
728 }
729 }
730
731 if ( !$this->listoutput ) {
732 $html[] = $this->closeList();
733 }
734
735 $html = $this->listoutput
736 ? MediaWikiServices::getInstance()->getContentLanguage()->listToText( $html )
737 : implode( '', $html );
738
739 $out->addHTML( $html );
740 }
741 }
742
747 function openList( $offset ) {
748 return "\n<ol start='" . ( $offset + 1 ) . "' class='special'>\n";
749 }
750
754 function closeList() {
755 return "</ol>\n";
756 }
757
763 function preprocessResults( $db, $res ) {
764 }
765
776 protected function executeLBFromResultWrapper( IResultWrapper $res, $ns = null ) {
777 if ( !$res->numRows() ) {
778 return;
779 }
780
781 $batch = new LinkBatch;
782 foreach ( $res as $row ) {
783 $batch->add( $ns ?? $row->namespace, $row->title );
784 }
785 $batch->execute();
786
787 $res->seek( 0 );
788 }
789}
and that you know you can do these things To protect your we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights These restrictions translate to certain responsibilities for you if you distribute copies of the or if you modify it For if you distribute copies of such a whether gratis or for a you must give the recipients all the rights that you have You must make sure that receive or can get the source code And you must show them these terms so they know their rights We protect your rights with two and(2) offer you this license which gives you legal permission to copy
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings,...
Definition Setup.php:123
$line
Definition cdb.php:59
Class representing a list of titles The execute() method checks them all for existence and adds them ...
Definition LinkBatch.php:34
add( $ns, $dbkey)
Definition LinkBatch.php:83
MediaWiki exception.
MediaWikiServices is the service locator for the application scope of MediaWiki.
This is a class for doing query pages; since they're almost all the same, we factor out some of the f...
Definition QueryPage.php:35
isExpensive()
Is this query expensive (for some definition of expensive)? Then we don't let it run in miser mode.
linkParameters()
If using extra form wheely-dealies, return a set of parameters here as an associative array.
getMaxResults()
Get max number of results we can return in miser mode.
doQuery( $offset=false, $limit=false)
Somewhat deprecated, you probably want to be using execute()
executeLBFromResultWrapper(IResultWrapper $res, $ns=null)
Creates a new LinkBatch object, adds all pages from the passed ResultWrapper (MUST include title and ...
setListoutput( $bool)
A mutator for $this->listoutput;.
recache( $limit, $ignoreErrors=true)
Clear the cache and save new results.
tryLastResult()
Some special pages (for example SpecialListusers used to) might not return the current object formatt...
fetchFromCache( $limit, $offset=false)
Fetch the query results from the query cache.
int $offset
The offset and limit in use, as passed to the query() function.
Definition QueryPage.php:40
outputResults( $out, $skin, $dbr, $res, $num, $offset)
Format and output report results using the given information plus OutputPage.
isCached()
Whether or not the output of the page in question is retrieved from the database cache.
sortDescending()
Override to sort by increasing values.
formatResult( $skin, $result)
Formats the results of the query for display.
isSyndicated()
Sometime we don't want to build rss / atom feeds.
getCachedTimestamp()
string null $cachedTimestamp
Definition QueryPage.php:57
static getPages()
Get a list of query page classes and their associated special pages, for periodic updates.
Definition QueryPage.php:73
bool $shownavigation
Whether to show prev/next links.
Definition QueryPage.php:62
reallyDoQuery( $limit, $offset=false)
Run the query and return the result.
isCacheable()
Is the output of this query cacheable? Non-cacheable expensive pages will be disabled in miser mode a...
getOrderFields()
Subclasses return an array of fields to order by here.
showEmptyText()
Outputs some kind of an informative message (via OutputPage) to let the user know that the query retu...
usesTimestamps()
Does this query return timestamps rather than integers in its 'value' field? If true,...
getCacheOrderFields()
Return the order fields for fetchFromCache.
getQueryInfo()
Subclasses return an SQL query here, formatted as an array with the following keys: tables => Table(s...
openList( $offset)
getDBLimit( $uiLimit, $uiOffset)
What is limit to fetch from DB.
int $numRows
The number of rows returned by the query.
Definition QueryPage.php:52
preprocessResults( $db, $res)
Do any necessary preprocessing of the result object.
getSQL()
For back-compat, subclasses may return a raw SQL query here, as a string.
getPageHeader()
The content returned by this function will be output before any result.
bool $listoutput
Whether or not we want plain listoutput rather than an ordered list.
Definition QueryPage.php:37
execute( $par)
This is the actual workhorse.
getLimitOffset()
Returns limit and offset, as returned by $this->getRequest()->getLimitOffset().
getRecacheDB()
Get a DB connection to be used for slow recache queries.
Parent class for all special pages.
outputHeader( $summaryMessageKey='')
Outputs a summary message on top of special pages Per default the message key is the canonical name o...
getName()
Get the name of this Special Page.
setHeaders()
Sets headers - this should be called from the execute() method of all derived classes!
getOutput()
Get the OutputPage being used for this instance.
getUser()
Shortcut to get the User executing this instance.
buildPrevNextNavigation( $offset, $limit, array $query=[], $atend=false, $subpage=false)
Generate (prev x| next x) (20|50|100...) type links for paging.
getSkin()
Shortcut to get the skin being used for this instance.
msg( $key)
Wrapper around wfMessage that sets the current context.
getConfig()
Shortcut to get main config object.
getRequest()
Get the WebRequest being used for this instance.
displayRestrictionError()
Output an error message telling the user what access level they have to have.
getLanguage()
Shortcut to get user's language.
userCanExecute(User $user)
Checks if the given user (identified by an object) can execute this special page (as defined by $mRes...
Database error base class.
Definition DBError.php:30
$res
Definition database.txt:21
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition deferred.txt:11
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
Definition hooks.txt:855
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition hooks.txt:1999
this hook is for auditing only RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist & $tables
Definition hooks.txt:996
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses & $html
Definition hooks.txt:2011
null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition hooks.txt:1617
returning false will NOT prevent logging $e
Definition hooks.txt:2175
Basic database interface for live and lazy-loaded relation database handles.
Definition IDatabase.php:38
delete( $table, $conds, $fname=__METHOD__)
DELETE query wrapper.
timestamp( $ts=0)
Convert a timestamp in one of the formats accepted by wfTimestamp() to the format used for inserting ...
insert( $table, $a, $fname=__METHOD__, $options=[])
INSERT wrapper, inserts an array into a table.
Result wrapper for grabbing data queried from an IDatabase object.
$batch
Definition linkcache.txt:23
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
const DB_REPLICA
Definition defines.php:25
const DB_MASTER
Definition defines.php:26
if(!isset( $args[0])) $lang