Merge "Added a --profiler option to all maintenance scripts."
[mediawiki.git] / includes / Pager.php
blobc2bd364687082189c973a7b762380847170aa977
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 $this->mDb = wfGetDB( DB_SLAVE );
155 $index = $this->getIndexField(); // column to sort on
156 $extraSort = $this->getExtraSortFields(); // extra columns to sort on for query planning
157 $order = $this->mRequest->getVal( 'order' );
158 if ( is_array( $index ) && isset( $index[$order] ) ) {
159 $this->mOrderType = $order;
160 $this->mIndexField = $index[$order];
161 $this->mExtraSortFields = isset( $extraSort[$order] )
162 ? (array)$extraSort[$order]
163 : array();
164 } elseif ( is_array( $index ) ) {
165 # First element is the default
166 reset( $index );
167 list( $this->mOrderType, $this->mIndexField ) = each( $index );
168 $this->mExtraSortFields = isset( $extraSort[$this->mOrderType] )
169 ? (array)$extraSort[$this->mOrderType]
170 : array();
171 } else {
172 # $index is not an array
173 $this->mOrderType = null;
174 $this->mIndexField = $index;
175 $this->mExtraSortFields = (array)$extraSort;
178 if ( !isset( $this->mDefaultDirection ) ) {
179 $dir = $this->getDefaultDirections();
180 $this->mDefaultDirection = is_array( $dir )
181 ? $dir[$this->mOrderType]
182 : $dir;
187 * Get the Database object in use
189 * @return DatabaseBase
191 public function getDatabase() {
192 return $this->mDb;
196 * Do the query, using information from the object context. This function
197 * has been kept minimal to make it overridable if necessary, to allow for
198 * result sets formed from multiple DB queries.
200 public function doQuery() {
201 # Use the child class name for profiling
202 $fname = __METHOD__ . ' (' . get_class( $this ) . ')';
203 wfProfileIn( $fname );
205 $descending = ( $this->mIsBackwards == $this->mDefaultDirection );
206 # Plus an extra row so that we can tell the "next" link should be shown
207 $queryLimit = $this->mLimit + 1;
209 if ( $this->mOffset == '' ) {
210 $isFirst = true;
211 } else {
212 // If there's an offset, we may or may not be at the first entry.
213 // The only way to tell is to run the query in the opposite
214 // direction see if we get a row.
215 $oldIncludeOffset = $this->mIncludeOffset;
216 $this->mIncludeOffset = !$this->mIncludeOffset;
217 $isFirst = !$this->reallyDoQuery( $this->mOffset, 1, !$descending )->numRows();
218 $this->mIncludeOffset = $oldIncludeOffset;
221 $this->mResult = $this->reallyDoQuery(
222 $this->mOffset,
223 $queryLimit,
224 $descending
227 $this->extractResultInfo( $isFirst, $queryLimit, $this->mResult );
228 $this->mQueryDone = true;
230 $this->preprocessResults( $this->mResult );
231 $this->mResult->rewind(); // Paranoia
233 wfProfileOut( $fname );
237 * @return ResultWrapper The result wrapper.
239 function getResult() {
240 return $this->mResult;
244 * Set the offset from an other source than the request
246 * @param $offset Int|String
248 function setOffset( $offset ) {
249 $this->mOffset = $offset;
252 * Set the limit from an other source than the request
254 * Verifies limit is between 1 and 5000
256 * @param $limit Int|String
258 function setLimit( $limit ) {
259 $limit = (int) $limit;
260 // WebRequest::getLimitOffset() puts a cap of 5000, so do same here.
261 if ( $limit > 5000 ) {
262 $limit = 5000;
264 if ( $limit > 0 ) {
265 $this->mLimit = $limit;
270 * Set whether a row matching exactly the offset should be also included
271 * in the result or not. By default this is not the case, but when the
272 * offset is user-supplied this might be wanted.
274 * @param $include bool
276 public function setIncludeOffset( $include ) {
277 $this->mIncludeOffset = $include;
281 * Extract some useful data from the result object for use by
282 * the navigation bar, put it into $this
284 * @param $isFirst bool: False if there are rows before those fetched (i.e.
285 * if a "previous" link would make sense)
286 * @param $limit Integer: exact query limit
287 * @param $res ResultWrapper
289 function extractResultInfo( $isFirst, $limit, ResultWrapper $res ) {
290 $numRows = $res->numRows();
291 if ( $numRows ) {
292 # Remove any table prefix from index field
293 $parts = explode( '.', $this->mIndexField );
294 $indexColumn = end( $parts );
296 $row = $res->fetchRow();
297 $firstIndex = $row[$indexColumn];
299 # Discard the extra result row if there is one
300 if ( $numRows > $this->mLimit && $numRows > 1 ) {
301 $res->seek( $numRows - 1 );
302 $this->mPastTheEndRow = $res->fetchObject();
303 $this->mPastTheEndIndex = $this->mPastTheEndRow->$indexColumn;
304 $res->seek( $numRows - 2 );
305 $row = $res->fetchRow();
306 $lastIndex = $row[$indexColumn];
307 } else {
308 $this->mPastTheEndRow = null;
309 # Setting indexes to an empty string means that they will be
310 # omitted if they would otherwise appear in URLs. It just so
311 # happens that this is the right thing to do in the standard
312 # UI, in all the relevant cases.
313 $this->mPastTheEndIndex = '';
314 $res->seek( $numRows - 1 );
315 $row = $res->fetchRow();
316 $lastIndex = $row[$indexColumn];
318 } else {
319 $firstIndex = '';
320 $lastIndex = '';
321 $this->mPastTheEndRow = null;
322 $this->mPastTheEndIndex = '';
325 if ( $this->mIsBackwards ) {
326 $this->mIsFirst = ( $numRows < $limit );
327 $this->mIsLast = $isFirst;
328 $this->mLastShown = $firstIndex;
329 $this->mFirstShown = $lastIndex;
330 } else {
331 $this->mIsFirst = $isFirst;
332 $this->mIsLast = ( $numRows < $limit );
333 $this->mLastShown = $lastIndex;
334 $this->mFirstShown = $firstIndex;
339 * Get some text to go in brackets in the "function name" part of the SQL comment
341 * @return String
343 function getSqlComment() {
344 return get_class( $this );
348 * Do a query with specified parameters, rather than using the object
349 * context
351 * @param string $offset index offset, inclusive
352 * @param $limit Integer: exact query limit
353 * @param $descending Boolean: query direction, false for ascending, true for descending
354 * @return ResultWrapper
356 public function reallyDoQuery( $offset, $limit, $descending ) {
357 list( $tables, $fields, $conds, $fname, $options, $join_conds ) = $this->buildQueryInfo( $offset, $limit, $descending );
358 return $this->mDb->select( $tables, $fields, $conds, $fname, $options, $join_conds );
362 * Build variables to use by the database wrapper.
364 * @param string $offset index offset, inclusive
365 * @param $limit Integer: exact query limit
366 * @param $descending Boolean: query direction, false for ascending, true for descending
367 * @return array
369 protected function buildQueryInfo( $offset, $limit, $descending ) {
370 $fname = __METHOD__ . ' (' . $this->getSqlComment() . ')';
371 $info = $this->getQueryInfo();
372 $tables = $info['tables'];
373 $fields = $info['fields'];
374 $conds = isset( $info['conds'] ) ? $info['conds'] : array();
375 $options = isset( $info['options'] ) ? $info['options'] : array();
376 $join_conds = isset( $info['join_conds'] ) ? $info['join_conds'] : array();
377 $sortColumns = array_merge( array( $this->mIndexField ), $this->mExtraSortFields );
378 if ( $descending ) {
379 $options['ORDER BY'] = $sortColumns;
380 $operator = $this->mIncludeOffset ? '>=' : '>';
381 } else {
382 $orderBy = array();
383 foreach ( $sortColumns as $col ) {
384 $orderBy[] = $col . ' DESC';
386 $options['ORDER BY'] = $orderBy;
387 $operator = $this->mIncludeOffset ? '<=' : '<';
389 if ( $offset != '' ) {
390 $conds[] = $this->mIndexField . $operator . $this->mDb->addQuotes( $offset );
392 $options['LIMIT'] = intval( $limit );
393 return array( $tables, $fields, $conds, $fname, $options, $join_conds );
397 * Pre-process results; useful for performing batch existence checks, etc.
399 * @param $result ResultWrapper
401 protected function preprocessResults( $result ) {}
404 * Get the formatted result list. Calls getStartBody(), formatRow() and
405 * getEndBody(), concatenates the results and returns them.
407 * @return String
409 public function getBody() {
410 if ( !$this->mQueryDone ) {
411 $this->doQuery();
414 if ( $this->mResult->numRows() ) {
415 # Do any special query batches before display
416 $this->doBatchLookups();
419 # Don't use any extra rows returned by the query
420 $numRows = min( $this->mResult->numRows(), $this->mLimit );
422 $s = $this->getStartBody();
423 if ( $numRows ) {
424 if ( $this->mIsBackwards ) {
425 for ( $i = $numRows - 1; $i >= 0; $i-- ) {
426 $this->mResult->seek( $i );
427 $row = $this->mResult->fetchObject();
428 $s .= $this->formatRow( $row );
430 } else {
431 $this->mResult->seek( 0 );
432 for ( $i = 0; $i < $numRows; $i++ ) {
433 $row = $this->mResult->fetchObject();
434 $s .= $this->formatRow( $row );
437 } else {
438 $s .= $this->getEmptyBody();
440 $s .= $this->getEndBody();
441 return $s;
445 * Make a self-link
447 * @param string $text text displayed on the link
448 * @param array $query associative array of parameter to be in the query string
449 * @param string $type value of the "rel" attribute
451 * @return String: HTML fragment
453 function makeLink( $text, array $query = null, $type = null ) {
454 if ( $query === null ) {
455 return $text;
458 $attrs = array();
459 if ( in_array( $type, array( 'first', 'prev', 'next', 'last' ) ) ) {
460 # HTML5 rel attributes
461 $attrs['rel'] = $type;
464 if ( $type ) {
465 $attrs['class'] = "mw-{$type}link";
468 return Linker::linkKnown(
469 $this->getTitle(),
470 $text,
471 $attrs,
472 $query + $this->getDefaultQuery()
477 * Called from getBody(), before getStartBody() is called and
478 * after doQuery() was called. This will be called only if there
479 * are rows in the result set.
481 * @return void
483 protected function doBatchLookups() {}
486 * Hook into getBody(), allows text to be inserted at the start. This
487 * will be called even if there are no rows in the result set.
489 * @return String
491 protected function getStartBody() {
492 return '';
496 * Hook into getBody() for the end of the list
498 * @return String
500 protected function getEndBody() {
501 return '';
505 * Hook into getBody(), for the bit between the start and the
506 * end when there are no rows
508 * @return String
510 protected function getEmptyBody() {
511 return '';
515 * Get an array of query parameters that should be put into self-links.
516 * By default, all parameters passed in the URL are used, except for a
517 * short blacklist.
519 * @return array Associative array
521 function getDefaultQuery() {
522 if ( !isset( $this->mDefaultQuery ) ) {
523 $this->mDefaultQuery = $this->getRequest()->getQueryValues();
524 unset( $this->mDefaultQuery['title'] );
525 unset( $this->mDefaultQuery['dir'] );
526 unset( $this->mDefaultQuery['offset'] );
527 unset( $this->mDefaultQuery['limit'] );
528 unset( $this->mDefaultQuery['order'] );
529 unset( $this->mDefaultQuery['month'] );
530 unset( $this->mDefaultQuery['year'] );
532 return $this->mDefaultQuery;
536 * Get the number of rows in the result set
538 * @return Integer
540 function getNumRows() {
541 if ( !$this->mQueryDone ) {
542 $this->doQuery();
544 return $this->mResult->numRows();
548 * Get a URL query array for the prev, next, first and last links.
550 * @return Array
552 function getPagingQueries() {
553 if ( !$this->mQueryDone ) {
554 $this->doQuery();
557 # Don't announce the limit everywhere if it's the default
558 $urlLimit = $this->mLimit == $this->mDefaultLimit ? null : $this->mLimit;
560 if ( $this->mIsFirst ) {
561 $prev = false;
562 $first = false;
563 } else {
564 $prev = array(
565 'dir' => 'prev',
566 'offset' => $this->mFirstShown,
567 'limit' => $urlLimit
569 $first = array( 'limit' => $urlLimit );
571 if ( $this->mIsLast ) {
572 $next = false;
573 $last = false;
574 } else {
575 $next = array( 'offset' => $this->mLastShown, 'limit' => $urlLimit );
576 $last = array( 'dir' => 'prev', 'limit' => $urlLimit );
578 return array(
579 'prev' => $prev,
580 'next' => $next,
581 'first' => $first,
582 'last' => $last
587 * Returns whether to show the "navigation bar"
589 * @return Boolean
591 function isNavigationBarShown() {
592 if ( !$this->mQueryDone ) {
593 $this->doQuery();
595 // Hide navigation by default if there is nothing to page
596 return !( $this->mIsFirst && $this->mIsLast );
600 * Get paging links. If a link is disabled, the item from $disabledTexts
601 * will be used. If there is no such item, the unlinked text from
602 * $linkTexts will be used. Both $linkTexts and $disabledTexts are arrays
603 * of HTML.
605 * @param $linkTexts Array
606 * @param $disabledTexts Array
607 * @return Array
609 function getPagingLinks( $linkTexts, $disabledTexts = array() ) {
610 $queries = $this->getPagingQueries();
611 $links = array();
613 foreach ( $queries as $type => $query ) {
614 if ( $query !== false ) {
615 $links[$type] = $this->makeLink(
616 $linkTexts[$type],
617 $queries[$type],
618 $type
620 } elseif ( isset( $disabledTexts[$type] ) ) {
621 $links[$type] = $disabledTexts[$type];
622 } else {
623 $links[$type] = $linkTexts[$type];
627 return $links;
630 function getLimitLinks() {
631 $links = array();
632 if ( $this->mIsBackwards ) {
633 $offset = $this->mPastTheEndIndex;
634 } else {
635 $offset = $this->mOffset;
637 foreach ( $this->mLimitsShown as $limit ) {
638 $links[] = $this->makeLink(
639 $this->getLanguage()->formatNum( $limit ),
640 array( 'offset' => $offset, 'limit' => $limit ),
641 'num'
644 return $links;
648 * Abstract formatting function. This should return an HTML string
649 * representing the result row $row. Rows will be concatenated and
650 * returned by getBody()
652 * @param $row Object: database row
653 * @return String
655 abstract function formatRow( $row );
658 * This function should be overridden to provide all parameters
659 * needed for the main paged query. It returns an associative
660 * array with the following elements:
661 * tables => Table(s) for passing to Database::select()
662 * fields => Field(s) for passing to Database::select(), may be *
663 * conds => WHERE conditions
664 * options => option array
665 * join_conds => JOIN conditions
667 * @return Array
669 abstract function getQueryInfo();
672 * This function should be overridden to return the name of the index fi-
673 * eld. If the pager supports multiple orders, it may return an array of
674 * 'querykey' => 'indexfield' pairs, so that a request with &count=querykey
675 * will use indexfield to sort. In this case, the first returned key is
676 * the default.
678 * Needless to say, it's really not a good idea to use a non-unique index
679 * for this! That won't page right.
681 * @return string|Array
683 abstract function getIndexField();
686 * This function should be overridden to return the names of secondary columns
687 * to order by in addition to the column in getIndexField(). These fields will
688 * not be used in the pager offset or in any links for users.
690 * If getIndexField() returns an array of 'querykey' => 'indexfield' pairs then
691 * this must return a corresponding array of 'querykey' => array( fields...) pairs
692 * in order for a request with &count=querykey to use array( fields...) to sort.
694 * This is useful for pagers that GROUP BY a unique column (say page_id)
695 * and ORDER BY another (say page_len). Using GROUP BY and ORDER BY both on
696 * page_len,page_id avoids temp tables (given a page_len index). This would
697 * also work if page_id was non-unique but we had a page_len,page_id index.
699 * @return Array
701 protected function getExtraSortFields() {
702 return array();
706 * Return the default sorting direction: false for ascending, true for
707 * descending. You can also have an associative array of ordertype => dir,
708 * if multiple order types are supported. In this case getIndexField()
709 * must return an array, and the keys of that must exactly match the keys
710 * of this.
712 * For backward compatibility, this method's return value will be ignored
713 * if $this->mDefaultDirection is already set when the constructor is
714 * called, for instance if it's statically initialized. In that case the
715 * value of that variable (which must be a boolean) will be used.
717 * Note that despite its name, this does not return the value of the
718 * $this->mDefaultDirection member variable. That's the default for this
719 * particular instantiation, which is a single value. This is the set of
720 * all defaults for the class.
722 * @return Boolean
724 protected function getDefaultDirections() {
725 return false;
730 * IndexPager with an alphabetic list and a formatted navigation bar
731 * @ingroup Pager
733 abstract class AlphabeticPager extends IndexPager {
736 * Shamelessly stolen bits from ReverseChronologicalPager,
737 * didn't want to do class magic as may be still revamped
739 * @return String HTML
741 function getNavigationBar() {
742 if ( !$this->isNavigationBarShown() ) {
743 return '';
746 if ( isset( $this->mNavigationBar ) ) {
747 return $this->mNavigationBar;
750 $linkTexts = array(
751 'prev' => $this->msg( 'prevn' )->numParams( $this->mLimit )->escaped(),
752 'next' => $this->msg( 'nextn' )->numParams( $this->mLimit )->escaped(),
753 'first' => $this->msg( 'page_first' )->escaped(),
754 'last' => $this->msg( 'page_last' )->escaped()
757 $lang = $this->getLanguage();
759 $pagingLinks = $this->getPagingLinks( $linkTexts );
760 $limitLinks = $this->getLimitLinks();
761 $limits = $lang->pipeList( $limitLinks );
763 $this->mNavigationBar = $this->msg( 'parentheses' )->rawParams(
764 $lang->pipeList( array( $pagingLinks['first'],
765 $pagingLinks['last'] ) ) )->escaped() . " " .
766 $this->msg( 'viewprevnext' )->rawParams( $pagingLinks['prev'],
767 $pagingLinks['next'], $limits )->escaped();
769 if ( !is_array( $this->getIndexField() ) ) {
770 # Early return to avoid undue nesting
771 return $this->mNavigationBar;
774 $extra = '';
775 $first = true;
776 $msgs = $this->getOrderTypeMessages();
777 foreach ( array_keys( $msgs ) as $order ) {
778 if ( $first ) {
779 $first = false;
780 } else {
781 $extra .= $this->msg( 'pipe-separator' )->escaped();
784 if ( $order == $this->mOrderType ) {
785 $extra .= $this->msg( $msgs[$order] )->escaped();
786 } else {
787 $extra .= $this->makeLink(
788 $this->msg( $msgs[$order] )->escaped(),
789 array( 'order' => $order )
794 if ( $extra !== '' ) {
795 $extra = ' ' . $this->msg( 'parentheses' )->rawParams( $extra )->escaped();
796 $this->mNavigationBar .= $extra;
799 return $this->mNavigationBar;
803 * If this supports multiple order type messages, give the message key for
804 * enabling each one in getNavigationBar. The return type is an associative
805 * array whose keys must exactly match the keys of the array returned
806 * by getIndexField(), and whose values are message keys.
808 * @return Array
810 protected function getOrderTypeMessages() {
811 return null;
816 * IndexPager with a formatted navigation bar
817 * @ingroup Pager
819 abstract class ReverseChronologicalPager extends IndexPager {
820 public $mDefaultDirection = true;
821 public $mYear;
822 public $mMonth;
824 function getNavigationBar() {
825 if ( !$this->isNavigationBarShown() ) {
826 return '';
829 if ( isset( $this->mNavigationBar ) ) {
830 return $this->mNavigationBar;
833 $linkTexts = array(
834 'prev' => $this->msg( 'pager-newer-n' )->numParams( $this->mLimit )->escaped(),
835 'next' => $this->msg( 'pager-older-n' )->numParams( $this->mLimit )->escaped(),
836 'first' => $this->msg( 'histlast' )->escaped(),
837 'last' => $this->msg( 'histfirst' )->escaped()
840 $pagingLinks = $this->getPagingLinks( $linkTexts );
841 $limitLinks = $this->getLimitLinks();
842 $limits = $this->getLanguage()->pipeList( $limitLinks );
843 $firstLastLinks = $this->msg( 'parentheses' )->rawParams( "{$pagingLinks['first']}" .
844 $this->msg( 'pipe-separator' )->escaped() .
845 "{$pagingLinks['last']}" )->escaped();
847 $this->mNavigationBar = $firstLastLinks . ' ' .
848 $this->msg( 'viewprevnext' )->rawParams(
849 $pagingLinks['prev'], $pagingLinks['next'], $limits )->escaped();
851 return $this->mNavigationBar;
854 function getDateCond( $year, $month ) {
855 $year = intval( $year );
856 $month = intval( $month );
858 // Basic validity checks
859 $this->mYear = $year > 0 ? $year : false;
860 $this->mMonth = ( $month > 0 && $month < 13 ) ? $month : false;
862 // Given an optional year and month, we need to generate a timestamp
863 // to use as "WHERE rev_timestamp <= result"
864 // Examples: year = 2006 equals < 20070101 (+000000)
865 // year=2005, month=1 equals < 20050201
866 // year=2005, month=12 equals < 20060101
867 if ( !$this->mYear && !$this->mMonth ) {
868 return;
871 if ( $this->mYear ) {
872 $year = $this->mYear;
873 } else {
874 // If no year given, assume the current one
875 $year = gmdate( 'Y' );
876 // If this month hasn't happened yet this year, go back to last year's month
877 if ( $this->mMonth > gmdate( 'n' ) ) {
878 $year--;
882 if ( $this->mMonth ) {
883 $month = $this->mMonth + 1;
884 // For December, we want January 1 of the next year
885 if ( $month > 12 ) {
886 $month = 1;
887 $year++;
889 } else {
890 // No month implies we want up to the end of the year in question
891 $month = 1;
892 $year++;
895 // Y2K38 bug
896 if ( $year > 2032 ) {
897 $year = 2032;
900 $ymd = (int)sprintf( "%04d%02d01", $year, $month );
902 if ( $ymd > 20320101 ) {
903 $ymd = 20320101;
906 $this->mOffset = $this->mDb->timestamp( "${ymd}000000" );
911 * Table-based display with a user-selectable sort order
912 * @ingroup Pager
914 abstract class TablePager extends IndexPager {
915 var $mSort;
916 var $mCurrentRow;
918 public function __construct( IContextSource $context = null ) {
919 if ( $context ) {
920 $this->setContext( $context );
923 $this->mSort = $this->getRequest()->getText( 'sort' );
924 if ( !array_key_exists( $this->mSort, $this->getFieldNames() )
925 || !$this->isFieldSortable( $this->mSort )
927 $this->mSort = $this->getDefaultSort();
929 if ( $this->getRequest()->getBool( 'asc' ) ) {
930 $this->mDefaultDirection = false;
931 } elseif ( $this->getRequest()->getBool( 'desc' ) ) {
932 $this->mDefaultDirection = true;
933 } /* Else leave it at whatever the class default is */
935 parent::__construct();
939 * @protected
940 * @return string
942 function getStartBody() {
943 global $wgStylePath;
944 $sortClass = $this->getSortHeaderClass();
946 $s = '';
947 $fields = $this->getFieldNames();
949 # Make table header
950 foreach ( $fields as $field => $name ) {
951 if ( strval( $name ) == '' ) {
952 $s .= Html::rawElement( 'th', array(), '&#160;' ) . "\n";
953 } elseif ( $this->isFieldSortable( $field ) ) {
954 $query = array( 'sort' => $field, 'limit' => $this->mLimit );
955 if ( $field == $this->mSort ) {
956 # This is the sorted column
957 # Prepare a link that goes in the other sort order
958 if ( $this->mDefaultDirection ) {
959 # Descending
960 $image = 'Arr_d.png';
961 $query['asc'] = '1';
962 $query['desc'] = '';
963 $alt = $this->msg( 'descending_abbrev' )->escaped();
964 } else {
965 # Ascending
966 $image = 'Arr_u.png';
967 $query['asc'] = '';
968 $query['desc'] = '1';
969 $alt = $this->msg( 'ascending_abbrev' )->escaped();
971 $image = "$wgStylePath/common/images/$image";
972 $link = $this->makeLink(
973 Html::element( 'img', array( 'width' => 12, 'height' => 12,
974 'alt' => $alt, 'src' => $image ) ) . htmlspecialchars( $name ), $query );
975 $s .= Html::rawElement( 'th', array( 'class' => $sortClass ), $link ) . "\n";
976 } else {
977 $s .= Html::rawElement( 'th', array(),
978 $this->makeLink( htmlspecialchars( $name ), $query ) ) . "\n";
980 } else {
981 $s .= Html::element( 'th', array(), $name ) . "\n";
985 $tableClass = $this->getTableClass();
986 $ret = Html::openElement( 'table', array( 'style' => 'border:1px;', 'class' => "mw-datatable $tableClass" ) );
987 $ret .= Html::rawElement( 'thead', array(), Html::rawElement( 'tr', array(), "\n" . $s . "\n" ) );
988 $ret .= Html::openElement( 'tbody' ) . "\n";
990 return $ret;
994 * @protected
995 * @return string
997 function getEndBody() {
998 return "</tbody></table>\n";
1002 * @protected
1003 * @return string
1005 function getEmptyBody() {
1006 $colspan = count( $this->getFieldNames() );
1007 $msgEmpty = $this->msg( 'table_pager_empty' )->text();
1008 return Html::rawElement( 'tr', array(),
1009 Html::element( 'td', array( 'colspan' => $colspan ), $msgEmpty ) );
1013 * @protected
1014 * @param stdClass $row
1015 * @return String HTML
1017 function formatRow( $row ) {
1018 $this->mCurrentRow = $row; // In case formatValue etc need to know
1019 $s = Html::openElement( 'tr', $this->getRowAttrs( $row ) ) . "\n";
1020 $fieldNames = $this->getFieldNames();
1022 foreach ( $fieldNames as $field => $name ) {
1023 $value = isset( $row->$field ) ? $row->$field : null;
1024 $formatted = strval( $this->formatValue( $field, $value ) );
1026 if ( $formatted == '' ) {
1027 $formatted = '&#160;';
1030 $s .= Html::rawElement( 'td', $this->getCellAttrs( $field, $value ), $formatted ) . "\n";
1033 $s .= Html::closeElement( 'tr' ) . "\n";
1035 return $s;
1039 * Get a class name to be applied to the given row.
1041 * @protected
1043 * @param $row Object: the database result row
1044 * @return String
1046 function getRowClass( $row ) {
1047 return '';
1051 * Get attributes to be applied to the given row.
1053 * @protected
1055 * @param $row Object: the database result row
1056 * @return Array of attribute => value
1058 function getRowAttrs( $row ) {
1059 $class = $this->getRowClass( $row );
1060 if ( $class === '' ) {
1061 // Return an empty array to avoid clutter in HTML like class=""
1062 return array();
1063 } else {
1064 return array( 'class' => $this->getRowClass( $row ) );
1069 * Get any extra attributes to be applied to the given cell. Don't
1070 * take this as an excuse to hardcode styles; use classes and
1071 * CSS instead. Row context is available in $this->mCurrentRow
1073 * @protected
1075 * @param string $field The column
1076 * @param string $value The cell contents
1077 * @return Array of attr => value
1079 function getCellAttrs( $field, $value ) {
1080 return array( 'class' => 'TablePager_col_' . $field );
1084 * @protected
1085 * @return string
1087 function getIndexField() {
1088 return $this->mSort;
1092 * @protected
1093 * @return string
1095 function getTableClass() {
1096 return 'TablePager';
1100 * @protected
1101 * @return string
1103 function getNavClass() {
1104 return 'TablePager_nav';
1108 * @protected
1109 * @return string
1111 function getSortHeaderClass() {
1112 return 'TablePager_sort';
1116 * A navigation bar with images
1117 * @return String HTML
1119 public function getNavigationBar() {
1120 global $wgStylePath;
1122 if ( !$this->isNavigationBarShown() ) {
1123 return '';
1126 $path = "$wgStylePath/common/images";
1127 $labels = array(
1128 'first' => 'table_pager_first',
1129 'prev' => 'table_pager_prev',
1130 'next' => 'table_pager_next',
1131 'last' => 'table_pager_last',
1133 $images = array(
1134 'first' => 'arrow_first_25.png',
1135 'prev' => 'arrow_left_25.png',
1136 'next' => 'arrow_right_25.png',
1137 'last' => 'arrow_last_25.png',
1139 $disabledImages = array(
1140 'first' => 'arrow_disabled_first_25.png',
1141 'prev' => 'arrow_disabled_left_25.png',
1142 'next' => 'arrow_disabled_right_25.png',
1143 'last' => 'arrow_disabled_last_25.png',
1145 if ( $this->getLanguage()->isRTL() ) {
1146 $keys = array_keys( $labels );
1147 $images = array_combine( $keys, array_reverse( $images ) );
1148 $disabledImages = array_combine( $keys, array_reverse( $disabledImages ) );
1151 $linkTexts = array();
1152 $disabledTexts = array();
1153 foreach ( $labels as $type => $label ) {
1154 $msgLabel = $this->msg( $label )->escaped();
1155 $linkTexts[$type] = Html::element( 'img', array( 'src' => "$path/{$images[$type]}",
1156 'alt' => $msgLabel ) ) . "<br />$msgLabel";
1157 $disabledTexts[$type] = Html::element( 'img', array( 'src' => "$path/{$disabledImages[$type]}",
1158 'alt' => $msgLabel ) ) . "<br />$msgLabel";
1160 $links = $this->getPagingLinks( $linkTexts, $disabledTexts );
1162 $s = Html::openElement( 'table', array( 'class' => $this->getNavClass() ) );
1163 $s .= Html::openElement( 'tr' ) . "\n";
1164 $width = 100 / count( $links ) . '%';
1165 foreach ( $labels as $type => $label ) {
1166 $s .= Html::rawElement( 'td', array( 'style' => "width:$width;" ), $links[$type] ) . "\n";
1168 $s .= Html::closeElement( 'tr' ) . Html::closeElement( 'table' ) . "\n";
1169 return $s;
1173 * Get a "<select>" element which has options for each of the allowed limits
1175 * @return String: HTML fragment
1177 public function getLimitSelect() {
1178 $select = new XmlSelect( 'limit', false, $this->mLimit );
1179 $select->addOptions( $this->getLimitSelectList() );
1180 return $select->getHTML();
1184 * Get a list of items to show in a "<select>" element of limits.
1185 * This can be passed directly to XmlSelect::addOptions().
1187 * @since 1.22
1188 * @return array
1190 public function getLimitSelectList() {
1191 # Add the current limit from the query string
1192 # to avoid that the limit is lost after clicking Go next time
1193 if ( !in_array( $this->mLimit, $this->mLimitsShown ) ) {
1194 $this->mLimitsShown[] = $this->mLimit;
1195 sort( $this->mLimitsShown );
1197 $ret = array();
1198 foreach ( $this->mLimitsShown as $key => $value ) {
1199 # The pair is either $index => $limit, in which case the $value
1200 # will be numeric, or $limit => $text, in which case the $value
1201 # will be a string.
1202 if ( is_int( $value ) ) {
1203 $limit = $value;
1204 $text = $this->getLanguage()->formatNum( $limit );
1205 } else {
1206 $limit = $key;
1207 $text = $value;
1209 $ret[$text] = $limit;
1211 return $ret;
1215 * Get \<input type="hidden"\> elements for use in a method="get" form.
1216 * Resubmits all defined elements of the query string, except for a
1217 * blacklist, passed in the $blacklist parameter.
1219 * @param array $blacklist parameters from the request query which should not be resubmitted
1220 * @return String: HTML fragment
1222 function getHiddenFields( $blacklist = array() ) {
1223 $blacklist = (array)$blacklist;
1224 $query = $this->getRequest()->getQueryValues();
1225 foreach ( $blacklist as $name ) {
1226 unset( $query[$name] );
1228 $s = '';
1229 foreach ( $query as $name => $value ) {
1230 $s .= Html::hidden( $name, $value ) . "\n";
1232 return $s;
1236 * Get a form containing a limit selection dropdown
1238 * @return String: HTML fragment
1240 function getLimitForm() {
1241 global $wgScript;
1243 return Html::rawElement(
1244 'form',
1245 array(
1246 'method' => 'get',
1247 'action' => $wgScript
1249 "\n" . $this->getLimitDropdown()
1250 ) . "\n";
1254 * Gets a limit selection dropdown
1256 * @return string
1258 function getLimitDropdown() {
1259 # Make the select with some explanatory text
1260 $msgSubmit = $this->msg( 'table_pager_limit_submit' )->escaped();
1262 return $this->msg( 'table_pager_limit' )
1263 ->rawParams( $this->getLimitSelect() )->escaped() .
1264 "\n<input type=\"submit\" value=\"$msgSubmit\"/>\n" .
1265 $this->getHiddenFields( array( 'limit' ) );
1269 * Return true if the named field should be sortable by the UI, false
1270 * otherwise
1272 * @param $field String
1274 abstract function isFieldSortable( $field );
1277 * Format a table cell. The return value should be HTML, but use an empty
1278 * string not &#160; for empty cells. Do not include the <td> and </td>.
1280 * The current result row is available as $this->mCurrentRow, in case you
1281 * need more context.
1283 * @protected
1285 * @param string $name the database field name
1286 * @param string $value the value retrieved from the database
1288 abstract function formatValue( $name, $value );
1291 * The database field name used as a default sort order.
1293 * @protected
1295 * @return string
1297 abstract function getDefaultSort();
1300 * An array mapping database field names to a textual description of the
1301 * field name, for use in the table header. The description should be plain
1302 * text, it will be HTML-escaped later.
1304 * @return Array
1306 abstract function getFieldNames();