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() {
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' );
82 $this->mLimit
= $this->mRequest
->getInt( 'limit', $this->mDefaultLimit
);
83 if ( $this->mLimit
<= 0 ||
$this->mLimit
> 50000 ) {
84 $this->mLimit
= $this->mDefaultLimit
;
86 $this->mIsBackwards
= ( $this->mRequest
->getVal( 'dir' ) == 'prev' );
87 $this->mIndexField
= $this->getIndexField();
88 $this->mDb
= wfGetDB( DB_SLAVE
);
92 * Do the query, using information from the object context. This function
93 * has been kept minimal to make it overridable if necessary, to allow for
94 * result sets formed from multiple DB queries.
97 # Use the child class name for profiling
98 $fname = __METHOD__
. ' (' . get_class( $this ) . ')';
99 wfProfileIn( $fname );
101 $descending = ( $this->mIsBackwards
== $this->mDefaultDirection
);
102 # Plus an extra row so that we can tell the "next" link should be shown
103 $queryLimit = $this->mLimit +
1;
105 $this->mResult
= $this->reallyDoQuery( $this->mOffset
, $queryLimit, $descending );
106 $this->extractResultInfo( $this->mOffset
, $queryLimit, $this->mResult
);
107 $this->mQueryDone
= true;
109 wfProfileOut( $fname );
113 * Extract some useful data from the result object for use by
114 * the navigation bar, put it into $this
116 function extractResultInfo( $offset, $limit, ResultWrapper
$res ) {
117 $numRows = $res->numRows();
119 $row = $res->fetchRow();
120 $firstIndex = $row[$this->mIndexField
];
122 # Discard the extra result row if there is one
123 if ( $numRows > $this->mLimit
&& $numRows > 1 ) {
124 $res->seek( $numRows - 1 );
125 $this->mPastTheEndRow
= $res->fetchObject();
126 $indexField = $this->mIndexField
;
127 $this->mPastTheEndIndex
= $this->mPastTheEndRow
->$indexField;
128 $res->seek( $numRows - 2 );
129 $row = $res->fetchRow();
130 $lastIndex = $row[$this->mIndexField
];
132 $this->mPastTheEndRow
= null;
133 # Setting indexes to an empty string means that they will be omitted
134 # if they would otherwise appear in URLs. It just so happens that this
135 # is the right thing to do in the standard UI, in all the relevant cases.
136 $this->mPastTheEndIndex
= '';
137 $res->seek( $numRows - 1 );
138 $row = $res->fetchRow();
139 $lastIndex = $row[$this->mIndexField
];
144 $this->mPastTheEndRow
= null;
145 $this->mPastTheEndIndex
= '';
148 if ( $this->mIsBackwards
) {
149 $this->mIsFirst
= ( $numRows < $limit );
150 $this->mIsLast
= ( $offset == '' );
151 $this->mLastShown
= $firstIndex;
152 $this->mFirstShown
= $lastIndex;
154 $this->mIsFirst
= ( $offset == '' );
155 $this->mIsLast
= ( $numRows < $limit );
156 $this->mLastShown
= $lastIndex;
157 $this->mFirstShown
= $firstIndex;
162 * Do a query with specified parameters, rather than using the object context
164 * @param string $offset Index offset, inclusive
165 * @param integer $limit Exact query limit
166 * @param boolean $descending Query direction, false for ascending, true for descending
167 * @return ResultWrapper
169 function reallyDoQuery( $offset, $limit, $ascending ) {
170 $fname = __METHOD__
. ' (' . get_class( $this ) . ')';
171 $info = $this->getQueryInfo();
172 $tables = $info['tables'];
173 $fields = $info['fields'];
174 $conds = isset( $info['conds'] ) ?
$info['conds'] : array();
175 $options = isset( $info['options'] ) ?
$info['options'] : array();
177 $options['ORDER BY'] = $this->mIndexField
;
180 $options['ORDER BY'] = $this->mIndexField
. ' DESC';
183 if ( $offset != '' ) {
184 $conds[] = $this->mIndexField
. $operator . $this->mDb
->addQuotes( $offset );
186 $options['LIMIT'] = intval( $limit );
187 $res = $this->mDb
->select( $tables, $fields, $conds, $fname, $options );
188 return new ResultWrapper( $this->mDb
, $res );
192 * Get the formatted result list. Calls getStartBody(), formatRow() and
193 * getEndBody(), concatenates the results and returns them.
196 if ( !$this->mQueryDone
) {
199 # Don't use any extra rows returned by the query
200 $numRows = min( $this->mResult
->numRows(), $this->mLimit
);
202 $s = $this->getStartBody();
204 if ( $this->mIsBackwards
) {
205 for ( $i = $numRows - 1; $i >= 0; $i-- ) {
206 $this->mResult
->seek( $i );
207 $row = $this->mResult
->fetchObject();
208 $s .= $this->formatRow( $row );
211 $this->mResult
->seek( 0 );
212 for ( $i = 0; $i < $numRows; $i++
) {
213 $row = $this->mResult
->fetchObject();
214 $s .= $this->formatRow( $row );
218 $s .= $this->getEmptyBody();
220 $s .= $this->getEndBody();
227 function makeLink($text, $query = NULL) {
228 if ( $query === null ) {
231 return $this->getSkin()->makeKnownLinkObj( $this->getTitle(), $text,
232 wfArrayToCGI( $query, $this->getDefaultQuery() ) );
237 * Hook into getBody(), allows text to be inserted at the start. This
238 * will be called even if there are no rows in the result set.
240 function getStartBody() {
245 * Hook into getBody() for the end of the list
247 function getEndBody() {
252 * Hook into getBody(), for the bit between the start and the
253 * end when there are no rows
255 function getEmptyBody() {
260 * Title used for self-links. Override this if you want to be able to
261 * use a title other than $wgTitle
263 function getTitle() {
264 return $GLOBALS['wgTitle'];
268 * Get the current skin. This can be overridden if necessary.
271 if ( !isset( $this->mSkin
) ) {
273 $this->mSkin
= $wgUser->getSkin();
279 * Get an array of query parameters that should be put into self-links.
280 * By default, all parameters passed in the URL are used, except for a
283 function getDefaultQuery() {
284 if ( !isset( $this->mDefaultQuery
) ) {
285 $this->mDefaultQuery
= $_GET;
286 unset( $this->mDefaultQuery
['title'] );
287 unset( $this->mDefaultQuery
['dir'] );
288 unset( $this->mDefaultQuery
['offset'] );
289 unset( $this->mDefaultQuery
['limit'] );
291 return $this->mDefaultQuery
;
295 * Get the number of rows in the result set
297 function getNumRows() {
298 if ( !$this->mQueryDone
) {
301 return $this->mResult
->numRows();
305 * Get a query array for the prev, next, first and last links.
307 function getPagingQueries() {
308 if ( !$this->mQueryDone
) {
312 # Don't announce the limit everywhere if it's the default
313 $urlLimit = $this->mLimit
== $this->mDefaultLimit ?
'' : $this->mLimit
;
315 if ( $this->mIsFirst
) {
319 $prev = array( 'dir' => 'prev', 'offset' => $this->mFirstShown
, 'limit' => $urlLimit );
320 $first = array( 'limit' => $urlLimit );
322 if ( $this->mIsLast
) {
326 $next = array( 'offset' => $this->mLastShown
, 'limit' => $urlLimit );
327 $last = array( 'dir' => 'prev', 'limit' => $urlLimit );
329 return array( 'prev' => $prev, 'next' => $next, 'first' => $first, 'last' => $last );
333 * Get paging links. If a link is disabled, the item from $disabledTexts will
334 * be used. If there is no such item, the unlinked text from $linkTexts will
335 * be used. Both $linkTexts and $disabledTexts are arrays of HTML.
337 function getPagingLinks( $linkTexts, $disabledTexts = array() ) {
338 $queries = $this->getPagingQueries();
340 foreach ( $queries as $type => $query ) {
341 if ( $query !== false ) {
342 $links[$type] = $this->makeLink( $linkTexts[$type], $queries[$type] );
343 } elseif ( isset( $disabledTexts[$type] ) ) {
344 $links[$type] = $disabledTexts[$type];
346 $links[$type] = $linkTexts[$type];
352 function getLimitLinks() {
355 if ( $this->mIsBackwards
) {
356 $offset = $this->mPastTheEndIndex
;
358 $offset = $this->mOffset
;
360 foreach ( $this->mLimitsShown
as $limit ) {
361 $links[] = $this->makeLink( $wgLang->formatNum( $limit ),
362 array( 'offset' => $offset, 'limit' => $limit ) );
368 * Abstract formatting function. This should return an HTML string
369 * representing the result row $row. Rows will be concatenated and
370 * returned by getBody()
372 abstract function formatRow( $row );
375 * This function should be overridden to provide all parameters
376 * needed for the main paged query. It returns an associative
377 * array with the following elements:
378 * tables => Table(s) for passing to Database::select()
379 * fields => Field(s) for passing to Database::select(), may be *
380 * conds => WHERE conditions
381 * options => option array
383 abstract function getQueryInfo();
386 * This function should be overridden to return the name of the
389 abstract function getIndexField();
394 * IndexPager with an alphabetic list and a formatted navigation bar
397 abstract class AlphabeticPager
extends IndexPager
{
398 public $mDefaultDirection = false;
400 function __construct() {
401 parent
::__construct();
405 * Shamelessly stolen bits from ReverseChronologicalPager, d
406 * didn't want to do class magic as may be still revamped
408 function getNavigationBar() {
412 'prev' => wfMsgHtml( "prevn", $this->mLimit
),
413 'next' => wfMsgHtml( 'nextn', $this->mLimit
),
414 'first' => wfMsgHtml('page_first'), /* Introduced the message */
415 'last' => wfMsgHtml( 'page_last' ) /* Introduced the message */
418 $pagingLinks = $this->getPagingLinks( $linkTexts );
419 $limitLinks = $this->getLimitLinks();
420 $limits = implode( ' | ', $limitLinks );
422 $this->mNavigationBar
= "({$pagingLinks['first']} | {$pagingLinks['last']}) " . wfMsgHtml("viewprevnext", $pagingLinks['prev'], $pagingLinks['next'], $limits);
423 return $this->mNavigationBar
;
429 * IndexPager with a formatted navigation bar
432 abstract class ReverseChronologicalPager
extends IndexPager
{
433 public $mDefaultDirection = true;
435 function __construct() {
436 parent
::__construct();
439 function getNavigationBar() {
442 if ( isset( $this->mNavigationBar
) ) {
443 return $this->mNavigationBar
;
446 'prev' => wfMsgHtml( "prevn", $this->mLimit
),
447 'next' => wfMsgHtml( 'nextn', $this->mLimit
),
448 'first' => wfMsgHtml('histlast'),
449 'last' => wfMsgHtml( 'histfirst' )
452 $pagingLinks = $this->getPagingLinks( $linkTexts );
453 $limitLinks = $this->getLimitLinks();
454 $limits = implode( ' | ', $limitLinks );
456 $this->mNavigationBar
= "({$pagingLinks['first']} | {$pagingLinks['last']}) " . wfMsgHtml("viewprevnext", $pagingLinks['prev'], $pagingLinks['next'], $limits);
457 return $this->mNavigationBar
;
462 * Table-based display with a user-selectable sort order
465 abstract class TablePager
extends IndexPager
{
469 function __construct() {
471 $this->mSort
= $wgRequest->getText( 'sort' );
472 if ( !array_key_exists( $this->mSort
, $this->getFieldNames() ) ) {
473 $this->mSort
= $this->getDefaultSort();
475 if ( $wgRequest->getBool( 'asc' ) ) {
476 $this->mDefaultDirection
= false;
477 } elseif ( $wgRequest->getBool( 'desc' ) ) {
478 $this->mDefaultDirection
= true;
479 } /* Else leave it at whatever the class default is */
481 parent
::__construct();
484 function getStartBody() {
486 $tableClass = htmlspecialchars( $this->getTableClass() );
487 $sortClass = htmlspecialchars( $this->getSortHeaderClass() );
489 $s = "<table border='1' class=\"$tableClass\"><thead><tr>\n";
490 $fields = $this->getFieldNames();
493 foreach ( $fields as $field => $name ) {
494 if ( strval( $name ) == '' ) {
495 $s .= "<th> </th>\n";
496 } elseif ( $this->isFieldSortable( $field ) ) {
497 $query = array( 'sort' => $field, 'limit' => $this->mLimit
);
498 if ( $field == $this->mSort
) {
499 # This is the sorted column
500 # Prepare a link that goes in the other sort order
501 if ( $this->mDefaultDirection
) {
503 $image = 'Arr_u.png';
506 $alt = htmlspecialchars( wfMsg( 'descending_abbrev' ) );
509 $image = 'Arr_d.png';
511 $query['desc'] = '1';
512 $alt = htmlspecialchars( wfMsg( 'ascending_abbrev' ) );
514 $image = htmlspecialchars( "$wgStylePath/common/images/$image" );
515 $link = $this->makeLink(
516 "<img width=\"12\" height=\"12\" alt=\"$alt\" src=\"$image\" />" .
517 htmlspecialchars( $name ), $query );
518 $s .= "<th class=\"$sortClass\">$link</th>\n";
520 $s .= '<th>' . $this->makeLink( htmlspecialchars( $name ), $query ) . "</th>\n";
523 $s .= '<th>' . htmlspecialchars( $name ) . "</th>\n";
526 $s .= "</tr></thead><tbody>\n";
530 function getEndBody() {
531 return "</tbody></table>\n";
534 function getEmptyBody() {
535 $colspan = count( $this->getFieldNames() );
536 $msgEmpty = wfMsgHtml( 'table_pager_empty' );
537 return "<tr><td colspan=\"$colspan\">$msgEmpty</td></tr>\n";
540 function formatRow( $row ) {
542 $fieldNames = $this->getFieldNames();
543 $this->mCurrentRow
= $row; # In case formatValue needs to know
544 foreach ( $fieldNames as $field => $name ) {
545 $value = isset( $row->$field ) ?
$row->$field : null;
546 $formatted = strval( $this->formatValue( $field, $value ) );
547 if ( $formatted == '' ) {
548 $formatted = ' ';
550 $class = 'TablePager_col_' . htmlspecialchars( $field );
551 $s .= "<td class=\"$class\">$formatted</td>\n";
557 function getIndexField() {
561 function getTableClass() {
565 function getNavClass() {
566 return 'TablePager_nav';
569 function getSortHeaderClass() {
570 return 'TablePager_sort';
574 * A navigation bar with images
576 function getNavigationBar() {
577 global $wgStylePath, $wgContLang;
578 $path = "$wgStylePath/common/images";
580 'first' => 'table_pager_first',
581 'prev' => 'table_pager_prev',
582 'next' => 'table_pager_next',
583 'last' => 'table_pager_last',
586 'first' => $wgContLang->isRTL() ?
'arrow_last_25.png' : 'arrow_first_25.png',
587 'prev' => $wgContLang->isRTL() ?
'arrow_right_25.png' : 'arrow_left_25.png',
588 'next' => $wgContLang->isRTL() ?
'arrow_left_25.png' : 'arrow_right_25.png',
589 'last' => $wgContLang->isRTL() ?
'arrow_first_25.png' : 'arrow_last_25.png',
591 $disabledImages = array(
592 'first' => $wgContLang->isRTL() ?
'arrow_disabled_last_25.png' : 'arrow_disabled_first_25.png',
593 'prev' => $wgContLang->isRTL() ?
'arrow_disabled_right_25.png' : 'arrow_disabled_left_25.png',
594 'next' => $wgContLang->isRTL() ?
'arrow_disabled_left_25.png' : 'arrow_disabled_right_25.png',
595 'last' => $wgContLang->isRTL() ?
'arrow_disabled_first_25.png' : 'arrow_disabled_last_25.png',
598 $linkTexts = array();
599 $disabledTexts = array();
600 foreach ( $labels as $type => $label ) {
601 $msgLabel = wfMsgHtml( $label );
602 $linkTexts[$type] = "<img src=\"$path/{$images[$type]}\" alt=\"$msgLabel\"/><br/>$msgLabel";
603 $disabledTexts[$type] = "<img src=\"$path/{$disabledImages[$type]}\" alt=\"$msgLabel\"/><br/>$msgLabel";
605 $links = $this->getPagingLinks( $linkTexts, $disabledTexts );
607 $navClass = htmlspecialchars( $this->getNavClass() );
608 $s = "<table class=\"$navClass\" align=\"center\" cellpadding=\"3\"><tr>\n";
609 $cellAttrs = 'valign="top" align="center" width="' . 100 / count( $links ) . '%"';
610 foreach ( $labels as $type => $label ) {
611 $s .= "<td $cellAttrs>{$links[$type]}</td>\n";
613 $s .= "</tr></table>\n";
618 * Get a <select> element which has options for each of the allowed limits
620 function getLimitSelect() {
622 $s = "<select name=\"limit\">";
623 foreach ( $this->mLimitsShown
as $limit ) {
624 $selected = $limit == $this->mLimit ?
'selected="selected"' : '';
625 $formattedLimit = $wgLang->formatNum( $limit );
626 $s .= "<option value=\"$limit\" $selected>$formattedLimit</option>\n";
633 * Get <input type="hidden"> elements for use in a method="get" form.
634 * Resubmits all defined elements of the $_GET array, except for a
635 * blacklist, passed in the $blacklist parameter.
637 function getHiddenFields( $blacklist = array() ) {
638 $blacklist = (array)$blacklist;
640 foreach ( $blacklist as $name ) {
641 unset( $query[$name] );
644 foreach ( $query as $name => $value ) {
645 $encName = htmlspecialchars( $name );
646 $encValue = htmlspecialchars( $value );
647 $s .= "<input type=\"hidden\" name=\"$encName\" value=\"$encValue\"/>\n";
653 * Get a form containing a limit selection dropdown
655 function getLimitForm() {
656 # Make the select with some explanatory text
657 $url = $this->getTitle()->escapeLocalURL();
658 $msgSubmit = wfMsgHtml( 'table_pager_limit_submit' );
660 "<form method=\"get\" action=\"$url\">" .
661 wfMsgHtml( 'table_pager_limit', $this->getLimitSelect() ) .
662 "\n<input type=\"submit\" value=\"$msgSubmit\"/>\n" .
663 $this->getHiddenFields( 'limit' ) .
668 * Return true if the named field should be sortable by the UI, false otherwise
669 * @param string $field
671 abstract function isFieldSortable( $field );
674 * Format a table cell. The return value should be HTML, but use an empty string
675 * not for empty cells. Do not include the <td> and </td>.
677 * @param string $name The database field name
678 * @param string $value The value retrieved from the database
680 * The current result row is available as $this->mCurrentRow, in case you need
683 abstract function formatValue( $name, $value );
686 * The database field name used as a default sort order
688 abstract function getDefaultSort();
691 * An array mapping database field names to a textual description of the field
692 * name, for use in the table header. The description should be plain text, it
693 * will be HTML-escaped later.
695 abstract function getFieldNames();