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