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
16 * specified number of offset rows to find the desired data, which can be
17 * expensive for large offsets.
19 * ReverseChronologicalPager is a child class of the abstract IndexPager, and
20 * contains some formatting and display code which is specific to the use of
21 * timestamps as indexes. Here is a synopsis of its operation:
23 * * The query is specified by the offset, limit and direction (dir)
24 * parameters, in addition to any subclass-specific parameters.
25 * * The offset is the non-inclusive start of the DB query. A row with an
26 * index value equal to the offset will never be shown.
27 * * The query may either be done backwards, where the rows are returned by
28 * the database in the opposite order to which they are displayed to the
29 * user, or forwards. This is specified by the "dir" parameter, dir=prev
30 * means backwards, anything else means forwards. The offset value
31 * specifies the start of the database result set, which may be either
32 * 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
34 * start of the previous page.
35 * * An additional row beyond the user-specified limit is always requested.
36 * This allows us to tell whether we should display a "next" link in the
37 * case of forwards mode, or a "previous" link in the case of backwards
38 * mode. Determining whether to display the other link (the one for the
39 * page before the start of the database result set) can be done
40 * heuristically by examining the offset.
42 * * An empty offset indicates that the offset condition should be omitted
43 * from the query. This naturally produces either the first page or the
44 * last page depending on the dir parameter.
46 * Subclassing the pager to implement concrete functionality should be fairly
47 * simple, please see the examples in PageHistory.php and
48 * SpecialIpblocklist.php. You just need to override formatRow(),
49 * getQueryInfo() and getIndexField(). Don't forget to call the parent
50 * constructor if you override it.
54 abstract class IndexPager
implements Pager
{
56 public $mLimitsShown = array( 20, 50, 100, 250, 500 );
57 public $mDefaultLimit = 50;
58 public $mOffset, $mLimit;
59 public $mQueryDone = false;
61 public $mPastTheEndRow;
63 protected $mIndexField;
66 * Default query direction. false for ascending, true for descending
68 public $mDefaultDirection = false;
71 * Result object for the query. Warning: seek before use.
75 function __construct() {
76 global $wgRequest, $wgUser;
77 $this->mRequest
= $wgRequest;
79 # NB: the offset is quoted, not validated. It is treated as an
80 # arbitrary string to support the widest variety of index types. Be
81 # careful outputting it into HTML!
82 $this->mOffset
= $this->mRequest
->getText( 'offset' );
84 # Use consistent behavior for the limit options
85 $this->mDefaultLimit
= intval( $wgUser->getOption( 'rclimit' ) );
86 list( $this->mLimit
, /* $offset */ ) = $this->mRequest
->getLimitOffset();
88 $this->mIsBackwards
= ( $this->mRequest
->getVal( 'dir' ) == 'prev' );
89 $this->mIndexField
= $this->getIndexField();
90 $this->mDb
= wfGetDB( DB_SLAVE
);
94 * Do the query, using information from the object context. This function
95 * has been kept minimal to make it overridable if necessary, to allow for
96 * result sets formed from multiple DB queries.
99 # Use the child class name for profiling
100 $fname = __METHOD__
. ' (' . get_class( $this ) . ')';
101 wfProfileIn( $fname );
103 $descending = ( $this->mIsBackwards
== $this->mDefaultDirection
);
104 # Plus an extra row so that we can tell the "next" link should be shown
105 $queryLimit = $this->mLimit +
1;
107 $this->mResult
= $this->reallyDoQuery( $this->mOffset
, $queryLimit, $descending );
108 $this->extractResultInfo( $this->mOffset
, $queryLimit, $this->mResult
);
109 $this->mQueryDone
= true;
111 $this->preprocessResults( $this->mResult
);
112 $this->mResult
->rewind(); // Paranoia
114 wfProfileOut( $fname );
118 * Extract some useful data from the result object for use by
119 * the navigation bar, put it into $this
121 function extractResultInfo( $offset, $limit, ResultWrapper
$res ) {
122 $numRows = $res->numRows();
124 $row = $res->fetchRow();
125 $firstIndex = $row[$this->mIndexField
];
127 # Discard the extra result row if there is one
128 if ( $numRows > $this->mLimit
&& $numRows > 1 ) {
129 $res->seek( $numRows - 1 );
130 $this->mPastTheEndRow
= $res->fetchObject();
131 $indexField = $this->mIndexField
;
132 $this->mPastTheEndIndex
= $this->mPastTheEndRow
->$indexField;
133 $res->seek( $numRows - 2 );
134 $row = $res->fetchRow();
135 $lastIndex = $row[$this->mIndexField
];
137 $this->mPastTheEndRow
= null;
138 # Setting indexes to an empty string means that they will be
139 # omitted if they would otherwise appear in URLs. It just so
140 # happens that this is the right thing to do in the standard
141 # UI, in all the relevant cases.
142 $this->mPastTheEndIndex
= '';
143 $res->seek( $numRows - 1 );
144 $row = $res->fetchRow();
145 $lastIndex = $row[$this->mIndexField
];
150 $this->mPastTheEndRow
= null;
151 $this->mPastTheEndIndex
= '';
154 if ( $this->mIsBackwards
) {
155 $this->mIsFirst
= ( $numRows < $limit );
156 $this->mIsLast
= ( $offset == '' );
157 $this->mLastShown
= $firstIndex;
158 $this->mFirstShown
= $lastIndex;
160 $this->mIsFirst
= ( $offset == '' );
161 $this->mIsLast
= ( $numRows < $limit );
162 $this->mLastShown
= $lastIndex;
163 $this->mFirstShown
= $firstIndex;
168 * Do a query with specified parameters, rather than using the object
171 * @param string $offset Index offset, inclusive
172 * @param integer $limit Exact query limit
173 * @param boolean $descending Query direction, false for ascending, true for descending
174 * @return ResultWrapper
176 function reallyDoQuery( $offset, $limit, $descending ) {
177 $fname = __METHOD__
. ' (' . get_class( $this ) . ')';
178 $info = $this->getQueryInfo();
179 $tables = $info['tables'];
180 $fields = $info['fields'];
181 $conds = isset( $info['conds'] ) ?
$info['conds'] : array();
182 $options = isset( $info['options'] ) ?
$info['options'] : array();
184 $options['ORDER BY'] = $this->mIndexField
;
187 $options['ORDER BY'] = $this->mIndexField
. ' DESC';
190 if ( $offset != '' ) {
191 $conds[] = $this->mIndexField
. $operator . $this->mDb
->addQuotes( $offset );
193 $options['LIMIT'] = intval( $limit );
194 $res = $this->mDb
->select( $tables, $fields, $conds, $fname, $options );
195 return new ResultWrapper( $this->mDb
, $res );
199 * Pre-process results; useful for performing batch existence checks, etc.
201 * @param ResultWrapper $result Result wrapper
203 protected function preprocessResults( $result ) {}
206 * Get the formatted result list. Calls getStartBody(), formatRow() and
207 * getEndBody(), concatenates the results and returns them.
210 if ( !$this->mQueryDone
) {
213 # Don't use any extra rows returned by the query
214 $numRows = min( $this->mResult
->numRows(), $this->mLimit
);
216 $s = $this->getStartBody();
218 if ( $this->mIsBackwards
) {
219 for ( $i = $numRows - 1; $i >= 0; $i-- ) {
220 $this->mResult
->seek( $i );
221 $row = $this->mResult
->fetchObject();
222 $s .= $this->formatRow( $row );
225 $this->mResult
->seek( 0 );
226 for ( $i = 0; $i < $numRows; $i++
) {
227 $row = $this->mResult
->fetchObject();
228 $s .= $this->formatRow( $row );
232 $s .= $this->getEmptyBody();
234 $s .= $this->getEndBody();
241 function makeLink($text, $query = NULL) {
242 if ( $query === null ) {
245 return $this->getSkin()->makeKnownLinkObj( $this->getTitle(), $text,
246 wfArrayToCGI( $query, $this->getDefaultQuery() ) );
251 * Hook into getBody(), allows text to be inserted at the start. This
252 * will be called even if there are no rows in the result set.
254 function getStartBody() {
259 * Hook into getBody() for the end of the list
261 function getEndBody() {
266 * Hook into getBody(), for the bit between the start and the
267 * end when there are no rows
269 function getEmptyBody() {
274 * Title used for self-links. Override this if you want to be able to
275 * use a title other than $wgTitle
277 function getTitle() {
278 return $GLOBALS['wgTitle'];
282 * Get the current skin. This can be overridden if necessary.
285 if ( !isset( $this->mSkin
) ) {
287 $this->mSkin
= $wgUser->getSkin();
293 * Get an array of query parameters that should be put into self-links.
294 * By default, all parameters passed in the URL are used, except for a
297 function getDefaultQuery() {
298 if ( !isset( $this->mDefaultQuery
) ) {
299 $this->mDefaultQuery
= $_GET;
300 unset( $this->mDefaultQuery
['title'] );
301 unset( $this->mDefaultQuery
['dir'] );
302 unset( $this->mDefaultQuery
['offset'] );
303 unset( $this->mDefaultQuery
['limit'] );
305 return $this->mDefaultQuery
;
309 * Get the number of rows in the result set
311 function getNumRows() {
312 if ( !$this->mQueryDone
) {
315 return $this->mResult
->numRows();
319 * Get a query array for the prev, next, first and last links.
321 function getPagingQueries() {
322 if ( !$this->mQueryDone
) {
326 # Don't announce the limit everywhere if it's the default
327 $urlLimit = $this->mLimit
== $this->mDefaultLimit ?
'' : $this->mLimit
;
329 if ( $this->mIsFirst
) {
333 $prev = array( 'dir' => 'prev', 'offset' => $this->mFirstShown
, 'limit' => $urlLimit );
334 $first = array( 'limit' => $urlLimit );
336 if ( $this->mIsLast
) {
340 $next = array( 'offset' => $this->mLastShown
, 'limit' => $urlLimit );
341 $last = array( 'dir' => 'prev', 'limit' => $urlLimit );
343 return array( 'prev' => $prev, 'next' => $next, 'first' => $first, 'last' => $last );
347 * Get paging links. If a link is disabled, the item from $disabledTexts
348 * will be used. If there is no such item, the unlinked text from
349 * $linkTexts will be used. Both $linkTexts and $disabledTexts are arrays
352 function getPagingLinks( $linkTexts, $disabledTexts = array() ) {
353 $queries = $this->getPagingQueries();
355 foreach ( $queries as $type => $query ) {
356 if ( $query !== false ) {
357 $links[$type] = $this->makeLink( $linkTexts[$type], $queries[$type] );
358 } elseif ( isset( $disabledTexts[$type] ) ) {
359 $links[$type] = $disabledTexts[$type];
361 $links[$type] = $linkTexts[$type];
367 function getLimitLinks() {
370 if ( $this->mIsBackwards
) {
371 $offset = $this->mPastTheEndIndex
;
373 $offset = $this->mOffset
;
375 foreach ( $this->mLimitsShown
as $limit ) {
376 $links[] = $this->makeLink( $wgLang->formatNum( $limit ),
377 array( 'offset' => $offset, 'limit' => $limit ) );
383 * Abstract formatting function. This should return an HTML string
384 * representing the result row $row. Rows will be concatenated and
385 * returned by getBody()
387 abstract function formatRow( $row );
390 * This function should be overridden to provide all parameters
391 * needed for the main paged query. It returns an associative
392 * array with the following elements:
393 * tables => Table(s) for passing to Database::select()
394 * fields => Field(s) for passing to Database::select(), may be *
395 * conds => WHERE conditions
396 * options => option array
398 abstract function getQueryInfo();
401 * This function should be overridden to return the name of the
404 abstract function getIndexField();
409 * IndexPager with an alphabetic list and a formatted navigation bar
412 abstract class AlphabeticPager
extends IndexPager
{
413 public $mDefaultDirection = false;
415 function __construct() {
416 parent
::__construct();
420 * Shamelessly stolen bits from ReverseChronologicalPager, d
421 * didn't want to do class magic as may be still revamped
423 function getNavigationBar() {
427 'prev' => wfMsgHtml( 'prevn', $wgLang->formatNum( $this->mLimit
) ),
428 'next' => wfMsgHtml( 'nextn', $wgLang->formatNum($this->mLimit
) ),
429 'first' => wfMsgHtml( 'page_first' ), /* Introduced the message */
430 'last' => wfMsgHtml( 'page_last' ) /* Introduced the message */
433 $pagingLinks = $this->getPagingLinks( $linkTexts );
434 $limitLinks = $this->getLimitLinks();
435 $limits = implode( ' | ', $limitLinks );
437 $this->mNavigationBar
= "({$pagingLinks['first']} | {$pagingLinks['last']}) " . wfMsgHtml("viewprevnext", $pagingLinks['prev'], $pagingLinks['next'], $limits);
438 return $this->mNavigationBar
;
444 * IndexPager with a formatted navigation bar
447 abstract class ReverseChronologicalPager
extends IndexPager
{
448 public $mDefaultDirection = true;
450 function __construct() {
451 parent
::__construct();
454 function getNavigationBar() {
457 if ( isset( $this->mNavigationBar
) ) {
458 return $this->mNavigationBar
;
461 'prev' => wfMsgHtml( 'prevn', $wgLang->formatNum( $this->mLimit
) ),
462 'next' => wfMsgHtml( 'nextn', $wgLang->formatNum( $this->mLimit
) ),
463 'first' => wfMsgHtml( 'histlast' ),
464 'last' => wfMsgHtml( 'histfirst' )
467 $pagingLinks = $this->getPagingLinks( $linkTexts );
468 $limitLinks = $this->getLimitLinks();
469 $limits = implode( ' | ', $limitLinks );
471 $this->mNavigationBar
= "({$pagingLinks['first']} | {$pagingLinks['last']}) " .
472 wfMsgHtml("viewprevnext", $pagingLinks['prev'], $pagingLinks['next'], $limits);
473 return $this->mNavigationBar
;
478 * Table-based display with a user-selectable sort order
481 abstract class TablePager
extends IndexPager
{
485 function __construct() {
487 $this->mSort
= $wgRequest->getText( 'sort' );
488 if ( !array_key_exists( $this->mSort
, $this->getFieldNames() ) ) {
489 $this->mSort
= $this->getDefaultSort();
491 if ( $wgRequest->getBool( 'asc' ) ) {
492 $this->mDefaultDirection
= false;
493 } elseif ( $wgRequest->getBool( 'desc' ) ) {
494 $this->mDefaultDirection
= true;
495 } /* Else leave it at whatever the class default is */
497 parent
::__construct();
500 function getStartBody() {
502 $tableClass = htmlspecialchars( $this->getTableClass() );
503 $sortClass = htmlspecialchars( $this->getSortHeaderClass() );
505 $s = "<table border='1' class=\"$tableClass\"><thead><tr>\n";
506 $fields = $this->getFieldNames();
509 foreach ( $fields as $field => $name ) {
510 if ( strval( $name ) == '' ) {
511 $s .= "<th> </th>\n";
512 } elseif ( $this->isFieldSortable( $field ) ) {
513 $query = array( 'sort' => $field, 'limit' => $this->mLimit
);
514 if ( $field == $this->mSort
) {
515 # This is the sorted column
516 # Prepare a link that goes in the other sort order
517 if ( $this->mDefaultDirection
) {
519 $image = 'Arr_u.png';
522 $alt = htmlspecialchars( wfMsg( 'descending_abbrev' ) );
525 $image = 'Arr_d.png';
527 $query['desc'] = '1';
528 $alt = htmlspecialchars( wfMsg( 'ascending_abbrev' ) );
530 $image = htmlspecialchars( "$wgStylePath/common/images/$image" );
531 $link = $this->makeLink(
532 "<img width=\"12\" height=\"12\" alt=\"$alt\" src=\"$image\" />" .
533 htmlspecialchars( $name ), $query );
534 $s .= "<th class=\"$sortClass\">$link</th>\n";
536 $s .= '<th>' . $this->makeLink( htmlspecialchars( $name ), $query ) . "</th>\n";
539 $s .= '<th>' . htmlspecialchars( $name ) . "</th>\n";
542 $s .= "</tr></thead><tbody>\n";
546 function getEndBody() {
547 return "</tbody></table>\n";
550 function getEmptyBody() {
551 $colspan = count( $this->getFieldNames() );
552 $msgEmpty = wfMsgHtml( 'table_pager_empty' );
553 return "<tr><td colspan=\"$colspan\">$msgEmpty</td></tr>\n";
556 function formatRow( $row ) {
558 $fieldNames = $this->getFieldNames();
559 $this->mCurrentRow
= $row; # In case formatValue needs to know
560 foreach ( $fieldNames as $field => $name ) {
561 $value = isset( $row->$field ) ?
$row->$field : null;
562 $formatted = strval( $this->formatValue( $field, $value ) );
563 if ( $formatted == '' ) {
564 $formatted = ' ';
566 $class = 'TablePager_col_' . htmlspecialchars( $field );
567 $s .= "<td class=\"$class\">$formatted</td>\n";
573 function getIndexField() {
577 function getTableClass() {
581 function getNavClass() {
582 return 'TablePager_nav';
585 function getSortHeaderClass() {
586 return 'TablePager_sort';
590 * A navigation bar with images
592 function getNavigationBar() {
593 global $wgStylePath, $wgContLang;
594 $path = "$wgStylePath/common/images";
596 'first' => 'table_pager_first',
597 'prev' => 'table_pager_prev',
598 'next' => 'table_pager_next',
599 'last' => 'table_pager_last',
602 'first' => $wgContLang->isRTL() ?
'arrow_last_25.png' : 'arrow_first_25.png',
603 'prev' => $wgContLang->isRTL() ?
'arrow_right_25.png' : 'arrow_left_25.png',
604 'next' => $wgContLang->isRTL() ?
'arrow_left_25.png' : 'arrow_right_25.png',
605 'last' => $wgContLang->isRTL() ?
'arrow_first_25.png' : 'arrow_last_25.png',
607 $disabledImages = array(
608 'first' => $wgContLang->isRTL() ?
'arrow_disabled_last_25.png' : 'arrow_disabled_first_25.png',
609 'prev' => $wgContLang->isRTL() ?
'arrow_disabled_right_25.png' : 'arrow_disabled_left_25.png',
610 'next' => $wgContLang->isRTL() ?
'arrow_disabled_left_25.png' : 'arrow_disabled_right_25.png',
611 'last' => $wgContLang->isRTL() ?
'arrow_disabled_first_25.png' : 'arrow_disabled_last_25.png',
614 $linkTexts = array();
615 $disabledTexts = array();
616 foreach ( $labels as $type => $label ) {
617 $msgLabel = wfMsgHtml( $label );
618 $linkTexts[$type] = "<img src=\"$path/{$images[$type]}\" alt=\"$msgLabel\"/><br/>$msgLabel";
619 $disabledTexts[$type] = "<img src=\"$path/{$disabledImages[$type]}\" alt=\"$msgLabel\"/><br/>$msgLabel";
621 $links = $this->getPagingLinks( $linkTexts, $disabledTexts );
623 $navClass = htmlspecialchars( $this->getNavClass() );
624 $s = "<table class=\"$navClass\" align=\"center\" cellpadding=\"3\"><tr>\n";
625 $cellAttrs = 'valign="top" align="center" width="' . 100 / count( $links ) . '%"';
626 foreach ( $labels as $type => $label ) {
627 $s .= "<td $cellAttrs>{$links[$type]}</td>\n";
629 $s .= "</tr></table>\n";
634 * Get a <select> element which has options for each of the allowed limits
636 function getLimitSelect() {
638 $s = "<select name=\"limit\">";
639 foreach ( $this->mLimitsShown
as $limit ) {
640 $selected = $limit == $this->mLimit ?
'selected="selected"' : '';
641 $formattedLimit = $wgLang->formatNum( $limit );
642 $s .= "<option value=\"$limit\" $selected>$formattedLimit</option>\n";
649 * Get <input type="hidden"> elements for use in a method="get" form.
650 * Resubmits all defined elements of the $_GET array, except for a
651 * blacklist, passed in the $blacklist parameter.
653 function getHiddenFields( $blacklist = array() ) {
654 $blacklist = (array)$blacklist;
656 foreach ( $blacklist as $name ) {
657 unset( $query[$name] );
660 foreach ( $query as $name => $value ) {
661 $encName = htmlspecialchars( $name );
662 $encValue = htmlspecialchars( $value );
663 $s .= "<input type=\"hidden\" name=\"$encName\" value=\"$encValue\"/>\n";
669 * Get a form containing a limit selection dropdown
671 function getLimitForm() {
672 # Make the select with some explanatory text
673 $url = $this->getTitle()->escapeLocalURL();
674 $msgSubmit = wfMsgHtml( 'table_pager_limit_submit' );
676 "<form method=\"get\" action=\"$url\">" .
677 wfMsgHtml( 'table_pager_limit', $this->getLimitSelect() ) .
678 "\n<input type=\"submit\" value=\"$msgSubmit\"/>\n" .
679 $this->getHiddenFields( 'limit' ) .
684 * Return true if the named field should be sortable by the UI, false
687 * @param string $field
689 abstract function isFieldSortable( $field );
692 * Format a table cell. The return value should be HTML, but use an empty
693 * string not for empty cells. Do not include the <td> and </td>.
695 * The current result row is available as $this->mCurrentRow, in case you
698 * @param string $name The database field name
699 * @param string $value The value retrieved from the database
701 abstract function formatValue( $name, $value );
704 * The database field name used as a default sort order
706 abstract function getDefaultSort();
709 * An array mapping database field names to a textual description of the
710 * field name, for use in the table header. The description should be plain
711 * text, it will be HTML-escaped later.
713 abstract function getFieldNames();