AuthManager: Break AuthPlugin::addUser more explicitly
[mediawiki.git] / includes / specials / pagers / ImageListPager.php
blob40706faaa02a3ebe25c118ec8eed004056261f7d
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.
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.
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
18 * @file
19 * @ingroup Pager
22 /**
23 * @ingroup Pager
25 class ImageListPager extends TablePager {
27 protected $mFieldNames = null;
29 // Subclasses should override buildQueryConds instead of using $mQueryConds variable.
30 protected $mQueryConds = [];
32 protected $mUserName = null;
34 /**
35 * The relevant user
37 * @var User|null
39 protected $mUser = null;
41 protected $mSearch = '';
43 protected $mIncluding = false;
45 protected $mShowAll = false;
47 protected $mTableName = 'image';
49 function __construct( IContextSource $context, $userName = null, $search = '',
50 $including = false, $showAll = false
51 ) {
52 $this->setContext( $context );
53 $this->mIncluding = $including;
54 $this->mShowAll = $showAll;
56 if ( $userName !== null && $userName !== '' ) {
57 $nt = Title::makeTitleSafe( NS_USER, $userName );
58 if ( is_null( $nt ) ) {
59 $this->outputUserDoesNotExist( $userName );
60 } else {
61 $this->mUserName = $nt->getText();
62 $user = User::newFromName( $this->mUserName, false );
63 if ( $user ) {
64 $this->mUser = $user;
66 if ( !$user || ( $user->isAnon() && !User::isIP( $user->getName() ) ) ) {
67 $this->outputUserDoesNotExist( $userName );
72 if ( $search !== '' && !$this->getConfig()->get( 'MiserMode' ) ) {
73 $this->mSearch = $search;
74 $nt = Title::newFromText( $this->mSearch );
76 if ( $nt ) {
77 $dbr = wfGetDB( DB_SLAVE );
78 $this->mQueryConds[] = 'LOWER(img_name)' .
79 $dbr->buildLike( $dbr->anyString(),
80 strtolower( $nt->getDBkey() ), $dbr->anyString() );
84 if ( !$including ) {
85 if ( $this->getRequest()->getText( 'sort', 'img_date' ) == 'img_date' ) {
86 $this->mDefaultDirection = IndexPager::DIR_DESCENDING;
87 } else {
88 $this->mDefaultDirection = IndexPager::DIR_ASCENDING;
90 } else {
91 $this->mDefaultDirection = IndexPager::DIR_DESCENDING;
94 parent::__construct( $context );
97 /**
98 * Get the user relevant to the ImageList
100 * @return User|null
102 function getRelevantUser() {
103 return $this->mUser;
107 * Add a message to the output stating that the user doesn't exist
109 * @param string $userName Unescaped user name
111 protected function outputUserDoesNotExist( $userName ) {
112 $this->getOutput()->wrapWikiMsg(
113 "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
115 'listfiles-userdoesnotexist',
116 wfEscapeWikiText( $userName ),
122 * Build the where clause of the query.
124 * Replaces the older mQueryConds member variable.
125 * @param string $table Either "image" or "oldimage"
126 * @return array The query conditions.
128 protected function buildQueryConds( $table ) {
129 $prefix = $table === 'image' ? 'img' : 'oi';
130 $conds = [];
132 if ( !is_null( $this->mUserName ) ) {
133 $conds[$prefix . '_user_text'] = $this->mUserName;
136 if ( $this->mSearch !== '' ) {
137 $nt = Title::newFromText( $this->mSearch );
138 if ( $nt ) {
139 $dbr = wfGetDB( DB_SLAVE );
140 $conds[] = 'LOWER(' . $prefix . '_name)' .
141 $dbr->buildLike( $dbr->anyString(),
142 strtolower( $nt->getDBkey() ), $dbr->anyString() );
146 if ( $table === 'oldimage' ) {
147 // Don't want to deal with revdel.
148 // Future fixme: Show partial information as appropriate.
149 // Would have to be careful about filtering by username when username is deleted.
150 $conds['oi_deleted'] = 0;
153 // Add mQueryConds in case anyone was subclassing and using the old variable.
154 return $conds + $this->mQueryConds;
158 * @return array
160 function getFieldNames() {
161 if ( !$this->mFieldNames ) {
162 $this->mFieldNames = [
163 'img_timestamp' => $this->msg( 'listfiles_date' )->text(),
164 'img_name' => $this->msg( 'listfiles_name' )->text(),
165 'thumb' => $this->msg( 'listfiles_thumb' )->text(),
166 'img_size' => $this->msg( 'listfiles_size' )->text(),
168 if ( is_null( $this->mUserName ) ) {
169 // Do not show username if filtering by username
170 $this->mFieldNames['img_user_text'] = $this->msg( 'listfiles_user' )->text();
172 // img_description down here, in order so that its still after the username field.
173 $this->mFieldNames['img_description'] = $this->msg( 'listfiles_description' )->text();
175 if ( !$this->getConfig()->get( 'MiserMode' ) && !$this->mShowAll ) {
176 $this->mFieldNames['count'] = $this->msg( 'listfiles_count' )->text();
178 if ( $this->mShowAll ) {
179 $this->mFieldNames['top'] = $this->msg( 'listfiles-latestversion' )->text();
183 return $this->mFieldNames;
186 function isFieldSortable( $field ) {
187 if ( $this->mIncluding ) {
188 return false;
190 $sortable = [ 'img_timestamp', 'img_name', 'img_size' ];
191 /* For reference, the indicies we can use for sorting are:
192 * On the image table: img_usertext_timestamp, img_size, img_timestamp
193 * On oldimage: oi_usertext_timestamp, oi_name_timestamp
195 * In particular that means we cannot sort by timestamp when not filtering
196 * by user and including old images in the results. Which is sad.
198 if ( $this->getConfig()->get( 'MiserMode' ) && !is_null( $this->mUserName ) ) {
199 // If we're sorting by user, the index only supports sorting by time.
200 if ( $field === 'img_timestamp' ) {
201 return true;
202 } else {
203 return false;
205 } elseif ( $this->getConfig()->get( 'MiserMode' )
206 && $this->mShowAll /* && mUserName === null */
208 // no oi_timestamp index, so only alphabetical sorting in this case.
209 if ( $field === 'img_name' ) {
210 return true;
211 } else {
212 return false;
216 return in_array( $field, $sortable );
219 function getQueryInfo() {
220 // Hacky Hacky Hacky - I want to get query info
221 // for two different tables, without reimplementing
222 // the pager class.
223 $qi = $this->getQueryInfoReal( $this->mTableName );
225 return $qi;
229 * Actually get the query info.
231 * This is to allow displaying both stuff from image and oldimage table.
233 * This is a bit hacky.
235 * @param string $table Either 'image' or 'oldimage'
236 * @return array Query info
238 protected function getQueryInfoReal( $table ) {
239 $prefix = $table === 'oldimage' ? 'oi' : 'img';
241 $tables = [ $table ];
242 $fields = array_keys( $this->getFieldNames() );
244 if ( $table === 'oldimage' ) {
245 foreach ( $fields as $id => &$field ) {
246 if ( substr( $field, 0, 4 ) !== 'img_' ) {
247 continue;
249 $field = $prefix . substr( $field, 3 ) . ' AS ' . $field;
251 $fields[array_search( 'top', $fields )] = "'no' AS top";
252 } else {
253 if ( $this->mShowAll ) {
254 $fields[array_search( 'top', $fields )] = "'yes' AS top";
257 $fields[] = $prefix . '_user AS img_user';
258 $fields[array_search( 'thumb', $fields )] = $prefix . '_name AS thumb';
260 $options = $join_conds = [];
262 # Depends on $wgMiserMode
263 # Will also not happen if mShowAll is true.
264 if ( isset( $this->mFieldNames['count'] ) ) {
265 $tables[] = 'oldimage';
267 # Need to rewrite this one
268 foreach ( $fields as &$field ) {
269 if ( $field == 'count' ) {
270 $field = 'COUNT(oi_archive_name) AS count';
273 unset( $field );
275 $dbr = wfGetDB( DB_SLAVE );
276 if ( $dbr->implicitGroupby() ) {
277 $options = [ 'GROUP BY' => 'img_name' ];
278 } else {
279 $columnlist = preg_grep( '/^img/', array_keys( $this->getFieldNames() ) );
280 $options = [ 'GROUP BY' => array_merge( [ 'img_user' ], $columnlist ) ];
282 $join_conds = [ 'oldimage' => [ 'LEFT JOIN', 'oi_name = img_name' ] ];
285 return [
286 'tables' => $tables,
287 'fields' => $fields,
288 'conds' => $this->buildQueryConds( $table ),
289 'options' => $options,
290 'join_conds' => $join_conds
295 * Override reallyDoQuery to mix together two queries.
297 * @note $asc is named $descending in IndexPager base class. However
298 * it is true when the order is ascending, and false when the order
299 * is descending, so I renamed it to $asc here.
300 * @param int $offset
301 * @param int $limit
302 * @param bool $asc
303 * @return array
304 * @throws MWException
306 function reallyDoQuery( $offset, $limit, $asc ) {
307 $prevTableName = $this->mTableName;
308 $this->mTableName = 'image';
309 list( $tables, $fields, $conds, $fname, $options, $join_conds ) =
310 $this->buildQueryInfo( $offset, $limit, $asc );
311 $imageRes = $this->mDb->select( $tables, $fields, $conds, $fname, $options, $join_conds );
312 $this->mTableName = $prevTableName;
314 if ( !$this->mShowAll ) {
315 return $imageRes;
318 $this->mTableName = 'oldimage';
320 # Hacky...
321 $oldIndex = $this->mIndexField;
322 if ( substr( $this->mIndexField, 0, 4 ) !== 'img_' ) {
323 throw new MWException( "Expected to be sorting on an image table field" );
325 $this->mIndexField = 'oi_' . substr( $this->mIndexField, 4 );
327 list( $tables, $fields, $conds, $fname, $options, $join_conds ) =
328 $this->buildQueryInfo( $offset, $limit, $asc );
329 $oldimageRes = $this->mDb->select( $tables, $fields, $conds, $fname, $options, $join_conds );
331 $this->mTableName = $prevTableName;
332 $this->mIndexField = $oldIndex;
334 return $this->combineResult( $imageRes, $oldimageRes, $limit, $asc );
338 * Combine results from 2 tables.
340 * Note: This will throw away some results
342 * @param ResultWrapper $res1
343 * @param ResultWrapper $res2
344 * @param int $limit
345 * @param bool $ascending See note about $asc in $this->reallyDoQuery
346 * @return FakeResultWrapper $res1 and $res2 combined
348 protected function combineResult( $res1, $res2, $limit, $ascending ) {
349 $res1->rewind();
350 $res2->rewind();
351 $topRes1 = $res1->next();
352 $topRes2 = $res2->next();
353 $resultArray = [];
354 for ( $i = 0; $i < $limit && $topRes1 && $topRes2; $i++ ) {
355 if ( strcmp( $topRes1->{$this->mIndexField}, $topRes2->{$this->mIndexField} ) > 0 ) {
356 if ( !$ascending ) {
357 $resultArray[] = $topRes1;
358 $topRes1 = $res1->next();
359 } else {
360 $resultArray[] = $topRes2;
361 $topRes2 = $res2->next();
363 } else {
364 if ( !$ascending ) {
365 $resultArray[] = $topRes2;
366 $topRes2 = $res2->next();
367 } else {
368 $resultArray[] = $topRes1;
369 $topRes1 = $res1->next();
374 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
375 for ( ; $i < $limit && $topRes1; $i++ ) {
376 // @codingStandardsIgnoreEnd
377 $resultArray[] = $topRes1;
378 $topRes1 = $res1->next();
381 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
382 for ( ; $i < $limit && $topRes2; $i++ ) {
383 // @codingStandardsIgnoreEnd
384 $resultArray[] = $topRes2;
385 $topRes2 = $res2->next();
388 return new FakeResultWrapper( $resultArray );
391 function getDefaultSort() {
392 if ( $this->mShowAll && $this->getConfig()->get( 'MiserMode' ) && is_null( $this->mUserName ) ) {
393 // Unfortunately no index on oi_timestamp.
394 return 'img_name';
395 } else {
396 return 'img_timestamp';
400 function doBatchLookups() {
401 $userIds = [];
402 $this->mResult->seek( 0 );
403 foreach ( $this->mResult as $row ) {
404 $userIds[] = $row->img_user;
406 # Do a link batch query for names and userpages
407 UserCache::singleton()->doQuery( $userIds, [ 'userpage' ], __METHOD__ );
411 * @param string $field
412 * @param string $value
413 * @return Message|string|int The return type depends on the value of $field:
414 * - thumb: string
415 * - img_timestamp: string
416 * - img_name: string
417 * - img_user_text: string
418 * - img_size: string
419 * - img_description: string
420 * - count: int
421 * - top: Message
422 * @throws MWException
424 function formatValue( $field, $value ) {
425 switch ( $field ) {
426 case 'thumb':
427 $opt = [ 'time' => wfTimestamp( TS_MW, $this->mCurrentRow->img_timestamp ) ];
428 $file = RepoGroup::singleton()->getLocalRepo()->findFile( $value, $opt );
429 // If statement for paranoia
430 if ( $file ) {
431 $thumb = $file->transform( [ 'width' => 180, 'height' => 360 ] );
433 return $thumb->toHtml( [ 'desc-link' => true ] );
434 } else {
435 return htmlspecialchars( $value );
437 case 'img_timestamp':
438 // We may want to make this a link to the "old" version when displaying old files
439 return htmlspecialchars( $this->getLanguage()->userTimeAndDate( $value, $this->getUser() ) );
440 case 'img_name':
441 static $imgfile = null;
442 if ( $imgfile === null ) {
443 $imgfile = $this->msg( 'imgfile' )->text();
446 // Weird files can maybe exist? Bug 22227
447 $filePage = Title::makeTitleSafe( NS_FILE, $value );
448 if ( $filePage ) {
449 $link = Linker::linkKnown(
450 $filePage,
451 htmlspecialchars( $filePage->getText() )
453 $download = Xml::element( 'a',
454 [ 'href' => wfLocalFile( $filePage )->getUrl() ],
455 $imgfile
457 $download = $this->msg( 'parentheses' )->rawParams( $download )->escaped();
459 // Add delete links if allowed
460 // From https://github.com/Wikia/app/pull/3859
461 if ( $filePage->userCan( 'delete', $this->getUser() ) ) {
462 $deleteMsg = $this->msg( 'listfiles-delete' )->escaped();
464 $delete = Linker::linkKnown(
465 $filePage, $deleteMsg, [], [ 'action' => 'delete' ]
467 $delete = $this->msg( 'parentheses' )->rawParams( $delete )->escaped();
469 return "$link $download $delete";
472 return "$link $download";
473 } else {
474 return htmlspecialchars( $value );
476 case 'img_user_text':
477 if ( $this->mCurrentRow->img_user ) {
478 $name = User::whoIs( $this->mCurrentRow->img_user );
479 $link = Linker::link(
480 Title::makeTitle( NS_USER, $name ),
481 htmlspecialchars( $name )
483 } else {
484 $link = htmlspecialchars( $value );
487 return $link;
488 case 'img_size':
489 return htmlspecialchars( $this->getLanguage()->formatSize( $value ) );
490 case 'img_description':
491 return Linker::formatComment( $value );
492 case 'count':
493 return $this->getLanguage()->formatNum( intval( $value ) + 1 );
494 case 'top':
495 // Messages: listfiles-latestversion-yes, listfiles-latestversion-no
496 return $this->msg( 'listfiles-latestversion-' . $value );
497 default:
498 throw new MWException( "Unknown field '$field'" );
502 function getForm() {
503 $fields = [];
504 $fields['limit'] = [
505 'type' => 'select',
506 'name' => 'limit',
507 'label-message' => 'table_pager_limit_label',
508 'options' => $this->getLimitSelectList(),
509 'default' => $this->mLimit,
512 if ( !$this->getConfig()->get( 'MiserMode' ) ) {
513 $fields['ilsearch'] = [
514 'type' => 'text',
515 'name' => 'ilsearch',
516 'id' => 'mw-ilsearch',
517 'label-message' => 'listfiles_search_for',
518 'default' => $this->mSearch,
519 'size' => '40',
520 'maxlength' => '255',
524 $this->getOutput()->addModules( 'mediawiki.userSuggest' );
525 $fields['user'] = [
526 'type' => 'text',
527 'name' => 'user',
528 'id' => 'mw-listfiles-user',
529 'label-message' => 'username',
530 'default' => $this->mUserName,
531 'size' => '40',
532 'maxlength' => '255',
533 'cssclass' => 'mw-autocomplete-user', // used by mediawiki.userSuggest
536 $fields['ilshowall'] = [
537 'type' => 'check',
538 'name' => 'ilshowall',
539 'id' => 'mw-listfiles-show-all',
540 'label-message' => 'listfiles-show-all',
541 'default' => $this->mShowAll,
544 $query = $this->getRequest()->getQueryValues();
545 unset( $query['title'] );
546 unset( $query['limit'] );
547 unset( $query['ilsearch'] );
548 unset( $query['ilshowall'] );
549 unset( $query['user'] );
551 $form = new HTMLForm( $fields, $this->getContext() );
553 $form->setMethod( 'get' );
554 $form->setTitle( $this->getTitle() );
555 $form->setId( 'mw-listfiles-form' );
556 $form->setWrapperLegendMsg( 'listfiles' );
557 $form->setSubmitTextMsg( 'table_pager_limit_submit' );
558 $form->addHiddenFields( $query );
560 $form->prepareForm();
561 $form->displayForm( '' );
564 protected function getTableClass() {
565 return parent::getTableClass() . ' listfiles';
568 protected function getNavClass() {
569 return parent::getNavClass() . ' listfiles_nav';
572 protected function getSortHeaderClass() {
573 return parent::getSortHeaderClass() . ' listfiles_sort';
576 function getPagingQueries() {
577 $queries = parent::getPagingQueries();
578 if ( !is_null( $this->mUserName ) ) {
579 # Append the username to the query string
580 foreach ( $queries as &$query ) {
581 if ( $query !== false ) {
582 $query['user'] = $this->mUserName;
587 return $queries;
590 function getDefaultQuery() {
591 $queries = parent::getDefaultQuery();
592 if ( !isset( $queries['user'] ) && !is_null( $this->mUserName ) ) {
593 $queries['user'] = $this->mUserName;
596 return $queries;
599 function getTitle() {
600 return SpecialPage::getTitleFor( 'Listfiles' );