3 * Efficient paging for SQL queries.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * @defgroup Pager Pager
29 * Basic pager interface.
33 function getNavigationBar();
38 * IndexPager is an efficient pager which uses a (roughly unique) index in the
39 * data set to implement paging, rather than a "LIMIT offset,limit" clause.
40 * In MySQL, such a limit/offset clause requires counting through the
41 * specified number of offset rows to find the desired data, which can be
42 * expensive for large offsets.
44 * ReverseChronologicalPager is a child class of the abstract IndexPager, and
45 * contains some formatting and display code which is specific to the use of
46 * timestamps as indexes. Here is a synopsis of its operation:
48 * * The query is specified by the offset, limit and direction (dir)
49 * parameters, in addition to any subclass-specific parameters.
50 * * The offset is the non-inclusive start of the DB query. A row with an
51 * index value equal to the offset will never be shown.
52 * * The query may either be done backwards, where the rows are returned by
53 * the database in the opposite order to which they are displayed to the
54 * user, or forwards. This is specified by the "dir" parameter, dir=prev
55 * means backwards, anything else means forwards. The offset value
56 * specifies the start of the database result set, which may be either
57 * the start or end of the displayed data set. This allows "previous"
58 * links to be implemented without knowledge of the index value at the
59 * start of the previous page.
60 * * An additional row beyond the user-specified limit is always requested.
61 * This allows us to tell whether we should display a "next" link in the
62 * case of forwards mode, or a "previous" link in the case of backwards
63 * mode. Determining whether to display the other link (the one for the
64 * page before the start of the database result set) can be done
65 * heuristically by examining the offset.
67 * * An empty offset indicates that the offset condition should be omitted
68 * from the query. This naturally produces either the first page or the
69 * last page depending on the dir parameter.
71 * Subclassing the pager to implement concrete functionality should be fairly
72 * simple, please see the examples in HistoryPage.php and
73 * SpecialBlockList.php. You just need to override formatRow(),
74 * getQueryInfo() and getIndexField(). Don't forget to call the parent
75 * constructor if you override it.
79 abstract class IndexPager
extends ContextSource
implements Pager
{
81 public $mLimitsShown = array( 20, 50, 100, 250, 500 );
82 public $mDefaultLimit = 50;
83 public $mOffset, $mLimit;
84 public $mQueryDone = false;
86 public $mPastTheEndRow;
89 * The index to actually be used for ordering. This is a single column,
90 * for one ordering, even if multiple orderings are supported.
92 protected $mIndexField;
94 * An array of secondary columns to order by. These fields are not part of the offset.
95 * This is a column list for one ordering, even if multiple orderings are supported.
97 protected $mExtraSortFields;
98 /** For pages that support multiple types of ordering, which one to use.
100 protected $mOrderType;
102 * $mDefaultDirection gives the direction to use when sorting results:
103 * false for ascending, true for descending. If $mIsBackwards is set, we
104 * start from the opposite end, but we still sort the page itself according
105 * to $mDefaultDirection. E.g., if $mDefaultDirection is false but we're
106 * going backwards, we'll display the last page of results, but the last
107 * result will be at the bottom, not the top.
109 * Like $mIndexField, $mDefaultDirection will be a single value even if the
110 * class supports multiple default directions for different order types.
112 public $mDefaultDirection;
113 public $mIsBackwards;
115 /** True if the current result set is the first one */
119 protected $mLastShown, $mFirstShown, $mPastTheEndIndex, $mDefaultQuery, $mNavigationBar;
122 * Result object for the query. Warning: seek before use.
128 public function __construct( IContextSource
$context = null ) {
130 $this->setContext( $context );
133 $this->mRequest
= $this->getRequest();
135 # NB: the offset is quoted, not validated. It is treated as an
136 # arbitrary string to support the widest variety of index types. Be
137 # careful outputting it into HTML!
138 $this->mOffset
= $this->mRequest
->getText( 'offset' );
140 # Use consistent behavior for the limit options
141 $this->mDefaultLimit
= intval( $this->getUser()->getOption( 'rclimit' ) );
142 list( $this->mLimit
, /* $offset */ ) = $this->mRequest
->getLimitOffset();
144 $this->mIsBackwards
= ( $this->mRequest
->getVal( 'dir' ) == 'prev' );
145 $this->mDb
= wfGetDB( DB_SLAVE
);
147 $index = $this->getIndexField(); // column to sort on
148 $extraSort = $this->getExtraSortFields(); // extra columns to sort on for query planning
149 $order = $this->mRequest
->getVal( 'order' );
150 if( is_array( $index ) && isset( $index[$order] ) ) {
151 $this->mOrderType
= $order;
152 $this->mIndexField
= $index[$order];
153 $this->mExtraSortFields
= isset( $extraSort[$order] )
154 ?
(array)$extraSort[$order]
156 } elseif( is_array( $index ) ) {
157 # First element is the default
159 list( $this->mOrderType
, $this->mIndexField
) = each( $index );
160 $this->mExtraSortFields
= isset( $extraSort[$this->mOrderType
] )
161 ?
(array)$extraSort[$this->mOrderType
]
164 # $index is not an array
165 $this->mOrderType
= null;
166 $this->mIndexField
= $index;
167 $this->mExtraSortFields
= (array)$extraSort;
170 if( !isset( $this->mDefaultDirection
) ) {
171 $dir = $this->getDefaultDirections();
172 $this->mDefaultDirection
= is_array( $dir )
173 ?
$dir[$this->mOrderType
]
179 * Do the query, using information from the object context. This function
180 * has been kept minimal to make it overridable if necessary, to allow for
181 * result sets formed from multiple DB queries.
183 public function doQuery() {
184 # Use the child class name for profiling
185 $fname = __METHOD__
. ' (' . get_class( $this ) . ')';
186 wfProfileIn( $fname );
188 $descending = ( $this->mIsBackwards
== $this->mDefaultDirection
);
189 # Plus an extra row so that we can tell the "next" link should be shown
190 $queryLimit = $this->mLimit +
1;
192 $this->mResult
= $this->reallyDoQuery(
197 $this->extractResultInfo( $this->mOffset
, $queryLimit, $this->mResult
);
198 $this->mQueryDone
= true;
200 $this->preprocessResults( $this->mResult
);
201 $this->mResult
->rewind(); // Paranoia
203 wfProfileOut( $fname );
207 * @return ResultWrapper The result wrapper.
209 function getResult() {
210 return $this->mResult
;
214 * Set the offset from an other source than the request
216 * @param $offset Int|String
218 function setOffset( $offset ) {
219 $this->mOffset
= $offset;
222 * Set the limit from an other source than the request
224 * @param $limit Int|String
226 function setLimit( $limit ) {
227 $this->mLimit
= $limit;
231 * Extract some useful data from the result object for use by
232 * the navigation bar, put it into $this
234 * @param $offset String: index offset, inclusive
235 * @param $limit Integer: exact query limit
236 * @param $res ResultWrapper
238 function extractResultInfo( $offset, $limit, ResultWrapper
$res ) {
239 $numRows = $res->numRows();
241 # Remove any table prefix from index field
242 $parts = explode( '.', $this->mIndexField
);
243 $indexColumn = end( $parts );
245 $row = $res->fetchRow();
246 $firstIndex = $row[$indexColumn];
248 # Discard the extra result row if there is one
249 if ( $numRows > $this->mLimit
&& $numRows > 1 ) {
250 $res->seek( $numRows - 1 );
251 $this->mPastTheEndRow
= $res->fetchObject();
252 $indexField = $this->mIndexField
;
253 $this->mPastTheEndIndex
= $this->mPastTheEndRow
->$indexField;
254 $res->seek( $numRows - 2 );
255 $row = $res->fetchRow();
256 $lastIndex = $row[$indexColumn];
258 $this->mPastTheEndRow
= null;
259 # Setting indexes to an empty string means that they will be
260 # omitted if they would otherwise appear in URLs. It just so
261 # happens that this is the right thing to do in the standard
262 # UI, in all the relevant cases.
263 $this->mPastTheEndIndex
= '';
264 $res->seek( $numRows - 1 );
265 $row = $res->fetchRow();
266 $lastIndex = $row[$indexColumn];
271 $this->mPastTheEndRow
= null;
272 $this->mPastTheEndIndex
= '';
275 if ( $this->mIsBackwards
) {
276 $this->mIsFirst
= ( $numRows < $limit );
277 $this->mIsLast
= ( $offset == '' );
278 $this->mLastShown
= $firstIndex;
279 $this->mFirstShown
= $lastIndex;
281 $this->mIsFirst
= ( $offset == '' );
282 $this->mIsLast
= ( $numRows < $limit );
283 $this->mLastShown
= $lastIndex;
284 $this->mFirstShown
= $firstIndex;
289 * Get some text to go in brackets in the "function name" part of the SQL comment
293 function getSqlComment() {
294 return get_class( $this );
298 * Do a query with specified parameters, rather than using the object
301 * @param $offset String: index offset, inclusive
302 * @param $limit Integer: exact query limit
303 * @param $descending Boolean: query direction, false for ascending, true for descending
304 * @return ResultWrapper
306 function reallyDoQuery( $offset, $limit, $descending ) {
307 $fname = __METHOD__
. ' (' . $this->getSqlComment() . ')';
308 $info = $this->getQueryInfo();
309 $tables = $info['tables'];
310 $fields = $info['fields'];
311 $conds = isset( $info['conds'] ) ?
$info['conds'] : array();
312 $options = isset( $info['options'] ) ?
$info['options'] : array();
313 $join_conds = isset( $info['join_conds'] ) ?
$info['join_conds'] : array();
314 $sortColumns = array_merge( array( $this->mIndexField
), $this->mExtraSortFields
);
316 $options['ORDER BY'] = $sortColumns;
320 foreach ( $sortColumns as $col ) {
321 $orderBy[] = $col . ' DESC';
323 $options['ORDER BY'] = $orderBy;
326 if ( $offset != '' ) {
327 $conds[] = $this->mIndexField
. $operator . $this->mDb
->addQuotes( $offset );
329 $options['LIMIT'] = intval( $limit );
330 $res = $this->mDb
->select( $tables, $fields, $conds, $fname, $options, $join_conds );
331 return new ResultWrapper( $this->mDb
, $res );
335 * Pre-process results; useful for performing batch existence checks, etc.
337 * @param $result ResultWrapper
339 protected function preprocessResults( $result ) {}
342 * Get the formatted result list. Calls getStartBody(), formatRow() and
343 * getEndBody(), concatenates the results and returns them.
347 public function getBody() {
348 if ( !$this->mQueryDone
) {
352 if ( $this->mResult
->numRows() ) {
353 # Do any special query batches before display
354 $this->doBatchLookups();
357 # Don't use any extra rows returned by the query
358 $numRows = min( $this->mResult
->numRows(), $this->mLimit
);
360 $s = $this->getStartBody();
362 if ( $this->mIsBackwards
) {
363 for ( $i = $numRows - 1; $i >= 0; $i-- ) {
364 $this->mResult
->seek( $i );
365 $row = $this->mResult
->fetchObject();
366 $s .= $this->formatRow( $row );
369 $this->mResult
->seek( 0 );
370 for ( $i = 0; $i < $numRows; $i++
) {
371 $row = $this->mResult
->fetchObject();
372 $s .= $this->formatRow( $row );
376 $s .= $this->getEmptyBody();
378 $s .= $this->getEndBody();
385 * @param $text String: text displayed on the link
386 * @param $query Array: associative array of paramter to be in the query string
387 * @param $type String: value of the "rel" attribute
389 * @return String: HTML fragment
391 function makeLink( $text, array $query = null, $type = null ) {
392 if ( $query === null ) {
397 if( in_array( $type, array( 'first', 'prev', 'next', 'last' ) ) ) {
398 # HTML5 rel attributes
399 $attrs['rel'] = $type;
403 $attrs['class'] = "mw-{$type}link";
406 return Linker
::linkKnown(
410 $query +
$this->getDefaultQuery()
415 * Called from getBody(), before getStartBody() is called and
416 * after doQuery() was called. This will be called only if there
417 * are rows in the result set.
421 protected function doBatchLookups() {}
424 * Hook into getBody(), allows text to be inserted at the start. This
425 * will be called even if there are no rows in the result set.
429 protected function getStartBody() {
434 * Hook into getBody() for the end of the list
438 protected function getEndBody() {
443 * Hook into getBody(), for the bit between the start and the
444 * end when there are no rows
448 protected function getEmptyBody() {
453 * Get an array of query parameters that should be put into self-links.
454 * By default, all parameters passed in the URL are used, except for a
457 * @return array Associative array
459 function getDefaultQuery() {
460 if ( !isset( $this->mDefaultQuery
) ) {
461 $this->mDefaultQuery
= $this->getRequest()->getQueryValues();
462 unset( $this->mDefaultQuery
['title'] );
463 unset( $this->mDefaultQuery
['dir'] );
464 unset( $this->mDefaultQuery
['offset'] );
465 unset( $this->mDefaultQuery
['limit'] );
466 unset( $this->mDefaultQuery
['order'] );
467 unset( $this->mDefaultQuery
['month'] );
468 unset( $this->mDefaultQuery
['year'] );
470 return $this->mDefaultQuery
;
474 * Get the number of rows in the result set
478 function getNumRows() {
479 if ( !$this->mQueryDone
) {
482 return $this->mResult
->numRows();
486 * Get a URL query array for the prev, next, first and last links.
490 function getPagingQueries() {
491 if ( !$this->mQueryDone
) {
495 # Don't announce the limit everywhere if it's the default
496 $urlLimit = $this->mLimit
== $this->mDefaultLimit ?
null : $this->mLimit
;
498 if ( $this->mIsFirst
) {
504 'offset' => $this->mFirstShown
,
507 $first = array( 'limit' => $urlLimit );
509 if ( $this->mIsLast
) {
513 $next = array( 'offset' => $this->mLastShown
, 'limit' => $urlLimit );
514 $last = array( 'dir' => 'prev', 'limit' => $urlLimit );
525 * Returns whether to show the "navigation bar"
529 function isNavigationBarShown() {
530 if ( !$this->mQueryDone
) {
533 // Hide navigation by default if there is nothing to page
534 return !($this->mIsFirst
&& $this->mIsLast
);
538 * Get paging links. If a link is disabled, the item from $disabledTexts
539 * will be used. If there is no such item, the unlinked text from
540 * $linkTexts will be used. Both $linkTexts and $disabledTexts are arrays
543 * @param $linkTexts Array
544 * @param $disabledTexts Array
547 function getPagingLinks( $linkTexts, $disabledTexts = array() ) {
548 $queries = $this->getPagingQueries();
551 foreach ( $queries as $type => $query ) {
552 if ( $query !== false ) {
553 $links[$type] = $this->makeLink(
558 } elseif ( isset( $disabledTexts[$type] ) ) {
559 $links[$type] = $disabledTexts[$type];
561 $links[$type] = $linkTexts[$type];
568 function getLimitLinks() {
570 if ( $this->mIsBackwards
) {
571 $offset = $this->mPastTheEndIndex
;
573 $offset = $this->mOffset
;
575 foreach ( $this->mLimitsShown
as $limit ) {
576 $links[] = $this->makeLink(
577 $this->getLanguage()->formatNum( $limit ),
578 array( 'offset' => $offset, 'limit' => $limit ),
586 * Abstract formatting function. This should return an HTML string
587 * representing the result row $row. Rows will be concatenated and
588 * returned by getBody()
590 * @param $row Object: database row
593 abstract function formatRow( $row );
596 * This function should be overridden to provide all parameters
597 * needed for the main paged query. It returns an associative
598 * array with the following elements:
599 * tables => Table(s) for passing to Database::select()
600 * fields => Field(s) for passing to Database::select(), may be *
601 * conds => WHERE conditions
602 * options => option array
603 * join_conds => JOIN conditions
607 abstract function getQueryInfo();
610 * This function should be overridden to return the name of the index fi-
611 * eld. If the pager supports multiple orders, it may return an array of
612 * 'querykey' => 'indexfield' pairs, so that a request with &count=querykey
613 * will use indexfield to sort. In this case, the first returned key is
616 * Needless to say, it's really not a good idea to use a non-unique index
617 * for this! That won't page right.
619 * @return string|Array
621 abstract function getIndexField();
624 * This function should be overridden to return the names of secondary columns
625 * to order by in addition to the column in getIndexField(). These fields will
626 * not be used in the pager offset or in any links for users.
628 * If getIndexField() returns an array of 'querykey' => 'indexfield' pairs then
629 * this must return a corresponding array of 'querykey' => array( fields...) pairs
630 * in order for a request with &count=querykey to use array( fields...) to sort.
632 * This is useful for pagers that GROUP BY a unique column (say page_id)
633 * and ORDER BY another (say page_len). Using GROUP BY and ORDER BY both on
634 * page_len,page_id avoids temp tables (given a page_len index). This would
635 * also work if page_id was non-unique but we had a page_len,page_id index.
639 protected function getExtraSortFields() { return array(); }
642 * Return the default sorting direction: false for ascending, true for de-
643 * scending. You can also have an associative array of ordertype => dir,
644 * if multiple order types are supported. In this case getIndexField()
645 * must return an array, and the keys of that must exactly match the keys
648 * For backward compatibility, this method's return value will be ignored
649 * if $this->mDefaultDirection is already set when the constructor is
650 * called, for instance if it's statically initialized. In that case the
651 * value of that variable (which must be a boolean) will be used.
653 * Note that despite its name, this does not return the value of the
654 * $this->mDefaultDirection member variable. That's the default for this
655 * particular instantiation, which is a single value. This is the set of
656 * all defaults for the class.
660 protected function getDefaultDirections() { return false; }
665 * IndexPager with an alphabetic list and a formatted navigation bar
668 abstract class AlphabeticPager
extends IndexPager
{
671 * Shamelessly stolen bits from ReverseChronologicalPager,
672 * didn't want to do class magic as may be still revamped
674 * @return String HTML
676 function getNavigationBar() {
677 if ( !$this->isNavigationBarShown() ) {
681 if( isset( $this->mNavigationBar
) ) {
682 return $this->mNavigationBar
;
685 $lang = $this->getLanguage();
687 $opts = array( 'parsemag', 'escapenoentities' );
692 $lang->formatNum( $this->mLimit
)
697 $lang->formatNum($this->mLimit
)
699 'first' => wfMsgExt( 'page_first', $opts ),
700 'last' => wfMsgExt( 'page_last', $opts )
703 $pagingLinks = $this->getPagingLinks( $linkTexts );
704 $limitLinks = $this->getLimitLinks();
705 $limits = $lang->pipeList( $limitLinks );
707 $this->mNavigationBar
= wfMessage( 'parentheses' )->rawParams(
709 array( $pagingLinks['first'],
710 $pagingLinks['last'] )
711 ) )->escaped() . " " .
712 wfMsgHtml( 'viewprevnext', $pagingLinks['prev'],
713 $pagingLinks['next'], $limits );
715 if( !is_array( $this->getIndexField() ) ) {
716 # Early return to avoid undue nesting
717 return $this->mNavigationBar
;
722 $msgs = $this->getOrderTypeMessages();
723 foreach( array_keys( $msgs ) as $order ) {
727 $extra .= wfMsgExt( 'pipe-separator' , 'escapenoentities' );
730 if( $order == $this->mOrderType
) {
731 $extra .= wfMsgHTML( $msgs[$order] );
733 $extra .= $this->makeLink(
734 wfMsgHTML( $msgs[$order] ),
735 array( 'order' => $order )
740 if( $extra !== '' ) {
741 $extra = ' ' . wfMessage( 'parentheses' )->rawParams( $extra )->escaped();
742 $this->mNavigationBar
.= $extra;
745 return $this->mNavigationBar
;
749 * If this supports multiple order type messages, give the message key for
750 * enabling each one in getNavigationBar. The return type is an associa-
751 * tive array whose keys must exactly match the keys of the array returned
752 * by getIndexField(), and whose values are message keys.
756 protected function getOrderTypeMessages() {
762 * IndexPager with a formatted navigation bar
765 abstract class ReverseChronologicalPager
extends IndexPager
{
766 public $mDefaultDirection = true;
770 function getNavigationBar() {
771 if ( !$this->isNavigationBarShown() ) {
775 if ( isset( $this->mNavigationBar
) ) {
776 return $this->mNavigationBar
;
779 $nicenumber = $this->getLanguage()->formatNum( $this->mLimit
);
783 array( 'parsemag', 'escape' ),
788 array( 'parsemag', 'escape' ),
791 'first' => wfMsgHtml( 'histlast' ),
792 'last' => wfMsgHtml( 'histfirst' )
795 $pagingLinks = $this->getPagingLinks( $linkTexts );
796 $limitLinks = $this->getLimitLinks();
797 $limits = $this->getLanguage()->pipeList( $limitLinks );
798 $firstLastLinks = wfMessage( 'parentheses' )->rawParams( "{$pagingLinks['first']}" .
799 wfMsgExt( 'pipe-separator' , 'escapenoentities' ) .
800 "{$pagingLinks['last']}" )->escaped();
802 $this->mNavigationBar
= $firstLastLinks . ' ' .
805 $pagingLinks['prev'], $pagingLinks['next'],
809 return $this->mNavigationBar
;
812 function getDateCond( $year, $month ) {
813 $year = intval( $year );
814 $month = intval( $month );
816 // Basic validity checks
817 $this->mYear
= $year > 0 ?
$year : false;
818 $this->mMonth
= ( $month > 0 && $month < 13 ) ?
$month : false;
820 // Given an optional year and month, we need to generate a timestamp
821 // to use as "WHERE rev_timestamp <= result"
822 // Examples: year = 2006 equals < 20070101 (+000000)
823 // year=2005, month=1 equals < 20050201
824 // year=2005, month=12 equals < 20060101
825 if ( !$this->mYear
&& !$this->mMonth
) {
829 if ( $this->mYear
) {
830 $year = $this->mYear
;
832 // If no year given, assume the current one
833 $year = gmdate( 'Y' );
834 // If this month hasn't happened yet this year, go back to last year's month
835 if( $this->mMonth
> gmdate( 'n' ) ) {
840 if ( $this->mMonth
) {
841 $month = $this->mMonth +
1;
842 // For December, we want January 1 of the next year
848 // No month implies we want up to the end of the year in question
854 if ( $year > 2032 ) {
858 $ymd = (int)sprintf( "%04d%02d01", $year, $month );
860 if ( $ymd > 20320101 ) {
864 $this->mOffset
= $this->mDb
->timestamp( "${ymd}000000" );
869 * Table-based display with a user-selectable sort order
872 abstract class TablePager
extends IndexPager
{
876 public function __construct( IContextSource
$context = null ) {
878 $this->setContext( $context );
881 $this->mSort
= $this->getRequest()->getText( 'sort' );
882 if ( !array_key_exists( $this->mSort
, $this->getFieldNames() ) ) {
883 $this->mSort
= $this->getDefaultSort();
885 if ( $this->getRequest()->getBool( 'asc' ) ) {
886 $this->mDefaultDirection
= false;
887 } elseif ( $this->getRequest()->getBool( 'desc' ) ) {
888 $this->mDefaultDirection
= true;
889 } /* Else leave it at whatever the class default is */
891 parent
::__construct();
898 function getStartBody() {
900 $tableClass = htmlspecialchars( $this->getTableClass() );
901 $sortClass = htmlspecialchars( $this->getSortHeaderClass() );
903 $s = "<table style='border:1;' class=\"mw-datatable $tableClass\"><thead><tr>\n";
904 $fields = $this->getFieldNames();
907 foreach ( $fields as $field => $name ) {
908 if ( strval( $name ) == '' ) {
909 $s .= "<th> </th>\n";
910 } elseif ( $this->isFieldSortable( $field ) ) {
911 $query = array( 'sort' => $field, 'limit' => $this->mLimit
);
912 if ( $field == $this->mSort
) {
913 # This is the sorted column
914 # Prepare a link that goes in the other sort order
915 if ( $this->mDefaultDirection
) {
917 $image = 'Arr_d.png';
920 $alt = htmlspecialchars( wfMsg( 'descending_abbrev' ) );
923 $image = 'Arr_u.png';
925 $query['desc'] = '1';
926 $alt = htmlspecialchars( wfMsg( 'ascending_abbrev' ) );
928 $image = htmlspecialchars( "$wgStylePath/common/images/$image" );
929 $link = $this->makeLink(
930 "<img width=\"12\" height=\"12\" alt=\"$alt\" src=\"$image\" />" .
931 htmlspecialchars( $name ), $query );
932 $s .= "<th class=\"$sortClass\">$link</th>\n";
934 $s .= '<th>' . $this->makeLink( htmlspecialchars( $name ), $query ) . "</th>\n";
937 $s .= '<th>' . htmlspecialchars( $name ) . "</th>\n";
940 $s .= "</tr></thead><tbody>\n";
948 function getEndBody() {
949 return "</tbody></table>\n";
956 function getEmptyBody() {
957 $colspan = count( $this->getFieldNames() );
958 $msgEmpty = wfMsgHtml( 'table_pager_empty' );
959 return "<tr><td colspan=\"$colspan\">$msgEmpty</td></tr>\n";
964 * @param stdClass $row
965 * @return String HTML
967 function formatRow( $row ) {
968 $this->mCurrentRow
= $row; // In case formatValue etc need to know
969 $s = Xml
::openElement( 'tr', $this->getRowAttrs( $row ) );
970 $fieldNames = $this->getFieldNames();
972 foreach ( $fieldNames as $field => $name ) {
973 $value = isset( $row->$field ) ?
$row->$field : null;
974 $formatted = strval( $this->formatValue( $field, $value ) );
976 if ( $formatted == '' ) {
977 $formatted = ' ';
980 $s .= Xml
::tags( 'td', $this->getCellAttrs( $field, $value ), $formatted );
989 * Get a class name to be applied to the given row.
993 * @param $row Object: the database result row
996 function getRowClass( $row ) {
1001 * Get attributes to be applied to the given row.
1005 * @param $row Object: the database result row
1006 * @return Array of <attr> => <value>
1008 function getRowAttrs( $row ) {
1009 $class = $this->getRowClass( $row );
1010 if ( $class === '' ) {
1011 // Return an empty array to avoid clutter in HTML like class=""
1014 return array( 'class' => $this->getRowClass( $row ) );
1019 * Get any extra attributes to be applied to the given cell. Don't
1020 * take this as an excuse to hardcode styles; use classes and
1021 * CSS instead. Row context is available in $this->mCurrentRow
1025 * @param $field String The column
1026 * @param $value String The cell contents
1027 * @return Array of attr => value
1029 function getCellAttrs( $field, $value ) {
1030 return array( 'class' => 'TablePager_col_' . $field );
1037 function getIndexField() {
1038 return $this->mSort
;
1045 function getTableClass() {
1046 return 'TablePager';
1053 function getNavClass() {
1054 return 'TablePager_nav';
1061 function getSortHeaderClass() {
1062 return 'TablePager_sort';
1066 * A navigation bar with images
1067 * @return String HTML
1069 public function getNavigationBar() {
1070 global $wgStylePath;
1072 if ( !$this->isNavigationBarShown() ) {
1076 $path = "$wgStylePath/common/images";
1078 'first' => 'table_pager_first',
1079 'prev' => 'table_pager_prev',
1080 'next' => 'table_pager_next',
1081 'last' => 'table_pager_last',
1084 'first' => 'arrow_first_25.png',
1085 'prev' => 'arrow_left_25.png',
1086 'next' => 'arrow_right_25.png',
1087 'last' => 'arrow_last_25.png',
1089 $disabledImages = array(
1090 'first' => 'arrow_disabled_first_25.png',
1091 'prev' => 'arrow_disabled_left_25.png',
1092 'next' => 'arrow_disabled_right_25.png',
1093 'last' => 'arrow_disabled_last_25.png',
1095 if( $this->getLanguage()->isRTL() ) {
1096 $keys = array_keys( $labels );
1097 $images = array_combine( $keys, array_reverse( $images ) );
1098 $disabledImages = array_combine( $keys, array_reverse( $disabledImages ) );
1101 $linkTexts = array();
1102 $disabledTexts = array();
1103 foreach ( $labels as $type => $label ) {
1104 $msgLabel = wfMsgHtml( $label );
1105 $linkTexts[$type] = "<img src=\"$path/{$images[$type]}\" alt=\"$msgLabel\"/><br />$msgLabel";
1106 $disabledTexts[$type] = "<img src=\"$path/{$disabledImages[$type]}\" alt=\"$msgLabel\"/><br />$msgLabel";
1108 $links = $this->getPagingLinks( $linkTexts, $disabledTexts );
1110 $navClass = htmlspecialchars( $this->getNavClass() );
1111 $s = "<table class=\"$navClass\"><tr>\n";
1112 $width = 100 / count( $links ) . '%';
1113 foreach ( $labels as $type => $label ) {
1114 $s .= "<td style='width:$width;'>{$links[$type]}</td>\n";
1116 $s .= "</tr></table>\n";
1121 * Get a <select> element which has options for each of the allowed limits
1123 * @return String: HTML fragment
1125 public function getLimitSelect() {
1126 # Add the current limit from the query string
1127 # to avoid that the limit is lost after clicking Go next time
1128 if ( !in_array( $this->mLimit
, $this->mLimitsShown
) ) {
1129 $this->mLimitsShown
[] = $this->mLimit
;
1130 sort( $this->mLimitsShown
);
1132 $s = Html
::openElement( 'select', array( 'name' => 'limit' ) ) . "\n";
1133 foreach ( $this->mLimitsShown
as $key => $value ) {
1134 # The pair is either $index => $limit, in which case the $value
1135 # will be numeric, or $limit => $text, in which case the $value
1137 if( is_int( $value ) ){
1139 $text = $this->getLanguage()->formatNum( $limit );
1144 $s .= Xml
::option( $text, $limit, $limit == $this->mLimit
) . "\n";
1146 $s .= Html
::closeElement( 'select' );
1151 * Get <input type="hidden"> elements for use in a method="get" form.
1152 * Resubmits all defined elements of the query string, except for a
1153 * blacklist, passed in the $blacklist parameter.
1155 * @param $blacklist Array parameters from the request query which should not be resubmitted
1156 * @return String: HTML fragment
1158 function getHiddenFields( $blacklist = array() ) {
1159 $blacklist = (array)$blacklist;
1160 $query = $this->getRequest()->getQueryValues();
1161 foreach ( $blacklist as $name ) {
1162 unset( $query[$name] );
1165 foreach ( $query as $name => $value ) {
1166 $encName = htmlspecialchars( $name );
1167 $encValue = htmlspecialchars( $value );
1168 $s .= "<input type=\"hidden\" name=\"$encName\" value=\"$encValue\"/>\n";
1174 * Get a form containing a limit selection dropdown
1176 * @return String: HTML fragment
1178 function getLimitForm() {
1181 return Xml
::openElement(
1185 'action' => $wgScript
1186 ) ) . "\n" . $this->getLimitDropdown() . "</form>\n";
1190 * Gets a limit selection dropdown
1194 function getLimitDropdown() {
1195 # Make the select with some explanatory text
1196 $msgSubmit = wfMsgHtml( 'table_pager_limit_submit' );
1198 return wfMsgHtml( 'table_pager_limit', $this->getLimitSelect() ) .
1199 "\n<input type=\"submit\" value=\"$msgSubmit\"/>\n" .
1200 $this->getHiddenFields( array( 'limit' ) );
1204 * Return true if the named field should be sortable by the UI, false
1207 * @param $field String
1209 abstract function isFieldSortable( $field );
1212 * Format a table cell. The return value should be HTML, but use an empty
1213 * string not   for empty cells. Do not include the <td> and </td>.
1215 * The current result row is available as $this->mCurrentRow, in case you
1216 * need more context.
1220 * @param $name String: the database field name
1221 * @param $value String: the value retrieved from the database
1223 abstract function formatValue( $name, $value );
1226 * The database field name used as a default sort order.
1232 abstract function getDefaultSort();
1235 * An array mapping database field names to a textual description of the
1236 * field name, for use in the table header. The description should be plain
1237 * text, it will be HTML-escaped later.
1241 abstract function getFieldNames();