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