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']}) " .
457 wfMsgHtml("viewprevnext", $pagingLinks['prev'], $pagingLinks['next'], $limits);
458 return $this->mNavigationBar
;
463 * Table-based display with a user-selectable sort order
466 abstract class TablePager
extends IndexPager
{
470 function __construct() {
472 $this->mSort
= $wgRequest->getText( 'sort' );
473 if ( !array_key_exists( $this->mSort
, $this->getFieldNames() ) ) {
474 $this->mSort
= $this->getDefaultSort();
476 if ( $wgRequest->getBool( 'asc' ) ) {
477 $this->mDefaultDirection
= false;
478 } elseif ( $wgRequest->getBool( 'desc' ) ) {
479 $this->mDefaultDirection
= true;
480 } /* Else leave it at whatever the class default is */
482 parent
::__construct();
485 function getStartBody() {
487 $tableClass = htmlspecialchars( $this->getTableClass() );
488 $sortClass = htmlspecialchars( $this->getSortHeaderClass() );
490 $s = "<table border='1' class=\"$tableClass\"><thead><tr>\n";
491 $fields = $this->getFieldNames();
494 foreach ( $fields as $field => $name ) {
495 if ( strval( $name ) == '' ) {
496 $s .= "<th> </th>\n";
497 } elseif ( $this->isFieldSortable( $field ) ) {
498 $query = array( 'sort' => $field, 'limit' => $this->mLimit
);
499 if ( $field == $this->mSort
) {
500 # This is the sorted column
501 # Prepare a link that goes in the other sort order
502 if ( $this->mDefaultDirection
) {
504 $image = 'Arr_u.png';
507 $alt = htmlspecialchars( wfMsg( 'descending_abbrev' ) );
510 $image = 'Arr_d.png';
512 $query['desc'] = '1';
513 $alt = htmlspecialchars( wfMsg( 'ascending_abbrev' ) );
515 $image = htmlspecialchars( "$wgStylePath/common/images/$image" );
516 $link = $this->makeLink(
517 "<img width=\"12\" height=\"12\" alt=\"$alt\" src=\"$image\" />" .
518 htmlspecialchars( $name ), $query );
519 $s .= "<th class=\"$sortClass\">$link</th>\n";
521 $s .= '<th>' . $this->makeLink( htmlspecialchars( $name ), $query ) . "</th>\n";
524 $s .= '<th>' . htmlspecialchars( $name ) . "</th>\n";
527 $s .= "</tr></thead><tbody>\n";
531 function getEndBody() {
532 return "</tbody></table>\n";
535 function getEmptyBody() {
536 $colspan = count( $this->getFieldNames() );
537 $msgEmpty = wfMsgHtml( 'table_pager_empty' );
538 return "<tr><td colspan=\"$colspan\">$msgEmpty</td></tr>\n";
541 function formatRow( $row ) {
543 $fieldNames = $this->getFieldNames();
544 $this->mCurrentRow
= $row; # In case formatValue needs to know
545 foreach ( $fieldNames as $field => $name ) {
546 $value = isset( $row->$field ) ?
$row->$field : null;
547 $formatted = strval( $this->formatValue( $field, $value ) );
548 if ( $formatted == '' ) {
549 $formatted = ' ';
551 $class = 'TablePager_col_' . htmlspecialchars( $field );
552 $s .= "<td class=\"$class\">$formatted</td>\n";
558 function getIndexField() {
562 function getTableClass() {
566 function getNavClass() {
567 return 'TablePager_nav';
570 function getSortHeaderClass() {
571 return 'TablePager_sort';
575 * A navigation bar with images
577 function getNavigationBar() {
578 global $wgStylePath, $wgContLang;
579 $path = "$wgStylePath/common/images";
581 'first' => 'table_pager_first',
582 'prev' => 'table_pager_prev',
583 'next' => 'table_pager_next',
584 'last' => 'table_pager_last',
587 'first' => $wgContLang->isRTL() ?
'arrow_last_25.png' : 'arrow_first_25.png',
588 'prev' => $wgContLang->isRTL() ?
'arrow_right_25.png' : 'arrow_left_25.png',
589 'next' => $wgContLang->isRTL() ?
'arrow_left_25.png' : 'arrow_right_25.png',
590 'last' => $wgContLang->isRTL() ?
'arrow_first_25.png' : 'arrow_last_25.png',
592 $disabledImages = array(
593 'first' => $wgContLang->isRTL() ?
'arrow_disabled_last_25.png' : 'arrow_disabled_first_25.png',
594 'prev' => $wgContLang->isRTL() ?
'arrow_disabled_right_25.png' : 'arrow_disabled_left_25.png',
595 'next' => $wgContLang->isRTL() ?
'arrow_disabled_left_25.png' : 'arrow_disabled_right_25.png',
596 'last' => $wgContLang->isRTL() ?
'arrow_disabled_first_25.png' : 'arrow_disabled_last_25.png',
599 $linkTexts = array();
600 $disabledTexts = array();
601 foreach ( $labels as $type => $label ) {
602 $msgLabel = wfMsgHtml( $label );
603 $linkTexts[$type] = "<img src=\"$path/{$images[$type]}\" alt=\"$msgLabel\"/><br/>$msgLabel";
604 $disabledTexts[$type] = "<img src=\"$path/{$disabledImages[$type]}\" alt=\"$msgLabel\"/><br/>$msgLabel";
606 $links = $this->getPagingLinks( $linkTexts, $disabledTexts );
608 $navClass = htmlspecialchars( $this->getNavClass() );
609 $s = "<table class=\"$navClass\" align=\"center\" cellpadding=\"3\"><tr>\n";
610 $cellAttrs = 'valign="top" align="center" width="' . 100 / count( $links ) . '%"';
611 foreach ( $labels as $type => $label ) {
612 $s .= "<td $cellAttrs>{$links[$type]}</td>\n";
614 $s .= "</tr></table>\n";
619 * Get a <select> element which has options for each of the allowed limits
621 function getLimitSelect() {
623 $s = "<select name=\"limit\">";
624 foreach ( $this->mLimitsShown
as $limit ) {
625 $selected = $limit == $this->mLimit ?
'selected="selected"' : '';
626 $formattedLimit = $wgLang->formatNum( $limit );
627 $s .= "<option value=\"$limit\" $selected>$formattedLimit</option>\n";
634 * Get <input type="hidden"> elements for use in a method="get" form.
635 * Resubmits all defined elements of the $_GET array, except for a
636 * blacklist, passed in the $blacklist parameter.
638 function getHiddenFields( $blacklist = array() ) {
639 $blacklist = (array)$blacklist;
641 foreach ( $blacklist as $name ) {
642 unset( $query[$name] );
645 foreach ( $query as $name => $value ) {
646 $encName = htmlspecialchars( $name );
647 $encValue = htmlspecialchars( $value );
648 $s .= "<input type=\"hidden\" name=\"$encName\" value=\"$encValue\"/>\n";
654 * Get a form containing a limit selection dropdown
656 function getLimitForm() {
657 # Make the select with some explanatory text
658 $url = $this->getTitle()->escapeLocalURL();
659 $msgSubmit = wfMsgHtml( 'table_pager_limit_submit' );
661 "<form method=\"get\" action=\"$url\">" .
662 wfMsgHtml( 'table_pager_limit', $this->getLimitSelect() ) .
663 "\n<input type=\"submit\" value=\"$msgSubmit\"/>\n" .
664 $this->getHiddenFields( 'limit' ) .
669 * Return true if the named field should be sortable by the UI, false otherwise
670 * @param string $field
672 abstract function isFieldSortable( $field );
675 * Format a table cell. The return value should be HTML, but use an empty string
676 * not for empty cells. Do not include the <td> and </td>.
678 * @param string $name The database field name
679 * @param string $value The value retrieved from the database
681 * The current result row is available as $this->mCurrentRow, in case you need
684 abstract function formatValue( $name, $value );
687 * The database field name used as a default sort order
689 abstract function getDefaultSort();
692 * An array mapping database field names to a textual description of the field
693 * name, for use in the table header. The description should be plain text, it
694 * will be HTML-escaped later.
696 abstract function getFieldNames();