Fixed spacing and removed unneeded parenthesis
[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 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;
219 }
220
221 $this->mResult = $this->reallyDoQuery(
222 $this->mOffset,
223 $queryLimit,
224 $descending
225 );
226
227 $this->extractResultInfo( $isFirst, $queryLimit, $this->mResult );
228 $this->mQueryDone = true;
229
230 $this->preprocessResults( $this->mResult );
231 $this->mResult->rewind(); // Paranoia
232
233 wfProfileOut( $fname );
234 }
235
236 /**
237 * @return ResultWrapper The result wrapper.
238 */
239 function getResult() {
240 return $this->mResult;
241 }
242
243 /**
244 * Set the offset from an other source than the request
245 *
246 * @param $offset Int|String
247 */
248 function setOffset( $offset ) {
249 $this->mOffset = $offset;
250 }
251 /**
252 * Set the limit from an other source than the request
253 *
254 * Verifies limit is between 1 and 5000
255 *
256 * @param $limit Int|String
257 */
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;
263 }
264 if ( $limit > 0 ) {
265 $this->mLimit = $limit;
266 }
267 }
268
269 /**
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.
273 *
274 * @param $include bool
275 */
276 public function setIncludeOffset( $include ) {
277 $this->mIncludeOffset = $include;
278 }
279
280 /**
281 * Extract some useful data from the result object for use by
282 * the navigation bar, put it into $this
283 *
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
288 */
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 );
295
296 $row = $res->fetchRow();
297 $firstIndex = $row[$indexColumn];
298
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];
317 }
318 } else {
319 $firstIndex = '';
320 $lastIndex = '';
321 $this->mPastTheEndRow = null;
322 $this->mPastTheEndIndex = '';
323 }
324
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;
335 }
336 }
337
338 /**
339 * Get some text to go in brackets in the "function name" part of the SQL comment
340 *
341 * @return String
342 */
343 function getSqlComment() {
344 return get_class( $this );
345 }
346
347 /**
348 * Do a query with specified parameters, rather than using the object
349 * context
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 ResultWrapper
355 */
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 );
359 }
360
361 /**
362 * Build variables to use by the database wrapper.
363 *
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
368 */
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';
385 }
386 $options['ORDER BY'] = $orderBy;
387 $operator = $this->mIncludeOffset ? '<=' : '<';
388 }
389 if ( $offset != '' ) {
390 $conds[] = $this->mIndexField . $operator . $this->mDb->addQuotes( $offset );
391 }
392 $options['LIMIT'] = intval( $limit );
393 return array( $tables, $fields, $conds, $fname, $options, $join_conds );
394 }
395
396 /**
397 * Pre-process results; useful for performing batch existence checks, etc.
398 *
399 * @param $result ResultWrapper
400 */
401 protected function preprocessResults( $result ) {}
402
403 /**
404 * Get the formatted result list. Calls getStartBody(), formatRow() and
405 * getEndBody(), concatenates the results and returns them.
406 *
407 * @return String
408 */
409 public function getBody() {
410 if ( !$this->mQueryDone ) {
411 $this->doQuery();
412 }
413
414 if ( $this->mResult->numRows() ) {
415 # Do any special query batches before display
416 $this->doBatchLookups();
417 }
418
419 # Don't use any extra rows returned by the query
420 $numRows = min( $this->mResult->numRows(), $this->mLimit );
421
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 );
429 }
430 } else {
431 $this->mResult->seek( 0 );
432 for ( $i = 0; $i < $numRows; $i++ ) {
433 $row = $this->mResult->fetchObject();
434 $s .= $this->formatRow( $row );
435 }
436 }
437 } else {
438 $s .= $this->getEmptyBody();
439 }
440 $s .= $this->getEndBody();
441 return $s;
442 }
443
444 /**
445 * Make a self-link
446 *
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
450 *
451 * @return String: HTML fragment
452 */
453 function makeLink( $text, array $query = null, $type = null ) {
454 if ( $query === null ) {
455 return $text;
456 }
457
458 $attrs = array();
459 if ( in_array( $type, array( 'first', 'prev', 'next', 'last' ) ) ) {
460 # HTML5 rel attributes
461 $attrs['rel'] = $type;
462 }
463
464 if ( $type ) {
465 $attrs['class'] = "mw-{$type}link";
466 }
467
468 return Linker::linkKnown(
469 $this->getTitle(),
470 $text,
471 $attrs,
472 $query + $this->getDefaultQuery()
473 );
474 }
475
476 /**
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.
480 *
481 * @return void
482 */
483 protected function doBatchLookups() {}
484
485 /**
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.
488 *
489 * @return String
490 */
491 protected function getStartBody() {
492 return '';
493 }
494
495 /**
496 * Hook into getBody() for the end of the list
497 *
498 * @return String
499 */
500 protected function getEndBody() {
501 return '';
502 }
503
504 /**
505 * Hook into getBody(), for the bit between the start and the
506 * end when there are no rows
507 *
508 * @return String
509 */
510 protected function getEmptyBody() {
511 return '';
512 }
513
514 /**
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.
518 *
519 * @return array Associative array
520 */
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'] );
531 }
532 return $this->mDefaultQuery;
533 }
534
535 /**
536 * Get the number of rows in the result set
537 *
538 * @return Integer
539 */
540 function getNumRows() {
541 if ( !$this->mQueryDone ) {
542 $this->doQuery();
543 }
544 return $this->mResult->numRows();
545 }
546
547 /**
548 * Get a URL query array for the prev, next, first and last links.
549 *
550 * @return Array
551 */
552 function getPagingQueries() {
553 if ( !$this->mQueryDone ) {
554 $this->doQuery();
555 }
556
557 # Don't announce the limit everywhere if it's the default
558 $urlLimit = $this->mLimit == $this->mDefaultLimit ? null : $this->mLimit;
559
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
568 );
569 $first = array( 'limit' => $urlLimit );
570 }
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 );
577 }
578 return array(
579 'prev' => $prev,
580 'next' => $next,
581 'first' => $first,
582 'last' => $last
583 );
584 }
585
586 /**
587 * Returns whether to show the "navigation bar"
588 *
589 * @return Boolean
590 */
591 function isNavigationBarShown() {
592 if ( !$this->mQueryDone ) {
593 $this->doQuery();
594 }
595 // Hide navigation by default if there is nothing to page
596 return !( $this->mIsFirst && $this->mIsLast );
597 }
598
599 /**
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.
604 *
605 * @param $linkTexts Array
606 * @param $disabledTexts Array
607 * @return Array
608 */
609 function getPagingLinks( $linkTexts, $disabledTexts = array() ) {
610 $queries = $this->getPagingQueries();
611 $links = array();
612
613 foreach ( $queries as $type => $query ) {
614 if ( $query !== false ) {
615 $links[$type] = $this->makeLink(
616 $linkTexts[$type],
617 $queries[$type],
618 $type
619 );
620 } elseif ( isset( $disabledTexts[$type] ) ) {
621 $links[$type] = $disabledTexts[$type];
622 } else {
623 $links[$type] = $linkTexts[$type];
624 }
625 }
626
627 return $links;
628 }
629
630 function getLimitLinks() {
631 $links = array();
632 if ( $this->mIsBackwards ) {
633 $offset = $this->mPastTheEndIndex;
634 } else {
635 $offset = $this->mOffset;
636 }
637 foreach ( $this->mLimitsShown as $limit ) {
638 $links[] = $this->makeLink(
639 $this->getLanguage()->formatNum( $limit ),
640 array( 'offset' => $offset, 'limit' => $limit ),
641 'num'
642 );
643 }
644 return $links;
645 }
646
647 /**
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()
651 *
652 * @param $row Object: database row
653 * @return String
654 */
655 abstract function formatRow( $row );
656
657 /**
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
666 *
667 * @return Array
668 */
669 abstract function getQueryInfo();
670
671 /**
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.
677 *
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.
680 *
681 * @return string|Array
682 */
683 abstract function getIndexField();
684
685 /**
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.
689 *
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.
693 *
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.
698 *
699 * @return Array
700 */
701 protected function getExtraSortFields() {
702 return array();
703 }
704
705 /**
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.
711 *
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.
716 *
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.
721 *
722 * @return Boolean
723 */
724 protected function getDefaultDirections() {
725 return false;
726 }
727 }
728
729 /**
730 * IndexPager with an alphabetic list and a formatted navigation bar
731 * @ingroup Pager
732 */
733 abstract class AlphabeticPager extends IndexPager {
734
735 /**
736 * Shamelessly stolen bits from ReverseChronologicalPager,
737 * didn't want to do class magic as may be still revamped
738 *
739 * @return String HTML
740 */
741 function getNavigationBar() {
742 if ( !$this->isNavigationBarShown() ) {
743 return '';
744 }
745
746 if ( isset( $this->mNavigationBar ) ) {
747 return $this->mNavigationBar;
748 }
749
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()
755 );
756
757 $lang = $this->getLanguage();
758
759 $pagingLinks = $this->getPagingLinks( $linkTexts );
760 $limitLinks = $this->getLimitLinks();
761 $limits = $lang->pipeList( $limitLinks );
762
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();
768
769 if ( !is_array( $this->getIndexField() ) ) {
770 # Early return to avoid undue nesting
771 return $this->mNavigationBar;
772 }
773
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();
782 }
783
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 )
790 );
791 }
792 }
793
794 if ( $extra !== '' ) {
795 $extra = ' ' . $this->msg( 'parentheses' )->rawParams( $extra )->escaped();
796 $this->mNavigationBar .= $extra;
797 }
798
799 return $this->mNavigationBar;
800 }
801
802 /**
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.
807 *
808 * @return Array
809 */
810 protected function getOrderTypeMessages() {
811 return null;
812 }
813 }
814
815 /**
816 * IndexPager with a formatted navigation bar
817 * @ingroup Pager
818 */
819 abstract class ReverseChronologicalPager extends IndexPager {
820 public $mDefaultDirection = true;
821 public $mYear;
822 public $mMonth;
823
824 function getNavigationBar() {
825 if ( !$this->isNavigationBarShown() ) {
826 return '';
827 }
828
829 if ( isset( $this->mNavigationBar ) ) {
830 return $this->mNavigationBar;
831 }
832
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()
838 );
839
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();
846
847 $this->mNavigationBar = $firstLastLinks . ' ' .
848 $this->msg( 'viewprevnext' )->rawParams(
849 $pagingLinks['prev'], $pagingLinks['next'], $limits )->escaped();
850
851 return $this->mNavigationBar;
852 }
853
854 function getDateCond( $year, $month ) {
855 $year = intval( $year );
856 $month = intval( $month );
857
858 // Basic validity checks
859 $this->mYear = $year > 0 ? $year : false;
860 $this->mMonth = ( $month > 0 && $month < 13 ) ? $month : false;
861
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;
869 }
870
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--;
879 }
880 }
881
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++;
888 }
889 } else {
890 // No month implies we want up to the end of the year in question
891 $month = 1;
892 $year++;
893 }
894
895 // Y2K38 bug
896 if ( $year > 2032 ) {
897 $year = 2032;
898 }
899
900 $ymd = (int)sprintf( "%04d%02d01", $year, $month );
901
902 if ( $ymd > 20320101 ) {
903 $ymd = 20320101;
904 }
905
906 $this->mOffset = $this->mDb->timestamp( "${ymd}000000" );
907 }
908 }
909
910 /**
911 * Table-based display with a user-selectable sort order
912 * @ingroup Pager
913 */
914 abstract class TablePager extends IndexPager {
915 var $mSort;
916 var $mCurrentRow;
917
918 public function __construct( IContextSource $context = null ) {
919 if ( $context ) {
920 $this->setContext( $context );
921 }
922
923 $this->mSort = $this->getRequest()->getText( 'sort' );
924 if ( !array_key_exists( $this->mSort, $this->getFieldNames() )
925 || !$this->isFieldSortable( $this->mSort )
926 ) {
927 $this->mSort = $this->getDefaultSort();
928 }
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 */
934
935 parent::__construct();
936 }
937
938 /**
939 * @protected
940 * @return string
941 */
942 function getStartBody() {
943 global $wgStylePath;
944 $sortClass = $this->getSortHeaderClass();
945
946 $s = '';
947 $fields = $this->getFieldNames();
948
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();
970 }
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";
979 }
980 } else {
981 $s .= Html::element( 'th', array(), $name ) . "\n";
982 }
983 }
984
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";
989
990 return $ret;
991 }
992
993 /**
994 * @protected
995 * @return string
996 */
997 function getEndBody() {
998 return "</tbody></table>\n";
999 }
1000
1001 /**
1002 * @protected
1003 * @return string
1004 */
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 ) );
1010 }
1011
1012 /**
1013 * @protected
1014 * @param stdClass $row
1015 * @return String HTML
1016 */
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();
1021
1022 foreach ( $fieldNames as $field => $name ) {
1023 $value = isset( $row->$field ) ? $row->$field : null;
1024 $formatted = strval( $this->formatValue( $field, $value ) );
1025
1026 if ( $formatted == '' ) {
1027 $formatted = '&#160;';
1028 }
1029
1030 $s .= Html::rawElement( 'td', $this->getCellAttrs( $field, $value ), $formatted ) . "\n";
1031 }
1032
1033 $s .= Html::closeElement( 'tr' ) . "\n";
1034
1035 return $s;
1036 }
1037
1038 /**
1039 * Get a class name to be applied to the given row.
1040 *
1041 * @protected
1042 *
1043 * @param $row Object: the database result row
1044 * @return String
1045 */
1046 function getRowClass( $row ) {
1047 return '';
1048 }
1049
1050 /**
1051 * Get attributes to be applied to the given row.
1052 *
1053 * @protected
1054 *
1055 * @param $row Object: the database result row
1056 * @return Array of attribute => value
1057 */
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 ) );
1065 }
1066 }
1067
1068 /**
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
1072 *
1073 * @protected
1074 *
1075 * @param string $field The column
1076 * @param string $value The cell contents
1077 * @return Array of attr => value
1078 */
1079 function getCellAttrs( $field, $value ) {
1080 return array( 'class' => 'TablePager_col_' . $field );
1081 }
1082
1083 /**
1084 * @protected
1085 * @return string
1086 */
1087 function getIndexField() {
1088 return $this->mSort;
1089 }
1090
1091 /**
1092 * @protected
1093 * @return string
1094 */
1095 function getTableClass() {
1096 return 'TablePager';
1097 }
1098
1099 /**
1100 * @protected
1101 * @return string
1102 */
1103 function getNavClass() {
1104 return 'TablePager_nav';
1105 }
1106
1107 /**
1108 * @protected
1109 * @return string
1110 */
1111 function getSortHeaderClass() {
1112 return 'TablePager_sort';
1113 }
1114
1115 /**
1116 * A navigation bar with images
1117 * @return String HTML
1118 */
1119 public function getNavigationBar() {
1120 global $wgStylePath;
1121
1122 if ( !$this->isNavigationBarShown() ) {
1123 return '';
1124 }
1125
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',
1132 );
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',
1138 );
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',
1144 );
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 ) );
1149 }
1150
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";
1159 }
1160 $links = $this->getPagingLinks( $linkTexts, $disabledTexts );
1161
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";
1167 }
1168 $s .= Html::closeElement( 'tr' ) . Html::closeElement( 'table' ) . "\n";
1169 return $s;
1170 }
1171
1172 /**
1173 * Get a "<select>" element which has options for each of the allowed limits
1174 *
1175 * @return String: HTML fragment
1176 */
1177 public function getLimitSelect() {
1178 $select = new XmlSelect( 'limit', false, $this->mLimit );
1179 $select->addOptions( $this->getLimitSelectList() );
1180 return $select->getHTML();
1181 }
1182
1183 /**
1184 * Get a list of items to show in a "<select>" element of limits.
1185 * This can be passed directly to XmlSelect::addOptions().
1186 *
1187 * @since 1.22
1188 * @return array
1189 */
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 );
1196 }
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;
1208 }
1209 $ret[$text] = $limit;
1210 }
1211 return $ret;
1212 }
1213
1214 /**
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.
1218 *
1219 * @param array $blacklist parameters from the request query which should not be resubmitted
1220 * @return String: HTML fragment
1221 */
1222 function getHiddenFields( $blacklist = array() ) {
1223 $blacklist = (array)$blacklist;
1224 $query = $this->getRequest()->getQueryValues();
1225 foreach ( $blacklist as $name ) {
1226 unset( $query[$name] );
1227 }
1228 $s = '';
1229 foreach ( $query as $name => $value ) {
1230 $s .= Html::hidden( $name, $value ) . "\n";
1231 }
1232 return $s;
1233 }
1234
1235 /**
1236 * Get a form containing a limit selection dropdown
1237 *
1238 * @return String: HTML fragment
1239 */
1240 function getLimitForm() {
1241 global $wgScript;
1242
1243 return Html::rawElement(
1244 'form',
1245 array(
1246 'method' => 'get',
1247 'action' => $wgScript
1248 ),
1249 "\n" . $this->getLimitDropdown()
1250 ) . "\n";
1251 }
1252
1253 /**
1254 * Gets a limit selection dropdown
1255 *
1256 * @return string
1257 */
1258 function getLimitDropdown() {
1259 # Make the select with some explanatory text
1260 $msgSubmit = $this->msg( 'table_pager_limit_submit' )->escaped();
1261
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' ) );
1266 }
1267
1268 /**
1269 * Return true if the named field should be sortable by the UI, false
1270 * otherwise
1271 *
1272 * @param $field String
1273 */
1274 abstract function isFieldSortable( $field );
1275
1276 /**
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>.
1279 *
1280 * The current result row is available as $this->mCurrentRow, in case you
1281 * need more context.
1282 *
1283 * @protected
1284 *
1285 * @param string $name the database field name
1286 * @param string $value the value retrieved from the database
1287 */
1288 abstract function formatValue( $name, $value );
1289
1290 /**
1291 * The database field name used as a default sort order.
1292 *
1293 * @protected
1294 *
1295 * @return string
1296 */
1297 abstract function getDefaultSort();
1298
1299 /**
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.
1303 *
1304 * @return Array
1305 */
1306 abstract function getFieldNames();
1307 }