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