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