Merge "Move list generation out of TablePager::getLimitSelect()"
[lhc/web/wiklou.git] / includes / Pager.php
1 <?php
2 /**
3 * Efficient paging for SQL queries.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Pager
22 */
23
24 /**
25 * @defgroup Pager Pager
26 */
27
28 /**
29 * Basic pager interface.
30 * @ingroup Pager
31 */
32 interface Pager {
33 function getNavigationBar();
34 function getBody();
35 }
36
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.
43 *
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:
47 *
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.
66 *
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.
70 *
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.
76 *
77 * @ingroup Pager
78 */
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;
87
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.
91 */
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.
96 */
97 protected $mExtraSortFields;
98 /** For pages that support multiple types of ordering, which one to use.
99 */
100 protected $mOrderType;
101 /**
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.
108 *
109 * Like $mIndexField, $mDefaultDirection will be a single value even if the
110 * class supports multiple default directions for different order types.
111 */
112 public $mDefaultDirection;
113 public $mIsBackwards;
114
115 /** True if the current result set is the first one */
116 public $mIsFirst;
117 public $mIsLast;
118
119 protected $mLastShown, $mFirstShown, $mPastTheEndIndex, $mDefaultQuery, $mNavigationBar;
120
121 /**
122 * Whether to include the offset in the query
123 */
124 protected $mIncludeOffset = false;
125
126 /**
127 * Result object for the query. Warning: seek before use.
128 *
129 * @var ResultWrapper
130 */
131 public $mResult;
132
133 public function __construct( IContextSource $context = null ) {
134 if ( $context ) {
135 $this->setContext( $context );
136 }
137
138 $this->mRequest = $this->getRequest();
139
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' );
144
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();
150 }
151
152 $this->mIsBackwards = ( $this->mRequest->getVal( 'dir' ) == 'prev' );
153 $this->mDb = wfGetDB( DB_SLAVE );
154
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;
176 }
177
178 if ( !isset( $this->mDefaultDirection ) ) {
179 $dir = $this->getDefaultDirections();
180 $this->mDefaultDirection = is_array( $dir )
181 ? $dir[$this->mOrderType]
182 : $dir;
183 }
184 }
185
186 /**
187 * Get the Database object in use
188 *
189 * @return DatabaseBase
190 */
191 public function getDatabase() {
192 return $this->mDb;
193 }
194
195 /**
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.
199 */
200 public function doQuery() {
201 # Use the child class name for profiling
202 $fname = __METHOD__ . ' (' . get_class( $this ) . ')';
203 wfProfileIn( $fname );
204
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;
208
209 $this->mResult = $this->reallyDoQuery(
210 $this->mOffset,
211 $queryLimit,
212 $descending
213 );
214
215 $this->extractResultInfo( $this->mOffset, $queryLimit, $this->mResult );
216 $this->mQueryDone = true;
217
218 $this->preprocessResults( $this->mResult );
219 $this->mResult->rewind(); // Paranoia
220
221 wfProfileOut( $fname );
222 }
223
224 /**
225 * @return ResultWrapper The result wrapper.
226 */
227 function getResult() {
228 return $this->mResult;
229 }
230
231 /**
232 * Set the offset from an other source than the request
233 *
234 * @param $offset Int|String
235 */
236 function setOffset( $offset ) {
237 $this->mOffset = $offset;
238 }
239 /**
240 * Set the limit from an other source than the request
241 *
242 * Verifies limit is between 1 and 5000
243 *
244 * @param $limit Int|String
245 */
246 function setLimit( $limit ) {
247 $limit = (int) $limit;
248 // WebRequest::getLimitOffset() puts a cap of 5000, so do same here.
249 if ( $limit > 5000 ) {
250 $limit = 5000;
251 }
252 if ( $limit > 0 ) {
253 $this->mLimit = $limit;
254 }
255 }
256
257 /**
258 * Set whether a row matching exactly the offset should be also included
259 * in the result or not. By default this is not the case, but when the
260 * offset is user-supplied this might be wanted.
261 *
262 * @param $include bool
263 */
264 public function setIncludeOffset( $include ) {
265 $this->mIncludeOffset = $include;
266 }
267
268 /**
269 * Extract some useful data from the result object for use by
270 * the navigation bar, put it into $this
271 *
272 * @param string $offset index offset, inclusive
273 * @param $limit Integer: exact query limit
274 * @param $res ResultWrapper
275 */
276 function extractResultInfo( $offset, $limit, ResultWrapper $res ) {
277 $numRows = $res->numRows();
278 if ( $numRows ) {
279 # Remove any table prefix from index field
280 $parts = explode( '.', $this->mIndexField );
281 $indexColumn = end( $parts );
282
283 $row = $res->fetchRow();
284 $firstIndex = $row[$indexColumn];
285
286 # Discard the extra result row if there is one
287 if ( $numRows > $this->mLimit && $numRows > 1 ) {
288 $res->seek( $numRows - 1 );
289 $this->mPastTheEndRow = $res->fetchObject();
290 $this->mPastTheEndIndex = $this->mPastTheEndRow->$indexColumn;
291 $res->seek( $numRows - 2 );
292 $row = $res->fetchRow();
293 $lastIndex = $row[$indexColumn];
294 } else {
295 $this->mPastTheEndRow = null;
296 # Setting indexes to an empty string means that they will be
297 # omitted if they would otherwise appear in URLs. It just so
298 # happens that this is the right thing to do in the standard
299 # UI, in all the relevant cases.
300 $this->mPastTheEndIndex = '';
301 $res->seek( $numRows - 1 );
302 $row = $res->fetchRow();
303 $lastIndex = $row[$indexColumn];
304 }
305 } else {
306 $firstIndex = '';
307 $lastIndex = '';
308 $this->mPastTheEndRow = null;
309 $this->mPastTheEndIndex = '';
310 }
311
312 if ( $this->mIsBackwards ) {
313 $this->mIsFirst = ( $numRows < $limit );
314 $this->mIsLast = ( $offset == '' );
315 $this->mLastShown = $firstIndex;
316 $this->mFirstShown = $lastIndex;
317 } else {
318 $this->mIsFirst = ( $offset == '' );
319 $this->mIsLast = ( $numRows < $limit );
320 $this->mLastShown = $lastIndex;
321 $this->mFirstShown = $firstIndex;
322 }
323 }
324
325 /**
326 * Get some text to go in brackets in the "function name" part of the SQL comment
327 *
328 * @return String
329 */
330 function getSqlComment() {
331 return get_class( $this );
332 }
333
334 /**
335 * Do a query with specified parameters, rather than using the object
336 * context
337 *
338 * @param string $offset index offset, inclusive
339 * @param $limit Integer: exact query limit
340 * @param $descending Boolean: query direction, false for ascending, true for descending
341 * @return ResultWrapper
342 */
343 public function reallyDoQuery( $offset, $limit, $descending ) {
344 list( $tables, $fields, $conds, $fname, $options, $join_conds ) = $this->buildQueryInfo( $offset, $limit, $descending );
345 return $this->mDb->select( $tables, $fields, $conds, $fname, $options, $join_conds );
346 }
347
348 /**
349 * Build variables to use by the database wrapper.
350 *
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 array
355 */
356 protected function buildQueryInfo( $offset, $limit, $descending ) {
357 $fname = __METHOD__ . ' (' . $this->getSqlComment() . ')';
358 $info = $this->getQueryInfo();
359 $tables = $info['tables'];
360 $fields = $info['fields'];
361 $conds = isset( $info['conds'] ) ? $info['conds'] : array();
362 $options = isset( $info['options'] ) ? $info['options'] : array();
363 $join_conds = isset( $info['join_conds'] ) ? $info['join_conds'] : array();
364 $sortColumns = array_merge( array( $this->mIndexField ), $this->mExtraSortFields );
365 if ( $descending ) {
366 $options['ORDER BY'] = $sortColumns;
367 $operator = $this->mIncludeOffset ? '>=' : '>';
368 } else {
369 $orderBy = array();
370 foreach ( $sortColumns as $col ) {
371 $orderBy[] = $col . ' DESC';
372 }
373 $options['ORDER BY'] = $orderBy;
374 $operator = $this->mIncludeOffset ? '<=' : '<';
375 }
376 if ( $offset != '' ) {
377 $conds[] = $this->mIndexField . $operator . $this->mDb->addQuotes( $offset );
378 }
379 $options['LIMIT'] = intval( $limit );
380 return array( $tables, $fields, $conds, $fname, $options, $join_conds );
381 }
382
383 /**
384 * Pre-process results; useful for performing batch existence checks, etc.
385 *
386 * @param $result ResultWrapper
387 */
388 protected function preprocessResults( $result ) {}
389
390 /**
391 * Get the formatted result list. Calls getStartBody(), formatRow() and
392 * getEndBody(), concatenates the results and returns them.
393 *
394 * @return String
395 */
396 public function getBody() {
397 if ( !$this->mQueryDone ) {
398 $this->doQuery();
399 }
400
401 if ( $this->mResult->numRows() ) {
402 # Do any special query batches before display
403 $this->doBatchLookups();
404 }
405
406 # Don't use any extra rows returned by the query
407 $numRows = min( $this->mResult->numRows(), $this->mLimit );
408
409 $s = $this->getStartBody();
410 if ( $numRows ) {
411 if ( $this->mIsBackwards ) {
412 for ( $i = $numRows - 1; $i >= 0; $i-- ) {
413 $this->mResult->seek( $i );
414 $row = $this->mResult->fetchObject();
415 $s .= $this->formatRow( $row );
416 }
417 } else {
418 $this->mResult->seek( 0 );
419 for ( $i = 0; $i < $numRows; $i++ ) {
420 $row = $this->mResult->fetchObject();
421 $s .= $this->formatRow( $row );
422 }
423 }
424 } else {
425 $s .= $this->getEmptyBody();
426 }
427 $s .= $this->getEndBody();
428 return $s;
429 }
430
431 /**
432 * Make a self-link
433 *
434 * @param string $text text displayed on the link
435 * @param array $query associative array of parameter to be in the query string
436 * @param string $type value of the "rel" attribute
437 *
438 * @return String: HTML fragment
439 */
440 function makeLink( $text, array $query = null, $type = null ) {
441 if ( $query === null ) {
442 return $text;
443 }
444
445 $attrs = array();
446 if ( in_array( $type, array( 'first', 'prev', 'next', 'last' ) ) ) {
447 # HTML5 rel attributes
448 $attrs['rel'] = $type;
449 }
450
451 if ( $type ) {
452 $attrs['class'] = "mw-{$type}link";
453 }
454
455 return Linker::linkKnown(
456 $this->getTitle(),
457 $text,
458 $attrs,
459 $query + $this->getDefaultQuery()
460 );
461 }
462
463 /**
464 * Called from getBody(), before getStartBody() is called and
465 * after doQuery() was called. This will be called only if there
466 * are rows in the result set.
467 *
468 * @return void
469 */
470 protected function doBatchLookups() {}
471
472 /**
473 * Hook into getBody(), allows text to be inserted at the start. This
474 * will be called even if there are no rows in the result set.
475 *
476 * @return String
477 */
478 protected function getStartBody() {
479 return '';
480 }
481
482 /**
483 * Hook into getBody() for the end of the list
484 *
485 * @return String
486 */
487 protected function getEndBody() {
488 return '';
489 }
490
491 /**
492 * Hook into getBody(), for the bit between the start and the
493 * end when there are no rows
494 *
495 * @return String
496 */
497 protected function getEmptyBody() {
498 return '';
499 }
500
501 /**
502 * Get an array of query parameters that should be put into self-links.
503 * By default, all parameters passed in the URL are used, except for a
504 * short blacklist.
505 *
506 * @return array Associative array
507 */
508 function getDefaultQuery() {
509 if ( !isset( $this->mDefaultQuery ) ) {
510 $this->mDefaultQuery = $this->getRequest()->getQueryValues();
511 unset( $this->mDefaultQuery['title'] );
512 unset( $this->mDefaultQuery['dir'] );
513 unset( $this->mDefaultQuery['offset'] );
514 unset( $this->mDefaultQuery['limit'] );
515 unset( $this->mDefaultQuery['order'] );
516 unset( $this->mDefaultQuery['month'] );
517 unset( $this->mDefaultQuery['year'] );
518 }
519 return $this->mDefaultQuery;
520 }
521
522 /**
523 * Get the number of rows in the result set
524 *
525 * @return Integer
526 */
527 function getNumRows() {
528 if ( !$this->mQueryDone ) {
529 $this->doQuery();
530 }
531 return $this->mResult->numRows();
532 }
533
534 /**
535 * Get a URL query array for the prev, next, first and last links.
536 *
537 * @return Array
538 */
539 function getPagingQueries() {
540 if ( !$this->mQueryDone ) {
541 $this->doQuery();
542 }
543
544 # Don't announce the limit everywhere if it's the default
545 $urlLimit = $this->mLimit == $this->mDefaultLimit ? null : $this->mLimit;
546
547 if ( $this->mIsFirst ) {
548 $prev = false;
549 $first = false;
550 } else {
551 $prev = array(
552 'dir' => 'prev',
553 'offset' => $this->mFirstShown,
554 'limit' => $urlLimit
555 );
556 $first = array( 'limit' => $urlLimit );
557 }
558 if ( $this->mIsLast ) {
559 $next = false;
560 $last = false;
561 } else {
562 $next = array( 'offset' => $this->mLastShown, 'limit' => $urlLimit );
563 $last = array( 'dir' => 'prev', 'limit' => $urlLimit );
564 }
565 return array(
566 'prev' => $prev,
567 'next' => $next,
568 'first' => $first,
569 'last' => $last
570 );
571 }
572
573 /**
574 * Returns whether to show the "navigation bar"
575 *
576 * @return Boolean
577 */
578 function isNavigationBarShown() {
579 if ( !$this->mQueryDone ) {
580 $this->doQuery();
581 }
582 // Hide navigation by default if there is nothing to page
583 return !($this->mIsFirst && $this->mIsLast);
584 }
585
586 /**
587 * Get paging links. If a link is disabled, the item from $disabledTexts
588 * will be used. If there is no such item, the unlinked text from
589 * $linkTexts will be used. Both $linkTexts and $disabledTexts are arrays
590 * of HTML.
591 *
592 * @param $linkTexts Array
593 * @param $disabledTexts Array
594 * @return Array
595 */
596 function getPagingLinks( $linkTexts, $disabledTexts = array() ) {
597 $queries = $this->getPagingQueries();
598 $links = array();
599
600 foreach ( $queries as $type => $query ) {
601 if ( $query !== false ) {
602 $links[$type] = $this->makeLink(
603 $linkTexts[$type],
604 $queries[$type],
605 $type
606 );
607 } elseif ( isset( $disabledTexts[$type] ) ) {
608 $links[$type] = $disabledTexts[$type];
609 } else {
610 $links[$type] = $linkTexts[$type];
611 }
612 }
613
614 return $links;
615 }
616
617 function getLimitLinks() {
618 $links = array();
619 if ( $this->mIsBackwards ) {
620 $offset = $this->mPastTheEndIndex;
621 } else {
622 $offset = $this->mOffset;
623 }
624 foreach ( $this->mLimitsShown as $limit ) {
625 $links[] = $this->makeLink(
626 $this->getLanguage()->formatNum( $limit ),
627 array( 'offset' => $offset, 'limit' => $limit ),
628 'num'
629 );
630 }
631 return $links;
632 }
633
634 /**
635 * Abstract formatting function. This should return an HTML string
636 * representing the result row $row. Rows will be concatenated and
637 * returned by getBody()
638 *
639 * @param $row Object: database row
640 * @return String
641 */
642 abstract function formatRow( $row );
643
644 /**
645 * This function should be overridden to provide all parameters
646 * needed for the main paged query. It returns an associative
647 * array with the following elements:
648 * tables => Table(s) for passing to Database::select()
649 * fields => Field(s) for passing to Database::select(), may be *
650 * conds => WHERE conditions
651 * options => option array
652 * join_conds => JOIN conditions
653 *
654 * @return Array
655 */
656 abstract function getQueryInfo();
657
658 /**
659 * This function should be overridden to return the name of the index fi-
660 * eld. If the pager supports multiple orders, it may return an array of
661 * 'querykey' => 'indexfield' pairs, so that a request with &count=querykey
662 * will use indexfield to sort. In this case, the first returned key is
663 * the default.
664 *
665 * Needless to say, it's really not a good idea to use a non-unique index
666 * for this! That won't page right.
667 *
668 * @return string|Array
669 */
670 abstract function getIndexField();
671
672 /**
673 * This function should be overridden to return the names of secondary columns
674 * to order by in addition to the column in getIndexField(). These fields will
675 * not be used in the pager offset or in any links for users.
676 *
677 * If getIndexField() returns an array of 'querykey' => 'indexfield' pairs then
678 * this must return a corresponding array of 'querykey' => array( fields...) pairs
679 * in order for a request with &count=querykey to use array( fields...) to sort.
680 *
681 * This is useful for pagers that GROUP BY a unique column (say page_id)
682 * and ORDER BY another (say page_len). Using GROUP BY and ORDER BY both on
683 * page_len,page_id avoids temp tables (given a page_len index). This would
684 * also work if page_id was non-unique but we had a page_len,page_id index.
685 *
686 * @return Array
687 */
688 protected function getExtraSortFields() {
689 return array();
690 }
691
692 /**
693 * Return the default sorting direction: false for ascending, true for
694 * descending. You can also have an associative array of ordertype => dir,
695 * if multiple order types are supported. In this case getIndexField()
696 * must return an array, and the keys of that must exactly match the keys
697 * of this.
698 *
699 * For backward compatibility, this method's return value will be ignored
700 * if $this->mDefaultDirection is already set when the constructor is
701 * called, for instance if it's statically initialized. In that case the
702 * value of that variable (which must be a boolean) will be used.
703 *
704 * Note that despite its name, this does not return the value of the
705 * $this->mDefaultDirection member variable. That's the default for this
706 * particular instantiation, which is a single value. This is the set of
707 * all defaults for the class.
708 *
709 * @return Boolean
710 */
711 protected function getDefaultDirections() {
712 return false;
713 }
714 }
715
716 /**
717 * IndexPager with an alphabetic list and a formatted navigation bar
718 * @ingroup Pager
719 */
720 abstract class AlphabeticPager extends IndexPager {
721
722 /**
723 * Shamelessly stolen bits from ReverseChronologicalPager,
724 * didn't want to do class magic as may be still revamped
725 *
726 * @return String HTML
727 */
728 function getNavigationBar() {
729 if ( !$this->isNavigationBarShown() ) {
730 return '';
731 }
732
733 if ( isset( $this->mNavigationBar ) ) {
734 return $this->mNavigationBar;
735 }
736
737 $linkTexts = array(
738 'prev' => $this->msg( 'prevn' )->numParams( $this->mLimit )->escaped(),
739 'next' => $this->msg( 'nextn' )->numParams( $this->mLimit )->escaped(),
740 'first' => $this->msg( 'page_first' )->escaped(),
741 'last' => $this->msg( 'page_last' )->escaped()
742 );
743
744 $lang = $this->getLanguage();
745
746 $pagingLinks = $this->getPagingLinks( $linkTexts );
747 $limitLinks = $this->getLimitLinks();
748 $limits = $lang->pipeList( $limitLinks );
749
750 $this->mNavigationBar = $this->msg( 'parentheses' )->rawParams(
751 $lang->pipeList( array( $pagingLinks['first'],
752 $pagingLinks['last'] ) ) )->escaped() . " " .
753 $this->msg( 'viewprevnext' )->rawParams( $pagingLinks['prev'],
754 $pagingLinks['next'], $limits )->escaped();
755
756 if ( !is_array( $this->getIndexField() ) ) {
757 # Early return to avoid undue nesting
758 return $this->mNavigationBar;
759 }
760
761 $extra = '';
762 $first = true;
763 $msgs = $this->getOrderTypeMessages();
764 foreach ( array_keys( $msgs ) as $order ) {
765 if ( $first ) {
766 $first = false;
767 } else {
768 $extra .= $this->msg( 'pipe-separator' )->escaped();
769 }
770
771 if ( $order == $this->mOrderType ) {
772 $extra .= $this->msg( $msgs[$order] )->escaped();
773 } else {
774 $extra .= $this->makeLink(
775 $this->msg( $msgs[$order] )->escaped(),
776 array( 'order' => $order )
777 );
778 }
779 }
780
781 if ( $extra !== '' ) {
782 $extra = ' ' . $this->msg( 'parentheses' )->rawParams( $extra )->escaped();
783 $this->mNavigationBar .= $extra;
784 }
785
786 return $this->mNavigationBar;
787 }
788
789 /**
790 * If this supports multiple order type messages, give the message key for
791 * enabling each one in getNavigationBar. The return type is an associative
792 * array whose keys must exactly match the keys of the array returned
793 * by getIndexField(), and whose values are message keys.
794 *
795 * @return Array
796 */
797 protected function getOrderTypeMessages() {
798 return null;
799 }
800 }
801
802 /**
803 * IndexPager with a formatted navigation bar
804 * @ingroup Pager
805 */
806 abstract class ReverseChronologicalPager extends IndexPager {
807 public $mDefaultDirection = true;
808 public $mYear;
809 public $mMonth;
810
811 function getNavigationBar() {
812 if ( !$this->isNavigationBarShown() ) {
813 return '';
814 }
815
816 if ( isset( $this->mNavigationBar ) ) {
817 return $this->mNavigationBar;
818 }
819
820 $linkTexts = array(
821 'prev' => $this->msg( 'pager-newer-n' )->numParams( $this->mLimit )->escaped(),
822 'next' => $this->msg( 'pager-older-n' )->numParams( $this->mLimit )->escaped(),
823 'first' => $this->msg( 'histlast' )->escaped(),
824 'last' => $this->msg( 'histfirst' )->escaped()
825 );
826
827 $pagingLinks = $this->getPagingLinks( $linkTexts );
828 $limitLinks = $this->getLimitLinks();
829 $limits = $this->getLanguage()->pipeList( $limitLinks );
830 $firstLastLinks = $this->msg( 'parentheses' )->rawParams( "{$pagingLinks['first']}" .
831 $this->msg( 'pipe-separator' )->escaped() .
832 "{$pagingLinks['last']}" )->escaped();
833
834 $this->mNavigationBar = $firstLastLinks . ' ' .
835 $this->msg( 'viewprevnext' )->rawParams(
836 $pagingLinks['prev'], $pagingLinks['next'], $limits )->escaped();
837
838 return $this->mNavigationBar;
839 }
840
841 function getDateCond( $year, $month ) {
842 $year = intval( $year );
843 $month = intval( $month );
844
845 // Basic validity checks
846 $this->mYear = $year > 0 ? $year : false;
847 $this->mMonth = ( $month > 0 && $month < 13 ) ? $month : false;
848
849 // Given an optional year and month, we need to generate a timestamp
850 // to use as "WHERE rev_timestamp <= result"
851 // Examples: year = 2006 equals < 20070101 (+000000)
852 // year=2005, month=1 equals < 20050201
853 // year=2005, month=12 equals < 20060101
854 if ( !$this->mYear && !$this->mMonth ) {
855 return;
856 }
857
858 if ( $this->mYear ) {
859 $year = $this->mYear;
860 } else {
861 // If no year given, assume the current one
862 $year = gmdate( 'Y' );
863 // If this month hasn't happened yet this year, go back to last year's month
864 if ( $this->mMonth > gmdate( 'n' ) ) {
865 $year--;
866 }
867 }
868
869 if ( $this->mMonth ) {
870 $month = $this->mMonth + 1;
871 // For December, we want January 1 of the next year
872 if ( $month > 12 ) {
873 $month = 1;
874 $year++;
875 }
876 } else {
877 // No month implies we want up to the end of the year in question
878 $month = 1;
879 $year++;
880 }
881
882 // Y2K38 bug
883 if ( $year > 2032 ) {
884 $year = 2032;
885 }
886
887 $ymd = (int)sprintf( "%04d%02d01", $year, $month );
888
889 if ( $ymd > 20320101 ) {
890 $ymd = 20320101;
891 }
892
893 $this->mOffset = $this->mDb->timestamp( "${ymd}000000" );
894 }
895 }
896
897 /**
898 * Table-based display with a user-selectable sort order
899 * @ingroup Pager
900 */
901 abstract class TablePager extends IndexPager {
902 var $mSort;
903 var $mCurrentRow;
904
905 public function __construct( IContextSource $context = null ) {
906 if ( $context ) {
907 $this->setContext( $context );
908 }
909
910 $this->mSort = $this->getRequest()->getText( 'sort' );
911 if ( !array_key_exists( $this->mSort, $this->getFieldNames() )
912 || !$this->isFieldSortable( $this->mSort )
913 ) {
914 $this->mSort = $this->getDefaultSort();
915 }
916 if ( $this->getRequest()->getBool( 'asc' ) ) {
917 $this->mDefaultDirection = false;
918 } elseif ( $this->getRequest()->getBool( 'desc' ) ) {
919 $this->mDefaultDirection = true;
920 } /* Else leave it at whatever the class default is */
921
922 parent::__construct();
923 }
924
925 /**
926 * @protected
927 * @return string
928 */
929 function getStartBody() {
930 global $wgStylePath;
931 $sortClass = $this->getSortHeaderClass();
932
933 $s = '';
934 $fields = $this->getFieldNames();
935
936 # Make table header
937 foreach ( $fields as $field => $name ) {
938 if ( strval( $name ) == '' ) {
939 $s .= Html::rawElement( 'th', array(), '&#160;' ) . "\n";
940 } elseif ( $this->isFieldSortable( $field ) ) {
941 $query = array( 'sort' => $field, 'limit' => $this->mLimit );
942 if ( $field == $this->mSort ) {
943 # This is the sorted column
944 # Prepare a link that goes in the other sort order
945 if ( $this->mDefaultDirection ) {
946 # Descending
947 $image = 'Arr_d.png';
948 $query['asc'] = '1';
949 $query['desc'] = '';
950 $alt = $this->msg( 'descending_abbrev' )->escaped();
951 } else {
952 # Ascending
953 $image = 'Arr_u.png';
954 $query['asc'] = '';
955 $query['desc'] = '1';
956 $alt = $this->msg( 'ascending_abbrev' )->escaped();
957 }
958 $image = "$wgStylePath/common/images/$image";
959 $link = $this->makeLink(
960 Html::element( 'img', array( 'width' => 12, 'height' => 12,
961 'alt' => $alt, 'src' => $image ) ) . htmlspecialchars( $name ), $query );
962 $s .= Html::rawElement( 'th', array( 'class' => $sortClass ), $link ) . "\n";
963 } else {
964 $s .= Html::rawElement( 'th', array(),
965 $this->makeLink( htmlspecialchars( $name ), $query ) ) . "\n";
966 }
967 } else {
968 $s .= Html::element( 'th', array(), $name ) . "\n";
969 }
970 }
971
972 $tableClass = $this->getTableClass();
973 $ret = Html::openElement( 'table', array( 'style' => 'border:1px;', 'class' => "mw-datatable $tableClass" ) );
974 $ret .= Html::rawElement( 'thead', array(), Html::rawElement( 'tr', array(), "\n" . $s . "\n" ) );
975 $ret .= Html::openElement( 'tbody' ) . "\n";
976
977 return $ret;
978 }
979
980 /**
981 * @protected
982 * @return string
983 */
984 function getEndBody() {
985 return "</tbody></table>\n";
986 }
987
988 /**
989 * @protected
990 * @return string
991 */
992 function getEmptyBody() {
993 $colspan = count( $this->getFieldNames() );
994 $msgEmpty = $this->msg( 'table_pager_empty' )->text();
995 return Html::rawElement( 'tr', array(),
996 Html::element( 'td', array( 'colspan' => $colspan ), $msgEmpty ) );
997 }
998
999 /**
1000 * @protected
1001 * @param stdClass $row
1002 * @return String HTML
1003 */
1004 function formatRow( $row ) {
1005 $this->mCurrentRow = $row; // In case formatValue etc need to know
1006 $s = Html::openElement( 'tr', $this->getRowAttrs( $row ) ) . "\n";
1007 $fieldNames = $this->getFieldNames();
1008
1009 foreach ( $fieldNames as $field => $name ) {
1010 $value = isset( $row->$field ) ? $row->$field : null;
1011 $formatted = strval( $this->formatValue( $field, $value ) );
1012
1013 if ( $formatted == '' ) {
1014 $formatted = '&#160;';
1015 }
1016
1017 $s .= Html::rawElement( 'td', $this->getCellAttrs( $field, $value ), $formatted ) . "\n";
1018 }
1019
1020 $s .= Html::closeElement( 'tr' ) . "\n";
1021
1022 return $s;
1023 }
1024
1025 /**
1026 * Get a class name to be applied to the given row.
1027 *
1028 * @protected
1029 *
1030 * @param $row Object: the database result row
1031 * @return String
1032 */
1033 function getRowClass( $row ) {
1034 return '';
1035 }
1036
1037 /**
1038 * Get attributes to be applied to the given row.
1039 *
1040 * @protected
1041 *
1042 * @param $row Object: the database result row
1043 * @return Array of attribute => value
1044 */
1045 function getRowAttrs( $row ) {
1046 $class = $this->getRowClass( $row );
1047 if ( $class === '' ) {
1048 // Return an empty array to avoid clutter in HTML like class=""
1049 return array();
1050 } else {
1051 return array( 'class' => $this->getRowClass( $row ) );
1052 }
1053 }
1054
1055 /**
1056 * Get any extra attributes to be applied to the given cell. Don't
1057 * take this as an excuse to hardcode styles; use classes and
1058 * CSS instead. Row context is available in $this->mCurrentRow
1059 *
1060 * @protected
1061 *
1062 * @param string $field The column
1063 * @param string $value The cell contents
1064 * @return Array of attr => value
1065 */
1066 function getCellAttrs( $field, $value ) {
1067 return array( 'class' => 'TablePager_col_' . $field );
1068 }
1069
1070 /**
1071 * @protected
1072 * @return string
1073 */
1074 function getIndexField() {
1075 return $this->mSort;
1076 }
1077
1078 /**
1079 * @protected
1080 * @return string
1081 */
1082 function getTableClass() {
1083 return 'TablePager';
1084 }
1085
1086 /**
1087 * @protected
1088 * @return string
1089 */
1090 function getNavClass() {
1091 return 'TablePager_nav';
1092 }
1093
1094 /**
1095 * @protected
1096 * @return string
1097 */
1098 function getSortHeaderClass() {
1099 return 'TablePager_sort';
1100 }
1101
1102 /**
1103 * A navigation bar with images
1104 * @return String HTML
1105 */
1106 public function getNavigationBar() {
1107 global $wgStylePath;
1108
1109 if ( !$this->isNavigationBarShown() ) {
1110 return '';
1111 }
1112
1113 $path = "$wgStylePath/common/images";
1114 $labels = array(
1115 'first' => 'table_pager_first',
1116 'prev' => 'table_pager_prev',
1117 'next' => 'table_pager_next',
1118 'last' => 'table_pager_last',
1119 );
1120 $images = array(
1121 'first' => 'arrow_first_25.png',
1122 'prev' => 'arrow_left_25.png',
1123 'next' => 'arrow_right_25.png',
1124 'last' => 'arrow_last_25.png',
1125 );
1126 $disabledImages = array(
1127 'first' => 'arrow_disabled_first_25.png',
1128 'prev' => 'arrow_disabled_left_25.png',
1129 'next' => 'arrow_disabled_right_25.png',
1130 'last' => 'arrow_disabled_last_25.png',
1131 );
1132 if ( $this->getLanguage()->isRTL() ) {
1133 $keys = array_keys( $labels );
1134 $images = array_combine( $keys, array_reverse( $images ) );
1135 $disabledImages = array_combine( $keys, array_reverse( $disabledImages ) );
1136 }
1137
1138 $linkTexts = array();
1139 $disabledTexts = array();
1140 foreach ( $labels as $type => $label ) {
1141 $msgLabel = $this->msg( $label )->escaped();
1142 $linkTexts[$type] = Html::element( 'img', array( 'src' => "$path/{$images[$type]}",
1143 'alt' => $msgLabel ) ) . "<br />$msgLabel";
1144 $disabledTexts[$type] = Html::element( 'img', array( 'src' => "$path/{$disabledImages[$type]}",
1145 'alt' => $msgLabel ) ) . "<br />$msgLabel";
1146 }
1147 $links = $this->getPagingLinks( $linkTexts, $disabledTexts );
1148
1149 $s = Html::openElement( 'table', array( 'class' => $this->getNavClass() ) );
1150 $s .= Html::openElement( 'tr' ) . "\n";
1151 $width = 100 / count( $links ) . '%';
1152 foreach ( $labels as $type => $label ) {
1153 $s .= Html::rawElement( 'td', array( 'style' => "width:$width;" ), $links[$type] ) . "\n";
1154 }
1155 $s .= Html::closeElement( 'tr' ) . Html::closeElement( 'table' ) . "\n";
1156 return $s;
1157 }
1158
1159 /**
1160 * Get a "<select>" element which has options for each of the allowed limits
1161 *
1162 * @return String: HTML fragment
1163 */
1164 public function getLimitSelect() {
1165 $select = new XmlSelect( 'limit', false, $this->mLimit );
1166 $select->addOptions( $this->getLimitSelectList() );
1167 return $select->getHTML();
1168 }
1169
1170 /**
1171 * Get a list of items to show in a "<select>" element of limits.
1172 * This can be passed directly to XmlSelect::addOptions().
1173 *
1174 * @since 1.22
1175 * @return array
1176 */
1177 public function getLimitSelectList() {
1178 # Add the current limit from the query string
1179 # to avoid that the limit is lost after clicking Go next time
1180 if ( !in_array( $this->mLimit, $this->mLimitsShown ) ) {
1181 $this->mLimitsShown[] = $this->mLimit;
1182 sort( $this->mLimitsShown );
1183 }
1184 $ret = array();
1185 foreach ( $this->mLimitsShown as $key => $value ) {
1186 # The pair is either $index => $limit, in which case the $value
1187 # will be numeric, or $limit => $text, in which case the $value
1188 # will be a string.
1189 if ( is_int( $value ) ) {
1190 $limit = $value;
1191 $text = $this->getLanguage()->formatNum( $limit );
1192 } else {
1193 $limit = $key;
1194 $text = $value;
1195 }
1196 $ret[$text] = $limit;
1197 }
1198 return $ret;
1199 }
1200
1201 /**
1202 * Get \<input type="hidden"\> elements for use in a method="get" form.
1203 * Resubmits all defined elements of the query string, except for a
1204 * blacklist, passed in the $blacklist parameter.
1205 *
1206 * @param array $blacklist parameters from the request query which should not be resubmitted
1207 * @return String: HTML fragment
1208 */
1209 function getHiddenFields( $blacklist = array() ) {
1210 $blacklist = (array)$blacklist;
1211 $query = $this->getRequest()->getQueryValues();
1212 foreach ( $blacklist as $name ) {
1213 unset( $query[$name] );
1214 }
1215 $s = '';
1216 foreach ( $query as $name => $value ) {
1217 $s .= Html::hidden( $name, $value ) . "\n";
1218 }
1219 return $s;
1220 }
1221
1222 /**
1223 * Get a form containing a limit selection dropdown
1224 *
1225 * @return String: HTML fragment
1226 */
1227 function getLimitForm() {
1228 global $wgScript;
1229
1230 return Html::rawElement(
1231 'form',
1232 array(
1233 'method' => 'get',
1234 'action' => $wgScript
1235 ),
1236 "\n" . $this->getLimitDropdown()
1237 ) . "\n";
1238 }
1239
1240 /**
1241 * Gets a limit selection dropdown
1242 *
1243 * @return string
1244 */
1245 function getLimitDropdown() {
1246 # Make the select with some explanatory text
1247 $msgSubmit = $this->msg( 'table_pager_limit_submit' )->escaped();
1248
1249 return $this->msg( 'table_pager_limit' )
1250 ->rawParams( $this->getLimitSelect() )->escaped() .
1251 "\n<input type=\"submit\" value=\"$msgSubmit\"/>\n" .
1252 $this->getHiddenFields( array( 'limit' ) );
1253 }
1254
1255 /**
1256 * Return true if the named field should be sortable by the UI, false
1257 * otherwise
1258 *
1259 * @param $field String
1260 */
1261 abstract function isFieldSortable( $field );
1262
1263 /**
1264 * Format a table cell. The return value should be HTML, but use an empty
1265 * string not &#160; for empty cells. Do not include the <td> and </td>.
1266 *
1267 * The current result row is available as $this->mCurrentRow, in case you
1268 * need more context.
1269 *
1270 * @protected
1271 *
1272 * @param string $name the database field name
1273 * @param string $value the value retrieved from the database
1274 */
1275 abstract function formatValue( $name, $value );
1276
1277 /**
1278 * The database field name used as a default sort order.
1279 *
1280 * @protected
1281 *
1282 * @return string
1283 */
1284 abstract function getDefaultSort();
1285
1286 /**
1287 * An array mapping database field names to a textual description of the
1288 * field name, for use in the table header. The description should be plain
1289 * text, it will be HTML-escaped later.
1290 *
1291 * @return Array
1292 */
1293 abstract function getFieldNames();
1294 }