Non-word characters don't terminate tag names.
[mediawiki.git] / includes / Pager.php
blob3ada0e2a038d5cb5ef42838d93c549e1cf63da63
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 * Whether to include the offset in the query
124 protected $mIncludeOffset = false;
127 * Result object for the query. Warning: seek before use.
129 * @var ResultWrapper
131 public $mResult;
133 public function __construct( IContextSource $context = null ) {
134 if ( $context ) {
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]
164 : array();
165 } elseif ( is_array( $index ) ) {
166 # First element is the default
167 reset( $index );
168 list( $this->mOrderType, $this->mIndexField ) = each( $index );
169 $this->mExtraSortFields = isset( $extraSort[$this->mOrderType] )
170 ? (array)$extraSort[$this->mOrderType]
171 : array();
172 } else {
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]
183 : $dir;
188 * Get the Database object in use
190 * @return DatabaseBase
192 public function getDatabase() {
193 return $this->mDb;
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 == '' ) {
211 $isFirst = true;
212 } else {
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(
223 $this->mOffset,
224 $queryLimit,
225 $descending
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 ) {
263 $limit = 5000;
265 if ( $limit > 0 ) {
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();
292 if ( $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];
308 } else {
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];
319 } else {
320 $firstIndex = '';
321 $lastIndex = '';
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;
331 } else {
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
342 * @return String
344 function getSqlComment() {
345 return get_class( $this );
349 * Do a query with specified parameters, rather than using the object
350 * context
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
368 * @return array
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 );
379 if ( $descending ) {
380 $options['ORDER BY'] = $sortColumns;
381 $operator = $this->mIncludeOffset ? '>=' : '>';
382 } else {
383 $orderBy = array();
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.
408 * @return String
410 public function getBody() {
411 if ( !$this->mQueryDone ) {
412 $this->doQuery();
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();
424 if ( $numRows ) {
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 );
431 } else {
432 $this->mResult->seek( 0 );
433 for ( $i = 0; $i < $numRows; $i++ ) {
434 $row = $this->mResult->fetchObject();
435 $s .= $this->formatRow( $row );
438 } else {
439 $s .= $this->getEmptyBody();
441 $s .= $this->getEndBody();
442 return $s;
446 * Make a self-link
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 ) {
456 return $text;
459 $attrs = array();
460 if ( in_array( $type, array( 'first', 'prev', 'next', 'last' ) ) ) {
461 # HTML5 rel attributes
462 $attrs['rel'] = $type;
465 if ( $type ) {
466 $attrs['class'] = "mw-{$type}link";
469 return Linker::linkKnown(
470 $this->getTitle(),
471 $text,
472 $attrs,
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.
482 * @return void
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.
490 * @return String
492 protected function getStartBody() {
493 return '';
497 * Hook into getBody() for the end of the list
499 * @return String
501 protected function getEndBody() {
502 return '';
506 * Hook into getBody(), for the bit between the start and the
507 * end when there are no rows
509 * @return String
511 protected function getEmptyBody() {
512 return '';
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
518 * short blacklist.
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
539 * @return Integer
541 function getNumRows() {
542 if ( !$this->mQueryDone ) {
543 $this->doQuery();
545 return $this->mResult->numRows();
549 * Get a URL query array for the prev, next, first and last links.
551 * @return Array
553 function getPagingQueries() {
554 if ( !$this->mQueryDone ) {
555 $this->doQuery();
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 ) {
562 $prev = false;
563 $first = false;
564 } else {
565 $prev = array(
566 'dir' => 'prev',
567 'offset' => $this->mFirstShown,
568 'limit' => $urlLimit
570 $first = array( 'limit' => $urlLimit );
572 if ( $this->mIsLast ) {
573 $next = false;
574 $last = false;
575 } else {
576 $next = array( 'offset' => $this->mLastShown, 'limit' => $urlLimit );
577 $last = array( 'dir' => 'prev', 'limit' => $urlLimit );
579 return array(
580 'prev' => $prev,
581 'next' => $next,
582 'first' => $first,
583 'last' => $last
588 * Returns whether to show the "navigation bar"
590 * @return Boolean
592 function isNavigationBarShown() {
593 if ( !$this->mQueryDone ) {
594 $this->doQuery();
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
604 * of HTML.
606 * @param $linkTexts Array
607 * @param $disabledTexts Array
608 * @return Array
610 function getPagingLinks( $linkTexts, $disabledTexts = array() ) {
611 $queries = $this->getPagingQueries();
612 $links = array();
614 foreach ( $queries as $type => $query ) {
615 if ( $query !== false ) {
616 $links[$type] = $this->makeLink(
617 $linkTexts[$type],
618 $queries[$type],
619 $type
621 } elseif ( isset( $disabledTexts[$type] ) ) {
622 $links[$type] = $disabledTexts[$type];
623 } else {
624 $links[$type] = $linkTexts[$type];
628 return $links;
631 function getLimitLinks() {
632 $links = array();
633 if ( $this->mIsBackwards ) {
634 $offset = $this->mPastTheEndIndex;
635 } else {
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 ),
642 'num'
645 return $links;
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
654 * @return String
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
668 * @return Array
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
677 * the default.
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.
700 * @return Array
702 protected function getExtraSortFields() {
703 return array();
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
711 * of this.
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.
723 * @return Boolean
725 protected function getDefaultDirections() {
726 return false;
731 * IndexPager with an alphabetic list and a formatted navigation bar
732 * @ingroup Pager
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() ) {
744 return '';
747 if ( isset( $this->mNavigationBar ) ) {
748 return $this->mNavigationBar;
751 $linkTexts = array(
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;
775 $extra = '';
776 $first = true;
777 $msgs = $this->getOrderTypeMessages();
778 foreach ( array_keys( $msgs ) as $order ) {
779 if ( $first ) {
780 $first = false;
781 } else {
782 $extra .= $this->msg( 'pipe-separator' )->escaped();
785 if ( $order == $this->mOrderType ) {
786 $extra .= $this->msg( $msgs[$order] )->escaped();
787 } else {
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.
809 * @return Array
811 protected function getOrderTypeMessages() {
812 return null;
817 * IndexPager with a formatted navigation bar
818 * @ingroup Pager
820 abstract class ReverseChronologicalPager extends IndexPager {
821 public $mDefaultDirection = true;
822 public $mYear;
823 public $mMonth;
825 function getNavigationBar() {
826 if ( !$this->isNavigationBarShown() ) {
827 return '';
830 if ( isset( $this->mNavigationBar ) ) {
831 return $this->mNavigationBar;
834 $linkTexts = array(
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 ) {
869 return;
872 if ( $this->mYear ) {
873 $year = $this->mYear;
874 } else {
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' ) ) {
880 $year--;
884 if ( $this->mMonth ) {
885 $month = $this->mMonth + 1;
886 // For December, we want January 1 of the next year
887 if ( $month > 12 ) {
888 $month = 1;
889 $year++;
891 } else {
892 // No month implies we want up to the end of the year in question
893 $month = 1;
894 $year++;
897 // Y2K38 bug
898 if ( $year > 2032 ) {
899 $year = 2032;
902 $ymd = (int)sprintf( "%04d%02d01", $year, $month );
904 if ( $ymd > 20320101 ) {
905 $ymd = 20320101;
908 $this->mOffset = $this->mDb->timestamp( "${ymd}000000" );
913 * Table-based display with a user-selectable sort order
914 * @ingroup Pager
916 abstract class TablePager extends IndexPager {
917 var $mSort;
918 var $mCurrentRow;
920 public function __construct( IContextSource $context = null ) {
921 if ( $context ) {
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();
941 * @protected
942 * @return string
944 function getStartBody() {
945 global $wgStylePath;
946 $sortClass = $this->getSortHeaderClass();
948 $s = '';
949 $fields = $this->getFieldNames();
951 # Make table header
952 foreach ( $fields as $field => $name ) {
953 if ( strval( $name ) == '' ) {
954 $s .= Html::rawElement( 'th', array(), '&#160;' ) . "\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 ) {
961 # Descending
962 $image = 'Arr_d.png';
963 $query['asc'] = '1';
964 $query['desc'] = '';
965 $alt = $this->msg( 'descending_abbrev' )->escaped();
966 } else {
967 # Ascending
968 $image = 'Arr_u.png';
969 $query['asc'] = '';
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";
978 } else {
979 $s .= Html::rawElement( 'th', array(),
980 $this->makeLink( htmlspecialchars( $name ), $query ) ) . "\n";
982 } else {
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";
992 return $ret;
996 * @protected
997 * @return string
999 function getEndBody() {
1000 return "</tbody></table>\n";
1004 * @protected
1005 * @return string
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 ) );
1015 * @protected
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 = '&#160;';
1032 $s .= Html::rawElement( 'td', $this->getCellAttrs( $field, $value ), $formatted ) . "\n";
1035 $s .= Html::closeElement( 'tr' ) . "\n";
1037 return $s;
1041 * Get a class name to be applied to the given row.
1043 * @protected
1045 * @param $row Object: the database result row
1046 * @return String
1048 function getRowClass( $row ) {
1049 return '';
1053 * Get attributes to be applied to the given row.
1055 * @protected
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=""
1064 return array();
1065 } else {
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
1075 * @protected
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 );
1086 * @protected
1087 * @return string
1089 function getIndexField() {
1090 return $this->mSort;
1094 * @protected
1095 * @return string
1097 function getTableClass() {
1098 return 'TablePager';
1102 * @protected
1103 * @return string
1105 function getNavClass() {
1106 return 'TablePager_nav';
1110 * @protected
1111 * @return string
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() ) {
1125 return '';
1128 $path = "$wgStylePath/common/images";
1129 $labels = array(
1130 'first' => 'table_pager_first',
1131 'prev' => 'table_pager_prev',
1132 'next' => 'table_pager_next',
1133 'last' => 'table_pager_last',
1135 $images = array(
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";
1171 return $s;
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().
1193 * @since 1.22
1194 * @return array
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 );
1203 $ret = array();
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
1207 # will be a string.
1208 if ( is_int( $value ) ) {
1209 $limit = $value;
1210 $text = $this->getLanguage()->formatNum( $limit );
1211 } else {
1212 $limit = $key;
1213 $text = $value;
1215 $ret[$text] = $limit;
1217 return $ret;
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] );
1234 $s = '';
1235 foreach ( $query as $name => $value ) {
1236 $s .= Html::hidden( $name, $value ) . "\n";
1238 return $s;
1242 * Get a form containing a limit selection dropdown
1244 * @return String: HTML fragment
1246 function getLimitForm() {
1247 global $wgScript;
1249 return Html::rawElement(
1250 'form',
1251 array(
1252 'method' => 'get',
1253 'action' => $wgScript
1255 "\n" . $this->getLimitDropdown()
1256 ) . "\n";
1260 * Gets a limit selection dropdown
1262 * @return string
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
1276 * otherwise
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 &#160; 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.
1289 * @protected
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.
1299 * @protected
1301 * @return string
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.
1310 * @return Array
1312 abstract function getFieldNames();