Declare visibility for class properties in DatabaseSqlite
[mediawiki.git] / includes / Pager.php
blob19c3c43fb028c77fefdc998908fd3c4560d180cc
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 * Get the current limit
273 * @return int
275 function getLimit() {
276 return $this->mLimit;
280 * Set whether a row matching exactly the offset should be also included
281 * in the result or not. By default this is not the case, but when the
282 * offset is user-supplied this might be wanted.
284 * @param $include bool
286 public function setIncludeOffset( $include ) {
287 $this->mIncludeOffset = $include;
291 * Extract some useful data from the result object for use by
292 * the navigation bar, put it into $this
294 * @param $isFirst bool: False if there are rows before those fetched (i.e.
295 * if a "previous" link would make sense)
296 * @param $limit Integer: exact query limit
297 * @param $res ResultWrapper
299 function extractResultInfo( $isFirst, $limit, ResultWrapper $res ) {
300 $numRows = $res->numRows();
301 if ( $numRows ) {
302 # Remove any table prefix from index field
303 $parts = explode( '.', $this->mIndexField );
304 $indexColumn = end( $parts );
306 $row = $res->fetchRow();
307 $firstIndex = $row[$indexColumn];
309 # Discard the extra result row if there is one
310 if ( $numRows > $this->mLimit && $numRows > 1 ) {
311 $res->seek( $numRows - 1 );
312 $this->mPastTheEndRow = $res->fetchObject();
313 $this->mPastTheEndIndex = $this->mPastTheEndRow->$indexColumn;
314 $res->seek( $numRows - 2 );
315 $row = $res->fetchRow();
316 $lastIndex = $row[$indexColumn];
317 } else {
318 $this->mPastTheEndRow = null;
319 # Setting indexes to an empty string means that they will be
320 # omitted if they would otherwise appear in URLs. It just so
321 # happens that this is the right thing to do in the standard
322 # UI, in all the relevant cases.
323 $this->mPastTheEndIndex = '';
324 $res->seek( $numRows - 1 );
325 $row = $res->fetchRow();
326 $lastIndex = $row[$indexColumn];
328 } else {
329 $firstIndex = '';
330 $lastIndex = '';
331 $this->mPastTheEndRow = null;
332 $this->mPastTheEndIndex = '';
335 if ( $this->mIsBackwards ) {
336 $this->mIsFirst = ( $numRows < $limit );
337 $this->mIsLast = $isFirst;
338 $this->mLastShown = $firstIndex;
339 $this->mFirstShown = $lastIndex;
340 } else {
341 $this->mIsFirst = $isFirst;
342 $this->mIsLast = ( $numRows < $limit );
343 $this->mLastShown = $lastIndex;
344 $this->mFirstShown = $firstIndex;
349 * Get some text to go in brackets in the "function name" part of the SQL comment
351 * @return String
353 function getSqlComment() {
354 return get_class( $this );
358 * Do a query with specified parameters, rather than using the object
359 * context
361 * @param string $offset index offset, inclusive
362 * @param $limit Integer: exact query limit
363 * @param $descending Boolean: query direction, false for ascending, true for descending
364 * @return ResultWrapper
366 public function reallyDoQuery( $offset, $limit, $descending ) {
367 list( $tables, $fields, $conds, $fname, $options, $join_conds ) = $this->buildQueryInfo( $offset, $limit, $descending );
368 return $this->mDb->select( $tables, $fields, $conds, $fname, $options, $join_conds );
372 * Build variables to use by the database wrapper.
374 * @param string $offset index offset, inclusive
375 * @param $limit Integer: exact query limit
376 * @param $descending Boolean: query direction, false for ascending, true for descending
377 * @return array
379 protected function buildQueryInfo( $offset, $limit, $descending ) {
380 $fname = __METHOD__ . ' (' . $this->getSqlComment() . ')';
381 $info = $this->getQueryInfo();
382 $tables = $info['tables'];
383 $fields = $info['fields'];
384 $conds = isset( $info['conds'] ) ? $info['conds'] : array();
385 $options = isset( $info['options'] ) ? $info['options'] : array();
386 $join_conds = isset( $info['join_conds'] ) ? $info['join_conds'] : array();
387 $sortColumns = array_merge( array( $this->mIndexField ), $this->mExtraSortFields );
388 if ( $descending ) {
389 $options['ORDER BY'] = $sortColumns;
390 $operator = $this->mIncludeOffset ? '>=' : '>';
391 } else {
392 $orderBy = array();
393 foreach ( $sortColumns as $col ) {
394 $orderBy[] = $col . ' DESC';
396 $options['ORDER BY'] = $orderBy;
397 $operator = $this->mIncludeOffset ? '<=' : '<';
399 if ( $offset != '' ) {
400 $conds[] = $this->mIndexField . $operator . $this->mDb->addQuotes( $offset );
402 $options['LIMIT'] = intval( $limit );
403 return array( $tables, $fields, $conds, $fname, $options, $join_conds );
407 * Pre-process results; useful for performing batch existence checks, etc.
409 * @param $result ResultWrapper
411 protected function preprocessResults( $result ) {}
414 * Get the formatted result list. Calls getStartBody(), formatRow() and
415 * getEndBody(), concatenates the results and returns them.
417 * @return String
419 public function getBody() {
420 if ( !$this->mQueryDone ) {
421 $this->doQuery();
424 if ( $this->mResult->numRows() ) {
425 # Do any special query batches before display
426 $this->doBatchLookups();
429 # Don't use any extra rows returned by the query
430 $numRows = min( $this->mResult->numRows(), $this->mLimit );
432 $s = $this->getStartBody();
433 if ( $numRows ) {
434 if ( $this->mIsBackwards ) {
435 for ( $i = $numRows - 1; $i >= 0; $i-- ) {
436 $this->mResult->seek( $i );
437 $row = $this->mResult->fetchObject();
438 $s .= $this->formatRow( $row );
440 } else {
441 $this->mResult->seek( 0 );
442 for ( $i = 0; $i < $numRows; $i++ ) {
443 $row = $this->mResult->fetchObject();
444 $s .= $this->formatRow( $row );
447 } else {
448 $s .= $this->getEmptyBody();
450 $s .= $this->getEndBody();
451 return $s;
455 * Make a self-link
457 * @param string $text text displayed on the link
458 * @param array $query associative array of parameter to be in the query string
459 * @param string $type value of the "rel" attribute
461 * @return String: HTML fragment
463 function makeLink( $text, array $query = null, $type = null ) {
464 if ( $query === null ) {
465 return $text;
468 $attrs = array();
469 if ( in_array( $type, array( 'first', 'prev', 'next', 'last' ) ) ) {
470 # HTML5 rel attributes
471 $attrs['rel'] = $type;
474 if ( $type ) {
475 $attrs['class'] = "mw-{$type}link";
478 return Linker::linkKnown(
479 $this->getTitle(),
480 $text,
481 $attrs,
482 $query + $this->getDefaultQuery()
487 * Called from getBody(), before getStartBody() is called and
488 * after doQuery() was called. This will be called only if there
489 * are rows in the result set.
491 * @return void
493 protected function doBatchLookups() {}
496 * Hook into getBody(), allows text to be inserted at the start. This
497 * will be called even if there are no rows in the result set.
499 * @return String
501 protected function getStartBody() {
502 return '';
506 * Hook into getBody() for the end of the list
508 * @return String
510 protected function getEndBody() {
511 return '';
515 * Hook into getBody(), for the bit between the start and the
516 * end when there are no rows
518 * @return String
520 protected function getEmptyBody() {
521 return '';
525 * Get an array of query parameters that should be put into self-links.
526 * By default, all parameters passed in the URL are used, except for a
527 * short blacklist.
529 * @return array Associative array
531 function getDefaultQuery() {
532 if ( !isset( $this->mDefaultQuery ) ) {
533 $this->mDefaultQuery = $this->getRequest()->getQueryValues();
534 unset( $this->mDefaultQuery['title'] );
535 unset( $this->mDefaultQuery['dir'] );
536 unset( $this->mDefaultQuery['offset'] );
537 unset( $this->mDefaultQuery['limit'] );
538 unset( $this->mDefaultQuery['order'] );
539 unset( $this->mDefaultQuery['month'] );
540 unset( $this->mDefaultQuery['year'] );
542 return $this->mDefaultQuery;
546 * Get the number of rows in the result set
548 * @return Integer
550 function getNumRows() {
551 if ( !$this->mQueryDone ) {
552 $this->doQuery();
554 return $this->mResult->numRows();
558 * Get a URL query array for the prev, next, first and last links.
560 * @return Array
562 function getPagingQueries() {
563 if ( !$this->mQueryDone ) {
564 $this->doQuery();
567 # Don't announce the limit everywhere if it's the default
568 $urlLimit = $this->mLimit == $this->mDefaultLimit ? null : $this->mLimit;
570 if ( $this->mIsFirst ) {
571 $prev = false;
572 $first = false;
573 } else {
574 $prev = array(
575 'dir' => 'prev',
576 'offset' => $this->mFirstShown,
577 'limit' => $urlLimit
579 $first = array( 'limit' => $urlLimit );
581 if ( $this->mIsLast ) {
582 $next = false;
583 $last = false;
584 } else {
585 $next = array( 'offset' => $this->mLastShown, 'limit' => $urlLimit );
586 $last = array( 'dir' => 'prev', 'limit' => $urlLimit );
588 return array(
589 'prev' => $prev,
590 'next' => $next,
591 'first' => $first,
592 'last' => $last
597 * Returns whether to show the "navigation bar"
599 * @return Boolean
601 function isNavigationBarShown() {
602 if ( !$this->mQueryDone ) {
603 $this->doQuery();
605 // Hide navigation by default if there is nothing to page
606 return !( $this->mIsFirst && $this->mIsLast );
610 * Get paging links. If a link is disabled, the item from $disabledTexts
611 * will be used. If there is no such item, the unlinked text from
612 * $linkTexts will be used. Both $linkTexts and $disabledTexts are arrays
613 * of HTML.
615 * @param $linkTexts Array
616 * @param $disabledTexts Array
617 * @return Array
619 function getPagingLinks( $linkTexts, $disabledTexts = array() ) {
620 $queries = $this->getPagingQueries();
621 $links = array();
623 foreach ( $queries as $type => $query ) {
624 if ( $query !== false ) {
625 $links[$type] = $this->makeLink(
626 $linkTexts[$type],
627 $queries[$type],
628 $type
630 } elseif ( isset( $disabledTexts[$type] ) ) {
631 $links[$type] = $disabledTexts[$type];
632 } else {
633 $links[$type] = $linkTexts[$type];
637 return $links;
640 function getLimitLinks() {
641 $links = array();
642 if ( $this->mIsBackwards ) {
643 $offset = $this->mPastTheEndIndex;
644 } else {
645 $offset = $this->mOffset;
647 foreach ( $this->mLimitsShown as $limit ) {
648 $links[] = $this->makeLink(
649 $this->getLanguage()->formatNum( $limit ),
650 array( 'offset' => $offset, 'limit' => $limit ),
651 'num'
654 return $links;
658 * Abstract formatting function. This should return an HTML string
659 * representing the result row $row. Rows will be concatenated and
660 * returned by getBody()
662 * @param array $row Database row
663 * @return string
665 abstract function formatRow( $row );
668 * This function should be overridden to provide all parameters
669 * needed for the main paged query. It returns an associative
670 * array with the following elements:
671 * tables => Table(s) for passing to Database::select()
672 * fields => Field(s) for passing to Database::select(), may be *
673 * conds => WHERE conditions
674 * options => option array
675 * join_conds => JOIN conditions
677 * @return Array
679 abstract function getQueryInfo();
682 * This function should be overridden to return the name of the index fi-
683 * eld. If the pager supports multiple orders, it may return an array of
684 * 'querykey' => 'indexfield' pairs, so that a request with &count=querykey
685 * will use indexfield to sort. In this case, the first returned key is
686 * the default.
688 * Needless to say, it's really not a good idea to use a non-unique index
689 * for this! That won't page right.
691 * @return string|Array
693 abstract function getIndexField();
696 * This function should be overridden to return the names of secondary columns
697 * to order by in addition to the column in getIndexField(). These fields will
698 * not be used in the pager offset or in any links for users.
700 * If getIndexField() returns an array of 'querykey' => 'indexfield' pairs then
701 * this must return a corresponding array of 'querykey' => array( fields...) pairs
702 * in order for a request with &count=querykey to use array( fields...) to sort.
704 * This is useful for pagers that GROUP BY a unique column (say page_id)
705 * and ORDER BY another (say page_len). Using GROUP BY and ORDER BY both on
706 * page_len,page_id avoids temp tables (given a page_len index). This would
707 * also work if page_id was non-unique but we had a page_len,page_id index.
709 * @return Array
711 protected function getExtraSortFields() {
712 return array();
716 * Return the default sorting direction: false for ascending, true for
717 * descending. You can also have an associative array of ordertype => dir,
718 * if multiple order types are supported. In this case getIndexField()
719 * must return an array, and the keys of that must exactly match the keys
720 * of this.
722 * For backward compatibility, this method's return value will be ignored
723 * if $this->mDefaultDirection is already set when the constructor is
724 * called, for instance if it's statically initialized. In that case the
725 * value of that variable (which must be a boolean) will be used.
727 * Note that despite its name, this does not return the value of the
728 * $this->mDefaultDirection member variable. That's the default for this
729 * particular instantiation, which is a single value. This is the set of
730 * all defaults for the class.
732 * @return Boolean
734 protected function getDefaultDirections() {
735 return false;
740 * IndexPager with an alphabetic list and a formatted navigation bar
741 * @ingroup Pager
743 abstract class AlphabeticPager extends IndexPager {
746 * Shamelessly stolen bits from ReverseChronologicalPager,
747 * didn't want to do class magic as may be still revamped
749 * @return String HTML
751 function getNavigationBar() {
752 if ( !$this->isNavigationBarShown() ) {
753 return '';
756 if ( isset( $this->mNavigationBar ) ) {
757 return $this->mNavigationBar;
760 $linkTexts = array(
761 'prev' => $this->msg( 'prevn' )->numParams( $this->mLimit )->escaped(),
762 'next' => $this->msg( 'nextn' )->numParams( $this->mLimit )->escaped(),
763 'first' => $this->msg( 'page_first' )->escaped(),
764 'last' => $this->msg( 'page_last' )->escaped()
767 $lang = $this->getLanguage();
769 $pagingLinks = $this->getPagingLinks( $linkTexts );
770 $limitLinks = $this->getLimitLinks();
771 $limits = $lang->pipeList( $limitLinks );
773 $this->mNavigationBar = $this->msg( 'parentheses' )->rawParams(
774 $lang->pipeList( array( $pagingLinks['first'],
775 $pagingLinks['last'] ) ) )->escaped() . " " .
776 $this->msg( 'viewprevnext' )->rawParams( $pagingLinks['prev'],
777 $pagingLinks['next'], $limits )->escaped();
779 if ( !is_array( $this->getIndexField() ) ) {
780 # Early return to avoid undue nesting
781 return $this->mNavigationBar;
784 $extra = '';
785 $first = true;
786 $msgs = $this->getOrderTypeMessages();
787 foreach ( array_keys( $msgs ) as $order ) {
788 if ( $first ) {
789 $first = false;
790 } else {
791 $extra .= $this->msg( 'pipe-separator' )->escaped();
794 if ( $order == $this->mOrderType ) {
795 $extra .= $this->msg( $msgs[$order] )->escaped();
796 } else {
797 $extra .= $this->makeLink(
798 $this->msg( $msgs[$order] )->escaped(),
799 array( 'order' => $order )
804 if ( $extra !== '' ) {
805 $extra = ' ' . $this->msg( 'parentheses' )->rawParams( $extra )->escaped();
806 $this->mNavigationBar .= $extra;
809 return $this->mNavigationBar;
813 * If this supports multiple order type messages, give the message key for
814 * enabling each one in getNavigationBar. The return type is an associative
815 * array whose keys must exactly match the keys of the array returned
816 * by getIndexField(), and whose values are message keys.
818 * @return Array
820 protected function getOrderTypeMessages() {
821 return null;
826 * IndexPager with a formatted navigation bar
827 * @ingroup Pager
829 abstract class ReverseChronologicalPager extends IndexPager {
830 public $mDefaultDirection = true;
831 public $mYear;
832 public $mMonth;
834 function getNavigationBar() {
835 if ( !$this->isNavigationBarShown() ) {
836 return '';
839 if ( isset( $this->mNavigationBar ) ) {
840 return $this->mNavigationBar;
843 $linkTexts = array(
844 'prev' => $this->msg( 'pager-newer-n' )->numParams( $this->mLimit )->escaped(),
845 'next' => $this->msg( 'pager-older-n' )->numParams( $this->mLimit )->escaped(),
846 'first' => $this->msg( 'histlast' )->escaped(),
847 'last' => $this->msg( 'histfirst' )->escaped()
850 $pagingLinks = $this->getPagingLinks( $linkTexts );
851 $limitLinks = $this->getLimitLinks();
852 $limits = $this->getLanguage()->pipeList( $limitLinks );
853 $firstLastLinks = $this->msg( 'parentheses' )->rawParams( "{$pagingLinks['first']}" .
854 $this->msg( 'pipe-separator' )->escaped() .
855 "{$pagingLinks['last']}" )->escaped();
857 $this->mNavigationBar = $firstLastLinks . ' ' .
858 $this->msg( 'viewprevnext' )->rawParams(
859 $pagingLinks['prev'], $pagingLinks['next'], $limits )->escaped();
861 return $this->mNavigationBar;
864 function getDateCond( $year, $month ) {
865 $year = intval( $year );
866 $month = intval( $month );
868 // Basic validity checks
869 $this->mYear = $year > 0 ? $year : false;
870 $this->mMonth = ( $month > 0 && $month < 13 ) ? $month : false;
872 // Given an optional year and month, we need to generate a timestamp
873 // to use as "WHERE rev_timestamp <= result"
874 // Examples: year = 2006 equals < 20070101 (+000000)
875 // year=2005, month=1 equals < 20050201
876 // year=2005, month=12 equals < 20060101
877 if ( !$this->mYear && !$this->mMonth ) {
878 return;
881 if ( $this->mYear ) {
882 $year = $this->mYear;
883 } else {
884 // If no year given, assume the current one
885 $timestamp = MWTimestamp::getInstance();
886 $year = $timestamp->format( 'Y' );
887 // If this month hasn't happened yet this year, go back to last year's month
888 if ( $this->mMonth > $timestamp->format( 'n' ) ) {
889 $year--;
893 if ( $this->mMonth ) {
894 $month = $this->mMonth + 1;
895 // For December, we want January 1 of the next year
896 if ( $month > 12 ) {
897 $month = 1;
898 $year++;
900 } else {
901 // No month implies we want up to the end of the year in question
902 $month = 1;
903 $year++;
906 // Y2K38 bug
907 if ( $year > 2032 ) {
908 $year = 2032;
911 $ymd = (int)sprintf( "%04d%02d01", $year, $month );
913 if ( $ymd > 20320101 ) {
914 $ymd = 20320101;
917 $this->mOffset = $this->mDb->timestamp( "${ymd}000000" );
922 * Table-based display with a user-selectable sort order
923 * @ingroup Pager
925 abstract class TablePager extends IndexPager {
926 var $mSort;
927 var $mCurrentRow;
929 public function __construct( IContextSource $context = null ) {
930 if ( $context ) {
931 $this->setContext( $context );
934 $this->mSort = $this->getRequest()->getText( 'sort' );
935 if ( !array_key_exists( $this->mSort, $this->getFieldNames() )
936 || !$this->isFieldSortable( $this->mSort )
938 $this->mSort = $this->getDefaultSort();
940 if ( $this->getRequest()->getBool( 'asc' ) ) {
941 $this->mDefaultDirection = false;
942 } elseif ( $this->getRequest()->getBool( 'desc' ) ) {
943 $this->mDefaultDirection = true;
944 } /* Else leave it at whatever the class default is */
946 parent::__construct();
950 * @protected
951 * @return string
953 function getStartBody() {
954 global $wgStylePath;
955 $sortClass = $this->getSortHeaderClass();
957 $s = '';
958 $fields = $this->getFieldNames();
960 # Make table header
961 foreach ( $fields as $field => $name ) {
962 if ( strval( $name ) == '' ) {
963 $s .= Html::rawElement( 'th', array(), '&#160;' ) . "\n";
964 } elseif ( $this->isFieldSortable( $field ) ) {
965 $query = array( 'sort' => $field, 'limit' => $this->mLimit );
966 if ( $field == $this->mSort ) {
967 # This is the sorted column
968 # Prepare a link that goes in the other sort order
969 if ( $this->mDefaultDirection ) {
970 # Descending
971 $image = 'Arr_d.png';
972 $query['asc'] = '1';
973 $query['desc'] = '';
974 $alt = $this->msg( 'descending_abbrev' )->escaped();
975 } else {
976 # Ascending
977 $image = 'Arr_u.png';
978 $query['asc'] = '';
979 $query['desc'] = '1';
980 $alt = $this->msg( 'ascending_abbrev' )->escaped();
982 $image = "$wgStylePath/common/images/$image";
983 $link = $this->makeLink(
984 Html::element( 'img', array( 'width' => 12, 'height' => 12,
985 'alt' => $alt, 'src' => $image ) ) . htmlspecialchars( $name ), $query );
986 $s .= Html::rawElement( 'th', array( 'class' => $sortClass ), $link ) . "\n";
987 } else {
988 $s .= Html::rawElement( 'th', array(),
989 $this->makeLink( htmlspecialchars( $name ), $query ) ) . "\n";
991 } else {
992 $s .= Html::element( 'th', array(), $name ) . "\n";
996 $tableClass = $this->getTableClass();
997 $ret = Html::openElement( 'table', array( 'style' => 'border:1px;', 'class' => "mw-datatable $tableClass" ) );
998 $ret .= Html::rawElement( 'thead', array(), Html::rawElement( 'tr', array(), "\n" . $s . "\n" ) );
999 $ret .= Html::openElement( 'tbody' ) . "\n";
1001 return $ret;
1005 * @protected
1006 * @return string
1008 function getEndBody() {
1009 return "</tbody></table>\n";
1013 * @protected
1014 * @return string
1016 function getEmptyBody() {
1017 $colspan = count( $this->getFieldNames() );
1018 $msgEmpty = $this->msg( 'table_pager_empty' )->text();
1019 return Html::rawElement( 'tr', array(),
1020 Html::element( 'td', array( 'colspan' => $colspan ), $msgEmpty ) );
1024 * @protected
1025 * @param stdClass $row
1026 * @return String HTML
1028 function formatRow( $row ) {
1029 $this->mCurrentRow = $row; // In case formatValue etc need to know
1030 $s = Html::openElement( 'tr', $this->getRowAttrs( $row ) ) . "\n";
1031 $fieldNames = $this->getFieldNames();
1033 foreach ( $fieldNames as $field => $name ) {
1034 $value = isset( $row->$field ) ? $row->$field : null;
1035 $formatted = strval( $this->formatValue( $field, $value ) );
1037 if ( $formatted == '' ) {
1038 $formatted = '&#160;';
1041 $s .= Html::rawElement( 'td', $this->getCellAttrs( $field, $value ), $formatted ) . "\n";
1044 $s .= Html::closeElement( 'tr' ) . "\n";
1046 return $s;
1050 * Get a class name to be applied to the given row.
1052 * @protected
1054 * @param $row Object: the database result row
1055 * @return String
1057 function getRowClass( $row ) {
1058 return '';
1062 * Get attributes to be applied to the given row.
1064 * @protected
1066 * @param $row Object: the database result row
1067 * @return Array of attribute => value
1069 function getRowAttrs( $row ) {
1070 $class = $this->getRowClass( $row );
1071 if ( $class === '' ) {
1072 // Return an empty array to avoid clutter in HTML like class=""
1073 return array();
1074 } else {
1075 return array( 'class' => $this->getRowClass( $row ) );
1080 * Get any extra attributes to be applied to the given cell. Don't
1081 * take this as an excuse to hardcode styles; use classes and
1082 * CSS instead. Row context is available in $this->mCurrentRow
1084 * @protected
1086 * @param string $field The column
1087 * @param string $value The cell contents
1088 * @return Array of attr => value
1090 function getCellAttrs( $field, $value ) {
1091 return array( 'class' => 'TablePager_col_' . $field );
1095 * @protected
1096 * @return string
1098 function getIndexField() {
1099 return $this->mSort;
1103 * @protected
1104 * @return string
1106 function getTableClass() {
1107 return 'TablePager';
1111 * @protected
1112 * @return string
1114 function getNavClass() {
1115 return 'TablePager_nav';
1119 * @protected
1120 * @return string
1122 function getSortHeaderClass() {
1123 return 'TablePager_sort';
1127 * A navigation bar with images
1128 * @return String HTML
1130 public function getNavigationBar() {
1131 global $wgStylePath;
1133 if ( !$this->isNavigationBarShown() ) {
1134 return '';
1137 $path = "$wgStylePath/common/images";
1138 $labels = array(
1139 'first' => 'table_pager_first',
1140 'prev' => 'table_pager_prev',
1141 'next' => 'table_pager_next',
1142 'last' => 'table_pager_last',
1144 $images = array(
1145 'first' => 'arrow_first_25.png',
1146 'prev' => 'arrow_left_25.png',
1147 'next' => 'arrow_right_25.png',
1148 'last' => 'arrow_last_25.png',
1150 $disabledImages = array(
1151 'first' => 'arrow_disabled_first_25.png',
1152 'prev' => 'arrow_disabled_left_25.png',
1153 'next' => 'arrow_disabled_right_25.png',
1154 'last' => 'arrow_disabled_last_25.png',
1156 if ( $this->getLanguage()->isRTL() ) {
1157 $keys = array_keys( $labels );
1158 $images = array_combine( $keys, array_reverse( $images ) );
1159 $disabledImages = array_combine( $keys, array_reverse( $disabledImages ) );
1162 $linkTexts = array();
1163 $disabledTexts = array();
1164 foreach ( $labels as $type => $label ) {
1165 $msgLabel = $this->msg( $label )->escaped();
1166 $linkTexts[$type] = Html::element( 'img', array( 'src' => "$path/{$images[$type]}",
1167 'alt' => $msgLabel ) ) . "<br />$msgLabel";
1168 $disabledTexts[$type] = Html::element( 'img', array( 'src' => "$path/{$disabledImages[$type]}",
1169 'alt' => $msgLabel ) ) . "<br />$msgLabel";
1171 $links = $this->getPagingLinks( $linkTexts, $disabledTexts );
1173 $s = Html::openElement( 'table', array( 'class' => $this->getNavClass() ) );
1174 $s .= Html::openElement( 'tr' ) . "\n";
1175 $width = 100 / count( $links ) . '%';
1176 foreach ( $labels as $type => $label ) {
1177 $s .= Html::rawElement( 'td', array( 'style' => "width:$width;" ), $links[$type] ) . "\n";
1179 $s .= Html::closeElement( 'tr' ) . Html::closeElement( 'table' ) . "\n";
1180 return $s;
1184 * Get a "<select>" element which has options for each of the allowed limits
1186 * @param $attribs String: Extra attributes to set
1187 * @return String: HTML fragment
1189 public function getLimitSelect( $attribs = array() ) {
1190 $select = new XmlSelect( 'limit', false, $this->mLimit );
1191 $select->addOptions( $this->getLimitSelectList() );
1192 foreach ( $attribs as $name => $value ) {
1193 $select->setAttribute( $name, $value );
1195 return $select->getHTML();
1199 * Get a list of items to show in a "<select>" element of limits.
1200 * This can be passed directly to XmlSelect::addOptions().
1202 * @since 1.22
1203 * @return array
1205 public function getLimitSelectList() {
1206 # Add the current limit from the query string
1207 # to avoid that the limit is lost after clicking Go next time
1208 if ( !in_array( $this->mLimit, $this->mLimitsShown ) ) {
1209 $this->mLimitsShown[] = $this->mLimit;
1210 sort( $this->mLimitsShown );
1212 $ret = array();
1213 foreach ( $this->mLimitsShown as $key => $value ) {
1214 # The pair is either $index => $limit, in which case the $value
1215 # will be numeric, or $limit => $text, in which case the $value
1216 # will be a string.
1217 if ( is_int( $value ) ) {
1218 $limit = $value;
1219 $text = $this->getLanguage()->formatNum( $limit );
1220 } else {
1221 $limit = $key;
1222 $text = $value;
1224 $ret[$text] = $limit;
1226 return $ret;
1230 * Get \<input type="hidden"\> elements for use in a method="get" form.
1231 * Resubmits all defined elements of the query string, except for a
1232 * blacklist, passed in the $blacklist parameter.
1234 * @param array $blacklist parameters from the request query which should not be resubmitted
1235 * @return String: HTML fragment
1237 function getHiddenFields( $blacklist = array() ) {
1238 $blacklist = (array)$blacklist;
1239 $query = $this->getRequest()->getQueryValues();
1240 foreach ( $blacklist as $name ) {
1241 unset( $query[$name] );
1243 $s = '';
1244 foreach ( $query as $name => $value ) {
1245 $s .= Html::hidden( $name, $value ) . "\n";
1247 return $s;
1251 * Get a form containing a limit selection dropdown
1253 * @return String: HTML fragment
1255 function getLimitForm() {
1256 global $wgScript;
1258 return Html::rawElement(
1259 'form',
1260 array(
1261 'method' => 'get',
1262 'action' => $wgScript
1264 "\n" . $this->getLimitDropdown()
1265 ) . "\n";
1269 * Gets a limit selection dropdown
1271 * @return string
1273 function getLimitDropdown() {
1274 # Make the select with some explanatory text
1275 $msgSubmit = $this->msg( 'table_pager_limit_submit' )->escaped();
1277 return $this->msg( 'table_pager_limit' )
1278 ->rawParams( $this->getLimitSelect() )->escaped() .
1279 "\n<input type=\"submit\" value=\"$msgSubmit\"/>\n" .
1280 $this->getHiddenFields( array( 'limit' ) );
1284 * Return true if the named field should be sortable by the UI, false
1285 * otherwise
1287 * @param $field String
1289 abstract function isFieldSortable( $field );
1292 * Format a table cell. The return value should be HTML, but use an empty
1293 * string not &#160; for empty cells. Do not include the <td> and </td>.
1295 * The current result row is available as $this->mCurrentRow, in case you
1296 * need more context.
1298 * @protected
1300 * @param string $name the database field name
1301 * @param string $value the value retrieved from the database
1303 abstract function formatValue( $name, $value );
1306 * The database field name used as a default sort order.
1308 * @protected
1310 * @return string
1312 abstract function getDefaultSort();
1315 * An array mapping database field names to a textual description of the
1316 * field name, for use in the table header. The description should be plain
1317 * text, it will be HTML-escaped later.
1319 * @return Array
1321 abstract function getFieldNames();