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