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