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