Added OutputPage::setPageTitleMsg() and OutputPage::setHTMLTitleMsg() as modified...
[mediawiki.git] / includes / Pager.php
blobbfb011c0a147965d97f1c4aa3c56a4d615e42f56
1 <?php
2 /**
3 * @defgroup Pager Pager
5 * @file
6 * @ingroup Pager
7 */
9 /**
10 * Basic pager interface.
11 * @ingroup Pager
13 interface Pager {
14 function getNavigationBar();
15 function getBody();
18 /**
19 * IndexPager is an efficient pager which uses a (roughly unique) index in the
20 * data set to implement paging, rather than a "LIMIT offset,limit" clause.
21 * In MySQL, such a limit/offset clause requires counting through the
22 * specified number of offset rows to find the desired data, which can be
23 * expensive for large offsets.
25 * ReverseChronologicalPager is a child class of the abstract IndexPager, and
26 * contains some formatting and display code which is specific to the use of
27 * timestamps as indexes. Here is a synopsis of its operation:
29 * * The query is specified by the offset, limit and direction (dir)
30 * parameters, in addition to any subclass-specific parameters.
31 * * The offset is the non-inclusive start of the DB query. A row with an
32 * index value equal to the offset will never be shown.
33 * * The query may either be done backwards, where the rows are returned by
34 * the database in the opposite order to which they are displayed to the
35 * user, or forwards. This is specified by the "dir" parameter, dir=prev
36 * means backwards, anything else means forwards. The offset value
37 * specifies the start of the database result set, which may be either
38 * the start or end of the displayed data set. This allows "previous"
39 * links to be implemented without knowledge of the index value at the
40 * start of the previous page.
41 * * An additional row beyond the user-specified limit is always requested.
42 * This allows us to tell whether we should display a "next" link in the
43 * case of forwards mode, or a "previous" link in the case of backwards
44 * mode. Determining whether to display the other link (the one for the
45 * page before the start of the database result set) can be done
46 * heuristically by examining the offset.
48 * * An empty offset indicates that the offset condition should be omitted
49 * from the query. This naturally produces either the first page or the
50 * last page depending on the dir parameter.
52 * Subclassing the pager to implement concrete functionality should be fairly
53 * simple, please see the examples in HistoryPage.php and
54 * SpecialBlockList.php. You just need to override formatRow(),
55 * getQueryInfo() and getIndexField(). Don't forget to call the parent
56 * constructor if you override it.
58 * @ingroup Pager
60 abstract class IndexPager extends ContextSource implements Pager {
61 public $mRequest;
62 public $mLimitsShown = array( 20, 50, 100, 250, 500 );
63 public $mDefaultLimit = 50;
64 public $mOffset, $mLimit;
65 public $mQueryDone = false;
66 public $mDb;
67 public $mPastTheEndRow;
69 /**
70 * The index to actually be used for ordering. This is a single column,
71 * for one ordering, even if multiple orderings are supported.
73 protected $mIndexField;
74 /**
75 * An array of secondary columns to order by. These fields are not part of the offset.
76 * This is a column list for one ordering, even if multiple orderings are supported.
78 protected $mExtraSortFields;
79 /** For pages that support multiple types of ordering, which one to use.
81 protected $mOrderType;
82 /**
83 * $mDefaultDirection gives the direction to use when sorting results:
84 * false for ascending, true for descending. If $mIsBackwards is set, we
85 * start from the opposite end, but we still sort the page itself according
86 * to $mDefaultDirection. E.g., if $mDefaultDirection is false but we're
87 * going backwards, we'll display the last page of results, but the last
88 * result will be at the bottom, not the top.
90 * Like $mIndexField, $mDefaultDirection will be a single value even if the
91 * class supports multiple default directions for different order types.
93 public $mDefaultDirection;
94 public $mIsBackwards;
96 /** True if the current result set is the first one */
97 public $mIsFirst;
98 public $mIsLast;
100 protected $mLastShown, $mFirstShown, $mPastTheEndIndex, $mDefaultQuery, $mNavigationBar;
103 * Result object for the query. Warning: seek before use.
105 * @var ResultWrapper
107 public $mResult;
109 public function __construct( IContextSource $context = null ) {
110 if ( $context ) {
111 $this->setContext( $context );
114 $this->mRequest = $this->getRequest();
116 # NB: the offset is quoted, not validated. It is treated as an
117 # arbitrary string to support the widest variety of index types. Be
118 # careful outputting it into HTML!
119 $this->mOffset = $this->mRequest->getText( 'offset' );
121 # Use consistent behavior for the limit options
122 $this->mDefaultLimit = intval( $this->getUser()->getOption( 'rclimit' ) );
123 list( $this->mLimit, /* $offset */ ) = $this->mRequest->getLimitOffset();
125 $this->mIsBackwards = ( $this->mRequest->getVal( 'dir' ) == 'prev' );
126 $this->mDb = wfGetDB( DB_SLAVE );
128 $index = $this->getIndexField(); // column to sort on
129 $extraSort = $this->getExtraSortFields(); // extra columns to sort on for query planning
130 $order = $this->mRequest->getVal( 'order' );
131 if( is_array( $index ) && isset( $index[$order] ) ) {
132 $this->mOrderType = $order;
133 $this->mIndexField = $index[$order];
134 $this->mExtraSortFields = isset( $extraSort[$order] )
135 ? (array)$extraSort[$order]
136 : array();
137 } elseif( is_array( $index ) ) {
138 # First element is the default
139 reset( $index );
140 list( $this->mOrderType, $this->mIndexField ) = each( $index );
141 $this->mExtraSortFields = isset( $extraSort[$this->mOrderType] )
142 ? (array)$extraSort[$this->mOrderType]
143 : array();
144 } else {
145 # $index is not an array
146 $this->mOrderType = null;
147 $this->mIndexField = $index;
148 $this->mExtraSortFields = (array)$extraSort;
151 if( !isset( $this->mDefaultDirection ) ) {
152 $dir = $this->getDefaultDirections();
153 $this->mDefaultDirection = is_array( $dir )
154 ? $dir[$this->mOrderType]
155 : $dir;
160 * Do the query, using information from the object context. This function
161 * has been kept minimal to make it overridable if necessary, to allow for
162 * result sets formed from multiple DB queries.
164 public function doQuery() {
165 # Use the child class name for profiling
166 $fname = __METHOD__ . ' (' . get_class( $this ) . ')';
167 wfProfileIn( $fname );
169 $descending = ( $this->mIsBackwards == $this->mDefaultDirection );
170 # Plus an extra row so that we can tell the "next" link should be shown
171 $queryLimit = $this->mLimit + 1;
173 $this->mResult = $this->reallyDoQuery(
174 $this->mOffset,
175 $queryLimit,
176 $descending
178 $this->extractResultInfo( $this->mOffset, $queryLimit, $this->mResult );
179 $this->mQueryDone = true;
181 $this->preprocessResults( $this->mResult );
182 $this->mResult->rewind(); // Paranoia
184 wfProfileOut( $fname );
188 * @return ResultWrapper The result wrapper.
190 function getResult() {
191 return $this->mResult;
195 * Set the offset from an other source than the request
197 * @param $offset Int|String
199 function setOffset( $offset ) {
200 $this->mOffset = $offset;
203 * Set the limit from an other source than the request
205 * @param $limit Int|String
207 function setLimit( $limit ) {
208 $this->mLimit = $limit;
212 * Extract some useful data from the result object for use by
213 * the navigation bar, put it into $this
215 * @param $offset String: index offset, inclusive
216 * @param $limit Integer: exact query limit
217 * @param $res ResultWrapper
219 function extractResultInfo( $offset, $limit, ResultWrapper $res ) {
220 $numRows = $res->numRows();
221 if ( $numRows ) {
222 # Remove any table prefix from index field
223 $parts = explode( '.', $this->mIndexField );
224 $indexColumn = end( $parts );
226 $row = $res->fetchRow();
227 $firstIndex = $row[$indexColumn];
229 # Discard the extra result row if there is one
230 if ( $numRows > $this->mLimit && $numRows > 1 ) {
231 $res->seek( $numRows - 1 );
232 $this->mPastTheEndRow = $res->fetchObject();
233 $indexField = $this->mIndexField;
234 $this->mPastTheEndIndex = $this->mPastTheEndRow->$indexField;
235 $res->seek( $numRows - 2 );
236 $row = $res->fetchRow();
237 $lastIndex = $row[$indexColumn];
238 } else {
239 $this->mPastTheEndRow = null;
240 # Setting indexes to an empty string means that they will be
241 # omitted if they would otherwise appear in URLs. It just so
242 # happens that this is the right thing to do in the standard
243 # UI, in all the relevant cases.
244 $this->mPastTheEndIndex = '';
245 $res->seek( $numRows - 1 );
246 $row = $res->fetchRow();
247 $lastIndex = $row[$indexColumn];
249 } else {
250 $firstIndex = '';
251 $lastIndex = '';
252 $this->mPastTheEndRow = null;
253 $this->mPastTheEndIndex = '';
256 if ( $this->mIsBackwards ) {
257 $this->mIsFirst = ( $numRows < $limit );
258 $this->mIsLast = ( $offset == '' );
259 $this->mLastShown = $firstIndex;
260 $this->mFirstShown = $lastIndex;
261 } else {
262 $this->mIsFirst = ( $offset == '' );
263 $this->mIsLast = ( $numRows < $limit );
264 $this->mLastShown = $lastIndex;
265 $this->mFirstShown = $firstIndex;
270 * Get some text to go in brackets in the "function name" part of the SQL comment
272 * @return String
274 function getSqlComment() {
275 return get_class( $this );
279 * Do a query with specified parameters, rather than using the object
280 * context
282 * @param $offset String: index offset, inclusive
283 * @param $limit Integer: exact query limit
284 * @param $descending Boolean: query direction, false for ascending, true for descending
285 * @return ResultWrapper
287 function reallyDoQuery( $offset, $limit, $descending ) {
288 $fname = __METHOD__ . ' (' . $this->getSqlComment() . ')';
289 $info = $this->getQueryInfo();
290 $tables = $info['tables'];
291 $fields = $info['fields'];
292 $conds = isset( $info['conds'] ) ? $info['conds'] : array();
293 $options = isset( $info['options'] ) ? $info['options'] : array();
294 $join_conds = isset( $info['join_conds'] ) ? $info['join_conds'] : array();
295 $sortColumns = array_merge( array( $this->mIndexField ), $this->mExtraSortFields );
296 if ( $descending ) {
297 $options['ORDER BY'] = implode( ',', $sortColumns );
298 $operator = '>';
299 } else {
300 $orderBy = array();
301 foreach ( $sortColumns as $col ) {
302 $orderBy[] = $col . ' DESC';
304 $options['ORDER BY'] = implode( ',', $orderBy );
305 $operator = '<';
307 if ( $offset != '' ) {
308 $conds[] = $this->mIndexField . $operator . $this->mDb->addQuotes( $offset );
310 $options['LIMIT'] = intval( $limit );
311 $res = $this->mDb->select( $tables, $fields, $conds, $fname, $options, $join_conds );
312 return new ResultWrapper( $this->mDb, $res );
316 * Pre-process results; useful for performing batch existence checks, etc.
318 * @param $result ResultWrapper
320 protected function preprocessResults( $result ) {}
323 * Get the formatted result list. Calls getStartBody(), formatRow() and
324 * getEndBody(), concatenates the results and returns them.
326 * @return String
328 public function getBody() {
329 if ( !$this->mQueryDone ) {
330 $this->doQuery();
332 # Do any special query batches before display
333 $this->doBatchLookups();
335 # Don't use any extra rows returned by the query
336 $numRows = min( $this->mResult->numRows(), $this->mLimit );
338 $s = $this->getStartBody();
339 if ( $numRows ) {
340 if ( $this->mIsBackwards ) {
341 for ( $i = $numRows - 1; $i >= 0; $i-- ) {
342 $this->mResult->seek( $i );
343 $row = $this->mResult->fetchObject();
344 $s .= $this->formatRow( $row );
346 } else {
347 $this->mResult->seek( 0 );
348 for ( $i = 0; $i < $numRows; $i++ ) {
349 $row = $this->mResult->fetchObject();
350 $s .= $this->formatRow( $row );
353 } else {
354 $s .= $this->getEmptyBody();
356 $s .= $this->getEndBody();
357 return $s;
361 * Make a self-link
363 * @param $text String: text displayed on the link
364 * @param $query Array: associative array of paramter to be in the query string
365 * @param $type String: value of the "rel" attribute
366 * @return String: HTML fragment
368 function makeLink($text, $query = null, $type=null) {
369 if ( $query === null ) {
370 return $text;
373 $attrs = array();
374 if( in_array( $type, array( 'first', 'prev', 'next', 'last' ) ) ) {
375 # HTML5 rel attributes
376 $attrs['rel'] = $type;
379 if( $type ) {
380 $attrs['class'] = "mw-{$type}link";
382 return Linker::linkKnown(
383 $this->getTitle(),
384 $text,
385 $attrs,
386 $query + $this->getDefaultQuery()
391 * Called from getBody(), before getStartBody() is called and
392 * after doQuery() was called. This will be called even if there
393 * are no rows in the result set.
395 * @return void
397 protected function doBatchLookups() {}
400 * Hook into getBody(), allows text to be inserted at the start. This
401 * will be called even if there are no rows in the result set.
403 * @return String
405 protected function getStartBody() {
406 return '';
410 * Hook into getBody() for the end of the list
412 * @return String
414 protected function getEndBody() {
415 return '';
419 * Hook into getBody(), for the bit between the start and the
420 * end when there are no rows
422 * @return String
424 protected function getEmptyBody() {
425 return '';
429 * Get an array of query parameters that should be put into self-links.
430 * By default, all parameters passed in the URL are used, except for a
431 * short blacklist.
433 * @return Associative array
435 function getDefaultQuery() {
436 if ( !isset( $this->mDefaultQuery ) ) {
437 $this->mDefaultQuery = $this->getRequest()->getQueryValues();
438 unset( $this->mDefaultQuery['title'] );
439 unset( $this->mDefaultQuery['dir'] );
440 unset( $this->mDefaultQuery['offset'] );
441 unset( $this->mDefaultQuery['limit'] );
442 unset( $this->mDefaultQuery['order'] );
443 unset( $this->mDefaultQuery['month'] );
444 unset( $this->mDefaultQuery['year'] );
446 return $this->mDefaultQuery;
450 * Get the number of rows in the result set
452 * @return Integer
454 function getNumRows() {
455 if ( !$this->mQueryDone ) {
456 $this->doQuery();
458 return $this->mResult->numRows();
462 * Get a URL query array for the prev, next, first and last links.
464 * @return Array
466 function getPagingQueries() {
467 if ( !$this->mQueryDone ) {
468 $this->doQuery();
471 # Don't announce the limit everywhere if it's the default
472 $urlLimit = $this->mLimit == $this->mDefaultLimit ? '' : $this->mLimit;
474 if ( $this->mIsFirst ) {
475 $prev = false;
476 $first = false;
477 } else {
478 $prev = array(
479 'dir' => 'prev',
480 'offset' => $this->mFirstShown,
481 'limit' => $urlLimit
483 $first = array( 'limit' => $urlLimit );
485 if ( $this->mIsLast ) {
486 $next = false;
487 $last = false;
488 } else {
489 $next = array( 'offset' => $this->mLastShown, 'limit' => $urlLimit );
490 $last = array( 'dir' => 'prev', 'limit' => $urlLimit );
492 return array(
493 'prev' => $prev,
494 'next' => $next,
495 'first' => $first,
496 'last' => $last
501 * Returns whether to show the "navigation bar"
503 * @return Boolean
505 function isNavigationBarShown() {
506 if ( !$this->mQueryDone ) {
507 $this->doQuery();
509 // Hide navigation by default if there is nothing to page
510 return !($this->mIsFirst && $this->mIsLast);
514 * Get paging links. If a link is disabled, the item from $disabledTexts
515 * will be used. If there is no such item, the unlinked text from
516 * $linkTexts will be used. Both $linkTexts and $disabledTexts are arrays
517 * of HTML.
519 * @param $linkTexts Array
520 * @param $disabledTexts Array
521 * @return Array
523 function getPagingLinks( $linkTexts, $disabledTexts = array() ) {
524 $queries = $this->getPagingQueries();
525 $links = array();
526 foreach ( $queries as $type => $query ) {
527 if ( $query !== false ) {
528 $links[$type] = $this->makeLink(
529 $linkTexts[$type],
530 $queries[$type],
531 $type
533 } elseif ( isset( $disabledTexts[$type] ) ) {
534 $links[$type] = $disabledTexts[$type];
535 } else {
536 $links[$type] = $linkTexts[$type];
539 return $links;
542 function getLimitLinks() {
543 $links = array();
544 if ( $this->mIsBackwards ) {
545 $offset = $this->mPastTheEndIndex;
546 } else {
547 $offset = $this->mOffset;
549 foreach ( $this->mLimitsShown as $limit ) {
550 $links[] = $this->makeLink(
551 $this->getLang()->formatNum( $limit ),
552 array( 'offset' => $offset, 'limit' => $limit ),
553 'num'
556 return $links;
560 * Abstract formatting function. This should return an HTML string
561 * representing the result row $row. Rows will be concatenated and
562 * returned by getBody()
564 * @param $row Object: database row
565 * @return String
567 abstract function formatRow( $row );
570 * This function should be overridden to provide all parameters
571 * needed for the main paged query. It returns an associative
572 * array with the following elements:
573 * tables => Table(s) for passing to Database::select()
574 * fields => Field(s) for passing to Database::select(), may be *
575 * conds => WHERE conditions
576 * options => option array
577 * join_conds => JOIN conditions
579 * @return Array
581 abstract function getQueryInfo();
584 * This function should be overridden to return the name of the index fi-
585 * eld. If the pager supports multiple orders, it may return an array of
586 * 'querykey' => 'indexfield' pairs, so that a request with &count=querykey
587 * will use indexfield to sort. In this case, the first returned key is
588 * the default.
590 * Needless to say, it's really not a good idea to use a non-unique index
591 * for this! That won't page right.
593 * @return string|Array
595 abstract function getIndexField();
598 * This function should be overridden to return the names of secondary columns
599 * to order by in addition to the column in getIndexField(). These fields will
600 * not be used in the pager offset or in any links for users.
602 * If getIndexField() returns an array of 'querykey' => 'indexfield' pairs then
603 * this must return a corresponding array of 'querykey' => array( fields...) pairs
604 * in order for a request with &count=querykey to use array( fields...) to sort.
606 * This is useful for pagers that GROUP BY a unique column (say page_id)
607 * and ORDER BY another (say page_len). Using GROUP BY and ORDER BY both on
608 * page_len,page_id avoids temp tables (given a page_len index). This would
609 * also work if page_id was non-unique but we had a page_len,page_id index.
611 * @return Array
613 protected function getExtraSortFields() { return array(); }
616 * Return the default sorting direction: false for ascending, true for de-
617 * scending. You can also have an associative array of ordertype => dir,
618 * if multiple order types are supported. In this case getIndexField()
619 * must return an array, and the keys of that must exactly match the keys
620 * of this.
622 * For backward compatibility, this method's return value will be ignored
623 * if $this->mDefaultDirection is already set when the constructor is
624 * called, for instance if it's statically initialized. In that case the
625 * value of that variable (which must be a boolean) will be used.
627 * Note that despite its name, this does not return the value of the
628 * $this->mDefaultDirection member variable. That's the default for this
629 * particular instantiation, which is a single value. This is the set of
630 * all defaults for the class.
632 * @return Boolean
634 protected function getDefaultDirections() { return false; }
639 * IndexPager with an alphabetic list and a formatted navigation bar
640 * @ingroup Pager
642 abstract class AlphabeticPager extends IndexPager {
645 * Shamelessly stolen bits from ReverseChronologicalPager,
646 * didn't want to do class magic as may be still revamped
648 * @return String HTML
650 function getNavigationBar() {
651 if ( !$this->isNavigationBarShown() ) return '';
653 if( isset( $this->mNavigationBar ) ) {
654 return $this->mNavigationBar;
657 $lang = $this->getLang();
659 $opts = array( 'parsemag', 'escapenoentities' );
660 $linkTexts = array(
661 'prev' => wfMsgExt(
662 'prevn',
663 $opts,
664 $lang->formatNum( $this->mLimit )
666 'next' => wfMsgExt(
667 'nextn',
668 $opts,
669 $lang->formatNum($this->mLimit )
671 'first' => wfMsgExt( 'page_first', $opts ),
672 'last' => wfMsgExt( 'page_last', $opts )
675 $pagingLinks = $this->getPagingLinks( $linkTexts );
676 $limitLinks = $this->getLimitLinks();
677 $limits = $lang->pipeList( $limitLinks );
679 $this->mNavigationBar =
680 "(" . $lang->pipeList(
681 array( $pagingLinks['first'],
682 $pagingLinks['last'] )
683 ) . ") " .
684 wfMsgHtml( 'viewprevnext', $pagingLinks['prev'],
685 $pagingLinks['next'], $limits );
687 if( !is_array( $this->getIndexField() ) ) {
688 # Early return to avoid undue nesting
689 return $this->mNavigationBar;
692 $extra = '';
693 $first = true;
694 $msgs = $this->getOrderTypeMessages();
695 foreach( array_keys( $msgs ) as $order ) {
696 if( $first ) {
697 $first = false;
698 } else {
699 $extra .= wfMsgExt( 'pipe-separator' , 'escapenoentities' );
702 if( $order == $this->mOrderType ) {
703 $extra .= wfMsgHTML( $msgs[$order] );
704 } else {
705 $extra .= $this->makeLink(
706 wfMsgHTML( $msgs[$order] ),
707 array( 'order' => $order )
712 if( $extra !== '' ) {
713 $this->mNavigationBar .= " ($extra)";
716 return $this->mNavigationBar;
720 * If this supports multiple order type messages, give the message key for
721 * enabling each one in getNavigationBar. The return type is an associa-
722 * tive array whose keys must exactly match the keys of the array returned
723 * by getIndexField(), and whose values are message keys.
725 * @return Array
727 protected function getOrderTypeMessages() {
728 return null;
733 * IndexPager with a formatted navigation bar
734 * @ingroup Pager
736 abstract class ReverseChronologicalPager extends IndexPager {
737 public $mDefaultDirection = true;
738 public $mYear;
739 public $mMonth;
741 function getNavigationBar() {
742 if ( !$this->isNavigationBarShown() ) {
743 return '';
746 if ( isset( $this->mNavigationBar ) ) {
747 return $this->mNavigationBar;
750 $nicenumber = $this->getLang()->formatNum( $this->mLimit );
751 $linkTexts = array(
752 'prev' => wfMsgExt(
753 'pager-newer-n',
754 array( 'parsemag', 'escape' ),
755 $nicenumber
757 'next' => wfMsgExt(
758 'pager-older-n',
759 array( 'parsemag', 'escape' ),
760 $nicenumber
762 'first' => wfMsgHtml( 'histlast' ),
763 'last' => wfMsgHtml( 'histfirst' )
766 $pagingLinks = $this->getPagingLinks( $linkTexts );
767 $limitLinks = $this->getLimitLinks();
768 $limits = $this->getLang()->pipeList( $limitLinks );
770 $this->mNavigationBar = "({$pagingLinks['first']}" .
771 wfMsgExt( 'pipe-separator' , 'escapenoentities' ) .
772 "{$pagingLinks['last']}) " .
773 wfMsgHTML(
774 'viewprevnext',
775 $pagingLinks['prev'], $pagingLinks['next'],
776 $limits
778 return $this->mNavigationBar;
781 function getDateCond( $year, $month ) {
782 $year = intval($year);
783 $month = intval($month);
784 // Basic validity checks
785 $this->mYear = $year > 0 ? $year : false;
786 $this->mMonth = ($month > 0 && $month < 13) ? $month : false;
787 // Given an optional year and month, we need to generate a timestamp
788 // to use as "WHERE rev_timestamp <= result"
789 // Examples: year = 2006 equals < 20070101 (+000000)
790 // year=2005, month=1 equals < 20050201
791 // year=2005, month=12 equals < 20060101
792 if ( !$this->mYear && !$this->mMonth ) {
793 return;
795 if ( $this->mYear ) {
796 $year = $this->mYear;
797 } else {
798 // If no year given, assume the current one
799 $year = gmdate( 'Y' );
800 // If this month hasn't happened yet this year, go back to last year's month
801 if( $this->mMonth > gmdate( 'n' ) ) {
802 $year--;
805 if ( $this->mMonth ) {
806 $month = $this->mMonth + 1;
807 // For December, we want January 1 of the next year
808 if ($month > 12) {
809 $month = 1;
810 $year++;
812 } else {
813 // No month implies we want up to the end of the year in question
814 $month = 1;
815 $year++;
817 // Y2K38 bug
818 if ( $year > 2032 ) {
819 $year = 2032;
821 $ymd = (int)sprintf( "%04d%02d01", $year, $month );
822 if ( $ymd > 20320101 ) {
823 $ymd = 20320101;
825 $this->mOffset = $this->mDb->timestamp( "${ymd}000000" );
830 * Table-based display with a user-selectable sort order
831 * @ingroup Pager
833 abstract class TablePager extends IndexPager {
834 var $mSort;
835 var $mCurrentRow;
837 function __construct( IContextSource $context = null ) {
838 if ( $context ) {
839 $this->setContext( $context );
842 $this->mSort = $this->getRequest()->getText( 'sort' );
843 if ( !array_key_exists( $this->mSort, $this->getFieldNames() ) ) {
844 $this->mSort = $this->getDefaultSort();
846 if ( $this->getRequest()->getBool( 'asc' ) ) {
847 $this->mDefaultDirection = false;
848 } elseif ( $this->getRequest()->getBool( 'desc' ) ) {
849 $this->mDefaultDirection = true;
850 } /* Else leave it at whatever the class default is */
852 parent::__construct();
855 function getStartBody() {
856 global $wgStylePath;
857 $tableClass = htmlspecialchars( $this->getTableClass() );
858 $sortClass = htmlspecialchars( $this->getSortHeaderClass() );
860 $s = "<table style='border:1;' class=\"mw-datatable $tableClass\"><thead><tr>\n";
861 $fields = $this->getFieldNames();
863 # Make table header
864 foreach ( $fields as $field => $name ) {
865 if ( strval( $name ) == '' ) {
866 $s .= "<th>&#160;</th>\n";
867 } elseif ( $this->isFieldSortable( $field ) ) {
868 $query = array( 'sort' => $field, 'limit' => $this->mLimit );
869 if ( $field == $this->mSort ) {
870 # This is the sorted column
871 # Prepare a link that goes in the other sort order
872 if ( $this->mDefaultDirection ) {
873 # Descending
874 $image = 'Arr_d.png';
875 $query['asc'] = '1';
876 $query['desc'] = '';
877 $alt = htmlspecialchars( wfMsg( 'descending_abbrev' ) );
878 } else {
879 # Ascending
880 $image = 'Arr_u.png';
881 $query['asc'] = '';
882 $query['desc'] = '1';
883 $alt = htmlspecialchars( wfMsg( 'ascending_abbrev' ) );
885 $image = htmlspecialchars( "$wgStylePath/common/images/$image" );
886 $link = $this->makeLink(
887 "<img width=\"12\" height=\"12\" alt=\"$alt\" src=\"$image\" />" .
888 htmlspecialchars( $name ), $query );
889 $s .= "<th class=\"$sortClass\">$link</th>\n";
890 } else {
891 $s .= '<th>' . $this->makeLink( htmlspecialchars( $name ), $query ) . "</th>\n";
893 } else {
894 $s .= '<th>' . htmlspecialchars( $name ) . "</th>\n";
897 $s .= "</tr></thead><tbody>\n";
898 return $s;
901 function getEndBody() {
902 return "</tbody></table>\n";
905 function getEmptyBody() {
906 $colspan = count( $this->getFieldNames() );
907 $msgEmpty = wfMsgHtml( 'table_pager_empty' );
908 return "<tr><td colspan=\"$colspan\">$msgEmpty</td></tr>\n";
912 * @param $row Array
913 * @return String HTML
915 function formatRow( $row ) {
916 $this->mCurrentRow = $row; # In case formatValue etc need to know
917 $s = Xml::openElement( 'tr', $this->getRowAttrs( $row ) );
918 $fieldNames = $this->getFieldNames();
919 foreach ( $fieldNames as $field => $name ) {
920 $value = isset( $row->$field ) ? $row->$field : null;
921 $formatted = strval( $this->formatValue( $field, $value ) );
922 if ( $formatted == '' ) {
923 $formatted = '&#160;';
925 $s .= Xml::tags( 'td', $this->getCellAttrs( $field, $value ), $formatted );
927 $s .= "</tr>\n";
928 return $s;
932 * Get a class name to be applied to the given row.
934 * @param $row Object: the database result row
935 * @return String
937 function getRowClass( $row ) {
938 return '';
942 * Get attributes to be applied to the given row.
944 * @param $row Object: the database result row
945 * @return Array of <attr> => <value>
947 function getRowAttrs( $row ) {
948 $class = $this->getRowClass( $row );
949 if ( $class === '' ) {
950 // Return an empty array to avoid clutter in HTML like class=""
951 return array();
952 } else {
953 return array( 'class' => $this->getRowClass( $row ) );
958 * Get any extra attributes to be applied to the given cell. Don't
959 * take this as an excuse to hardcode styles; use classes and
960 * CSS instead. Row context is available in $this->mCurrentRow
962 * @param $field String The column
963 * @param $value String The cell contents
964 * @return Array of attr => value
966 function getCellAttrs( $field, $value ) {
967 return array( 'class' => 'TablePager_col_' . $field );
970 function getIndexField() {
971 return $this->mSort;
974 function getTableClass() {
975 return 'TablePager';
978 function getNavClass() {
979 return 'TablePager_nav';
982 function getSortHeaderClass() {
983 return 'TablePager_sort';
987 * A navigation bar with images
988 * @return String HTML
990 function getNavigationBar() {
991 global $wgStylePath;
993 if ( !$this->isNavigationBarShown() ) {
994 return '';
997 $path = "$wgStylePath/common/images";
998 $labels = array(
999 'first' => 'table_pager_first',
1000 'prev' => 'table_pager_prev',
1001 'next' => 'table_pager_next',
1002 'last' => 'table_pager_last',
1004 $images = array(
1005 'first' => 'arrow_first_25.png',
1006 'prev' => 'arrow_left_25.png',
1007 'next' => 'arrow_right_25.png',
1008 'last' => 'arrow_last_25.png',
1010 $disabledImages = array(
1011 'first' => 'arrow_disabled_first_25.png',
1012 'prev' => 'arrow_disabled_left_25.png',
1013 'next' => 'arrow_disabled_right_25.png',
1014 'last' => 'arrow_disabled_last_25.png',
1016 if( $this->getLang()->isRTL() ) {
1017 $keys = array_keys( $labels );
1018 $images = array_combine( $keys, array_reverse( $images ) );
1019 $disabledImages = array_combine( $keys, array_reverse( $disabledImages ) );
1022 $linkTexts = array();
1023 $disabledTexts = array();
1024 foreach ( $labels as $type => $label ) {
1025 $msgLabel = wfMsgHtml( $label );
1026 $linkTexts[$type] = "<img src=\"$path/{$images[$type]}\" alt=\"$msgLabel\"/><br />$msgLabel";
1027 $disabledTexts[$type] = "<img src=\"$path/{$disabledImages[$type]}\" alt=\"$msgLabel\"/><br />$msgLabel";
1029 $links = $this->getPagingLinks( $linkTexts, $disabledTexts );
1031 $navClass = htmlspecialchars( $this->getNavClass() );
1032 $s = "<table class=\"$navClass\"><tr>\n";
1033 $width = 100 / count( $links ) . '%';
1034 foreach ( $labels as $type => $label ) {
1035 $s .= "<td style='width:$width;'>{$links[$type]}</td>\n";
1037 $s .= "</tr></table>\n";
1038 return $s;
1042 * Get a <select> element which has options for each of the allowed limits
1044 * @return String: HTML fragment
1046 function getLimitSelect() {
1047 # Add the current limit from the query string
1048 # to avoid that the limit is lost after clicking Go next time
1049 if ( !in_array( $this->mLimit, $this->mLimitsShown ) ) {
1050 $this->mLimitsShown[] = $this->mLimit;
1051 sort( $this->mLimitsShown );
1053 $s = Html::openElement( 'select', array( 'name' => 'limit' ) ) . "\n";
1054 foreach ( $this->mLimitsShown as $key => $value ) {
1055 # The pair is either $index => $limit, in which case the $value
1056 # will be numeric, or $limit => $text, in which case the $value
1057 # will be a string.
1058 if( is_int( $value ) ){
1059 $limit = $value;
1060 $text = $this->getLang()->formatNum( $limit );
1061 } else {
1062 $limit = $key;
1063 $text = $value;
1065 $s .= Xml::option( $text, $limit, $limit == $this->mLimit ) . "\n";
1067 $s .= Html::closeElement( 'select' );
1068 return $s;
1072 * Get <input type="hidden"> elements for use in a method="get" form.
1073 * Resubmits all defined elements of the query string, except for a
1074 * blacklist, passed in the $blacklist parameter.
1076 * @param $blacklist Array parameters from the request query which should not be resubmitted
1077 * @return String: HTML fragment
1079 function getHiddenFields( $blacklist = array() ) {
1080 $blacklist = (array)$blacklist;
1081 $query = $this->getRequest()->getQueryValues();
1082 foreach ( $blacklist as $name ) {
1083 unset( $query[$name] );
1085 $s = '';
1086 foreach ( $query as $name => $value ) {
1087 $encName = htmlspecialchars( $name );
1088 $encValue = htmlspecialchars( $value );
1089 $s .= "<input type=\"hidden\" name=\"$encName\" value=\"$encValue\"/>\n";
1091 return $s;
1095 * Get a form containing a limit selection dropdown
1097 * @return String: HTML fragment
1099 function getLimitForm() {
1100 global $wgScript;
1102 return Xml::openElement(
1103 'form',
1104 array(
1105 'method' => 'get',
1106 'action' => $wgScript
1107 ) ) . "\n" . $this->getLimitDropdown() . "</form>\n";
1111 * Gets a limit selection dropdown
1113 * @return string
1115 function getLimitDropdown() {
1116 # Make the select with some explanatory text
1117 $msgSubmit = wfMsgHtml( 'table_pager_limit_submit' );
1119 return wfMsgHtml( 'table_pager_limit', $this->getLimitSelect() ) .
1120 "\n<input type=\"submit\" value=\"$msgSubmit\"/>\n" .
1121 $this->getHiddenFields( array( 'limit' ) );
1125 * Return true if the named field should be sortable by the UI, false
1126 * otherwise
1128 * @param $field String
1130 abstract function isFieldSortable( $field );
1133 * Format a table cell. The return value should be HTML, but use an empty
1134 * string not &#160; for empty cells. Do not include the <td> and </td>.
1136 * The current result row is available as $this->mCurrentRow, in case you
1137 * need more context.
1139 * @param $name String: the database field name
1140 * @param $value String: the value retrieved from the database
1142 abstract function formatValue( $name, $value );
1145 * The database field name used as a default sort order
1147 abstract function getDefaultSort();
1150 * An array mapping database field names to a textual description of the
1151 * field name, for use in the table header. The description should be plain
1152 * text, it will be HTML-escaped later.
1154 * @return Array
1156 abstract function getFieldNames();