Introduce a new hook that allows extensions to add to My Contributions
[mediawiki.git] / includes / Pager.php
blob9d1f9fcb7edbea8f195bac13e680782c2fa966df
1 <?php
2 /**
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
20 * @file
21 * @ingroup Pager
24 /**
25 * @defgroup Pager Pager
28 /**
29 * Basic pager interface.
30 * @ingroup Pager
32 interface Pager {
33 function getNavigationBar();
34 function getBody();
37 /**
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.
77 * @ingroup Pager
79 abstract class IndexPager extends ContextSource implements Pager {
80 public $mRequest;
81 public $mLimitsShown = array( 20, 50, 100, 250, 500 );
82 public $mDefaultLimit = 50;
83 public $mOffset, $mLimit;
84 public $mQueryDone = false;
85 public $mDb;
86 public $mPastTheEndRow;
88 /**
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;
93 /**
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 */
116 public $mIsFirst;
117 public $mIsLast;
119 protected $mLastShown, $mFirstShown, $mPastTheEndIndex, $mDefaultQuery, $mNavigationBar;
122 * Result object for the query. Warning: seek before use.
124 * @var ResultWrapper
126 public $mResult;
128 public function __construct( IContextSource $context = null ) {
129 if ( $context ) {
130 $this->setContext( $context );
133 $this->mRequest = $this->getRequest();
135 # NB: the offset is quoted, not validated. It is treated as an
136 # arbitrary string to support the widest variety of index types. Be
137 # careful outputting it into HTML!
138 $this->mOffset = $this->mRequest->getText( 'offset' );
140 # Use consistent behavior for the limit options
141 $this->mDefaultLimit = intval( $this->getUser()->getOption( 'rclimit' ) );
142 list( $this->mLimit, /* $offset */ ) = $this->mRequest->getLimitOffset();
144 $this->mIsBackwards = ( $this->mRequest->getVal( 'dir' ) == 'prev' );
145 $this->mDb = wfGetDB( DB_SLAVE );
147 $index = $this->getIndexField(); // column to sort on
148 $extraSort = $this->getExtraSortFields(); // extra columns to sort on for query planning
149 $order = $this->mRequest->getVal( 'order' );
150 if( is_array( $index ) && isset( $index[$order] ) ) {
151 $this->mOrderType = $order;
152 $this->mIndexField = $index[$order];
153 $this->mExtraSortFields = isset( $extraSort[$order] )
154 ? (array)$extraSort[$order]
155 : array();
156 } elseif( is_array( $index ) ) {
157 # First element is the default
158 reset( $index );
159 list( $this->mOrderType, $this->mIndexField ) = each( $index );
160 $this->mExtraSortFields = isset( $extraSort[$this->mOrderType] )
161 ? (array)$extraSort[$this->mOrderType]
162 : array();
163 } else {
164 # $index is not an array
165 $this->mOrderType = null;
166 $this->mIndexField = $index;
167 $this->mExtraSortFields = (array)$extraSort;
170 if( !isset( $this->mDefaultDirection ) ) {
171 $dir = $this->getDefaultDirections();
172 $this->mDefaultDirection = is_array( $dir )
173 ? $dir[$this->mOrderType]
174 : $dir;
179 * Do the query, using information from the object context. This function
180 * has been kept minimal to make it overridable if necessary, to allow for
181 * result sets formed from multiple DB queries.
183 public function doQuery() {
184 # Use the child class name for profiling
185 $fname = __METHOD__ . ' (' . get_class( $this ) . ')';
186 wfProfileIn( $fname );
188 $descending = ( $this->mIsBackwards == $this->mDefaultDirection );
189 # Plus an extra row so that we can tell the "next" link should be shown
190 $queryLimit = $this->mLimit + 1;
192 $this->mResult = $this->reallyDoQuery(
193 $this->mOffset,
194 $queryLimit,
195 $descending
198 $this->extractResultInfo( $this->mOffset, $queryLimit, $this->mResult );
199 $this->mQueryDone = true;
201 $this->preprocessResults( $this->mResult );
202 $this->mResult->rewind(); // Paranoia
204 wfProfileOut( $fname );
208 * @return ResultWrapper The result wrapper.
210 function getResult() {
211 return $this->mResult;
215 * Set the offset from an other source than the request
217 * @param $offset Int|String
219 function setOffset( $offset ) {
220 $this->mOffset = $offset;
223 * Set the limit from an other source than the request
225 * @param $limit Int|String
227 function setLimit( $limit ) {
228 $this->mLimit = $limit;
232 * Extract some useful data from the result object for use by
233 * the navigation bar, put it into $this
235 * @param $offset String: index offset, inclusive
236 * @param $limit Integer: exact query limit
237 * @param $res ResultWrapper
239 function extractResultInfo( $offset, $limit, ResultWrapper $res ) {
240 $numRows = $res->numRows();
241 if ( $numRows ) {
242 # Remove any table prefix from index field
243 $parts = explode( '.', $this->mIndexField );
244 $indexColumn = end( $parts );
246 $row = $res->fetchRow();
247 $firstIndex = $row[$indexColumn];
249 # Discard the extra result row if there is one
250 if ( $numRows > $this->mLimit && $numRows > 1 ) {
251 $res->seek( $numRows - 1 );
252 $this->mPastTheEndRow = $res->fetchObject();
253 $indexField = $this->mIndexField;
254 $this->mPastTheEndIndex = $this->mPastTheEndRow->$indexField;
255 $res->seek( $numRows - 2 );
256 $row = $res->fetchRow();
257 $lastIndex = $row[$indexColumn];
258 } else {
259 $this->mPastTheEndRow = null;
260 # Setting indexes to an empty string means that they will be
261 # omitted if they would otherwise appear in URLs. It just so
262 # happens that this is the right thing to do in the standard
263 # UI, in all the relevant cases.
264 $this->mPastTheEndIndex = '';
265 $res->seek( $numRows - 1 );
266 $row = $res->fetchRow();
267 $lastIndex = $row[$indexColumn];
269 } else {
270 $firstIndex = '';
271 $lastIndex = '';
272 $this->mPastTheEndRow = null;
273 $this->mPastTheEndIndex = '';
276 if ( $this->mIsBackwards ) {
277 $this->mIsFirst = ( $numRows < $limit );
278 $this->mIsLast = ( $offset == '' );
279 $this->mLastShown = $firstIndex;
280 $this->mFirstShown = $lastIndex;
281 } else {
282 $this->mIsFirst = ( $offset == '' );
283 $this->mIsLast = ( $numRows < $limit );
284 $this->mLastShown = $lastIndex;
285 $this->mFirstShown = $firstIndex;
290 * Get some text to go in brackets in the "function name" part of the SQL comment
292 * @return String
294 function getSqlComment() {
295 return get_class( $this );
299 * Do a query with specified parameters, rather than using the object
300 * context
302 * @param $offset String: index offset, inclusive
303 * @param $limit Integer: exact query limit
304 * @param $descending Boolean: query direction, false for ascending, true for descending
305 * @return ResultWrapper
307 public function reallyDoQuery( $offset, $limit, $descending ) {
308 list( $tables, $fields, $conds, $fname, $options, $join_conds ) = $this->buildQueryInfo( $offset, $limit, $descending );
309 $result = $this->mDb->select( $tables, $fields, $conds, $fname, $options, $join_conds );
310 return new ResultWrapper( $this->mDb, $result );
314 * Build variables to use by the database wrapper.
316 * @param $offset String: index offset, inclusive
317 * @param $limit Integer: exact query limit
318 * @param $descending Boolean: query direction, false for ascending, true for descending
319 * @return array
321 protected function buildQueryInfo( $offset, $limit, $descending ) {
322 $fname = __METHOD__ . ' (' . $this->getSqlComment() . ')';
323 $info = $this->getQueryInfo();
324 $tables = $info['tables'];
325 $fields = $info['fields'];
326 $conds = isset( $info['conds'] ) ? $info['conds'] : array();
327 $options = isset( $info['options'] ) ? $info['options'] : array();
328 $join_conds = isset( $info['join_conds'] ) ? $info['join_conds'] : array();
329 $sortColumns = array_merge( array( $this->mIndexField ), $this->mExtraSortFields );
330 if ( $descending ) {
331 $options['ORDER BY'] = $sortColumns;
332 $operator = '>';
333 } else {
334 $orderBy = array();
335 foreach ( $sortColumns as $col ) {
336 $orderBy[] = $col . ' DESC';
338 $options['ORDER BY'] = $orderBy;
339 $operator = '<';
341 if ( $offset != '' ) {
342 $conds[] = $this->mIndexField . $operator . $this->mDb->addQuotes( $offset );
344 $options['LIMIT'] = intval( $limit );
345 return array( $tables, $fields, $conds, $fname, $options, $join_conds );
349 * Pre-process results; useful for performing batch existence checks, etc.
351 * @param $result ResultWrapper
353 protected function preprocessResults( $result ) {}
356 * Get the formatted result list. Calls getStartBody(), formatRow() and
357 * getEndBody(), concatenates the results and returns them.
359 * @return String
361 public function getBody() {
362 if ( !$this->mQueryDone ) {
363 $this->doQuery();
366 if ( $this->mResult->numRows() ) {
367 # Do any special query batches before display
368 $this->doBatchLookups();
371 # Don't use any extra rows returned by the query
372 $numRows = min( $this->mResult->numRows(), $this->mLimit );
374 $s = $this->getStartBody();
375 if ( $numRows ) {
376 if ( $this->mIsBackwards ) {
377 for ( $i = $numRows - 1; $i >= 0; $i-- ) {
378 $this->mResult->seek( $i );
379 $row = $this->mResult->fetchObject();
380 $s .= $this->formatRow( $row );
382 } else {
383 $this->mResult->seek( 0 );
384 for ( $i = 0; $i < $numRows; $i++ ) {
385 $row = $this->mResult->fetchObject();
386 $s .= $this->formatRow( $row );
389 } else {
390 $s .= $this->getEmptyBody();
392 $s .= $this->getEndBody();
393 return $s;
397 * Make a self-link
399 * @param $text String: text displayed on the link
400 * @param $query Array: associative array of paramter to be in the query string
401 * @param $type String: value of the "rel" attribute
403 * @return String: HTML fragment
405 function makeLink( $text, array $query = null, $type = null ) {
406 if ( $query === null ) {
407 return $text;
410 $attrs = array();
411 if( in_array( $type, array( 'first', 'prev', 'next', 'last' ) ) ) {
412 # HTML5 rel attributes
413 $attrs['rel'] = $type;
416 if( $type ) {
417 $attrs['class'] = "mw-{$type}link";
420 return Linker::linkKnown(
421 $this->getTitle(),
422 $text,
423 $attrs,
424 $query + $this->getDefaultQuery()
429 * Called from getBody(), before getStartBody() is called and
430 * after doQuery() was called. This will be called only if there
431 * are rows in the result set.
433 * @return void
435 protected function doBatchLookups() {}
438 * Hook into getBody(), allows text to be inserted at the start. This
439 * will be called even if there are no rows in the result set.
441 * @return String
443 protected function getStartBody() {
444 return '';
448 * Hook into getBody() for the end of the list
450 * @return String
452 protected function getEndBody() {
453 return '';
457 * Hook into getBody(), for the bit between the start and the
458 * end when there are no rows
460 * @return String
462 protected function getEmptyBody() {
463 return '';
467 * Get an array of query parameters that should be put into self-links.
468 * By default, all parameters passed in the URL are used, except for a
469 * short blacklist.
471 * @return array Associative array
473 function getDefaultQuery() {
474 if ( !isset( $this->mDefaultQuery ) ) {
475 $this->mDefaultQuery = $this->getRequest()->getQueryValues();
476 unset( $this->mDefaultQuery['title'] );
477 unset( $this->mDefaultQuery['dir'] );
478 unset( $this->mDefaultQuery['offset'] );
479 unset( $this->mDefaultQuery['limit'] );
480 unset( $this->mDefaultQuery['order'] );
481 unset( $this->mDefaultQuery['month'] );
482 unset( $this->mDefaultQuery['year'] );
484 return $this->mDefaultQuery;
488 * Get the number of rows in the result set
490 * @return Integer
492 function getNumRows() {
493 if ( !$this->mQueryDone ) {
494 $this->doQuery();
496 return $this->mResult->numRows();
500 * Get a URL query array for the prev, next, first and last links.
502 * @return Array
504 function getPagingQueries() {
505 if ( !$this->mQueryDone ) {
506 $this->doQuery();
509 # Don't announce the limit everywhere if it's the default
510 $urlLimit = $this->mLimit == $this->mDefaultLimit ? null : $this->mLimit;
512 if ( $this->mIsFirst ) {
513 $prev = false;
514 $first = false;
515 } else {
516 $prev = array(
517 'dir' => 'prev',
518 'offset' => $this->mFirstShown,
519 'limit' => $urlLimit
521 $first = array( 'limit' => $urlLimit );
523 if ( $this->mIsLast ) {
524 $next = false;
525 $last = false;
526 } else {
527 $next = array( 'offset' => $this->mLastShown, 'limit' => $urlLimit );
528 $last = array( 'dir' => 'prev', 'limit' => $urlLimit );
530 return array(
531 'prev' => $prev,
532 'next' => $next,
533 'first' => $first,
534 'last' => $last
539 * Returns whether to show the "navigation bar"
541 * @return Boolean
543 function isNavigationBarShown() {
544 if ( !$this->mQueryDone ) {
545 $this->doQuery();
547 // Hide navigation by default if there is nothing to page
548 return !($this->mIsFirst && $this->mIsLast);
552 * Get paging links. If a link is disabled, the item from $disabledTexts
553 * will be used. If there is no such item, the unlinked text from
554 * $linkTexts will be used. Both $linkTexts and $disabledTexts are arrays
555 * of HTML.
557 * @param $linkTexts Array
558 * @param $disabledTexts Array
559 * @return Array
561 function getPagingLinks( $linkTexts, $disabledTexts = array() ) {
562 $queries = $this->getPagingQueries();
563 $links = array();
565 foreach ( $queries as $type => $query ) {
566 if ( $query !== false ) {
567 $links[$type] = $this->makeLink(
568 $linkTexts[$type],
569 $queries[$type],
570 $type
572 } elseif ( isset( $disabledTexts[$type] ) ) {
573 $links[$type] = $disabledTexts[$type];
574 } else {
575 $links[$type] = $linkTexts[$type];
579 return $links;
582 function getLimitLinks() {
583 $links = array();
584 if ( $this->mIsBackwards ) {
585 $offset = $this->mPastTheEndIndex;
586 } else {
587 $offset = $this->mOffset;
589 foreach ( $this->mLimitsShown as $limit ) {
590 $links[] = $this->makeLink(
591 $this->getLanguage()->formatNum( $limit ),
592 array( 'offset' => $offset, 'limit' => $limit ),
593 'num'
596 return $links;
600 * Abstract formatting function. This should return an HTML string
601 * representing the result row $row. Rows will be concatenated and
602 * returned by getBody()
604 * @param $row Object: database row
605 * @return String
607 abstract function formatRow( $row );
610 * This function should be overridden to provide all parameters
611 * needed for the main paged query. It returns an associative
612 * array with the following elements:
613 * tables => Table(s) for passing to Database::select()
614 * fields => Field(s) for passing to Database::select(), may be *
615 * conds => WHERE conditions
616 * options => option array
617 * join_conds => JOIN conditions
619 * @return Array
621 abstract function getQueryInfo();
624 * This function should be overridden to return the name of the index fi-
625 * eld. If the pager supports multiple orders, it may return an array of
626 * 'querykey' => 'indexfield' pairs, so that a request with &count=querykey
627 * will use indexfield to sort. In this case, the first returned key is
628 * the default.
630 * Needless to say, it's really not a good idea to use a non-unique index
631 * for this! That won't page right.
633 * @return string|Array
635 abstract function getIndexField();
638 * This function should be overridden to return the names of secondary columns
639 * to order by in addition to the column in getIndexField(). These fields will
640 * not be used in the pager offset or in any links for users.
642 * If getIndexField() returns an array of 'querykey' => 'indexfield' pairs then
643 * this must return a corresponding array of 'querykey' => array( fields...) pairs
644 * in order for a request with &count=querykey to use array( fields...) to sort.
646 * This is useful for pagers that GROUP BY a unique column (say page_id)
647 * and ORDER BY another (say page_len). Using GROUP BY and ORDER BY both on
648 * page_len,page_id avoids temp tables (given a page_len index). This would
649 * also work if page_id was non-unique but we had a page_len,page_id index.
651 * @return Array
653 protected function getExtraSortFields() { return array(); }
656 * Return the default sorting direction: false for ascending, true for de-
657 * scending. You can also have an associative array of ordertype => dir,
658 * if multiple order types are supported. In this case getIndexField()
659 * must return an array, and the keys of that must exactly match the keys
660 * of this.
662 * For backward compatibility, this method's return value will be ignored
663 * if $this->mDefaultDirection is already set when the constructor is
664 * called, for instance if it's statically initialized. In that case the
665 * value of that variable (which must be a boolean) will be used.
667 * Note that despite its name, this does not return the value of the
668 * $this->mDefaultDirection member variable. That's the default for this
669 * particular instantiation, which is a single value. This is the set of
670 * all defaults for the class.
672 * @return Boolean
674 protected function getDefaultDirections() { return false; }
679 * IndexPager with an alphabetic list and a formatted navigation bar
680 * @ingroup Pager
682 abstract class AlphabeticPager extends IndexPager {
685 * Shamelessly stolen bits from ReverseChronologicalPager,
686 * didn't want to do class magic as may be still revamped
688 * @return String HTML
690 function getNavigationBar() {
691 if ( !$this->isNavigationBarShown() ) {
692 return '';
695 if( isset( $this->mNavigationBar ) ) {
696 return $this->mNavigationBar;
699 $linkTexts = array(
700 'prev' => $this->msg( 'prevn' )->numParams( $this->mLimit )->escaped(),
701 'next' => $this->msg( 'nextn' )->numParams( $this->mLimit )->escaped(),
702 'first' => $this->msg( 'page_first' )->escaped(),
703 'last' => $this->msg( 'page_last' )->escaped()
706 $lang = $this->getLanguage();
708 $pagingLinks = $this->getPagingLinks( $linkTexts );
709 $limitLinks = $this->getLimitLinks();
710 $limits = $lang->pipeList( $limitLinks );
712 $this->mNavigationBar = $this->msg( 'parentheses' )->rawParams(
713 $lang->pipeList( array( $pagingLinks['first'],
714 $pagingLinks['last'] ) ) )->escaped() . " " .
715 $this->msg( 'viewprevnext' )->rawParams( $pagingLinks['prev'],
716 $pagingLinks['next'], $limits )->escaped();
718 if( !is_array( $this->getIndexField() ) ) {
719 # Early return to avoid undue nesting
720 return $this->mNavigationBar;
723 $extra = '';
724 $first = true;
725 $msgs = $this->getOrderTypeMessages();
726 foreach( array_keys( $msgs ) as $order ) {
727 if( $first ) {
728 $first = false;
729 } else {
730 $extra .= $this->msg( 'pipe-separator' )->escaped();
733 if( $order == $this->mOrderType ) {
734 $extra .= $this->msg( $msgs[$order] )->escaped();
735 } else {
736 $extra .= $this->makeLink(
737 $this->msg( $msgs[$order] )->escaped(),
738 array( 'order' => $order )
743 if( $extra !== '' ) {
744 $extra = ' ' . $this->msg( 'parentheses' )->rawParams( $extra )->escaped();
745 $this->mNavigationBar .= $extra;
748 return $this->mNavigationBar;
752 * If this supports multiple order type messages, give the message key for
753 * enabling each one in getNavigationBar. The return type is an associa-
754 * tive array whose keys must exactly match the keys of the array returned
755 * by getIndexField(), and whose values are message keys.
757 * @return Array
759 protected function getOrderTypeMessages() {
760 return null;
765 * IndexPager with a formatted navigation bar
766 * @ingroup Pager
768 abstract class ReverseChronologicalPager extends IndexPager {
769 public $mDefaultDirection = true;
770 public $mYear;
771 public $mMonth;
773 function getNavigationBar() {
774 if ( !$this->isNavigationBarShown() ) {
775 return '';
778 if ( isset( $this->mNavigationBar ) ) {
779 return $this->mNavigationBar;
782 $linkTexts = array(
783 'prev' => $this->msg( 'pager-newer-n' )->numParams( $this->mLimit )->escaped(),
784 'next' => $this->msg( 'pager-older-n' )->numParams( $this->mLimit )->escaped(),
785 'first' => $this->msg( 'histlast' )->escaped(),
786 'last' => $this->msg( 'histfirst' )->escaped()
789 $pagingLinks = $this->getPagingLinks( $linkTexts );
790 $limitLinks = $this->getLimitLinks();
791 $limits = $this->getLanguage()->pipeList( $limitLinks );
792 $firstLastLinks = $this->msg( 'parentheses' )->rawParams( "{$pagingLinks['first']}" .
793 $this->msg( 'pipe-separator' )->escaped() .
794 "{$pagingLinks['last']}" )->escaped();
796 $this->mNavigationBar = $firstLastLinks . ' ' .
797 $this->msg( 'viewprevnext' )->rawParams(
798 $pagingLinks['prev'], $pagingLinks['next'], $limits )->escaped();
800 return $this->mNavigationBar;
803 function getDateCond( $year, $month ) {
804 $year = intval( $year );
805 $month = intval( $month );
807 // Basic validity checks
808 $this->mYear = $year > 0 ? $year : false;
809 $this->mMonth = ( $month > 0 && $month < 13 ) ? $month : false;
811 // Given an optional year and month, we need to generate a timestamp
812 // to use as "WHERE rev_timestamp <= result"
813 // Examples: year = 2006 equals < 20070101 (+000000)
814 // year=2005, month=1 equals < 20050201
815 // year=2005, month=12 equals < 20060101
816 if ( !$this->mYear && !$this->mMonth ) {
817 return;
820 if ( $this->mYear ) {
821 $year = $this->mYear;
822 } else {
823 // If no year given, assume the current one
824 $year = gmdate( 'Y' );
825 // If this month hasn't happened yet this year, go back to last year's month
826 if( $this->mMonth > gmdate( 'n' ) ) {
827 $year--;
831 if ( $this->mMonth ) {
832 $month = $this->mMonth + 1;
833 // For December, we want January 1 of the next year
834 if ($month > 12) {
835 $month = 1;
836 $year++;
838 } else {
839 // No month implies we want up to the end of the year in question
840 $month = 1;
841 $year++;
844 // Y2K38 bug
845 if ( $year > 2032 ) {
846 $year = 2032;
849 $ymd = (int)sprintf( "%04d%02d01", $year, $month );
851 if ( $ymd > 20320101 ) {
852 $ymd = 20320101;
855 $this->mOffset = $this->mDb->timestamp( "${ymd}000000" );
860 * Table-based display with a user-selectable sort order
861 * @ingroup Pager
863 abstract class TablePager extends IndexPager {
864 var $mSort;
865 var $mCurrentRow;
867 public function __construct( IContextSource $context = null ) {
868 if ( $context ) {
869 $this->setContext( $context );
872 $this->mSort = $this->getRequest()->getText( 'sort' );
873 if ( !array_key_exists( $this->mSort, $this->getFieldNames() ) ) {
874 $this->mSort = $this->getDefaultSort();
876 if ( $this->getRequest()->getBool( 'asc' ) ) {
877 $this->mDefaultDirection = false;
878 } elseif ( $this->getRequest()->getBool( 'desc' ) ) {
879 $this->mDefaultDirection = true;
880 } /* Else leave it at whatever the class default is */
882 parent::__construct();
886 * @protected
887 * @return string
889 function getStartBody() {
890 global $wgStylePath;
891 $tableClass = htmlspecialchars( $this->getTableClass() );
892 $sortClass = htmlspecialchars( $this->getSortHeaderClass() );
894 $s = "<table style='border:1;' class=\"mw-datatable $tableClass\"><thead><tr>\n";
895 $fields = $this->getFieldNames();
897 # Make table header
898 foreach ( $fields as $field => $name ) {
899 if ( strval( $name ) == '' ) {
900 $s .= "<th>&#160;</th>\n";
901 } elseif ( $this->isFieldSortable( $field ) ) {
902 $query = array( 'sort' => $field, 'limit' => $this->mLimit );
903 if ( $field == $this->mSort ) {
904 # This is the sorted column
905 # Prepare a link that goes in the other sort order
906 if ( $this->mDefaultDirection ) {
907 # Descending
908 $image = 'Arr_d.png';
909 $query['asc'] = '1';
910 $query['desc'] = '';
911 $alt = $this->msg( 'descending_abbrev' )->escaped();
912 } else {
913 # Ascending
914 $image = 'Arr_u.png';
915 $query['asc'] = '';
916 $query['desc'] = '1';
917 $alt = $this->msg( 'ascending_abbrev' )->escaped();
919 $image = htmlspecialchars( "$wgStylePath/common/images/$image" );
920 $link = $this->makeLink(
921 "<img width=\"12\" height=\"12\" alt=\"$alt\" src=\"$image\" />" .
922 htmlspecialchars( $name ), $query );
923 $s .= "<th class=\"$sortClass\">$link</th>\n";
924 } else {
925 $s .= '<th>' . $this->makeLink( htmlspecialchars( $name ), $query ) . "</th>\n";
927 } else {
928 $s .= '<th>' . htmlspecialchars( $name ) . "</th>\n";
931 $s .= "</tr></thead><tbody>\n";
932 return $s;
936 * @protected
937 * @return string
939 function getEndBody() {
940 return "</tbody></table>\n";
944 * @protected
945 * @return string
947 function getEmptyBody() {
948 $colspan = count( $this->getFieldNames() );
949 $msgEmpty = $this->msg( 'table_pager_empty' )->escaped();
950 return "<tr><td colspan=\"$colspan\">$msgEmpty</td></tr>\n";
954 * @protected
955 * @param stdClass $row
956 * @return String HTML
958 function formatRow( $row ) {
959 $this->mCurrentRow = $row; // In case formatValue etc need to know
960 $s = Xml::openElement( 'tr', $this->getRowAttrs( $row ) );
961 $fieldNames = $this->getFieldNames();
963 foreach ( $fieldNames as $field => $name ) {
964 $value = isset( $row->$field ) ? $row->$field : null;
965 $formatted = strval( $this->formatValue( $field, $value ) );
967 if ( $formatted == '' ) {
968 $formatted = '&#160;';
971 $s .= Xml::tags( 'td', $this->getCellAttrs( $field, $value ), $formatted );
974 $s .= "</tr>\n";
976 return $s;
980 * Get a class name to be applied to the given row.
982 * @protected
984 * @param $row Object: the database result row
985 * @return String
987 function getRowClass( $row ) {
988 return '';
992 * Get attributes to be applied to the given row.
994 * @protected
996 * @param $row Object: the database result row
997 * @return Array of <attr> => <value>
999 function getRowAttrs( $row ) {
1000 $class = $this->getRowClass( $row );
1001 if ( $class === '' ) {
1002 // Return an empty array to avoid clutter in HTML like class=""
1003 return array();
1004 } else {
1005 return array( 'class' => $this->getRowClass( $row ) );
1010 * Get any extra attributes to be applied to the given cell. Don't
1011 * take this as an excuse to hardcode styles; use classes and
1012 * CSS instead. Row context is available in $this->mCurrentRow
1014 * @protected
1016 * @param $field String The column
1017 * @param $value String The cell contents
1018 * @return Array of attr => value
1020 function getCellAttrs( $field, $value ) {
1021 return array( 'class' => 'TablePager_col_' . $field );
1025 * @protected
1026 * @return string
1028 function getIndexField() {
1029 return $this->mSort;
1033 * @protected
1034 * @return string
1036 function getTableClass() {
1037 return 'TablePager';
1041 * @protected
1042 * @return string
1044 function getNavClass() {
1045 return 'TablePager_nav';
1049 * @protected
1050 * @return string
1052 function getSortHeaderClass() {
1053 return 'TablePager_sort';
1057 * A navigation bar with images
1058 * @return String HTML
1060 public function getNavigationBar() {
1061 global $wgStylePath;
1063 if ( !$this->isNavigationBarShown() ) {
1064 return '';
1067 $path = "$wgStylePath/common/images";
1068 $labels = array(
1069 'first' => 'table_pager_first',
1070 'prev' => 'table_pager_prev',
1071 'next' => 'table_pager_next',
1072 'last' => 'table_pager_last',
1074 $images = array(
1075 'first' => 'arrow_first_25.png',
1076 'prev' => 'arrow_left_25.png',
1077 'next' => 'arrow_right_25.png',
1078 'last' => 'arrow_last_25.png',
1080 $disabledImages = array(
1081 'first' => 'arrow_disabled_first_25.png',
1082 'prev' => 'arrow_disabled_left_25.png',
1083 'next' => 'arrow_disabled_right_25.png',
1084 'last' => 'arrow_disabled_last_25.png',
1086 if( $this->getLanguage()->isRTL() ) {
1087 $keys = array_keys( $labels );
1088 $images = array_combine( $keys, array_reverse( $images ) );
1089 $disabledImages = array_combine( $keys, array_reverse( $disabledImages ) );
1092 $linkTexts = array();
1093 $disabledTexts = array();
1094 foreach ( $labels as $type => $label ) {
1095 $msgLabel = $this->msg( $label )->escaped();
1096 $linkTexts[$type] = "<img src=\"$path/{$images[$type]}\" alt=\"$msgLabel\"/><br />$msgLabel";
1097 $disabledTexts[$type] = "<img src=\"$path/{$disabledImages[$type]}\" alt=\"$msgLabel\"/><br />$msgLabel";
1099 $links = $this->getPagingLinks( $linkTexts, $disabledTexts );
1101 $navClass = htmlspecialchars( $this->getNavClass() );
1102 $s = "<table class=\"$navClass\"><tr>\n";
1103 $width = 100 / count( $links ) . '%';
1104 foreach ( $labels as $type => $label ) {
1105 $s .= "<td style='width:$width;'>{$links[$type]}</td>\n";
1107 $s .= "</tr></table>\n";
1108 return $s;
1112 * Get a <select> element which has options for each of the allowed limits
1114 * @return String: HTML fragment
1116 public function getLimitSelect() {
1117 # Add the current limit from the query string
1118 # to avoid that the limit is lost after clicking Go next time
1119 if ( !in_array( $this->mLimit, $this->mLimitsShown ) ) {
1120 $this->mLimitsShown[] = $this->mLimit;
1121 sort( $this->mLimitsShown );
1123 $s = Html::openElement( 'select', array( 'name' => 'limit' ) ) . "\n";
1124 foreach ( $this->mLimitsShown as $key => $value ) {
1125 # The pair is either $index => $limit, in which case the $value
1126 # will be numeric, or $limit => $text, in which case the $value
1127 # will be a string.
1128 if( is_int( $value ) ){
1129 $limit = $value;
1130 $text = $this->getLanguage()->formatNum( $limit );
1131 } else {
1132 $limit = $key;
1133 $text = $value;
1135 $s .= Xml::option( $text, $limit, $limit == $this->mLimit ) . "\n";
1137 $s .= Html::closeElement( 'select' );
1138 return $s;
1142 * Get <input type="hidden"> elements for use in a method="get" form.
1143 * Resubmits all defined elements of the query string, except for a
1144 * blacklist, passed in the $blacklist parameter.
1146 * @param $blacklist Array parameters from the request query which should not be resubmitted
1147 * @return String: HTML fragment
1149 function getHiddenFields( $blacklist = array() ) {
1150 $blacklist = (array)$blacklist;
1151 $query = $this->getRequest()->getQueryValues();
1152 foreach ( $blacklist as $name ) {
1153 unset( $query[$name] );
1155 $s = '';
1156 foreach ( $query as $name => $value ) {
1157 $encName = htmlspecialchars( $name );
1158 $encValue = htmlspecialchars( $value );
1159 $s .= "<input type=\"hidden\" name=\"$encName\" value=\"$encValue\"/>\n";
1161 return $s;
1165 * Get a form containing a limit selection dropdown
1167 * @return String: HTML fragment
1169 function getLimitForm() {
1170 global $wgScript;
1172 return Xml::openElement(
1173 'form',
1174 array(
1175 'method' => 'get',
1176 'action' => $wgScript
1177 ) ) . "\n" . $this->getLimitDropdown() . "</form>\n";
1181 * Gets a limit selection dropdown
1183 * @return string
1185 function getLimitDropdown() {
1186 # Make the select with some explanatory text
1187 $msgSubmit = $this->msg( 'table_pager_limit_submit' )->escaped();
1189 return $this->msg( 'table_pager_limit' )
1190 ->rawParams( $this->getLimitSelect() )->escaped() .
1191 "\n<input type=\"submit\" value=\"$msgSubmit\"/>\n" .
1192 $this->getHiddenFields( array( 'limit' ) );
1196 * Return true if the named field should be sortable by the UI, false
1197 * otherwise
1199 * @param $field String
1201 abstract function isFieldSortable( $field );
1204 * Format a table cell. The return value should be HTML, but use an empty
1205 * string not &#160; for empty cells. Do not include the <td> and </td>.
1207 * The current result row is available as $this->mCurrentRow, in case you
1208 * need more context.
1210 * @protected
1212 * @param $name String: the database field name
1213 * @param $value String: the value retrieved from the database
1215 abstract function formatValue( $name, $value );
1218 * The database field name used as a default sort order.
1220 * @protected
1222 * @return string
1224 abstract function getDefaultSort();
1227 * An array mapping database field names to a textual description of the
1228 * field name, for use in the table header. The description should be plain
1229 * text, it will be HTML-escaped later.
1231 * @return Array
1233 abstract function getFieldNames();