MediaWiki REL1_30
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;
83 public $mDb;
85
90 protected $mIndexField;
98 protected $mOrderType;
112
114 public $mIsFirst;
115 public $mIsLast;
116
118
122 protected $mIncludeOffset = false;
123
129 public $mResult;
130
131 public function __construct( IContextSource $context = null ) {
132 if ( $context ) {
133 $this->setContext( $context );
134 }
135
136 $this->mRequest = $this->getRequest();
137
138 # NB: the offset is quoted, not validated. It is treated as an
139 # arbitrary string to support the widest variety of index types. Be
140 # careful outputting it into HTML!
141 $this->mOffset = $this->mRequest->getText( 'offset' );
142
143 # Use consistent behavior for the limit options
144 $this->mDefaultLimit = $this->getUser()->getIntOption( 'rclimit' );
145 if ( !$this->mLimit ) {
146 // Don't override if a subclass calls $this->setLimit() in its constructor.
147 list( $this->mLimit, /* $offset */ ) = $this->mRequest->getLimitOffset();
148 }
149
150 $this->mIsBackwards = ( $this->mRequest->getVal( 'dir' ) == 'prev' );
151 # Let the subclass set the DB here; otherwise use a replica DB for the current wiki
152 $this->mDb = $this->mDb ?: wfGetDB( DB_REPLICA );
153
154 $index = $this->getIndexField(); // column to sort on
155 $extraSort = $this->getExtraSortFields(); // extra columns to sort on for query planning
156 $order = $this->mRequest->getVal( 'order' );
157 if ( is_array( $index ) && isset( $index[$order] ) ) {
158 $this->mOrderType = $order;
159 $this->mIndexField = $index[$order];
160 $this->mExtraSortFields = isset( $extraSort[$order] )
161 ? (array)$extraSort[$order]
162 : [];
163 } elseif ( is_array( $index ) ) {
164 # First element is the default
165 reset( $index );
166 list( $this->mOrderType, $this->mIndexField ) = each( $index );
167 $this->mExtraSortFields = isset( $extraSort[$this->mOrderType] )
168 ? (array)$extraSort[$this->mOrderType]
169 : [];
170 } else {
171 # $index is not an array
172 $this->mOrderType = null;
173 $this->mIndexField = $index;
174 $this->mExtraSortFields = (array)$extraSort;
175 }
176
177 if ( !isset( $this->mDefaultDirection ) ) {
178 $dir = $this->getDefaultDirections();
179 $this->mDefaultDirection = is_array( $dir )
181 : $dir;
182 }
183 }
184
190 public function getDatabase() {
191 return $this->mDb;
192 }
193
199 public function doQuery() {
200 # Use the child class name for profiling
201 $fname = __METHOD__ . ' (' . static::class . ')';
202 $section = Profiler::instance()->scopedProfileIn( $fname );
203
204 // @todo This should probably compare to DIR_DESCENDING and DIR_ASCENDING constants
205 $descending = ( $this->mIsBackwards == $this->mDefaultDirection );
206 # Plus an extra row so that we can tell the "next" link should be shown
207 $queryLimit = $this->mLimit + 1;
208
209 if ( $this->mOffset == '' ) {
210 $isFirst = true;
211 } else {
212 // If there's an offset, we may or may not be at the first entry.
213 // The only way to tell is to run the query in the opposite
214 // direction see if we get a row.
215 $oldIncludeOffset = $this->mIncludeOffset;
216 $this->mIncludeOffset = !$this->mIncludeOffset;
217 $isFirst = !$this->reallyDoQuery( $this->mOffset, 1, !$descending )->numRows();
218 $this->mIncludeOffset = $oldIncludeOffset;
219 }
220
221 $this->mResult = $this->reallyDoQuery(
222 $this->mOffset,
223 $queryLimit,
224 $descending
225 );
226
227 $this->extractResultInfo( $isFirst, $queryLimit, $this->mResult );
228 $this->mQueryDone = true;
229
230 $this->preprocessResults( $this->mResult );
231 $this->mResult->rewind(); // Paranoia
232 }
233
237 function getResult() {
238 return $this->mResult;
239 }
240
246 function setOffset( $offset ) {
247 $this->mOffset = $offset;
248 }
249
257 function setLimit( $limit ) {
258 $limit = (int)$limit;
259 // WebRequest::getLimitOffset() puts a cap of 5000, so do same here.
260 if ( $limit > 5000 ) {
261 $limit = 5000;
262 }
263 if ( $limit > 0 ) {
264 $this->mLimit = $limit;
265 }
266 }
267
273 function getLimit() {
274 return $this->mLimit;
275 }
276
284 public function setIncludeOffset( $include ) {
285 $this->mIncludeOffset = $include;
286 }
287
297 function extractResultInfo( $isFirst, $limit, ResultWrapper $res ) {
298 $numRows = $res->numRows();
299 if ( $numRows ) {
300 # Remove any table prefix from index field
301 $parts = explode( '.', $this->mIndexField );
302 $indexColumn = end( $parts );
303
304 $row = $res->fetchRow();
305 $firstIndex = $row[$indexColumn];
306
307 # Discard the extra result row if there is one
308 if ( $numRows > $this->mLimit && $numRows > 1 ) {
309 $res->seek( $numRows - 1 );
310 $this->mPastTheEndRow = $res->fetchObject();
311 $this->mPastTheEndIndex = $this->mPastTheEndRow->$indexColumn;
312 $res->seek( $numRows - 2 );
313 $row = $res->fetchRow();
314 $lastIndex = $row[$indexColumn];
315 } else {
316 $this->mPastTheEndRow = null;
317 # Setting indexes to an empty string means that they will be
318 # omitted if they would otherwise appear in URLs. It just so
319 # happens that this is the right thing to do in the standard
320 # UI, in all the relevant cases.
321 $this->mPastTheEndIndex = '';
322 $res->seek( $numRows - 1 );
323 $row = $res->fetchRow();
324 $lastIndex = $row[$indexColumn];
325 }
326 } else {
327 $firstIndex = '';
328 $lastIndex = '';
329 $this->mPastTheEndRow = null;
330 $this->mPastTheEndIndex = '';
331 }
332
333 if ( $this->mIsBackwards ) {
334 $this->mIsFirst = ( $numRows < $limit );
335 $this->mIsLast = $isFirst;
336 $this->mLastShown = $firstIndex;
337 $this->mFirstShown = $lastIndex;
338 } else {
339 $this->mIsFirst = $isFirst;
340 $this->mIsLast = ( $numRows < $limit );
341 $this->mLastShown = $lastIndex;
342 $this->mFirstShown = $firstIndex;
343 }
344 }
345
351 function getSqlComment() {
352 return static::class;
353 }
354
364 public function reallyDoQuery( $offset, $limit, $descending ) {
365 list( $tables, $fields, $conds, $fname, $options, $join_conds ) =
366 $this->buildQueryInfo( $offset, $limit, $descending );
367
368 return $this->mDb->select( $tables, $fields, $conds, $fname, $options, $join_conds );
369 }
370
379 protected function buildQueryInfo( $offset, $limit, $descending ) {
380 $fname = __METHOD__ . ' (' . $this->getSqlComment() . ')';
381 $info = $this->getQueryInfo();
382 $tables = $info['tables'];
383 $fields = $info['fields'];
384 $conds = isset( $info['conds'] ) ? $info['conds'] : [];
385 $options = isset( $info['options'] ) ? $info['options'] : [];
386 $join_conds = isset( $info['join_conds'] ) ? $info['join_conds'] : [];
387 $sortColumns = array_merge( [ $this->mIndexField ], $this->mExtraSortFields );
388 if ( $descending ) {
389 $options['ORDER BY'] = $sortColumns;
390 $operator = $this->mIncludeOffset ? '>=' : '>';
391 } else {
392 $orderBy = [];
393 foreach ( $sortColumns as $col ) {
394 $orderBy[] = $col . ' DESC';
395 }
396 $options['ORDER BY'] = $orderBy;
397 $operator = $this->mIncludeOffset ? '<=' : '<';
398 }
399 if ( $offset != '' ) {
400 $conds[] = $this->mIndexField . $operator . $this->mDb->addQuotes( $offset );
401 }
402 $options['LIMIT'] = intval( $limit );
403 return [ $tables, $fields, $conds, $fname, $options, $join_conds ];
404 }
405
411 protected function preprocessResults( $result ) {
412 }
413
420 public function getBody() {
421 if ( !$this->mQueryDone ) {
422 $this->doQuery();
423 }
424
425 if ( $this->mResult->numRows() ) {
426 # Do any special query batches before display
427 $this->doBatchLookups();
428 }
429
430 # Don't use any extra rows returned by the query
431 $numRows = min( $this->mResult->numRows(), $this->mLimit );
432
433 $s = $this->getStartBody();
434 if ( $numRows ) {
435 if ( $this->mIsBackwards ) {
436 for ( $i = $numRows - 1; $i >= 0; $i-- ) {
437 $this->mResult->seek( $i );
438 $row = $this->mResult->fetchObject();
439 $s .= $this->formatRow( $row );
440 }
441 } else {
442 $this->mResult->seek( 0 );
443 for ( $i = 0; $i < $numRows; $i++ ) {
444 $row = $this->mResult->fetchObject();
445 $s .= $this->formatRow( $row );
446 }
447 }
448 } else {
449 $s .= $this->getEmptyBody();
450 }
451 $s .= $this->getEndBody();
452 return $s;
453 }
454
464 function makeLink( $text, array $query = null, $type = null ) {
465 if ( $query === null ) {
466 return $text;
467 }
468
469 $attrs = [];
470 if ( in_array( $type, [ 'prev', 'next' ] ) ) {
471 $attrs['rel'] = $type;
472 }
473
474 if ( in_array( $type, [ 'asc', 'desc' ] ) ) {
475 $attrs['title'] = wfMessage( $type == 'asc' ? 'sort-ascending' : 'sort-descending' )->text();
476 }
477
478 if ( $type ) {
479 $attrs['class'] = "mw-{$type}link";
480 }
481
482 return Linker::linkKnown(
483 $this->getTitle(),
484 $text,
485 $attrs,
486 $query + $this->getDefaultQuery()
487 );
488 }
489
497 protected function doBatchLookups() {
498 }
499
506 protected function getStartBody() {
507 return '';
508 }
509
515 protected function getEndBody() {
516 return '';
517 }
518
525 protected function getEmptyBody() {
526 return '';
527 }
528
536 function getDefaultQuery() {
537 if ( !isset( $this->mDefaultQuery ) ) {
538 $this->mDefaultQuery = $this->getRequest()->getQueryValues();
539 unset( $this->mDefaultQuery['title'] );
540 unset( $this->mDefaultQuery['dir'] );
541 unset( $this->mDefaultQuery['offset'] );
542 unset( $this->mDefaultQuery['limit'] );
543 unset( $this->mDefaultQuery['order'] );
544 unset( $this->mDefaultQuery['month'] );
545 unset( $this->mDefaultQuery['year'] );
546 }
548 }
549
555 function getNumRows() {
556 if ( !$this->mQueryDone ) {
557 $this->doQuery();
558 }
559 return $this->mResult->numRows();
560 }
561
567 function getPagingQueries() {
568 if ( !$this->mQueryDone ) {
569 $this->doQuery();
570 }
571
572 # Don't announce the limit everywhere if it's the default
573 $urlLimit = $this->mLimit == $this->mDefaultLimit ? null : $this->mLimit;
574
575 if ( $this->mIsFirst ) {
576 $prev = false;
577 $first = false;
578 } else {
579 $prev = [
580 'dir' => 'prev',
581 'offset' => $this->mFirstShown,
582 'limit' => $urlLimit
583 ];
584 $first = [ 'limit' => $urlLimit ];
585 }
586 if ( $this->mIsLast ) {
587 $next = false;
588 $last = false;
589 } else {
590 $next = [ 'offset' => $this->mLastShown, 'limit' => $urlLimit ];
591 $last = [ 'dir' => 'prev', 'limit' => $urlLimit ];
592 }
593 return [
594 'prev' => $prev,
595 'next' => $next,
596 'first' => $first,
597 'last' => $last
598 ];
599 }
600
607 if ( !$this->mQueryDone ) {
608 $this->doQuery();
609 }
610 // Hide navigation by default if there is nothing to page
611 return !( $this->mIsFirst && $this->mIsLast );
612 }
613
624 function getPagingLinks( $linkTexts, $disabledTexts = [] ) {
625 $queries = $this->getPagingQueries();
626 $links = [];
627
628 foreach ( $queries as $type => $query ) {
629 if ( $query !== false ) {
630 $links[$type] = $this->makeLink(
631 $linkTexts[$type],
633 $type
634 );
635 } elseif ( isset( $disabledTexts[$type] ) ) {
636 $links[$type] = $disabledTexts[$type];
637 } else {
638 $links[$type] = $linkTexts[$type];
639 }
640 }
641
642 return $links;
643 }
644
645 function getLimitLinks() {
646 $links = [];
647 if ( $this->mIsBackwards ) {
648 $offset = $this->mPastTheEndIndex;
649 } else {
650 $offset = $this->mOffset;
651 }
652 foreach ( $this->mLimitsShown as $limit ) {
653 $links[] = $this->makeLink(
654 $this->getLanguage()->formatNum( $limit ),
655 [ 'offset' => $offset, 'limit' => $limit ],
656 'num'
657 );
658 }
659 return $links;
660 }
661
670 abstract function formatRow( $row );
671
684 abstract function getQueryInfo();
685
698 abstract function getIndexField();
699
716 protected function getExtraSortFields() {
717 return [];
718 }
719
739 protected function getDefaultDirections() {
740 return self::DIR_ASCENDING;
741 }
742}
$dir
Definition Autoload.php:8
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined.
Definition Setup.php:36
The simplest way of implementing IContextSource is to hold a RequestContext as a member variable and ...
getUser()
Get the User object.
getRequest()
Get the WebRequest object.
getTitle()
Get the Title object.
IContextSource $context
getLanguage()
Get the Language object.
setContext(IContextSource $context)
Set the IContextSource object.
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.
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.
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.
ResultWrapper $mResult
Result object for the query.
getStartBody()
Hook into getBody(), allows text to be inserted at the start.
extractResultInfo( $isFirst, $limit, ResultWrapper $res)
Extract some useful data from the result object for use by the navigation bar, put it into $this.
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:164
Result wrapper for grabbing data queried from an IDatabase object.
$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
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add text
Definition design.txt:18
the array() calling protocol came about after MediaWiki 1.4rc1.
this hook is for auditing only RecentChangesLinked and Watchlist 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:1013
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:1971
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 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 additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt;div ...>$1&lt;/div>"). - flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException':Called before an exception(or PHP error) is logged. This is meant for integration with external error aggregation services
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:1610
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:2990
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:40
$queries
$last
const DB_REPLICA
Definition defines.php:25