Use local context to get messages
[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'] = $sortColumns;
317 $operator = '>';
318 } else {
319 $orderBy = array();
320 foreach ( $sortColumns as $col ) {
321 $orderBy[] = $col . ' DESC';
322 }
323 $options['ORDER BY'] = $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 $linkTexts = array(
686 'prev' => $this->msg( 'prevn' )->numParams( $this->mLimit )->escaped(),
687 'next' => $this->msg( 'nextn' )->numParams( $this->mLimit )->escaped(),
688 'first' => $this->msg( 'page_first' )->escaped(),
689 'last' => $this->msg( 'page_last' )->escaped()
690 );
691
692 $lang = $this->getLanguage();
693
694 $pagingLinks = $this->getPagingLinks( $linkTexts );
695 $limitLinks = $this->getLimitLinks();
696 $limits = $lang->pipeList( $limitLinks );
697
698 $this->mNavigationBar = $this->msg( 'parentheses' )->rawParams(
699 $lang->pipeList( array( $pagingLinks['first'],
700 $pagingLinks['last'] ) ) )->escaped() . " " .
701 $this->msg( 'viewprevnext' )->rawParams( $pagingLinks['prev'],
702 $pagingLinks['next'], $limits )->escaped();
703
704 if( !is_array( $this->getIndexField() ) ) {
705 # Early return to avoid undue nesting
706 return $this->mNavigationBar;
707 }
708
709 $extra = '';
710 $first = true;
711 $msgs = $this->getOrderTypeMessages();
712 foreach( array_keys( $msgs ) as $order ) {
713 if( $first ) {
714 $first = false;
715 } else {
716 $extra .= $this->msg( 'pipe-separator' )->escaped();
717 }
718
719 if( $order == $this->mOrderType ) {
720 $extra .= $this->msg( $msgs[$order] )->escaped();
721 } else {
722 $extra .= $this->makeLink(
723 $this->msg( $msgs[$order] )->escaped(),
724 array( 'order' => $order )
725 );
726 }
727 }
728
729 if( $extra !== '' ) {
730 $extra = ' ' . $this->msg( 'parentheses' )->rawParams( $extra )->escaped();
731 $this->mNavigationBar .= $extra;
732 }
733
734 return $this->mNavigationBar;
735 }
736
737 /**
738 * If this supports multiple order type messages, give the message key for
739 * enabling each one in getNavigationBar. The return type is an associa-
740 * tive array whose keys must exactly match the keys of the array returned
741 * by getIndexField(), and whose values are message keys.
742 *
743 * @return Array
744 */
745 protected function getOrderTypeMessages() {
746 return null;
747 }
748 }
749
750 /**
751 * IndexPager with a formatted navigation bar
752 * @ingroup Pager
753 */
754 abstract class ReverseChronologicalPager extends IndexPager {
755 public $mDefaultDirection = true;
756 public $mYear;
757 public $mMonth;
758
759 function getNavigationBar() {
760 if ( !$this->isNavigationBarShown() ) {
761 return '';
762 }
763
764 if ( isset( $this->mNavigationBar ) ) {
765 return $this->mNavigationBar;
766 }
767
768 $linkTexts = array(
769 'prev' => $this->msg( 'pager-newer-n' )->numParams( $this->mLimit )->escaped(),
770 'next' => $this->msg( 'pager-older-n' )->numParams( $this->mLimit )->escaped(),
771 'first' => $this->msg( 'histlast' )->escaped(),
772 'last' => $this->msg( 'histfirst' )->escaped()
773 );
774
775 $pagingLinks = $this->getPagingLinks( $linkTexts );
776 $limitLinks = $this->getLimitLinks();
777 $limits = $this->getLanguage()->pipeList( $limitLinks );
778 $firstLastLinks = $this->msg( 'parentheses' )->rawParams( "{$pagingLinks['first']}" .
779 $this->msg( 'pipe-separator' )->escaped() .
780 "{$pagingLinks['last']}" )->escaped();
781
782 $this->mNavigationBar = $firstLastLinks . ' ' .
783 $this->msg( 'viewprevnext' )->rawParams(
784 $pagingLinks['prev'], $pagingLinks['next'], $limits )->escaped();
785
786 return $this->mNavigationBar;
787 }
788
789 function getDateCond( $year, $month ) {
790 $year = intval( $year );
791 $month = intval( $month );
792
793 // Basic validity checks
794 $this->mYear = $year > 0 ? $year : false;
795 $this->mMonth = ( $month > 0 && $month < 13 ) ? $month : false;
796
797 // Given an optional year and month, we need to generate a timestamp
798 // to use as "WHERE rev_timestamp <= result"
799 // Examples: year = 2006 equals < 20070101 (+000000)
800 // year=2005, month=1 equals < 20050201
801 // year=2005, month=12 equals < 20060101
802 if ( !$this->mYear && !$this->mMonth ) {
803 return;
804 }
805
806 if ( $this->mYear ) {
807 $year = $this->mYear;
808 } else {
809 // If no year given, assume the current one
810 $year = gmdate( 'Y' );
811 // If this month hasn't happened yet this year, go back to last year's month
812 if( $this->mMonth > gmdate( 'n' ) ) {
813 $year--;
814 }
815 }
816
817 if ( $this->mMonth ) {
818 $month = $this->mMonth + 1;
819 // For December, we want January 1 of the next year
820 if ($month > 12) {
821 $month = 1;
822 $year++;
823 }
824 } else {
825 // No month implies we want up to the end of the year in question
826 $month = 1;
827 $year++;
828 }
829
830 // Y2K38 bug
831 if ( $year > 2032 ) {
832 $year = 2032;
833 }
834
835 $ymd = (int)sprintf( "%04d%02d01", $year, $month );
836
837 if ( $ymd > 20320101 ) {
838 $ymd = 20320101;
839 }
840
841 $this->mOffset = $this->mDb->timestamp( "${ymd}000000" );
842 }
843 }
844
845 /**
846 * Table-based display with a user-selectable sort order
847 * @ingroup Pager
848 */
849 abstract class TablePager extends IndexPager {
850 var $mSort;
851 var $mCurrentRow;
852
853 public function __construct( IContextSource $context = null ) {
854 if ( $context ) {
855 $this->setContext( $context );
856 }
857
858 $this->mSort = $this->getRequest()->getText( 'sort' );
859 if ( !array_key_exists( $this->mSort, $this->getFieldNames() ) ) {
860 $this->mSort = $this->getDefaultSort();
861 }
862 if ( $this->getRequest()->getBool( 'asc' ) ) {
863 $this->mDefaultDirection = false;
864 } elseif ( $this->getRequest()->getBool( 'desc' ) ) {
865 $this->mDefaultDirection = true;
866 } /* Else leave it at whatever the class default is */
867
868 parent::__construct();
869 }
870
871 /**
872 * @protected
873 * @return string
874 */
875 function getStartBody() {
876 global $wgStylePath;
877 $tableClass = htmlspecialchars( $this->getTableClass() );
878 $sortClass = htmlspecialchars( $this->getSortHeaderClass() );
879
880 $s = "<table style='border:1;' class=\"mw-datatable $tableClass\"><thead><tr>\n";
881 $fields = $this->getFieldNames();
882
883 # Make table header
884 foreach ( $fields as $field => $name ) {
885 if ( strval( $name ) == '' ) {
886 $s .= "<th>&#160;</th>\n";
887 } elseif ( $this->isFieldSortable( $field ) ) {
888 $query = array( 'sort' => $field, 'limit' => $this->mLimit );
889 if ( $field == $this->mSort ) {
890 # This is the sorted column
891 # Prepare a link that goes in the other sort order
892 if ( $this->mDefaultDirection ) {
893 # Descending
894 $image = 'Arr_d.png';
895 $query['asc'] = '1';
896 $query['desc'] = '';
897 $alt = $this->msg( 'descending_abbrev' )->escaped();
898 } else {
899 # Ascending
900 $image = 'Arr_u.png';
901 $query['asc'] = '';
902 $query['desc'] = '1';
903 $alt = $this->msg( 'ascending_abbrev' )->escaped();
904 }
905 $image = htmlspecialchars( "$wgStylePath/common/images/$image" );
906 $link = $this->makeLink(
907 "<img width=\"12\" height=\"12\" alt=\"$alt\" src=\"$image\" />" .
908 htmlspecialchars( $name ), $query );
909 $s .= "<th class=\"$sortClass\">$link</th>\n";
910 } else {
911 $s .= '<th>' . $this->makeLink( htmlspecialchars( $name ), $query ) . "</th>\n";
912 }
913 } else {
914 $s .= '<th>' . htmlspecialchars( $name ) . "</th>\n";
915 }
916 }
917 $s .= "</tr></thead><tbody>\n";
918 return $s;
919 }
920
921 /**
922 * @protected
923 * @return string
924 */
925 function getEndBody() {
926 return "</tbody></table>\n";
927 }
928
929 /**
930 * @protected
931 * @return string
932 */
933 function getEmptyBody() {
934 $colspan = count( $this->getFieldNames() );
935 $msgEmpty = $this->msg( 'table_pager_empty' )->escaped();
936 return "<tr><td colspan=\"$colspan\">$msgEmpty</td></tr>\n";
937 }
938
939 /**
940 * @protected
941 * @param stdClass $row
942 * @return String HTML
943 */
944 function formatRow( $row ) {
945 $this->mCurrentRow = $row; // In case formatValue etc need to know
946 $s = Xml::openElement( 'tr', $this->getRowAttrs( $row ) );
947 $fieldNames = $this->getFieldNames();
948
949 foreach ( $fieldNames as $field => $name ) {
950 $value = isset( $row->$field ) ? $row->$field : null;
951 $formatted = strval( $this->formatValue( $field, $value ) );
952
953 if ( $formatted == '' ) {
954 $formatted = '&#160;';
955 }
956
957 $s .= Xml::tags( 'td', $this->getCellAttrs( $field, $value ), $formatted );
958 }
959
960 $s .= "</tr>\n";
961
962 return $s;
963 }
964
965 /**
966 * Get a class name to be applied to the given row.
967 *
968 * @protected
969 *
970 * @param $row Object: the database result row
971 * @return String
972 */
973 function getRowClass( $row ) {
974 return '';
975 }
976
977 /**
978 * Get attributes to be applied to the given row.
979 *
980 * @protected
981 *
982 * @param $row Object: the database result row
983 * @return Array of <attr> => <value>
984 */
985 function getRowAttrs( $row ) {
986 $class = $this->getRowClass( $row );
987 if ( $class === '' ) {
988 // Return an empty array to avoid clutter in HTML like class=""
989 return array();
990 } else {
991 return array( 'class' => $this->getRowClass( $row ) );
992 }
993 }
994
995 /**
996 * Get any extra attributes to be applied to the given cell. Don't
997 * take this as an excuse to hardcode styles; use classes and
998 * CSS instead. Row context is available in $this->mCurrentRow
999 *
1000 * @protected
1001 *
1002 * @param $field String The column
1003 * @param $value String The cell contents
1004 * @return Array of attr => value
1005 */
1006 function getCellAttrs( $field, $value ) {
1007 return array( 'class' => 'TablePager_col_' . $field );
1008 }
1009
1010 /**
1011 * @protected
1012 * @return string
1013 */
1014 function getIndexField() {
1015 return $this->mSort;
1016 }
1017
1018 /**
1019 * @protected
1020 * @return string
1021 */
1022 function getTableClass() {
1023 return 'TablePager';
1024 }
1025
1026 /**
1027 * @protected
1028 * @return string
1029 */
1030 function getNavClass() {
1031 return 'TablePager_nav';
1032 }
1033
1034 /**
1035 * @protected
1036 * @return string
1037 */
1038 function getSortHeaderClass() {
1039 return 'TablePager_sort';
1040 }
1041
1042 /**
1043 * A navigation bar with images
1044 * @return String HTML
1045 */
1046 public function getNavigationBar() {
1047 global $wgStylePath;
1048
1049 if ( !$this->isNavigationBarShown() ) {
1050 return '';
1051 }
1052
1053 $path = "$wgStylePath/common/images";
1054 $labels = array(
1055 'first' => 'table_pager_first',
1056 'prev' => 'table_pager_prev',
1057 'next' => 'table_pager_next',
1058 'last' => 'table_pager_last',
1059 );
1060 $images = array(
1061 'first' => 'arrow_first_25.png',
1062 'prev' => 'arrow_left_25.png',
1063 'next' => 'arrow_right_25.png',
1064 'last' => 'arrow_last_25.png',
1065 );
1066 $disabledImages = array(
1067 'first' => 'arrow_disabled_first_25.png',
1068 'prev' => 'arrow_disabled_left_25.png',
1069 'next' => 'arrow_disabled_right_25.png',
1070 'last' => 'arrow_disabled_last_25.png',
1071 );
1072 if( $this->getLanguage()->isRTL() ) {
1073 $keys = array_keys( $labels );
1074 $images = array_combine( $keys, array_reverse( $images ) );
1075 $disabledImages = array_combine( $keys, array_reverse( $disabledImages ) );
1076 }
1077
1078 $linkTexts = array();
1079 $disabledTexts = array();
1080 foreach ( $labels as $type => $label ) {
1081 $msgLabel = $this->msg( $label )->escaped();
1082 $linkTexts[$type] = "<img src=\"$path/{$images[$type]}\" alt=\"$msgLabel\"/><br />$msgLabel";
1083 $disabledTexts[$type] = "<img src=\"$path/{$disabledImages[$type]}\" alt=\"$msgLabel\"/><br />$msgLabel";
1084 }
1085 $links = $this->getPagingLinks( $linkTexts, $disabledTexts );
1086
1087 $navClass = htmlspecialchars( $this->getNavClass() );
1088 $s = "<table class=\"$navClass\"><tr>\n";
1089 $width = 100 / count( $links ) . '%';
1090 foreach ( $labels as $type => $label ) {
1091 $s .= "<td style='width:$width;'>{$links[$type]}</td>\n";
1092 }
1093 $s .= "</tr></table>\n";
1094 return $s;
1095 }
1096
1097 /**
1098 * Get a <select> element which has options for each of the allowed limits
1099 *
1100 * @return String: HTML fragment
1101 */
1102 public function getLimitSelect() {
1103 # Add the current limit from the query string
1104 # to avoid that the limit is lost after clicking Go next time
1105 if ( !in_array( $this->mLimit, $this->mLimitsShown ) ) {
1106 $this->mLimitsShown[] = $this->mLimit;
1107 sort( $this->mLimitsShown );
1108 }
1109 $s = Html::openElement( 'select', array( 'name' => 'limit' ) ) . "\n";
1110 foreach ( $this->mLimitsShown as $key => $value ) {
1111 # The pair is either $index => $limit, in which case the $value
1112 # will be numeric, or $limit => $text, in which case the $value
1113 # will be a string.
1114 if( is_int( $value ) ){
1115 $limit = $value;
1116 $text = $this->getLanguage()->formatNum( $limit );
1117 } else {
1118 $limit = $key;
1119 $text = $value;
1120 }
1121 $s .= Xml::option( $text, $limit, $limit == $this->mLimit ) . "\n";
1122 }
1123 $s .= Html::closeElement( 'select' );
1124 return $s;
1125 }
1126
1127 /**
1128 * Get <input type="hidden"> elements for use in a method="get" form.
1129 * Resubmits all defined elements of the query string, except for a
1130 * blacklist, passed in the $blacklist parameter.
1131 *
1132 * @param $blacklist Array parameters from the request query which should not be resubmitted
1133 * @return String: HTML fragment
1134 */
1135 function getHiddenFields( $blacklist = array() ) {
1136 $blacklist = (array)$blacklist;
1137 $query = $this->getRequest()->getQueryValues();
1138 foreach ( $blacklist as $name ) {
1139 unset( $query[$name] );
1140 }
1141 $s = '';
1142 foreach ( $query as $name => $value ) {
1143 $encName = htmlspecialchars( $name );
1144 $encValue = htmlspecialchars( $value );
1145 $s .= "<input type=\"hidden\" name=\"$encName\" value=\"$encValue\"/>\n";
1146 }
1147 return $s;
1148 }
1149
1150 /**
1151 * Get a form containing a limit selection dropdown
1152 *
1153 * @return String: HTML fragment
1154 */
1155 function getLimitForm() {
1156 global $wgScript;
1157
1158 return Xml::openElement(
1159 'form',
1160 array(
1161 'method' => 'get',
1162 'action' => $wgScript
1163 ) ) . "\n" . $this->getLimitDropdown() . "</form>\n";
1164 }
1165
1166 /**
1167 * Gets a limit selection dropdown
1168 *
1169 * @return string
1170 */
1171 function getLimitDropdown() {
1172 # Make the select with some explanatory text
1173 $msgSubmit = $this->msg( 'table_pager_limit_submit' )->escaped();
1174
1175 return $this->msg( 'table_pager_limit' )
1176 ->rawParams( $this->getLimitSelect() )->escaped() .
1177 "\n<input type=\"submit\" value=\"$msgSubmit\"/>\n" .
1178 $this->getHiddenFields( array( 'limit' ) );
1179 }
1180
1181 /**
1182 * Return true if the named field should be sortable by the UI, false
1183 * otherwise
1184 *
1185 * @param $field String
1186 */
1187 abstract function isFieldSortable( $field );
1188
1189 /**
1190 * Format a table cell. The return value should be HTML, but use an empty
1191 * string not &#160; for empty cells. Do not include the <td> and </td>.
1192 *
1193 * The current result row is available as $this->mCurrentRow, in case you
1194 * need more context.
1195 *
1196 * @protected
1197 *
1198 * @param $name String: the database field name
1199 * @param $value String: the value retrieved from the database
1200 */
1201 abstract function formatValue( $name, $value );
1202
1203 /**
1204 * The database field name used as a default sort order.
1205 *
1206 * @protected
1207 *
1208 * @return string
1209 */
1210 abstract function getDefaultSort();
1211
1212 /**
1213 * An array mapping database field names to a textual description of the
1214 * field name, for use in the table header. The description should be plain
1215 * text, it will be HTML-escaped later.
1216 *
1217 * @return Array
1218 */
1219 abstract function getFieldNames();
1220 }