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