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