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