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