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\Linker\LinkRenderer
;
26 use MediaWiki\MediaWikiServices
;
27 use Wikimedia\Rdbms\IResultWrapper
;
28 use Wikimedia\Rdbms\FakeResultWrapper
;
30 class ImageListPager
extends TablePager
{
32 protected $mFieldNames = null;
34 // Subclasses should override buildQueryConds instead of using $mQueryConds variable.
35 protected $mQueryConds = [];
37 protected $mUserName = null;
44 protected $mUser = null;
46 protected $mSearch = '';
48 protected $mIncluding = false;
50 protected $mShowAll = false;
52 protected $mTableName = 'image';
54 public function __construct( IContextSource
$context, $userName = null, $search = '',
55 $including = false, $showAll = false, LinkRenderer
$linkRenderer
57 $this->setContext( $context );
59 $this->mIncluding
= $including;
60 $this->mShowAll
= $showAll;
62 if ( $userName !== null && $userName !== '' ) {
63 $nt = Title
::makeTitleSafe( NS_USER
, $userName );
64 if ( is_null( $nt ) ) {
65 $this->outputUserDoesNotExist( $userName );
67 $this->mUserName
= $nt->getText();
68 $user = User
::newFromName( $this->mUserName
, false );
72 if ( !$user ||
( $user->isAnon() && !User
::isIP( $user->getName() ) ) ) {
73 $this->outputUserDoesNotExist( $userName );
78 if ( $search !== '' && !$this->getConfig()->get( 'MiserMode' ) ) {
79 $this->mSearch
= $search;
80 $nt = Title
::newFromText( $this->mSearch
);
83 $dbr = wfGetDB( DB_REPLICA
);
84 $this->mQueryConds
[] = 'LOWER(img_name)' .
85 $dbr->buildLike( $dbr->anyString(),
86 strtolower( $nt->getDBkey() ), $dbr->anyString() );
91 if ( $this->getRequest()->getText( 'sort', 'img_date' ) == 'img_date' ) {
92 $this->mDefaultDirection
= IndexPager
::DIR_DESCENDING
;
94 $this->mDefaultDirection
= IndexPager
::DIR_ASCENDING
;
97 $this->mDefaultDirection
= IndexPager
::DIR_DESCENDING
;
100 parent
::__construct( $context, $linkRenderer );
104 * Get the user relevant to the ImageList
108 function getRelevantUser() {
113 * Add a message to the output stating that the user doesn't exist
115 * @param string $userName Unescaped user name
117 protected function outputUserDoesNotExist( $userName ) {
118 $this->getOutput()->wrapWikiMsg(
119 "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
121 'listfiles-userdoesnotexist',
122 wfEscapeWikiText( $userName ),
128 * Build the where clause of the query.
130 * Replaces the older mQueryConds member variable.
131 * @param string $table Either "image" or "oldimage"
132 * @return array The query conditions.
134 protected function buildQueryConds( $table ) {
135 $prefix = $table === 'image' ?
'img' : 'oi';
138 if ( !is_null( $this->mUserName
) ) {
139 // getQueryInfoReal() should have handled the tables and joins.
140 $dbr = wfGetDB( DB_REPLICA
);
141 $actorWhere = ActorMigration
::newMigration()->getWhere(
144 User
::newFromName( $this->mUserName
, false ),
145 // oldimage doesn't have an index on oi_user, while image does. Set $useId accordingly.
148 $conds[] = $actorWhere['conds'];
151 if ( $this->mSearch
!== '' ) {
152 $nt = Title
::newFromText( $this->mSearch
);
154 $dbr = wfGetDB( DB_REPLICA
);
155 $conds[] = 'LOWER(' . $prefix . '_name)' .
156 $dbr->buildLike( $dbr->anyString(),
157 strtolower( $nt->getDBkey() ), $dbr->anyString() );
161 if ( $table === 'oldimage' ) {
162 // Don't want to deal with revdel.
163 // Future fixme: Show partial information as appropriate.
164 // Would have to be careful about filtering by username when username is deleted.
165 $conds['oi_deleted'] = 0;
168 // Add mQueryConds in case anyone was subclassing and using the old variable.
169 return $conds +
$this->mQueryConds
;
173 * The array keys (but not the array values) are used in sql. Phan
174 * gets confused by this, so mark this method as being ok for sql in general.
175 * @return-taint onlysafefor_sql
178 function getFieldNames() {
179 if ( !$this->mFieldNames
) {
180 $this->mFieldNames
= [
181 'img_timestamp' => $this->msg( 'listfiles_date' )->text(),
182 'img_name' => $this->msg( 'listfiles_name' )->text(),
183 'thumb' => $this->msg( 'listfiles_thumb' )->text(),
184 'img_size' => $this->msg( 'listfiles_size' )->text(),
186 if ( is_null( $this->mUserName
) ) {
187 // Do not show username if filtering by username
188 $this->mFieldNames
['img_user_text'] = $this->msg( 'listfiles_user' )->text();
190 // img_description down here, in order so that its still after the username field.
191 $this->mFieldNames
['img_description'] = $this->msg( 'listfiles_description' )->text();
193 if ( !$this->getConfig()->get( 'MiserMode' ) && !$this->mShowAll
) {
194 $this->mFieldNames
['count'] = $this->msg( 'listfiles_count' )->text();
196 if ( $this->mShowAll
) {
197 $this->mFieldNames
['top'] = $this->msg( 'listfiles-latestversion' )->text();
201 return $this->mFieldNames
;
204 function isFieldSortable( $field ) {
205 if ( $this->mIncluding
) {
208 $sortable = [ 'img_timestamp', 'img_name', 'img_size' ];
209 /* For reference, the indicies we can use for sorting are:
210 * On the image table: img_user_timestamp/img_usertext_timestamp/img_actor_timestamp,
211 * img_size, img_timestamp
212 * On oldimage: oi_usertext_timestamp/oi_actor_timestamp, oi_name_timestamp
214 * In particular that means we cannot sort by timestamp when not filtering
215 * by user and including old images in the results. Which is sad.
217 if ( $this->getConfig()->get( 'MiserMode' ) && !is_null( $this->mUserName
) ) {
218 // If we're sorting by user, the index only supports sorting by time.
219 if ( $field === 'img_timestamp' ) {
224 } elseif ( $this->getConfig()->get( 'MiserMode' )
225 && $this->mShowAll
/* && mUserName === null */
227 // no oi_timestamp index, so only alphabetical sorting in this case.
228 if ( $field === 'img_name' ) {
235 return in_array( $field, $sortable );
238 function getQueryInfo() {
239 // Hacky Hacky Hacky - I want to get query info
240 // for two different tables, without reimplementing
242 $qi = $this->getQueryInfoReal( $this->mTableName
);
248 * Actually get the query info.
250 * This is to allow displaying both stuff from image and oldimage table.
252 * This is a bit hacky.
254 * @param string $table Either 'image' or 'oldimage'
255 * @return array Query info
257 protected function getQueryInfoReal( $table ) {
258 $dbr = wfGetDB( DB_REPLICA
);
259 $prefix = $table === 'oldimage' ?
'oi' : 'img';
261 $tables = [ $table ];
262 $fields = array_keys( $this->getFieldNames() );
263 $fields = array_combine( $fields, $fields );
264 unset( $fields['img_description'] );
265 unset( $fields['img_user_text'] );
267 if ( $table === 'oldimage' ) {
268 foreach ( $fields as $id => $field ) {
269 if ( substr( $id, 0, 4 ) === 'img_' ) {
270 $fields[$id] = $prefix . substr( $field, 3 );
273 $fields['top'] = $dbr->addQuotes( 'no' );
274 } elseif ( $this->mShowAll
) {
275 $fields['top'] = $dbr->addQuotes( 'yes' );
277 $fields['thumb'] = $prefix . '_name';
279 $options = $join_conds = [];
282 $commentQuery = CommentStore
::getStore()->getJoin( $prefix . '_description' );
283 $tables +
= $commentQuery['tables'];
284 $fields +
= $commentQuery['fields'];
285 $join_conds +
= $commentQuery['joins'];
286 $fields['description_field'] = $dbr->addQuotes( "{$prefix}_description" );
289 $actorQuery = ActorMigration
::newMigration()->getJoin( $prefix . '_user' );
290 $tables +
= $actorQuery['tables'];
291 $join_conds +
= $actorQuery['joins'];
292 $fields['img_user'] = $actorQuery['fields'][$prefix . '_user'];
293 $fields['img_user_text'] = $actorQuery['fields'][$prefix . '_user_text'];
294 $fields['img_actor'] = $actorQuery['fields'][$prefix . '_actor'];
296 # Depends on $wgMiserMode
297 # Will also not happen if mShowAll is true.
298 if ( isset( $fields['count'] ) ) {
299 $fields['count'] = $dbr->buildSelectSubquery(
301 'COUNT(oi_archive_name)',
302 'oi_name = img_name',
310 'conds' => $this->buildQueryConds( $table ),
311 'options' => $options,
312 'join_conds' => $join_conds
317 * Override reallyDoQuery to mix together two queries.
319 * @note $asc is named $descending in IndexPager base class. However
320 * it is true when the order is ascending, and false when the order
321 * is descending, so I renamed it to $asc here.
324 * @param bool $order IndexPager::QUERY_ASCENDING or IndexPager::QUERY_DESCENDING
325 * @return FakeResultWrapper
326 * @throws MWException
328 function reallyDoQuery( $offset, $limit, $order ) {
329 $prevTableName = $this->mTableName
;
330 $this->mTableName
= 'image';
331 list( $tables, $fields, $conds, $fname, $options, $join_conds ) =
332 $this->buildQueryInfo( $offset, $limit, $order );
333 $imageRes = $this->mDb
->select( $tables, $fields, $conds, $fname, $options, $join_conds );
334 $this->mTableName
= $prevTableName;
336 if ( !$this->mShowAll
) {
340 $this->mTableName
= 'oldimage';
343 $oldIndex = $this->mIndexField
;
344 if ( substr( $this->mIndexField
, 0, 4 ) !== 'img_' ) {
345 throw new MWException( "Expected to be sorting on an image table field" );
347 $this->mIndexField
= 'oi_' . substr( $this->mIndexField
, 4 );
349 list( $tables, $fields, $conds, $fname, $options, $join_conds ) =
350 $this->buildQueryInfo( $offset, $limit, $order );
351 $oldimageRes = $this->mDb
->select( $tables, $fields, $conds, $fname, $options, $join_conds );
353 $this->mTableName
= $prevTableName;
354 $this->mIndexField
= $oldIndex;
356 return $this->combineResult( $imageRes, $oldimageRes, $limit, $order );
360 * Combine results from 2 tables.
362 * Note: This will throw away some results
364 * @param IResultWrapper $res1
365 * @param IResultWrapper $res2
367 * @param bool $ascending See note about $asc in $this->reallyDoQuery
368 * @return FakeResultWrapper $res1 and $res2 combined
370 protected function combineResult( $res1, $res2, $limit, $ascending ) {
373 $topRes1 = $res1->next();
374 $topRes2 = $res2->next();
376 for ( $i = 0; $i < $limit && $topRes1 && $topRes2; $i++
) {
377 if ( strcmp( $topRes1->{$this->mIndexField
}, $topRes2->{$this->mIndexField
} ) > 0 ) {
379 $resultArray[] = $topRes1;
380 $topRes1 = $res1->next();
382 $resultArray[] = $topRes2;
383 $topRes2 = $res2->next();
385 } elseif ( !$ascending ) {
386 $resultArray[] = $topRes2;
387 $topRes2 = $res2->next();
389 $resultArray[] = $topRes1;
390 $topRes1 = $res1->next();
394 for ( ; $i < $limit && $topRes1; $i++
) {
395 $resultArray[] = $topRes1;
396 $topRes1 = $res1->next();
399 for ( ; $i < $limit && $topRes2; $i++
) {
400 $resultArray[] = $topRes2;
401 $topRes2 = $res2->next();
404 return new FakeResultWrapper( $resultArray );
407 function getDefaultSort() {
408 if ( $this->mShowAll
&& $this->getConfig()->get( 'MiserMode' ) && is_null( $this->mUserName
) ) {
409 // Unfortunately no index on oi_timestamp.
412 return 'img_timestamp';
416 protected function doBatchLookups() {
418 $this->mResult
->seek( 0 );
419 foreach ( $this->mResult
as $row ) {
420 $userIds[] = $row->img_user
;
422 # Do a link batch query for names and userpages
423 UserCache
::singleton()->doQuery( $userIds, [ 'userpage' ], __METHOD__
);
427 * @param string $field
428 * @param string $value
429 * @return Message|string|int The return type depends on the value of $field:
431 * - img_timestamp: string
433 * - img_user_text: string
435 * - img_description: string
438 * @throws MWException
440 function formatValue( $field, $value ) {
441 $services = MediaWikiServices
::getInstance();
442 $linkRenderer = $this->getLinkRenderer();
445 $opt = [ 'time' => wfTimestamp( TS_MW
, $this->mCurrentRow
->img_timestamp
) ];
446 $file = RepoGroup
::singleton()->getLocalRepo()->findFile( $value, $opt );
447 // If statement for paranoia
449 $thumb = $file->transform( [ 'width' => 180, 'height' => 360 ] );
451 return $thumb->toHtml( [ 'desc-link' => true ] );
453 return $this->msg( 'thumbnail_error', '' )->escaped();
456 return htmlspecialchars( $value );
458 case 'img_timestamp':
459 // We may want to make this a link to the "old" version when displaying old files
460 return htmlspecialchars( $this->getLanguage()->userTimeAndDate( $value, $this->getUser() ) );
462 static $imgfile = null;
463 if ( $imgfile === null ) {
464 $imgfile = $this->msg( 'imgfile' )->text();
467 // Weird files can maybe exist? T24227
468 $filePage = Title
::makeTitleSafe( NS_FILE
, $value );
470 $link = $linkRenderer->makeKnownLink(
474 $download = Xml
::element(
476 [ 'href' => $services->getRepoGroup()->getLocalRepo()->newFile( $filePage )->getUrl() ],
479 $download = $this->msg( 'parentheses' )->rawParams( $download )->escaped();
481 // Add delete links if allowed
482 // From https://github.com/Wikia/app/pull/3859
483 $permissionManager = $services->getPermissionManager();
485 if ( $permissionManager->userCan( 'delete', $this->getUser(), $filePage ) ) {
486 $deleteMsg = $this->msg( 'listfiles-delete' )->text();
488 $delete = $linkRenderer->makeKnownLink(
489 $filePage, $deleteMsg, [], [ 'action' => 'delete' ]
491 $delete = $this->msg( 'parentheses' )->rawParams( $delete )->escaped();
493 return "$link $download $delete";
496 return "$link $download";
498 return htmlspecialchars( $value );
500 case 'img_user_text':
501 if ( $this->mCurrentRow
->img_user
) {
502 $name = User
::whoIs( $this->mCurrentRow
->img_user
);
503 $link = $linkRenderer->makeLink(
504 Title
::makeTitle( NS_USER
, $name ),
508 $link = htmlspecialchars( $value );
513 return htmlspecialchars( $this->getLanguage()->formatSize( $value ) );
514 case 'img_description':
515 $field = $this->mCurrentRow
->description_field
;
516 $value = CommentStore
::getStore()->getComment( $field, $this->mCurrentRow
)->text
;
517 return Linker
::formatComment( $value );
519 return $this->getLanguage()->formatNum( intval( $value ) +
1 );
521 // Messages: listfiles-latestversion-yes, listfiles-latestversion-no
522 return $this->msg( 'listfiles-latestversion-' . $value )->escaped();
524 throw new MWException( "Unknown field '$field'" );
529 $formDescriptor = [];
530 $formDescriptor['limit'] = [
533 'label-message' => 'table_pager_limit_label',
534 'options' => $this->getLimitSelectList(),
535 'default' => $this->mLimit
,
538 if ( !$this->getConfig()->get( 'MiserMode' ) ) {
539 $formDescriptor['ilsearch'] = [
541 'name' => 'ilsearch',
542 'id' => 'mw-ilsearch',
543 'label-message' => 'listfiles_search_for',
544 'default' => $this->mSearch
,
546 'maxlength' => '255',
550 $formDescriptor['user'] = [
553 'id' => 'mw-listfiles-user',
554 'label-message' => 'username',
555 'default' => $this->mUserName
,
557 'maxlength' => '255',
560 $formDescriptor['ilshowall'] = [
562 'name' => 'ilshowall',
563 'id' => 'mw-listfiles-show-all',
564 'label-message' => 'listfiles-show-all',
565 'default' => $this->mShowAll
,
568 $query = $this->getRequest()->getQueryValues();
569 unset( $query['title'] );
570 unset( $query['limit'] );
571 unset( $query['ilsearch'] );
572 unset( $query['ilshowall'] );
573 unset( $query['user'] );
575 $htmlForm = HTMLForm
::factory( 'ooui', $formDescriptor, $this->getContext() );
578 ->setId( 'mw-listfiles-form' )
579 ->setTitle( $this->getTitle() )
580 ->setSubmitTextMsg( 'table_pager_limit_submit' )
581 ->setWrapperLegendMsg( 'listfiles' )
582 ->addHiddenFields( $query )
587 protected function getTableClass() {
588 return parent
::getTableClass() . ' listfiles';
591 protected function getNavClass() {
592 return parent
::getNavClass() . ' listfiles_nav';
595 protected function getSortHeaderClass() {
596 return parent
::getSortHeaderClass() . ' listfiles_sort';
599 function getPagingQueries() {
600 $queries = parent
::getPagingQueries();
601 if ( !is_null( $this->mUserName
) ) {
602 # Append the username to the query string
603 foreach ( $queries as &$query ) {
604 if ( $query !== false ) {
605 $query['user'] = $this->mUserName
;
613 function getDefaultQuery() {
614 $queries = parent
::getDefaultQuery();
615 if ( !isset( $queries['user'] ) && !is_null( $this->mUserName
) ) {
616 $queries['user'] = $this->mUserName
;
622 function getTitle() {
623 return SpecialPage
::getTitleFor( 'Listfiles' );