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