3 * @defgroup Pager Pager
10 * Basic pager interface.
14 function getNavigationBar();
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.
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:
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.
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.
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.
60 abstract class IndexPager
extends ContextSource
implements Pager
{
62 public $mLimitsShown = array( 20, 50, 100, 250, 500 );
63 public $mDefaultLimit = 50;
64 public $mOffset, $mLimit;
65 public $mQueryDone = false;
67 public $mPastTheEndRow;
70 * The index to actually be used for ordering. This is a single column,
71 * for one ordering, even if multiple orderings are supported.
73 protected $mIndexField;
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.
78 protected $mExtraSortFields;
79 /** For pages that support multiple types of ordering, which one to use.
81 protected $mOrderType;
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.
90 * Like $mIndexField, $mDefaultDirection will be a single value even if the
91 * class supports multiple default directions for different order types.
93 public $mDefaultDirection;
96 /** True if the current result set is the first one */
100 protected $mLastShown, $mFirstShown, $mPastTheEndIndex, $mDefaultQuery, $mNavigationBar;
107 protected $mHTMLForm;
110 * Result object for the query. Warning: seek before use.
116 public function __construct( IContextSource
$context = null ) {
118 $this->setContext( $context );
121 $this->mRequest
= $this->getRequest();
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' );
128 # Use consistent behavior for the limit options
129 $this->mDefaultLimit
= intval( $this->getUser()->getOption( 'rclimit' ) );
130 list( $this->mLimit
, /* $offset */ ) = $this->mRequest
->getLimitOffset();
132 $this->mIsBackwards
= ( $this->mRequest
->getVal( 'dir' ) == 'prev' );
133 $this->mDb
= wfGetDB( DB_SLAVE
);
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]
144 } elseif( is_array( $index ) ) {
145 # First element is the default
147 list( $this->mOrderType
, $this->mIndexField
) = each( $index );
148 $this->mExtraSortFields
= isset( $extraSort[$this->mOrderType
] )
149 ?
(array)$extraSort[$this->mOrderType
]
152 # $index is not an array
153 $this->mOrderType
= null;
154 $this->mIndexField
= $index;
155 $this->mExtraSortFields
= (array)$extraSort;
158 if( !isset( $this->mDefaultDirection
) ) {
159 $dir = $this->getDefaultDirections();
160 $this->mDefaultDirection
= is_array( $dir )
161 ?
$dir[$this->mOrderType
]
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.
171 public function doQuery() {
172 # Use the child class name for profiling
173 $fname = __METHOD__
. ' (' . get_class( $this ) . ')';
174 wfProfileIn( $fname );
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;
180 $this->mResult
= $this->reallyDoQuery(
185 $this->extractResultInfo( $this->mOffset
, $queryLimit, $this->mResult
);
186 $this->mQueryDone
= true;
188 $this->preprocessResults( $this->mResult
);
189 $this->mResult
->rewind(); // Paranoia
191 wfProfileOut( $fname );
195 * @return ResultWrapper The result wrapper.
197 function getResult() {
198 return $this->mResult
;
202 * Set the offset from an other source than the request
204 * @param $offset Int|String
206 function setOffset( $offset ) {
207 $this->mOffset
= $offset;
210 * Set the limit from an other source than the request
212 * @param $limit Int|String
214 function setLimit( $limit ) {
215 $this->mLimit
= $limit;
219 * Extract some useful data from the result object for use by
220 * the navigation bar, put it into $this
222 * @param $offset String: index offset, inclusive
223 * @param $limit Integer: exact query limit
224 * @param $res ResultWrapper
226 function extractResultInfo( $offset, $limit, ResultWrapper
$res ) {
227 $numRows = $res->numRows();
229 # Remove any table prefix from index field
230 $parts = explode( '.', $this->mIndexField
);
231 $indexColumn = end( $parts );
233 $row = $res->fetchRow();
234 $firstIndex = $row[$indexColumn];
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];
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];
259 $this->mPastTheEndRow
= null;
260 $this->mPastTheEndIndex
= '';
263 if ( $this->mIsBackwards
) {
264 $this->mIsFirst
= ( $numRows < $limit );
265 $this->mIsLast
= ( $offset == '' );
266 $this->mLastShown
= $firstIndex;
267 $this->mFirstShown
= $lastIndex;
269 $this->mIsFirst
= ( $offset == '' );
270 $this->mIsLast
= ( $numRows < $limit );
271 $this->mLastShown
= $lastIndex;
272 $this->mFirstShown
= $firstIndex;
277 * Get some text to go in brackets in the "function name" part of the SQL comment
281 function getSqlComment() {
282 return get_class( $this );
286 * Do a query with specified parameters, rather than using the object
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
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
);
304 $options['ORDER BY'] = implode( ',', $sortColumns );
308 foreach ( $sortColumns as $col ) {
309 $orderBy[] = $col . ' DESC';
311 $options['ORDER BY'] = implode( ',', $orderBy );
314 if ( $offset != '' ) {
315 $conds[] = $this->mIndexField
. $operator . $this->mDb
->addQuotes( $offset );
317 $options['LIMIT'] = intval( $limit );
318 $res = $this->mDb
->select( $tables, $fields, $conds, $fname, $options, $join_conds );
319 return new ResultWrapper( $this->mDb
, $res );
323 * Pre-process results; useful for performing batch existence checks, etc.
325 * @param $result ResultWrapper
327 protected function preprocessResults( $result ) {}
330 * Get the formatted result list. Calls getStartBody(), formatRow() and
331 * getEndBody(), concatenates the results and returns them.
335 public function getBody() {
336 if ( !$this->mQueryDone
) {
340 if ( $this->mResult
->numRows() ) {
341 # Do any special query batches before display
342 $this->doBatchLookups();
345 # Don't use any extra rows returned by the query
346 $numRows = min( $this->mResult
->numRows(), $this->mLimit
);
348 $s = $this->getStartBody();
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 );
357 $this->mResult
->seek( 0 );
358 for ( $i = 0; $i < $numRows; $i++
) {
359 $row = $this->mResult
->fetchObject();
360 $s .= $this->formatRow( $row );
364 $s .= $this->getEmptyBody();
366 $s .= $this->getEndBody();
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
378 function makeLink($text, $query = null, $type=null) {
379 if ( $query === null ) {
384 if( in_array( $type, array( 'first', 'prev', 'next', 'last' ) ) ) {
385 # HTML5 rel attributes
386 $attrs['rel'] = $type;
390 $attrs['class'] = "mw-{$type}link";
392 return Linker
::linkKnown(
396 $query +
$this->getDefaultQuery()
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.
407 protected function doBatchLookups() {}
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.
415 protected function getStartBody() {
420 * Hook into getBody() for the end of the list
424 protected function getEndBody() {
429 * Hook into getBody(), for the bit between the start and the
430 * end when there are no rows
434 protected function getEmptyBody() {
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
443 * @return Associative array
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'] );
456 return $this->mDefaultQuery
;
460 * Get the number of rows in the result set
464 function getNumRows() {
465 if ( !$this->mQueryDone
) {
468 return $this->mResult
->numRows();
472 * Get a URL query array for the prev, next, first and last links.
476 function getPagingQueries() {
477 if ( !$this->mQueryDone
) {
481 # Don't announce the limit everywhere if it's the default
482 $urlLimit = $this->mLimit
== $this->mDefaultLimit ?
'' : $this->mLimit
;
484 if ( $this->mIsFirst
) {
490 'offset' => $this->mFirstShown
,
493 $first = array( 'limit' => $urlLimit );
495 if ( $this->mIsLast
) {
499 $next = array( 'offset' => $this->mLastShown
, 'limit' => $urlLimit );
500 $last = array( 'dir' => 'prev', 'limit' => $urlLimit );
511 * Returns whether to show the "navigation bar"
515 function isNavigationBarShown() {
516 if ( !$this->mQueryDone
) {
519 // Hide navigation by default if there is nothing to page
520 return !($this->mIsFirst
&& $this->mIsLast
);
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
529 * @param $linkTexts Array
530 * @param $disabledTexts Array
533 function getPagingLinks( $linkTexts, $disabledTexts = array() ) {
534 $queries = $this->getPagingQueries();
536 foreach ( $queries as $type => $query ) {
537 if ( $query !== false ) {
538 $links[$type] = $this->makeLink(
543 } elseif ( isset( $disabledTexts[$type] ) ) {
544 $links[$type] = $disabledTexts[$type];
546 $links[$type] = $linkTexts[$type];
552 function getLimitLinks() {
554 if ( $this->mIsBackwards
) {
555 $offset = $this->mPastTheEndIndex
;
557 $offset = $this->mOffset
;
559 foreach ( $this->mLimitsShown
as $limit ) {
560 $links[] = $this->makeLink(
561 $this->getLanguage()->formatNum( $limit ),
562 array( 'offset' => $offset, 'limit' => $limit ),
570 * Assembles an HTMLForm for the Pager and returns the HTML
574 public function buildHTMLForm() {
575 if ( $this->getHTMLFormFields() === null ) {
576 throw new MWException( __METHOD__
. " was called without any form fields being defined" );
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();
587 return $this->mHTMLForm
->getHTML( '' );
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
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();
601 foreach ( $query as $name => $value ) {
602 if ( in_array( $name, $fieldsBlacklist ) ) {
605 $this->mHTMLForm
->addHiddenField( $name, $value );
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()
614 * @param $row Object: database row
617 abstract function formatRow( $row );
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
631 abstract function getQueryInfo();
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
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.
643 * @return string|Array
645 abstract function getIndexField();
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.
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.
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.
663 protected function getExtraSortFields() { return array(); }
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
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.
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.
684 protected function getDefaultDirections() { return false; }
687 * Returns an array for HTMLForm fields for the pager
689 * Only used if the pager makes use of HTMLForms
693 protected function getHTMLFormFields() { return null; }
696 * Message name for the fieldset legend text
698 * Only used if the pager makes use of HTMLForms
702 protected function getHTMLFormLegend() { return ''; }
705 * Message name for the submit button text
707 * Only used if the pager makes use of HTMLForms
711 protected function getHTMLFormSubmit() { return ''; }
714 * If the pager needs to do any modifications to the Form, override this
717 * Only used if the pager makes use of HTMLForms
719 * @param HTMLForm $form
721 protected function modifyHTMLForm( HTMLForm
$form ) {}
726 * IndexPager with an alphabetic list and a formatted navigation bar
729 abstract class AlphabeticPager
extends IndexPager
{
732 * Shamelessly stolen bits from ReverseChronologicalPager,
733 * didn't want to do class magic as may be still revamped
735 * @return String HTML
737 function getNavigationBar() {
738 if ( !$this->isNavigationBarShown() ) return '';
740 if( isset( $this->mNavigationBar
) ) {
741 return $this->mNavigationBar
;
744 $lang = $this->getLanguage();
746 $opts = array( 'parsemag', 'escapenoentities' );
751 $lang->formatNum( $this->mLimit
)
756 $lang->formatNum($this->mLimit
)
758 'first' => wfMsgExt( 'page_first', $opts ),
759 'last' => wfMsgExt( 'page_last', $opts )
762 $pagingLinks = $this->getPagingLinks( $linkTexts );
763 $limitLinks = $this->getLimitLinks();
764 $limits = $lang->pipeList( $limitLinks );
766 $this->mNavigationBar
=
767 "(" . $lang->pipeList(
768 array( $pagingLinks['first'],
769 $pagingLinks['last'] )
771 wfMsgHtml( 'viewprevnext', $pagingLinks['prev'],
772 $pagingLinks['next'], $limits );
774 if( !is_array( $this->getIndexField() ) ) {
775 # Early return to avoid undue nesting
776 return $this->mNavigationBar
;
781 $msgs = $this->getOrderTypeMessages();
782 foreach( array_keys( $msgs ) as $order ) {
786 $extra .= wfMsgExt( 'pipe-separator' , 'escapenoentities' );
789 if( $order == $this->mOrderType
) {
790 $extra .= wfMsgHTML( $msgs[$order] );
792 $extra .= $this->makeLink(
793 wfMsgHTML( $msgs[$order] ),
794 array( 'order' => $order )
799 if( $extra !== '' ) {
800 $this->mNavigationBar
.= " ($extra)";
803 return $this->mNavigationBar
;
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.
814 protected function getOrderTypeMessages() {
820 * IndexPager with a formatted navigation bar
823 abstract class ReverseChronologicalPager
extends IndexPager
{
824 public $mDefaultDirection = true;
828 function getNavigationBar() {
829 if ( !$this->isNavigationBarShown() ) {
833 if ( isset( $this->mNavigationBar
) ) {
834 return $this->mNavigationBar
;
837 $nicenumber = $this->getLanguage()->formatNum( $this->mLimit
);
841 array( 'parsemag', 'escape' ),
846 array( 'parsemag', 'escape' ),
849 'first' => wfMsgHtml( 'histlast' ),
850 'last' => wfMsgHtml( 'histfirst' )
853 $pagingLinks = $this->getPagingLinks( $linkTexts );
854 $limitLinks = $this->getLimitLinks();
855 $limits = $this->getLanguage()->pipeList( $limitLinks );
857 $this->mNavigationBar
= "({$pagingLinks['first']}" .
858 wfMsgExt( 'pipe-separator' , 'escapenoentities' ) .
859 "{$pagingLinks['last']}) " .
862 $pagingLinks['prev'], $pagingLinks['next'],
865 return $this->mNavigationBar
;
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
) {
882 if ( $this->mYear
) {
883 $year = $this->mYear
;
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' ) ) {
892 if ( $this->mMonth
) {
893 $month = $this->mMonth +
1;
894 // For December, we want January 1 of the next year
900 // No month implies we want up to the end of the year in question
905 if ( $year > 2032 ) {
908 $ymd = (int)sprintf( "%04d%02d01", $year, $month );
909 if ( $ymd > 20320101 ) {
912 $this->mOffset
= $this->mDb
->timestamp( "${ymd}000000" );
917 * Table-based display with a user-selectable sort order
920 abstract class TablePager
extends IndexPager
{
924 function __construct( IContextSource
$context = null ) {
926 $this->setContext( $context );
929 $this->mSort
= $this->getRequest()->getText( 'sort' );
930 if ( !array_key_exists( $this->mSort
, $this->getFieldNames() ) ) {
931 $this->mSort
= $this->getDefaultSort();
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 */
939 parent
::__construct();
942 function getStartBody() {
944 $tableClass = htmlspecialchars( $this->getTableClass() );
945 $sortClass = htmlspecialchars( $this->getSortHeaderClass() );
947 $s = "<table style='border:1;' class=\"mw-datatable $tableClass\"><thead><tr>\n";
948 $fields = $this->getFieldNames();
951 foreach ( $fields as $field => $name ) {
952 if ( strval( $name ) == '' ) {
953 $s .= "<th> </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
) {
961 $image = 'Arr_d.png';
964 $alt = htmlspecialchars( wfMsg( 'descending_abbrev' ) );
967 $image = 'Arr_u.png';
969 $query['desc'] = '1';
970 $alt = htmlspecialchars( wfMsg( 'ascending_abbrev' ) );
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";
978 $s .= '<th>' . $this->makeLink( htmlspecialchars( $name ), $query ) . "</th>\n";
981 $s .= '<th>' . htmlspecialchars( $name ) . "</th>\n";
984 $s .= "</tr></thead><tbody>\n";
988 function getEndBody() {
989 return "</tbody></table>\n";
992 function getEmptyBody() {
993 $colspan = count( $this->getFieldNames() );
994 $msgEmpty = wfMsgHtml( 'table_pager_empty' );
995 return "<tr><td colspan=\"$colspan\">$msgEmpty</td></tr>\n";
1000 * @return String HTML
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 = ' ';
1012 $s .= Xml
::tags( 'td', $this->getCellAttrs( $field, $value ), $formatted );
1019 * Get a class name to be applied to the given row.
1021 * @param $row Object: the database result row
1024 function getRowClass( $row ) {
1029 * Get attributes to be applied to the given row.
1031 * @param $row Object: the database result row
1032 * @return Array of <attr> => <value>
1034 function getRowAttrs( $row ) {
1035 $class = $this->getRowClass( $row );
1036 if ( $class === '' ) {
1037 // Return an empty array to avoid clutter in HTML like class=""
1040 return array( 'class' => $this->getRowClass( $row ) );
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
1049 * @param $field String The column
1050 * @param $value String The cell contents
1051 * @return Array of attr => value
1053 function getCellAttrs( $field, $value ) {
1054 return array( 'class' => 'TablePager_col_' . $field );
1057 function getIndexField() {
1058 return $this->mSort
;
1061 function getTableClass() {
1062 return 'TablePager';
1065 function getNavClass() {
1066 return 'TablePager_nav';
1069 function getSortHeaderClass() {
1070 return 'TablePager_sort';
1074 * A navigation bar with images
1075 * @return String HTML
1077 function getNavigationBar() {
1078 global $wgStylePath;
1080 if ( !$this->isNavigationBarShown() ) {
1084 $path = "$wgStylePath/common/images";
1086 'first' => 'table_pager_first',
1087 'prev' => 'table_pager_prev',
1088 'next' => 'table_pager_next',
1089 'last' => 'table_pager_last',
1092 'first' => 'arrow_first_25.png',
1093 'prev' => 'arrow_left_25.png',
1094 'next' => 'arrow_right_25.png',
1095 'last' => 'arrow_last_25.png',
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',
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 ) );
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";
1116 $links = $this->getPagingLinks( $linkTexts, $disabledTexts );
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";
1124 $s .= "</tr></table>\n";
1129 * Get a <select> element which has options for each of the allowed limits
1131 * @return String: HTML fragment
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
);
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
1145 if( is_int( $value ) ){
1147 $text = $this->getLanguage()->formatNum( $limit );
1152 $s .= Xml
::option( $text, $limit, $limit == $this->mLimit
) . "\n";
1154 $s .= Html
::closeElement( 'select' );
1159 * Returns an HTMLFormField definition for the "Items per page:" dropdown
1163 protected function getHTMLFormLimitSelect() {
1165 'class' => 'HTMLItemsPerPageField',
1166 'label-message' => 'table_pager_limit_label',
1167 'options' => array(),
1168 'default' => $this->mDefaultLimit
,
1172 foreach( $this->mLimitsShown
as $limit ) {
1173 $f['options'][$this->getLanguage()->formatNum( $limit )] = $limit;
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.
1184 * @param $blacklist Array parameters from the request query which should not be resubmitted
1185 * @return String: HTML fragment
1187 function getHiddenFields( $blacklist = array() ) {
1188 $blacklist = (array)$blacklist;
1189 $query = $this->getRequest()->getQueryValues();
1190 foreach ( $blacklist as $name ) {
1191 unset( $query[$name] );
1194 foreach ( $query as $name => $value ) {
1195 $encName = htmlspecialchars( $name );
1196 $encValue = htmlspecialchars( $value );
1197 $s .= "<input type=\"hidden\" name=\"$encName\" value=\"$encValue\"/>\n";
1203 * Get a form containing a limit selection dropdown
1205 * @return String: HTML fragment
1207 function getLimitForm() {
1210 return Xml
::openElement(
1214 'action' => $wgScript
1215 ) ) . "\n" . $this->getLimitDropdown() . "</form>\n";
1219 * Gets a limit selection dropdown
1223 function getLimitDropdown() {
1224 # Make the select with some explanatory text
1225 $msgSubmit = wfMsgHtml( 'table_pager_limit_submit' );
1227 return wfMsgHtml( 'table_pager_limit', $this->getLimitSelect() ) .
1228 "\n<input type=\"submit\" value=\"$msgSubmit\"/>\n" .
1229 $this->getHiddenFields( array( 'limit' ) );
1233 * Return true if the named field should be sortable by the UI, false
1236 * @param $field String
1238 abstract function isFieldSortable( $field );
1241 * Format a table cell. The return value should be HTML, but use an empty
1242 * string not   for empty cells. Do not include the <td> and </td>.
1244 * The current result row is available as $this->mCurrentRow, in case you
1245 * need more context.
1247 * @param $name String: the database field name
1248 * @param $value String: the value retrieved from the database
1250 abstract function formatValue( $name, $value );
1253 * The database field name used as a default sort order
1255 abstract function getDefaultSort();
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.
1264 abstract function getFieldNames();
1268 * Items per page dropdown for HTMLForm
1270 class HTMLItemsPerPageField
extends HTMLSelectField
{
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
1279 function validate( $value, $alldata ) {
1280 if ( $value == '' ) {
1284 if ( !in_array( $value, $this->mParams
['options'] ) ) {
1285 $this->mParams
['options'][ $this->mParent
->getLanguage()->formatNum( $value ) ] = intval($value);
1286 asort( $this->mParams
['options'] );