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