Merge "Improve docs for Title::getInternalURL/getCanonicalURL"
[lhc/web/wiklou.git] / includes / pager / TablePager.php
1 <?php
2 /**
3 * Efficient paging for SQL queries.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Pager
22 */
23
24 /**
25 * Table-based display with a user-selectable sort order
26 * @ingroup Pager
27 */
28 abstract class TablePager extends IndexPager {
29 /** @var string */
30 protected $mSort;
31
32 /** @var stdClass */
33 protected $mCurrentRow;
34
35 public function __construct( IContextSource $context = null ) {
36 if ( $context ) {
37 $this->setContext( $context );
38 }
39
40 $this->mSort = $this->getRequest()->getText( 'sort' );
41 if ( !array_key_exists( $this->mSort, $this->getFieldNames() )
42 || !$this->isFieldSortable( $this->mSort )
43 ) {
44 $this->mSort = $this->getDefaultSort();
45 }
46 if ( $this->getRequest()->getBool( 'asc' ) ) {
47 $this->mDefaultDirection = IndexPager::DIR_ASCENDING;
48 } elseif ( $this->getRequest()->getBool( 'desc' ) ) {
49 $this->mDefaultDirection = IndexPager::DIR_DESCENDING;
50 } /* Else leave it at whatever the class default is */
51
52 parent::__construct();
53 }
54
55 /**
56 * Get the formatted result list. Calls getStartBody(), formatRow() and getEndBody(), concatenates
57 * the results and returns them.
58 *
59 * Also adds the required styles to our OutputPage object (this means that if context wasn't
60 * passed to constructor or otherwise set up, you will get a pager with missing styles).
61 *
62 * This method has been made 'final' in 1.24. There's no reason to override it, and if there exist
63 * any subclasses that do, the style loading hack is probably broken in them. Let's fail fast
64 * rather than mysteriously render things wrong.
65 *
66 * @deprecated since 1.24, use getBodyOutput() or getFullOutput() instead
67 * @return string
68 */
69 final public function getBody() {
70 $this->getOutput()->addModuleStyles( $this->getModuleStyles() );
71 return parent::getBody();
72 }
73
74 /**
75 * Get the formatted result list.
76 *
77 * Calls getBody() and getModuleStyles() and builds a ParserOutput object. (This is a bit hacky
78 * but works well.)
79 *
80 * @since 1.24
81 * @return ParserOutput
82 */
83 public function getBodyOutput() {
84 $body = parent::getBody();
85
86 $pout = new ParserOutput;
87 $pout->setText( $body );
88 $pout->addModuleStyles( $this->getModuleStyles() );
89 return $pout;
90 }
91
92 /**
93 * Get the formatted result list, with navigation bars.
94 *
95 * Calls getBody(), getNavigationBar() and getModuleStyles() and
96 * builds a ParserOutput object. (This is a bit hacky but works well.)
97 *
98 * @since 1.24
99 * @return ParserOutput
100 */
101 public function getFullOutput() {
102 $navigation = $this->getNavigationBar();
103 $body = parent::getBody();
104
105 $pout = new ParserOutput;
106 $pout->setText( $navigation . $body . $navigation );
107 $pout->addModuleStyles( $this->getModuleStyles() );
108 return $pout;
109 }
110
111 /**
112 * @protected
113 * @return string
114 */
115 protected function getStartBody() {
116 $sortClass = $this->getSortHeaderClass();
117
118 $s = '';
119 $fields = $this->getFieldNames();
120
121 // Make table header
122 foreach ( $fields as $field => $name ) {
123 if ( strval( $name ) == '' ) {
124 $s .= Html::rawElement( 'th', [], "\u{00A0}" ) . "\n";
125 } elseif ( $this->isFieldSortable( $field ) ) {
126 $query = [ 'sort' => $field, 'limit' => $this->mLimit ];
127 $linkType = null;
128 $class = null;
129
130 if ( $this->mSort == $field ) {
131 // The table is sorted by this field already, make a link to sort in the other direction
132 // We don't actually know in which direction other fields will be sorted by default…
133 if ( $this->mDefaultDirection == IndexPager::DIR_DESCENDING ) {
134 $linkType = 'asc';
135 $class = "$sortClass mw-datatable-is-sorted mw-datatable-is-descending";
136 $query['asc'] = '1';
137 $query['desc'] = '';
138 } else {
139 $linkType = 'desc';
140 $class = "$sortClass mw-datatable-is-sorted mw-datatable-is-ascending";
141 $query['asc'] = '';
142 $query['desc'] = '1';
143 }
144 }
145
146 $link = $this->makeLink( htmlspecialchars( $name ), $query, $linkType );
147 $s .= Html::rawElement( 'th', [ 'class' => $class ], $link ) . "\n";
148 } else {
149 $s .= Html::element( 'th', [], $name ) . "\n";
150 }
151 }
152
153 $tableClass = $this->getTableClass();
154 $ret = Html::openElement( 'table', [
155 'class' => " $tableClass" ]
156 );
157 $ret .= Html::rawElement( 'thead', [], Html::rawElement( 'tr', [], "\n" . $s . "\n" ) );
158 $ret .= Html::openElement( 'tbody' ) . "\n";
159
160 return $ret;
161 }
162
163 /**
164 * @protected
165 * @return string
166 */
167 protected function getEndBody() {
168 return "</tbody></table>\n";
169 }
170
171 /**
172 * @protected
173 * @return string
174 */
175 function getEmptyBody() {
176 $colspan = count( $this->getFieldNames() );
177 $msgEmpty = $this->msg( 'table_pager_empty' )->text();
178 return Html::rawElement( 'tr', [],
179 Html::element( 'td', [ 'colspan' => $colspan ], $msgEmpty ) );
180 }
181
182 /**
183 * @protected
184 * @param stdClass $row
185 * @return string HTML
186 */
187 function formatRow( $row ) {
188 $this->mCurrentRow = $row; // In case formatValue etc need to know
189 $s = Html::openElement( 'tr', $this->getRowAttrs( $row ) ) . "\n";
190 $fieldNames = $this->getFieldNames();
191
192 foreach ( $fieldNames as $field => $name ) {
193 $value = $row->$field ?? null;
194 $formatted = strval( $this->formatValue( $field, $value ) );
195
196 if ( $formatted == '' ) {
197 $formatted = "\u{00A0}";
198 }
199
200 $s .= Html::rawElement( 'td', $this->getCellAttrs( $field, $value ), $formatted ) . "\n";
201 }
202
203 $s .= Html::closeElement( 'tr' ) . "\n";
204
205 return $s;
206 }
207
208 /**
209 * Get a class name to be applied to the given row.
210 *
211 * @protected
212 *
213 * @param object $row The database result row
214 * @return string
215 */
216 function getRowClass( $row ) {
217 return '';
218 }
219
220 /**
221 * Get attributes to be applied to the given row.
222 *
223 * @protected
224 *
225 * @param object $row The database result row
226 * @return array Array of attribute => value
227 */
228 function getRowAttrs( $row ) {
229 $class = $this->getRowClass( $row );
230 if ( $class === '' ) {
231 // Return an empty array to avoid clutter in HTML like class=""
232 return [];
233 } else {
234 return [ 'class' => $this->getRowClass( $row ) ];
235 }
236 }
237
238 /**
239 * @return stdClass
240 */
241 protected function getCurrentRow() {
242 return $this->mCurrentRow;
243 }
244
245 /**
246 * Get any extra attributes to be applied to the given cell. Don't
247 * take this as an excuse to hardcode styles; use classes and
248 * CSS instead. Row context is available in $this->mCurrentRow
249 *
250 * @protected
251 *
252 * @param string $field The column
253 * @param string $value The cell contents
254 * @return array Array of attr => value
255 */
256 function getCellAttrs( $field, $value ) {
257 return [ 'class' => 'TablePager_col_' . $field ];
258 }
259
260 /**
261 * @protected
262 * @return string
263 */
264 function getIndexField() {
265 return $this->mSort;
266 }
267
268 /**
269 * TablePager relies on `mw-datatable` for styling, see T214208
270 * @return string
271 */
272 protected function getTableClass() {
273 return 'mw-datatable';
274 }
275
276 /**
277 * @return string
278 */
279 protected function getNavClass() {
280 return 'TablePager_nav';
281 }
282
283 /**
284 * @return string
285 */
286 protected function getSortHeaderClass() {
287 return 'TablePager_sort';
288 }
289
290 /**
291 * A navigation bar with images
292 * @return string HTML
293 */
294 public function getNavigationBar() {
295 if ( !$this->isNavigationBarShown() ) {
296 return '';
297 }
298
299 $this->getOutput()->enableOOUI();
300
301 $types = [ 'first', 'prev', 'next', 'last' ];
302
303 $queries = $this->getPagingQueries();
304
305 $buttons = [];
306
307 $title = $this->getTitle();
308
309 foreach ( $types as $type ) {
310 $buttons[] = new \OOUI\ButtonWidget( [
311 // Messages used here:
312 // * table_pager_first
313 // * table_pager_prev
314 // * table_pager_next
315 // * table_pager_last
316 'classes' => [ 'TablePager-button-' . $type ],
317 'flags' => [ 'progressive' ],
318 'framed' => false,
319 'label' => $this->msg( 'table_pager_' . $type )->text(),
320 'href' => $queries[ $type ] ?
321 $title->getLinkURL( $queries[ $type ] + $this->getDefaultQuery() ) :
322 null,
323 'icon' => $type === 'prev' ? 'previous' : $type,
324 'disabled' => $queries[ $type ] === false
325 ] );
326 }
327 return new \OOUI\ButtonGroupWidget( [
328 'classes' => [ $this->getNavClass() ],
329 'items' => $buttons,
330 ] );
331 }
332
333 /**
334 * ResourceLoader modules that must be loaded to provide correct styling for this pager
335 * @since 1.24
336 * @return string[]
337 */
338 public function getModuleStyles() {
339 return [ 'mediawiki.pager.tablePager', 'oojs-ui.styles.icons-movement' ];
340 }
341
342 /**
343 * Get a "<select>" element which has options for each of the allowed limits
344 *
345 * @param string[] $attribs Extra attributes to set
346 * @return string HTML fragment
347 */
348 public function getLimitSelect( $attribs = [] ) {
349 $select = new XmlSelect( 'limit', false, $this->mLimit );
350 $select->addOptions( $this->getLimitSelectList() );
351 foreach ( $attribs as $name => $value ) {
352 $select->setAttribute( $name, $value );
353 }
354 return $select->getHTML();
355 }
356
357 /**
358 * Get a list of items to show in a "<select>" element of limits.
359 * This can be passed directly to XmlSelect::addOptions().
360 *
361 * @since 1.22
362 * @return array
363 */
364 public function getLimitSelectList() {
365 # Add the current limit from the query string
366 # to avoid that the limit is lost after clicking Go next time
367 if ( !in_array( $this->mLimit, $this->mLimitsShown ) ) {
368 $this->mLimitsShown[] = $this->mLimit;
369 sort( $this->mLimitsShown );
370 }
371 $ret = [];
372 foreach ( $this->mLimitsShown as $key => $value ) {
373 # The pair is either $index => $limit, in which case the $value
374 # will be numeric, or $limit => $text, in which case the $value
375 # will be a string.
376 if ( is_int( $value ) ) {
377 $limit = $value;
378 $text = $this->getLanguage()->formatNum( $limit );
379 } else {
380 $limit = $key;
381 $text = $value;
382 }
383 $ret[$text] = $limit;
384 }
385 return $ret;
386 }
387
388 /**
389 * Get \<input type="hidden"\> elements for use in a method="get" form.
390 * Resubmits all defined elements of the query string, except for a
391 * blacklist, passed in the $blacklist parameter.
392 *
393 * @param array $blacklist Parameters from the request query which should not be resubmitted
394 * @return string HTML fragment
395 */
396 function getHiddenFields( $blacklist = [] ) {
397 $blacklist = (array)$blacklist;
398 $query = $this->getRequest()->getQueryValues();
399 foreach ( $blacklist as $name ) {
400 unset( $query[$name] );
401 }
402 $s = '';
403 foreach ( $query as $name => $value ) {
404 $s .= Html::hidden( $name, $value ) . "\n";
405 }
406 return $s;
407 }
408
409 /**
410 * Get a form containing a limit selection dropdown
411 *
412 * @return string HTML fragment
413 */
414 function getLimitForm() {
415 return Html::rawElement(
416 'form',
417 [
418 'method' => 'get',
419 'action' => wfScript(),
420 ],
421 "\n" . $this->getLimitDropdown()
422 ) . "\n";
423 }
424
425 /**
426 * Gets a limit selection dropdown
427 *
428 * @return string
429 */
430 function getLimitDropdown() {
431 # Make the select with some explanatory text
432 $msgSubmit = $this->msg( 'table_pager_limit_submit' )->escaped();
433
434 return $this->msg( 'table_pager_limit' )
435 ->rawParams( $this->getLimitSelect() )->escaped() .
436 "\n<input type=\"submit\" value=\"$msgSubmit\"/>\n" .
437 $this->getHiddenFields( [ 'limit' ] );
438 }
439
440 /**
441 * Return true if the named field should be sortable by the UI, false
442 * otherwise
443 *
444 * @param string $field
445 */
446 abstract function isFieldSortable( $field );
447
448 /**
449 * Format a table cell. The return value should be HTML, but use an empty
450 * string not &#160; for empty cells. Do not include the <td> and </td>.
451 *
452 * The current result row is available as $this->mCurrentRow, in case you
453 * need more context.
454 *
455 * @protected
456 *
457 * @param string $name The database field name
458 * @param string $value The value retrieved from the database
459 */
460 abstract function formatValue( $name, $value );
461
462 /**
463 * The database field name used as a default sort order.
464 *
465 * @protected
466 *
467 * @return string
468 */
469 abstract function getDefaultSort();
470
471 /**
472 * An array mapping database field names to a textual description of the
473 * field name, for use in the table header. The description should be plain
474 * text, it will be HTML-escaped later.
475 *
476 * @return array
477 */
478 abstract function getFieldNames();
479 }