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