MediaWiki  master
IndexPager.php
Go to the documentation of this file.
1 <?php
29 
72 abstract class IndexPager extends ContextSource implements Pager {
74  const DIR_ASCENDING = false;
76  const DIR_DESCENDING = true;
77 
79  const QUERY_ASCENDING = true;
81  const QUERY_DESCENDING = false;
82 
84  public $mRequest;
86  public $mLimitsShown = [ 20, 50, 100, 250, 500 ];
88  public $mDefaultLimit = 50;
90  public $mOffset;
92  public $mLimit;
94  public $mQueryDone = false;
96  public $mDb;
99 
105  protected $mIndexField;
111  protected $mExtraSortFields;
115  protected $mOrderType;
131 
133  public $mIsFirst;
135  public $mIsLast;
136 
138  protected $mLastShown;
140  protected $mFirstShown;
142  protected $mPastTheEndIndex;
144  protected $mDefaultQuery;
146  protected $mNavigationBar;
147 
152  protected $mIncludeOffset = false;
153 
159  public $mResult;
160 
162  private $linkRenderer;
163 
164  public function __construct( IContextSource $context = null, LinkRenderer $linkRenderer = null ) {
165  if ( $context ) {
166  $this->setContext( $context );
167  }
168 
169  $this->mRequest = $this->getRequest();
170 
171  # NB: the offset is quoted, not validated. It is treated as an
172  # arbitrary string to support the widest variety of index types. Be
173  # careful outputting it into HTML!
174  $this->mOffset = $this->mRequest->getText( 'offset' );
175 
176  # Use consistent behavior for the limit options
177  $this->mDefaultLimit = $this->getUser()->getIntOption( 'rclimit' );
178  if ( !$this->mLimit ) {
179  // Don't override if a subclass calls $this->setLimit() in its constructor.
180  list( $this->mLimit, /* $offset */ ) = $this->mRequest->getLimitOffset();
181  }
182 
183  $this->mIsBackwards = ( $this->mRequest->getVal( 'dir' ) == 'prev' );
184  # Let the subclass set the DB here; otherwise use a replica DB for the current wiki
185  $this->mDb = $this->mDb ?: wfGetDB( DB_REPLICA );
186 
187  $index = $this->getIndexField(); // column to sort on
188  $extraSort = $this->getExtraSortFields(); // extra columns to sort on for query planning
189  $order = $this->mRequest->getVal( 'order' );
190  if ( is_array( $index ) && isset( $index[$order] ) ) {
191  $this->mOrderType = $order;
192  $this->mIndexField = $index[$order];
193  $this->mExtraSortFields = isset( $extraSort[$order] )
194  ? (array)$extraSort[$order]
195  : [];
196  } elseif ( is_array( $index ) ) {
197  # First element is the default
198  $this->mIndexField = reset( $index );
199  $this->mOrderType = key( $index );
200  $this->mExtraSortFields = isset( $extraSort[$this->mOrderType] )
201  ? (array)$extraSort[$this->mOrderType]
202  : [];
203  } else {
204  # $index is not an array
205  $this->mOrderType = null;
206  $this->mIndexField = $index;
207  $isSortAssociative = array_values( $extraSort ) !== $extraSort;
208  if ( $isSortAssociative ) {
209  $this->mExtraSortFields = isset( $extraSort[$index] )
210  ? (array)$extraSort[$index]
211  : [];
212  } else {
213  $this->mExtraSortFields = (array)$extraSort;
214  }
215  }
216 
217  if ( !isset( $this->mDefaultDirection ) ) {
218  $dir = $this->getDefaultDirections();
219  $this->mDefaultDirection = is_array( $dir )
220  ? $dir[$this->mOrderType]
221  : $dir;
222  }
223  $this->linkRenderer = $linkRenderer;
224  }
225 
231  public function getDatabase() {
232  return $this->mDb;
233  }
234 
240  public function doQuery() {
241  # Use the child class name for profiling
242  $fname = __METHOD__ . ' (' . static::class . ')';
244  $section = Profiler::instance()->scopedProfileIn( $fname );
245 
246  $defaultOrder = ( $this->mDefaultDirection === self::DIR_ASCENDING )
247  ? self::QUERY_ASCENDING
248  : self::QUERY_DESCENDING;
249  $order = $this->mIsBackwards ? self::oppositeOrder( $defaultOrder ) : $defaultOrder;
250 
251  # Plus an extra row so that we can tell the "next" link should be shown
252  $queryLimit = $this->mLimit + 1;
253 
254  if ( $this->mOffset == '' ) {
255  $isFirst = true;
256  } else {
257  // If there's an offset, we may or may not be at the first entry.
258  // The only way to tell is to run the query in the opposite
259  // direction see if we get a row.
260  $oldIncludeOffset = $this->mIncludeOffset;
261  $this->mIncludeOffset = !$this->mIncludeOffset;
262  $oppositeOrder = self::oppositeOrder( $order );
263  $isFirst = !$this->reallyDoQuery( $this->mOffset, 1, $oppositeOrder )->numRows();
264  $this->mIncludeOffset = $oldIncludeOffset;
265  }
266 
267  $this->mResult = $this->reallyDoQuery(
268  $this->mOffset,
269  $queryLimit,
270  $order
271  );
272 
273  $this->extractResultInfo( $isFirst, $queryLimit, $this->mResult );
274  $this->mQueryDone = true;
275 
276  $this->preprocessResults( $this->mResult );
277  $this->mResult->rewind(); // Paranoia
278  }
279 
284  final protected static function oppositeOrder( $order ) {
285  return ( $order === self::QUERY_ASCENDING )
286  ? self::QUERY_DESCENDING
287  : self::QUERY_ASCENDING;
288  }
289 
293  function getResult() {
294  return $this->mResult;
295  }
296 
302  function setOffset( $offset ) {
303  $this->mOffset = $offset;
304  }
305 
313  function setLimit( $limit ) {
314  $limit = (int)$limit;
315  // WebRequest::getLimitOffset() puts a cap of 5000, so do same here.
316  if ( $limit > 5000 ) {
317  $limit = 5000;
318  }
319  if ( $limit > 0 ) {
320  $this->mLimit = $limit;
321  }
322  }
323 
329  function getLimit() {
330  return $this->mLimit;
331  }
332 
340  public function setIncludeOffset( $include ) {
341  $this->mIncludeOffset = $include;
342  }
343 
353  function extractResultInfo( $isFirst, $limit, IResultWrapper $res ) {
354  $numRows = $res->numRows();
355  if ( $numRows ) {
356  # Remove any table prefix from index field
357  $parts = explode( '.', $this->mIndexField );
358  $indexColumn = end( $parts );
359 
360  $row = $res->fetchRow();
361  $firstIndex = $row[$indexColumn];
362 
363  # Discard the extra result row if there is one
364  if ( $numRows > $this->mLimit && $numRows > 1 ) {
365  $res->seek( $numRows - 1 );
366  $this->mPastTheEndRow = $res->fetchObject();
367  $this->mPastTheEndIndex = $this->mPastTheEndRow->$indexColumn;
368  $res->seek( $numRows - 2 );
369  $row = $res->fetchRow();
370  $lastIndex = $row[$indexColumn];
371  } else {
372  $this->mPastTheEndRow = null;
373  # Setting indexes to an empty string means that they will be
374  # omitted if they would otherwise appear in URLs. It just so
375  # happens that this is the right thing to do in the standard
376  # UI, in all the relevant cases.
377  $this->mPastTheEndIndex = '';
378  $res->seek( $numRows - 1 );
379  $row = $res->fetchRow();
380  $lastIndex = $row[$indexColumn];
381  }
382  } else {
383  $firstIndex = '';
384  $lastIndex = '';
385  $this->mPastTheEndRow = null;
386  $this->mPastTheEndIndex = '';
387  }
388 
389  if ( $this->mIsBackwards ) {
390  $this->mIsFirst = ( $numRows < $limit );
391  $this->mIsLast = $isFirst;
392  $this->mLastShown = $firstIndex;
393  $this->mFirstShown = $lastIndex;
394  } else {
395  $this->mIsFirst = $isFirst;
396  $this->mIsLast = ( $numRows < $limit );
397  $this->mLastShown = $lastIndex;
398  $this->mFirstShown = $firstIndex;
399  }
400  }
401 
407  function getSqlComment() {
408  return static::class;
409  }
410 
421  public function reallyDoQuery( $offset, $limit, $order ) {
422  list( $tables, $fields, $conds, $fname, $options, $join_conds ) =
423  $this->buildQueryInfo( $offset, $limit, $order );
424 
425  return $this->mDb->select( $tables, $fields, $conds, $fname, $options, $join_conds );
426  }
427 
438  protected function buildQueryInfo( $offset, $limit, $order ) {
439  $fname = __METHOD__ . ' (' . $this->getSqlComment() . ')';
440  $info = $this->getQueryInfo();
441  $tables = $info['tables'];
442  $fields = $info['fields'];
443  $conds = $info['conds'] ?? [];
444  $options = $info['options'] ?? [];
445  $join_conds = $info['join_conds'] ?? [];
446  $sortColumns = array_merge( [ $this->mIndexField ], $this->mExtraSortFields );
447  if ( $order === self::QUERY_ASCENDING ) {
448  $options['ORDER BY'] = $sortColumns;
449  $operator = $this->mIncludeOffset ? '>=' : '>';
450  } else {
451  $orderBy = [];
452  foreach ( $sortColumns as $col ) {
453  $orderBy[] = $col . ' DESC';
454  }
455  $options['ORDER BY'] = $orderBy;
456  $operator = $this->mIncludeOffset ? '<=' : '<';
457  }
458  if ( $offset != '' ) {
459  $conds[] = $this->mIndexField . $operator . $this->mDb->addQuotes( $offset );
460  }
461  $options['LIMIT'] = intval( $limit );
462  return [ $tables, $fields, $conds, $fname, $options, $join_conds ];
463  }
464 
470  protected function preprocessResults( $result ) {
471  }
472 
479  public function getBody() {
480  if ( !$this->mQueryDone ) {
481  $this->doQuery();
482  }
483 
484  if ( $this->mResult->numRows() ) {
485  # Do any special query batches before display
486  $this->doBatchLookups();
487  }
488 
489  # Don't use any extra rows returned by the query
490  $numRows = min( $this->mResult->numRows(), $this->mLimit );
491 
492  $s = $this->getStartBody();
493  if ( $numRows ) {
494  if ( $this->mIsBackwards ) {
495  for ( $i = $numRows - 1; $i >= 0; $i-- ) {
496  $this->mResult->seek( $i );
497  $row = $this->mResult->fetchObject();
498  $s .= $this->formatRow( $row );
499  }
500  } else {
501  $this->mResult->seek( 0 );
502  for ( $i = 0; $i < $numRows; $i++ ) {
503  $row = $this->mResult->fetchObject();
504  $s .= $this->formatRow( $row );
505  }
506  }
507  } else {
508  $s .= $this->getEmptyBody();
509  }
510  $s .= $this->getEndBody();
511  return $s;
512  }
513 
523  function makeLink( $text, array $query = null, $type = null ) {
524  if ( $query === null ) {
525  return $text;
526  }
527 
528  $attrs = [];
529  if ( in_array( $type, [ 'prev', 'next' ] ) ) {
530  $attrs['rel'] = $type;
531  }
532 
533  if ( in_array( $type, [ 'asc', 'desc' ] ) ) {
534  $attrs['title'] = $this->msg( $type == 'asc' ? 'sort-ascending' : 'sort-descending' )->text();
535  }
536 
537  if ( $type ) {
538  $attrs['class'] = "mw-{$type}link";
539  }
540 
541  return $this->getLinkRenderer()->makeKnownLink(
542  $this->getTitle(),
543  new HtmlArmor( $text ),
544  $attrs,
545  $query + $this->getDefaultQuery()
546  );
547  }
548 
556  protected function doBatchLookups() {
557  }
558 
565  protected function getStartBody() {
566  return '';
567  }
568 
574  protected function getEndBody() {
575  return '';
576  }
577 
584  protected function getEmptyBody() {
585  return '';
586  }
587 
595  function getDefaultQuery() {
596  if ( !isset( $this->mDefaultQuery ) ) {
597  $this->mDefaultQuery = $this->getRequest()->getQueryValues();
598  unset( $this->mDefaultQuery['title'] );
599  unset( $this->mDefaultQuery['dir'] );
600  unset( $this->mDefaultQuery['offset'] );
601  unset( $this->mDefaultQuery['limit'] );
602  unset( $this->mDefaultQuery['order'] );
603  unset( $this->mDefaultQuery['month'] );
604  unset( $this->mDefaultQuery['year'] );
605  }
606  return $this->mDefaultQuery;
607  }
608 
614  function getNumRows() {
615  if ( !$this->mQueryDone ) {
616  $this->doQuery();
617  }
618  return $this->mResult->numRows();
619  }
620 
626  function getPagingQueries() {
627  if ( !$this->mQueryDone ) {
628  $this->doQuery();
629  }
630 
631  # Don't announce the limit everywhere if it's the default
632  $urlLimit = $this->mLimit == $this->mDefaultLimit ? null : $this->mLimit;
633 
634  if ( $this->mIsFirst ) {
635  $prev = false;
636  $first = false;
637  } else {
638  $prev = [
639  'dir' => 'prev',
640  'offset' => $this->mFirstShown,
641  'limit' => $urlLimit
642  ];
643  $first = [ 'limit' => $urlLimit ];
644  }
645  if ( $this->mIsLast ) {
646  $next = false;
647  $last = false;
648  } else {
649  $next = [ 'offset' => $this->mLastShown, 'limit' => $urlLimit ];
650  $last = [ 'dir' => 'prev', 'limit' => $urlLimit ];
651  }
652  return [
653  'prev' => $prev,
654  'next' => $next,
655  'first' => $first,
656  'last' => $last
657  ];
658  }
659 
665  function isNavigationBarShown() {
666  if ( !$this->mQueryDone ) {
667  $this->doQuery();
668  }
669  // Hide navigation by default if there is nothing to page
670  return !( $this->mIsFirst && $this->mIsLast );
671  }
672 
683  function getPagingLinks( $linkTexts, $disabledTexts = [] ) {
684  $queries = $this->getPagingQueries();
685  $links = [];
686 
687  foreach ( $queries as $type => $query ) {
688  if ( $query !== false ) {
689  $links[$type] = $this->makeLink(
690  $linkTexts[$type],
691  $queries[$type],
692  $type
693  );
694  } elseif ( isset( $disabledTexts[$type] ) ) {
695  $links[$type] = $disabledTexts[$type];
696  } else {
697  $links[$type] = $linkTexts[$type];
698  }
699  }
700 
701  return $links;
702  }
703 
704  function getLimitLinks() {
705  $links = [];
706  if ( $this->mIsBackwards ) {
707  $offset = $this->mPastTheEndIndex;
708  } else {
709  $offset = $this->mOffset;
710  }
711  foreach ( $this->mLimitsShown as $limit ) {
712  $links[] = $this->makeLink(
713  $this->getLanguage()->formatNum( $limit ),
714  [ 'offset' => $offset, 'limit' => $limit ],
715  'num'
716  );
717  }
718  return $links;
719  }
720 
729  abstract function formatRow( $row );
730 
743  abstract function getQueryInfo();
744 
757  abstract function getIndexField();
758 
780  protected function getExtraSortFields() {
781  return [];
782  }
783 
803  protected function getDefaultDirections() {
804  return self::DIR_ASCENDING;
805  }
806 
817  protected function buildPrevNextNavigation( Title $title, $offset, $limit,
818  array $query = [], $atend = false
819  ) {
820  $prevNext = new PrevNextNavigationRenderer( $this );
821 
822  return $prevNext->buildPrevNextNavigation( $title, $offset, $limit, $query, $atend );
823  }
824 
825  protected function getLinkRenderer() {
826  if ( $this->linkRenderer === null ) {
827  $this->linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
828  }
829  return $this->linkRenderer;
830  }
831 }
const DIR_DESCENDING
Backwards-compatible constant for $mDefaultDirection field (do not change)
Definition: IndexPager.php:76
setContext(IContextSource $context)
setOffset( $offset)
Set the offset from an other source than the request.
Definition: IndexPager.php:302
buildPrevNextNavigation(Title $title, $offset, $limit, array $query=[], $atend=false)
Generate (prev x| next x) (20|50|100...) type links for paging.
Definition: IndexPager.php:817
mixed $mOffset
The starting point to enumerate entries.
Definition: IndexPager.php:90
fetchObject()
Fetch the next row from the given result object, in object form.
preprocessResults( $result)
Pre-process results; useful for performing batch existence checks, etc.
Definition: IndexPager.php:470
Helper class for generating prev/next links for paging.
formatRow( $row)
Abstract formatting function.
getIndexField()
This function should be overridden to return the name of the index fi- eld.
bool $mDefaultDirection
$mDefaultDirection gives the direction to use when sorting results: DIR_ASCENDING or DIR_DESCENDING...
Definition: IndexPager.php:128
The simplest way of implementing IContextSource is to hold a RequestContext as a member variable and ...
int [] $mLimitsShown
List of default entry limit options to be presented to clients.
Definition: IndexPager.php:86
static instance()
Singleton.
Definition: Profiler.php:63
buildQueryInfo( $offset, $limit, $order)
Build variables to use by the database wrapper.
Definition: IndexPager.php:438
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
bool $mIsLast
Definition: IndexPager.php:135
__construct(IContextSource $context=null, LinkRenderer $linkRenderer=null)
Definition: IndexPager.php:164
static oppositeOrder( $order)
Definition: IndexPager.php:284
getPagingLinks( $linkTexts, $disabledTexts=[])
Get paging links.
Definition: IndexPager.php:683
doQuery()
Do the query, using information from the object context.
Definition: IndexPager.php:240
string $mIndexField
The index to actually be used for ordering.
Definition: IndexPager.php:105
LinkRenderer $linkRenderer
Definition: IndexPager.php:162
extractResultInfo( $isFirst, $limit, IResultWrapper $res)
Extract some useful data from the result object for use by the navigation bar, put it into $this...
Definition: IndexPager.php:353
IContextSource $context
getDatabase()
Get the Database object in use.
Definition: IndexPager.php:231
bool $mQueryDone
Whether the listing query completed.
Definition: IndexPager.php:94
doBatchLookups()
Called from getBody(), before getStartBody() is called and after doQuery() was called.
Definition: IndexPager.php:556
IndexPager is an efficient pager which uses a (roughly unique) index in the data set to implement pag...
Definition: IndexPager.php:72
bool $mIncludeOffset
Whether to include the offset in the query.
Definition: IndexPager.php:152
mixed $mLastShown
Definition: IndexPager.php:138
makeLink( $text, array $query=null, $type=null)
Make a self-link.
Definition: IndexPager.php:523
mixed $mPastTheEndIndex
Definition: IndexPager.php:142
getEmptyBody()
Hook into getBody(), for the bit between the start and the end when there are no rows.
Definition: IndexPager.php:584
getSqlComment()
Get some text to go in brackets in the "function name" part of the SQL comment.
Definition: IndexPager.php:407
Basic pager interface.
Definition: Pager.php:32
WebRequest $mRequest
Definition: IndexPager.php:84
Class that generates HTML links for pages.
getExtraSortFields()
This function should be overridden to return the names of secondary columns to order by in addition t...
Definition: IndexPager.php:780
getStartBody()
Hook into getBody(), allows text to be inserted at the start.
Definition: IndexPager.php:565
IDatabase $mDb
Definition: IndexPager.php:96
bool $mIsBackwards
Definition: IndexPager.php:130
const QUERY_ASCENDING
Backwards-compatible constant for reallyDoQuery() (do not change)
Definition: IndexPager.php:79
reallyDoQuery( $offset, $limit, $order)
Do a query with specified parameters, rather than using the object context.
Definition: IndexPager.php:421
isNavigationBarShown()
Returns whether to show the "navigation bar".
Definition: IndexPager.php:665
getLimit()
Get the current limit.
Definition: IndexPager.php:329
string $mNavigationBar
Definition: IndexPager.php:146
Result wrapper for grabbing data queried from an IDatabase object.
IResultWrapper $mResult
Result object for the query.
Definition: IndexPager.php:159
getQueryInfo()
This function should be overridden to provide all parameters needed for the main paged query...
mixed $mFirstShown
Definition: IndexPager.php:140
numRows()
Get the number of rows in a result object.
const QUERY_DESCENDING
Backwards-compatible constant for reallyDoQuery() (do not change)
Definition: IndexPager.php:81
seek( $pos)
Change the position of the cursor in a result object.
stdClass bool null $mPastTheEndRow
Extra row fetched at the end to see if the end was reached.
Definition: IndexPager.php:98
msg( $key,... $params)
Get a Message object with context set Parameters are the same as wfMessage()
getDefaultQuery()
Get an array of query parameters that should be put into self-links.
Definition: IndexPager.php:595
fetchRow()
Fetch the next row from the given result object, in associative array form.
setLimit( $limit)
Set the limit from an other source than the request.
Definition: IndexPager.php:313
setIncludeOffset( $include)
Set whether a row matching exactly the offset should be also included in the result or not...
Definition: IndexPager.php:340
bool $mIsFirst
True if the current result set is the first one.
Definition: IndexPager.php:133
const DB_REPLICA
Definition: defines.php:25
int $mDefaultLimit
The default entry limit choosen for clients.
Definition: IndexPager.php:88
getBody()
Get the formatted result list.
Definition: IndexPager.php:479
getDefaultDirections()
Return the default sorting direction: DIR_ASCENDING or DIR_DESCENDING.
Definition: IndexPager.php:803
getPagingQueries()
Get a URL query array for the prev, next, first and last links.
Definition: IndexPager.php:626
string [] $mExtraSortFields
An array of secondary columns to order by.
Definition: IndexPager.php:111
string null $mOrderType
For pages that support multiple types of ordering, which one to use.
Definition: IndexPager.php:115
const DIR_ASCENDING
Backwards-compatible constant for $mDefaultDirection field (do not change)
Definition: IndexPager.php:74
array $mDefaultQuery
Definition: IndexPager.php:144
getNumRows()
Get the number of rows in the result set.
Definition: IndexPager.php:614
getEndBody()
Hook into getBody() for the end of the list.
Definition: IndexPager.php:574
int $mLimit
The maximum number of entries to show.
Definition: IndexPager.php:92