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