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