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