MediaWiki REL1_33
IndexPager.php
Go to the documentation of this file.
1<?php
26
69abstract class IndexPager extends ContextSource implements Pager {
71 const DIR_ASCENDING = false;
73 const DIR_DESCENDING = true;
74
76 const QUERY_ASCENDING = true;
78 const QUERY_DESCENDING = false;
79
81 public $mRequest;
83 public $mLimitsShown = [ 20, 50, 100, 250, 500 ];
85 public $mDefaultLimit = 50;
87 public $mOffset;
89 public $mLimit;
91 public $mQueryDone = false;
93 public $mDb;
96
102 protected $mIndexField;
112 protected $mOrderType;
128
130 public $mIsFirst;
132 public $mIsLast;
133
135 protected $mLastShown;
137 protected $mFirstShown;
141 protected $mDefaultQuery;
144
149 protected $mIncludeOffset = false;
150
156 public $mResult;
157
158 public function __construct( IContextSource $context = null ) {
159 if ( $context ) {
160 $this->setContext( $context );
161 }
162
163 $this->mRequest = $this->getRequest();
164
165 # NB: the offset is quoted, not validated. It is treated as an
166 # arbitrary string to support the widest variety of index types. Be
167 # careful outputting it into HTML!
168 $this->mOffset = $this->mRequest->getText( 'offset' );
169
170 # Use consistent behavior for the limit options
171 $this->mDefaultLimit = $this->getUser()->getIntOption( 'rclimit' );
172 if ( !$this->mLimit ) {
173 // Don't override if a subclass calls $this->setLimit() in its constructor.
174 list( $this->mLimit, /* $offset */ ) = $this->mRequest->getLimitOffset();
175 }
176
177 $this->mIsBackwards = ( $this->mRequest->getVal( 'dir' ) == 'prev' );
178 # Let the subclass set the DB here; otherwise use a replica DB for the current wiki
179 $this->mDb = $this->mDb ?: wfGetDB( DB_REPLICA );
180
181 $index = $this->getIndexField(); // column to sort on
182 $extraSort = $this->getExtraSortFields(); // extra columns to sort on for query planning
183 $order = $this->mRequest->getVal( 'order' );
184 if ( is_array( $index ) && isset( $index[$order] ) ) {
185 $this->mOrderType = $order;
186 $this->mIndexField = $index[$order];
187 $this->mExtraSortFields = isset( $extraSort[$order] )
188 ? (array)$extraSort[$order]
189 : [];
190 } elseif ( is_array( $index ) ) {
191 # First element is the default
192 $this->mIndexField = reset( $index );
193 $this->mOrderType = key( $index );
194 $this->mExtraSortFields = isset( $extraSort[$this->mOrderType] )
195 ? (array)$extraSort[$this->mOrderType]
196 : [];
197 } else {
198 # $index is not an array
199 $this->mOrderType = null;
200 $this->mIndexField = $index;
201 $this->mExtraSortFields = (array)$extraSort;
202 }
203
204 if ( !isset( $this->mDefaultDirection ) ) {
205 $dir = $this->getDefaultDirections();
206 $this->mDefaultDirection = is_array( $dir )
207 ? $dir[$this->mOrderType]
208 : $dir;
209 }
210 }
211
217 public function getDatabase() {
218 return $this->mDb;
219 }
220
226 public function doQuery() {
227 # Use the child class name for profiling
228 $fname = __METHOD__ . ' (' . static::class . ')';
230 $section = Profiler::instance()->scopedProfileIn( $fname );
231
232 $defaultOrder = ( $this->mDefaultDirection === self::DIR_ASCENDING )
233 ? self::QUERY_ASCENDING
235 $order = $this->mIsBackwards ? self::oppositeOrder( $defaultOrder ) : $defaultOrder;
236
237 # Plus an extra row so that we can tell the "next" link should be shown
238 $queryLimit = $this->mLimit + 1;
239
240 if ( $this->mOffset == '' ) {
241 $isFirst = true;
242 } else {
243 // If there's an offset, we may or may not be at the first entry.
244 // The only way to tell is to run the query in the opposite
245 // direction see if we get a row.
246 $oldIncludeOffset = $this->mIncludeOffset;
247 $this->mIncludeOffset = !$this->mIncludeOffset;
248 $oppositeOrder = self::oppositeOrder( $order );
249 $isFirst = !$this->reallyDoQuery( $this->mOffset, 1, $oppositeOrder )->numRows();
250 $this->mIncludeOffset = $oldIncludeOffset;
251 }
252
253 $this->mResult = $this->reallyDoQuery(
254 $this->mOffset,
255 $queryLimit,
256 $order
257 );
258
259 $this->extractResultInfo( $isFirst, $queryLimit, $this->mResult );
260 $this->mQueryDone = true;
261
262 $this->preprocessResults( $this->mResult );
263 $this->mResult->rewind(); // Paranoia
264 }
265
270 final protected static function oppositeOrder( $order ) {
271 return ( $order === self::QUERY_ASCENDING )
274 }
275
279 function getResult() {
280 return $this->mResult;
281 }
282
288 function setOffset( $offset ) {
289 $this->mOffset = $offset;
290 }
291
299 function setLimit( $limit ) {
300 $limit = (int)$limit;
301 // WebRequest::getLimitOffset() puts a cap of 5000, so do same here.
302 if ( $limit > 5000 ) {
303 $limit = 5000;
304 }
305 if ( $limit > 0 ) {
306 $this->mLimit = $limit;
307 }
308 }
309
315 function getLimit() {
316 return $this->mLimit;
317 }
318
326 public function setIncludeOffset( $include ) {
327 $this->mIncludeOffset = $include;
328 }
329
339 function extractResultInfo( $isFirst, $limit, IResultWrapper $res ) {
340 $numRows = $res->numRows();
341 if ( $numRows ) {
342 # Remove any table prefix from index field
343 $parts = explode( '.', $this->mIndexField );
344 $indexColumn = end( $parts );
345
346 $row = $res->fetchRow();
347 $firstIndex = $row[$indexColumn];
348
349 # Discard the extra result row if there is one
350 if ( $numRows > $this->mLimit && $numRows > 1 ) {
351 $res->seek( $numRows - 1 );
352 $this->mPastTheEndRow = $res->fetchObject();
353 $this->mPastTheEndIndex = $this->mPastTheEndRow->$indexColumn;
354 $res->seek( $numRows - 2 );
355 $row = $res->fetchRow();
356 $lastIndex = $row[$indexColumn];
357 } else {
358 $this->mPastTheEndRow = null;
359 # Setting indexes to an empty string means that they will be
360 # omitted if they would otherwise appear in URLs. It just so
361 # happens that this is the right thing to do in the standard
362 # UI, in all the relevant cases.
363 $this->mPastTheEndIndex = '';
364 $res->seek( $numRows - 1 );
365 $row = $res->fetchRow();
366 $lastIndex = $row[$indexColumn];
367 }
368 } else {
369 $firstIndex = '';
370 $lastIndex = '';
371 $this->mPastTheEndRow = null;
372 $this->mPastTheEndIndex = '';
373 }
374
375 if ( $this->mIsBackwards ) {
376 $this->mIsFirst = ( $numRows < $limit );
377 $this->mIsLast = $isFirst;
378 $this->mLastShown = $firstIndex;
379 $this->mFirstShown = $lastIndex;
380 } else {
381 $this->mIsFirst = $isFirst;
382 $this->mIsLast = ( $numRows < $limit );
383 $this->mLastShown = $lastIndex;
384 $this->mFirstShown = $firstIndex;
385 }
386 }
387
393 function getSqlComment() {
394 return static::class;
395 }
396
407 public function reallyDoQuery( $offset, $limit, $order ) {
408 list( $tables, $fields, $conds, $fname, $options, $join_conds ) =
409 $this->buildQueryInfo( $offset, $limit, $order );
410
411 return $this->mDb->select( $tables, $fields, $conds, $fname, $options, $join_conds );
412 }
413
424 protected function buildQueryInfo( $offset, $limit, $order ) {
425 $fname = __METHOD__ . ' (' . $this->getSqlComment() . ')';
426 $info = $this->getQueryInfo();
427 $tables = $info['tables'];
428 $fields = $info['fields'];
429 $conds = $info['conds'] ?? [];
430 $options = $info['options'] ?? [];
431 $join_conds = $info['join_conds'] ?? [];
432 $sortColumns = array_merge( [ $this->mIndexField ], $this->mExtraSortFields );
433 if ( $order === self::QUERY_ASCENDING ) {
434 $options['ORDER BY'] = $sortColumns;
435 $operator = $this->mIncludeOffset ? '>=' : '>';
436 } else {
437 $orderBy = [];
438 foreach ( $sortColumns as $col ) {
439 $orderBy[] = $col . ' DESC';
440 }
441 $options['ORDER BY'] = $orderBy;
442 $operator = $this->mIncludeOffset ? '<=' : '<';
443 }
444 if ( $offset != '' ) {
445 $conds[] = $this->mIndexField . $operator . $this->mDb->addQuotes( $offset );
446 }
447 $options['LIMIT'] = intval( $limit );
448 return [ $tables, $fields, $conds, $fname, $options, $join_conds ];
449 }
450
456 protected function preprocessResults( $result ) {
457 }
458
465 public function getBody() {
466 if ( !$this->mQueryDone ) {
467 $this->doQuery();
468 }
469
470 if ( $this->mResult->numRows() ) {
471 # Do any special query batches before display
472 $this->doBatchLookups();
473 }
474
475 # Don't use any extra rows returned by the query
476 $numRows = min( $this->mResult->numRows(), $this->mLimit );
477
478 $s = $this->getStartBody();
479 if ( $numRows ) {
480 if ( $this->mIsBackwards ) {
481 for ( $i = $numRows - 1; $i >= 0; $i-- ) {
482 $this->mResult->seek( $i );
483 $row = $this->mResult->fetchObject();
484 $s .= $this->formatRow( $row );
485 }
486 } else {
487 $this->mResult->seek( 0 );
488 for ( $i = 0; $i < $numRows; $i++ ) {
489 $row = $this->mResult->fetchObject();
490 $s .= $this->formatRow( $row );
491 }
492 }
493 } else {
494 $s .= $this->getEmptyBody();
495 }
496 $s .= $this->getEndBody();
497 return $s;
498 }
499
509 function makeLink( $text, array $query = null, $type = null ) {
510 if ( $query === null ) {
511 return $text;
512 }
513
514 $attrs = [];
515 if ( in_array( $type, [ 'prev', 'next' ] ) ) {
516 $attrs['rel'] = $type;
517 }
518
519 if ( in_array( $type, [ 'asc', 'desc' ] ) ) {
520 $attrs['title'] = $this->msg( $type == 'asc' ? 'sort-ascending' : 'sort-descending' )->text();
521 }
522
523 if ( $type ) {
524 $attrs['class'] = "mw-{$type}link";
525 }
526
527 return Linker::linkKnown(
528 $this->getTitle(),
529 $text,
530 $attrs,
531 $query + $this->getDefaultQuery()
532 );
533 }
534
542 protected function doBatchLookups() {
543 }
544
551 protected function getStartBody() {
552 return '';
553 }
554
560 protected function getEndBody() {
561 return '';
562 }
563
570 protected function getEmptyBody() {
571 return '';
572 }
573
581 function getDefaultQuery() {
582 if ( !isset( $this->mDefaultQuery ) ) {
583 $this->mDefaultQuery = $this->getRequest()->getQueryValues();
584 unset( $this->mDefaultQuery['title'] );
585 unset( $this->mDefaultQuery['dir'] );
586 unset( $this->mDefaultQuery['offset'] );
587 unset( $this->mDefaultQuery['limit'] );
588 unset( $this->mDefaultQuery['order'] );
589 unset( $this->mDefaultQuery['month'] );
590 unset( $this->mDefaultQuery['year'] );
591 }
593 }
594
600 function getNumRows() {
601 if ( !$this->mQueryDone ) {
602 $this->doQuery();
603 }
604 return $this->mResult->numRows();
605 }
606
612 function getPagingQueries() {
613 if ( !$this->mQueryDone ) {
614 $this->doQuery();
615 }
616
617 # Don't announce the limit everywhere if it's the default
618 $urlLimit = $this->mLimit == $this->mDefaultLimit ? null : $this->mLimit;
619
620 if ( $this->mIsFirst ) {
621 $prev = false;
622 $first = false;
623 } else {
624 $prev = [
625 'dir' => 'prev',
626 'offset' => $this->mFirstShown,
627 'limit' => $urlLimit
628 ];
629 $first = [ 'limit' => $urlLimit ];
630 }
631 if ( $this->mIsLast ) {
632 $next = false;
633 $last = false;
634 } else {
635 $next = [ 'offset' => $this->mLastShown, 'limit' => $urlLimit ];
636 $last = [ 'dir' => 'prev', 'limit' => $urlLimit ];
637 }
638 return [
639 'prev' => $prev,
640 'next' => $next,
641 'first' => $first,
642 'last' => $last
643 ];
644 }
645
652 if ( !$this->mQueryDone ) {
653 $this->doQuery();
654 }
655 // Hide navigation by default if there is nothing to page
656 return !( $this->mIsFirst && $this->mIsLast );
657 }
658
669 function getPagingLinks( $linkTexts, $disabledTexts = [] ) {
670 $queries = $this->getPagingQueries();
671 $links = [];
672
673 foreach ( $queries as $type => $query ) {
674 if ( $query !== false ) {
675 $links[$type] = $this->makeLink(
676 $linkTexts[$type],
678 $type
679 );
680 } elseif ( isset( $disabledTexts[$type] ) ) {
681 $links[$type] = $disabledTexts[$type];
682 } else {
683 $links[$type] = $linkTexts[$type];
684 }
685 }
686
687 return $links;
688 }
689
690 function getLimitLinks() {
691 $links = [];
692 if ( $this->mIsBackwards ) {
693 $offset = $this->mPastTheEndIndex;
694 } else {
695 $offset = $this->mOffset;
696 }
697 foreach ( $this->mLimitsShown as $limit ) {
698 $links[] = $this->makeLink(
699 $this->getLanguage()->formatNum( $limit ),
700 [ 'offset' => $offset, 'limit' => $limit ],
701 'num'
702 );
703 }
704 return $links;
705 }
706
715 abstract function formatRow( $row );
716
729 abstract function getQueryInfo();
730
743 abstract function getIndexField();
744
761 protected function getExtraSortFields() {
762 return [];
763 }
764
784 protected function getDefaultDirections() {
785 return self::DIR_ASCENDING;
786 }
787}
This list may contain false positives That usually means there is additional text with links below the first Each row contains links to the first and second as well as the first line of the second redirect text
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.
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings,...
Definition Setup.php:123
The simplest way of implementing IContextSource is to hold a RequestContext as a member variable and ...
msg( $key)
Get a Message object with context set Parameters are the same as wfMessage()
IContextSource $context
setContext(IContextSource $context)
IndexPager is an efficient pager which uses a (roughly unique) index in the data set to implement pag...
getQueryInfo()
This function should be overridden to provide all parameters needed for the main paged query.
getEndBody()
Hook into getBody() for the end of the list.
const QUERY_DESCENDING
Backwards-compatible constant for reallyDoQuery() (do not change)
string[] $mExtraSortFields
An array of secondary columns to order by.
array $mDefaultQuery
int $mLimit
The maximum number of entries to show.
bool $mDefaultDirection
$mDefaultDirection gives the direction to use when sorting results: DIR_ASCENDING or DIR_DESCENDING.
WebRequest $mRequest
getDefaultDirections()
Return the default sorting direction: DIR_ASCENDING or DIR_DESCENDING.
setOffset( $offset)
Set the offset from an other source than the request.
makeLink( $text, array $query=null, $type=null)
Make a self-link.
const DIR_ASCENDING
Backwards-compatible constant for $mDefaultDirection field (do not change)
IResultWrapper $mResult
Result object for the query.
getEmptyBody()
Hook into getBody(), for the bit between the start and the end when there are no rows.
setIncludeOffset( $include)
Set whether a row matching exactly the offset should be also included in the result or not.
IDatabase $mDb
bool $mQueryDone
Whether the listing query completed.
extractResultInfo( $isFirst, $limit, IResultWrapper $res)
Extract some useful data from the result object for use by the navigation bar, put it into $this.
getLimit()
Get the current limit.
getSqlComment()
Get some text to go in brackets in the "function name" part of the SQL comment.
string $mNavigationBar
bool $mIncludeOffset
Whether to include the offset in the query.
static oppositeOrder( $order)
getPagingLinks( $linkTexts, $disabledTexts=[])
Get paging links.
mixed $mOffset
The starting point to enumerate entries.
int[] $mLimitsShown
List of default entry limit options to be presented to clients.
buildQueryInfo( $offset, $limit, $order)
Build variables to use by the database wrapper.
string null $mOrderType
For pages that support multiple types of ordering, which one to use.
getPagingQueries()
Get a URL query array for the prev, next, first and last links.
string $mIndexField
The index to actually be used for ordering.
getStartBody()
Hook into getBody(), allows text to be inserted at the start.
bool $mIsFirst
True if the current result set is the first one.
getDatabase()
Get the Database object in use.
formatRow( $row)
Abstract formatting function.
getBody()
Get the formatted result list.
int $mDefaultLimit
The default entry limit choosen for clients.
doQuery()
Do the query, using information from the object context.
getNumRows()
Get the number of rows in the result set.
isNavigationBarShown()
Returns whether to show the "navigation bar".
mixed $mLastShown
const DIR_DESCENDING
Backwards-compatible constant for $mDefaultDirection field (do not change)
getIndexField()
This function should be overridden to return the name of the index fi- eld.
doBatchLookups()
Called from getBody(), before getStartBody() is called and after doQuery() was called.
stdClass bool null $mPastTheEndRow
Extra row fetched at the end to see if the end was reached.
const QUERY_ASCENDING
Backwards-compatible constant for reallyDoQuery() (do not change)
bool $mIsBackwards
preprocessResults( $result)
Pre-process results; useful for performing batch existence checks, etc.
getExtraSortFields()
This function should be overridden to return the names of secondary columns to order by in addition t...
getDefaultQuery()
Get an array of query parameters that should be put into self-links.
setLimit( $limit)
Set the limit from an other source than the request.
__construct(IContextSource $context=null)
mixed $mPastTheEndIndex
mixed $mFirstShown
reallyDoQuery( $offset, $limit, $order)
Do a query with specified parameters, rather than using the object context.
static linkKnown( $target, $html=null, $customAttribs=[], $query=[], $options=[ 'known'])
Identical to link(), except $options defaults to 'known'.
Definition Linker.php:146
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
$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
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
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message key
Definition hooks.txt:2163
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
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 null
Definition hooks.txt:783
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
usually copyright or history_copyright This message must be in HTML not wikitext if the section is included from a template $section
Definition hooks.txt:3070
Interface for objects which can provide a MediaWiki context on request.
Basic pager interface.
Definition Pager.php:32
Basic database interface for live and lazy-loaded relation database handles.
Definition IDatabase.php:38
Result wrapper for grabbing data queried from an IDatabase object.
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))
$queries
$last
const DB_REPLICA
Definition defines.php:25