MediaWiki REL1_32
IndexPager.php
Go to the documentation of this file.
1<?php
26
69abstract class IndexPager extends ContextSource implements Pager {
75 const DIR_ASCENDING = false;
76 const DIR_DESCENDING = true;
77
78 public $mRequest;
79 public $mLimitsShown = [ 20, 50, 100, 250, 500 ];
80 public $mDefaultLimit = 50;
82 public $mQueryDone = false;
84 public $mDb;
86
91 protected $mIndexField;
99 protected $mOrderType;
113
115 public $mIsFirst;
116 public $mIsLast;
117
119
123 protected $mIncludeOffset = false;
124
130 public $mResult;
131
132 public function __construct( IContextSource $context = null ) {
133 if ( $context ) {
134 $this->setContext( $context );
135 }
136
137 $this->mRequest = $this->getRequest();
138
139 # NB: the offset is quoted, not validated. It is treated as an
140 # arbitrary string to support the widest variety of index types. Be
141 # careful outputting it into HTML!
142 $this->mOffset = $this->mRequest->getText( 'offset' );
143
144 # Use consistent behavior for the limit options
145 $this->mDefaultLimit = $this->getUser()->getIntOption( 'rclimit' );
146 if ( !$this->mLimit ) {
147 // Don't override if a subclass calls $this->setLimit() in its constructor.
148 list( $this->mLimit, /* $offset */ ) = $this->mRequest->getLimitOffset();
149 }
150
151 $this->mIsBackwards = ( $this->mRequest->getVal( 'dir' ) == 'prev' );
152 # Let the subclass set the DB here; otherwise use a replica DB for the current wiki
153 $this->mDb = $this->mDb ?: wfGetDB( DB_REPLICA );
154
155 $index = $this->getIndexField(); // column to sort on
156 $extraSort = $this->getExtraSortFields(); // extra columns to sort on for query planning
157 $order = $this->mRequest->getVal( 'order' );
158 if ( is_array( $index ) && isset( $index[$order] ) ) {
159 $this->mOrderType = $order;
160 $this->mIndexField = $index[$order];
161 $this->mExtraSortFields = isset( $extraSort[$order] )
162 ? (array)$extraSort[$order]
163 : [];
164 } elseif ( is_array( $index ) ) {
165 # First element is the default
166 $this->mIndexField = reset( $index );
167 $this->mOrderType = key( $index );
168 $this->mExtraSortFields = isset( $extraSort[$this->mOrderType] )
169 ? (array)$extraSort[$this->mOrderType]
170 : [];
171 } else {
172 # $index is not an array
173 $this->mOrderType = null;
174 $this->mIndexField = $index;
175 $this->mExtraSortFields = (array)$extraSort;
176 }
177
178 if ( !isset( $this->mDefaultDirection ) ) {
179 $dir = $this->getDefaultDirections();
180 $this->mDefaultDirection = is_array( $dir )
181 ? $dir[$this->mOrderType]
182 : $dir;
183 }
184 }
185
191 public function getDatabase() {
192 return $this->mDb;
193 }
194
200 public function doQuery() {
201 # Use the child class name for profiling
202 $fname = __METHOD__ . ' (' . static::class . ')';
203 $section = Profiler::instance()->scopedProfileIn( $fname );
204
205 // @todo This should probably compare to DIR_DESCENDING and DIR_ASCENDING constants
206 $descending = ( $this->mIsBackwards == $this->mDefaultDirection );
207 # Plus an extra row so that we can tell the "next" link should be shown
208 $queryLimit = $this->mLimit + 1;
209
210 if ( $this->mOffset == '' ) {
211 $isFirst = true;
212 } else {
213 // If there's an offset, we may or may not be at the first entry.
214 // The only way to tell is to run the query in the opposite
215 // direction see if we get a row.
216 $oldIncludeOffset = $this->mIncludeOffset;
217 $this->mIncludeOffset = !$this->mIncludeOffset;
218 $isFirst = !$this->reallyDoQuery( $this->mOffset, 1, !$descending )->numRows();
219 $this->mIncludeOffset = $oldIncludeOffset;
220 }
221
222 $this->mResult = $this->reallyDoQuery(
223 $this->mOffset,
224 $queryLimit,
225 $descending
226 );
227
228 $this->extractResultInfo( $isFirst, $queryLimit, $this->mResult );
229 $this->mQueryDone = true;
230
231 $this->preprocessResults( $this->mResult );
232 $this->mResult->rewind(); // Paranoia
233 }
234
238 function getResult() {
239 return $this->mResult;
240 }
241
247 function setOffset( $offset ) {
248 $this->mOffset = $offset;
249 }
250
258 function setLimit( $limit ) {
259 $limit = (int)$limit;
260 // WebRequest::getLimitOffset() puts a cap of 5000, so do same here.
261 if ( $limit > 5000 ) {
262 $limit = 5000;
263 }
264 if ( $limit > 0 ) {
265 $this->mLimit = $limit;
266 }
267 }
268
274 function getLimit() {
275 return $this->mLimit;
276 }
277
285 public function setIncludeOffset( $include ) {
286 $this->mIncludeOffset = $include;
287 }
288
298 function extractResultInfo( $isFirst, $limit, IResultWrapper $res ) {
299 $numRows = $res->numRows();
300 if ( $numRows ) {
301 # Remove any table prefix from index field
302 $parts = explode( '.', $this->mIndexField );
303 $indexColumn = end( $parts );
304
305 $row = $res->fetchRow();
306 $firstIndex = $row[$indexColumn];
307
308 # Discard the extra result row if there is one
309 if ( $numRows > $this->mLimit && $numRows > 1 ) {
310 $res->seek( $numRows - 1 );
311 $this->mPastTheEndRow = $res->fetchObject();
312 $this->mPastTheEndIndex = $this->mPastTheEndRow->$indexColumn;
313 $res->seek( $numRows - 2 );
314 $row = $res->fetchRow();
315 $lastIndex = $row[$indexColumn];
316 } else {
317 $this->mPastTheEndRow = null;
318 # Setting indexes to an empty string means that they will be
319 # omitted if they would otherwise appear in URLs. It just so
320 # happens that this is the right thing to do in the standard
321 # UI, in all the relevant cases.
322 $this->mPastTheEndIndex = '';
323 $res->seek( $numRows - 1 );
324 $row = $res->fetchRow();
325 $lastIndex = $row[$indexColumn];
326 }
327 } else {
328 $firstIndex = '';
329 $lastIndex = '';
330 $this->mPastTheEndRow = null;
331 $this->mPastTheEndIndex = '';
332 }
333
334 if ( $this->mIsBackwards ) {
335 $this->mIsFirst = ( $numRows < $limit );
336 $this->mIsLast = $isFirst;
337 $this->mLastShown = $firstIndex;
338 $this->mFirstShown = $lastIndex;
339 } else {
340 $this->mIsFirst = $isFirst;
341 $this->mIsLast = ( $numRows < $limit );
342 $this->mLastShown = $lastIndex;
343 $this->mFirstShown = $firstIndex;
344 }
345 }
346
352 function getSqlComment() {
353 return static::class;
354 }
355
365 public function reallyDoQuery( $offset, $limit, $descending ) {
366 list( $tables, $fields, $conds, $fname, $options, $join_conds ) =
367 $this->buildQueryInfo( $offset, $limit, $descending );
368
369 return $this->mDb->select( $tables, $fields, $conds, $fname, $options, $join_conds );
370 }
371
380 protected function buildQueryInfo( $offset, $limit, $descending ) {
381 $fname = __METHOD__ . ' (' . $this->getSqlComment() . ')';
382 $info = $this->getQueryInfo();
383 $tables = $info['tables'];
384 $fields = $info['fields'];
385 $conds = $info['conds'] ?? [];
386 $options = $info['options'] ?? [];
387 $join_conds = $info['join_conds'] ?? [];
388 $sortColumns = array_merge( [ $this->mIndexField ], $this->mExtraSortFields );
389 if ( $descending ) {
390 $options['ORDER BY'] = $sortColumns;
391 $operator = $this->mIncludeOffset ? '>=' : '>';
392 } else {
393 $orderBy = [];
394 foreach ( $sortColumns as $col ) {
395 $orderBy[] = $col . ' DESC';
396 }
397 $options['ORDER BY'] = $orderBy;
398 $operator = $this->mIncludeOffset ? '<=' : '<';
399 }
400 if ( $offset != '' ) {
401 $conds[] = $this->mIndexField . $operator . $this->mDb->addQuotes( $offset );
402 }
403 $options['LIMIT'] = intval( $limit );
404 return [ $tables, $fields, $conds, $fname, $options, $join_conds ];
405 }
406
412 protected function preprocessResults( $result ) {
413 }
414
421 public function getBody() {
422 if ( !$this->mQueryDone ) {
423 $this->doQuery();
424 }
425
426 if ( $this->mResult->numRows() ) {
427 # Do any special query batches before display
428 $this->doBatchLookups();
429 }
430
431 # Don't use any extra rows returned by the query
432 $numRows = min( $this->mResult->numRows(), $this->mLimit );
433
434 $s = $this->getStartBody();
435 if ( $numRows ) {
436 if ( $this->mIsBackwards ) {
437 for ( $i = $numRows - 1; $i >= 0; $i-- ) {
438 $this->mResult->seek( $i );
439 $row = $this->mResult->fetchObject();
440 $s .= $this->formatRow( $row );
441 }
442 } else {
443 $this->mResult->seek( 0 );
444 for ( $i = 0; $i < $numRows; $i++ ) {
445 $row = $this->mResult->fetchObject();
446 $s .= $this->formatRow( $row );
447 }
448 }
449 } else {
450 $s .= $this->getEmptyBody();
451 }
452 $s .= $this->getEndBody();
453 return $s;
454 }
455
465 function makeLink( $text, array $query = null, $type = null ) {
466 if ( $query === null ) {
467 return $text;
468 }
469
470 $attrs = [];
471 if ( in_array( $type, [ 'prev', 'next' ] ) ) {
472 $attrs['rel'] = $type;
473 }
474
475 if ( in_array( $type, [ 'asc', 'desc' ] ) ) {
476 $attrs['title'] = $this->msg( $type == 'asc' ? 'sort-ascending' : 'sort-descending' )->text();
477 }
478
479 if ( $type ) {
480 $attrs['class'] = "mw-{$type}link";
481 }
482
483 return Linker::linkKnown(
484 $this->getTitle(),
485 $text,
486 $attrs,
487 $query + $this->getDefaultQuery()
488 );
489 }
490
498 protected function doBatchLookups() {
499 }
500
507 protected function getStartBody() {
508 return '';
509 }
510
516 protected function getEndBody() {
517 return '';
518 }
519
526 protected function getEmptyBody() {
527 return '';
528 }
529
537 function getDefaultQuery() {
538 if ( !isset( $this->mDefaultQuery ) ) {
539 $this->mDefaultQuery = $this->getRequest()->getQueryValues();
540 unset( $this->mDefaultQuery['title'] );
541 unset( $this->mDefaultQuery['dir'] );
542 unset( $this->mDefaultQuery['offset'] );
543 unset( $this->mDefaultQuery['limit'] );
544 unset( $this->mDefaultQuery['order'] );
545 unset( $this->mDefaultQuery['month'] );
546 unset( $this->mDefaultQuery['year'] );
547 }
549 }
550
556 function getNumRows() {
557 if ( !$this->mQueryDone ) {
558 $this->doQuery();
559 }
560 return $this->mResult->numRows();
561 }
562
568 function getPagingQueries() {
569 if ( !$this->mQueryDone ) {
570 $this->doQuery();
571 }
572
573 # Don't announce the limit everywhere if it's the default
574 $urlLimit = $this->mLimit == $this->mDefaultLimit ? null : $this->mLimit;
575
576 if ( $this->mIsFirst ) {
577 $prev = false;
578 $first = false;
579 } else {
580 $prev = [
581 'dir' => 'prev',
582 'offset' => $this->mFirstShown,
583 'limit' => $urlLimit
584 ];
585 $first = [ 'limit' => $urlLimit ];
586 }
587 if ( $this->mIsLast ) {
588 $next = false;
589 $last = false;
590 } else {
591 $next = [ 'offset' => $this->mLastShown, 'limit' => $urlLimit ];
592 $last = [ 'dir' => 'prev', 'limit' => $urlLimit ];
593 }
594 return [
595 'prev' => $prev,
596 'next' => $next,
597 'first' => $first,
598 'last' => $last
599 ];
600 }
601
608 if ( !$this->mQueryDone ) {
609 $this->doQuery();
610 }
611 // Hide navigation by default if there is nothing to page
612 return !( $this->mIsFirst && $this->mIsLast );
613 }
614
625 function getPagingLinks( $linkTexts, $disabledTexts = [] ) {
626 $queries = $this->getPagingQueries();
627 $links = [];
628
629 foreach ( $queries as $type => $query ) {
630 if ( $query !== false ) {
631 $links[$type] = $this->makeLink(
632 $linkTexts[$type],
634 $type
635 );
636 } elseif ( isset( $disabledTexts[$type] ) ) {
637 $links[$type] = $disabledTexts[$type];
638 } else {
639 $links[$type] = $linkTexts[$type];
640 }
641 }
642
643 return $links;
644 }
645
646 function getLimitLinks() {
647 $links = [];
648 if ( $this->mIsBackwards ) {
649 $offset = $this->mPastTheEndIndex;
650 } else {
651 $offset = $this->mOffset;
652 }
653 foreach ( $this->mLimitsShown as $limit ) {
654 $links[] = $this->makeLink(
655 $this->getLanguage()->formatNum( $limit ),
656 [ 'offset' => $offset, 'limit' => $limit ],
657 'num'
658 );
659 }
660 return $links;
661 }
662
671 abstract function formatRow( $row );
672
685 abstract function getQueryInfo();
686
699 abstract function getIndexField();
700
717 protected function getExtraSortFields() {
718 return [];
719 }
720
740 protected function getDefaultDirections() {
741 return self::DIR_ASCENDING;
742 }
743}
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
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:121
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.
$mIndexField
The index to actually be used for ordering.
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
Constants for the $mDefaultDirection field.
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
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.
$mIsFirst
True if the current result set is the first one.
buildQueryInfo( $offset, $limit, $descending)
Build variables to use by the database wrapper.
getPagingLinks( $linkTexts, $disabledTexts=[])
Get paging links.
reallyDoQuery( $offset, $limit, $descending)
Do a query with specified parameters, rather than using the object context.
$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.
getStartBody()
Hook into getBody(), allows text to be inserted at the start.
getDatabase()
Get the Database object in use.
formatRow( $row)
Abstract formatting function.
$mIncludeOffset
Whether to include the offset in the query.
getBody()
Get the formatted result list.
$mDefaultDirection
$mDefaultDirection gives the direction to use when sorting results: DIR_ASCENDING or DIR_DESCENDING.
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".
const DIR_DESCENDING
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.
$mExtraSortFields
An array of secondary columns to order by.
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)
static linkKnown( $target, $html=null, $customAttribs=[], $query=[], $options=[ 'known'])
Identical to link(), except $options defaults to 'known'.
Definition Linker.php:141
$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:2050
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:2214
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:1035
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:1656
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:3107
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