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