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