Merge "rdbms: remove unused $fulltextEnabled field from DatabaseSqlite"
[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 parent::__construct( $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
100 /**
101 * Get the user relevant to the ImageList
102 *
103 * @return User|null
104 */
105 function getRelevantUser() {
106 return $this->mUser;
107 }
108
109 /**
110 * Add a message to the output stating that the user doesn't exist
111 *
112 * @param string $userName Unescaped user name
113 */
114 protected function outputUserDoesNotExist( $userName ) {
115 $this->getOutput()->wrapWikiMsg(
116 "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
117 [
118 'listfiles-userdoesnotexist',
119 wfEscapeWikiText( $userName ),
120 ]
121 );
122 }
123
124 /**
125 * Build the where clause of the query.
126 *
127 * Replaces the older mQueryConds member variable.
128 * @param string $table Either "image" or "oldimage"
129 * @return array The query conditions.
130 */
131 protected function buildQueryConds( $table ) {
132 $prefix = $table === 'image' ? 'img' : 'oi';
133 $conds = [];
134
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(
139 $dbr,
140 $prefix . '_user',
141 User::newFromName( $this->mUserName, false ),
142 // oldimage doesn't have an index on oi_user, while image does. Set $useId accordingly.
143 $prefix === 'img'
144 );
145 $conds[] = $actorWhere['conds'];
146 }
147
148 if ( $this->mSearch !== '' ) {
149 $nt = Title::newFromText( $this->mSearch );
150 if ( $nt ) {
151 $dbr = wfGetDB( DB_REPLICA );
152 $conds[] = 'LOWER(' . $prefix . '_name)' .
153 $dbr->buildLike( $dbr->anyString(),
154 strtolower( $nt->getDBkey() ), $dbr->anyString() );
155 }
156 }
157
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;
163 }
164
165 // Add mQueryConds in case anyone was subclassing and using the old variable.
166 return $conds + $this->mQueryConds;
167 }
168
169 /**
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
173 * @return array
174 */
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(),
182 ];
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();
186 }
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();
189
190 if ( !$this->getConfig()->get( 'MiserMode' ) && !$this->mShowAll ) {
191 $this->mFieldNames['count'] = $this->msg( 'listfiles_count' )->text();
192 }
193 if ( $this->mShowAll ) {
194 $this->mFieldNames['top'] = $this->msg( 'listfiles-latestversion' )->text();
195 }
196 }
197
198 return $this->mFieldNames;
199 }
200
201 function isFieldSortable( $field ) {
202 if ( $this->mIncluding ) {
203 return false;
204 }
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
210 *
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.
213 */
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' ) {
217 return true;
218 } else {
219 return false;
220 }
221 } elseif ( $this->getConfig()->get( 'MiserMode' )
222 && $this->mShowAll /* && mUserName === null */
223 ) {
224 // no oi_timestamp index, so only alphabetical sorting in this case.
225 if ( $field === 'img_name' ) {
226 return true;
227 } else {
228 return false;
229 }
230 }
231
232 return in_array( $field, $sortable );
233 }
234
235 function getQueryInfo() {
236 // Hacky Hacky Hacky - I want to get query info
237 // for two different tables, without reimplementing
238 // the pager class.
239 $qi = $this->getQueryInfoReal( $this->mTableName );
240
241 return $qi;
242 }
243
244 /**
245 * Actually get the query info.
246 *
247 * This is to allow displaying both stuff from image and oldimage table.
248 *
249 * This is a bit hacky.
250 *
251 * @param string $table Either 'image' or 'oldimage'
252 * @return array Query info
253 */
254 protected function getQueryInfoReal( $table ) {
255 $dbr = wfGetDB( DB_REPLICA );
256 $prefix = $table === 'oldimage' ? 'oi' : 'img';
257
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'] );
263
264 if ( $table === 'oldimage' ) {
265 foreach ( $fields as $id => $field ) {
266 if ( substr( $id, 0, 4 ) === 'img_' ) {
267 $fields[$id] = $prefix . substr( $field, 3 );
268 }
269 }
270 $fields['top'] = $dbr->addQuotes( 'no' );
271 } elseif ( $this->mShowAll ) {
272 $fields['top'] = $dbr->addQuotes( 'yes' );
273 }
274 $fields['thumb'] = $prefix . '_name';
275
276 $options = $join_conds = [];
277
278 # Description field
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" );
284
285 # User fields
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'];
292
293 # Depends on $wgMiserMode
294 # Will also not happen if mShowAll is true.
295 if ( isset( $fields['count'] ) ) {
296 $fields['count'] = $dbr->buildSelectSubquery(
297 'oldimage',
298 'COUNT(oi_archive_name)',
299 'oi_name = img_name',
300 __METHOD__
301 );
302 }
303
304 return [
305 'tables' => $tables,
306 'fields' => $fields,
307 'conds' => $this->buildQueryConds( $table ),
308 'options' => $options,
309 'join_conds' => $join_conds
310 ];
311 }
312
313 /**
314 * Override reallyDoQuery to mix together two queries.
315 *
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.
319 * @param int $offset
320 * @param int $limit
321 * @param bool $order IndexPager::QUERY_ASCENDING or IndexPager::QUERY_DESCENDING
322 * @return FakeResultWrapper
323 * @throws MWException
324 */
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;
332
333 if ( !$this->mShowAll ) {
334 return $imageRes;
335 }
336
337 $this->mTableName = 'oldimage';
338
339 # Hacky...
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" );
343 }
344 $this->mIndexField = 'oi_' . substr( $this->mIndexField, 4 );
345
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 );
349
350 $this->mTableName = $prevTableName;
351 $this->mIndexField = $oldIndex;
352
353 return $this->combineResult( $imageRes, $oldimageRes, $limit, $order );
354 }
355
356 /**
357 * Combine results from 2 tables.
358 *
359 * Note: This will throw away some results
360 *
361 * @param IResultWrapper $res1
362 * @param IResultWrapper $res2
363 * @param int $limit
364 * @param bool $ascending See note about $asc in $this->reallyDoQuery
365 * @return FakeResultWrapper $res1 and $res2 combined
366 */
367 protected function combineResult( $res1, $res2, $limit, $ascending ) {
368 $res1->rewind();
369 $res2->rewind();
370 $topRes1 = $res1->next();
371 $topRes2 = $res2->next();
372 $resultArray = [];
373 for ( $i = 0; $i < $limit && $topRes1 && $topRes2; $i++ ) {
374 if ( strcmp( $topRes1->{$this->mIndexField}, $topRes2->{$this->mIndexField} ) > 0 ) {
375 if ( !$ascending ) {
376 $resultArray[] = $topRes1;
377 $topRes1 = $res1->next();
378 } else {
379 $resultArray[] = $topRes2;
380 $topRes2 = $res2->next();
381 }
382 } elseif ( !$ascending ) {
383 $resultArray[] = $topRes2;
384 $topRes2 = $res2->next();
385 } else {
386 $resultArray[] = $topRes1;
387 $topRes1 = $res1->next();
388 }
389 }
390
391 for ( ; $i < $limit && $topRes1; $i++ ) {
392 $resultArray[] = $topRes1;
393 $topRes1 = $res1->next();
394 }
395
396 for ( ; $i < $limit && $topRes2; $i++ ) {
397 $resultArray[] = $topRes2;
398 $topRes2 = $res2->next();
399 }
400
401 return new FakeResultWrapper( $resultArray );
402 }
403
404 function getDefaultSort() {
405 if ( $this->mShowAll && $this->getConfig()->get( 'MiserMode' ) && is_null( $this->mUserName ) ) {
406 // Unfortunately no index on oi_timestamp.
407 return 'img_name';
408 } else {
409 return 'img_timestamp';
410 }
411 }
412
413 protected function doBatchLookups() {
414 $userIds = [];
415 $this->mResult->seek( 0 );
416 foreach ( $this->mResult as $row ) {
417 $userIds[] = $row->img_user;
418 }
419 # Do a link batch query for names and userpages
420 UserCache::singleton()->doQuery( $userIds, [ 'userpage' ], __METHOD__ );
421 }
422
423 /**
424 * @param string $field
425 * @param string $value
426 * @return Message|string|int The return type depends on the value of $field:
427 * - thumb: string
428 * - img_timestamp: string
429 * - img_name: string
430 * - img_user_text: string
431 * - img_size: string
432 * - img_description: string
433 * - count: int
434 * - top: Message
435 * @throws MWException
436 */
437 function formatValue( $field, $value ) {
438 $services = MediaWikiServices::getInstance();
439 $linkRenderer = $this->getLinkRenderer();
440 switch ( $field ) {
441 case 'thumb':
442 $opt = [ 'time' => wfTimestamp( TS_MW, $this->mCurrentRow->img_timestamp ) ];
443 $file = RepoGroup::singleton()->getLocalRepo()->findFile( $value, $opt );
444 // If statement for paranoia
445 if ( $file ) {
446 $thumb = $file->transform( [ 'width' => 180, 'height' => 360 ] );
447 if ( $thumb ) {
448 return $thumb->toHtml( [ 'desc-link' => true ] );
449 } else {
450 return $this->msg( 'thumbnail_error', '' )->escaped();
451 }
452 } else {
453 return htmlspecialchars( $value );
454 }
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() ) );
458 case 'img_name':
459 static $imgfile = null;
460 if ( $imgfile === null ) {
461 $imgfile = $this->msg( 'imgfile' )->text();
462 }
463
464 // Weird files can maybe exist? T24227
465 $filePage = Title::makeTitleSafe( NS_FILE, $value );
466 if ( $filePage ) {
467 $link = $linkRenderer->makeKnownLink(
468 $filePage,
469 $filePage->getText()
470 );
471 $download = Xml::element(
472 'a',
473 [ 'href' => $services->getRepoGroup()->getLocalRepo()->newFile( $filePage )->getUrl() ],
474 $imgfile
475 );
476 $download = $this->msg( 'parentheses' )->rawParams( $download )->escaped();
477
478 // Add delete links if allowed
479 // From https://github.com/Wikia/app/pull/3859
480 $permissionManager = $services->getPermissionManager();
481
482 if ( $permissionManager->userCan( 'delete', $this->getUser(), $filePage ) ) {
483 $deleteMsg = $this->msg( 'listfiles-delete' )->text();
484
485 $delete = $linkRenderer->makeKnownLink(
486 $filePage, $deleteMsg, [], [ 'action' => 'delete' ]
487 );
488 $delete = $this->msg( 'parentheses' )->rawParams( $delete )->escaped();
489
490 return "$link $download $delete";
491 }
492
493 return "$link $download";
494 } else {
495 return htmlspecialchars( $value );
496 }
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 ),
502 $name
503 );
504 } else {
505 $link = htmlspecialchars( $value );
506 }
507
508 return $link;
509 case 'img_size':
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 );
515 case 'count':
516 return $this->getLanguage()->formatNum( intval( $value ) + 1 );
517 case 'top':
518 // Messages: listfiles-latestversion-yes, listfiles-latestversion-no
519 return $this->msg( 'listfiles-latestversion-' . $value )->escaped();
520 default:
521 throw new MWException( "Unknown field '$field'" );
522 }
523 }
524
525 function getForm() {
526 $formDescriptor = [];
527 $formDescriptor['limit'] = [
528 'type' => 'select',
529 'name' => 'limit',
530 'label-message' => 'table_pager_limit_label',
531 'options' => $this->getLimitSelectList(),
532 'default' => $this->mLimit,
533 ];
534
535 if ( !$this->getConfig()->get( 'MiserMode' ) ) {
536 $formDescriptor['ilsearch'] = [
537 'type' => 'text',
538 'name' => 'ilsearch',
539 'id' => 'mw-ilsearch',
540 'label-message' => 'listfiles_search_for',
541 'default' => $this->mSearch,
542 'size' => '40',
543 'maxlength' => '255',
544 ];
545 }
546
547 $formDescriptor['user'] = [
548 'type' => 'user',
549 'name' => 'user',
550 'id' => 'mw-listfiles-user',
551 'label-message' => 'username',
552 'default' => $this->mUserName,
553 'size' => '40',
554 'maxlength' => '255',
555 ];
556
557 $formDescriptor['ilshowall'] = [
558 'type' => 'check',
559 'name' => 'ilshowall',
560 'id' => 'mw-listfiles-show-all',
561 'label-message' => 'listfiles-show-all',
562 'default' => $this->mShowAll,
563 ];
564
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'] );
571
572 $htmlForm = HTMLForm::factory( 'ooui', $formDescriptor, $this->getContext() );
573 $htmlForm
574 ->setMethod( 'get' )
575 ->setId( 'mw-listfiles-form' )
576 ->setTitle( $this->getTitle() )
577 ->setSubmitTextMsg( 'table_pager_limit_submit' )
578 ->setWrapperLegendMsg( 'listfiles' )
579 ->addHiddenFields( $query )
580 ->prepareForm()
581 ->displayForm( '' );
582 }
583
584 protected function getTableClass() {
585 return parent::getTableClass() . ' listfiles';
586 }
587
588 protected function getNavClass() {
589 return parent::getNavClass() . ' listfiles_nav';
590 }
591
592 protected function getSortHeaderClass() {
593 return parent::getSortHeaderClass() . ' listfiles_sort';
594 }
595
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;
603 }
604 }
605 }
606
607 return $queries;
608 }
609
610 function getDefaultQuery() {
611 $queries = parent::getDefaultQuery();
612 if ( !isset( $queries['user'] ) && !is_null( $this->mUserName ) ) {
613 $queries['user'] = $this->mUserName;
614 }
615
616 return $queries;
617 }
618
619 function getTitle() {
620 return SpecialPage::getTitleFor( 'Listfiles' );
621 }
622 }