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