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