Merge "DatabaseMssql: Don't duplicate body of makeList()"
[mediawiki.git] / includes / specials / SpecialListfiles.php
blob760704d90e183d3d68c38370a650e23d81355469
1 <?php
2 /**
3 * Implements Special:Listfiles
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.
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.
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
20 * @file
21 * @ingroup SpecialPage
24 class SpecialListFiles extends IncludableSpecialPage {
25 public function __construct() {
26 parent::__construct( 'Listfiles' );
29 public function execute( $par ) {
30 $this->setHeaders();
31 $this->outputHeader();
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 );
43 $pager = new ImageListPager(
44 $this->getContext(),
45 $userName,
46 $search,
47 $this->including(),
48 $showAll
51 $out = $this->getOutput();
52 if ( $this->including() ) {
53 $out->addParserOutputContent( $pager->getBodyOutput() );
54 } else {
55 $out->addHTML( $pager->getForm() );
56 $out->addParserOutputContent( $pager->getFullOutput() );
60 protected function getGroupName() {
61 return 'media';
65 /**
66 * @ingroup SpecialPage Pager
68 class ImageListPager extends TablePager {
69 protected $mFieldNames = null;
71 // Subclasses should override buildQueryConds instead of using $mQueryConds variable.
72 protected $mQueryConds = array();
74 protected $mUserName = null;
76 protected $mSearch = '';
78 protected $mIncluding = false;
80 protected $mShowAll = false;
82 protected $mTableName = 'image';
84 function __construct( IContextSource $context, $userName = null, $search = '',
85 $including = false, $showAll = false
86 ) {
87 $this->mIncluding = $including;
88 $this->mShowAll = $showAll;
90 if ( $userName !== null && $userName !== '' ) {
91 $nt = Title::newFromText( $userName, NS_USER );
92 if ( !is_null( $nt ) ) {
93 $this->mUserName = $nt->getText();
97 if ( $search !== '' && !$this->getConfig()->get( 'MiserMode' ) ) {
98 $this->mSearch = $search;
99 $nt = Title::newFromURL( $this->mSearch );
101 if ( $nt ) {
102 $dbr = wfGetDB( DB_SLAVE );
103 $this->mQueryConds[] = 'LOWER(img_name)' .
104 $dbr->buildLike( $dbr->anyString(),
105 strtolower( $nt->getDBkey() ), $dbr->anyString() );
109 if ( !$including ) {
110 if ( $context->getRequest()->getText( 'sort', 'img_date' ) == 'img_date' ) {
111 $this->mDefaultDirection = IndexPager::DIR_DESCENDING;
112 } else {
113 $this->mDefaultDirection = IndexPager::DIR_ASCENDING;
115 } else {
116 $this->mDefaultDirection = IndexPager::DIR_DESCENDING;
119 parent::__construct( $context );
123 * Build the where clause of the query.
125 * Replaces the older mQueryConds member variable.
126 * @param string $table Either "image" or "oldimage"
127 * @return array The query conditions.
129 protected function buildQueryConds( $table ) {
130 $prefix = $table === 'image' ? 'img' : 'oi';
131 $conds = array();
133 if ( !is_null( $this->mUserName ) ) {
134 $conds[$prefix . '_user_text'] = $this->mUserName;
137 if ( $this->mSearch !== '' ) {
138 $nt = Title::newFromURL( $this->mSearch );
139 if ( $nt ) {
140 $dbr = wfGetDB( DB_SLAVE );
141 $conds[] = 'LOWER(' . $prefix . '_name)' .
142 $dbr->buildLike( $dbr->anyString(),
143 strtolower( $nt->getDBkey() ), $dbr->anyString() );
147 if ( $table === 'oldimage' ) {
148 // Don't want to deal with revdel.
149 // Future fixme: Show partial information as appropriate.
150 // Would have to be careful about filtering by username when username is deleted.
151 $conds['oi_deleted'] = 0;
154 // Add mQueryConds in case anyone was subclassing and using the old variable.
155 return $conds + $this->mQueryConds;
159 * @return array
161 function getFieldNames() {
162 if ( !$this->mFieldNames ) {
163 $this->mFieldNames = array(
164 'img_timestamp' => $this->msg( 'listfiles_date' )->text(),
165 'img_name' => $this->msg( 'listfiles_name' )->text(),
166 'thumb' => $this->msg( 'listfiles_thumb' )->text(),
167 'img_size' => $this->msg( 'listfiles_size' )->text(),
169 if ( is_null( $this->mUserName ) ) {
170 // Do not show username if filtering by username
171 $this->mFieldNames['img_user_text'] = $this->msg( 'listfiles_user' )->text();
173 // img_description down here, in order so that its still after the username field.
174 $this->mFieldNames['img_description'] = $this->msg( 'listfiles_description' )->text();
176 if ( !$this->getConfig()->get( 'MiserMode' ) && !$this->mShowAll ) {
177 $this->mFieldNames['count'] = $this->msg( 'listfiles_count' )->text();
179 if ( $this->mShowAll ) {
180 $this->mFieldNames['top'] = $this->msg( 'listfiles-latestversion' )->text();
184 return $this->mFieldNames;
187 function isFieldSortable( $field ) {
188 if ( $this->mIncluding ) {
189 return false;
191 $sortable = array( 'img_timestamp', 'img_name', 'img_size' );
192 /* For reference, the indicies we can use for sorting are:
193 * On the image table: img_usertext_timestamp, img_size, img_timestamp
194 * On oldimage: oi_usertext_timestamp, oi_name_timestamp
196 * In particular that means we cannot sort by timestamp when not filtering
197 * by user and including old images in the results. Which is sad.
199 if ( $this->getConfig()->get( 'MiserMode' ) && !is_null( $this->mUserName ) ) {
200 // If we're sorting by user, the index only supports sorting by time.
201 if ( $field === 'img_timestamp' ) {
202 return true;
203 } else {
204 return false;
206 } elseif ( $this->getConfig()->get( 'MiserMode' )
207 && $this->mShowAll /* && mUserName === null */
209 // no oi_timestamp index, so only alphabetical sorting in this case.
210 if ( $field === 'img_name' ) {
211 return true;
212 } else {
213 return false;
217 return in_array( $field, $sortable );
220 function getQueryInfo() {
221 // Hacky Hacky Hacky - I want to get query info
222 // for two different tables, without reimplementing
223 // the pager class.
224 $qi = $this->getQueryInfoReal( $this->mTableName );
226 return $qi;
230 * Actually get the query info.
232 * This is to allow displaying both stuff from image and oldimage table.
234 * This is a bit hacky.
236 * @param string $table Either 'image' or 'oldimage'
237 * @return array Query info
239 protected function getQueryInfoReal( $table ) {
240 $prefix = $table === 'oldimage' ? 'oi' : 'img';
242 $tables = array( $table );
243 $fields = array_keys( $this->getFieldNames() );
245 if ( $table === 'oldimage' ) {
246 foreach ( $fields as $id => &$field ) {
247 if ( substr( $field, 0, 4 ) !== 'img_' ) {
248 continue;
250 $field = $prefix . substr( $field, 3 ) . ' AS ' . $field;
252 $fields[array_search( 'top', $fields )] = "'no' AS top";
253 } else {
254 if ( $this->mShowAll ) {
255 $fields[array_search( 'top', $fields )] = "'yes' AS top";
258 $fields[] = $prefix . '_user AS img_user';
259 $fields[array_search( 'thumb', $fields )] = $prefix . '_name AS thumb';
261 $options = $join_conds = array();
263 # Depends on $wgMiserMode
264 # Will also not happen if mShowAll is true.
265 if ( isset( $this->mFieldNames['count'] ) ) {
266 $tables[] = 'oldimage';
268 # Need to rewrite this one
269 foreach ( $fields as &$field ) {
270 if ( $field == 'count' ) {
271 $field = 'COUNT(oi_archive_name) AS count';
274 unset( $field );
276 $dbr = wfGetDB( DB_SLAVE );
277 if ( $dbr->implicitGroupby() ) {
278 $options = array( 'GROUP BY' => 'img_name' );
279 } else {
280 $columnlist = preg_grep( '/^img/', array_keys( $this->getFieldNames() ) );
281 $options = array( 'GROUP BY' => array_merge( array( 'img_user' ), $columnlist ) );
283 $join_conds = array( 'oldimage' => array( 'LEFT JOIN', 'oi_name = img_name' ) );
286 return array(
287 'tables' => $tables,
288 'fields' => $fields,
289 'conds' => $this->buildQueryConds( $table ),
290 'options' => $options,
291 'join_conds' => $join_conds
296 * Override reallyDoQuery to mix together two queries.
298 * @note $asc is named $descending in IndexPager base class. However
299 * it is true when the order is ascending, and false when the order
300 * is descending, so I renamed it to $asc here.
301 * @param int $offset
302 * @param int $limit
303 * @param bool $asc
304 * @return array
305 * @throws MWException
307 function reallyDoQuery( $offset, $limit, $asc ) {
308 $prevTableName = $this->mTableName;
309 $this->mTableName = 'image';
310 list( $tables, $fields, $conds, $fname, $options, $join_conds ) =
311 $this->buildQueryInfo( $offset, $limit, $asc );
312 $imageRes = $this->mDb->select( $tables, $fields, $conds, $fname, $options, $join_conds );
313 $this->mTableName = $prevTableName;
315 if ( !$this->mShowAll ) {
316 return $imageRes;
319 $this->mTableName = 'oldimage';
321 # Hacky...
322 $oldIndex = $this->mIndexField;
323 if ( substr( $this->mIndexField, 0, 4 ) !== 'img_' ) {
324 throw new MWException( "Expected to be sorting on an image table field" );
326 $this->mIndexField = 'oi_' . substr( $this->mIndexField, 4 );
328 list( $tables, $fields, $conds, $fname, $options, $join_conds ) =
329 $this->buildQueryInfo( $offset, $limit, $asc );
330 $oldimageRes = $this->mDb->select( $tables, $fields, $conds, $fname, $options, $join_conds );
332 $this->mTableName = $prevTableName;
333 $this->mIndexField = $oldIndex;
335 return $this->combineResult( $imageRes, $oldimageRes, $limit, $asc );
339 * Combine results from 2 tables.
341 * Note: This will throw away some results
343 * @param ResultWrapper $res1
344 * @param ResultWrapper $res2
345 * @param int $limit
346 * @param bool $ascending See note about $asc in $this->reallyDoQuery
347 * @return FakeResultWrapper $res1 and $res2 combined
349 protected function combineResult( $res1, $res2, $limit, $ascending ) {
350 $res1->rewind();
351 $res2->rewind();
352 $topRes1 = $res1->next();
353 $topRes2 = $res2->next();
354 $resultArray = array();
355 for ( $i = 0; $i < $limit && $topRes1 && $topRes2; $i++ ) {
356 if ( strcmp( $topRes1->{$this->mIndexField}, $topRes2->{$this->mIndexField} ) > 0 ) {
357 if ( !$ascending ) {
358 $resultArray[] = $topRes1;
359 $topRes1 = $res1->next();
360 } else {
361 $resultArray[] = $topRes2;
362 $topRes2 = $res2->next();
364 } else {
365 if ( !$ascending ) {
366 $resultArray[] = $topRes2;
367 $topRes2 = $res2->next();
368 } else {
369 $resultArray[] = $topRes1;
370 $topRes1 = $res1->next();
375 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
376 for ( ; $i < $limit && $topRes1; $i++ ) {
377 // @codingStandardsIgnoreEnd
378 $resultArray[] = $topRes1;
379 $topRes1 = $res1->next();
382 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
383 for ( ; $i < $limit && $topRes2; $i++ ) {
384 // @codingStandardsIgnoreEnd
385 $resultArray[] = $topRes2;
386 $topRes2 = $res2->next();
389 return new FakeResultWrapper( $resultArray );
392 function getDefaultSort() {
393 if ( $this->mShowAll && $this->getConfig()->get( 'MiserMode' ) && is_null( $this->mUserName ) ) {
394 // Unfortunately no index on oi_timestamp.
395 return 'img_name';
396 } else {
397 return 'img_timestamp';
401 function doBatchLookups() {
402 $userIds = array();
403 $this->mResult->seek( 0 );
404 foreach ( $this->mResult as $row ) {
405 $userIds[] = $row->img_user;
407 # Do a link batch query for names and userpages
408 UserCache::singleton()->doQuery( $userIds, array( 'userpage' ), __METHOD__ );
412 * @param string $field
413 * @param string $value
414 * @return Message|string|int The return type depends on the value of $field:
415 * - thumb: string
416 * - img_timestamp: string
417 * - img_name: string
418 * - img_user_text: string
419 * - img_size: string
420 * - img_description: string
421 * - count: int
422 * - top: Message
423 * @throws MWException
425 function formatValue( $field, $value ) {
426 switch ( $field ) {
427 case 'thumb':
428 $opt = array( 'time' => $this->mCurrentRow->img_timestamp );
429 $file = RepoGroup::singleton()->getLocalRepo()->findFile( $value, $opt );
430 // If statement for paranoia
431 if ( $file ) {
432 $thumb = $file->transform( array( 'width' => 180, 'height' => 360 ) );
434 return $thumb->toHtml( array( 'desc-link' => true ) );
435 } else {
436 return htmlspecialchars( $value );
438 case 'img_timestamp':
439 // We may want to make this a link to the "old" version when displaying old files
440 return htmlspecialchars( $this->getLanguage()->userTimeAndDate( $value, $this->getUser() ) );
441 case 'img_name':
442 static $imgfile = null;
443 if ( $imgfile === null ) {
444 $imgfile = $this->msg( 'imgfile' )->text();
447 // Weird files can maybe exist? Bug 22227
448 $filePage = Title::makeTitleSafe( NS_FILE, $value );
449 if ( $filePage ) {
450 $link = Linker::linkKnown(
451 $filePage,
452 htmlspecialchars( $filePage->getText() )
454 $download = Xml::element( 'a',
455 array( 'href' => wfLocalFile( $filePage )->getURL() ),
456 $imgfile
458 $download = $this->msg( 'parentheses' )->rawParams( $download )->escaped();
460 // Add delete links if allowed
461 // From https://github.com/Wikia/app/pull/3859
462 if ( $filePage->userCan( 'delete', $this->getUser() ) ) {
463 $deleteMsg = $this->msg( 'listfiles-delete' )->escaped();
465 $delete = Linker::linkKnown(
466 $filePage, $deleteMsg, array(), array( 'action' => 'delete' )
468 $delete = $this->msg( 'parentheses' )->rawParams( $delete )->escaped();
470 return "$link $download $delete";
473 return "$link $download";
474 } else {
475 return htmlspecialchars( $value );
477 case 'img_user_text':
478 if ( $this->mCurrentRow->img_user ) {
479 $name = User::whoIs( $this->mCurrentRow->img_user );
480 $link = Linker::link(
481 Title::makeTitle( NS_USER, $name ),
482 htmlspecialchars( $name )
484 } else {
485 $link = htmlspecialchars( $value );
488 return $link;
489 case 'img_size':
490 return htmlspecialchars( $this->getLanguage()->formatSize( $value ) );
491 case 'img_description':
492 return Linker::formatComment( $value );
493 case 'count':
494 return intval( $value ) + 1;
495 case 'top':
496 // Messages: listfiles-latestversion-yes, listfiles-latestversion-no
497 return $this->msg( 'listfiles-latestversion-' . $value );
498 default:
499 throw new MWException( "Unknown field '$field'" );
503 function getForm() {
504 $fields = array();
505 $fields['limit'] = array(
506 'type' => 'select',
507 'name' => 'limit',
508 'label-message' => 'table_pager_limit_label',
509 'options' => $this->getLimitSelectList(),
510 'default' => $this->mLimit,
513 if ( !$this->getConfig()->get( 'MiserMode' ) ) {
514 $fields['ilsearch'] = array(
515 'type' => 'text',
516 'name' => 'ilsearch',
517 'id' => 'mw-ilsearch',
518 'label-message' => 'listfiles_search_for',
519 'default' => $this->mSearch,
520 'size' => '40',
521 'maxlength' => '255',
525 $this->getOutput()->addModules( 'mediawiki.userSuggest' );
526 $fields['user'] = array(
527 'type' => 'text',
528 'name' => 'user',
529 'id' => 'mw-listfiles-user',
530 'label-message' => 'username',
531 'default' => $this->mUserName,
532 'size' => '40',
533 'maxlength' => '255',
534 'cssclass' => 'mw-autocomplete-user', // used by mediawiki.userSuggest
537 $fields['ilshowall'] = array(
538 'type' => 'check',
539 'name' => 'ilshowall',
540 'id' => 'mw-listfiles-show-all',
541 'label-message' => 'listfiles-show-all',
542 'default' => $this->mShowAll,
545 $query = $this->getRequest()->getQueryValues();
546 unset( $query['title'] );
547 unset( $query['limit'] );
548 unset( $query['ilsearch'] );
549 unset( $query['ilshowall'] );
550 unset( $query['user'] );
552 $form = new HTMLForm( $fields, $this->getContext() );
554 $form->setMethod( 'get' );
555 $form->setTitle( $this->getTitle() );
556 $form->setId( 'mw-listfiles-form' );
557 $form->setWrapperLegendMsg( 'listfiles' );
558 $form->setSubmitTextMsg( 'table_pager_limit_submit' );
559 $form->addHiddenFields( $query );
561 $form->prepareForm();
562 $form->displayForm( '' );
565 function getTableClass() {
566 return parent::getTableClass() . ' listfiles';
569 function getNavClass() {
570 return parent::getNavClass() . ' listfiles_nav';
573 function getSortHeaderClass() {
574 return parent::getSortHeaderClass() . ' listfiles_sort';
577 function getPagingQueries() {
578 $queries = parent::getPagingQueries();
579 if ( !is_null( $this->mUserName ) ) {
580 # Append the username to the query string
581 foreach ( $queries as &$query ) {
582 if ( $query !== false ) {
583 $query['user'] = $this->mUserName;
588 return $queries;
591 function getDefaultQuery() {
592 $queries = parent::getDefaultQuery();
593 if ( !isset( $queries['user'] ) && !is_null( $this->mUserName ) ) {
594 $queries['user'] = $this->mUserName;
597 return $queries;
600 function getTitle() {
601 return SpecialPage::getTitleFor( 'Listfiles' );