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 $this->setContext( $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
;
99 parent
::__construct();
103 * Get the user relevant to the ImageList
107 function getRelevantUser() {
112 * Add a message to the output stating that the user doesn't exist
114 * @param string $userName Unescaped user name
116 protected function outputUserDoesNotExist( $userName ) {
117 $this->getOutput()->wrapWikiMsg(
118 "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
120 'listfiles-userdoesnotexist',
121 wfEscapeWikiText( $userName ),
127 * Build the where clause of the query.
129 * Replaces the older mQueryConds member variable.
130 * @param string $table Either "image" or "oldimage"
131 * @return array The query conditions.
133 protected function buildQueryConds( $table ) {
134 $prefix = $table === 'image' ?
'img' : 'oi';
137 if ( !is_null( $this->mUserName
) ) {
138 // getQueryInfoReal() should have handled the tables and joins.
139 $dbr = wfGetDB( DB_REPLICA
);
140 $actorWhere = ActorMigration
::newMigration()->getWhere(
143 User
::newFromName( $this->mUserName
, false ),
144 // oldimage doesn't have an index on oi_user, while image does. Set $useId accordingly.
147 $conds[] = $actorWhere['conds'];
150 if ( $this->mSearch
!== '' ) {
151 $nt = Title
::newFromText( $this->mSearch
);
153 $dbr = wfGetDB( DB_REPLICA
);
154 $conds[] = 'LOWER(' . $prefix . '_name)' .
155 $dbr->buildLike( $dbr->anyString(),
156 strtolower( $nt->getDBkey() ), $dbr->anyString() );
160 if ( $table === 'oldimage' ) {
161 // Don't want to deal with revdel.
162 // Future fixme: Show partial information as appropriate.
163 // Would have to be careful about filtering by username when username is deleted.
164 $conds['oi_deleted'] = 0;
167 // Add mQueryConds in case anyone was subclassing and using the old variable.
168 return $conds +
$this->mQueryConds
;
172 * The array keys (but not the array values) are used in sql. Phan
173 * gets confused by this, so mark this method as being ok for sql in general.
174 * @return-taint onlysafefor_sql
177 function getFieldNames() {
178 if ( !$this->mFieldNames
) {
179 $this->mFieldNames
= [
180 'img_timestamp' => $this->msg( 'listfiles_date' )->text(),
181 'img_name' => $this->msg( 'listfiles_name' )->text(),
182 'thumb' => $this->msg( 'listfiles_thumb' )->text(),
183 'img_size' => $this->msg( 'listfiles_size' )->text(),
185 if ( is_null( $this->mUserName
) ) {
186 // Do not show username if filtering by username
187 $this->mFieldNames
['img_user_text'] = $this->msg( 'listfiles_user' )->text();
189 // img_description down here, in order so that its still after the username field.
190 $this->mFieldNames
['img_description'] = $this->msg( 'listfiles_description' )->text();
192 if ( !$this->getConfig()->get( 'MiserMode' ) && !$this->mShowAll
) {
193 $this->mFieldNames
['count'] = $this->msg( 'listfiles_count' )->text();
195 if ( $this->mShowAll
) {
196 $this->mFieldNames
['top'] = $this->msg( 'listfiles-latestversion' )->text();
200 return $this->mFieldNames
;
203 function isFieldSortable( $field ) {
204 if ( $this->mIncluding
) {
207 $sortable = [ 'img_timestamp', 'img_name', 'img_size' ];
208 /* For reference, the indicies we can use for sorting are:
209 * On the image table: img_user_timestamp/img_usertext_timestamp/img_actor_timestamp,
210 * img_size, img_timestamp
211 * On oldimage: oi_usertext_timestamp/oi_actor_timestamp, oi_name_timestamp
213 * In particular that means we cannot sort by timestamp when not filtering
214 * by user and including old images in the results. Which is sad.
216 if ( $this->getConfig()->get( 'MiserMode' ) && !is_null( $this->mUserName
) ) {
217 // If we're sorting by user, the index only supports sorting by time.
218 if ( $field === 'img_timestamp' ) {
223 } elseif ( $this->getConfig()->get( 'MiserMode' )
224 && $this->mShowAll
/* && mUserName === null */
226 // no oi_timestamp index, so only alphabetical sorting in this case.
227 if ( $field === 'img_name' ) {
234 return in_array( $field, $sortable );
237 function getQueryInfo() {
238 // Hacky Hacky Hacky - I want to get query info
239 // for two different tables, without reimplementing
241 $qi = $this->getQueryInfoReal( $this->mTableName
);
247 * Actually get the query info.
249 * This is to allow displaying both stuff from image and oldimage table.
251 * This is a bit hacky.
253 * @param string $table Either 'image' or 'oldimage'
254 * @return array Query info
256 protected function getQueryInfoReal( $table ) {
257 $dbr = wfGetDB( DB_REPLICA
);
258 $prefix = $table === 'oldimage' ?
'oi' : 'img';
260 $tables = [ $table ];
261 $fields = array_keys( $this->getFieldNames() );
262 $fields = array_combine( $fields, $fields );
263 unset( $fields['img_description'] );
264 unset( $fields['img_user_text'] );
266 if ( $table === 'oldimage' ) {
267 foreach ( $fields as $id => $field ) {
268 if ( substr( $id, 0, 4 ) === 'img_' ) {
269 $fields[$id] = $prefix . substr( $field, 3 );
272 $fields['top'] = $dbr->addQuotes( 'no' );
273 } elseif ( $this->mShowAll
) {
274 $fields['top'] = $dbr->addQuotes( 'yes' );
276 $fields['thumb'] = $prefix . '_name';
278 $options = $join_conds = [];
281 $commentQuery = CommentStore
::getStore()->getJoin( $prefix . '_description' );
282 $tables +
= $commentQuery['tables'];
283 $fields +
= $commentQuery['fields'];
284 $join_conds +
= $commentQuery['joins'];
285 $fields['description_field'] = $dbr->addQuotes( "{$prefix}_description" );
288 $actorQuery = ActorMigration
::newMigration()->getJoin( $prefix . '_user' );
289 $tables +
= $actorQuery['tables'];
290 $join_conds +
= $actorQuery['joins'];
291 $fields['img_user'] = $actorQuery['fields'][$prefix . '_user'];
292 $fields['img_user_text'] = $actorQuery['fields'][$prefix . '_user_text'];
293 $fields['img_actor'] = $actorQuery['fields'][$prefix . '_actor'];
295 # Depends on $wgMiserMode
296 # Will also not happen if mShowAll is true.
297 if ( isset( $fields['count'] ) ) {
298 $fields['count'] = $dbr->buildSelectSubquery(
300 'COUNT(oi_archive_name)',
301 'oi_name = img_name',
309 'conds' => $this->buildQueryConds( $table ),
310 'options' => $options,
311 'join_conds' => $join_conds
316 * Override reallyDoQuery to mix together two queries.
318 * @note $asc is named $descending in IndexPager base class. However
319 * it is true when the order is ascending, and false when the order
320 * is descending, so I renamed it to $asc here.
323 * @param bool $order IndexPager::QUERY_ASCENDING or IndexPager::QUERY_DESCENDING
324 * @return FakeResultWrapper
325 * @throws MWException
327 function reallyDoQuery( $offset, $limit, $order ) {
328 $prevTableName = $this->mTableName
;
329 $this->mTableName
= 'image';
330 list( $tables, $fields, $conds, $fname, $options, $join_conds ) =
331 $this->buildQueryInfo( $offset, $limit, $order );
332 $imageRes = $this->mDb
->select( $tables, $fields, $conds, $fname, $options, $join_conds );
333 $this->mTableName
= $prevTableName;
335 if ( !$this->mShowAll
) {
339 $this->mTableName
= 'oldimage';
342 $oldIndex = $this->mIndexField
;
343 if ( substr( $this->mIndexField
, 0, 4 ) !== 'img_' ) {
344 throw new MWException( "Expected to be sorting on an image table field" );
346 $this->mIndexField
= 'oi_' . substr( $this->mIndexField
, 4 );
348 list( $tables, $fields, $conds, $fname, $options, $join_conds ) =
349 $this->buildQueryInfo( $offset, $limit, $order );
350 $oldimageRes = $this->mDb
->select( $tables, $fields, $conds, $fname, $options, $join_conds );
352 $this->mTableName
= $prevTableName;
353 $this->mIndexField
= $oldIndex;
355 return $this->combineResult( $imageRes, $oldimageRes, $limit, $order );
359 * Combine results from 2 tables.
361 * Note: This will throw away some results
363 * @param IResultWrapper $res1
364 * @param IResultWrapper $res2
366 * @param bool $ascending See note about $asc in $this->reallyDoQuery
367 * @return FakeResultWrapper $res1 and $res2 combined
369 protected function combineResult( $res1, $res2, $limit, $ascending ) {
372 $topRes1 = $res1->next();
373 $topRes2 = $res2->next();
375 for ( $i = 0; $i < $limit && $topRes1 && $topRes2; $i++
) {
376 if ( strcmp( $topRes1->{$this->mIndexField
}, $topRes2->{$this->mIndexField
} ) > 0 ) {
378 $resultArray[] = $topRes1;
379 $topRes1 = $res1->next();
381 $resultArray[] = $topRes2;
382 $topRes2 = $res2->next();
384 } elseif ( !$ascending ) {
385 $resultArray[] = $topRes2;
386 $topRes2 = $res2->next();
388 $resultArray[] = $topRes1;
389 $topRes1 = $res1->next();
393 for ( ; $i < $limit && $topRes1; $i++
) {
394 $resultArray[] = $topRes1;
395 $topRes1 = $res1->next();
398 for ( ; $i < $limit && $topRes2; $i++
) {
399 $resultArray[] = $topRes2;
400 $topRes2 = $res2->next();
403 return new FakeResultWrapper( $resultArray );
406 function getDefaultSort() {
407 if ( $this->mShowAll
&& $this->getConfig()->get( 'MiserMode' ) && is_null( $this->mUserName
) ) {
408 // Unfortunately no index on oi_timestamp.
411 return 'img_timestamp';
415 protected function doBatchLookups() {
417 $this->mResult
->seek( 0 );
418 foreach ( $this->mResult
as $row ) {
419 $userIds[] = $row->img_user
;
421 # Do a link batch query for names and userpages
422 UserCache
::singleton()->doQuery( $userIds, [ 'userpage' ], __METHOD__
);
426 * @param string $field
427 * @param string $value
428 * @return Message|string|int The return type depends on the value of $field:
430 * - img_timestamp: string
432 * - img_user_text: string
434 * - img_description: string
437 * @throws MWException
439 function formatValue( $field, $value ) {
440 $services = MediaWikiServices
::getInstance();
441 $linkRenderer = $this->getLinkRenderer();
444 $opt = [ 'time' => wfTimestamp( TS_MW
, $this->mCurrentRow
->img_timestamp
) ];
445 $file = RepoGroup
::singleton()->getLocalRepo()->findFile( $value, $opt );
446 // If statement for paranoia
448 $thumb = $file->transform( [ 'width' => 180, 'height' => 360 ] );
450 return $thumb->toHtml( [ 'desc-link' => true ] );
452 return $this->msg( 'thumbnail_error', '' )->escaped();
455 return htmlspecialchars( $value );
457 case 'img_timestamp':
458 // We may want to make this a link to the "old" version when displaying old files
459 return htmlspecialchars( $this->getLanguage()->userTimeAndDate( $value, $this->getUser() ) );
461 static $imgfile = null;
462 if ( $imgfile === null ) {
463 $imgfile = $this->msg( 'imgfile' )->text();
466 // Weird files can maybe exist? T24227
467 $filePage = Title
::makeTitleSafe( NS_FILE
, $value );
469 $link = $linkRenderer->makeKnownLink(
473 $download = Xml
::element(
475 [ 'href' => $services->getRepoGroup()->getLocalRepo()->newFile( $filePage )->getUrl() ],
478 $download = $this->msg( 'parentheses' )->rawParams( $download )->escaped();
480 // Add delete links if allowed
481 // From https://github.com/Wikia/app/pull/3859
482 $permissionManager = $services->getPermissionManager();
484 if ( $permissionManager->userCan( 'delete', $this->getUser(), $filePage ) ) {
485 $deleteMsg = $this->msg( 'listfiles-delete' )->text();
487 $delete = $linkRenderer->makeKnownLink(
488 $filePage, $deleteMsg, [], [ 'action' => 'delete' ]
490 $delete = $this->msg( 'parentheses' )->rawParams( $delete )->escaped();
492 return "$link $download $delete";
495 return "$link $download";
497 return htmlspecialchars( $value );
499 case 'img_user_text':
500 if ( $this->mCurrentRow
->img_user
) {
501 $name = User
::whoIs( $this->mCurrentRow
->img_user
);
502 $link = $linkRenderer->makeLink(
503 Title
::makeTitle( NS_USER
, $name ),
507 $link = htmlspecialchars( $value );
512 return htmlspecialchars( $this->getLanguage()->formatSize( $value ) );
513 case 'img_description':
514 $field = $this->mCurrentRow
->description_field
;
515 $value = CommentStore
::getStore()->getComment( $field, $this->mCurrentRow
)->text
;
516 return Linker
::formatComment( $value );
518 return $this->getLanguage()->formatNum( intval( $value ) +
1 );
520 // Messages: listfiles-latestversion-yes, listfiles-latestversion-no
521 return $this->msg( 'listfiles-latestversion-' . $value )->escaped();
523 throw new MWException( "Unknown field '$field'" );
528 $formDescriptor = [];
529 $formDescriptor['limit'] = [
532 'label-message' => 'table_pager_limit_label',
533 'options' => $this->getLimitSelectList(),
534 'default' => $this->mLimit
,
537 if ( !$this->getConfig()->get( 'MiserMode' ) ) {
538 $formDescriptor['ilsearch'] = [
540 'name' => 'ilsearch',
541 'id' => 'mw-ilsearch',
542 'label-message' => 'listfiles_search_for',
543 'default' => $this->mSearch
,
545 'maxlength' => '255',
549 $formDescriptor['user'] = [
552 'id' => 'mw-listfiles-user',
553 'label-message' => 'username',
554 'default' => $this->mUserName
,
556 'maxlength' => '255',
559 $formDescriptor['ilshowall'] = [
561 'name' => 'ilshowall',
562 'id' => 'mw-listfiles-show-all',
563 'label-message' => 'listfiles-show-all',
564 'default' => $this->mShowAll
,
567 $query = $this->getRequest()->getQueryValues();
568 unset( $query['title'] );
569 unset( $query['limit'] );
570 unset( $query['ilsearch'] );
571 unset( $query['ilshowall'] );
572 unset( $query['user'] );
574 $htmlForm = HTMLForm
::factory( 'ooui', $formDescriptor, $this->getContext() );
577 ->setId( 'mw-listfiles-form' )
578 ->setTitle( $this->getTitle() )
579 ->setSubmitTextMsg( 'table_pager_limit_submit' )
580 ->setWrapperLegendMsg( 'listfiles' )
581 ->addHiddenFields( $query )
586 protected function getTableClass() {
587 return parent
::getTableClass() . ' listfiles';
590 protected function getNavClass() {
591 return parent
::getNavClass() . ' listfiles_nav';
594 protected function getSortHeaderClass() {
595 return parent
::getSortHeaderClass() . ' listfiles_sort';
598 function getPagingQueries() {
599 $queries = parent
::getPagingQueries();
600 if ( !is_null( $this->mUserName
) ) {
601 # Append the username to the query string
602 foreach ( $queries as &$query ) {
603 if ( $query !== false ) {
604 $query['user'] = $this->mUserName
;
612 function getDefaultQuery() {
613 $queries = parent
::getDefaultQuery();
614 if ( !isset( $queries['user'] ) && !is_null( $this->mUserName
) ) {
615 $queries['user'] = $this->mUserName
;
621 function getTitle() {
622 return SpecialPage
::getTitleFor( 'Listfiles' );