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