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