Merge "RevisionStoreDbTestBase, remove redundant needsDB override"
[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\IResultWrapper;
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 * The array keys (but not the array values) are used in sql. Phan
163 * gets confused by this, so mark this method as being ok for sql in general.
164 * @return-taint onlysafefor_sql
165 * @return array
166 */
167 function getFieldNames() {
168 if ( !$this->mFieldNames ) {
169 $this->mFieldNames = [
170 'img_timestamp' => $this->msg( 'listfiles_date' )->text(),
171 'img_name' => $this->msg( 'listfiles_name' )->text(),
172 'thumb' => $this->msg( 'listfiles_thumb' )->text(),
173 'img_size' => $this->msg( 'listfiles_size' )->text(),
174 ];
175 if ( is_null( $this->mUserName ) ) {
176 // Do not show username if filtering by username
177 $this->mFieldNames['img_user_text'] = $this->msg( 'listfiles_user' )->text();
178 }
179 // img_description down here, in order so that its still after the username field.
180 $this->mFieldNames['img_description'] = $this->msg( 'listfiles_description' )->text();
181
182 if ( !$this->getConfig()->get( 'MiserMode' ) && !$this->mShowAll ) {
183 $this->mFieldNames['count'] = $this->msg( 'listfiles_count' )->text();
184 }
185 if ( $this->mShowAll ) {
186 $this->mFieldNames['top'] = $this->msg( 'listfiles-latestversion' )->text();
187 }
188 }
189
190 return $this->mFieldNames;
191 }
192
193 function isFieldSortable( $field ) {
194 if ( $this->mIncluding ) {
195 return false;
196 }
197 $sortable = [ 'img_timestamp', 'img_name', 'img_size' ];
198 /* For reference, the indicies we can use for sorting are:
199 * On the image table: img_user_timestamp/img_usertext_timestamp/img_actor_timestamp,
200 * img_size, img_timestamp
201 * On oldimage: oi_usertext_timestamp/oi_actor_timestamp, oi_name_timestamp
202 *
203 * In particular that means we cannot sort by timestamp when not filtering
204 * by user and including old images in the results. Which is sad.
205 */
206 if ( $this->getConfig()->get( 'MiserMode' ) && !is_null( $this->mUserName ) ) {
207 // If we're sorting by user, the index only supports sorting by time.
208 if ( $field === 'img_timestamp' ) {
209 return true;
210 } else {
211 return false;
212 }
213 } elseif ( $this->getConfig()->get( 'MiserMode' )
214 && $this->mShowAll /* && mUserName === null */
215 ) {
216 // no oi_timestamp index, so only alphabetical sorting in this case.
217 if ( $field === 'img_name' ) {
218 return true;
219 } else {
220 return false;
221 }
222 }
223
224 return in_array( $field, $sortable );
225 }
226
227 function getQueryInfo() {
228 // Hacky Hacky Hacky - I want to get query info
229 // for two different tables, without reimplementing
230 // the pager class.
231 $qi = $this->getQueryInfoReal( $this->mTableName );
232
233 return $qi;
234 }
235
236 /**
237 * Actually get the query info.
238 *
239 * This is to allow displaying both stuff from image and oldimage table.
240 *
241 * This is a bit hacky.
242 *
243 * @param string $table Either 'image' or 'oldimage'
244 * @return array Query info
245 */
246 protected function getQueryInfoReal( $table ) {
247 $prefix = $table === 'oldimage' ? 'oi' : 'img';
248
249 $tables = [ $table ];
250 $fields = $this->getFieldNames();
251 unset( $fields['img_description'] );
252 unset( $fields['img_user_text'] );
253 $fields = array_keys( $fields );
254
255 if ( $table === 'oldimage' ) {
256 foreach ( $fields as $id => &$field ) {
257 if ( substr( $field, 0, 4 ) !== 'img_' ) {
258 continue;
259 }
260 $field = $prefix . substr( $field, 3 ) . ' AS ' . $field;
261 }
262 $fields[array_search( 'top', $fields )] = "'no' AS top";
263 } else {
264 if ( $this->mShowAll ) {
265 $fields[array_search( 'top', $fields )] = "'yes' AS top";
266 }
267 }
268 $fields[array_search( 'thumb', $fields )] = $prefix . '_name AS thumb';
269
270 $options = $join_conds = [];
271
272 # Description field
273 $commentQuery = CommentStore::getStore()->getJoin( $prefix . '_description' );
274 $tables += $commentQuery['tables'];
275 $fields += $commentQuery['fields'];
276 $join_conds += $commentQuery['joins'];
277 $fields['description_field'] = "'{$prefix}_description'";
278
279 # User fields
280 $actorQuery = ActorMigration::newMigration()->getJoin( $prefix . '_user' );
281 $tables += $actorQuery['tables'];
282 $join_conds += $actorQuery['joins'];
283 $fields['img_user'] = $actorQuery['fields'][$prefix . '_user'];
284 $fields['img_user_text'] = $actorQuery['fields'][$prefix . '_user_text'];
285 $fields['img_actor'] = $actorQuery['fields'][$prefix . '_actor'];
286
287 # Depends on $wgMiserMode
288 # Will also not happen if mShowAll is true.
289 if ( isset( $this->mFieldNames['count'] ) ) {
290 $tables[] = 'oldimage';
291
292 # Need to rewrite this one
293 foreach ( $fields as &$field ) {
294 if ( $field == 'count' ) {
295 $field = 'COUNT(oi_archive_name) AS count';
296 }
297 }
298 unset( $field );
299
300 $columnlist = preg_grep( '/^img/', array_keys( $this->getFieldNames() ) );
301 $options = [ 'GROUP BY' => array_merge( [ $fields['img_user'] ], $columnlist ) ];
302 $join_conds['oldimage'] = [ 'LEFT JOIN', 'oi_name = img_name' ];
303 }
304
305 return [
306 'tables' => $tables,
307 'fields' => $fields,
308 'conds' => $this->buildQueryConds( $table ),
309 'options' => $options,
310 'join_conds' => $join_conds
311 ];
312 }
313
314 /**
315 * Override reallyDoQuery to mix together two queries.
316 *
317 * @note $asc is named $descending in IndexPager base class. However
318 * it is true when the order is ascending, and false when the order
319 * is descending, so I renamed it to $asc here.
320 * @param int $offset
321 * @param int $limit
322 * @param bool $asc
323 * @return array
324 * @throws MWException
325 */
326 function reallyDoQuery( $offset, $limit, $asc ) {
327 $prevTableName = $this->mTableName;
328 $this->mTableName = 'image';
329 list( $tables, $fields, $conds, $fname, $options, $join_conds ) =
330 $this->buildQueryInfo( $offset, $limit, $asc );
331 $imageRes = $this->mDb->select( $tables, $fields, $conds, $fname, $options, $join_conds );
332 $this->mTableName = $prevTableName;
333
334 if ( !$this->mShowAll ) {
335 return $imageRes;
336 }
337
338 $this->mTableName = 'oldimage';
339
340 # Hacky...
341 $oldIndex = $this->mIndexField;
342 if ( substr( $this->mIndexField, 0, 4 ) !== 'img_' ) {
343 throw new MWException( "Expected to be sorting on an image table field" );
344 }
345 $this->mIndexField = 'oi_' . substr( $this->mIndexField, 4 );
346
347 list( $tables, $fields, $conds, $fname, $options, $join_conds ) =
348 $this->buildQueryInfo( $offset, $limit, $asc );
349 $oldimageRes = $this->mDb->select( $tables, $fields, $conds, $fname, $options, $join_conds );
350
351 $this->mTableName = $prevTableName;
352 $this->mIndexField = $oldIndex;
353
354 return $this->combineResult( $imageRes, $oldimageRes, $limit, $asc );
355 }
356
357 /**
358 * Combine results from 2 tables.
359 *
360 * Note: This will throw away some results
361 *
362 * @param IResultWrapper $res1
363 * @param IResultWrapper $res2
364 * @param int $limit
365 * @param bool $ascending See note about $asc in $this->reallyDoQuery
366 * @return FakeResultWrapper $res1 and $res2 combined
367 */
368 protected function combineResult( $res1, $res2, $limit, $ascending ) {
369 $res1->rewind();
370 $res2->rewind();
371 $topRes1 = $res1->next();
372 $topRes2 = $res2->next();
373 $resultArray = [];
374 for ( $i = 0; $i < $limit && $topRes1 && $topRes2; $i++ ) {
375 if ( strcmp( $topRes1->{$this->mIndexField}, $topRes2->{$this->mIndexField} ) > 0 ) {
376 if ( !$ascending ) {
377 $resultArray[] = $topRes1;
378 $topRes1 = $res1->next();
379 } else {
380 $resultArray[] = $topRes2;
381 $topRes2 = $res2->next();
382 }
383 } else {
384 if ( !$ascending ) {
385 $resultArray[] = $topRes2;
386 $topRes2 = $res2->next();
387 } else {
388 $resultArray[] = $topRes1;
389 $topRes1 = $res1->next();
390 }
391 }
392 }
393
394 for ( ; $i < $limit && $topRes1; $i++ ) {
395 $resultArray[] = $topRes1;
396 $topRes1 = $res1->next();
397 }
398
399 for ( ; $i < $limit && $topRes2; $i++ ) {
400 $resultArray[] = $topRes2;
401 $topRes2 = $res2->next();
402 }
403
404 return new FakeResultWrapper( $resultArray );
405 }
406
407 function getDefaultSort() {
408 if ( $this->mShowAll && $this->getConfig()->get( 'MiserMode' ) && is_null( $this->mUserName ) ) {
409 // Unfortunately no index on oi_timestamp.
410 return 'img_name';
411 } else {
412 return 'img_timestamp';
413 }
414 }
415
416 function doBatchLookups() {
417 $userIds = [];
418 $this->mResult->seek( 0 );
419 foreach ( $this->mResult as $row ) {
420 $userIds[] = $row->img_user;
421 }
422 # Do a link batch query for names and userpages
423 UserCache::singleton()->doQuery( $userIds, [ 'userpage' ], __METHOD__ );
424 }
425
426 /**
427 * @param string $field
428 * @param string $value
429 * @return Message|string|int The return type depends on the value of $field:
430 * - thumb: string
431 * - img_timestamp: string
432 * - img_name: string
433 * - img_user_text: string
434 * - img_size: string
435 * - img_description: string
436 * - count: int
437 * - top: Message
438 * @throws MWException
439 */
440 function formatValue( $field, $value ) {
441 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
442 switch ( $field ) {
443 case 'thumb':
444 $opt = [ 'time' => wfTimestamp( TS_MW, $this->mCurrentRow->img_timestamp ) ];
445 $file = RepoGroup::singleton()->getLocalRepo()->findFile( $value, $opt );
446 // If statement for paranoia
447 if ( $file ) {
448 $thumb = $file->transform( [ 'width' => 180, 'height' => 360 ] );
449 if ( $thumb ) {
450 return $thumb->toHtml( [ 'desc-link' => true ] );
451 } else {
452 return $this->msg( 'thumbnail_error', '' )->escaped();
453 }
454 } else {
455 return htmlspecialchars( $value );
456 }
457 case 'img_timestamp':
458 // We may want to make this a link to the "old" version when displaying old files
459 return htmlspecialchars( $this->getLanguage()->userTimeAndDate( $value, $this->getUser() ) );
460 case 'img_name':
461 static $imgfile = null;
462 if ( $imgfile === null ) {
463 $imgfile = $this->msg( 'imgfile' )->text();
464 }
465
466 // Weird files can maybe exist? T24227
467 $filePage = Title::makeTitleSafe( NS_FILE, $value );
468 if ( $filePage ) {
469 $link = $linkRenderer->makeKnownLink(
470 $filePage,
471 $filePage->getText()
472 );
473 $download = Xml::element( 'a',
474 [ 'href' => wfLocalFile( $filePage )->getUrl() ],
475 $imgfile
476 );
477 $download = $this->msg( 'parentheses' )->rawParams( $download )->escaped();
478
479 // Add delete links if allowed
480 // From https://github.com/Wikia/app/pull/3859
481 if ( $filePage->userCan( 'delete', $this->getUser() ) ) {
482 $deleteMsg = $this->msg( 'listfiles-delete' )->text();
483
484 $delete = $linkRenderer->makeKnownLink(
485 $filePage, $deleteMsg, [], [ 'action' => 'delete' ]
486 );
487 $delete = $this->msg( 'parentheses' )->rawParams( $delete )->escaped();
488
489 return "$link $download $delete";
490 }
491
492 return "$link $download";
493 } else {
494 return htmlspecialchars( $value );
495 }
496 case 'img_user_text':
497 if ( $this->mCurrentRow->img_user ) {
498 $name = User::whoIs( $this->mCurrentRow->img_user );
499 $link = $linkRenderer->makeLink(
500 Title::makeTitle( NS_USER, $name ),
501 $name
502 );
503 } else {
504 $link = htmlspecialchars( $value );
505 }
506
507 return $link;
508 case 'img_size':
509 return htmlspecialchars( $this->getLanguage()->formatSize( $value ) );
510 case 'img_description':
511 $field = $this->mCurrentRow->description_field;
512 $value = CommentStore::getStore()->getComment( $field, $this->mCurrentRow )->text;
513 return Linker::formatComment( $value );
514 case 'count':
515 return $this->getLanguage()->formatNum( intval( $value ) + 1 );
516 case 'top':
517 // Messages: listfiles-latestversion-yes, listfiles-latestversion-no
518 return $this->msg( 'listfiles-latestversion-' . $value );
519 default:
520 throw new MWException( "Unknown field '$field'" );
521 }
522 }
523
524 function getForm() {
525 $formDescriptor = [];
526 $formDescriptor['limit'] = [
527 'type' => 'select',
528 'name' => 'limit',
529 'label-message' => 'table_pager_limit_label',
530 'options' => $this->getLimitSelectList(),
531 'default' => $this->mLimit,
532 ];
533
534 if ( !$this->getConfig()->get( 'MiserMode' ) ) {
535 $formDescriptor['ilsearch'] = [
536 'type' => 'text',
537 'name' => 'ilsearch',
538 'id' => 'mw-ilsearch',
539 'label-message' => 'listfiles_search_for',
540 'default' => $this->mSearch,
541 'size' => '40',
542 'maxlength' => '255',
543 ];
544 }
545
546 $formDescriptor['user'] = [
547 'type' => 'user',
548 'name' => 'user',
549 'id' => 'mw-listfiles-user',
550 'label-message' => 'username',
551 'default' => $this->mUserName,
552 'size' => '40',
553 'maxlength' => '255',
554 ];
555
556 $formDescriptor['ilshowall'] = [
557 'type' => 'check',
558 'name' => 'ilshowall',
559 'id' => 'mw-listfiles-show-all',
560 'label-message' => 'listfiles-show-all',
561 'default' => $this->mShowAll,
562 ];
563
564 $query = $this->getRequest()->getQueryValues();
565 unset( $query['title'] );
566 unset( $query['limit'] );
567 unset( $query['ilsearch'] );
568 unset( $query['ilshowall'] );
569 unset( $query['user'] );
570
571 $htmlForm = HTMLForm::factory( 'ooui', $formDescriptor, $this->getContext() );
572 $htmlForm
573 ->setMethod( 'get' )
574 ->setId( 'mw-listfiles-form' )
575 ->setTitle( $this->getTitle() )
576 ->setSubmitTextMsg( 'table_pager_limit_submit' )
577 ->setWrapperLegendMsg( 'listfiles' )
578 ->addHiddenFields( $query )
579 ->prepareForm()
580 ->displayForm( '' );
581 }
582
583 protected function getTableClass() {
584 return parent::getTableClass() . ' listfiles';
585 }
586
587 protected function getNavClass() {
588 return parent::getNavClass() . ' listfiles_nav';
589 }
590
591 protected function getSortHeaderClass() {
592 return parent::getSortHeaderClass() . ' listfiles_sort';
593 }
594
595 function getPagingQueries() {
596 $queries = parent::getPagingQueries();
597 if ( !is_null( $this->mUserName ) ) {
598 # Append the username to the query string
599 foreach ( $queries as &$query ) {
600 if ( $query !== false ) {
601 $query['user'] = $this->mUserName;
602 }
603 }
604 }
605
606 return $queries;
607 }
608
609 function getDefaultQuery() {
610 $queries = parent::getDefaultQuery();
611 if ( !isset( $queries['user'] ) && !is_null( $this->mUserName ) ) {
612 $queries['user'] = $this->mUserName;
613 }
614
615 return $queries;
616 }
617
618 function getTitle() {
619 return SpecialPage::getTitleFor( 'Listfiles' );
620 }
621 }