Fix use of GenderCache in ApiPageSet::processTitlesArray
[lhc/web/wiklou.git] / includes / specials / pagers / ImageListPager.php
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.
7 *
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.
12 *
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
17 *
18 * @file
19 * @ingroup Pager
20 */
21
22 /**
23 * @ingroup Pager
24 */
25 use MediaWiki\MediaWikiServices;
26 use Wikimedia\Rdbms\IResultWrapper;
27 use Wikimedia\Rdbms\FakeResultWrapper;
28
29 class ImageListPager extends TablePager {
30
31 protected $mFieldNames = null;
32
33 // Subclasses should override buildQueryConds instead of using $mQueryConds variable.
34 protected $mQueryConds = [];
35
36 protected $mUserName = null;
37
38 /**
39 * The relevant user
40 *
41 * @var User|null
42 */
43 protected $mUser = null;
44
45 protected $mSearch = '';
46
47 protected $mIncluding = false;
48
49 protected $mShowAll = false;
50
51 protected $mTableName = 'image';
52
53 public function __construct( IContextSource $context, $userName = null, $search = '',
54 $including = false, $showAll = false
55 ) {
56 $this->setContext( $context );
57
58 $this->mIncluding = $including;
59 $this->mShowAll = $showAll;
60
61 if ( $userName !== null && $userName !== '' ) {
62 $nt = Title::makeTitleSafe( NS_USER, $userName );
63 if ( is_null( $nt ) ) {
64 $this->outputUserDoesNotExist( $userName );
65 } else {
66 $this->mUserName = $nt->getText();
67 $user = User::newFromName( $this->mUserName, false );
68 if ( $user ) {
69 $this->mUser = $user;
70 }
71 if ( !$user || ( $user->isAnon() && !User::isIP( $user->getName() ) ) ) {
72 $this->outputUserDoesNotExist( $userName );
73 }
74 }
75 }
76
77 if ( $search !== '' && !$this->getConfig()->get( 'MiserMode' ) ) {
78 $this->mSearch = $search;
79 $nt = Title::newFromText( $this->mSearch );
80
81 if ( $nt ) {
82 $dbr = wfGetDB( DB_REPLICA );
83 $this->mQueryConds[] = 'LOWER(img_name)' .
84 $dbr->buildLike( $dbr->anyString(),
85 strtolower( $nt->getDBkey() ), $dbr->anyString() );
86 }
87 }
88
89 if ( !$including ) {
90 if ( $this->getRequest()->getText( 'sort', 'img_date' ) == 'img_date' ) {
91 $this->mDefaultDirection = IndexPager::DIR_DESCENDING;
92 } else {
93 $this->mDefaultDirection = IndexPager::DIR_ASCENDING;
94 }
95 } else {
96 $this->mDefaultDirection = IndexPager::DIR_DESCENDING;
97 }
98
99 parent::__construct();
100 }
101
102 /**
103 * Get the user relevant to the ImageList
104 *
105 * @return User|null
106 */
107 function getRelevantUser() {
108 return $this->mUser;
109 }
110
111 /**
112 * Add a message to the output stating that the user doesn't exist
113 *
114 * @param string $userName Unescaped user name
115 */
116 protected function outputUserDoesNotExist( $userName ) {
117 $this->getOutput()->wrapWikiMsg(
118 "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
119 [
120 'listfiles-userdoesnotexist',
121 wfEscapeWikiText( $userName ),
122 ]
123 );
124 }
125
126 /**
127 * Build the where clause of the query.
128 *
129 * Replaces the older mQueryConds member variable.
130 * @param string $table Either "image" or "oldimage"
131 * @return array The query conditions.
132 */
133 protected function buildQueryConds( $table ) {
134 $prefix = $table === 'image' ? 'img' : 'oi';
135 $conds = [];
136
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(
141 $dbr,
142 $prefix . '_user',
143 User::newFromName( $this->mUserName, false ),
144 // oldimage doesn't have an index on oi_user, while image does. Set $useId accordingly.
145 $prefix === 'img'
146 );
147 $conds[] = $actorWhere['conds'];
148 }
149
150 if ( $this->mSearch !== '' ) {
151 $nt = Title::newFromText( $this->mSearch );
152 if ( $nt ) {
153 $dbr = wfGetDB( DB_REPLICA );
154 $conds[] = 'LOWER(' . $prefix . '_name)' .
155 $dbr->buildLike( $dbr->anyString(),
156 strtolower( $nt->getDBkey() ), $dbr->anyString() );
157 }
158 }
159
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;
165 }
166
167 // Add mQueryConds in case anyone was subclassing and using the old variable.
168 return $conds + $this->mQueryConds;
169 }
170
171 /**
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
175 * @return array
176 */
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(),
184 ];
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();
188 }
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();
191
192 if ( !$this->getConfig()->get( 'MiserMode' ) && !$this->mShowAll ) {
193 $this->mFieldNames['count'] = $this->msg( 'listfiles_count' )->text();
194 }
195 if ( $this->mShowAll ) {
196 $this->mFieldNames['top'] = $this->msg( 'listfiles-latestversion' )->text();
197 }
198 }
199
200 return $this->mFieldNames;
201 }
202
203 function isFieldSortable( $field ) {
204 if ( $this->mIncluding ) {
205 return false;
206 }
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
212 *
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.
215 */
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' ) {
219 return true;
220 } else {
221 return false;
222 }
223 } elseif ( $this->getConfig()->get( 'MiserMode' )
224 && $this->mShowAll /* && mUserName === null */
225 ) {
226 // no oi_timestamp index, so only alphabetical sorting in this case.
227 if ( $field === 'img_name' ) {
228 return true;
229 } else {
230 return false;
231 }
232 }
233
234 return in_array( $field, $sortable );
235 }
236
237 function getQueryInfo() {
238 // Hacky Hacky Hacky - I want to get query info
239 // for two different tables, without reimplementing
240 // the pager class.
241 $qi = $this->getQueryInfoReal( $this->mTableName );
242
243 return $qi;
244 }
245
246 /**
247 * Actually get the query info.
248 *
249 * This is to allow displaying both stuff from image and oldimage table.
250 *
251 * This is a bit hacky.
252 *
253 * @param string $table Either 'image' or 'oldimage'
254 * @return array Query info
255 */
256 protected function getQueryInfoReal( $table ) {
257 $dbr = wfGetDB( DB_REPLICA );
258 $prefix = $table === 'oldimage' ? 'oi' : 'img';
259
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'] );
265
266 if ( $table === 'oldimage' ) {
267 foreach ( $fields as $id => $field ) {
268 if ( substr( $id, 0, 4 ) === 'img_' ) {
269 $fields[$id] = $prefix . substr( $field, 3 );
270 }
271 }
272 $fields['top'] = $dbr->addQuotes( 'no' );
273 } elseif ( $this->mShowAll ) {
274 $fields['top'] = $dbr->addQuotes( 'yes' );
275 }
276 $fields['thumb'] = $prefix . '_name';
277
278 $options = $join_conds = [];
279
280 # Description field
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" );
286
287 # User fields
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'];
294
295 # Depends on $wgMiserMode
296 # Will also not happen if mShowAll is true.
297 if ( isset( $fields['count'] ) ) {
298 $fields['count'] = $dbr->buildSelectSubquery(
299 'oldimage',
300 'COUNT(oi_archive_name)',
301 'oi_name = img_name',
302 __METHOD__
303 );
304 }
305
306 return [
307 'tables' => $tables,
308 'fields' => $fields,
309 'conds' => $this->buildQueryConds( $table ),
310 'options' => $options,
311 'join_conds' => $join_conds
312 ];
313 }
314
315 /**
316 * Override reallyDoQuery to mix together two queries.
317 *
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.
321 * @param int $offset
322 * @param int $limit
323 * @param bool $order IndexPager::QUERY_ASCENDING or IndexPager::QUERY_DESCENDING
324 * @return FakeResultWrapper
325 * @throws MWException
326 */
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;
334
335 if ( !$this->mShowAll ) {
336 return $imageRes;
337 }
338
339 $this->mTableName = 'oldimage';
340
341 # Hacky...
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" );
345 }
346 $this->mIndexField = 'oi_' . substr( $this->mIndexField, 4 );
347
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 );
351
352 $this->mTableName = $prevTableName;
353 $this->mIndexField = $oldIndex;
354
355 return $this->combineResult( $imageRes, $oldimageRes, $limit, $order );
356 }
357
358 /**
359 * Combine results from 2 tables.
360 *
361 * Note: This will throw away some results
362 *
363 * @param IResultWrapper $res1
364 * @param IResultWrapper $res2
365 * @param int $limit
366 * @param bool $ascending See note about $asc in $this->reallyDoQuery
367 * @return FakeResultWrapper $res1 and $res2 combined
368 */
369 protected function combineResult( $res1, $res2, $limit, $ascending ) {
370 $res1->rewind();
371 $res2->rewind();
372 $topRes1 = $res1->next();
373 $topRes2 = $res2->next();
374 $resultArray = [];
375 for ( $i = 0; $i < $limit && $topRes1 && $topRes2; $i++ ) {
376 if ( strcmp( $topRes1->{$this->mIndexField}, $topRes2->{$this->mIndexField} ) > 0 ) {
377 if ( !$ascending ) {
378 $resultArray[] = $topRes1;
379 $topRes1 = $res1->next();
380 } else {
381 $resultArray[] = $topRes2;
382 $topRes2 = $res2->next();
383 }
384 } elseif ( !$ascending ) {
385 $resultArray[] = $topRes2;
386 $topRes2 = $res2->next();
387 } else {
388 $resultArray[] = $topRes1;
389 $topRes1 = $res1->next();
390 }
391 }
392
393 for ( ; $i < $limit && $topRes1; $i++ ) {
394 $resultArray[] = $topRes1;
395 $topRes1 = $res1->next();
396 }
397
398 for ( ; $i < $limit && $topRes2; $i++ ) {
399 $resultArray[] = $topRes2;
400 $topRes2 = $res2->next();
401 }
402
403 return new FakeResultWrapper( $resultArray );
404 }
405
406 function getDefaultSort() {
407 if ( $this->mShowAll && $this->getConfig()->get( 'MiserMode' ) && is_null( $this->mUserName ) ) {
408 // Unfortunately no index on oi_timestamp.
409 return 'img_name';
410 } else {
411 return 'img_timestamp';
412 }
413 }
414
415 protected function doBatchLookups() {
416 $userIds = [];
417 $this->mResult->seek( 0 );
418 foreach ( $this->mResult as $row ) {
419 $userIds[] = $row->img_user;
420 }
421 # Do a link batch query for names and userpages
422 UserCache::singleton()->doQuery( $userIds, [ 'userpage' ], __METHOD__ );
423 }
424
425 /**
426 * @param string $field
427 * @param string $value
428 * @return Message|string|int The return type depends on the value of $field:
429 * - thumb: string
430 * - img_timestamp: string
431 * - img_name: string
432 * - img_user_text: string
433 * - img_size: string
434 * - img_description: string
435 * - count: int
436 * - top: Message
437 * @throws MWException
438 */
439 function formatValue( $field, $value ) {
440 $services = MediaWikiServices::getInstance();
441 $linkRenderer = $this->getLinkRenderer();
442 switch ( $field ) {
443 case 'thumb':
444 $opt = [ 'time' => wfTimestamp( TS_MW, $this->mCurrentRow->img_timestamp ) ];
445 $file = RepoGroup::singleton()->getLocalRepo()->findFile( $value, $opt );
446 // If statement for paranoia
447 if ( $file ) {
448 $thumb = $file->transform( [ 'width' => 180, 'height' => 360 ] );
449 if ( $thumb ) {
450 return $thumb->toHtml( [ 'desc-link' => true ] );
451 } else {
452 return $this->msg( 'thumbnail_error', '' )->escaped();
453 }
454 } else {
455 return htmlspecialchars( $value );
456 }
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() ) );
460 case 'img_name':
461 static $imgfile = null;
462 if ( $imgfile === null ) {
463 $imgfile = $this->msg( 'imgfile' )->text();
464 }
465
466 // Weird files can maybe exist? T24227
467 $filePage = Title::makeTitleSafe( NS_FILE, $value );
468 if ( $filePage ) {
469 $link = $linkRenderer->makeKnownLink(
470 $filePage,
471 $filePage->getText()
472 );
473 $download = Xml::element(
474 'a',
475 [ 'href' => $services->getRepoGroup()->getLocalRepo()->newFile( $filePage )->getUrl() ],
476 $imgfile
477 );
478 $download = $this->msg( 'parentheses' )->rawParams( $download )->escaped();
479
480 // Add delete links if allowed
481 // From https://github.com/Wikia/app/pull/3859
482 $permissionManager = $services->getPermissionManager();
483
484 if ( $permissionManager->userCan( 'delete', $this->getUser(), $filePage ) ) {
485 $deleteMsg = $this->msg( 'listfiles-delete' )->text();
486
487 $delete = $linkRenderer->makeKnownLink(
488 $filePage, $deleteMsg, [], [ 'action' => 'delete' ]
489 );
490 $delete = $this->msg( 'parentheses' )->rawParams( $delete )->escaped();
491
492 return "$link $download $delete";
493 }
494
495 return "$link $download";
496 } else {
497 return htmlspecialchars( $value );
498 }
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 ),
504 $name
505 );
506 } else {
507 $link = htmlspecialchars( $value );
508 }
509
510 return $link;
511 case 'img_size':
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 );
517 case 'count':
518 return $this->getLanguage()->formatNum( intval( $value ) + 1 );
519 case 'top':
520 // Messages: listfiles-latestversion-yes, listfiles-latestversion-no
521 return $this->msg( 'listfiles-latestversion-' . $value )->escaped();
522 default:
523 throw new MWException( "Unknown field '$field'" );
524 }
525 }
526
527 function getForm() {
528 $formDescriptor = [];
529 $formDescriptor['limit'] = [
530 'type' => 'select',
531 'name' => 'limit',
532 'label-message' => 'table_pager_limit_label',
533 'options' => $this->getLimitSelectList(),
534 'default' => $this->mLimit,
535 ];
536
537 if ( !$this->getConfig()->get( 'MiserMode' ) ) {
538 $formDescriptor['ilsearch'] = [
539 'type' => 'text',
540 'name' => 'ilsearch',
541 'id' => 'mw-ilsearch',
542 'label-message' => 'listfiles_search_for',
543 'default' => $this->mSearch,
544 'size' => '40',
545 'maxlength' => '255',
546 ];
547 }
548
549 $formDescriptor['user'] = [
550 'type' => 'user',
551 'name' => 'user',
552 'id' => 'mw-listfiles-user',
553 'label-message' => 'username',
554 'default' => $this->mUserName,
555 'size' => '40',
556 'maxlength' => '255',
557 ];
558
559 $formDescriptor['ilshowall'] = [
560 'type' => 'check',
561 'name' => 'ilshowall',
562 'id' => 'mw-listfiles-show-all',
563 'label-message' => 'listfiles-show-all',
564 'default' => $this->mShowAll,
565 ];
566
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'] );
573
574 $htmlForm = HTMLForm::factory( 'ooui', $formDescriptor, $this->getContext() );
575 $htmlForm
576 ->setMethod( 'get' )
577 ->setId( 'mw-listfiles-form' )
578 ->setTitle( $this->getTitle() )
579 ->setSubmitTextMsg( 'table_pager_limit_submit' )
580 ->setWrapperLegendMsg( 'listfiles' )
581 ->addHiddenFields( $query )
582 ->prepareForm()
583 ->displayForm( '' );
584 }
585
586 protected function getTableClass() {
587 return parent::getTableClass() . ' listfiles';
588 }
589
590 protected function getNavClass() {
591 return parent::getNavClass() . ' listfiles_nav';
592 }
593
594 protected function getSortHeaderClass() {
595 return parent::getSortHeaderClass() . ' listfiles_sort';
596 }
597
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;
605 }
606 }
607 }
608
609 return $queries;
610 }
611
612 function getDefaultQuery() {
613 $queries = parent::getDefaultQuery();
614 if ( !isset( $queries['user'] ) && !is_null( $this->mUserName ) ) {
615 $queries['user'] = $this->mUserName;
616 }
617
618 return $queries;
619 }
620
621 function getTitle() {
622 return SpecialPage::getTitleFor( 'Listfiles' );
623 }
624 }