Merge "Add CollationFa"
[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
27 class ImageListPager extends TablePager {
28
29 protected $mFieldNames = null;
30
31 // Subclasses should override buildQueryConds instead of using $mQueryConds variable.
32 protected $mQueryConds = [];
33
34 protected $mUserName = null;
35
36 /**
37 * The relevant user
38 *
39 * @var User|null
40 */
41 protected $mUser = null;
42
43 protected $mSearch = '';
44
45 protected $mIncluding = false;
46
47 protected $mShowAll = false;
48
49 protected $mTableName = 'image';
50
51 function __construct( IContextSource $context, $userName = null, $search = '',
52 $including = false, $showAll = false
53 ) {
54 $this->setContext( $context );
55 $this->mIncluding = $including;
56 $this->mShowAll = $showAll;
57
58 if ( $userName !== null && $userName !== '' ) {
59 $nt = Title::makeTitleSafe( NS_USER, $userName );
60 if ( is_null( $nt ) ) {
61 $this->outputUserDoesNotExist( $userName );
62 } else {
63 $this->mUserName = $nt->getText();
64 $user = User::newFromName( $this->mUserName, false );
65 if ( $user ) {
66 $this->mUser = $user;
67 }
68 if ( !$user || ( $user->isAnon() && !User::isIP( $user->getName() ) ) ) {
69 $this->outputUserDoesNotExist( $userName );
70 }
71 }
72 }
73
74 if ( $search !== '' && !$this->getConfig()->get( 'MiserMode' ) ) {
75 $this->mSearch = $search;
76 $nt = Title::newFromText( $this->mSearch );
77
78 if ( $nt ) {
79 $dbr = wfGetDB( DB_REPLICA );
80 $this->mQueryConds[] = 'LOWER(img_name)' .
81 $dbr->buildLike( $dbr->anyString(),
82 strtolower( $nt->getDBkey() ), $dbr->anyString() );
83 }
84 }
85
86 if ( !$including ) {
87 if ( $this->getRequest()->getText( 'sort', 'img_date' ) == 'img_date' ) {
88 $this->mDefaultDirection = IndexPager::DIR_DESCENDING;
89 } else {
90 $this->mDefaultDirection = IndexPager::DIR_ASCENDING;
91 }
92 } else {
93 $this->mDefaultDirection = IndexPager::DIR_DESCENDING;
94 }
95
96 parent::__construct( $context );
97 }
98
99 /**
100 * Get the user relevant to the ImageList
101 *
102 * @return User|null
103 */
104 function getRelevantUser() {
105 return $this->mUser;
106 }
107
108 /**
109 * Add a message to the output stating that the user doesn't exist
110 *
111 * @param string $userName Unescaped user name
112 */
113 protected function outputUserDoesNotExist( $userName ) {
114 $this->getOutput()->wrapWikiMsg(
115 "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
116 [
117 'listfiles-userdoesnotexist',
118 wfEscapeWikiText( $userName ),
119 ]
120 );
121 }
122
123 /**
124 * Build the where clause of the query.
125 *
126 * Replaces the older mQueryConds member variable.
127 * @param string $table Either "image" or "oldimage"
128 * @return array The query conditions.
129 */
130 protected function buildQueryConds( $table ) {
131 $prefix = $table === 'image' ? 'img' : 'oi';
132 $conds = [];
133
134 if ( !is_null( $this->mUserName ) ) {
135 $conds[$prefix . '_user_text'] = $this->mUserName;
136 }
137
138 if ( $this->mSearch !== '' ) {
139 $nt = Title::newFromText( $this->mSearch );
140 if ( $nt ) {
141 $dbr = wfGetDB( DB_REPLICA );
142 $conds[] = 'LOWER(' . $prefix . '_name)' .
143 $dbr->buildLike( $dbr->anyString(),
144 strtolower( $nt->getDBkey() ), $dbr->anyString() );
145 }
146 }
147
148 if ( $table === 'oldimage' ) {
149 // Don't want to deal with revdel.
150 // Future fixme: Show partial information as appropriate.
151 // Would have to be careful about filtering by username when username is deleted.
152 $conds['oi_deleted'] = 0;
153 }
154
155 // Add mQueryConds in case anyone was subclassing and using the old variable.
156 return $conds + $this->mQueryConds;
157 }
158
159 /**
160 * @return array
161 */
162 function getFieldNames() {
163 if ( !$this->mFieldNames ) {
164 $this->mFieldNames = [
165 'img_timestamp' => $this->msg( 'listfiles_date' )->text(),
166 'img_name' => $this->msg( 'listfiles_name' )->text(),
167 'thumb' => $this->msg( 'listfiles_thumb' )->text(),
168 'img_size' => $this->msg( 'listfiles_size' )->text(),
169 ];
170 if ( is_null( $this->mUserName ) ) {
171 // Do not show username if filtering by username
172 $this->mFieldNames['img_user_text'] = $this->msg( 'listfiles_user' )->text();
173 }
174 // img_description down here, in order so that its still after the username field.
175 $this->mFieldNames['img_description'] = $this->msg( 'listfiles_description' )->text();
176
177 if ( !$this->getConfig()->get( 'MiserMode' ) && !$this->mShowAll ) {
178 $this->mFieldNames['count'] = $this->msg( 'listfiles_count' )->text();
179 }
180 if ( $this->mShowAll ) {
181 $this->mFieldNames['top'] = $this->msg( 'listfiles-latestversion' )->text();
182 }
183 }
184
185 return $this->mFieldNames;
186 }
187
188 function isFieldSortable( $field ) {
189 if ( $this->mIncluding ) {
190 return false;
191 }
192 $sortable = [ 'img_timestamp', 'img_name', 'img_size' ];
193 /* For reference, the indicies we can use for sorting are:
194 * On the image table: img_usertext_timestamp, img_size, img_timestamp
195 * On oldimage: oi_usertext_timestamp, oi_name_timestamp
196 *
197 * In particular that means we cannot sort by timestamp when not filtering
198 * by user and including old images in the results. Which is sad.
199 */
200 if ( $this->getConfig()->get( 'MiserMode' ) && !is_null( $this->mUserName ) ) {
201 // If we're sorting by user, the index only supports sorting by time.
202 if ( $field === 'img_timestamp' ) {
203 return true;
204 } else {
205 return false;
206 }
207 } elseif ( $this->getConfig()->get( 'MiserMode' )
208 && $this->mShowAll /* && mUserName === null */
209 ) {
210 // no oi_timestamp index, so only alphabetical sorting in this case.
211 if ( $field === 'img_name' ) {
212 return true;
213 } else {
214 return false;
215 }
216 }
217
218 return in_array( $field, $sortable );
219 }
220
221 function getQueryInfo() {
222 // Hacky Hacky Hacky - I want to get query info
223 // for two different tables, without reimplementing
224 // the pager class.
225 $qi = $this->getQueryInfoReal( $this->mTableName );
226
227 return $qi;
228 }
229
230 /**
231 * Actually get the query info.
232 *
233 * This is to allow displaying both stuff from image and oldimage table.
234 *
235 * This is a bit hacky.
236 *
237 * @param string $table Either 'image' or 'oldimage'
238 * @return array Query info
239 */
240 protected function getQueryInfoReal( $table ) {
241 $prefix = $table === 'oldimage' ? 'oi' : 'img';
242
243 $tables = [ $table ];
244 $fields = array_keys( $this->getFieldNames() );
245
246 if ( $table === 'oldimage' ) {
247 foreach ( $fields as $id => &$field ) {
248 if ( substr( $field, 0, 4 ) !== 'img_' ) {
249 continue;
250 }
251 $field = $prefix . substr( $field, 3 ) . ' AS ' . $field;
252 }
253 $fields[array_search( 'top', $fields )] = "'no' AS top";
254 } else {
255 if ( $this->mShowAll ) {
256 $fields[array_search( 'top', $fields )] = "'yes' AS top";
257 }
258 }
259 $fields[] = $prefix . '_user AS img_user';
260 $fields[array_search( 'thumb', $fields )] = $prefix . '_name AS thumb';
261
262 $options = $join_conds = [];
263
264 # Depends on $wgMiserMode
265 # Will also not happen if mShowAll is true.
266 if ( isset( $this->mFieldNames['count'] ) ) {
267 $tables[] = 'oldimage';
268
269 # Need to rewrite this one
270 foreach ( $fields as &$field ) {
271 if ( $field == 'count' ) {
272 $field = 'COUNT(oi_archive_name) AS count';
273 }
274 }
275 unset( $field );
276
277 $dbr = wfGetDB( DB_REPLICA );
278 if ( $dbr->implicitGroupby() ) {
279 $options = [ 'GROUP BY' => 'img_name' ];
280 } else {
281 $columnlist = preg_grep( '/^img/', array_keys( $this->getFieldNames() ) );
282 $options = [ 'GROUP BY' => array_merge( [ 'img_user' ], $columnlist ) ];
283 }
284 $join_conds = [ 'oldimage' => [ 'LEFT JOIN', 'oi_name = img_name' ] ];
285 }
286
287 return [
288 'tables' => $tables,
289 'fields' => $fields,
290 'conds' => $this->buildQueryConds( $table ),
291 'options' => $options,
292 'join_conds' => $join_conds
293 ];
294 }
295
296 /**
297 * Override reallyDoQuery to mix together two queries.
298 *
299 * @note $asc is named $descending in IndexPager base class. However
300 * it is true when the order is ascending, and false when the order
301 * is descending, so I renamed it to $asc here.
302 * @param int $offset
303 * @param int $limit
304 * @param bool $asc
305 * @return array
306 * @throws MWException
307 */
308 function reallyDoQuery( $offset, $limit, $asc ) {
309 $prevTableName = $this->mTableName;
310 $this->mTableName = 'image';
311 list( $tables, $fields, $conds, $fname, $options, $join_conds ) =
312 $this->buildQueryInfo( $offset, $limit, $asc );
313 $imageRes = $this->mDb->select( $tables, $fields, $conds, $fname, $options, $join_conds );
314 $this->mTableName = $prevTableName;
315
316 if ( !$this->mShowAll ) {
317 return $imageRes;
318 }
319
320 $this->mTableName = 'oldimage';
321
322 # Hacky...
323 $oldIndex = $this->mIndexField;
324 if ( substr( $this->mIndexField, 0, 4 ) !== 'img_' ) {
325 throw new MWException( "Expected to be sorting on an image table field" );
326 }
327 $this->mIndexField = 'oi_' . substr( $this->mIndexField, 4 );
328
329 list( $tables, $fields, $conds, $fname, $options, $join_conds ) =
330 $this->buildQueryInfo( $offset, $limit, $asc );
331 $oldimageRes = $this->mDb->select( $tables, $fields, $conds, $fname, $options, $join_conds );
332
333 $this->mTableName = $prevTableName;
334 $this->mIndexField = $oldIndex;
335
336 return $this->combineResult( $imageRes, $oldimageRes, $limit, $asc );
337 }
338
339 /**
340 * Combine results from 2 tables.
341 *
342 * Note: This will throw away some results
343 *
344 * @param ResultWrapper $res1
345 * @param ResultWrapper $res2
346 * @param int $limit
347 * @param bool $ascending See note about $asc in $this->reallyDoQuery
348 * @return FakeResultWrapper $res1 and $res2 combined
349 */
350 protected function combineResult( $res1, $res2, $limit, $ascending ) {
351 $res1->rewind();
352 $res2->rewind();
353 $topRes1 = $res1->next();
354 $topRes2 = $res2->next();
355 $resultArray = [];
356 for ( $i = 0; $i < $limit && $topRes1 && $topRes2; $i++ ) {
357 if ( strcmp( $topRes1->{$this->mIndexField}, $topRes2->{$this->mIndexField} ) > 0 ) {
358 if ( !$ascending ) {
359 $resultArray[] = $topRes1;
360 $topRes1 = $res1->next();
361 } else {
362 $resultArray[] = $topRes2;
363 $topRes2 = $res2->next();
364 }
365 } else {
366 if ( !$ascending ) {
367 $resultArray[] = $topRes2;
368 $topRes2 = $res2->next();
369 } else {
370 $resultArray[] = $topRes1;
371 $topRes1 = $res1->next();
372 }
373 }
374 }
375
376 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
377 for ( ; $i < $limit && $topRes1; $i++ ) {
378 // @codingStandardsIgnoreEnd
379 $resultArray[] = $topRes1;
380 $topRes1 = $res1->next();
381 }
382
383 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
384 for ( ; $i < $limit && $topRes2; $i++ ) {
385 // @codingStandardsIgnoreEnd
386 $resultArray[] = $topRes2;
387 $topRes2 = $res2->next();
388 }
389
390 return new FakeResultWrapper( $resultArray );
391 }
392
393 function getDefaultSort() {
394 if ( $this->mShowAll && $this->getConfig()->get( 'MiserMode' ) && is_null( $this->mUserName ) ) {
395 // Unfortunately no index on oi_timestamp.
396 return 'img_name';
397 } else {
398 return 'img_timestamp';
399 }
400 }
401
402 function doBatchLookups() {
403 $userIds = [];
404 $this->mResult->seek( 0 );
405 foreach ( $this->mResult as $row ) {
406 $userIds[] = $row->img_user;
407 }
408 # Do a link batch query for names and userpages
409 UserCache::singleton()->doQuery( $userIds, [ 'userpage' ], __METHOD__ );
410 }
411
412 /**
413 * @param string $field
414 * @param string $value
415 * @return Message|string|int The return type depends on the value of $field:
416 * - thumb: string
417 * - img_timestamp: string
418 * - img_name: string
419 * - img_user_text: string
420 * - img_size: string
421 * - img_description: string
422 * - count: int
423 * - top: Message
424 * @throws MWException
425 */
426 function formatValue( $field, $value ) {
427 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
428 switch ( $field ) {
429 case 'thumb':
430 $opt = [ 'time' => wfTimestamp( TS_MW, $this->mCurrentRow->img_timestamp ) ];
431 $file = RepoGroup::singleton()->getLocalRepo()->findFile( $value, $opt );
432 // If statement for paranoia
433 if ( $file ) {
434 $thumb = $file->transform( [ 'width' => 180, 'height' => 360 ] );
435 if ( $thumb ) {
436 return $thumb->toHtml( [ 'desc-link' => true ] );
437 } else {
438 return wfMessage( 'thumbnail_error', '' )->escaped();
439 }
440 } else {
441 return htmlspecialchars( $value );
442 }
443 case 'img_timestamp':
444 // We may want to make this a link to the "old" version when displaying old files
445 return htmlspecialchars( $this->getLanguage()->userTimeAndDate( $value, $this->getUser() ) );
446 case 'img_name':
447 static $imgfile = null;
448 if ( $imgfile === null ) {
449 $imgfile = $this->msg( 'imgfile' )->text();
450 }
451
452 // Weird files can maybe exist? Bug 22227
453 $filePage = Title::makeTitleSafe( NS_FILE, $value );
454 if ( $filePage ) {
455 $link = $linkRenderer->makeKnownLink(
456 $filePage,
457 $filePage->getText()
458 );
459 $download = Xml::element( 'a',
460 [ 'href' => wfLocalFile( $filePage )->getUrl() ],
461 $imgfile
462 );
463 $download = $this->msg( 'parentheses' )->rawParams( $download )->escaped();
464
465 // Add delete links if allowed
466 // From https://github.com/Wikia/app/pull/3859
467 if ( $filePage->userCan( 'delete', $this->getUser() ) ) {
468 $deleteMsg = $this->msg( 'listfiles-delete' )->text();
469
470 $delete = $linkRenderer->makeKnownLink(
471 $filePage, $deleteMsg, [], [ 'action' => 'delete' ]
472 );
473 $delete = $this->msg( 'parentheses' )->rawParams( $delete )->escaped();
474
475 return "$link $download $delete";
476 }
477
478 return "$link $download";
479 } else {
480 return htmlspecialchars( $value );
481 }
482 case 'img_user_text':
483 if ( $this->mCurrentRow->img_user ) {
484 $name = User::whoIs( $this->mCurrentRow->img_user );
485 $link = $linkRenderer->makeLink(
486 Title::makeTitle( NS_USER, $name ),
487 $name
488 );
489 } else {
490 $link = htmlspecialchars( $value );
491 }
492
493 return $link;
494 case 'img_size':
495 return htmlspecialchars( $this->getLanguage()->formatSize( $value ) );
496 case 'img_description':
497 return Linker::formatComment( $value );
498 case 'count':
499 return $this->getLanguage()->formatNum( intval( $value ) + 1 );
500 case 'top':
501 // Messages: listfiles-latestversion-yes, listfiles-latestversion-no
502 return $this->msg( 'listfiles-latestversion-' . $value );
503 default:
504 throw new MWException( "Unknown field '$field'" );
505 }
506 }
507
508 function getForm() {
509 $fields = [];
510 $fields['limit'] = [
511 'type' => 'select',
512 'name' => 'limit',
513 'label-message' => 'table_pager_limit_label',
514 'options' => $this->getLimitSelectList(),
515 'default' => $this->mLimit,
516 ];
517
518 if ( !$this->getConfig()->get( 'MiserMode' ) ) {
519 $fields['ilsearch'] = [
520 'type' => 'text',
521 'name' => 'ilsearch',
522 'id' => 'mw-ilsearch',
523 'label-message' => 'listfiles_search_for',
524 'default' => $this->mSearch,
525 'size' => '40',
526 'maxlength' => '255',
527 ];
528 }
529
530 $this->getOutput()->addModules( 'mediawiki.userSuggest' );
531 $fields['user'] = [
532 'type' => 'text',
533 'name' => 'user',
534 'id' => 'mw-listfiles-user',
535 'label-message' => 'username',
536 'default' => $this->mUserName,
537 'size' => '40',
538 'maxlength' => '255',
539 'cssclass' => 'mw-autocomplete-user', // used by mediawiki.userSuggest
540 ];
541
542 $fields['ilshowall'] = [
543 'type' => 'check',
544 'name' => 'ilshowall',
545 'id' => 'mw-listfiles-show-all',
546 'label-message' => 'listfiles-show-all',
547 'default' => $this->mShowAll,
548 ];
549
550 $query = $this->getRequest()->getQueryValues();
551 unset( $query['title'] );
552 unset( $query['limit'] );
553 unset( $query['ilsearch'] );
554 unset( $query['ilshowall'] );
555 unset( $query['user'] );
556
557 $form = new HTMLForm( $fields, $this->getContext() );
558
559 $form->setMethod( 'get' );
560 $form->setTitle( $this->getTitle() );
561 $form->setId( 'mw-listfiles-form' );
562 $form->setWrapperLegendMsg( 'listfiles' );
563 $form->setSubmitTextMsg( 'table_pager_limit_submit' );
564 $form->addHiddenFields( $query );
565
566 $form->prepareForm();
567 $form->displayForm( '' );
568 }
569
570 protected function getTableClass() {
571 return parent::getTableClass() . ' listfiles';
572 }
573
574 protected function getNavClass() {
575 return parent::getNavClass() . ' listfiles_nav';
576 }
577
578 protected function getSortHeaderClass() {
579 return parent::getSortHeaderClass() . ' listfiles_sort';
580 }
581
582 function getPagingQueries() {
583 $queries = parent::getPagingQueries();
584 if ( !is_null( $this->mUserName ) ) {
585 # Append the username to the query string
586 foreach ( $queries as &$query ) {
587 if ( $query !== false ) {
588 $query['user'] = $this->mUserName;
589 }
590 }
591 }
592
593 return $queries;
594 }
595
596 function getDefaultQuery() {
597 $queries = parent::getDefaultQuery();
598 if ( !isset( $queries['user'] ) && !is_null( $this->mUserName ) ) {
599 $queries['user'] = $this->mUserName;
600 }
601
602 return $queries;
603 }
604
605 function getTitle() {
606 return SpecialPage::getTitleFor( 'Listfiles' );
607 }
608 }