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