Merge "Add getPersonalToolsList to SkinTemplate"
[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 $timestamp = MWTimestamp::getInstance();
876 $year = $timestamp->format( 'Y' );
877 // If this month hasn't happened yet this year, go back to last year's month
878 if ( $this->mMonth > $timestamp->format( 'n' ) ) {
879 $year--;
880 }
881 }
882
883 if ( $this->mMonth ) {
884 $month = $this->mMonth + 1;
885 // For December, we want January 1 of the next year
886 if ( $month > 12 ) {
887 $month = 1;
888 $year++;
889 }
890 } else {
891 // No month implies we want up to the end of the year in question
892 $month = 1;
893 $year++;
894 }
895
896 // Y2K38 bug
897 if ( $year > 2032 ) {
898 $year = 2032;
899 }
900
901 $ymd = (int)sprintf( "%04d%02d01", $year, $month );
902
903 if ( $ymd > 20320101 ) {
904 $ymd = 20320101;
905 }
906
907 $this->mOffset = $this->mDb->timestamp( "${ymd}000000" );
908 }
909 }
910
911 /**
912 * Table-based display with a user-selectable sort order
913 * @ingroup Pager
914 */
915 abstract class TablePager extends IndexPager {
916 var $mSort;
917 var $mCurrentRow;
918
919 public function __construct( IContextSource $context = null ) {
920 if ( $context ) {
921 $this->setContext( $context );
922 }
923
924 $this->mSort = $this->getRequest()->getText( 'sort' );
925 if ( !array_key_exists( $this->mSort, $this->getFieldNames() )
926 || !$this->isFieldSortable( $this->mSort )
927 ) {
928 $this->mSort = $this->getDefaultSort();
929 }
930 if ( $this->getRequest()->getBool( 'asc' ) ) {
931 $this->mDefaultDirection = false;
932 } elseif ( $this->getRequest()->getBool( 'desc' ) ) {
933 $this->mDefaultDirection = true;
934 } /* Else leave it at whatever the class default is */
935
936 parent::__construct();
937 }
938
939 /**
940 * @protected
941 * @return string
942 */
943 function getStartBody() {
944 global $wgStylePath;
945 $sortClass = $this->getSortHeaderClass();
946
947 $s = '';
948 $fields = $this->getFieldNames();
949
950 # Make table header
951 foreach ( $fields as $field => $name ) {
952 if ( strval( $name ) == '' ) {
953 $s .= Html::rawElement( 'th', array(), '&#160;' ) . "\n";
954 } elseif ( $this->isFieldSortable( $field ) ) {
955 $query = array( 'sort' => $field, 'limit' => $this->mLimit );
956 if ( $field == $this->mSort ) {
957 # This is the sorted column
958 # Prepare a link that goes in the other sort order
959 if ( $this->mDefaultDirection ) {
960 # Descending
961 $image = 'Arr_d.png';
962 $query['asc'] = '1';
963 $query['desc'] = '';
964 $alt = $this->msg( 'descending_abbrev' )->escaped();
965 } else {
966 # Ascending
967 $image = 'Arr_u.png';
968 $query['asc'] = '';
969 $query['desc'] = '1';
970 $alt = $this->msg( 'ascending_abbrev' )->escaped();
971 }
972 $image = "$wgStylePath/common/images/$image";
973 $link = $this->makeLink(
974 Html::element( 'img', array( 'width' => 12, 'height' => 12,
975 'alt' => $alt, 'src' => $image ) ) . htmlspecialchars( $name ), $query );
976 $s .= Html::rawElement( 'th', array( 'class' => $sortClass ), $link ) . "\n";
977 } else {
978 $s .= Html::rawElement( 'th', array(),
979 $this->makeLink( htmlspecialchars( $name ), $query ) ) . "\n";
980 }
981 } else {
982 $s .= Html::element( 'th', array(), $name ) . "\n";
983 }
984 }
985
986 $tableClass = $this->getTableClass();
987 $ret = Html::openElement( 'table', array( 'style' => 'border:1px;', 'class' => "mw-datatable $tableClass" ) );
988 $ret .= Html::rawElement( 'thead', array(), Html::rawElement( 'tr', array(), "\n" . $s . "\n" ) );
989 $ret .= Html::openElement( 'tbody' ) . "\n";
990
991 return $ret;
992 }
993
994 /**
995 * @protected
996 * @return string
997 */
998 function getEndBody() {
999 return "</tbody></table>\n";
1000 }
1001
1002 /**
1003 * @protected
1004 * @return string
1005 */
1006 function getEmptyBody() {
1007 $colspan = count( $this->getFieldNames() );
1008 $msgEmpty = $this->msg( 'table_pager_empty' )->text();
1009 return Html::rawElement( 'tr', array(),
1010 Html::element( 'td', array( 'colspan' => $colspan ), $msgEmpty ) );
1011 }
1012
1013 /**
1014 * @protected
1015 * @param stdClass $row
1016 * @return String HTML
1017 */
1018 function formatRow( $row ) {
1019 $this->mCurrentRow = $row; // In case formatValue etc need to know
1020 $s = Html::openElement( 'tr', $this->getRowAttrs( $row ) ) . "\n";
1021 $fieldNames = $this->getFieldNames();
1022
1023 foreach ( $fieldNames as $field => $name ) {
1024 $value = isset( $row->$field ) ? $row->$field : null;
1025 $formatted = strval( $this->formatValue( $field, $value ) );
1026
1027 if ( $formatted == '' ) {
1028 $formatted = '&#160;';
1029 }
1030
1031 $s .= Html::rawElement( 'td', $this->getCellAttrs( $field, $value ), $formatted ) . "\n";
1032 }
1033
1034 $s .= Html::closeElement( 'tr' ) . "\n";
1035
1036 return $s;
1037 }
1038
1039 /**
1040 * Get a class name to be applied to the given row.
1041 *
1042 * @protected
1043 *
1044 * @param $row Object: the database result row
1045 * @return String
1046 */
1047 function getRowClass( $row ) {
1048 return '';
1049 }
1050
1051 /**
1052 * Get attributes to be applied to the given row.
1053 *
1054 * @protected
1055 *
1056 * @param $row Object: the database result row
1057 * @return Array of attribute => value
1058 */
1059 function getRowAttrs( $row ) {
1060 $class = $this->getRowClass( $row );
1061 if ( $class === '' ) {
1062 // Return an empty array to avoid clutter in HTML like class=""
1063 return array();
1064 } else {
1065 return array( 'class' => $this->getRowClass( $row ) );
1066 }
1067 }
1068
1069 /**
1070 * Get any extra attributes to be applied to the given cell. Don't
1071 * take this as an excuse to hardcode styles; use classes and
1072 * CSS instead. Row context is available in $this->mCurrentRow
1073 *
1074 * @protected
1075 *
1076 * @param string $field The column
1077 * @param string $value The cell contents
1078 * @return Array of attr => value
1079 */
1080 function getCellAttrs( $field, $value ) {
1081 return array( 'class' => 'TablePager_col_' . $field );
1082 }
1083
1084 /**
1085 * @protected
1086 * @return string
1087 */
1088 function getIndexField() {
1089 return $this->mSort;
1090 }
1091
1092 /**
1093 * @protected
1094 * @return string
1095 */
1096 function getTableClass() {
1097 return 'TablePager';
1098 }
1099
1100 /**
1101 * @protected
1102 * @return string
1103 */
1104 function getNavClass() {
1105 return 'TablePager_nav';
1106 }
1107
1108 /**
1109 * @protected
1110 * @return string
1111 */
1112 function getSortHeaderClass() {
1113 return 'TablePager_sort';
1114 }
1115
1116 /**
1117 * A navigation bar with images
1118 * @return String HTML
1119 */
1120 public function getNavigationBar() {
1121 global $wgStylePath;
1122
1123 if ( !$this->isNavigationBarShown() ) {
1124 return '';
1125 }
1126
1127 $path = "$wgStylePath/common/images";
1128 $labels = array(
1129 'first' => 'table_pager_first',
1130 'prev' => 'table_pager_prev',
1131 'next' => 'table_pager_next',
1132 'last' => 'table_pager_last',
1133 );
1134 $images = array(
1135 'first' => 'arrow_first_25.png',
1136 'prev' => 'arrow_left_25.png',
1137 'next' => 'arrow_right_25.png',
1138 'last' => 'arrow_last_25.png',
1139 );
1140 $disabledImages = array(
1141 'first' => 'arrow_disabled_first_25.png',
1142 'prev' => 'arrow_disabled_left_25.png',
1143 'next' => 'arrow_disabled_right_25.png',
1144 'last' => 'arrow_disabled_last_25.png',
1145 );
1146 if ( $this->getLanguage()->isRTL() ) {
1147 $keys = array_keys( $labels );
1148 $images = array_combine( $keys, array_reverse( $images ) );
1149 $disabledImages = array_combine( $keys, array_reverse( $disabledImages ) );
1150 }
1151
1152 $linkTexts = array();
1153 $disabledTexts = array();
1154 foreach ( $labels as $type => $label ) {
1155 $msgLabel = $this->msg( $label )->escaped();
1156 $linkTexts[$type] = Html::element( 'img', array( 'src' => "$path/{$images[$type]}",
1157 'alt' => $msgLabel ) ) . "<br />$msgLabel";
1158 $disabledTexts[$type] = Html::element( 'img', array( 'src' => "$path/{$disabledImages[$type]}",
1159 'alt' => $msgLabel ) ) . "<br />$msgLabel";
1160 }
1161 $links = $this->getPagingLinks( $linkTexts, $disabledTexts );
1162
1163 $s = Html::openElement( 'table', array( 'class' => $this->getNavClass() ) );
1164 $s .= Html::openElement( 'tr' ) . "\n";
1165 $width = 100 / count( $links ) . '%';
1166 foreach ( $labels as $type => $label ) {
1167 $s .= Html::rawElement( 'td', array( 'style' => "width:$width;" ), $links[$type] ) . "\n";
1168 }
1169 $s .= Html::closeElement( 'tr' ) . Html::closeElement( 'table' ) . "\n";
1170 return $s;
1171 }
1172
1173 /**
1174 * Get a "<select>" element which has options for each of the allowed limits
1175 *
1176 * @param $attribs String: Extra attributes to set
1177 * @return String: HTML fragment
1178 */
1179 public function getLimitSelect( $attribs = array() ) {
1180 $select = new XmlSelect( 'limit', false, $this->mLimit );
1181 $select->addOptions( $this->getLimitSelectList() );
1182 foreach ( $attribs as $name => $value ) {
1183 $select->setAttribute( $name, $value );
1184 }
1185 return $select->getHTML();
1186 }
1187
1188 /**
1189 * Get a list of items to show in a "<select>" element of limits.
1190 * This can be passed directly to XmlSelect::addOptions().
1191 *
1192 * @since 1.22
1193 * @return array
1194 */
1195 public function getLimitSelectList() {
1196 # Add the current limit from the query string
1197 # to avoid that the limit is lost after clicking Go next time
1198 if ( !in_array( $this->mLimit, $this->mLimitsShown ) ) {
1199 $this->mLimitsShown[] = $this->mLimit;
1200 sort( $this->mLimitsShown );
1201 }
1202 $ret = array();
1203 foreach ( $this->mLimitsShown as $key => $value ) {
1204 # The pair is either $index => $limit, in which case the $value
1205 # will be numeric, or $limit => $text, in which case the $value
1206 # will be a string.
1207 if ( is_int( $value ) ) {
1208 $limit = $value;
1209 $text = $this->getLanguage()->formatNum( $limit );
1210 } else {
1211 $limit = $key;
1212 $text = $value;
1213 }
1214 $ret[$text] = $limit;
1215 }
1216 return $ret;
1217 }
1218
1219 /**
1220 * Get \<input type="hidden"\> elements for use in a method="get" form.
1221 * Resubmits all defined elements of the query string, except for a
1222 * blacklist, passed in the $blacklist parameter.
1223 *
1224 * @param array $blacklist parameters from the request query which should not be resubmitted
1225 * @return String: HTML fragment
1226 */
1227 function getHiddenFields( $blacklist = array() ) {
1228 $blacklist = (array)$blacklist;
1229 $query = $this->getRequest()->getQueryValues();
1230 foreach ( $blacklist as $name ) {
1231 unset( $query[$name] );
1232 }
1233 $s = '';
1234 foreach ( $query as $name => $value ) {
1235 $s .= Html::hidden( $name, $value ) . "\n";
1236 }
1237 return $s;
1238 }
1239
1240 /**
1241 * Get a form containing a limit selection dropdown
1242 *
1243 * @return String: HTML fragment
1244 */
1245 function getLimitForm() {
1246 global $wgScript;
1247
1248 return Html::rawElement(
1249 'form',
1250 array(
1251 'method' => 'get',
1252 'action' => $wgScript
1253 ),
1254 "\n" . $this->getLimitDropdown()
1255 ) . "\n";
1256 }
1257
1258 /**
1259 * Gets a limit selection dropdown
1260 *
1261 * @return string
1262 */
1263 function getLimitDropdown() {
1264 # Make the select with some explanatory text
1265 $msgSubmit = $this->msg( 'table_pager_limit_submit' )->escaped();
1266
1267 return $this->msg( 'table_pager_limit' )
1268 ->rawParams( $this->getLimitSelect() )->escaped() .
1269 "\n<input type=\"submit\" value=\"$msgSubmit\"/>\n" .
1270 $this->getHiddenFields( array( 'limit' ) );
1271 }
1272
1273 /**
1274 * Return true if the named field should be sortable by the UI, false
1275 * otherwise
1276 *
1277 * @param $field String
1278 */
1279 abstract function isFieldSortable( $field );
1280
1281 /**
1282 * Format a table cell. The return value should be HTML, but use an empty
1283 * string not &#160; for empty cells. Do not include the <td> and </td>.
1284 *
1285 * The current result row is available as $this->mCurrentRow, in case you
1286 * need more context.
1287 *
1288 * @protected
1289 *
1290 * @param string $name the database field name
1291 * @param string $value the value retrieved from the database
1292 */
1293 abstract function formatValue( $name, $value );
1294
1295 /**
1296 * The database field name used as a default sort order.
1297 *
1298 * @protected
1299 *
1300 * @return string
1301 */
1302 abstract function getDefaultSort();
1303
1304 /**
1305 * An array mapping database field names to a textual description of the
1306 * field name, for use in the table header. The description should be plain
1307 * text, it will be HTML-escaped later.
1308 *
1309 * @return Array
1310 */
1311 abstract function getFieldNames();
1312 }