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
;
460 $nicenumber = $wgLang->formatNum( $this->mLimit
);
462 'prev' => wfMsgExt( 'pager-newer-n', array( 'parsemag' ), $nicenumber ),
463 'next' => wfMsgExt( 'pager-older-n', array( 'parsemag' ), $nicenumber ),
464 'first' => wfMsgHtml( 'histlast' ),
465 'last' => wfMsgHtml( 'histfirst' )
468 $pagingLinks = $this->getPagingLinks( $linkTexts );
469 $limitLinks = $this->getLimitLinks();
470 $limits = implode( ' | ', $limitLinks );
472 $this->mNavigationBar
= "({$pagingLinks['first']} | {$pagingLinks['last']}) " .
473 wfMsgHtml("viewprevnext", $pagingLinks['prev'], $pagingLinks['next'], $limits);
474 return $this->mNavigationBar
;
479 * Table-based display with a user-selectable sort order
482 abstract class TablePager
extends IndexPager
{
486 function __construct() {
488 $this->mSort
= $wgRequest->getText( 'sort' );
489 if ( !array_key_exists( $this->mSort
, $this->getFieldNames() ) ) {
490 $this->mSort
= $this->getDefaultSort();
492 if ( $wgRequest->getBool( 'asc' ) ) {
493 $this->mDefaultDirection
= false;
494 } elseif ( $wgRequest->getBool( 'desc' ) ) {
495 $this->mDefaultDirection
= true;
496 } /* Else leave it at whatever the class default is */
498 parent
::__construct();
501 function getStartBody() {
503 $tableClass = htmlspecialchars( $this->getTableClass() );
504 $sortClass = htmlspecialchars( $this->getSortHeaderClass() );
506 $s = "<table border='1' class=\"$tableClass\"><thead><tr>\n";
507 $fields = $this->getFieldNames();
510 foreach ( $fields as $field => $name ) {
511 if ( strval( $name ) == '' ) {
512 $s .= "<th> </th>\n";
513 } elseif ( $this->isFieldSortable( $field ) ) {
514 $query = array( 'sort' => $field, 'limit' => $this->mLimit
);
515 if ( $field == $this->mSort
) {
516 # This is the sorted column
517 # Prepare a link that goes in the other sort order
518 if ( $this->mDefaultDirection
) {
520 $image = 'Arr_u.png';
523 $alt = htmlspecialchars( wfMsg( 'descending_abbrev' ) );
526 $image = 'Arr_d.png';
528 $query['desc'] = '1';
529 $alt = htmlspecialchars( wfMsg( 'ascending_abbrev' ) );
531 $image = htmlspecialchars( "$wgStylePath/common/images/$image" );
532 $link = $this->makeLink(
533 "<img width=\"12\" height=\"12\" alt=\"$alt\" src=\"$image\" />" .
534 htmlspecialchars( $name ), $query );
535 $s .= "<th class=\"$sortClass\">$link</th>\n";
537 $s .= '<th>' . $this->makeLink( htmlspecialchars( $name ), $query ) . "</th>\n";
540 $s .= '<th>' . htmlspecialchars( $name ) . "</th>\n";
543 $s .= "</tr></thead><tbody>\n";
547 function getEndBody() {
548 return "</tbody></table>\n";
551 function getEmptyBody() {
552 $colspan = count( $this->getFieldNames() );
553 $msgEmpty = wfMsgHtml( 'table_pager_empty' );
554 return "<tr><td colspan=\"$colspan\">$msgEmpty</td></tr>\n";
557 function formatRow( $row ) {
559 $fieldNames = $this->getFieldNames();
560 $this->mCurrentRow
= $row; # In case formatValue needs to know
561 foreach ( $fieldNames as $field => $name ) {
562 $value = isset( $row->$field ) ?
$row->$field : null;
563 $formatted = strval( $this->formatValue( $field, $value ) );
564 if ( $formatted == '' ) {
565 $formatted = ' ';
567 $class = 'TablePager_col_' . htmlspecialchars( $field );
568 $s .= "<td class=\"$class\">$formatted</td>\n";
574 function getIndexField() {
578 function getTableClass() {
582 function getNavClass() {
583 return 'TablePager_nav';
586 function getSortHeaderClass() {
587 return 'TablePager_sort';
591 * A navigation bar with images
593 function getNavigationBar() {
594 global $wgStylePath, $wgContLang;
595 $path = "$wgStylePath/common/images";
597 'first' => 'table_pager_first',
598 'prev' => 'table_pager_prev',
599 'next' => 'table_pager_next',
600 'last' => 'table_pager_last',
603 'first' => $wgContLang->isRTL() ?
'arrow_last_25.png' : 'arrow_first_25.png',
604 'prev' => $wgContLang->isRTL() ?
'arrow_right_25.png' : 'arrow_left_25.png',
605 'next' => $wgContLang->isRTL() ?
'arrow_left_25.png' : 'arrow_right_25.png',
606 'last' => $wgContLang->isRTL() ?
'arrow_first_25.png' : 'arrow_last_25.png',
608 $disabledImages = array(
609 'first' => $wgContLang->isRTL() ?
'arrow_disabled_last_25.png' : 'arrow_disabled_first_25.png',
610 'prev' => $wgContLang->isRTL() ?
'arrow_disabled_right_25.png' : 'arrow_disabled_left_25.png',
611 'next' => $wgContLang->isRTL() ?
'arrow_disabled_left_25.png' : 'arrow_disabled_right_25.png',
612 'last' => $wgContLang->isRTL() ?
'arrow_disabled_first_25.png' : 'arrow_disabled_last_25.png',
615 $linkTexts = array();
616 $disabledTexts = array();
617 foreach ( $labels as $type => $label ) {
618 $msgLabel = wfMsgHtml( $label );
619 $linkTexts[$type] = "<img src=\"$path/{$images[$type]}\" alt=\"$msgLabel\"/><br/>$msgLabel";
620 $disabledTexts[$type] = "<img src=\"$path/{$disabledImages[$type]}\" alt=\"$msgLabel\"/><br/>$msgLabel";
622 $links = $this->getPagingLinks( $linkTexts, $disabledTexts );
624 $navClass = htmlspecialchars( $this->getNavClass() );
625 $s = "<table class=\"$navClass\" align=\"center\" cellpadding=\"3\"><tr>\n";
626 $cellAttrs = 'valign="top" align="center" width="' . 100 / count( $links ) . '%"';
627 foreach ( $labels as $type => $label ) {
628 $s .= "<td $cellAttrs>{$links[$type]}</td>\n";
630 $s .= "</tr></table>\n";
635 * Get a <select> element which has options for each of the allowed limits
637 function getLimitSelect() {
639 $s = "<select name=\"limit\">";
640 foreach ( $this->mLimitsShown
as $limit ) {
641 $selected = $limit == $this->mLimit ?
'selected="selected"' : '';
642 $formattedLimit = $wgLang->formatNum( $limit );
643 $s .= "<option value=\"$limit\" $selected>$formattedLimit</option>\n";
650 * Get <input type="hidden"> elements for use in a method="get" form.
651 * Resubmits all defined elements of the $_GET array, except for a
652 * blacklist, passed in the $blacklist parameter.
654 function getHiddenFields( $blacklist = array() ) {
655 $blacklist = (array)$blacklist;
657 foreach ( $blacklist as $name ) {
658 unset( $query[$name] );
661 foreach ( $query as $name => $value ) {
662 $encName = htmlspecialchars( $name );
663 $encValue = htmlspecialchars( $value );
664 $s .= "<input type=\"hidden\" name=\"$encName\" value=\"$encValue\"/>\n";
670 * Get a form containing a limit selection dropdown
672 function getLimitForm() {
673 # Make the select with some explanatory text
674 $url = $this->getTitle()->escapeLocalURL();
675 $msgSubmit = wfMsgHtml( 'table_pager_limit_submit' );
677 "<form method=\"get\" action=\"$url\">" .
678 wfMsgHtml( 'table_pager_limit', $this->getLimitSelect() ) .
679 "\n<input type=\"submit\" value=\"$msgSubmit\"/>\n" .
680 $this->getHiddenFields( 'limit' ) .
685 * Return true if the named field should be sortable by the UI, false
688 * @param string $field
690 abstract function isFieldSortable( $field );
693 * Format a table cell. The return value should be HTML, but use an empty
694 * string not for empty cells. Do not include the <td> and </td>.
696 * The current result row is available as $this->mCurrentRow, in case you
699 * @param string $name The database field name
700 * @param string $value The value retrieved from the database
702 abstract function formatValue( $name, $value );
705 * The database field name used as a default sort order
707 abstract function getDefaultSort();
710 * An array mapping database field names to a textual description of the
711 * field name, for use in the table header. The description should be plain
712 * text, it will be HTML-escaped later.
714 abstract function getFieldNames();