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