Merge "SpecialMovepage: Convert form to use OOUI controls"
[lhc/web/wiklou.git] / includes / page / ImagePage.php
1 <?php
2 /**
3 * Special handling for file description pages.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 /**
24 * Class for viewing MediaWiki file description pages
25 *
26 * @ingroup Media
27 */
28 class ImagePage extends Article {
29 /** @var File */
30 private $displayImg;
31
32 /** @var FileRepo */
33 private $repo;
34
35 /** @var bool */
36 private $fileLoaded;
37
38 /** @var bool */
39 protected $mExtraDescription = false;
40
41 /**
42 * @param Title $title
43 * @return WikiFilePage
44 */
45 protected function newPage( Title $title ) {
46 // Overload mPage with a file-specific page
47 return new WikiFilePage( $title );
48 }
49
50 /**
51 * Constructor from a page id
52 * @param int $id Article ID to load
53 * @return ImagePage|null
54 */
55 public static function newFromID( $id ) {
56 $t = Title::newFromID( $id );
57 # @todo FIXME: Doesn't inherit right
58 return $t == null ? null : new self( $t );
59 # return $t == null ? null : new static( $t ); // PHP 5.3
60 }
61
62 /**
63 * @param File $file
64 * @return void
65 */
66 public function setFile( $file ) {
67 $this->mPage->setFile( $file );
68 $this->displayImg = $file;
69 $this->fileLoaded = true;
70 }
71
72 protected function loadFile() {
73 if ( $this->fileLoaded ) {
74 return;
75 }
76 $this->fileLoaded = true;
77
78 $this->displayImg = $img = false;
79 Hooks::run( 'ImagePageFindFile', array( $this, &$img, &$this->displayImg ) );
80 if ( !$img ) { // not set by hook?
81 $img = wfFindFile( $this->getTitle() );
82 if ( !$img ) {
83 $img = wfLocalFile( $this->getTitle() );
84 }
85 }
86 $this->mPage->setFile( $img );
87 if ( !$this->displayImg ) { // not set by hook?
88 $this->displayImg = $img;
89 }
90 $this->repo = $img->getRepo();
91 }
92
93 /**
94 * Handler for action=render
95 * Include body text only; none of the image extras
96 */
97 public function render() {
98 $this->getContext()->getOutput()->setArticleBodyOnly( true );
99 parent::view();
100 }
101
102 public function view() {
103 global $wgShowEXIF;
104
105 $out = $this->getContext()->getOutput();
106 $request = $this->getContext()->getRequest();
107 $diff = $request->getVal( 'diff' );
108 $diffOnly = $request->getBool(
109 'diffonly',
110 $this->getContext()->getUser()->getOption( 'diffonly' )
111 );
112
113 if ( $this->getTitle()->getNamespace() != NS_FILE || ( $diff !== null && $diffOnly ) ) {
114 parent::view();
115 return;
116 }
117
118 $this->loadFile();
119
120 if ( $this->getTitle()->getNamespace() == NS_FILE && $this->mPage->getFile()->getRedirected() ) {
121 if ( $this->getTitle()->getDBkey() == $this->mPage->getFile()->getName() || $diff !== null ) {
122 // mTitle is the same as the redirect target so ask Article
123 // to perform the redirect for us.
124 $request->setVal( 'diffonly', 'true' );
125 parent::view();
126 return;
127 } else {
128 // mTitle is not the same as the redirect target so it is
129 // probably the redirect page itself. Fake the redirect symbol
130 $out->setPageTitle( $this->getTitle()->getPrefixedText() );
131 $out->addHTML( $this->viewRedirect(
132 Title::makeTitle( NS_FILE, $this->mPage->getFile()->getName() ),
133 /* $appendSubtitle */ true,
134 /* $forceKnown */ true )
135 );
136 $this->mPage->doViewUpdates( $this->getContext()->getUser(), $this->getOldID() );
137 return;
138 }
139 }
140
141 if ( $wgShowEXIF && $this->displayImg->exists() ) {
142 // @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
143 $formattedMetadata = $this->displayImg->formatMetadata( $this->getContext() );
144 $showmeta = $formattedMetadata !== false;
145 } else {
146 $showmeta = false;
147 }
148
149 if ( !$diff && $this->displayImg->exists() ) {
150 $out->addHTML( $this->showTOC( $showmeta ) );
151 }
152
153 if ( !$diff ) {
154 $this->openShowImage();
155 }
156
157 # No need to display noarticletext, we use our own message, output in openShowImage()
158 if ( $this->mPage->getID() ) {
159 # NS_FILE is in the user language, but this section (the actual wikitext)
160 # should be in page content language
161 $pageLang = $this->getTitle()->getPageViewLanguage();
162 $out->addHTML( Xml::openElement( 'div', array( 'id' => 'mw-imagepage-content',
163 'lang' => $pageLang->getHtmlCode(), 'dir' => $pageLang->getDir(),
164 'class' => 'mw-content-' . $pageLang->getDir() ) ) );
165
166 parent::view();
167
168 $out->addHTML( Xml::closeElement( 'div' ) );
169 } else {
170 # Just need to set the right headers
171 $out->setArticleFlag( true );
172 $out->setPageTitle( $this->getTitle()->getPrefixedText() );
173 $this->mPage->doViewUpdates( $this->getContext()->getUser(), $this->getOldID() );
174 }
175
176 # Show shared description, if needed
177 if ( $this->mExtraDescription ) {
178 $fol = $this->getContext()->msg( 'shareddescriptionfollows' );
179 if ( !$fol->isDisabled() ) {
180 $out->addWikiText( $fol->plain() );
181 }
182 $out->addHTML( '<div id="shared-image-desc">' . $this->mExtraDescription . "</div>\n" );
183 }
184
185 $this->closeShowImage();
186 $this->imageHistory();
187 // TODO: Cleanup the following
188
189 $out->addHTML( Xml::element( 'h2',
190 array( 'id' => 'filelinks' ),
191 $this->getContext()->msg( 'imagelinks' )->text() ) . "\n" );
192 $this->imageDupes();
193 # @todo FIXME: For some freaky reason, we can't redirect to foreign images.
194 # Yet we return metadata about the target. Definitely an issue in the FileRepo
195 $this->imageLinks();
196
197 # Allow extensions to add something after the image links
198 $html = '';
199 Hooks::run( 'ImagePageAfterImageLinks', array( $this, &$html ) );
200 if ( $html ) {
201 $out->addHTML( $html );
202 }
203
204 if ( $showmeta ) {
205 $out->addHTML( Xml::element(
206 'h2',
207 array( 'id' => 'metadata' ),
208 $this->getContext()->msg( 'metadata' )->text() ) . "\n" );
209 $out->addWikiText( $this->makeMetadataTable( $formattedMetadata ) );
210 $out->addModules( array( 'mediawiki.action.view.metadata' ) );
211 }
212
213 // Add remote Filepage.css
214 if ( !$this->repo->isLocal() ) {
215 $css = $this->repo->getDescriptionStylesheetUrl();
216 if ( $css ) {
217 $out->addStyle( $css );
218 }
219 }
220 // always show the local local Filepage.css, bug 29277
221 $out->addModuleStyles( 'filepage' );
222
223 // Add MediaWiki styles for a file page
224 $out->addModuleStyles( 'mediawiki.action.view.filepage' );
225 }
226
227 /**
228 * @return File
229 */
230 public function getDisplayedFile() {
231 $this->loadFile();
232 return $this->displayImg;
233 }
234
235 /**
236 * Create the TOC
237 *
238 * @param bool $metadata Whether or not to show the metadata link
239 * @return string
240 */
241 protected function showTOC( $metadata ) {
242 $r = array(
243 '<li><a href="#file">' . $this->getContext()->msg( 'file-anchor-link' )->escaped() . '</a></li>',
244 '<li><a href="#filehistory">' . $this->getContext()->msg( 'filehist' )->escaped() . '</a></li>',
245 '<li><a href="#filelinks">' . $this->getContext()->msg( 'imagelinks' )->escaped() . '</a></li>',
246 );
247
248 Hooks::run( 'ImagePageShowTOC', array( $this, &$r ) );
249
250 if ( $metadata ) {
251 $r[] = '<li><a href="#metadata">' . $this->getContext()->msg( 'metadata' )->escaped() . '</a></li>';
252 }
253
254 return '<ul id="filetoc">' . implode( "\n", $r ) . '</ul>';
255 }
256
257 /**
258 * Make a table with metadata to be shown in the output page.
259 *
260 * @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
261 *
262 * @param array $metadata The array containing the Exif data
263 * @return string The metadata table. This is treated as Wikitext (!)
264 */
265 protected function makeMetadataTable( $metadata ) {
266 $r = "<div class=\"mw-imagepage-section-metadata\">";
267 $r .= $this->getContext()->msg( 'metadata-help' )->plain();
268 $r .= "<table id=\"mw_metadata\" class=\"mw_metadata\">\n";
269 foreach ( $metadata as $type => $stuff ) {
270 foreach ( $stuff as $v ) {
271 # @todo FIXME: Why is this using escapeId for a class?!
272 $class = Sanitizer::escapeId( $v['id'] );
273 if ( $type == 'collapsed' ) {
274 // Handled by mediawiki.action.view.metadata module.
275 $class .= ' collapsable';
276 }
277 $r .= "<tr class=\"$class\">\n";
278 $r .= "<th>{$v['name']}</th>\n";
279 $r .= "<td>{$v['value']}</td>\n</tr>";
280 }
281 }
282 $r .= "</table>\n</div>\n";
283 return $r;
284 }
285
286 /**
287 * Overloading Article's getContentObject method.
288 *
289 * Omit noarticletext if sharedupload; text will be fetched from the
290 * shared upload server if possible.
291 * @return string
292 */
293 public function getContentObject() {
294 $this->loadFile();
295 if ( $this->mPage->getFile() && !$this->mPage->getFile()->isLocal() && 0 == $this->getID() ) {
296 return null;
297 }
298 return parent::getContentObject();
299 }
300
301 protected function openShowImage() {
302 global $wgEnableUploads, $wgSend404Code, $wgSVGMaxSize;
303
304 $this->loadFile();
305 $out = $this->getContext()->getOutput();
306 $user = $this->getContext()->getUser();
307 $lang = $this->getContext()->getLanguage();
308 $dirmark = $lang->getDirMarkEntity();
309 $request = $this->getContext()->getRequest();
310
311 $max = $this->getImageLimitsFromOption( $user, 'imagesize' );
312 $maxWidth = $max[0];
313 $maxHeight = $max[1];
314
315 if ( $this->displayImg->exists() ) {
316 # image
317 $page = $request->getIntOrNull( 'page' );
318 if ( is_null( $page ) ) {
319 $params = array();
320 $page = 1;
321 } else {
322 $params = array( 'page' => $page );
323 }
324
325 $renderLang = $request->getVal( 'lang' );
326 if ( !is_null( $renderLang ) ) {
327 $handler = $this->displayImg->getHandler();
328 if ( $handler && $handler->validateParam( 'lang', $renderLang ) ) {
329 $params['lang'] = $renderLang;
330 } else {
331 $renderLang = null;
332 }
333 }
334
335 $width_orig = $this->displayImg->getWidth( $page );
336 $width = $width_orig;
337 $height_orig = $this->displayImg->getHeight( $page );
338 $height = $height_orig;
339
340 $filename = wfEscapeWikiText( $this->displayImg->getName() );
341 $linktext = $filename;
342
343 Hooks::run( 'ImageOpenShowImageInlineBefore', array( &$this, &$out ) );
344
345 if ( $this->displayImg->allowInlineDisplay() ) {
346 # image
347 # "Download high res version" link below the image
348 # $msgsize = $this->getContext()->msg( 'file-info-size', $width_orig, $height_orig,
349 # Linker::formatSize( $this->displayImg->getSize() ), $mime )->escaped();
350 # We'll show a thumbnail of this image
351 if ( $width > $maxWidth || $height > $maxHeight || $this->displayImg->isVectorized() ) {
352 list( $width, $height ) = $this->getDisplayWidthHeight(
353 $maxWidth, $maxHeight, $width, $height
354 );
355 $linktext = $this->getContext()->msg( 'show-big-image' )->escaped();
356
357 $thumbSizes = $this->getThumbSizes( $width_orig, $height_orig );
358 # Generate thumbnails or thumbnail links as needed...
359 $otherSizes = array();
360 foreach ( $thumbSizes as $size ) {
361 // We include a thumbnail size in the list, if it is
362 // less than or equal to the original size of the image
363 // asset ($width_orig/$height_orig). We also exclude
364 // the current thumbnail's size ($width/$height)
365 // since that is added to the message separately, so
366 // it can be denoted as the current size being shown.
367 // Vectorized images are limited by $wgSVGMaxSize big,
368 // so all thumbs less than or equal that are shown.
369 if ( ( ( $size[0] <= $width_orig && $size[1] <= $height_orig )
370 || ( $this->displayImg->isVectorized()
371 && max( $size[0], $size[1] ) <= $wgSVGMaxSize )
372 )
373 && $size[0] != $width && $size[1] != $height
374 ) {
375 $sizeLink = $this->makeSizeLink( $params, $size[0], $size[1] );
376 if ( $sizeLink ) {
377 $otherSizes[] = $sizeLink;
378 }
379 }
380 }
381 $otherSizes = array_unique( $otherSizes );
382
383 $msgsmall = '';
384 $sizeLinkBigImagePreview = $this->makeSizeLink( $params, $width, $height );
385 if ( $sizeLinkBigImagePreview ) {
386 $msgsmall .= $this->getContext()->msg( 'show-big-image-preview' )->
387 rawParams( $sizeLinkBigImagePreview )->
388 parse();
389 }
390 if ( count( $otherSizes ) ) {
391 $msgsmall .= ' ' .
392 Html::rawElement( 'span', array( 'class' => 'mw-filepage-other-resolutions' ),
393 $this->getContext()->msg( 'show-big-image-other' )->rawParams( $lang->pipeList( $otherSizes ) )->
394 params( count( $otherSizes ) )->parse()
395 );
396 }
397 } elseif ( $width == 0 && $height == 0 ) {
398 # Some sort of audio file that doesn't have dimensions
399 # Don't output a no hi res message for such a file
400 $msgsmall = '';
401 } else {
402 # Image is small enough to show full size on image page
403 $msgsmall = $this->getContext()->msg( 'file-nohires' )->parse();
404 }
405
406 $params['width'] = $width;
407 $params['height'] = $height;
408 $thumbnail = $this->displayImg->transform( $params );
409 Linker::processResponsiveImages( $this->displayImg, $thumbnail, $params );
410
411 $anchorclose = Html::rawElement(
412 'div',
413 array( 'class' => 'mw-filepage-resolutioninfo' ),
414 $msgsmall
415 );
416
417 $isMulti = $this->displayImg->isMultipage() && $this->displayImg->pageCount() > 1;
418 if ( $isMulti ) {
419 $out->addModules( 'mediawiki.page.image.pagination' );
420 $out->addHTML( '<table class="multipageimage"><tr><td>' );
421 }
422
423 if ( $thumbnail ) {
424 $options = array(
425 'alt' => $this->displayImg->getTitle()->getPrefixedText(),
426 'file-link' => true,
427 );
428 $out->addHTML( '<div class="fullImageLink" id="file">' .
429 $thumbnail->toHtml( $options ) .
430 $anchorclose . "</div>\n" );
431 }
432
433 if ( $isMulti ) {
434 $count = $this->displayImg->pageCount();
435
436 if ( $page > 1 ) {
437 $label = $out->parse( $this->getContext()->msg( 'imgmultipageprev' )->text(), false );
438 // on the client side, this link is generated in ajaxifyPageNavigation()
439 // in the mediawiki.page.image.pagination module
440 $link = Linker::linkKnown(
441 $this->getTitle(),
442 $label,
443 array(),
444 array( 'page' => $page - 1 )
445 );
446 $thumb1 = Linker::makeThumbLinkObj(
447 $this->getTitle(),
448 $this->displayImg,
449 $link,
450 $label,
451 'none',
452 array( 'page' => $page - 1 )
453 );
454 } else {
455 $thumb1 = '';
456 }
457
458 if ( $page < $count ) {
459 $label = $this->getContext()->msg( 'imgmultipagenext' )->text();
460 $link = Linker::linkKnown(
461 $this->getTitle(),
462 $label,
463 array(),
464 array( 'page' => $page + 1 )
465 );
466 $thumb2 = Linker::makeThumbLinkObj(
467 $this->getTitle(),
468 $this->displayImg,
469 $link,
470 $label,
471 'none',
472 array( 'page' => $page + 1 )
473 );
474 } else {
475 $thumb2 = '';
476 }
477
478 global $wgScript;
479
480 $formParams = array(
481 'name' => 'pageselector',
482 'action' => $wgScript,
483 );
484 $options = array();
485 for ( $i = 1; $i <= $count; $i++ ) {
486 $options[] = Xml::option( $lang->formatNum( $i ), $i, $i == $page );
487 }
488 $select = Xml::tags( 'select',
489 array( 'id' => 'pageselector', 'name' => 'page' ),
490 implode( "\n", $options ) );
491
492 $out->addHTML(
493 '</td><td><div class="multipageimagenavbox">' .
494 Xml::openElement( 'form', $formParams ) .
495 Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() ) .
496 $this->getContext()->msg( 'imgmultigoto' )->rawParams( $select )->parse() .
497 Xml::submitButton( $this->getContext()->msg( 'imgmultigo' )->text() ) .
498 Xml::closeElement( 'form' ) .
499 "<hr />$thumb1\n$thumb2<br style=\"clear: both\" /></div></td></tr></table>"
500 );
501 }
502 } elseif ( $this->displayImg->isSafeFile() ) {
503 # if direct link is allowed but it's not a renderable image, show an icon.
504 $icon = $this->displayImg->iconThumb();
505
506 $out->addHTML( '<div class="fullImageLink" id="file">' .
507 $icon->toHtml( array( 'file-link' => true ) ) .
508 "</div>\n" );
509 }
510
511 $longDesc = $this->getContext()->msg( 'parentheses', $this->displayImg->getLongDesc() )->text();
512
513 $handler = $this->displayImg->getHandler();
514
515 // If this is a filetype with potential issues, warn the user.
516 if ( $handler ) {
517 $warningConfig = $handler->getWarningConfig( $this->displayImg );
518
519 if ( $warningConfig !== null ) {
520 // The warning will be displayed via CSS and JavaScript.
521 // We just need to tell the client side what message to use.
522 $output = $this->getContext()->getOutput();
523 $output->addJsConfigVars( 'wgFileWarning', $warningConfig );
524 $output->addModules( $warningConfig['module'] );
525 $output->addModules( 'mediawiki.filewarning' );
526 }
527 }
528
529 $medialink = "[[Media:$filename|$linktext]]";
530
531 if ( !$this->displayImg->isSafeFile() ) {
532 $warning = $this->getContext()->msg( 'mediawarning' )->plain();
533 // dirmark is needed here to separate the file name, which
534 // most likely ends in Latin characters, from the description,
535 // which may begin with the file type. In RTL environment
536 // this will get messy.
537 // The dirmark, however, must not be immediately adjacent
538 // to the filename, because it can get copied with it.
539 // See bug 25277.
540 // @codingStandardsIgnoreStart Ignore long line
541 $out->addWikiText( <<<EOT
542 <div class="fullMedia"><span class="dangerousLink">{$medialink}</span> $dirmark<span class="fileInfo">$longDesc</span></div>
543 <div class="mediaWarning">$warning</div>
544 EOT
545 );
546 // @codingStandardsIgnoreEnd
547 } else {
548 $out->addWikiText( <<<EOT
549 <div class="fullMedia">{$medialink} {$dirmark}<span class="fileInfo">$longDesc</span>
550 </div>
551 EOT
552 );
553 }
554
555 $renderLangOptions = $this->displayImg->getAvailableLanguages();
556 if ( count( $renderLangOptions ) >= 1 ) {
557 $currentLanguage = $renderLang;
558 $defaultLang = $this->displayImg->getDefaultRenderLanguage();
559 if ( is_null( $currentLanguage ) ) {
560 $currentLanguage = $defaultLang;
561 }
562 $out->addHtml( $this->doRenderLangOpt( $renderLangOptions, $currentLanguage, $defaultLang ) );
563 }
564
565 // Add cannot animate thumbnail warning
566 if ( !$this->displayImg->canAnimateThumbIfAppropriate() ) {
567 // Include the extension so wiki admins can
568 // customize it on a per file-type basis
569 // (aka say things like use format X instead).
570 // additionally have a specific message for
571 // file-no-thumb-animation-gif
572 $ext = $this->displayImg->getExtension();
573 $noAnimMesg = wfMessageFallback(
574 'file-no-thumb-animation-' . $ext,
575 'file-no-thumb-animation'
576 )->plain();
577
578 $out->addWikiText( <<<EOT
579 <div class="mw-noanimatethumb">{$noAnimMesg}</div>
580 EOT
581 );
582 }
583
584 if ( !$this->displayImg->isLocal() ) {
585 $this->printSharedImageText();
586 }
587 } else {
588 # Image does not exist
589 if ( !$this->getID() ) {
590 # No article exists either
591 # Show deletion log to be consistent with normal articles
592 LogEventsList::showLogExtract(
593 $out,
594 array( 'delete', 'move' ),
595 $this->getTitle()->getPrefixedText(),
596 '',
597 array( 'lim' => 10,
598 'conds' => array( "log_action != 'revision'" ),
599 'showIfEmpty' => false,
600 'msgKey' => array( 'moveddeleted-notice' )
601 )
602 );
603 }
604
605 if ( $wgEnableUploads && $user->isAllowed( 'upload' ) ) {
606 // Only show an upload link if the user can upload
607 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
608 $nofile = array(
609 'filepage-nofile-link',
610 $uploadTitle->getFullURL( array( 'wpDestFile' => $this->mPage->getFile()->getName() ) )
611 );
612 } else {
613 $nofile = 'filepage-nofile';
614 }
615 // Note, if there is an image description page, but
616 // no image, then this setRobotPolicy is overridden
617 // by Article::View().
618 $out->setRobotPolicy( 'noindex,nofollow' );
619 $out->wrapWikiMsg( "<div id='mw-imagepage-nofile' class='plainlinks'>\n$1\n</div>", $nofile );
620 if ( !$this->getID() && $wgSend404Code ) {
621 // If there is no image, no shared image, and no description page,
622 // output a 404, to be consistent with Article::showMissingArticle.
623 $request->response()->statusHeader( 404 );
624 }
625 }
626 $out->setFileVersion( $this->displayImg );
627 }
628
629 /**
630 * Creates an thumbnail of specified size and returns an HTML link to it
631 * @param array $params Scaler parameters
632 * @param int $width
633 * @param int $height
634 * @return string
635 */
636 private function makeSizeLink( $params, $width, $height ) {
637 $params['width'] = $width;
638 $params['height'] = $height;
639 $thumbnail = $this->displayImg->transform( $params );
640 if ( $thumbnail && !$thumbnail->isError() ) {
641 return Html::rawElement( 'a', array(
642 'href' => $thumbnail->getUrl(),
643 'class' => 'mw-thumbnail-link'
644 ), $this->getContext()->msg( 'show-big-image-size' )->numParams(
645 $thumbnail->getWidth(), $thumbnail->getHeight()
646 )->parse() );
647 } else {
648 return '';
649 }
650 }
651
652 /**
653 * Show a notice that the file is from a shared repository
654 */
655 protected function printSharedImageText() {
656 $out = $this->getContext()->getOutput();
657 $this->loadFile();
658
659 $descUrl = $this->mPage->getFile()->getDescriptionUrl();
660 $descText = $this->mPage->getFile()->getDescriptionText( $this->getContext()->getLanguage() );
661
662 /* Add canonical to head if there is no local page for this shared file */
663 if ( $descUrl && $this->mPage->getID() == 0 ) {
664 $out->setCanonicalUrl( $descUrl );
665 }
666
667 $wrap = "<div class=\"sharedUploadNotice\">\n$1\n</div>\n";
668 $repo = $this->mPage->getFile()->getRepo()->getDisplayName();
669
670 if ( $descUrl && $descText && $this->getContext()->msg( 'sharedupload-desc-here' )->plain() !== '-' ) {
671 $out->wrapWikiMsg( $wrap, array( 'sharedupload-desc-here', $repo, $descUrl ) );
672 } elseif ( $descUrl && $this->getContext()->msg( 'sharedupload-desc-there' )->plain() !== '-' ) {
673 $out->wrapWikiMsg( $wrap, array( 'sharedupload-desc-there', $repo, $descUrl ) );
674 } else {
675 $out->wrapWikiMsg( $wrap, array( 'sharedupload', $repo ), ''/*BACKCOMPAT*/ );
676 }
677
678 if ( $descText ) {
679 $this->mExtraDescription = $descText;
680 }
681 }
682
683 public function getUploadUrl() {
684 $this->loadFile();
685 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
686 return $uploadTitle->getFullURL( array(
687 'wpDestFile' => $this->mPage->getFile()->getName(),
688 'wpForReUpload' => 1
689 ) );
690 }
691
692 /**
693 * Print out the various links at the bottom of the image page, e.g. reupload,
694 * external editing (and instructions link) etc.
695 */
696 protected function uploadLinksBox() {
697 global $wgEnableUploads;
698
699 if ( !$wgEnableUploads ) {
700 return;
701 }
702
703 $this->loadFile();
704 if ( !$this->mPage->getFile()->isLocal() ) {
705 return;
706 }
707
708 $out = $this->getContext()->getOutput();
709 $out->addHTML( "<ul>\n" );
710
711 # "Upload a new version of this file" link
712 $canUpload = $this->getTitle()->quickUserCan( 'upload', $this->getContext()->getUser() );
713 if ( $canUpload && UploadBase::userCanReUpload(
714 $this->getContext()->getUser(),
715 $this->mPage->getFile()->name )
716 ) {
717 $ulink = Linker::makeExternalLink(
718 $this->getUploadUrl(),
719 $this->getContext()->msg( 'uploadnewversion-linktext' )->text()
720 );
721 $out->addHTML( "<li id=\"mw-imagepage-reupload-link\">"
722 . "<div class=\"plainlinks\">{$ulink}</div></li>\n" );
723 } else {
724 $out->addHTML( "<li id=\"mw-imagepage-upload-disallowed\">"
725 . $this->getContext()->msg( 'upload-disallowed-here' )->escaped() . "</li>\n" );
726 }
727
728 $out->addHTML( "</ul>\n" );
729 }
730
731 /**
732 * For overloading
733 */
734 protected function closeShowImage() {
735 }
736
737 /**
738 * If the page we've just displayed is in the "Image" namespace,
739 * we follow it with an upload history of the image and its usage.
740 */
741 protected function imageHistory() {
742 $this->loadFile();
743 $out = $this->getContext()->getOutput();
744 $pager = new ImageHistoryPseudoPager( $this );
745 $out->addHTML( $pager->getBody() );
746 $out->preventClickjacking( $pager->getPreventClickjacking() );
747
748 $this->mPage->getFile()->resetHistory(); // free db resources
749
750 # Exist check because we don't want to show this on pages where an image
751 # doesn't exist along with the noimage message, that would suck. -ævar
752 if ( $this->mPage->getFile()->exists() ) {
753 $this->uploadLinksBox();
754 }
755 }
756
757 /**
758 * @param string $target
759 * @param int $limit
760 * @return ResultWrapper
761 */
762 protected function queryImageLinks( $target, $limit ) {
763 $dbr = wfGetDB( DB_SLAVE );
764
765 return $dbr->select(
766 array( 'imagelinks', 'page' ),
767 array( 'page_namespace', 'page_title', 'il_to' ),
768 array( 'il_to' => $target, 'il_from = page_id' ),
769 __METHOD__,
770 array( 'LIMIT' => $limit + 1, 'ORDER BY' => 'il_from', )
771 );
772 }
773
774 protected function imageLinks() {
775 $limit = 100;
776
777 $out = $this->getContext()->getOutput();
778
779 $rows = array();
780 $redirects = array();
781 foreach ( $this->getTitle()->getRedirectsHere( NS_FILE ) as $redir ) {
782 $redirects[$redir->getDBkey()] = array();
783 $rows[] = (object)array(
784 'page_namespace' => NS_FILE,
785 'page_title' => $redir->getDBkey(),
786 );
787 }
788
789 $res = $this->queryImageLinks( $this->getTitle()->getDBkey(), $limit + 1 );
790 foreach ( $res as $row ) {
791 $rows[] = $row;
792 }
793 $count = count( $rows );
794
795 $hasMore = $count > $limit;
796 if ( !$hasMore && count( $redirects ) ) {
797 $res = $this->queryImageLinks( array_keys( $redirects ),
798 $limit - count( $rows ) + 1 );
799 foreach ( $res as $row ) {
800 $redirects[$row->il_to][] = $row;
801 $count++;
802 }
803 $hasMore = ( $res->numRows() + count( $rows ) ) > $limit;
804 }
805
806 if ( $count == 0 ) {
807 $out->wrapWikiMsg(
808 Html::rawElement( 'div',
809 array( 'id' => 'mw-imagepage-nolinkstoimage' ), "\n$1\n" ),
810 'nolinkstoimage'
811 );
812 return;
813 }
814
815 $out->addHTML( "<div id='mw-imagepage-section-linkstoimage'>\n" );
816 if ( !$hasMore ) {
817 $out->addWikiMsg( 'linkstoimage', $count );
818 } else {
819 // More links than the limit. Add a link to [[Special:Whatlinkshere]]
820 $out->addWikiMsg( 'linkstoimage-more',
821 $this->getContext()->getLanguage()->formatNum( $limit ),
822 $this->getTitle()->getPrefixedDBkey()
823 );
824 }
825
826 $out->addHTML(
827 Html::openElement( 'ul',
828 array( 'class' => 'mw-imagepage-linkstoimage' ) ) . "\n"
829 );
830 $count = 0;
831
832 // Sort the list by namespace:title
833 usort( $rows, array( $this, 'compare' ) );
834
835 // Create links for every element
836 $currentCount = 0;
837 foreach ( $rows as $element ) {
838 $currentCount++;
839 if ( $currentCount > $limit ) {
840 break;
841 }
842
843 $query = array();
844 # Add a redirect=no to make redirect pages reachable
845 if ( isset( $redirects[$element->page_title] ) ) {
846 $query['redirect'] = 'no';
847 }
848 $link = Linker::linkKnown(
849 Title::makeTitle( $element->page_namespace, $element->page_title ),
850 null, array(), $query
851 );
852 if ( !isset( $redirects[$element->page_title] ) ) {
853 # No redirects
854 $liContents = $link;
855 } elseif ( count( $redirects[$element->page_title] ) === 0 ) {
856 # Redirect without usages
857 $liContents = $this->getContext()->msg( 'linkstoimage-redirect' )->rawParams( $link, '' )->parse();
858 } else {
859 # Redirect with usages
860 $li = '';
861 foreach ( $redirects[$element->page_title] as $row ) {
862 $currentCount++;
863 if ( $currentCount > $limit ) {
864 break;
865 }
866
867 $link2 = Linker::linkKnown( Title::makeTitle( $row->page_namespace, $row->page_title ) );
868 $li .= Html::rawElement(
869 'li',
870 array( 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ),
871 $link2
872 ) . "\n";
873 }
874
875 $ul = Html::rawElement(
876 'ul',
877 array( 'class' => 'mw-imagepage-redirectstofile' ),
878 $li
879 ) . "\n";
880 $liContents = $this->getContext()->msg( 'linkstoimage-redirect' )->rawParams(
881 $link, $ul )->parse();
882 }
883 $out->addHTML( Html::rawElement(
884 'li',
885 array( 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ),
886 $liContents
887 ) . "\n"
888 );
889
890 };
891 $out->addHTML( Html::closeElement( 'ul' ) . "\n" );
892 $res->free();
893
894 // Add a links to [[Special:Whatlinkshere]]
895 if ( $count > $limit ) {
896 $out->addWikiMsg( 'morelinkstoimage', $this->getTitle()->getPrefixedDBkey() );
897 }
898 $out->addHTML( Html::closeElement( 'div' ) . "\n" );
899 }
900
901 protected function imageDupes() {
902 $this->loadFile();
903 $out = $this->getContext()->getOutput();
904
905 $dupes = $this->mPage->getDuplicates();
906 if ( count( $dupes ) == 0 ) {
907 return;
908 }
909
910 $out->addHTML( "<div id='mw-imagepage-section-duplicates'>\n" );
911 $out->addWikiMsg( 'duplicatesoffile',
912 $this->getContext()->getLanguage()->formatNum( count( $dupes ) ), $this->getTitle()->getDBkey()
913 );
914 $out->addHTML( "<ul class='mw-imagepage-duplicates'>\n" );
915
916 /**
917 * @var $file File
918 */
919 foreach ( $dupes as $file ) {
920 $fromSrc = '';
921 if ( $file->isLocal() ) {
922 $link = Linker::linkKnown( $file->getTitle() );
923 } else {
924 $link = Linker::makeExternalLink( $file->getDescriptionUrl(),
925 $file->getTitle()->getPrefixedText() );
926 $fromSrc = $this->getContext()->msg( 'shared-repo-from', $file->getRepo()->getDisplayName() )->text();
927 }
928 $out->addHTML( "<li>{$link} {$fromSrc}</li>\n" );
929 }
930 $out->addHTML( "</ul></div>\n" );
931 }
932
933 /**
934 * Delete the file, or an earlier version of it
935 */
936 public function delete() {
937 $file = $this->mPage->getFile();
938 if ( !$file->exists() || !$file->isLocal() || $file->getRedirected() ) {
939 // Standard article deletion
940 parent::delete();
941 return;
942 }
943
944 $deleter = new FileDeleteForm( $file );
945 $deleter->execute();
946 }
947
948 /**
949 * Display an error with a wikitext description
950 *
951 * @param string $description
952 */
953 function showError( $description ) {
954 $out = $this->getContext()->getOutput();
955 $out->setPageTitle( $this->getContext()->msg( 'internalerror' ) );
956 $out->setRobotPolicy( 'noindex,nofollow' );
957 $out->setArticleRelated( false );
958 $out->enableClientCache( false );
959 $out->addWikiText( $description );
960 }
961
962 /**
963 * Callback for usort() to do link sorts by (namespace, title)
964 * Function copied from Title::compare()
965 *
966 * @param object $a Object page to compare with
967 * @param object $b Object page to compare with
968 * @return int Result of string comparison, or namespace comparison
969 */
970 protected function compare( $a, $b ) {
971 if ( $a->page_namespace == $b->page_namespace ) {
972 return strcmp( $a->page_title, $b->page_title );
973 } else {
974 return $a->page_namespace - $b->page_namespace;
975 }
976 }
977
978 /**
979 * Returns the corresponding $wgImageLimits entry for the selected user option
980 *
981 * @param User $user
982 * @param string $optionName Name of a option to check, typically imagesize or thumbsize
983 * @return array
984 * @since 1.21
985 */
986 public function getImageLimitsFromOption( $user, $optionName ) {
987 global $wgImageLimits;
988
989 $option = $user->getIntOption( $optionName );
990 if ( !isset( $wgImageLimits[$option] ) ) {
991 $option = User::getDefaultOption( $optionName );
992 }
993
994 // The user offset might still be incorrect, specially if
995 // $wgImageLimits got changed (see bug #8858).
996 if ( !isset( $wgImageLimits[$option] ) ) {
997 // Default to the first offset in $wgImageLimits
998 $option = 0;
999 }
1000
1001 return isset( $wgImageLimits[$option] )
1002 ? $wgImageLimits[$option]
1003 : array( 800, 600 ); // if nothing is set, fallback to a hardcoded default
1004 }
1005
1006 /**
1007 * Output a drop-down box for language options for the file
1008 *
1009 * @param array $langChoices Array of string language codes
1010 * @param string $curLang Language code file is being viewed in.
1011 * @param string $defaultLang Language code that image is rendered in by default
1012 * @return string HTML to insert underneath image.
1013 */
1014 protected function doRenderLangOpt( array $langChoices, $curLang, $defaultLang ) {
1015 global $wgScript;
1016 sort( $langChoices );
1017 $curLang = wfBCP47( $curLang );
1018 $defaultLang = wfBCP47( $defaultLang );
1019 $opts = '';
1020 $haveCurrentLang = false;
1021 $haveDefaultLang = false;
1022
1023 // We make a list of all the language choices in the file.
1024 // Additionally if the default language to render this file
1025 // is not included as being in this file (for example, in svgs
1026 // usually the fallback content is the english content) also
1027 // include a choice for that. Last of all, if we're viewing
1028 // the file in a language not on the list, add it as a choice.
1029 foreach ( $langChoices as $lang ) {
1030 $code = wfBCP47( $lang );
1031 $name = Language::fetchLanguageName( $code, $this->getContext()->getLanguage()->getCode() );
1032 if ( $name !== '' ) {
1033 $display = $this->getContext()->msg( 'img-lang-opt', $code, $name )->text();
1034 } else {
1035 $display = $code;
1036 }
1037 $opts .= "\n" . Xml::option( $display, $code, $curLang === $code );
1038 if ( $curLang === $code ) {
1039 $haveCurrentLang = true;
1040 }
1041 if ( $defaultLang === $code ) {
1042 $haveDefaultLang = true;
1043 }
1044 }
1045 if ( !$haveDefaultLang ) {
1046 // Its hard to know if the content is really in the default language, or
1047 // if its just unmarked content that could be in any language.
1048 $opts = Xml::option(
1049 $this->getContext()->msg( 'img-lang-default' )->text(),
1050 $defaultLang,
1051 $defaultLang === $curLang
1052 ) . $opts;
1053 }
1054 if ( !$haveCurrentLang && $defaultLang !== $curLang ) {
1055 $name = Language::fetchLanguageName( $curLang, $this->getContext()->getLanguage()->getCode() );
1056 if ( $name !== '' ) {
1057 $display = $this->getContext()->msg( 'img-lang-opt', $curLang, $name )->text();
1058 } else {
1059 $display = $curLang;
1060 }
1061 $opts = Xml::option( $display, $curLang, true ) . $opts;
1062 }
1063
1064 $select = Html::rawElement(
1065 'select',
1066 array( 'id' => 'mw-imglangselector', 'name' => 'lang' ),
1067 $opts
1068 );
1069 $submit = Xml::submitButton( $this->getContext()->msg( 'img-lang-go' )->text() );
1070
1071 $formContents = $this->getContext()->msg( 'img-lang-info' )->rawParams( $select, $submit )->parse()
1072 . Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() );
1073
1074 $langSelectLine = Html::rawElement( 'div', array( 'id' => 'mw-imglangselector-line' ),
1075 Html::rawElement( 'form', array( 'action' => $wgScript ), $formContents )
1076 );
1077 return $langSelectLine;
1078 }
1079
1080 /**
1081 * Get the width and height to display image at.
1082 *
1083 * @note This method assumes that it is only called if one
1084 * of the dimensions are bigger than the max, or if the
1085 * image is vectorized.
1086 *
1087 * @param int $maxWidth Max width to display at
1088 * @param int $maxHeight Max height to display at
1089 * @param int $width Actual width of the image
1090 * @param int $height Actual height of the image
1091 * @throws MWException
1092 * @return array Array (width, height)
1093 */
1094 protected function getDisplayWidthHeight( $maxWidth, $maxHeight, $width, $height ) {
1095 if ( !$maxWidth || !$maxHeight ) {
1096 // should never happen
1097 throw new MWException( 'Using a choice from $wgImageLimits that is 0x0' );
1098 }
1099
1100 if ( !$width || !$height ) {
1101 return array( 0, 0 );
1102 }
1103
1104 # Calculate the thumbnail size.
1105 if ( $width <= $maxWidth && $height <= $maxHeight ) {
1106 // Vectorized image, do nothing.
1107 } elseif ( $width / $height >= $maxWidth / $maxHeight ) {
1108 # The limiting factor is the width, not the height.
1109 $height = round( $height * $maxWidth / $width );
1110 $width = $maxWidth;
1111 # Note that $height <= $maxHeight now.
1112 } else {
1113 $newwidth = floor( $width * $maxHeight / $height );
1114 $height = round( $height * $newwidth / $width );
1115 $width = $newwidth;
1116 # Note that $height <= $maxHeight now, but might not be identical
1117 # because of rounding.
1118 }
1119 return array( $width, $height );
1120 }
1121
1122 /**
1123 * Get alternative thumbnail sizes.
1124 *
1125 * @note This will only list several alternatives if thumbnails are rendered on 404
1126 * @param int $origWidth Actual width of image
1127 * @param int $origHeight Actual height of image
1128 * @return array An array of [width, height] pairs.
1129 */
1130 protected function getThumbSizes( $origWidth, $origHeight ) {
1131 global $wgImageLimits;
1132 if ( $this->displayImg->getRepo()->canTransformVia404() ) {
1133 $thumbSizes = $wgImageLimits;
1134 // Also include the full sized resolution in the list, so
1135 // that users know they can get it. This will link to the
1136 // original file asset if mustRender() === false. In the case
1137 // that we mustRender, some users have indicated that they would
1138 // find it useful to have the full size image in the rendered
1139 // image format.
1140 $thumbSizes[] = array( $origWidth, $origHeight );
1141 } else {
1142 # Creating thumb links triggers thumbnail generation.
1143 # Just generate the thumb for the current users prefs.
1144 $thumbSizes = array( $this->getImageLimitsFromOption( $this->getContext()->getUser(), 'thumbsize' ) );
1145 if ( !$this->displayImg->mustRender() ) {
1146 // We can safely include a link to the "full-size" preview,
1147 // without actually rendering.
1148 $thumbSizes[] = array( $origWidth, $origHeight );
1149 }
1150 }
1151 return $thumbSizes;
1152 }
1153
1154 }
1155
1156 /**
1157 * Builds the image revision log shown on image pages
1158 *
1159 * @ingroup Media
1160 */
1161 class ImageHistoryList extends ContextSource {
1162
1163 /**
1164 * @var Title
1165 */
1166 protected $title;
1167
1168 /**
1169 * @var File
1170 */
1171 protected $img;
1172
1173 /**
1174 * @var ImagePage
1175 */
1176 protected $imagePage;
1177
1178 /**
1179 * @var File
1180 */
1181 protected $current;
1182
1183 protected $repo, $showThumb;
1184 protected $preventClickjacking = false;
1185
1186 /**
1187 * @param ImagePage $imagePage
1188 */
1189 public function __construct( $imagePage ) {
1190 global $wgShowArchiveThumbnails;
1191 $this->current = $imagePage->getFile();
1192 $this->img = $imagePage->getDisplayedFile();
1193 $this->title = $imagePage->getTitle();
1194 $this->imagePage = $imagePage;
1195 $this->showThumb = $wgShowArchiveThumbnails && $this->img->canRender();
1196 $this->setContext( $imagePage->getContext() );
1197 }
1198
1199 /**
1200 * @return ImagePage
1201 */
1202 public function getImagePage() {
1203 return $this->imagePage;
1204 }
1205
1206 /**
1207 * @return File
1208 */
1209 public function getFile() {
1210 return $this->img;
1211 }
1212
1213 /**
1214 * @param string $navLinks
1215 * @return string
1216 */
1217 public function beginImageHistoryList( $navLinks = '' ) {
1218 return Xml::element( 'h2', array( 'id' => 'filehistory' ), $this->msg( 'filehist' )->text() )
1219 . "\n"
1220 . "<div id=\"mw-imagepage-section-filehistory\">\n"
1221 . $this->msg( 'filehist-help' )->parseAsBlock()
1222 . $navLinks . "\n"
1223 . Xml::openElement( 'table', array( 'class' => 'wikitable filehistory' ) ) . "\n"
1224 . '<tr><th></th>'
1225 . ( $this->current->isLocal()
1226 && ( $this->getUser()->isAllowedAny( 'delete', 'deletedhistory' ) ) ? '<th></th>' : '' )
1227 . '<th>' . $this->msg( 'filehist-datetime' )->escaped() . '</th>'
1228 . ( $this->showThumb ? '<th>' . $this->msg( 'filehist-thumb' )->escaped() . '</th>' : '' )
1229 . '<th>' . $this->msg( 'filehist-dimensions' )->escaped() . '</th>'
1230 . '<th>' . $this->msg( 'filehist-user' )->escaped() . '</th>'
1231 . '<th>' . $this->msg( 'filehist-comment' )->escaped() . '</th>'
1232 . "</tr>\n";
1233 }
1234
1235 /**
1236 * @param string $navLinks
1237 * @return string
1238 */
1239 public function endImageHistoryList( $navLinks = '' ) {
1240 return "</table>\n$navLinks\n</div>\n";
1241 }
1242
1243 /**
1244 * @param bool $iscur
1245 * @param File $file
1246 * @return string
1247 */
1248 public function imageHistoryLine( $iscur, $file ) {
1249 global $wgContLang;
1250
1251 $user = $this->getUser();
1252 $lang = $this->getLanguage();
1253 $timestamp = wfTimestamp( TS_MW, $file->getTimestamp() );
1254 $img = $iscur ? $file->getName() : $file->getArchiveName();
1255 $userId = $file->getUser( 'id' );
1256 $userText = $file->getUser( 'text' );
1257 $description = $file->getDescription( File::FOR_THIS_USER, $user );
1258
1259 $local = $this->current->isLocal();
1260 $row = $selected = '';
1261
1262 // Deletion link
1263 if ( $local && ( $user->isAllowedAny( 'delete', 'deletedhistory' ) ) ) {
1264 $row .= '<td>';
1265 # Link to remove from history
1266 if ( $user->isAllowed( 'delete' ) ) {
1267 $q = array( 'action' => 'delete' );
1268 if ( !$iscur ) {
1269 $q['oldimage'] = $img;
1270 }
1271 $row .= Linker::linkKnown(
1272 $this->title,
1273 $this->msg( $iscur ? 'filehist-deleteall' : 'filehist-deleteone' )->escaped(),
1274 array(), $q
1275 );
1276 }
1277 # Link to hide content. Don't show useless link to people who cannot hide revisions.
1278 $canHide = $user->isAllowed( 'deleterevision' );
1279 if ( $canHide || ( $user->isAllowed( 'deletedhistory' ) && $file->getVisibility() ) ) {
1280 if ( $user->isAllowed( 'delete' ) ) {
1281 $row .= '<br />';
1282 }
1283 // If file is top revision or locked from this user, don't link
1284 if ( $iscur || !$file->userCan( File::DELETED_RESTRICTED, $user ) ) {
1285 $del = Linker::revDeleteLinkDisabled( $canHide );
1286 } else {
1287 list( $ts, ) = explode( '!', $img, 2 );
1288 $query = array(
1289 'type' => 'oldimage',
1290 'target' => $this->title->getPrefixedText(),
1291 'ids' => $ts,
1292 );
1293 $del = Linker::revDeleteLink( $query,
1294 $file->isDeleted( File::DELETED_RESTRICTED ), $canHide );
1295 }
1296 $row .= $del;
1297 }
1298 $row .= '</td>';
1299 }
1300
1301 // Reversion link/current indicator
1302 $row .= '<td>';
1303 if ( $iscur ) {
1304 $row .= $this->msg( 'filehist-current' )->escaped();
1305 } elseif ( $local && $this->title->quickUserCan( 'edit', $user )
1306 && $this->title->quickUserCan( 'upload', $user )
1307 ) {
1308 if ( $file->isDeleted( File::DELETED_FILE ) ) {
1309 $row .= $this->msg( 'filehist-revert' )->escaped();
1310 } else {
1311 $row .= Linker::linkKnown(
1312 $this->title,
1313 $this->msg( 'filehist-revert' )->escaped(),
1314 array(),
1315 array(
1316 'action' => 'revert',
1317 'oldimage' => $img,
1318 'wpEditToken' => $user->getEditToken( $img )
1319 )
1320 );
1321 }
1322 }
1323 $row .= '</td>';
1324
1325 // Date/time and image link
1326 if ( $file->getTimestamp() === $this->img->getTimestamp() ) {
1327 $selected = "class='filehistory-selected'";
1328 }
1329 $row .= "<td $selected style='white-space: nowrap;'>";
1330 if ( !$file->userCan( File::DELETED_FILE, $user ) ) {
1331 # Don't link to unviewable files
1332 $row .= '<span class="history-deleted">'
1333 . $lang->userTimeAndDate( $timestamp, $user ) . '</span>';
1334 } elseif ( $file->isDeleted( File::DELETED_FILE ) ) {
1335 if ( $local ) {
1336 $this->preventClickjacking();
1337 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
1338 # Make a link to review the image
1339 $url = Linker::linkKnown(
1340 $revdel,
1341 $lang->userTimeAndDate( $timestamp, $user ),
1342 array(),
1343 array(
1344 'target' => $this->title->getPrefixedText(),
1345 'file' => $img,
1346 'token' => $user->getEditToken( $img )
1347 )
1348 );
1349 } else {
1350 $url = $lang->userTimeAndDate( $timestamp, $user );
1351 }
1352 $row .= '<span class="history-deleted">' . $url . '</span>';
1353 } elseif ( !$file->exists() ) {
1354 $row .= '<span class="mw-file-missing">'
1355 . $lang->userTimeAndDate( $timestamp, $user ) . '</span>';
1356 } else {
1357 $url = $iscur ? $this->current->getUrl() : $this->current->getArchiveUrl( $img );
1358 $row .= Xml::element(
1359 'a',
1360 array( 'href' => $url ),
1361 $lang->userTimeAndDate( $timestamp, $user )
1362 );
1363 }
1364 $row .= "</td>";
1365
1366 // Thumbnail
1367 if ( $this->showThumb ) {
1368 $row .= '<td>' . $this->getThumbForLine( $file ) . '</td>';
1369 }
1370
1371 // Image dimensions + size
1372 $row .= '<td>';
1373 $row .= htmlspecialchars( $file->getDimensionsString() );
1374 $row .= $this->msg( 'word-separator' )->escaped();
1375 $row .= '<span style="white-space: nowrap;">';
1376 $row .= $this->msg( 'parentheses' )->sizeParams( $file->getSize() )->escaped();
1377 $row .= '</span>';
1378 $row .= '</td>';
1379
1380 // Uploading user
1381 $row .= '<td>';
1382 // Hide deleted usernames
1383 if ( $file->isDeleted( File::DELETED_USER ) ) {
1384 $row .= '<span class="history-deleted">'
1385 . $this->msg( 'rev-deleted-user' )->escaped() . '</span>';
1386 } else {
1387 if ( $local ) {
1388 $row .= Linker::userLink( $userId, $userText );
1389 $row .= '<span style="white-space: nowrap;">';
1390 $row .= Linker::userToolLinks( $userId, $userText );
1391 $row .= '</span>';
1392 } else {
1393 $row .= htmlspecialchars( $userText );
1394 }
1395 }
1396 $row .= '</td>';
1397
1398 // Don't show deleted descriptions
1399 if ( $file->isDeleted( File::DELETED_COMMENT ) ) {
1400 $row .= '<td><span class="history-deleted">' .
1401 $this->msg( 'rev-deleted-comment' )->escaped() . '</span></td>';
1402 } else {
1403 $row .= '<td dir="' . $wgContLang->getDir() . '">' .
1404 Linker::formatComment( $description, $this->title ) . '</td>';
1405 }
1406
1407 $rowClass = null;
1408 Hooks::run( 'ImagePageFileHistoryLine', array( $this, $file, &$row, &$rowClass ) );
1409 $classAttr = $rowClass ? " class='$rowClass'" : '';
1410
1411 return "<tr{$classAttr}>{$row}</tr>\n";
1412 }
1413
1414 /**
1415 * @param File $file
1416 * @return string
1417 */
1418 protected function getThumbForLine( $file ) {
1419 $lang = $this->getLanguage();
1420 $user = $this->getUser();
1421 if ( $file->allowInlineDisplay() && $file->userCan( File::DELETED_FILE, $user )
1422 && !$file->isDeleted( File::DELETED_FILE )
1423 ) {
1424 $params = array(
1425 'width' => '120',
1426 'height' => '120',
1427 );
1428 $timestamp = wfTimestamp( TS_MW, $file->getTimestamp() );
1429
1430 $thumbnail = $file->transform( $params );
1431 $options = array(
1432 'alt' => $this->msg( 'filehist-thumbtext',
1433 $lang->userTimeAndDate( $timestamp, $user ),
1434 $lang->userDate( $timestamp, $user ),
1435 $lang->userTime( $timestamp, $user ) )->text(),
1436 'file-link' => true,
1437 );
1438
1439 if ( !$thumbnail ) {
1440 return $this->msg( 'filehist-nothumb' )->escaped();
1441 }
1442
1443 return $thumbnail->toHtml( $options );
1444 } else {
1445 return $this->msg( 'filehist-nothumb' )->escaped();
1446 }
1447 }
1448
1449 /**
1450 * @param bool $enable
1451 */
1452 protected function preventClickjacking( $enable = true ) {
1453 $this->preventClickjacking = $enable;
1454 }
1455
1456 /**
1457 * @return bool
1458 */
1459 public function getPreventClickjacking() {
1460 return $this->preventClickjacking;
1461 }
1462 }
1463
1464 class ImageHistoryPseudoPager extends ReverseChronologicalPager {
1465 protected $preventClickjacking = false;
1466
1467 /**
1468 * @var File
1469 */
1470 protected $mImg;
1471
1472 /**
1473 * @var Title
1474 */
1475 protected $mTitle;
1476
1477 /**
1478 * @param ImagePage $imagePage
1479 */
1480 function __construct( $imagePage ) {
1481 parent::__construct( $imagePage->getContext() );
1482 $this->mImagePage = $imagePage;
1483 $this->mTitle = clone ( $imagePage->getTitle() );
1484 $this->mTitle->setFragment( '#filehistory' );
1485 $this->mImg = null;
1486 $this->mHist = array();
1487 $this->mRange = array( 0, 0 ); // display range
1488 }
1489
1490 /**
1491 * @return Title
1492 */
1493 function getTitle() {
1494 return $this->mTitle;
1495 }
1496
1497 function getQueryInfo() {
1498 return false;
1499 }
1500
1501 /**
1502 * @return string
1503 */
1504 function getIndexField() {
1505 return '';
1506 }
1507
1508 /**
1509 * @param object $row
1510 * @return string
1511 */
1512 function formatRow( $row ) {
1513 return '';
1514 }
1515
1516 /**
1517 * @return string
1518 */
1519 function getBody() {
1520 $s = '';
1521 $this->doQuery();
1522 if ( count( $this->mHist ) ) {
1523 if ( $this->mImg->isLocal() ) {
1524 // Do a batch existence check for user pages and talkpages
1525 $linkBatch = new LinkBatch();
1526 for ( $i = $this->mRange[0]; $i <= $this->mRange[1]; $i++ ) {
1527 $file = $this->mHist[$i];
1528 $user = $file->getUser( 'text' );
1529 $linkBatch->add( NS_USER, $user );
1530 $linkBatch->add( NS_USER_TALK, $user );
1531 }
1532 $linkBatch->execute();
1533 }
1534
1535 $list = new ImageHistoryList( $this->mImagePage );
1536 # Generate prev/next links
1537 $navLink = $this->getNavigationBar();
1538 $s = $list->beginImageHistoryList( $navLink );
1539 // Skip rows there just for paging links
1540 for ( $i = $this->mRange[0]; $i <= $this->mRange[1]; $i++ ) {
1541 $file = $this->mHist[$i];
1542 $s .= $list->imageHistoryLine( !$file->isOld(), $file );
1543 }
1544 $s .= $list->endImageHistoryList( $navLink );
1545
1546 if ( $list->getPreventClickjacking() ) {
1547 $this->preventClickjacking();
1548 }
1549 }
1550 return $s;
1551 }
1552
1553 function doQuery() {
1554 if ( $this->mQueryDone ) {
1555 return;
1556 }
1557 $this->mImg = $this->mImagePage->getFile(); // ensure loading
1558 if ( !$this->mImg->exists() ) {
1559 return;
1560 }
1561 $queryLimit = $this->mLimit + 1; // limit plus extra row
1562 if ( $this->mIsBackwards ) {
1563 // Fetch the file history
1564 $this->mHist = $this->mImg->getHistory( $queryLimit, null, $this->mOffset, false );
1565 // The current rev may not meet the offset/limit
1566 $numRows = count( $this->mHist );
1567 if ( $numRows <= $this->mLimit && $this->mImg->getTimestamp() > $this->mOffset ) {
1568 $this->mHist = array_merge( array( $this->mImg ), $this->mHist );
1569 }
1570 } else {
1571 // The current rev may not meet the offset
1572 if ( !$this->mOffset || $this->mImg->getTimestamp() < $this->mOffset ) {
1573 $this->mHist[] = $this->mImg;
1574 }
1575 // Old image versions (fetch extra row for nav links)
1576 $oiLimit = count( $this->mHist ) ? $this->mLimit : $this->mLimit + 1;
1577 // Fetch the file history
1578 $this->mHist = array_merge( $this->mHist,
1579 $this->mImg->getHistory( $oiLimit, $this->mOffset, null, false ) );
1580 }
1581 $numRows = count( $this->mHist ); // Total number of query results
1582 if ( $numRows ) {
1583 # Index value of top item in the list
1584 $firstIndex = $this->mIsBackwards ?
1585 $this->mHist[$numRows - 1]->getTimestamp() : $this->mHist[0]->getTimestamp();
1586 # Discard the extra result row if there is one
1587 if ( $numRows > $this->mLimit && $numRows > 1 ) {
1588 if ( $this->mIsBackwards ) {
1589 # Index value of item past the index
1590 $this->mPastTheEndIndex = $this->mHist[0]->getTimestamp();
1591 # Index value of bottom item in the list
1592 $lastIndex = $this->mHist[1]->getTimestamp();
1593 # Display range
1594 $this->mRange = array( 1, $numRows - 1 );
1595 } else {
1596 # Index value of item past the index
1597 $this->mPastTheEndIndex = $this->mHist[$numRows - 1]->getTimestamp();
1598 # Index value of bottom item in the list
1599 $lastIndex = $this->mHist[$numRows - 2]->getTimestamp();
1600 # Display range
1601 $this->mRange = array( 0, $numRows - 2 );
1602 }
1603 } else {
1604 # Setting indexes to an empty string means that they will be
1605 # omitted if they would otherwise appear in URLs. It just so
1606 # happens that this is the right thing to do in the standard
1607 # UI, in all the relevant cases.
1608 $this->mPastTheEndIndex = '';
1609 # Index value of bottom item in the list
1610 $lastIndex = $this->mIsBackwards ?
1611 $this->mHist[0]->getTimestamp() : $this->mHist[$numRows - 1]->getTimestamp();
1612 # Display range
1613 $this->mRange = array( 0, $numRows - 1 );
1614 }
1615 } else {
1616 $firstIndex = '';
1617 $lastIndex = '';
1618 $this->mPastTheEndIndex = '';
1619 }
1620 if ( $this->mIsBackwards ) {
1621 $this->mIsFirst = ( $numRows < $queryLimit );
1622 $this->mIsLast = ( $this->mOffset == '' );
1623 $this->mLastShown = $firstIndex;
1624 $this->mFirstShown = $lastIndex;
1625 } else {
1626 $this->mIsFirst = ( $this->mOffset == '' );
1627 $this->mIsLast = ( $numRows < $queryLimit );
1628 $this->mLastShown = $lastIndex;
1629 $this->mFirstShown = $firstIndex;
1630 }
1631 $this->mQueryDone = true;
1632 }
1633
1634 /**
1635 * @param bool $enable
1636 */
1637 protected function preventClickjacking( $enable = true ) {
1638 $this->preventClickjacking = $enable;
1639 }
1640
1641 /**
1642 * @return bool
1643 */
1644 public function getPreventClickjacking() {
1645 return $this->preventClickjacking;
1646 }
1647
1648 }