4 * Basic pager interface.
8 function getNavigationBar();
13 * IndexPager is an efficient pager which uses a (roughly unique) index in the
14 * data set to implement paging, rather than a "LIMIT offset,limit" clause.
15 * In MySQL, such a limit/offset clause requires counting through the specified number
16 * of offset rows to find the desired data, which can be expensive for large offsets.
18 * ReverseChronologicalPager is a child class of the abstract IndexPager, and contains
19 * some formatting and display code which is specific to the use of timestamps as
20 * indexes. Here is a synopsis of its operation:
22 * * The query is specified by the offset, limit and direction (dir) parameters, in
23 * addition to any subclass-specific parameters.
25 * * The offset is the non-inclusive start of the DB query. A row with an index value
26 * equal to the offset will never be shown.
28 * * The query may either be done backwards, where the rows are returned by the database
29 * in the opposite order to which they are displayed to the user, or forwards. This is
30 * specified by the "dir" parameter, dir=prev means backwards, anything else means
31 * forwards. The offset value specifies the start of the database result set, which
32 * may be either the start or end of the displayed data set. This allows "previous"
33 * links to be implemented without knowledge of the index value at the start of the
36 * * An additional row beyond the user-specified limit is always requested. This allows
37 * us to tell whether we should display a "next" link in the case of forwards mode,
38 * or a "previous" link in the case of backwards mode. Determining whether to
39 * display the other link (the one for the page before the start of the database
40 * result set) can be done heuristically by examining the offset.
42 * * An empty offset indicates that the offset condition should be omitted from the query.
43 * This naturally produces either the first page or the last page depending on the
46 * Subclassing the pager to implement concrete functionality should be fairly simple,
47 * please see the examples in PageHistory.php and SpecialIpblocklist.php. You just need
48 * to override formatRow(), getQueryInfo() and getIndexField(). Don't forget to call the
49 * parent constructor if you override it.
53 abstract class IndexPager
implements Pager
{
55 public $mLimitsShown = array( 20, 50, 100, 250, 500 );
56 public $mDefaultLimit = 50;
57 public $mOffset, $mLimit;
58 public $mQueryDone = false;
60 public $mPastTheEndRow;
62 protected $mIndexField;
65 * Default query direction. false for ascending, true for descending
67 public $mDefaultDirection = false;
70 * Result object for the query. Warning: seek before use.
74 function __construct() {
75 global $wgRequest, $wgUser;
76 $this->mRequest
= $wgRequest;
78 # NB: the offset is quoted, not validated. It is treated as an arbitrary string
79 # to support the widest variety of index types. Be careful outputting it into
81 $this->mOffset
= $this->mRequest
->getText( 'offset' );
83 # Use consistent behavior for the limit options
84 $this->mDefaultLimit
= intval( $wgUser->getOption( 'rclimit' ) );
85 list( $this->mLimit
, /* $offset */ ) = $this->mRequest
->getLimitOffset();
87 $this->mIsBackwards
= ( $this->mRequest
->getVal( 'dir' ) == 'prev' );
88 $this->mIndexField
= $this->getIndexField();
89 $this->mDb
= wfGetDB( DB_SLAVE
);
93 * Do the query, using information from the object context. This function
94 * has been kept minimal to make it overridable if necessary, to allow for
95 * result sets formed from multiple DB queries.
98 # Use the child class name for profiling
99 $fname = __METHOD__
. ' (' . get_class( $this ) . ')';
100 wfProfileIn( $fname );
102 $descending = ( $this->mIsBackwards
== $this->mDefaultDirection
);
103 # Plus an extra row so that we can tell the "next" link should be shown
104 $queryLimit = $this->mLimit +
1;
106 $this->mResult
= $this->reallyDoQuery( $this->mOffset
, $queryLimit, $descending );
107 $this->extractResultInfo( $this->mOffset
, $queryLimit, $this->mResult
);
108 $this->mQueryDone
= true;
110 wfProfileOut( $fname );
114 * Extract some useful data from the result object for use by
115 * the navigation bar, put it into $this
117 function extractResultInfo( $offset, $limit, ResultWrapper
$res ) {
118 $numRows = $res->numRows();
120 $row = $res->fetchRow();
121 $firstIndex = $row[$this->mIndexField
];
123 # Discard the extra result row if there is one
124 if ( $numRows > $this->mLimit
&& $numRows > 1 ) {
125 $res->seek( $numRows - 1 );
126 $this->mPastTheEndRow
= $res->fetchObject();
127 $indexField = $this->mIndexField
;
128 $this->mPastTheEndIndex
= $this->mPastTheEndRow
->$indexField;
129 $res->seek( $numRows - 2 );
130 $row = $res->fetchRow();
131 $lastIndex = $row[$this->mIndexField
];
133 $this->mPastTheEndRow
= null;
134 # Setting indexes to an empty string means that they will be omitted
135 # if they would otherwise appear in URLs. It just so happens that this
136 # is the right thing to do in the standard UI, in all the relevant cases.
137 $this->mPastTheEndIndex
= '';
138 $res->seek( $numRows - 1 );
139 $row = $res->fetchRow();
140 $lastIndex = $row[$this->mIndexField
];
145 $this->mPastTheEndRow
= null;
146 $this->mPastTheEndIndex
= '';
149 if ( $this->mIsBackwards
) {
150 $this->mIsFirst
= ( $numRows < $limit );
151 $this->mIsLast
= ( $offset == '' );
152 $this->mLastShown
= $firstIndex;
153 $this->mFirstShown
= $lastIndex;
155 $this->mIsFirst
= ( $offset == '' );
156 $this->mIsLast
= ( $numRows < $limit );
157 $this->mLastShown
= $lastIndex;
158 $this->mFirstShown
= $firstIndex;
163 * Do a query with specified parameters, rather than using the object context
165 * @param string $offset Index offset, inclusive
166 * @param integer $limit Exact query limit
167 * @param boolean $descending Query direction, false for ascending, true for descending
168 * @return ResultWrapper
170 function reallyDoQuery( $offset, $limit, $ascending ) {
171 $fname = __METHOD__
. ' (' . get_class( $this ) . ')';
172 $info = $this->getQueryInfo();
173 $tables = $info['tables'];
174 $fields = $info['fields'];
175 $conds = isset( $info['conds'] ) ?
$info['conds'] : array();
176 $options = isset( $info['options'] ) ?
$info['options'] : array();
178 $options['ORDER BY'] = $this->mIndexField
;
181 $options['ORDER BY'] = $this->mIndexField
. ' DESC';
184 if ( $offset != '' ) {
185 $conds[] = $this->mIndexField
. $operator . $this->mDb
->addQuotes( $offset );
187 $options['LIMIT'] = intval( $limit );
188 $res = $this->mDb
->select( $tables, $fields, $conds, $fname, $options );
189 return new ResultWrapper( $this->mDb
, $res );
193 * Get the formatted result list. Calls getStartBody(), formatRow() and
194 * getEndBody(), concatenates the results and returns them.
197 if ( !$this->mQueryDone
) {
200 # Don't use any extra rows returned by the query
201 $numRows = min( $this->mResult
->numRows(), $this->mLimit
);
203 $s = $this->getStartBody();
205 if ( $this->mIsBackwards
) {
206 for ( $i = $numRows - 1; $i >= 0; $i-- ) {
207 $this->mResult
->seek( $i );
208 $row = $this->mResult
->fetchObject();
209 $s .= $this->formatRow( $row );
212 $this->mResult
->seek( 0 );
213 for ( $i = 0; $i < $numRows; $i++
) {
214 $row = $this->mResult
->fetchObject();
215 $s .= $this->formatRow( $row );
219 $s .= $this->getEmptyBody();
221 $s .= $this->getEndBody();
228 function makeLink($text, $query = NULL) {
229 if ( $query === null ) {
232 return $this->getSkin()->makeKnownLinkObj( $this->getTitle(), $text,
233 wfArrayToCGI( $query, $this->getDefaultQuery() ) );
238 * Hook into getBody(), allows text to be inserted at the start. This
239 * will be called even if there are no rows in the result set.
241 function getStartBody() {
246 * Hook into getBody() for the end of the list
248 function getEndBody() {
253 * Hook into getBody(), for the bit between the start and the
254 * end when there are no rows
256 function getEmptyBody() {
261 * Title used for self-links. Override this if you want to be able to
262 * use a title other than $wgTitle
264 function getTitle() {
265 return $GLOBALS['wgTitle'];
269 * Get the current skin. This can be overridden if necessary.
272 if ( !isset( $this->mSkin
) ) {
274 $this->mSkin
= $wgUser->getSkin();
280 * Get an array of query parameters that should be put into self-links.
281 * By default, all parameters passed in the URL are used, except for a
284 function getDefaultQuery() {
285 if ( !isset( $this->mDefaultQuery
) ) {
286 $this->mDefaultQuery
= $_GET;
287 unset( $this->mDefaultQuery
['title'] );
288 unset( $this->mDefaultQuery
['dir'] );
289 unset( $this->mDefaultQuery
['offset'] );
290 unset( $this->mDefaultQuery
['limit'] );
292 return $this->mDefaultQuery
;
296 * Get the number of rows in the result set
298 function getNumRows() {
299 if ( !$this->mQueryDone
) {
302 return $this->mResult
->numRows();
306 * Get a query array for the prev, next, first and last links.
308 function getPagingQueries() {
309 if ( !$this->mQueryDone
) {
313 # Don't announce the limit everywhere if it's the default
314 $urlLimit = $this->mLimit
== $this->mDefaultLimit ?
'' : $this->mLimit
;
316 if ( $this->mIsFirst
) {
320 $prev = array( 'dir' => 'prev', 'offset' => $this->mFirstShown
, 'limit' => $urlLimit );
321 $first = array( 'limit' => $urlLimit );
323 if ( $this->mIsLast
) {
327 $next = array( 'offset' => $this->mLastShown
, 'limit' => $urlLimit );
328 $last = array( 'dir' => 'prev', 'limit' => $urlLimit );
330 return array( 'prev' => $prev, 'next' => $next, 'first' => $first, 'last' => $last );
334 * Get paging links. If a link is disabled, the item from $disabledTexts will
335 * be used. If there is no such item, the unlinked text from $linkTexts will
336 * be used. Both $linkTexts and $disabledTexts are arrays of HTML.
338 function getPagingLinks( $linkTexts, $disabledTexts = array() ) {
339 $queries = $this->getPagingQueries();
341 foreach ( $queries as $type => $query ) {
342 if ( $query !== false ) {
343 $links[$type] = $this->makeLink( $linkTexts[$type], $queries[$type] );
344 } elseif ( isset( $disabledTexts[$type] ) ) {
345 $links[$type] = $disabledTexts[$type];
347 $links[$type] = $linkTexts[$type];
353 function getLimitLinks() {
356 if ( $this->mIsBackwards
) {
357 $offset = $this->mPastTheEndIndex
;
359 $offset = $this->mOffset
;
361 foreach ( $this->mLimitsShown
as $limit ) {
362 $links[] = $this->makeLink( $wgLang->formatNum( $limit ),
363 array( 'offset' => $offset, 'limit' => $limit ) );
369 * Abstract formatting function. This should return an HTML string
370 * representing the result row $row. Rows will be concatenated and
371 * returned by getBody()
373 abstract function formatRow( $row );
376 * This function should be overridden to provide all parameters
377 * needed for the main paged query. It returns an associative
378 * array with the following elements:
379 * tables => Table(s) for passing to Database::select()
380 * fields => Field(s) for passing to Database::select(), may be *
381 * conds => WHERE conditions
382 * options => option array
384 abstract function getQueryInfo();
387 * This function should be overridden to return the name of the
390 abstract function getIndexField();
395 * IndexPager with an alphabetic list and a formatted navigation bar
398 abstract class AlphabeticPager
extends IndexPager
{
399 public $mDefaultDirection = false;
401 function __construct() {
402 parent
::__construct();
406 * Shamelessly stolen bits from ReverseChronologicalPager, d
407 * didn't want to do class magic as may be still revamped
409 function getNavigationBar() {
413 'prev' => wfMsgHtml( "prevn", $this->mLimit
),
414 'next' => wfMsgHtml( 'nextn', $this->mLimit
),
415 'first' => wfMsgHtml('page_first'), /* Introduced the message */
416 'last' => wfMsgHtml( 'page_last' ) /* Introduced the message */
419 $pagingLinks = $this->getPagingLinks( $linkTexts );
420 $limitLinks = $this->getLimitLinks();
421 $limits = implode( ' | ', $limitLinks );
423 $this->mNavigationBar
= "({$pagingLinks['first']} | {$pagingLinks['last']}) " . wfMsgHtml("viewprevnext", $pagingLinks['prev'], $pagingLinks['next'], $limits);
424 return $this->mNavigationBar
;
430 * IndexPager with a formatted navigation bar
433 abstract class ReverseChronologicalPager
extends IndexPager
{
434 public $mDefaultDirection = true;
436 function __construct() {
437 parent
::__construct();
440 function getNavigationBar() {
443 if ( isset( $this->mNavigationBar
) ) {
444 return $this->mNavigationBar
;
447 'prev' => wfMsgHtml( "prevn", $this->mLimit
),
448 'next' => wfMsgHtml( 'nextn', $this->mLimit
),
449 'first' => wfMsgHtml('histlast'),
450 'last' => wfMsgHtml( 'histfirst' )
453 $pagingLinks = $this->getPagingLinks( $linkTexts );
454 $limitLinks = $this->getLimitLinks();
455 $limits = implode( ' | ', $limitLinks );
457 $this->mNavigationBar
= "({$pagingLinks['first']} | {$pagingLinks['last']}) " .
458 wfMsgHtml("viewprevnext", $pagingLinks['prev'], $pagingLinks['next'], $limits);
459 return $this->mNavigationBar
;
464 * Table-based display with a user-selectable sort order
467 abstract class TablePager
extends IndexPager
{
471 function __construct() {
473 $this->mSort
= $wgRequest->getText( 'sort' );
474 if ( !array_key_exists( $this->mSort
, $this->getFieldNames() ) ) {
475 $this->mSort
= $this->getDefaultSort();
477 if ( $wgRequest->getBool( 'asc' ) ) {
478 $this->mDefaultDirection
= false;
479 } elseif ( $wgRequest->getBool( 'desc' ) ) {
480 $this->mDefaultDirection
= true;
481 } /* Else leave it at whatever the class default is */
483 parent
::__construct();
486 function getStartBody() {
488 $tableClass = htmlspecialchars( $this->getTableClass() );
489 $sortClass = htmlspecialchars( $this->getSortHeaderClass() );
491 $s = "<table border='1' class=\"$tableClass\"><thead><tr>\n";
492 $fields = $this->getFieldNames();
495 foreach ( $fields as $field => $name ) {
496 if ( strval( $name ) == '' ) {
497 $s .= "<th> </th>\n";
498 } elseif ( $this->isFieldSortable( $field ) ) {
499 $query = array( 'sort' => $field, 'limit' => $this->mLimit
);
500 if ( $field == $this->mSort
) {
501 # This is the sorted column
502 # Prepare a link that goes in the other sort order
503 if ( $this->mDefaultDirection
) {
505 $image = 'Arr_u.png';
508 $alt = htmlspecialchars( wfMsg( 'descending_abbrev' ) );
511 $image = 'Arr_d.png';
513 $query['desc'] = '1';
514 $alt = htmlspecialchars( wfMsg( 'ascending_abbrev' ) );
516 $image = htmlspecialchars( "$wgStylePath/common/images/$image" );
517 $link = $this->makeLink(
518 "<img width=\"12\" height=\"12\" alt=\"$alt\" src=\"$image\" />" .
519 htmlspecialchars( $name ), $query );
520 $s .= "<th class=\"$sortClass\">$link</th>\n";
522 $s .= '<th>' . $this->makeLink( htmlspecialchars( $name ), $query ) . "</th>\n";
525 $s .= '<th>' . htmlspecialchars( $name ) . "</th>\n";
528 $s .= "</tr></thead><tbody>\n";
532 function getEndBody() {
533 return "</tbody></table>\n";
536 function getEmptyBody() {
537 $colspan = count( $this->getFieldNames() );
538 $msgEmpty = wfMsgHtml( 'table_pager_empty' );
539 return "<tr><td colspan=\"$colspan\">$msgEmpty</td></tr>\n";
542 function formatRow( $row ) {
544 $fieldNames = $this->getFieldNames();
545 $this->mCurrentRow
= $row; # In case formatValue needs to know
546 foreach ( $fieldNames as $field => $name ) {
547 $value = isset( $row->$field ) ?
$row->$field : null;
548 $formatted = strval( $this->formatValue( $field, $value ) );
549 if ( $formatted == '' ) {
550 $formatted = ' ';
552 $class = 'TablePager_col_' . htmlspecialchars( $field );
553 $s .= "<td class=\"$class\">$formatted</td>\n";
559 function getIndexField() {
563 function getTableClass() {
567 function getNavClass() {
568 return 'TablePager_nav';
571 function getSortHeaderClass() {
572 return 'TablePager_sort';
576 * A navigation bar with images
578 function getNavigationBar() {
579 global $wgStylePath, $wgContLang;
580 $path = "$wgStylePath/common/images";
582 'first' => 'table_pager_first',
583 'prev' => 'table_pager_prev',
584 'next' => 'table_pager_next',
585 'last' => 'table_pager_last',
588 'first' => $wgContLang->isRTL() ?
'arrow_last_25.png' : 'arrow_first_25.png',
589 'prev' => $wgContLang->isRTL() ?
'arrow_right_25.png' : 'arrow_left_25.png',
590 'next' => $wgContLang->isRTL() ?
'arrow_left_25.png' : 'arrow_right_25.png',
591 'last' => $wgContLang->isRTL() ?
'arrow_first_25.png' : 'arrow_last_25.png',
593 $disabledImages = array(
594 'first' => $wgContLang->isRTL() ?
'arrow_disabled_last_25.png' : 'arrow_disabled_first_25.png',
595 'prev' => $wgContLang->isRTL() ?
'arrow_disabled_right_25.png' : 'arrow_disabled_left_25.png',
596 'next' => $wgContLang->isRTL() ?
'arrow_disabled_left_25.png' : 'arrow_disabled_right_25.png',
597 'last' => $wgContLang->isRTL() ?
'arrow_disabled_first_25.png' : 'arrow_disabled_last_25.png',
600 $linkTexts = array();
601 $disabledTexts = array();
602 foreach ( $labels as $type => $label ) {
603 $msgLabel = wfMsgHtml( $label );
604 $linkTexts[$type] = "<img src=\"$path/{$images[$type]}\" alt=\"$msgLabel\"/><br/>$msgLabel";
605 $disabledTexts[$type] = "<img src=\"$path/{$disabledImages[$type]}\" alt=\"$msgLabel\"/><br/>$msgLabel";
607 $links = $this->getPagingLinks( $linkTexts, $disabledTexts );
609 $navClass = htmlspecialchars( $this->getNavClass() );
610 $s = "<table class=\"$navClass\" align=\"center\" cellpadding=\"3\"><tr>\n";
611 $cellAttrs = 'valign="top" align="center" width="' . 100 / count( $links ) . '%"';
612 foreach ( $labels as $type => $label ) {
613 $s .= "<td $cellAttrs>{$links[$type]}</td>\n";
615 $s .= "</tr></table>\n";
620 * Get a <select> element which has options for each of the allowed limits
622 function getLimitSelect() {
624 $s = "<select name=\"limit\">";
625 foreach ( $this->mLimitsShown
as $limit ) {
626 $selected = $limit == $this->mLimit ?
'selected="selected"' : '';
627 $formattedLimit = $wgLang->formatNum( $limit );
628 $s .= "<option value=\"$limit\" $selected>$formattedLimit</option>\n";
635 * Get <input type="hidden"> elements for use in a method="get" form.
636 * Resubmits all defined elements of the $_GET array, except for a
637 * blacklist, passed in the $blacklist parameter.
639 function getHiddenFields( $blacklist = array() ) {
640 $blacklist = (array)$blacklist;
642 foreach ( $blacklist as $name ) {
643 unset( $query[$name] );
646 foreach ( $query as $name => $value ) {
647 $encName = htmlspecialchars( $name );
648 $encValue = htmlspecialchars( $value );
649 $s .= "<input type=\"hidden\" name=\"$encName\" value=\"$encValue\"/>\n";
655 * Get a form containing a limit selection dropdown
657 function getLimitForm() {
658 # Make the select with some explanatory text
659 $url = $this->getTitle()->escapeLocalURL();
660 $msgSubmit = wfMsgHtml( 'table_pager_limit_submit' );
662 "<form method=\"get\" action=\"$url\">" .
663 wfMsgHtml( 'table_pager_limit', $this->getLimitSelect() ) .
664 "\n<input type=\"submit\" value=\"$msgSubmit\"/>\n" .
665 $this->getHiddenFields( 'limit' ) .
670 * Return true if the named field should be sortable by the UI, false otherwise
671 * @param string $field
673 abstract function isFieldSortable( $field );
676 * Format a table cell. The return value should be HTML, but use an empty string
677 * not for empty cells. Do not include the <td> and </td>.
679 * @param string $name The database field name
680 * @param string $value The value retrieved from the database
682 * The current result row is available as $this->mCurrentRow, in case you need
685 abstract function formatValue( $name, $value );
688 * The database field name used as a default sort order
690 abstract function getDefaultSort();
693 * An array mapping database field names to a textual description of the field
694 * name, for use in the table header. The description should be plain text, it
695 * will be HTML-escaped later.
697 abstract function getFieldNames();