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