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