3 * Efficient paging for SQL queries.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * @defgroup Pager Pager
29 * Basic pager interface.
33 function getNavigationBar();
38 * IndexPager is an efficient pager which uses a (roughly unique) index in the
39 * data set to implement paging, rather than a "LIMIT offset,limit" clause.
40 * In MySQL, such a limit/offset clause requires counting through the
41 * specified number of offset rows to find the desired data, which can be
42 * expensive for large offsets.
44 * ReverseChronologicalPager is a child class of the abstract IndexPager, and
45 * contains some formatting and display code which is specific to the use of
46 * timestamps as indexes. Here is a synopsis of its operation:
48 * * The query is specified by the offset, limit and direction (dir)
49 * parameters, in addition to any subclass-specific parameters.
50 * * The offset is the non-inclusive start of the DB query. A row with an
51 * index value equal to the offset will never be shown.
52 * * The query may either be done backwards, where the rows are returned by
53 * the database in the opposite order to which they are displayed to the
54 * user, or forwards. This is specified by the "dir" parameter, dir=prev
55 * means backwards, anything else means forwards. The offset value
56 * specifies the start of the database result set, which may be either
57 * the start or end of the displayed data set. This allows "previous"
58 * links to be implemented without knowledge of the index value at the
59 * start of the previous page.
60 * * An additional row beyond the user-specified limit is always requested.
61 * This allows us to tell whether we should display a "next" link in the
62 * case of forwards mode, or a "previous" link in the case of backwards
63 * mode. Determining whether to display the other link (the one for the
64 * page before the start of the database result set) can be done
65 * heuristically by examining the offset.
67 * * An empty offset indicates that the offset condition should be omitted
68 * from the query. This naturally produces either the first page or the
69 * last page depending on the dir parameter.
71 * Subclassing the pager to implement concrete functionality should be fairly
72 * simple, please see the examples in HistoryPage.php and
73 * SpecialBlockList.php. You just need to override formatRow(),
74 * getQueryInfo() and getIndexField(). Don't forget to call the parent
75 * constructor if you override it.
79 abstract class IndexPager
extends ContextSource
implements Pager
{
81 public $mLimitsShown = array( 20, 50, 100, 250, 500 );
82 public $mDefaultLimit = 50;
83 public $mOffset, $mLimit;
84 public $mQueryDone = false;
86 public $mPastTheEndRow;
89 * The index to actually be used for ordering. This is a single column,
90 * for one ordering, even if multiple orderings are supported.
92 protected $mIndexField;
94 * An array of secondary columns to order by. These fields are not part of the offset.
95 * This is a column list for one ordering, even if multiple orderings are supported.
97 protected $mExtraSortFields;
98 /** For pages that support multiple types of ordering, which one to use.
100 protected $mOrderType;
102 * $mDefaultDirection gives the direction to use when sorting results:
103 * false for ascending, true for descending. If $mIsBackwards is set, we
104 * start from the opposite end, but we still sort the page itself according
105 * to $mDefaultDirection. E.g., if $mDefaultDirection is false but we're
106 * going backwards, we'll display the last page of results, but the last
107 * result will be at the bottom, not the top.
109 * Like $mIndexField, $mDefaultDirection will be a single value even if the
110 * class supports multiple default directions for different order types.
112 public $mDefaultDirection;
113 public $mIsBackwards;
115 /** True if the current result set is the first one */
119 protected $mLastShown, $mFirstShown, $mPastTheEndIndex, $mDefaultQuery, $mNavigationBar;
122 * Whether to include the offset in the query
124 protected $mIncludeOffset = false;
127 * Result object for the query. Warning: seek before use.
133 public function __construct( IContextSource
$context = null ) {
135 $this->setContext( $context );
138 $this->mRequest
= $this->getRequest();
140 # NB: the offset is quoted, not validated. It is treated as an
141 # arbitrary string to support the widest variety of index types. Be
142 # careful outputting it into HTML!
143 $this->mOffset
= $this->mRequest
->getText( 'offset' );
145 # Use consistent behavior for the limit options
146 $this->mDefaultLimit
= $this->getUser()->getIntOption( 'rclimit' );
147 if ( !$this->mLimit
) {
148 // Don't override if a subclass calls $this->setLimit() in its constructor.
149 list( $this->mLimit
, /* $offset */ ) = $this->mRequest
->getLimitOffset();
152 $this->mIsBackwards
= ( $this->mRequest
->getVal( 'dir' ) == 'prev' );
153 # Let the subclass set the DB here; otherwise use a slave DB for the current wiki
154 $this->mDb
= $this->mDb ?
: wfGetDB( DB_SLAVE
);
156 $index = $this->getIndexField(); // column to sort on
157 $extraSort = $this->getExtraSortFields(); // extra columns to sort on for query planning
158 $order = $this->mRequest
->getVal( 'order' );
159 if ( is_array( $index ) && isset( $index[$order] ) ) {
160 $this->mOrderType
= $order;
161 $this->mIndexField
= $index[$order];
162 $this->mExtraSortFields
= isset( $extraSort[$order] )
163 ?
(array)$extraSort[$order]
165 } elseif ( is_array( $index ) ) {
166 # First element is the default
168 list( $this->mOrderType
, $this->mIndexField
) = each( $index );
169 $this->mExtraSortFields
= isset( $extraSort[$this->mOrderType
] )
170 ?
(array)$extraSort[$this->mOrderType
]
173 # $index is not an array
174 $this->mOrderType
= null;
175 $this->mIndexField
= $index;
176 $this->mExtraSortFields
= (array)$extraSort;
179 if ( !isset( $this->mDefaultDirection
) ) {
180 $dir = $this->getDefaultDirections();
181 $this->mDefaultDirection
= is_array( $dir )
182 ?
$dir[$this->mOrderType
]
188 * Get the Database object in use
190 * @return DatabaseBase
192 public function getDatabase() {
197 * Do the query, using information from the object context. This function
198 * has been kept minimal to make it overridable if necessary, to allow for
199 * result sets formed from multiple DB queries.
201 public function doQuery() {
202 # Use the child class name for profiling
203 $fname = __METHOD__
. ' (' . get_class( $this ) . ')';
204 wfProfileIn( $fname );
206 $descending = ( $this->mIsBackwards
== $this->mDefaultDirection
);
207 # Plus an extra row so that we can tell the "next" link should be shown
208 $queryLimit = $this->mLimit +
1;
210 if ( $this->mOffset
== '' ) {
213 // If there's an offset, we may or may not be at the first entry.
214 // The only way to tell is to run the query in the opposite
215 // direction see if we get a row.
216 $oldIncludeOffset = $this->mIncludeOffset
;
217 $this->mIncludeOffset
= !$this->mIncludeOffset
;
218 $isFirst = !$this->reallyDoQuery( $this->mOffset
, 1, !$descending )->numRows();
219 $this->mIncludeOffset
= $oldIncludeOffset;
222 $this->mResult
= $this->reallyDoQuery(
228 $this->extractResultInfo( $isFirst, $queryLimit, $this->mResult
);
229 $this->mQueryDone
= true;
231 $this->preprocessResults( $this->mResult
);
232 $this->mResult
->rewind(); // Paranoia
234 wfProfileOut( $fname );
238 * @return ResultWrapper The result wrapper.
240 function getResult() {
241 return $this->mResult
;
245 * Set the offset from an other source than the request
247 * @param $offset Int|String
249 function setOffset( $offset ) {
250 $this->mOffset
= $offset;
253 * Set the limit from an other source than the request
255 * Verifies limit is between 1 and 5000
257 * @param $limit Int|String
259 function setLimit( $limit ) {
260 $limit = (int) $limit;
261 // WebRequest::getLimitOffset() puts a cap of 5000, so do same here.
262 if ( $limit > 5000 ) {
266 $this->mLimit
= $limit;
271 * Set whether a row matching exactly the offset should be also included
272 * in the result or not. By default this is not the case, but when the
273 * offset is user-supplied this might be wanted.
275 * @param $include bool
277 public function setIncludeOffset( $include ) {
278 $this->mIncludeOffset
= $include;
282 * Extract some useful data from the result object for use by
283 * the navigation bar, put it into $this
285 * @param $isFirst bool: False if there are rows before those fetched (i.e.
286 * if a "previous" link would make sense)
287 * @param $limit Integer: exact query limit
288 * @param $res ResultWrapper
290 function extractResultInfo( $isFirst, $limit, ResultWrapper
$res ) {
291 $numRows = $res->numRows();
293 # Remove any table prefix from index field
294 $parts = explode( '.', $this->mIndexField
);
295 $indexColumn = end( $parts );
297 $row = $res->fetchRow();
298 $firstIndex = $row[$indexColumn];
300 # Discard the extra result row if there is one
301 if ( $numRows > $this->mLimit
&& $numRows > 1 ) {
302 $res->seek( $numRows - 1 );
303 $this->mPastTheEndRow
= $res->fetchObject();
304 $this->mPastTheEndIndex
= $this->mPastTheEndRow
->$indexColumn;
305 $res->seek( $numRows - 2 );
306 $row = $res->fetchRow();
307 $lastIndex = $row[$indexColumn];
309 $this->mPastTheEndRow
= null;
310 # Setting indexes to an empty string means that they will be
311 # omitted if they would otherwise appear in URLs. It just so
312 # happens that this is the right thing to do in the standard
313 # UI, in all the relevant cases.
314 $this->mPastTheEndIndex
= '';
315 $res->seek( $numRows - 1 );
316 $row = $res->fetchRow();
317 $lastIndex = $row[$indexColumn];
322 $this->mPastTheEndRow
= null;
323 $this->mPastTheEndIndex
= '';
326 if ( $this->mIsBackwards
) {
327 $this->mIsFirst
= ( $numRows < $limit );
328 $this->mIsLast
= $isFirst;
329 $this->mLastShown
= $firstIndex;
330 $this->mFirstShown
= $lastIndex;
332 $this->mIsFirst
= $isFirst;
333 $this->mIsLast
= ( $numRows < $limit );
334 $this->mLastShown
= $lastIndex;
335 $this->mFirstShown
= $firstIndex;
340 * Get some text to go in brackets in the "function name" part of the SQL comment
344 function getSqlComment() {
345 return get_class( $this );
349 * Do a query with specified parameters, rather than using the object
352 * @param string $offset index offset, inclusive
353 * @param $limit Integer: exact query limit
354 * @param $descending Boolean: query direction, false for ascending, true for descending
355 * @return ResultWrapper
357 public function reallyDoQuery( $offset, $limit, $descending ) {
358 list( $tables, $fields, $conds, $fname, $options, $join_conds ) = $this->buildQueryInfo( $offset, $limit, $descending );
359 return $this->mDb
->select( $tables, $fields, $conds, $fname, $options, $join_conds );
363 * Build variables to use by the database wrapper.
365 * @param string $offset index offset, inclusive
366 * @param $limit Integer: exact query limit
367 * @param $descending Boolean: query direction, false for ascending, true for descending
370 protected function buildQueryInfo( $offset, $limit, $descending ) {
371 $fname = __METHOD__
. ' (' . $this->getSqlComment() . ')';
372 $info = $this->getQueryInfo();
373 $tables = $info['tables'];
374 $fields = $info['fields'];
375 $conds = isset( $info['conds'] ) ?
$info['conds'] : array();
376 $options = isset( $info['options'] ) ?
$info['options'] : array();
377 $join_conds = isset( $info['join_conds'] ) ?
$info['join_conds'] : array();
378 $sortColumns = array_merge( array( $this->mIndexField
), $this->mExtraSortFields
);
380 $options['ORDER BY'] = $sortColumns;
381 $operator = $this->mIncludeOffset ?
'>=' : '>';
384 foreach ( $sortColumns as $col ) {
385 $orderBy[] = $col . ' DESC';
387 $options['ORDER BY'] = $orderBy;
388 $operator = $this->mIncludeOffset ?
'<=' : '<';
390 if ( $offset != '' ) {
391 $conds[] = $this->mIndexField
. $operator . $this->mDb
->addQuotes( $offset );
393 $options['LIMIT'] = intval( $limit );
394 return array( $tables, $fields, $conds, $fname, $options, $join_conds );
398 * Pre-process results; useful for performing batch existence checks, etc.
400 * @param $result ResultWrapper
402 protected function preprocessResults( $result ) {}
405 * Get the formatted result list. Calls getStartBody(), formatRow() and
406 * getEndBody(), concatenates the results and returns them.
410 public function getBody() {
411 if ( !$this->mQueryDone
) {
415 if ( $this->mResult
->numRows() ) {
416 # Do any special query batches before display
417 $this->doBatchLookups();
420 # Don't use any extra rows returned by the query
421 $numRows = min( $this->mResult
->numRows(), $this->mLimit
);
423 $s = $this->getStartBody();
425 if ( $this->mIsBackwards
) {
426 for ( $i = $numRows - 1; $i >= 0; $i-- ) {
427 $this->mResult
->seek( $i );
428 $row = $this->mResult
->fetchObject();
429 $s .= $this->formatRow( $row );
432 $this->mResult
->seek( 0 );
433 for ( $i = 0; $i < $numRows; $i++
) {
434 $row = $this->mResult
->fetchObject();
435 $s .= $this->formatRow( $row );
439 $s .= $this->getEmptyBody();
441 $s .= $this->getEndBody();
448 * @param string $text text displayed on the link
449 * @param array $query associative array of parameter to be in the query string
450 * @param string $type value of the "rel" attribute
452 * @return String: HTML fragment
454 function makeLink( $text, array $query = null, $type = null ) {
455 if ( $query === null ) {
460 if ( in_array( $type, array( 'first', 'prev', 'next', 'last' ) ) ) {
461 # HTML5 rel attributes
462 $attrs['rel'] = $type;
466 $attrs['class'] = "mw-{$type}link";
469 return Linker
::linkKnown(
473 $query +
$this->getDefaultQuery()
478 * Called from getBody(), before getStartBody() is called and
479 * after doQuery() was called. This will be called only if there
480 * are rows in the result set.
484 protected function doBatchLookups() {}
487 * Hook into getBody(), allows text to be inserted at the start. This
488 * will be called even if there are no rows in the result set.
492 protected function getStartBody() {
497 * Hook into getBody() for the end of the list
501 protected function getEndBody() {
506 * Hook into getBody(), for the bit between the start and the
507 * end when there are no rows
511 protected function getEmptyBody() {
516 * Get an array of query parameters that should be put into self-links.
517 * By default, all parameters passed in the URL are used, except for a
520 * @return array Associative array
522 function getDefaultQuery() {
523 if ( !isset( $this->mDefaultQuery
) ) {
524 $this->mDefaultQuery
= $this->getRequest()->getQueryValues();
525 unset( $this->mDefaultQuery
['title'] );
526 unset( $this->mDefaultQuery
['dir'] );
527 unset( $this->mDefaultQuery
['offset'] );
528 unset( $this->mDefaultQuery
['limit'] );
529 unset( $this->mDefaultQuery
['order'] );
530 unset( $this->mDefaultQuery
['month'] );
531 unset( $this->mDefaultQuery
['year'] );
533 return $this->mDefaultQuery
;
537 * Get the number of rows in the result set
541 function getNumRows() {
542 if ( !$this->mQueryDone
) {
545 return $this->mResult
->numRows();
549 * Get a URL query array for the prev, next, first and last links.
553 function getPagingQueries() {
554 if ( !$this->mQueryDone
) {
558 # Don't announce the limit everywhere if it's the default
559 $urlLimit = $this->mLimit
== $this->mDefaultLimit ?
null : $this->mLimit
;
561 if ( $this->mIsFirst
) {
567 'offset' => $this->mFirstShown
,
570 $first = array( 'limit' => $urlLimit );
572 if ( $this->mIsLast
) {
576 $next = array( 'offset' => $this->mLastShown
, 'limit' => $urlLimit );
577 $last = array( 'dir' => 'prev', 'limit' => $urlLimit );
588 * Returns whether to show the "navigation bar"
592 function isNavigationBarShown() {
593 if ( !$this->mQueryDone
) {
596 // Hide navigation by default if there is nothing to page
597 return !( $this->mIsFirst
&& $this->mIsLast
);
601 * Get paging links. If a link is disabled, the item from $disabledTexts
602 * will be used. If there is no such item, the unlinked text from
603 * $linkTexts will be used. Both $linkTexts and $disabledTexts are arrays
606 * @param $linkTexts Array
607 * @param $disabledTexts Array
610 function getPagingLinks( $linkTexts, $disabledTexts = array() ) {
611 $queries = $this->getPagingQueries();
614 foreach ( $queries as $type => $query ) {
615 if ( $query !== false ) {
616 $links[$type] = $this->makeLink(
621 } elseif ( isset( $disabledTexts[$type] ) ) {
622 $links[$type] = $disabledTexts[$type];
624 $links[$type] = $linkTexts[$type];
631 function getLimitLinks() {
633 if ( $this->mIsBackwards
) {
634 $offset = $this->mPastTheEndIndex
;
636 $offset = $this->mOffset
;
638 foreach ( $this->mLimitsShown
as $limit ) {
639 $links[] = $this->makeLink(
640 $this->getLanguage()->formatNum( $limit ),
641 array( 'offset' => $offset, 'limit' => $limit ),
649 * Abstract formatting function. This should return an HTML string
650 * representing the result row $row. Rows will be concatenated and
651 * returned by getBody()
653 * @param $row Object: database row
656 abstract function formatRow( $row );
659 * This function should be overridden to provide all parameters
660 * needed for the main paged query. It returns an associative
661 * array with the following elements:
662 * tables => Table(s) for passing to Database::select()
663 * fields => Field(s) for passing to Database::select(), may be *
664 * conds => WHERE conditions
665 * options => option array
666 * join_conds => JOIN conditions
670 abstract function getQueryInfo();
673 * This function should be overridden to return the name of the index fi-
674 * eld. If the pager supports multiple orders, it may return an array of
675 * 'querykey' => 'indexfield' pairs, so that a request with &count=querykey
676 * will use indexfield to sort. In this case, the first returned key is
679 * Needless to say, it's really not a good idea to use a non-unique index
680 * for this! That won't page right.
682 * @return string|Array
684 abstract function getIndexField();
687 * This function should be overridden to return the names of secondary columns
688 * to order by in addition to the column in getIndexField(). These fields will
689 * not be used in the pager offset or in any links for users.
691 * If getIndexField() returns an array of 'querykey' => 'indexfield' pairs then
692 * this must return a corresponding array of 'querykey' => array( fields...) pairs
693 * in order for a request with &count=querykey to use array( fields...) to sort.
695 * This is useful for pagers that GROUP BY a unique column (say page_id)
696 * and ORDER BY another (say page_len). Using GROUP BY and ORDER BY both on
697 * page_len,page_id avoids temp tables (given a page_len index). This would
698 * also work if page_id was non-unique but we had a page_len,page_id index.
702 protected function getExtraSortFields() {
707 * Return the default sorting direction: false for ascending, true for
708 * descending. You can also have an associative array of ordertype => dir,
709 * if multiple order types are supported. In this case getIndexField()
710 * must return an array, and the keys of that must exactly match the keys
713 * For backward compatibility, this method's return value will be ignored
714 * if $this->mDefaultDirection is already set when the constructor is
715 * called, for instance if it's statically initialized. In that case the
716 * value of that variable (which must be a boolean) will be used.
718 * Note that despite its name, this does not return the value of the
719 * $this->mDefaultDirection member variable. That's the default for this
720 * particular instantiation, which is a single value. This is the set of
721 * all defaults for the class.
725 protected function getDefaultDirections() {
731 * IndexPager with an alphabetic list and a formatted navigation bar
734 abstract class AlphabeticPager
extends IndexPager
{
737 * Shamelessly stolen bits from ReverseChronologicalPager,
738 * didn't want to do class magic as may be still revamped
740 * @return String HTML
742 function getNavigationBar() {
743 if ( !$this->isNavigationBarShown() ) {
747 if ( isset( $this->mNavigationBar
) ) {
748 return $this->mNavigationBar
;
752 'prev' => $this->msg( 'prevn' )->numParams( $this->mLimit
)->escaped(),
753 'next' => $this->msg( 'nextn' )->numParams( $this->mLimit
)->escaped(),
754 'first' => $this->msg( 'page_first' )->escaped(),
755 'last' => $this->msg( 'page_last' )->escaped()
758 $lang = $this->getLanguage();
760 $pagingLinks = $this->getPagingLinks( $linkTexts );
761 $limitLinks = $this->getLimitLinks();
762 $limits = $lang->pipeList( $limitLinks );
764 $this->mNavigationBar
= $this->msg( 'parentheses' )->rawParams(
765 $lang->pipeList( array( $pagingLinks['first'],
766 $pagingLinks['last'] ) ) )->escaped() . " " .
767 $this->msg( 'viewprevnext' )->rawParams( $pagingLinks['prev'],
768 $pagingLinks['next'], $limits )->escaped();
770 if ( !is_array( $this->getIndexField() ) ) {
771 # Early return to avoid undue nesting
772 return $this->mNavigationBar
;
777 $msgs = $this->getOrderTypeMessages();
778 foreach ( array_keys( $msgs ) as $order ) {
782 $extra .= $this->msg( 'pipe-separator' )->escaped();
785 if ( $order == $this->mOrderType
) {
786 $extra .= $this->msg( $msgs[$order] )->escaped();
788 $extra .= $this->makeLink(
789 $this->msg( $msgs[$order] )->escaped(),
790 array( 'order' => $order )
795 if ( $extra !== '' ) {
796 $extra = ' ' . $this->msg( 'parentheses' )->rawParams( $extra )->escaped();
797 $this->mNavigationBar
.= $extra;
800 return $this->mNavigationBar
;
804 * If this supports multiple order type messages, give the message key for
805 * enabling each one in getNavigationBar. The return type is an associative
806 * array whose keys must exactly match the keys of the array returned
807 * by getIndexField(), and whose values are message keys.
811 protected function getOrderTypeMessages() {
817 * IndexPager with a formatted navigation bar
820 abstract class ReverseChronologicalPager
extends IndexPager
{
821 public $mDefaultDirection = true;
825 function getNavigationBar() {
826 if ( !$this->isNavigationBarShown() ) {
830 if ( isset( $this->mNavigationBar
) ) {
831 return $this->mNavigationBar
;
835 'prev' => $this->msg( 'pager-newer-n' )->numParams( $this->mLimit
)->escaped(),
836 'next' => $this->msg( 'pager-older-n' )->numParams( $this->mLimit
)->escaped(),
837 'first' => $this->msg( 'histlast' )->escaped(),
838 'last' => $this->msg( 'histfirst' )->escaped()
841 $pagingLinks = $this->getPagingLinks( $linkTexts );
842 $limitLinks = $this->getLimitLinks();
843 $limits = $this->getLanguage()->pipeList( $limitLinks );
844 $firstLastLinks = $this->msg( 'parentheses' )->rawParams( "{$pagingLinks['first']}" .
845 $this->msg( 'pipe-separator' )->escaped() .
846 "{$pagingLinks['last']}" )->escaped();
848 $this->mNavigationBar
= $firstLastLinks . ' ' .
849 $this->msg( 'viewprevnext' )->rawParams(
850 $pagingLinks['prev'], $pagingLinks['next'], $limits )->escaped();
852 return $this->mNavigationBar
;
855 function getDateCond( $year, $month ) {
856 $year = intval( $year );
857 $month = intval( $month );
859 // Basic validity checks
860 $this->mYear
= $year > 0 ?
$year : false;
861 $this->mMonth
= ( $month > 0 && $month < 13 ) ?
$month : false;
863 // Given an optional year and month, we need to generate a timestamp
864 // to use as "WHERE rev_timestamp <= result"
865 // Examples: year = 2006 equals < 20070101 (+000000)
866 // year=2005, month=1 equals < 20050201
867 // year=2005, month=12 equals < 20060101
868 if ( !$this->mYear
&& !$this->mMonth
) {
872 if ( $this->mYear
) {
873 $year = $this->mYear
;
875 // If no year given, assume the current one
876 $timestamp = MWTimestamp
::getInstance();
877 $year = $timestamp->format( 'Y' );
878 // If this month hasn't happened yet this year, go back to last year's month
879 if ( $this->mMonth
> $timestamp->format( 'n' ) ) {
884 if ( $this->mMonth
) {
885 $month = $this->mMonth +
1;
886 // For December, we want January 1 of the next year
892 // No month implies we want up to the end of the year in question
898 if ( $year > 2032 ) {
902 $ymd = (int)sprintf( "%04d%02d01", $year, $month );
904 if ( $ymd > 20320101 ) {
908 $this->mOffset
= $this->mDb
->timestamp( "${ymd}000000" );
913 * Table-based display with a user-selectable sort order
916 abstract class TablePager
extends IndexPager
{
920 public function __construct( IContextSource
$context = null ) {
922 $this->setContext( $context );
925 $this->mSort
= $this->getRequest()->getText( 'sort' );
926 if ( !array_key_exists( $this->mSort
, $this->getFieldNames() )
927 ||
!$this->isFieldSortable( $this->mSort
)
929 $this->mSort
= $this->getDefaultSort();
931 if ( $this->getRequest()->getBool( 'asc' ) ) {
932 $this->mDefaultDirection
= false;
933 } elseif ( $this->getRequest()->getBool( 'desc' ) ) {
934 $this->mDefaultDirection
= true;
935 } /* Else leave it at whatever the class default is */
937 parent
::__construct();
944 function getStartBody() {
946 $sortClass = $this->getSortHeaderClass();
949 $fields = $this->getFieldNames();
952 foreach ( $fields as $field => $name ) {
953 if ( strval( $name ) == '' ) {
954 $s .= Html
::rawElement( 'th', array(), ' ' ) . "\n";
955 } elseif ( $this->isFieldSortable( $field ) ) {
956 $query = array( 'sort' => $field, 'limit' => $this->mLimit
);
957 if ( $field == $this->mSort
) {
958 # This is the sorted column
959 # Prepare a link that goes in the other sort order
960 if ( $this->mDefaultDirection
) {
962 $image = 'Arr_d.png';
965 $alt = $this->msg( 'descending_abbrev' )->escaped();
968 $image = 'Arr_u.png';
970 $query['desc'] = '1';
971 $alt = $this->msg( 'ascending_abbrev' )->escaped();
973 $image = "$wgStylePath/common/images/$image";
974 $link = $this->makeLink(
975 Html
::element( 'img', array( 'width' => 12, 'height' => 12,
976 'alt' => $alt, 'src' => $image ) ) . htmlspecialchars( $name ), $query );
977 $s .= Html
::rawElement( 'th', array( 'class' => $sortClass ), $link ) . "\n";
979 $s .= Html
::rawElement( 'th', array(),
980 $this->makeLink( htmlspecialchars( $name ), $query ) ) . "\n";
983 $s .= Html
::element( 'th', array(), $name ) . "\n";
987 $tableClass = $this->getTableClass();
988 $ret = Html
::openElement( 'table', array( 'style' => 'border:1px;', 'class' => "mw-datatable $tableClass" ) );
989 $ret .= Html
::rawElement( 'thead', array(), Html
::rawElement( 'tr', array(), "\n" . $s . "\n" ) );
990 $ret .= Html
::openElement( 'tbody' ) . "\n";
999 function getEndBody() {
1000 return "</tbody></table>\n";
1007 function getEmptyBody() {
1008 $colspan = count( $this->getFieldNames() );
1009 $msgEmpty = $this->msg( 'table_pager_empty' )->text();
1010 return Html
::rawElement( 'tr', array(),
1011 Html
::element( 'td', array( 'colspan' => $colspan ), $msgEmpty ) );
1016 * @param stdClass $row
1017 * @return String HTML
1019 function formatRow( $row ) {
1020 $this->mCurrentRow
= $row; // In case formatValue etc need to know
1021 $s = Html
::openElement( 'tr', $this->getRowAttrs( $row ) ) . "\n";
1022 $fieldNames = $this->getFieldNames();
1024 foreach ( $fieldNames as $field => $name ) {
1025 $value = isset( $row->$field ) ?
$row->$field : null;
1026 $formatted = strval( $this->formatValue( $field, $value ) );
1028 if ( $formatted == '' ) {
1029 $formatted = ' ';
1032 $s .= Html
::rawElement( 'td', $this->getCellAttrs( $field, $value ), $formatted ) . "\n";
1035 $s .= Html
::closeElement( 'tr' ) . "\n";
1041 * Get a class name to be applied to the given row.
1045 * @param $row Object: the database result row
1048 function getRowClass( $row ) {
1053 * Get attributes to be applied to the given row.
1057 * @param $row Object: the database result row
1058 * @return Array of attribute => value
1060 function getRowAttrs( $row ) {
1061 $class = $this->getRowClass( $row );
1062 if ( $class === '' ) {
1063 // Return an empty array to avoid clutter in HTML like class=""
1066 return array( 'class' => $this->getRowClass( $row ) );
1071 * Get any extra attributes to be applied to the given cell. Don't
1072 * take this as an excuse to hardcode styles; use classes and
1073 * CSS instead. Row context is available in $this->mCurrentRow
1077 * @param string $field The column
1078 * @param string $value The cell contents
1079 * @return Array of attr => value
1081 function getCellAttrs( $field, $value ) {
1082 return array( 'class' => 'TablePager_col_' . $field );
1089 function getIndexField() {
1090 return $this->mSort
;
1097 function getTableClass() {
1098 return 'TablePager';
1105 function getNavClass() {
1106 return 'TablePager_nav';
1113 function getSortHeaderClass() {
1114 return 'TablePager_sort';
1118 * A navigation bar with images
1119 * @return String HTML
1121 public function getNavigationBar() {
1122 global $wgStylePath;
1124 if ( !$this->isNavigationBarShown() ) {
1128 $path = "$wgStylePath/common/images";
1130 'first' => 'table_pager_first',
1131 'prev' => 'table_pager_prev',
1132 'next' => 'table_pager_next',
1133 'last' => 'table_pager_last',
1136 'first' => 'arrow_first_25.png',
1137 'prev' => 'arrow_left_25.png',
1138 'next' => 'arrow_right_25.png',
1139 'last' => 'arrow_last_25.png',
1141 $disabledImages = array(
1142 'first' => 'arrow_disabled_first_25.png',
1143 'prev' => 'arrow_disabled_left_25.png',
1144 'next' => 'arrow_disabled_right_25.png',
1145 'last' => 'arrow_disabled_last_25.png',
1147 if ( $this->getLanguage()->isRTL() ) {
1148 $keys = array_keys( $labels );
1149 $images = array_combine( $keys, array_reverse( $images ) );
1150 $disabledImages = array_combine( $keys, array_reverse( $disabledImages ) );
1153 $linkTexts = array();
1154 $disabledTexts = array();
1155 foreach ( $labels as $type => $label ) {
1156 $msgLabel = $this->msg( $label )->escaped();
1157 $linkTexts[$type] = Html
::element( 'img', array( 'src' => "$path/{$images[$type]}",
1158 'alt' => $msgLabel ) ) . "<br />$msgLabel";
1159 $disabledTexts[$type] = Html
::element( 'img', array( 'src' => "$path/{$disabledImages[$type]}",
1160 'alt' => $msgLabel ) ) . "<br />$msgLabel";
1162 $links = $this->getPagingLinks( $linkTexts, $disabledTexts );
1164 $s = Html
::openElement( 'table', array( 'class' => $this->getNavClass() ) );
1165 $s .= Html
::openElement( 'tr' ) . "\n";
1166 $width = 100 / count( $links ) . '%';
1167 foreach ( $labels as $type => $label ) {
1168 $s .= Html
::rawElement( 'td', array( 'style' => "width:$width;" ), $links[$type] ) . "\n";
1170 $s .= Html
::closeElement( 'tr' ) . Html
::closeElement( 'table' ) . "\n";
1175 * Get a "<select>" element which has options for each of the allowed limits
1177 * @param $attribs String: Extra attributes to set
1178 * @return String: HTML fragment
1180 public function getLimitSelect( $attribs = array() ) {
1181 $select = new XmlSelect( 'limit', false, $this->mLimit
);
1182 $select->addOptions( $this->getLimitSelectList() );
1183 foreach ( $attribs as $name => $value ) {
1184 $select->setAttribute( $name, $value );
1186 return $select->getHTML();
1190 * Get a list of items to show in a "<select>" element of limits.
1191 * This can be passed directly to XmlSelect::addOptions().
1196 public function getLimitSelectList() {
1197 # Add the current limit from the query string
1198 # to avoid that the limit is lost after clicking Go next time
1199 if ( !in_array( $this->mLimit
, $this->mLimitsShown
) ) {
1200 $this->mLimitsShown
[] = $this->mLimit
;
1201 sort( $this->mLimitsShown
);
1204 foreach ( $this->mLimitsShown
as $key => $value ) {
1205 # The pair is either $index => $limit, in which case the $value
1206 # will be numeric, or $limit => $text, in which case the $value
1208 if ( is_int( $value ) ) {
1210 $text = $this->getLanguage()->formatNum( $limit );
1215 $ret[$text] = $limit;
1221 * Get \<input type="hidden"\> elements for use in a method="get" form.
1222 * Resubmits all defined elements of the query string, except for a
1223 * blacklist, passed in the $blacklist parameter.
1225 * @param array $blacklist parameters from the request query which should not be resubmitted
1226 * @return String: HTML fragment
1228 function getHiddenFields( $blacklist = array() ) {
1229 $blacklist = (array)$blacklist;
1230 $query = $this->getRequest()->getQueryValues();
1231 foreach ( $blacklist as $name ) {
1232 unset( $query[$name] );
1235 foreach ( $query as $name => $value ) {
1236 $s .= Html
::hidden( $name, $value ) . "\n";
1242 * Get a form containing a limit selection dropdown
1244 * @return String: HTML fragment
1246 function getLimitForm() {
1249 return Html
::rawElement(
1253 'action' => $wgScript
1255 "\n" . $this->getLimitDropdown()
1260 * Gets a limit selection dropdown
1264 function getLimitDropdown() {
1265 # Make the select with some explanatory text
1266 $msgSubmit = $this->msg( 'table_pager_limit_submit' )->escaped();
1268 return $this->msg( 'table_pager_limit' )
1269 ->rawParams( $this->getLimitSelect() )->escaped() .
1270 "\n<input type=\"submit\" value=\"$msgSubmit\"/>\n" .
1271 $this->getHiddenFields( array( 'limit' ) );
1275 * Return true if the named field should be sortable by the UI, false
1278 * @param $field String
1280 abstract function isFieldSortable( $field );
1283 * Format a table cell. The return value should be HTML, but use an empty
1284 * string not   for empty cells. Do not include the <td> and </td>.
1286 * The current result row is available as $this->mCurrentRow, in case you
1287 * need more context.
1291 * @param string $name the database field name
1292 * @param string $value the value retrieved from the database
1294 abstract function formatValue( $name, $value );
1297 * The database field name used as a default sort order.
1303 abstract function getDefaultSort();
1306 * An array mapping database field names to a textual description of the
1307 * field name, for use in the table header. The description should be plain
1308 * text, it will be HTML-escaped later.
1312 abstract function getFieldNames();