Merge "Handle missing namespace prefix in XML dumps more gracefully"
[lhc/web/wiklou.git] / includes / specials / pagers / ImageListPager.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 * @ingroup Pager
20 */
21
22 /**
23 * @ingroup Pager
24 */
25 use MediaWiki\MediaWikiServices;
26 use Wikimedia\Rdbms\ResultWrapper;
27 use Wikimedia\Rdbms\FakeResultWrapper;
28
29 class ImageListPager extends TablePager {
30
31 protected $mFieldNames = null;
32
33 // Subclasses should override buildQueryConds instead of using $mQueryConds variable.
34 protected $mQueryConds = [];
35
36 protected $mUserName = null;
37
38 /**
39 * The relevant user
40 *
41 * @var User|null
42 */
43 protected $mUser = null;
44
45 protected $mSearch = '';
46
47 protected $mIncluding = false;
48
49 protected $mShowAll = false;
50
51 protected $mTableName = 'image';
52
53 function __construct( IContextSource $context, $userName = null, $search = '',
54 $including = false, $showAll = false
55 ) {
56 $this->setContext( $context );
57 $this->mIncluding = $including;
58 $this->mShowAll = $showAll;
59
60 if ( $userName !== null && $userName !== '' ) {
61 $nt = Title::makeTitleSafe( NS_USER, $userName );
62 if ( is_null( $nt ) ) {
63 $this->outputUserDoesNotExist( $userName );
64 } else {
65 $this->mUserName = $nt->getText();
66 $user = User::newFromName( $this->mUserName, false );
67 if ( $user ) {
68 $this->mUser = $user;
69 }
70 if ( !$user || ( $user->isAnon() && !User::isIP( $user->getName() ) ) ) {
71 $this->outputUserDoesNotExist( $userName );
72 }
73 }
74 }
75
76 if ( $search !== '' && !$this->getConfig()->get( 'MiserMode' ) ) {
77 $this->mSearch = $search;
78 $nt = Title::newFromText( $this->mSearch );
79
80 if ( $nt ) {
81 $dbr = wfGetDB( DB_REPLICA );
82 $this->mQueryConds[] = 'LOWER(img_name)' .
83 $dbr->buildLike( $dbr->anyString(),
84 strtolower( $nt->getDBkey() ), $dbr->anyString() );
85 }
86 }
87
88 if ( !$including ) {
89 if ( $this->getRequest()->getText( 'sort', 'img_date' ) == 'img_date' ) {
90 $this->mDefaultDirection = IndexPager::DIR_DESCENDING;
91 } else {
92 $this->mDefaultDirection = IndexPager::DIR_ASCENDING;
93 }
94 } else {
95 $this->mDefaultDirection = IndexPager::DIR_DESCENDING;
96 }
97
98 parent::__construct( $context );
99 }
100
101 /**
102 * Get the user relevant to the ImageList
103 *
104 * @return User|null
105 */
106 function getRelevantUser() {
107 return $this->mUser;
108 }
109
110 /**
111 * Add a message to the output stating that the user doesn't exist
112 *
113 * @param string $userName Unescaped user name
114 */
115 protected function outputUserDoesNotExist( $userName ) {
116 $this->getOutput()->wrapWikiMsg(
117 "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
118 [
119 'listfiles-userdoesnotexist',
120 wfEscapeWikiText( $userName ),
121 ]
122 );
123 }
124
125 /**
126 * Build the where clause of the query.
127 *
128 * Replaces the older mQueryConds member variable.
129 * @param string $table Either "image" or "oldimage"
130 * @return array The query conditions.
131 */
132 protected function buildQueryConds( $table ) {
133 $prefix = $table === 'image' ? 'img' : 'oi';
134 $conds = [];
135
136 if ( !is_null( $this->mUserName ) ) {
137 $conds[$prefix . '_user_text'] = $this->mUserName;
138 }
139
140 if ( $this->mSearch !== '' ) {
141 $nt = Title::newFromText( $this->mSearch );
142 if ( $nt ) {
143 $dbr = wfGetDB( DB_REPLICA );
144 $conds[] = 'LOWER(' . $prefix . '_name)' .
145 $dbr->buildLike( $dbr->anyString(),
146 strtolower( $nt->getDBkey() ), $dbr->anyString() );
147 }
148 }
149
150 if ( $table === 'oldimage' ) {
151 // Don't want to deal with revdel.
152 // Future fixme: Show partial information as appropriate.
153 // Would have to be careful about filtering by username when username is deleted.
154 $conds['oi_deleted'] = 0;
155 }
156
157 // Add mQueryConds in case anyone was subclassing and using the old variable.
158 return $conds + $this->mQueryConds;
159 }
160
161 /**
162 * @return array
163 */
164 function getFieldNames() {
165 if ( !$this->mFieldNames ) {
166 $this->mFieldNames = [
167 'img_timestamp' => $this->msg( 'listfiles_date' )->text(),
168 'img_name' => $this->msg( 'listfiles_name' )->text(),
169 'thumb' => $this->msg( 'listfiles_thumb' )->text(),
170 'img_size' => $this->msg( 'listfiles_size' )->text(),
171 ];
172 if ( is_null( $this->mUserName ) ) {
173 // Do not show username if filtering by username
174 $this->mFieldNames['img_user_text'] = $this->msg( 'listfiles_user' )->text();
175 }
176 // img_description down here, in order so that its still after the username field.
177 $this->mFieldNames['img_description'] = $this->msg( 'listfiles_description' )->text();
178
179 if ( !$this->getConfig()->get( 'MiserMode' ) && !$this->mShowAll ) {
180 $this->mFieldNames['count'] = $this->msg( 'listfiles_count' )->text();
181 }
182 if ( $this->mShowAll ) {
183 $this->mFieldNames['top'] = $this->msg( 'listfiles-latestversion' )->text();
184 }
185 }
186
187 return $this->mFieldNames;
188 }
189
190 function isFieldSortable( $field ) {
191 if ( $this->mIncluding ) {
192 return false;
193 }
194 $sortable = [ 'img_timestamp', 'img_name', 'img_size' ];
195 /* For reference, the indicies we can use for sorting are:
196 * On the image table: img_usertext_timestamp, img_size, img_timestamp
197 * On oldimage: oi_usertext_timestamp, oi_name_timestamp
198 *
199 * In particular that means we cannot sort by timestamp when not filtering
200 * by user and including old images in the results. Which is sad.
201 */
202 if ( $this->getConfig()->get( 'MiserMode' ) && !is_null( $this->mUserName ) ) {
203 // If we're sorting by user, the index only supports sorting by time.
204 if ( $field === 'img_timestamp' ) {
205 return true;
206 } else {
207 return false;
208 }
209 } elseif ( $this->getConfig()->get( 'MiserMode' )
210 && $this->mShowAll /* && mUserName === null */
211 ) {
212 // no oi_timestamp index, so only alphabetical sorting in this case.
213 if ( $field === 'img_name' ) {
214 return true;
215 } else {
216 return false;
217 }
218 }
219
220 return in_array( $field, $sortable );
221 }
222
223 function getQueryInfo() {
224 // Hacky Hacky Hacky - I want to get query info
225 // for two different tables, without reimplementing
226 // the pager class.
227 $qi = $this->getQueryInfoReal( $this->mTableName );
228
229 return $qi;
230 }
231
232 /**
233 * Actually get the query info.
234 *
235 * This is to allow displaying both stuff from image and oldimage table.
236 *
237 * This is a bit hacky.
238 *
239 * @param string $table Either 'image' or 'oldimage'
240 * @return array Query info
241 */
242 protected function getQueryInfoReal( $table ) {
243 $prefix = $table === 'oldimage' ? 'oi' : 'img';
244
245 $tables = [ $table ];
246 $fields = array_keys( $this->getFieldNames() );
247
248 if ( $table === 'oldimage' ) {
249 foreach ( $fields as $id => &$field ) {
250 if ( substr( $field, 0, 4 ) !== 'img_' ) {
251 continue;
252 }
253 $field = $prefix . substr( $field, 3 ) . ' AS ' . $field;
254 }
255 $fields[array_search( 'top', $fields )] = "'no' AS top";
256 } else {
257 if ( $this->mShowAll ) {
258 $fields[array_search( 'top', $fields )] = "'yes' AS top";
259 }
260 }
261 $fields[] = $prefix . '_user AS img_user';
262 $fields[array_search( 'thumb', $fields )] = $prefix . '_name AS thumb';
263
264 $options = $join_conds = [];
265
266 # Depends on $wgMiserMode
267 # Will also not happen if mShowAll is true.
268 if ( isset( $this->mFieldNames['count'] ) ) {
269 $tables[] = 'oldimage';
270
271 # Need to rewrite this one
272 foreach ( $fields as &$field ) {
273 if ( $field == 'count' ) {
274 $field = 'COUNT(oi_archive_name) AS count';
275 }
276 }
277 unset( $field );
278
279 $dbr = wfGetDB( DB_REPLICA );
280 if ( $dbr->implicitGroupby() ) {
281 $options = [ 'GROUP BY' => 'img_name' ];
282 } else {
283 $columnlist = preg_grep( '/^img/', array_keys( $this->getFieldNames() ) );
284 $options = [ 'GROUP BY' => array_merge( [ 'img_user' ], $columnlist ) ];
285 }
286 $join_conds = [ 'oldimage' => [ 'LEFT JOIN', 'oi_name = img_name' ] ];
287 }
288
289 return [
290 'tables' => $tables,
291 'fields' => $fields,
292 'conds' => $this->buildQueryConds( $table ),
293 'options' => $options,
294 'join_conds' => $join_conds
295 ];
296 }
297
298 /**
299 * Override reallyDoQuery to mix together two queries.
300 *
301 * @note $asc is named $descending in IndexPager base class. However
302 * it is true when the order is ascending, and false when the order
303 * is descending, so I renamed it to $asc here.
304 * @param int $offset
305 * @param int $limit
306 * @param bool $asc
307 * @return array
308 * @throws MWException
309 */
310 function reallyDoQuery( $offset, $limit, $asc ) {
311 $prevTableName = $this->mTableName;
312 $this->mTableName = 'image';
313 list( $tables, $fields, $conds, $fname, $options, $join_conds ) =
314 $this->buildQueryInfo( $offset, $limit, $asc );
315 $imageRes = $this->mDb->select( $tables, $fields, $conds, $fname, $options, $join_conds );
316 $this->mTableName = $prevTableName;
317
318 if ( !$this->mShowAll ) {
319 return $imageRes;
320 }
321
322 $this->mTableName = 'oldimage';
323
324 # Hacky...
325 $oldIndex = $this->mIndexField;
326 if ( substr( $this->mIndexField, 0, 4 ) !== 'img_' ) {
327 throw new MWException( "Expected to be sorting on an image table field" );
328 }
329 $this->mIndexField = 'oi_' . substr( $this->mIndexField, 4 );
330
331 list( $tables, $fields, $conds, $fname, $options, $join_conds ) =
332 $this->buildQueryInfo( $offset, $limit, $asc );
333 $oldimageRes = $this->mDb->select( $tables, $fields, $conds, $fname, $options, $join_conds );
334
335 $this->mTableName = $prevTableName;
336 $this->mIndexField = $oldIndex;
337
338 return $this->combineResult( $imageRes, $oldimageRes, $limit, $asc );
339 }
340
341 /**
342 * Combine results from 2 tables.
343 *
344 * Note: This will throw away some results
345 *
346 * @param ResultWrapper $res1
347 * @param ResultWrapper $res2
348 * @param int $limit
349 * @param bool $ascending See note about $asc in $this->reallyDoQuery
350 * @return FakeResultWrapper $res1 and $res2 combined
351 */
352 protected function combineResult( $res1, $res2, $limit, $ascending ) {
353 $res1->rewind();
354 $res2->rewind();
355 $topRes1 = $res1->next();
356 $topRes2 = $res2->next();
357 $resultArray = [];
358 for ( $i = 0; $i < $limit && $topRes1 && $topRes2; $i++ ) {
359 if ( strcmp( $topRes1->{$this->mIndexField}, $topRes2->{$this->mIndexField} ) > 0 ) {
360 if ( !$ascending ) {
361 $resultArray[] = $topRes1;
362 $topRes1 = $res1->next();
363 } else {
364 $resultArray[] = $topRes2;
365 $topRes2 = $res2->next();
366 }
367 } else {
368 if ( !$ascending ) {
369 $resultArray[] = $topRes2;
370 $topRes2 = $res2->next();
371 } else {
372 $resultArray[] = $topRes1;
373 $topRes1 = $res1->next();
374 }
375 }
376 }
377
378 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
379 for ( ; $i < $limit && $topRes1; $i++ ) {
380 // @codingStandardsIgnoreEnd
381 $resultArray[] = $topRes1;
382 $topRes1 = $res1->next();
383 }
384
385 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
386 for ( ; $i < $limit && $topRes2; $i++ ) {
387 // @codingStandardsIgnoreEnd
388 $resultArray[] = $topRes2;
389 $topRes2 = $res2->next();
390 }
391
392 return new FakeResultWrapper( $resultArray );
393 }
394
395 function getDefaultSort() {
396 if ( $this->mShowAll && $this->getConfig()->get( 'MiserMode' ) && is_null( $this->mUserName ) ) {
397 // Unfortunately no index on oi_timestamp.
398 return 'img_name';
399 } else {
400 return 'img_timestamp';
401 }
402 }
403
404 function doBatchLookups() {
405 $userIds = [];
406 $this->mResult->seek( 0 );
407 foreach ( $this->mResult as $row ) {
408 $userIds[] = $row->img_user;
409 }
410 # Do a link batch query for names and userpages
411 UserCache::singleton()->doQuery( $userIds, [ 'userpage' ], __METHOD__ );
412 }
413
414 /**
415 * @param string $field
416 * @param string $value
417 * @return Message|string|int The return type depends on the value of $field:
418 * - thumb: string
419 * - img_timestamp: string
420 * - img_name: string
421 * - img_user_text: string
422 * - img_size: string
423 * - img_description: string
424 * - count: int
425 * - top: Message
426 * @throws MWException
427 */
428 function formatValue( $field, $value ) {
429 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
430 switch ( $field ) {
431 case 'thumb':
432 $opt = [ 'time' => wfTimestamp( TS_MW, $this->mCurrentRow->img_timestamp ) ];
433 $file = RepoGroup::singleton()->getLocalRepo()->findFile( $value, $opt );
434 // If statement for paranoia
435 if ( $file ) {
436 $thumb = $file->transform( [ 'width' => 180, 'height' => 360 ] );
437 if ( $thumb ) {
438 return $thumb->toHtml( [ 'desc-link' => true ] );
439 } else {
440 return wfMessage( 'thumbnail_error', '' )->escaped();
441 }
442 } else {
443 return htmlspecialchars( $value );
444 }
445 case 'img_timestamp':
446 // We may want to make this a link to the "old" version when displaying old files
447 return htmlspecialchars( $this->getLanguage()->userTimeAndDate( $value, $this->getUser() ) );
448 case 'img_name':
449 static $imgfile = null;
450 if ( $imgfile === null ) {
451 $imgfile = $this->msg( 'imgfile' )->text();
452 }
453
454 // Weird files can maybe exist? T24227
455 $filePage = Title::makeTitleSafe( NS_FILE, $value );
456 if ( $filePage ) {
457 $link = $linkRenderer->makeKnownLink(
458 $filePage,
459 $filePage->getText()
460 );
461 $download = Xml::element( 'a',
462 [ 'href' => wfLocalFile( $filePage )->getUrl() ],
463 $imgfile
464 );
465 $download = $this->msg( 'parentheses' )->rawParams( $download )->escaped();
466
467 // Add delete links if allowed
468 // From https://github.com/Wikia/app/pull/3859
469 if ( $filePage->userCan( 'delete', $this->getUser() ) ) {
470 $deleteMsg = $this->msg( 'listfiles-delete' )->text();
471
472 $delete = $linkRenderer->makeKnownLink(
473 $filePage, $deleteMsg, [], [ 'action' => 'delete' ]
474 );
475 $delete = $this->msg( 'parentheses' )->rawParams( $delete )->escaped();
476
477 return "$link $download $delete";
478 }
479
480 return "$link $download";
481 } else {
482 return htmlspecialchars( $value );
483 }
484 case 'img_user_text':
485 if ( $this->mCurrentRow->img_user ) {
486 $name = User::whoIs( $this->mCurrentRow->img_user );
487 $link = $linkRenderer->makeLink(
488 Title::makeTitle( NS_USER, $name ),
489 $name
490 );
491 } else {
492 $link = htmlspecialchars( $value );
493 }
494
495 return $link;
496 case 'img_size':
497 return htmlspecialchars( $this->getLanguage()->formatSize( $value ) );
498 case 'img_description':
499 return Linker::formatComment( $value );
500 case 'count':
501 return $this->getLanguage()->formatNum( intval( $value ) + 1 );
502 case 'top':
503 // Messages: listfiles-latestversion-yes, listfiles-latestversion-no
504 return $this->msg( 'listfiles-latestversion-' . $value );
505 default:
506 throw new MWException( "Unknown field '$field'" );
507 }
508 }
509
510 function getForm() {
511 $fields = [];
512 $fields['limit'] = [
513 'type' => 'select',
514 'name' => 'limit',
515 'label-message' => 'table_pager_limit_label',
516 'options' => $this->getLimitSelectList(),
517 'default' => $this->mLimit,
518 ];
519
520 if ( !$this->getConfig()->get( 'MiserMode' ) ) {
521 $fields['ilsearch'] = [
522 'type' => 'text',
523 'name' => 'ilsearch',
524 'id' => 'mw-ilsearch',
525 'label-message' => 'listfiles_search_for',
526 'default' => $this->mSearch,
527 'size' => '40',
528 'maxlength' => '255',
529 ];
530 }
531
532 $this->getOutput()->addModules( 'mediawiki.userSuggest' );
533 $fields['user'] = [
534 'type' => 'text',
535 'name' => 'user',
536 'id' => 'mw-listfiles-user',
537 'label-message' => 'username',
538 'default' => $this->mUserName,
539 'size' => '40',
540 'maxlength' => '255',
541 'cssclass' => 'mw-autocomplete-user', // used by mediawiki.userSuggest
542 ];
543
544 $fields['ilshowall'] = [
545 'type' => 'check',
546 'name' => 'ilshowall',
547 'id' => 'mw-listfiles-show-all',
548 'label-message' => 'listfiles-show-all',
549 'default' => $this->mShowAll,
550 ];
551
552 $query = $this->getRequest()->getQueryValues();
553 unset( $query['title'] );
554 unset( $query['limit'] );
555 unset( $query['ilsearch'] );
556 unset( $query['ilshowall'] );
557 unset( $query['user'] );
558
559 $form = new HTMLForm( $fields, $this->getContext() );
560
561 $form->setMethod( 'get' );
562 $form->setTitle( $this->getTitle() );
563 $form->setId( 'mw-listfiles-form' );
564 $form->setWrapperLegendMsg( 'listfiles' );
565 $form->setSubmitTextMsg( 'table_pager_limit_submit' );
566 $form->addHiddenFields( $query );
567
568 $form->prepareForm();
569 $form->displayForm( '' );
570 }
571
572 protected function getTableClass() {
573 return parent::getTableClass() . ' listfiles';
574 }
575
576 protected function getNavClass() {
577 return parent::getNavClass() . ' listfiles_nav';
578 }
579
580 protected function getSortHeaderClass() {
581 return parent::getSortHeaderClass() . ' listfiles_sort';
582 }
583
584 function getPagingQueries() {
585 $queries = parent::getPagingQueries();
586 if ( !is_null( $this->mUserName ) ) {
587 # Append the username to the query string
588 foreach ( $queries as &$query ) {
589 if ( $query !== false ) {
590 $query['user'] = $this->mUserName;
591 }
592 }
593 }
594
595 return $queries;
596 }
597
598 function getDefaultQuery() {
599 $queries = parent::getDefaultQuery();
600 if ( !isset( $queries['user'] ) && !is_null( $this->mUserName ) ) {
601 $queries['user'] = $this->mUserName;
602 }
603
604 return $queries;
605 }
606
607 function getTitle() {
608 return SpecialPage::getTitleFor( 'Listfiles' );
609 }
610 }