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
25 use MediaWiki\MediaWikiServices
;
26 use Wikimedia\Rdbms\IResultWrapper
;
27 use Wikimedia\Rdbms\FakeResultWrapper
;
29 class ImageListPager
extends TablePager
{
31 protected $mFieldNames = null;
33 // Subclasses should override buildQueryConds instead of using $mQueryConds variable.
34 protected $mQueryConds = [];
36 protected $mUserName = null;
43 protected $mUser = null;
45 protected $mSearch = '';
47 protected $mIncluding = false;
49 protected $mShowAll = false;
51 protected $mTableName = 'image';
53 public function __construct( IContextSource
$context, $userName = null, $search = '',
54 $including = false, $showAll = false
56 parent
::__construct( $context );
58 $this->mIncluding
= $including;
59 $this->mShowAll
= $showAll;
61 if ( $userName !== null && $userName !== '' ) {
62 $nt = Title
::makeTitleSafe( NS_USER
, $userName );
63 if ( is_null( $nt ) ) {
64 $this->outputUserDoesNotExist( $userName );
66 $this->mUserName
= $nt->getText();
67 $user = User
::newFromName( $this->mUserName
, false );
71 if ( !$user ||
( $user->isAnon() && !User
::isIP( $user->getName() ) ) ) {
72 $this->outputUserDoesNotExist( $userName );
77 if ( $search !== '' && !$this->getConfig()->get( 'MiserMode' ) ) {
78 $this->mSearch
= $search;
79 $nt = Title
::newFromText( $this->mSearch
);
82 $dbr = wfGetDB( DB_REPLICA
);
83 $this->mQueryConds
[] = 'LOWER(img_name)' .
84 $dbr->buildLike( $dbr->anyString(),
85 strtolower( $nt->getDBkey() ), $dbr->anyString() );
90 if ( $this->getRequest()->getText( 'sort', 'img_date' ) == 'img_date' ) {
91 $this->mDefaultDirection
= IndexPager
::DIR_DESCENDING
;
93 $this->mDefaultDirection
= IndexPager
::DIR_ASCENDING
;
96 $this->mDefaultDirection
= IndexPager
::DIR_DESCENDING
;
101 * Get the user relevant to the ImageList
105 function getRelevantUser() {
110 * Add a message to the output stating that the user doesn't exist
112 * @param string $userName Unescaped user name
114 protected function outputUserDoesNotExist( $userName ) {
115 $this->getOutput()->wrapWikiMsg(
116 "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
118 'listfiles-userdoesnotexist',
119 wfEscapeWikiText( $userName ),
125 * Build the where clause of the query.
127 * Replaces the older mQueryConds member variable.
128 * @param string $table Either "image" or "oldimage"
129 * @return array The query conditions.
131 protected function buildQueryConds( $table ) {
132 $prefix = $table === 'image' ?
'img' : 'oi';
135 if ( !is_null( $this->mUserName
) ) {
136 // getQueryInfoReal() should have handled the tables and joins.
137 $dbr = wfGetDB( DB_REPLICA
);
138 $actorWhere = ActorMigration
::newMigration()->getWhere(
141 User
::newFromName( $this->mUserName
, false ),
142 // oldimage doesn't have an index on oi_user, while image does. Set $useId accordingly.
145 $conds[] = $actorWhere['conds'];
148 if ( $this->mSearch
!== '' ) {
149 $nt = Title
::newFromText( $this->mSearch
);
151 $dbr = wfGetDB( DB_REPLICA
);
152 $conds[] = 'LOWER(' . $prefix . '_name)' .
153 $dbr->buildLike( $dbr->anyString(),
154 strtolower( $nt->getDBkey() ), $dbr->anyString() );
158 if ( $table === 'oldimage' ) {
159 // Don't want to deal with revdel.
160 // Future fixme: Show partial information as appropriate.
161 // Would have to be careful about filtering by username when username is deleted.
162 $conds['oi_deleted'] = 0;
165 // Add mQueryConds in case anyone was subclassing and using the old variable.
166 return $conds +
$this->mQueryConds
;
170 * The array keys (but not the array values) are used in sql. Phan
171 * gets confused by this, so mark this method as being ok for sql in general.
172 * @return-taint onlysafefor_sql
175 function getFieldNames() {
176 if ( !$this->mFieldNames
) {
177 $this->mFieldNames
= [
178 'img_timestamp' => $this->msg( 'listfiles_date' )->text(),
179 'img_name' => $this->msg( 'listfiles_name' )->text(),
180 'thumb' => $this->msg( 'listfiles_thumb' )->text(),
181 'img_size' => $this->msg( 'listfiles_size' )->text(),
183 if ( is_null( $this->mUserName
) ) {
184 // Do not show username if filtering by username
185 $this->mFieldNames
['img_user_text'] = $this->msg( 'listfiles_user' )->text();
187 // img_description down here, in order so that its still after the username field.
188 $this->mFieldNames
['img_description'] = $this->msg( 'listfiles_description' )->text();
190 if ( !$this->getConfig()->get( 'MiserMode' ) && !$this->mShowAll
) {
191 $this->mFieldNames
['count'] = $this->msg( 'listfiles_count' )->text();
193 if ( $this->mShowAll
) {
194 $this->mFieldNames
['top'] = $this->msg( 'listfiles-latestversion' )->text();
198 return $this->mFieldNames
;
201 function isFieldSortable( $field ) {
202 if ( $this->mIncluding
) {
205 $sortable = [ 'img_timestamp', 'img_name', 'img_size' ];
206 /* For reference, the indicies we can use for sorting are:
207 * On the image table: img_user_timestamp/img_usertext_timestamp/img_actor_timestamp,
208 * img_size, img_timestamp
209 * On oldimage: oi_usertext_timestamp/oi_actor_timestamp, oi_name_timestamp
211 * In particular that means we cannot sort by timestamp when not filtering
212 * by user and including old images in the results. Which is sad.
214 if ( $this->getConfig()->get( 'MiserMode' ) && !is_null( $this->mUserName
) ) {
215 // If we're sorting by user, the index only supports sorting by time.
216 if ( $field === 'img_timestamp' ) {
221 } elseif ( $this->getConfig()->get( 'MiserMode' )
222 && $this->mShowAll
/* && mUserName === null */
224 // no oi_timestamp index, so only alphabetical sorting in this case.
225 if ( $field === 'img_name' ) {
232 return in_array( $field, $sortable );
235 function getQueryInfo() {
236 // Hacky Hacky Hacky - I want to get query info
237 // for two different tables, without reimplementing
239 $qi = $this->getQueryInfoReal( $this->mTableName
);
245 * Actually get the query info.
247 * This is to allow displaying both stuff from image and oldimage table.
249 * This is a bit hacky.
251 * @param string $table Either 'image' or 'oldimage'
252 * @return array Query info
254 protected function getQueryInfoReal( $table ) {
255 $dbr = wfGetDB( DB_REPLICA
);
256 $prefix = $table === 'oldimage' ?
'oi' : 'img';
258 $tables = [ $table ];
259 $fields = array_keys( $this->getFieldNames() );
260 $fields = array_combine( $fields, $fields );
261 unset( $fields['img_description'] );
262 unset( $fields['img_user_text'] );
264 if ( $table === 'oldimage' ) {
265 foreach ( $fields as $id => $field ) {
266 if ( substr( $id, 0, 4 ) === 'img_' ) {
267 $fields[$id] = $prefix . substr( $field, 3 );
270 $fields['top'] = $dbr->addQuotes( 'no' );
271 } elseif ( $this->mShowAll
) {
272 $fields['top'] = $dbr->addQuotes( 'yes' );
274 $fields['thumb'] = $prefix . '_name';
276 $options = $join_conds = [];
279 $commentQuery = CommentStore
::getStore()->getJoin( $prefix . '_description' );
280 $tables +
= $commentQuery['tables'];
281 $fields +
= $commentQuery['fields'];
282 $join_conds +
= $commentQuery['joins'];
283 $fields['description_field'] = $dbr->addQuotes( "{$prefix}_description" );
286 $actorQuery = ActorMigration
::newMigration()->getJoin( $prefix . '_user' );
287 $tables +
= $actorQuery['tables'];
288 $join_conds +
= $actorQuery['joins'];
289 $fields['img_user'] = $actorQuery['fields'][$prefix . '_user'];
290 $fields['img_user_text'] = $actorQuery['fields'][$prefix . '_user_text'];
291 $fields['img_actor'] = $actorQuery['fields'][$prefix . '_actor'];
293 # Depends on $wgMiserMode
294 # Will also not happen if mShowAll is true.
295 if ( isset( $fields['count'] ) ) {
296 $fields['count'] = $dbr->buildSelectSubquery(
298 'COUNT(oi_archive_name)',
299 'oi_name = img_name',
307 'conds' => $this->buildQueryConds( $table ),
308 'options' => $options,
309 'join_conds' => $join_conds
314 * Override reallyDoQuery to mix together two queries.
316 * @note $asc is named $descending in IndexPager base class. However
317 * it is true when the order is ascending, and false when the order
318 * is descending, so I renamed it to $asc here.
321 * @param bool $order IndexPager::QUERY_ASCENDING or IndexPager::QUERY_DESCENDING
322 * @return FakeResultWrapper
323 * @throws MWException
325 function reallyDoQuery( $offset, $limit, $order ) {
326 $prevTableName = $this->mTableName
;
327 $this->mTableName
= 'image';
328 list( $tables, $fields, $conds, $fname, $options, $join_conds ) =
329 $this->buildQueryInfo( $offset, $limit, $order );
330 $imageRes = $this->mDb
->select( $tables, $fields, $conds, $fname, $options, $join_conds );
331 $this->mTableName
= $prevTableName;
333 if ( !$this->mShowAll
) {
337 $this->mTableName
= 'oldimage';
340 $oldIndex = $this->mIndexField
;
341 if ( substr( $this->mIndexField
, 0, 4 ) !== 'img_' ) {
342 throw new MWException( "Expected to be sorting on an image table field" );
344 $this->mIndexField
= 'oi_' . substr( $this->mIndexField
, 4 );
346 list( $tables, $fields, $conds, $fname, $options, $join_conds ) =
347 $this->buildQueryInfo( $offset, $limit, $order );
348 $oldimageRes = $this->mDb
->select( $tables, $fields, $conds, $fname, $options, $join_conds );
350 $this->mTableName
= $prevTableName;
351 $this->mIndexField
= $oldIndex;
353 return $this->combineResult( $imageRes, $oldimageRes, $limit, $order );
357 * Combine results from 2 tables.
359 * Note: This will throw away some results
361 * @param IResultWrapper $res1
362 * @param IResultWrapper $res2
364 * @param bool $ascending See note about $asc in $this->reallyDoQuery
365 * @return FakeResultWrapper $res1 and $res2 combined
367 protected function combineResult( $res1, $res2, $limit, $ascending ) {
370 $topRes1 = $res1->next();
371 $topRes2 = $res2->next();
373 for ( $i = 0; $i < $limit && $topRes1 && $topRes2; $i++
) {
374 if ( strcmp( $topRes1->{$this->mIndexField
}, $topRes2->{$this->mIndexField
} ) > 0 ) {
376 $resultArray[] = $topRes1;
377 $topRes1 = $res1->next();
379 $resultArray[] = $topRes2;
380 $topRes2 = $res2->next();
382 } elseif ( !$ascending ) {
383 $resultArray[] = $topRes2;
384 $topRes2 = $res2->next();
386 $resultArray[] = $topRes1;
387 $topRes1 = $res1->next();
391 for ( ; $i < $limit && $topRes1; $i++
) {
392 $resultArray[] = $topRes1;
393 $topRes1 = $res1->next();
396 for ( ; $i < $limit && $topRes2; $i++
) {
397 $resultArray[] = $topRes2;
398 $topRes2 = $res2->next();
401 return new FakeResultWrapper( $resultArray );
404 function getDefaultSort() {
405 if ( $this->mShowAll
&& $this->getConfig()->get( 'MiserMode' ) && is_null( $this->mUserName
) ) {
406 // Unfortunately no index on oi_timestamp.
409 return 'img_timestamp';
413 protected function doBatchLookups() {
415 $this->mResult
->seek( 0 );
416 foreach ( $this->mResult
as $row ) {
417 $userIds[] = $row->img_user
;
419 # Do a link batch query for names and userpages
420 UserCache
::singleton()->doQuery( $userIds, [ 'userpage' ], __METHOD__
);
424 * @param string $field
425 * @param string $value
426 * @return Message|string|int The return type depends on the value of $field:
428 * - img_timestamp: string
430 * - img_user_text: string
432 * - img_description: string
435 * @throws MWException
437 function formatValue( $field, $value ) {
438 $services = MediaWikiServices
::getInstance();
439 $linkRenderer = $this->getLinkRenderer();
442 $opt = [ 'time' => wfTimestamp( TS_MW
, $this->mCurrentRow
->img_timestamp
) ];
443 $file = RepoGroup
::singleton()->getLocalRepo()->findFile( $value, $opt );
444 // If statement for paranoia
446 $thumb = $file->transform( [ 'width' => 180, 'height' => 360 ] );
448 return $thumb->toHtml( [ 'desc-link' => true ] );
450 return $this->msg( 'thumbnail_error', '' )->escaped();
453 return htmlspecialchars( $value );
455 case 'img_timestamp':
456 // We may want to make this a link to the "old" version when displaying old files
457 return htmlspecialchars( $this->getLanguage()->userTimeAndDate( $value, $this->getUser() ) );
459 static $imgfile = null;
460 if ( $imgfile === null ) {
461 $imgfile = $this->msg( 'imgfile' )->text();
464 // Weird files can maybe exist? T24227
465 $filePage = Title
::makeTitleSafe( NS_FILE
, $value );
467 $link = $linkRenderer->makeKnownLink(
471 $download = Xml
::element(
473 [ 'href' => $services->getRepoGroup()->getLocalRepo()->newFile( $filePage )->getUrl() ],
476 $download = $this->msg( 'parentheses' )->rawParams( $download )->escaped();
478 // Add delete links if allowed
479 // From https://github.com/Wikia/app/pull/3859
480 $permissionManager = $services->getPermissionManager();
482 if ( $permissionManager->userCan( 'delete', $this->getUser(), $filePage ) ) {
483 $deleteMsg = $this->msg( 'listfiles-delete' )->text();
485 $delete = $linkRenderer->makeKnownLink(
486 $filePage, $deleteMsg, [], [ 'action' => 'delete' ]
488 $delete = $this->msg( 'parentheses' )->rawParams( $delete )->escaped();
490 return "$link $download $delete";
493 return "$link $download";
495 return htmlspecialchars( $value );
497 case 'img_user_text':
498 if ( $this->mCurrentRow
->img_user
) {
499 $name = User
::whoIs( $this->mCurrentRow
->img_user
);
500 $link = $linkRenderer->makeLink(
501 Title
::makeTitle( NS_USER
, $name ),
505 $link = htmlspecialchars( $value );
510 return htmlspecialchars( $this->getLanguage()->formatSize( $value ) );
511 case 'img_description':
512 $field = $this->mCurrentRow
->description_field
;
513 $value = CommentStore
::getStore()->getComment( $field, $this->mCurrentRow
)->text
;
514 return Linker
::formatComment( $value );
516 return $this->getLanguage()->formatNum( intval( $value ) +
1 );
518 // Messages: listfiles-latestversion-yes, listfiles-latestversion-no
519 return $this->msg( 'listfiles-latestversion-' . $value )->escaped();
521 throw new MWException( "Unknown field '$field'" );
526 $formDescriptor = [];
527 $formDescriptor['limit'] = [
530 'label-message' => 'table_pager_limit_label',
531 'options' => $this->getLimitSelectList(),
532 'default' => $this->mLimit
,
535 if ( !$this->getConfig()->get( 'MiserMode' ) ) {
536 $formDescriptor['ilsearch'] = [
538 'name' => 'ilsearch',
539 'id' => 'mw-ilsearch',
540 'label-message' => 'listfiles_search_for',
541 'default' => $this->mSearch
,
543 'maxlength' => '255',
547 $formDescriptor['user'] = [
550 'id' => 'mw-listfiles-user',
551 'label-message' => 'username',
552 'default' => $this->mUserName
,
554 'maxlength' => '255',
557 $formDescriptor['ilshowall'] = [
559 'name' => 'ilshowall',
560 'id' => 'mw-listfiles-show-all',
561 'label-message' => 'listfiles-show-all',
562 'default' => $this->mShowAll
,
565 $query = $this->getRequest()->getQueryValues();
566 unset( $query['title'] );
567 unset( $query['limit'] );
568 unset( $query['ilsearch'] );
569 unset( $query['ilshowall'] );
570 unset( $query['user'] );
572 $htmlForm = HTMLForm
::factory( 'ooui', $formDescriptor, $this->getContext() );
575 ->setId( 'mw-listfiles-form' )
576 ->setTitle( $this->getTitle() )
577 ->setSubmitTextMsg( 'table_pager_limit_submit' )
578 ->setWrapperLegendMsg( 'listfiles' )
579 ->addHiddenFields( $query )
584 protected function getTableClass() {
585 return parent
::getTableClass() . ' listfiles';
588 protected function getNavClass() {
589 return parent
::getNavClass() . ' listfiles_nav';
592 protected function getSortHeaderClass() {
593 return parent
::getSortHeaderClass() . ' listfiles_sort';
596 function getPagingQueries() {
597 $queries = parent
::getPagingQueries();
598 if ( !is_null( $this->mUserName
) ) {
599 # Append the username to the query string
600 foreach ( $queries as &$query ) {
601 if ( $query !== false ) {
602 $query['user'] = $this->mUserName
;
610 function getDefaultQuery() {
611 $queries = parent
::getDefaultQuery();
612 if ( !isset( $queries['user'] ) && !is_null( $this->mUserName
) ) {
613 $queries['user'] = $this->mUserName
;
619 function getTitle() {
620 return SpecialPage
::getTitleFor( 'Listfiles' );