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