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