Merge branch 'master' into Wikidata
[lhc/web/wiklou.git] / includes / ImagePage.php
1 <?php
2 /**
3 * Class for viewing MediaWiki file description pages
4 *
5 * @ingroup Media
6 */
7 class ImagePage extends Article {
8
9 /**
10 * @var File
11 */
12 private $displayImg;
13 /**
14 * @var FileRepo
15 */
16 private $repo;
17 private $fileLoaded;
18
19 var $mExtraDescription = false;
20
21 /**
22 * @param $title Title
23 * @return WikiFilePage
24 */
25 protected function newPage( Title $title ) {
26 // Overload mPage with a file-specific page
27 return new WikiFilePage( $title );
28 }
29
30 /**
31 * Constructor from a page id
32 * @param $id Int article ID to load
33 * @returnImagePage|null
34 */
35 public static function newFromID( $id ) {
36 $t = Title::newFromID( $id );
37 # @todo FIXME: Doesn't inherit right
38 return $t == null ? null : new self( $t );
39 # return $t == null ? null : new static( $t ); // PHP 5.3
40 }
41
42 /**
43 * @param $file File:
44 * @return void
45 */
46 public function setFile( $file ) {
47 $this->mPage->setFile( $file );
48 $this->displayImg = $file;
49 $this->fileLoaded = true;
50 }
51
52 protected function loadFile() {
53 if ( $this->fileLoaded ) {
54 return true;
55 }
56 $this->fileLoaded = true;
57
58 $this->displayImg = $img = false;
59 wfRunHooks( 'ImagePageFindFile', array( $this, &$img, &$this->displayImg ) );
60 if ( !$img ) { // not set by hook?
61 $img = wfFindFile( $this->getTitle() );
62 if ( !$img ) {
63 $img = wfLocalFile( $this->getTitle() );
64 }
65 }
66 $this->mPage->setFile( $img );
67 if ( !$this->displayImg ) { // not set by hook?
68 $this->displayImg = $img;
69 }
70 $this->repo = $img->getRepo();
71 }
72
73 /**
74 * Handler for action=render
75 * Include body text only; none of the image extras
76 */
77 public function render() {
78 global $wgOut;
79 $wgOut->setArticleBodyOnly( true );
80 parent::view();
81 }
82
83 public function view() {
84 global $wgOut, $wgShowEXIF, $wgRequest, $wgUser;
85
86 $diff = $wgRequest->getVal( 'diff' );
87 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
88
89 if ( $this->getTitle()->getNamespace() != NS_FILE || ( isset( $diff ) && $diffOnly ) ) {
90 return parent::view();
91 }
92
93 $this->loadFile();
94
95 if ( $this->getTitle()->getNamespace() == NS_FILE && $this->mPage->getFile()->getRedirected() ) {
96 if ( $this->getTitle()->getDBkey() == $this->mPage->getFile()->getName() || isset( $diff ) ) {
97 // mTitle is the same as the redirect target so ask Article
98 // to perform the redirect for us.
99 $wgRequest->setVal( 'diffonly', 'true' );
100 return parent::view();
101 } else {
102 // mTitle is not the same as the redirect target so it is
103 // probably the redirect page itself. Fake the redirect symbol
104 $wgOut->setPageTitle( $this->getTitle()->getPrefixedText() );
105 $wgOut->addHTML( $this->viewRedirect( Title::makeTitle( NS_FILE, $this->mPage->getFile()->getName() ),
106 /* $appendSubtitle */ true, /* $forceKnown */ true ) );
107 $this->mPage->doViewUpdates( $this->getContext()->getUser() );
108 return;
109 }
110 }
111
112 if ( $wgShowEXIF && $this->displayImg->exists() ) {
113 // @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
114 $formattedMetadata = $this->displayImg->formatMetadata();
115 $showmeta = $formattedMetadata !== false;
116 } else {
117 $showmeta = false;
118 }
119
120 if ( !$diff && $this->displayImg->exists() ) {
121 $wgOut->addHTML( $this->showTOC( $showmeta ) );
122 }
123
124 if ( !$diff ) {
125 $this->openShowImage();
126 }
127
128 # No need to display noarticletext, we use our own message, output in openShowImage()
129 if ( $this->mPage->getID() ) {
130 # NS_FILE is in the user language, but this section (the actual wikitext)
131 # should be in page content language
132 $pageLang = $this->getTitle()->getPageLanguage();
133 $wgOut->addHTML( Xml::openElement( 'div', array( 'id' => 'mw-imagepage-content',
134 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
135 'class' => 'mw-content-'.$pageLang->getDir() ) ) );
136
137 parent::view(); #FIXME: use ContentHandler::makeArticle() !!
138
139 $wgOut->addHTML( Xml::closeElement( 'div' ) );
140 } else {
141 # Just need to set the right headers
142 $wgOut->setArticleFlag( true );
143 $wgOut->setPageTitle( $this->getTitle()->getPrefixedText() );
144 $this->mPage->doViewUpdates( $this->getContext()->getUser() );
145 }
146
147 # Show shared description, if needed
148 if ( $this->mExtraDescription ) {
149 $fol = wfMessage( 'shareddescriptionfollows' );
150 if ( !$fol->isDisabled() ) {
151 $wgOut->addWikiText( $fol->plain() );
152 }
153 $wgOut->addHTML( '<div id="shared-image-desc">' . $this->mExtraDescription . "</div>\n" );
154 }
155
156 $this->closeShowImage();
157 $this->imageHistory();
158 // TODO: Cleanup the following
159
160 $wgOut->addHTML( Xml::element( 'h2',
161 array( 'id' => 'filelinks' ),
162 wfMsg( 'imagelinks' ) ) . "\n" );
163 $this->imageDupes();
164 # @todo FIXME: For some freaky reason, we can't redirect to foreign images.
165 # Yet we return metadata about the target. Definitely an issue in the FileRepo
166 $this->imageLinks();
167
168 # Allow extensions to add something after the image links
169 $html = '';
170 wfRunHooks( 'ImagePageAfterImageLinks', array( $this, &$html ) );
171 if ( $html ) {
172 $wgOut->addHTML( $html );
173 }
174
175 if ( $showmeta ) {
176 $wgOut->addHTML( Xml::element( 'h2', array( 'id' => 'metadata' ), wfMsg( 'metadata' ) ) . "\n" );
177 $wgOut->addWikiText( $this->makeMetadataTable( $formattedMetadata ) );
178 $wgOut->addModules( array( 'mediawiki.action.view.metadata' ) );
179 }
180
181 // Add remote Filepage.css
182 if( !$this->repo->isLocal() ) {
183 $css = $this->repo->getDescriptionStylesheetUrl();
184 if ( $css ) {
185 $wgOut->addStyle( $css );
186 }
187 }
188 // always show the local local Filepage.css, bug 29277
189 $wgOut->addModuleStyles( 'filepage' );
190 }
191
192 /**
193 * @return File
194 */
195 public function getDisplayedFile() {
196 $this->loadFile();
197 return $this->displayImg;
198 }
199
200 /**
201 * Create the TOC
202 *
203 * @param $metadata Boolean: whether or not to show the metadata link
204 * @return String
205 */
206 protected function showTOC( $metadata ) {
207 $r = array(
208 '<li><a href="#file">' . wfMsgHtml( 'file-anchor-link' ) . '</a></li>',
209 '<li><a href="#filehistory">' . wfMsgHtml( 'filehist' ) . '</a></li>',
210 '<li><a href="#filelinks">' . wfMsgHtml( 'imagelinks' ) . '</a></li>',
211 );
212 if ( $metadata ) {
213 $r[] = '<li><a href="#metadata">' . wfMsgHtml( 'metadata' ) . '</a></li>';
214 }
215
216 wfRunHooks( 'ImagePageShowTOC', array( $this, &$r ) );
217
218 return '<ul id="filetoc">' . implode( "\n", $r ) . '</ul>';
219 }
220
221 /**
222 * Make a table with metadata to be shown in the output page.
223 *
224 * @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
225 *
226 * @param $metadata Array: the array containing the EXIF data
227 * @return String The metadata table. This is treated as Wikitext (!)
228 */
229 protected function makeMetadataTable( $metadata ) {
230 $r = "<div class=\"mw-imagepage-section-metadata\">";
231 $r .= wfMsgNoTrans( 'metadata-help' );
232 $r .= "<table id=\"mw_metadata\" class=\"mw_metadata\">\n";
233 foreach ( $metadata as $type => $stuff ) {
234 foreach ( $stuff as $v ) {
235 # @todo FIXME: Why is this using escapeId for a class?!
236 $class = Sanitizer::escapeId( $v['id'] );
237 if ( $type == 'collapsed' ) {
238 $class .= ' collapsable';
239 }
240 $r .= "<tr class=\"$class\">\n";
241 $r .= "<th>{$v['name']}</th>\n";
242 $r .= "<td>{$v['value']}</td>\n</tr>";
243 }
244 }
245 $r .= "</table>\n</div>\n";
246 return $r;
247 }
248
249 /**
250 * Overloading Article's getContentObject method.
251 *
252 * Omit noarticletext if sharedupload; text will be fetched from the
253 * shared upload server if possible.
254 * @return string
255 */
256 public function getContentObject() {
257 $this->loadFile();
258 if ( $this->mPage->getFile() && !$this->mPage->getFile()->isLocal() && 0 == $this->getID() ) {
259 return null;
260 }
261 return parent::getContentObject();
262 }
263
264 protected function openShowImage() {
265 global $wgOut, $wgUser, $wgImageLimits, $wgRequest,
266 $wgLang, $wgEnableUploads, $wgSend404Code;
267
268 $this->loadFile();
269
270 $sizeSel = intval( $wgUser->getOption( 'imagesize' ) );
271 if ( !isset( $wgImageLimits[$sizeSel] ) ) {
272 $sizeSel = User::getDefaultOption( 'imagesize' );
273
274 // The user offset might still be incorrect, specially if
275 // $wgImageLimits got changed (see bug #8858).
276 if ( !isset( $wgImageLimits[$sizeSel] ) ) {
277 // Default to the first offset in $wgImageLimits
278 $sizeSel = 0;
279 }
280 }
281 $max = $wgImageLimits[$sizeSel];
282 $maxWidth = $max[0];
283 $maxHeight = $max[1];
284 $dirmark = $wgLang->getDirMarkEntity();
285
286 if ( $this->displayImg->exists() ) {
287 # image
288 $page = $wgRequest->getIntOrNull( 'page' );
289 if ( is_null( $page ) ) {
290 $params = array();
291 $page = 1;
292 } else {
293 $params = array( 'page' => $page );
294 }
295 $width_orig = $this->displayImg->getWidth( $page );
296 $width = $width_orig;
297 $height_orig = $this->displayImg->getHeight( $page );
298 $height = $height_orig;
299
300 $longDesc = wfMsg( 'parentheses', $this->displayImg->getLongDesc() );
301
302 wfRunHooks( 'ImageOpenShowImageInlineBefore', array( &$this, &$wgOut ) );
303
304 if ( $this->displayImg->allowInlineDisplay() ) {
305 # image
306
307 # "Download high res version" link below the image
308 # $msgsize = wfMsgHtml( 'file-info-size', $width_orig, $height_orig, Linker::formatSize( $this->displayImg->getSize() ), $mime );
309 # We'll show a thumbnail of this image
310 if ( $width > $maxWidth || $height > $maxHeight ) {
311 # Calculate the thumbnail size.
312 # First case, the limiting factor is the width, not the height.
313 if ( $width / $height >= $maxWidth / $maxHeight ) {
314 $height = round( $height * $maxWidth / $width );
315 $width = $maxWidth;
316 # Note that $height <= $maxHeight now.
317 } else {
318 $newwidth = floor( $width * $maxHeight / $height );
319 $height = round( $height * $newwidth / $width );
320 $width = $newwidth;
321 # Note that $height <= $maxHeight now, but might not be identical
322 # because of rounding.
323 }
324 $msgbig = wfMsgHtml( 'show-big-image' );
325 $otherSizes = array();
326 foreach ( $wgImageLimits as $size ) {
327 if ( $size[0] < $width_orig && $size[1] < $height_orig &&
328 $size[0] != $width && $size[1] != $height ) {
329 $otherSizes[] = $this->makeSizeLink( $params, $size[0], $size[1] );
330 }
331 }
332 $msgsmall = wfMessage( 'show-big-image-preview' )->
333 rawParams( $this->makeSizeLink( $params, $width, $height ) )->
334 parse();
335 if ( count( $otherSizes ) && $this->displayImg->getRepo()->canTransformVia404() ) {
336 $msgsmall .= ' ' .
337 Html::rawElement( 'span', array( 'class' => 'mw-filepage-other-resolutions' ),
338 wfMessage( 'show-big-image-other' )->rawParams( $wgLang->pipeList( $otherSizes ) )->
339 params( count( $otherSizes ) )->parse()
340 );
341 }
342 } elseif ( $width == 0 && $height == 0 ){
343 # Some sort of audio file that doesn't have dimensions
344 # Don't output a no hi res message for such a file
345 $msgsmall = '';
346 } else {
347 # Image is small enough to show full size on image page
348 $msgsmall = wfMessage( 'file-nohires' )->parse();
349 }
350
351 $params['width'] = $width;
352 $params['height'] = $height;
353 $thumbnail = $this->displayImg->transform( $params );
354
355 $showLink = true;
356 $anchorclose = Html::rawElement( 'div', array( 'class' => 'mw-filepage-resolutioninfo' ), $msgsmall );
357
358 $isMulti = $this->displayImg->isMultipage() && $this->displayImg->pageCount() > 1;
359 if ( $isMulti ) {
360 $wgOut->addHTML( '<table class="multipageimage"><tr><td>' );
361 }
362
363 if ( $thumbnail ) {
364 $options = array(
365 'alt' => $this->displayImg->getTitle()->getPrefixedText(),
366 'file-link' => true,
367 );
368 $wgOut->addHTML( '<div class="fullImageLink" id="file">' .
369 $thumbnail->toHtml( $options ) .
370 $anchorclose . "</div>\n" );
371 }
372
373 if ( $isMulti ) {
374 $count = $this->displayImg->pageCount();
375
376 if ( $page > 1 ) {
377 $label = $wgOut->parse( wfMsg( 'imgmultipageprev' ), false );
378 $link = Linker::link(
379 $this->getTitle(),
380 $label,
381 array(),
382 array( 'page' => $page - 1 ),
383 array( 'known', 'noclasses' )
384 );
385 $thumb1 = Linker::makeThumbLinkObj( $this->getTitle(), $this->displayImg, $link, $label, 'none',
386 array( 'page' => $page - 1 ) );
387 } else {
388 $thumb1 = '';
389 }
390
391 if ( $page < $count ) {
392 $label = wfMsg( 'imgmultipagenext' );
393 $link = Linker::link(
394 $this->getTitle(),
395 $label,
396 array(),
397 array( 'page' => $page + 1 ),
398 array( 'known', 'noclasses' )
399 );
400 $thumb2 = Linker::makeThumbLinkObj( $this->getTitle(), $this->displayImg, $link, $label, 'none',
401 array( 'page' => $page + 1 ) );
402 } else {
403 $thumb2 = '';
404 }
405
406 global $wgScript;
407
408 $formParams = array(
409 'name' => 'pageselector',
410 'action' => $wgScript,
411 'onchange' => 'document.pageselector.submit();',
412 );
413 $options = array();
414 for ( $i = 1; $i <= $count; $i++ ) {
415 $options[] = Xml::option( $wgLang->formatNum( $i ), $i, $i == $page );
416 }
417 $select = Xml::tags( 'select',
418 array( 'id' => 'pageselector', 'name' => 'page' ),
419 implode( "\n", $options ) );
420
421 $wgOut->addHTML(
422 '</td><td><div class="multipageimagenavbox">' .
423 Xml::openElement( 'form', $formParams ) .
424 Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() ) .
425 wfMsgExt( 'imgmultigoto', array( 'parseinline', 'replaceafter' ), $select ) .
426 Xml::submitButton( wfMsg( 'imgmultigo' ) ) .
427 Xml::closeElement( 'form' ) .
428 "<hr />$thumb1\n$thumb2<br style=\"clear: both\" /></div></td></tr></table>"
429 );
430 }
431 } else {
432 # if direct link is allowed but it's not a renderable image, show an icon.
433 if ( $this->displayImg->isSafeFile() ) {
434 $icon = $this->displayImg->iconThumb();
435
436 $wgOut->addHTML( '<div class="fullImageLink" id="file">' .
437 $icon->toHtml( array( 'file-link' => true ) ) .
438 "</div>\n" );
439 }
440
441 $showLink = true;
442 }
443
444 if ( $showLink ) {
445 $filename = wfEscapeWikiText( $this->displayImg->getName() );
446 $linktext = $filename;
447 if ( isset( $msgbig ) ) {
448 $linktext = wfEscapeWikiText( $msgbig );
449 }
450 $medialink = "[[Media:$filename|$linktext]]";
451
452 if ( !$this->displayImg->isSafeFile() ) {
453 $warning = wfMsgNoTrans( 'mediawarning' );
454 // dirmark is needed here to separate the file name, which
455 // most likely ends in Latin characters, from the description,
456 // which may begin with the file type. In RTL environment
457 // this will get messy.
458 // The dirmark, however, must not be immediately adjacent
459 // to the filename, because it can get copied with it.
460 // See bug 25277.
461 $wgOut->addWikiText( <<<EOT
462 <div class="fullMedia"><span class="dangerousLink">{$medialink}</span> $dirmark<span class="fileInfo">$longDesc</span></div>
463 <div class="mediaWarning">$warning</div>
464 EOT
465 );
466 } else {
467 $wgOut->addWikiText( <<<EOT
468 <div class="fullMedia">{$medialink} {$dirmark}<span class="fileInfo">$longDesc</span>
469 </div>
470 EOT
471 );
472 }
473 }
474
475 if ( !$this->displayImg->isLocal() ) {
476 $this->printSharedImageText();
477 }
478 } else {
479 # Image does not exist
480 if ( !$this->getID() ) {
481 # No article exists either
482 # Show deletion log to be consistent with normal articles
483 LogEventsList::showLogExtract(
484 $wgOut,
485 array( 'delete', 'move' ),
486 $this->getTitle()->getPrefixedText(),
487 '',
488 array( 'lim' => 10,
489 'conds' => array( "log_action != 'revision'" ),
490 'showIfEmpty' => false,
491 'msgKey' => array( 'moveddeleted-notice' )
492 )
493 );
494 }
495
496 if ( $wgEnableUploads && $wgUser->isAllowed( 'upload' ) ) {
497 // Only show an upload link if the user can upload
498 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
499 $nofile = array(
500 'filepage-nofile-link',
501 $uploadTitle->getFullURL( array( 'wpDestFile' => $this->mPage->getFile()->getName() ) )
502 );
503 } else {
504 $nofile = 'filepage-nofile';
505 }
506 // Note, if there is an image description page, but
507 // no image, then this setRobotPolicy is overriden
508 // by Article::View().
509 $wgOut->setRobotPolicy( 'noindex,nofollow' );
510 $wgOut->wrapWikiMsg( "<div id='mw-imagepage-nofile' class='plainlinks'>\n$1\n</div>", $nofile );
511 if ( !$this->getID() && $wgSend404Code ) {
512 // If there is no image, no shared image, and no description page,
513 // output a 404, to be consistent with articles.
514 $wgRequest->response()->header( 'HTTP/1.1 404 Not Found' );
515 }
516 }
517 $wgOut->setFileVersion( $this->displayImg );
518 }
519
520 /**
521 * Creates an thumbnail of specified size and returns an HTML link to it
522 * @param $params array Scaler parameters
523 * @param $width int
524 * @param $height int
525 * @return string
526 */
527 private function makeSizeLink( $params, $width, $height ) {
528 $params['width'] = $width;
529 $params['height'] = $height;
530 $thumbnail = $this->displayImg->transform( $params );
531 if ( $thumbnail && !$thumbnail->isError() ) {
532 return Html::rawElement( 'a', array(
533 'href' => $thumbnail->getUrl(),
534 'class' => 'mw-thumbnail-link'
535 ), wfMessage( 'show-big-image-size' )->numParams(
536 $thumbnail->getWidth(), $thumbnail->getHeight()
537 )->parse() );
538 } else {
539 return '';
540 }
541 }
542
543 /**
544 * Show a notice that the file is from a shared repository
545 */
546 protected function printSharedImageText() {
547 global $wgOut;
548
549 $this->loadFile();
550
551 $descUrl = $this->mPage->getFile()->getDescriptionUrl();
552 $descText = $this->mPage->getFile()->getDescriptionText();
553
554 /* Add canonical to head if there is no local page for this shared file */
555 if( $descUrl && $this->mPage->getID() == 0 ) {
556 $wgOut->addLink( array( 'rel' => 'canonical', 'href' => $descUrl ) );
557 }
558
559 $wrap = "<div class=\"sharedUploadNotice\">\n$1\n</div>\n";
560 $repo = $this->mPage->getFile()->getRepo()->getDisplayName();
561
562 if ( $descUrl && $descText && wfMsgNoTrans( 'sharedupload-desc-here' ) !== '-' ) {
563 $wgOut->wrapWikiMsg( $wrap, array( 'sharedupload-desc-here', $repo, $descUrl ) );
564 } elseif ( $descUrl && wfMsgNoTrans( 'sharedupload-desc-there' ) !== '-' ) {
565 $wgOut->wrapWikiMsg( $wrap, array( 'sharedupload-desc-there', $repo, $descUrl ) );
566 } else {
567 $wgOut->wrapWikiMsg( $wrap, array( 'sharedupload', $repo ), ''/*BACKCOMPAT*/ );
568 }
569
570 if ( $descText ) {
571 $this->mExtraDescription = $descText;
572 }
573 }
574
575 public function getUploadUrl() {
576 $this->loadFile();
577 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
578 return $uploadTitle->getFullURL( array(
579 'wpDestFile' => $this->mPage->getFile()->getName(),
580 'wpForReUpload' => 1
581 ) );
582 }
583
584 /**
585 * Print out the various links at the bottom of the image page, e.g. reupload,
586 * external editing (and instructions link) etc.
587 */
588 protected function uploadLinksBox() {
589 global $wgUser, $wgOut, $wgEnableUploads, $wgUseExternalEditor;
590
591 if ( !$wgEnableUploads ) {
592 return;
593 }
594
595 $this->loadFile();
596 if ( !$this->mPage->getFile()->isLocal() ) {
597 return;
598 }
599
600 $wgOut->addHTML( "<br /><ul>\n" );
601
602 # "Upload a new version of this file" link
603 if ( UploadBase::userCanReUpload( $wgUser, $this->mPage->getFile()->name ) ) {
604 $ulink = Linker::makeExternalLink( $this->getUploadUrl(), wfMsg( 'uploadnewversion-linktext' ) );
605 $wgOut->addHTML( "<li id=\"mw-imagepage-reupload-link\"><div class=\"plainlinks\">{$ulink}</div></li>\n" );
606 }
607
608 # External editing link
609 if ( $wgUseExternalEditor ) {
610 $elink = Linker::link(
611 $this->getTitle(),
612 wfMsgHtml( 'edit-externally' ),
613 array(),
614 array(
615 'action' => 'edit',
616 'externaledit' => 'true',
617 'mode' => 'file'
618 ),
619 array( 'known', 'noclasses' )
620 );
621 $wgOut->addHTML(
622 '<li id="mw-imagepage-edit-external">' . $elink . ' <small>' .
623 wfMsgExt( 'edit-externally-help', array( 'parseinline' ) ) .
624 "</small></li>\n"
625 );
626 }
627
628 $wgOut->addHTML( "</ul>\n" );
629 }
630
631 protected function closeShowImage() { } # For overloading
632
633 /**
634 * If the page we've just displayed is in the "Image" namespace,
635 * we follow it with an upload history of the image and its usage.
636 */
637 protected function imageHistory() {
638 global $wgOut;
639
640 $this->loadFile();
641 $pager = new ImageHistoryPseudoPager( $this );
642 $wgOut->addHTML( $pager->getBody() );
643 $wgOut->preventClickjacking( $pager->getPreventClickjacking() );
644
645 $this->mPage->getFile()->resetHistory(); // free db resources
646
647 # Exist check because we don't want to show this on pages where an image
648 # doesn't exist along with the noimage message, that would suck. -ævar
649 if ( $this->mPage->getFile()->exists() ) {
650 $this->uploadLinksBox();
651 }
652 }
653
654 /**
655 * @param $target
656 * @param $limit
657 * @return ResultWrapper
658 */
659 protected function queryImageLinks( $target, $limit ) {
660 $dbr = wfGetDB( DB_SLAVE );
661
662 return $dbr->select(
663 array( 'imagelinks', 'page' ),
664 array( 'page_namespace', 'page_title', 'page_is_redirect', 'il_to' ),
665 array( 'il_to' => $target, 'il_from = page_id' ),
666 __METHOD__,
667 array( 'LIMIT' => $limit + 1, 'ORDER BY' => 'il_from', )
668 );
669 }
670
671 protected function imageLinks() {
672 global $wgOut, $wgLang;
673
674 $limit = 100;
675
676 $res = $this->queryImageLinks( $this->getTitle()->getDbKey(), $limit + 1);
677 $rows = array();
678 $redirects = array();
679 foreach ( $res as $row ) {
680 if ( $row->page_is_redirect ) {
681 $redirects[$row->page_title] = array();
682 }
683 $rows[] = $row;
684 }
685 $count = count( $rows );
686
687 $hasMore = $count > $limit;
688 if ( !$hasMore && count( $redirects ) ) {
689 $res = $this->queryImageLinks( array_keys( $redirects ),
690 $limit - count( $rows ) + 1 );
691 foreach ( $res as $row ) {
692 $redirects[$row->il_to][] = $row;
693 $count++;
694 }
695 $hasMore = ( $res->numRows() + count( $rows ) ) > $limit;
696 }
697
698 if ( $count == 0 ) {
699 $wgOut->wrapWikiMsg(
700 Html::rawElement( 'div',
701 array( 'id' => 'mw-imagepage-nolinkstoimage' ), "\n$1\n" ),
702 'nolinkstoimage'
703 );
704 return;
705 }
706
707 $wgOut->addHTML( "<div id='mw-imagepage-section-linkstoimage'>\n" );
708 if ( !$hasMore ) {
709 $wgOut->addWikiMsg( 'linkstoimage', $count );
710 } else {
711 // More links than the limit. Add a link to [[Special:Whatlinkshere]]
712 $wgOut->addWikiMsg( 'linkstoimage-more',
713 $wgLang->formatNum( $limit ),
714 $this->getTitle()->getPrefixedDBkey()
715 );
716 }
717
718 $wgOut->addHTML(
719 Html::openElement( 'ul',
720 array( 'class' => 'mw-imagepage-linkstoimage' ) ) . "\n"
721 );
722 $count = 0;
723
724 // Sort the list by namespace:title
725 usort( $rows, array( $this, 'compare' ) );
726
727 // Create links for every element
728 $currentCount = 0;
729 foreach( $rows as $element ) {
730 $currentCount++;
731 if ( $currentCount > $limit ) {
732 break;
733 }
734
735 $link = Linker::linkKnown( Title::makeTitle( $element->page_namespace, $element->page_title ) );
736 if ( !isset( $redirects[$element->page_title] ) ) {
737 $liContents = $link;
738 } else {
739 $ul = "<ul class='mw-imagepage-redirectstofile'>\n";
740 foreach ( $redirects[$element->page_title] as $row ) {
741 $currentCount++;
742 if ( $currentCount > $limit ) {
743 break;
744 }
745
746 $link2 = Linker::linkKnown( Title::makeTitle( $row->page_namespace, $row->page_title ) );
747 $ul .= Html::rawElement(
748 'li',
749 array( 'id' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ),
750 $link2
751 ) . "\n";
752 }
753 $ul .= '</ul>';
754 $liContents = wfMessage( 'linkstoimage-redirect' )->rawParams(
755 $link, $ul )->parse();
756 }
757 $wgOut->addHTML( Html::rawElement(
758 'li',
759 array( 'id' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ),
760 $liContents
761 ) . "\n"
762 );
763
764 };
765 $wgOut->addHTML( Html::closeElement( 'ul' ) . "\n" );
766 $res->free();
767
768 // Add a links to [[Special:Whatlinkshere]]
769 if ( $count > $limit ) {
770 $wgOut->addWikiMsg( 'morelinkstoimage', $this->getTitle()->getPrefixedDBkey() );
771 }
772 $wgOut->addHTML( Html::closeElement( 'div' ) . "\n" );
773 }
774
775 protected function imageDupes() {
776 global $wgOut, $wgLang;
777
778 $this->loadFile();
779
780 $dupes = $this->mPage->getDuplicates();
781 if ( count( $dupes ) == 0 ) {
782 return;
783 }
784
785 $wgOut->addHTML( "<div id='mw-imagepage-section-duplicates'>\n" );
786 $wgOut->addWikiMsg( 'duplicatesoffile',
787 $wgLang->formatNum( count( $dupes ) ), $this->getTitle()->getDBkey()
788 );
789 $wgOut->addHTML( "<ul class='mw-imagepage-duplicates'>\n" );
790
791 /**
792 * @var $file File
793 */
794 foreach ( $dupes as $file ) {
795 $fromSrc = '';
796 if ( $file->isLocal() ) {
797 $link = Linker::link(
798 $file->getTitle(),
799 null,
800 array(),
801 array(),
802 array( 'known', 'noclasses' )
803 );
804 } else {
805 $link = Linker::makeExternalLink( $file->getDescriptionUrl(),
806 $file->getTitle()->getPrefixedText() );
807 $fromSrc = wfMsg( 'shared-repo-from', $file->getRepo()->getDisplayName() );
808 }
809 $wgOut->addHTML( "<li>{$link} {$fromSrc}</li>\n" );
810 }
811 $wgOut->addHTML( "</ul></div>\n" );
812 }
813
814 /**
815 * Delete the file, or an earlier version of it
816 */
817 public function delete() {
818 $file = $this->mPage->getFile();
819 if ( !$file->exists() || !$file->isLocal() || $file->getRedirected() ) {
820 // Standard article deletion
821 parent::delete();
822 return;
823 }
824
825 $deleter = new FileDeleteForm( $file );
826 $deleter->execute();
827 }
828
829 /**
830 * Display an error with a wikitext description
831 *
832 * @param $description String
833 */
834 function showError( $description ) {
835 global $wgOut;
836 $wgOut->setPageTitle( wfMessage( 'internalerror' ) );
837 $wgOut->setRobotPolicy( 'noindex,nofollow' );
838 $wgOut->setArticleRelated( false );
839 $wgOut->enableClientCache( false );
840 $wgOut->addWikiText( $description );
841 }
842
843 /**
844 * Callback for usort() to do link sorts by (namespace, title)
845 * Function copied from Title::compare()
846 *
847 * @param $a object page to compare with
848 * @param $b object page to compare with
849 * @return Integer: result of string comparison, or namespace comparison
850 */
851 protected function compare( $a, $b ) {
852 if ( $a->page_namespace == $b->page_namespace ) {
853 return strcmp( $a->page_title, $b->page_title );
854 } else {
855 return $a->page_namespace - $b->page_namespace;
856 }
857 }
858 }
859
860 /**
861 * Builds the image revision log shown on image pages
862 *
863 * @ingroup Media
864 */
865 class ImageHistoryList {
866
867 /**
868 * @var Title
869 */
870 protected $title;
871
872 /**
873 * @var File
874 */
875 protected $img;
876
877 /**
878 * @var ImagePage
879 */
880 protected $imagePage;
881
882 /**
883 * @var File
884 */
885 protected $current;
886
887 protected $repo, $showThumb;
888 protected $preventClickjacking = false;
889
890 /**
891 * @param ImagePage $imagePage
892 */
893 public function __construct( $imagePage ) {
894 global $wgShowArchiveThumbnails;
895 $this->current = $imagePage->getFile();
896 $this->img = $imagePage->getDisplayedFile();
897 $this->title = $imagePage->getTitle();
898 $this->imagePage = $imagePage;
899 $this->showThumb = $wgShowArchiveThumbnails && $this->img->canRender();
900 }
901
902 /**
903 * @return ImagePage
904 */
905 public function getImagePage() {
906 return $this->imagePage;
907 }
908
909 /**
910 * @return File
911 */
912 public function getFile() {
913 return $this->img;
914 }
915
916 /**
917 * @param $navLinks string
918 * @return string
919 */
920 public function beginImageHistoryList( $navLinks = '' ) {
921 global $wgOut, $wgUser;
922 return Xml::element( 'h2', array( 'id' => 'filehistory' ), wfMsg( 'filehist' ) ) . "\n"
923 . "<div id=\"mw-imagepage-section-filehistory\">\n"
924 . $wgOut->parse( wfMsgNoTrans( 'filehist-help' ) )
925 . $navLinks . "\n"
926 . Xml::openElement( 'table', array( 'class' => 'wikitable filehistory' ) ) . "\n"
927 . '<tr><td></td>'
928 . ( $this->current->isLocal() && ( $wgUser->isAllowedAny( 'delete', 'deletedhistory' ) ) ? '<td></td>' : '' )
929 . '<th>' . wfMsgHtml( 'filehist-datetime' ) . '</th>'
930 . ( $this->showThumb ? '<th>' . wfMsgHtml( 'filehist-thumb' ) . '</th>' : '' )
931 . '<th>' . wfMsgHtml( 'filehist-dimensions' ) . '</th>'
932 . '<th>' . wfMsgHtml( 'filehist-user' ) . '</th>'
933 . '<th>' . wfMsgHtml( 'filehist-comment' ) . '</th>'
934 . "</tr>\n";
935 }
936
937 /**
938 * @param $navLinks string
939 * @return string
940 */
941 public function endImageHistoryList( $navLinks = '' ) {
942 return "</table>\n$navLinks\n</div>\n";
943 }
944
945 /**
946 * @param $iscur
947 * @param $file File
948 * @return string
949 */
950 public function imageHistoryLine( $iscur, $file ) {
951 global $wgUser, $wgLang, $wgContLang;
952
953 $timestamp = wfTimestamp( TS_MW, $file->getTimestamp() );
954 $img = $iscur ? $file->getName() : $file->getArchiveName();
955 $user = $file->getUser( 'id' );
956 $usertext = $file->getUser( 'text' );
957 $description = $file->getDescription();
958
959 $local = $this->current->isLocal();
960 $row = $selected = '';
961
962 // Deletion link
963 if ( $local && ( $wgUser->isAllowedAny( 'delete', 'deletedhistory' ) ) ) {
964 $row .= '<td>';
965 # Link to remove from history
966 if ( $wgUser->isAllowed( 'delete' ) ) {
967 $q = array( 'action' => 'delete' );
968 if ( !$iscur ) {
969 $q['oldimage'] = $img;
970 }
971 $row .= Linker::link(
972 $this->title,
973 wfMsgHtml( $iscur ? 'filehist-deleteall' : 'filehist-deleteone' ),
974 array(), $q, array( 'known' )
975 );
976 }
977 # Link to hide content. Don't show useless link to people who cannot hide revisions.
978 $canHide = $wgUser->isAllowed( 'deleterevision' );
979 if ( $canHide || ( $wgUser->isAllowed( 'deletedhistory' ) && $file->getVisibility() ) ) {
980 if ( $wgUser->isAllowed( 'delete' ) ) {
981 $row .= '<br />';
982 }
983 // If file is top revision or locked from this user, don't link
984 if ( $iscur || !$file->userCan( File::DELETED_RESTRICTED ) ) {
985 $del = Linker::revDeleteLinkDisabled( $canHide );
986 } else {
987 list( $ts, $name ) = explode( '!', $img, 2 );
988 $query = array(
989 'type' => 'oldimage',
990 'target' => $this->title->getPrefixedText(),
991 'ids' => $ts,
992 );
993 $del = Linker::revDeleteLink( $query,
994 $file->isDeleted( File::DELETED_RESTRICTED ), $canHide );
995 }
996 $row .= $del;
997 }
998 $row .= '</td>';
999 }
1000
1001 // Reversion link/current indicator
1002 $row .= '<td>';
1003 if ( $iscur ) {
1004 $row .= wfMsgHtml( 'filehist-current' );
1005 } elseif ( $local && $wgUser->isLoggedIn() && $this->title->userCan( 'edit' ) ) {
1006 if ( $file->isDeleted( File::DELETED_FILE ) ) {
1007 $row .= wfMsgHtml( 'filehist-revert' );
1008 } else {
1009 $row .= Linker::link(
1010 $this->title,
1011 wfMsgHtml( 'filehist-revert' ),
1012 array(),
1013 array(
1014 'action' => 'revert',
1015 'oldimage' => $img,
1016 'wpEditToken' => $wgUser->getEditToken( $img )
1017 ),
1018 array( 'known', 'noclasses' )
1019 );
1020 }
1021 }
1022 $row .= '</td>';
1023
1024 // Date/time and image link
1025 if ( $file->getTimestamp() === $this->img->getTimestamp() ) {
1026 $selected = "class='filehistory-selected'";
1027 }
1028 $row .= "<td $selected style='white-space: nowrap;'>";
1029 if ( !$file->userCan( File::DELETED_FILE ) ) {
1030 # Don't link to unviewable files
1031 $row .= '<span class="history-deleted">' . $wgLang->timeanddate( $timestamp, true ) . '</span>';
1032 } elseif ( $file->isDeleted( File::DELETED_FILE ) ) {
1033 if ( $local ) {
1034 $this->preventClickjacking();
1035 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
1036 # Make a link to review the image
1037 $url = Linker::link(
1038 $revdel,
1039 $wgLang->timeanddate( $timestamp, true ),
1040 array(),
1041 array(
1042 'target' => $this->title->getPrefixedText(),
1043 'file' => $img,
1044 'token' => $wgUser->getEditToken( $img )
1045 ),
1046 array( 'known', 'noclasses' )
1047 );
1048 } else {
1049 $url = $wgLang->timeanddate( $timestamp, true );
1050 }
1051 $row .= '<span class="history-deleted">' . $url . '</span>';
1052 } else {
1053 $url = $iscur ? $this->current->getUrl() : $this->current->getArchiveUrl( $img );
1054 $row .= Xml::element( 'a', array( 'href' => $url ), $wgLang->timeanddate( $timestamp, true ) );
1055 }
1056 $row .= "</td>";
1057
1058 // Thumbnail
1059 if ( $this->showThumb ) {
1060 $row .= '<td>' . $this->getThumbForLine( $file ) . '</td>';
1061 }
1062
1063 // Image dimensions + size
1064 $row .= '<td>';
1065 $row .= htmlspecialchars( $file->getDimensionsString() );
1066 $row .= ' <span style="white-space: nowrap;">(' . Linker::formatSize( $file->getSize() ) . ')</span>';
1067 $row .= '</td>';
1068
1069 // Uploading user
1070 $row .= '<td>';
1071 // Hide deleted usernames
1072 if ( $file->isDeleted( File::DELETED_USER ) ) {
1073 $row .= '<span class="history-deleted">' . wfMsgHtml( 'rev-deleted-user' ) . '</span>';
1074 } else {
1075 if ( $local ) {
1076 $row .= Linker::userLink( $user, $usertext ) . ' <span style="white-space: nowrap;">' .
1077 Linker::userToolLinks( $user, $usertext ) . '</span>';
1078 } else {
1079 $row .= htmlspecialchars( $usertext );
1080 }
1081 }
1082 $row .= '</td>';
1083
1084 // Don't show deleted descriptions
1085 if ( $file->isDeleted( File::DELETED_COMMENT ) ) {
1086 $row .= '<td><span class="history-deleted">' . wfMsgHtml( 'rev-deleted-comment' ) . '</span></td>';
1087 } else {
1088 $row .= '<td dir="' . $wgContLang->getDir() . '">' . Linker::formatComment( $description, $this->title ) . '</td>';
1089 }
1090
1091 $rowClass = null;
1092 wfRunHooks( 'ImagePageFileHistoryLine', array( $this, $file, &$row, &$rowClass ) );
1093 $classAttr = $rowClass ? " class='$rowClass'" : '';
1094
1095 return "<tr{$classAttr}>{$row}</tr>\n";
1096 }
1097
1098 /**
1099 * @param $file File
1100 * @return string
1101 */
1102 protected function getThumbForLine( $file ) {
1103 global $wgLang;
1104
1105 if ( $file->allowInlineDisplay() && $file->userCan( File::DELETED_FILE ) && !$file->isDeleted( File::DELETED_FILE ) ) {
1106 $params = array(
1107 'width' => '120',
1108 'height' => '120',
1109 );
1110 $timestamp = wfTimestamp( TS_MW, $file->getTimestamp() );
1111
1112 $thumbnail = $file->transform( $params );
1113 $options = array(
1114 'alt' => wfMsg( 'filehist-thumbtext',
1115 $wgLang->timeanddate( $timestamp, true ),
1116 $wgLang->date( $timestamp, true ),
1117 $wgLang->time( $timestamp, true ) ),
1118 'file-link' => true,
1119 );
1120
1121 if ( !$thumbnail ) {
1122 return wfMsgHtml( 'filehist-nothumb' );
1123 }
1124
1125 return $thumbnail->toHtml( $options );
1126 } else {
1127 return wfMsgHtml( 'filehist-nothumb' );
1128 }
1129 }
1130
1131 /**
1132 * @param $enable bool
1133 */
1134 protected function preventClickjacking( $enable = true ) {
1135 $this->preventClickjacking = $enable;
1136 }
1137
1138 /**
1139 * @return bool
1140 */
1141 public function getPreventClickjacking() {
1142 return $this->preventClickjacking;
1143 }
1144 }
1145
1146 class ImageHistoryPseudoPager extends ReverseChronologicalPager {
1147 protected $preventClickjacking = false;
1148
1149 /**
1150 * @var File
1151 */
1152 protected $mImg;
1153
1154 /**
1155 * @var Title
1156 */
1157 protected $mTitle;
1158
1159 /**
1160 * @param ImagePage $imagePage
1161 */
1162 function __construct( $imagePage ) {
1163 parent::__construct();
1164 $this->mImagePage = $imagePage;
1165 $this->mTitle = clone ( $imagePage->getTitle() );
1166 $this->mTitle->setFragment( '#filehistory' );
1167 $this->mImg = null;
1168 $this->mHist = array();
1169 $this->mRange = array( 0, 0 ); // display range
1170 }
1171
1172 /**
1173 * @return Title
1174 */
1175 function getTitle() {
1176 return $this->mTitle;
1177 }
1178
1179 function getQueryInfo() {
1180 return false;
1181 }
1182
1183 /**
1184 * @return string
1185 */
1186 function getIndexField() {
1187 return '';
1188 }
1189
1190 /**
1191 * @return string
1192 */
1193 function formatRow( $row ) {
1194 return '';
1195 }
1196
1197 /**
1198 * @return string
1199 */
1200 function getBody() {
1201 $s = '';
1202 $this->doQuery();
1203 if ( count( $this->mHist ) ) {
1204 $list = new ImageHistoryList( $this->mImagePage );
1205 # Generate prev/next links
1206 $navLink = $this->getNavigationBar();
1207 $s = $list->beginImageHistoryList( $navLink );
1208 // Skip rows there just for paging links
1209 for ( $i = $this->mRange[0]; $i <= $this->mRange[1]; $i++ ) {
1210 $file = $this->mHist[$i];
1211 $s .= $list->imageHistoryLine( !$file->isOld(), $file );
1212 }
1213 $s .= $list->endImageHistoryList( $navLink );
1214
1215 if ( $list->getPreventClickjacking() ) {
1216 $this->preventClickjacking();
1217 }
1218 }
1219 return $s;
1220 }
1221
1222 function doQuery() {
1223 if ( $this->mQueryDone ) {
1224 return;
1225 }
1226 $this->mImg = $this->mImagePage->getFile(); // ensure loading
1227 if ( !$this->mImg->exists() ) {
1228 return;
1229 }
1230 $queryLimit = $this->mLimit + 1; // limit plus extra row
1231 if ( $this->mIsBackwards ) {
1232 // Fetch the file history
1233 $this->mHist = $this->mImg->getHistory( $queryLimit, null, $this->mOffset, false );
1234 // The current rev may not meet the offset/limit
1235 $numRows = count( $this->mHist );
1236 if ( $numRows <= $this->mLimit && $this->mImg->getTimestamp() > $this->mOffset ) {
1237 $this->mHist = array_merge( array( $this->mImg ), $this->mHist );
1238 }
1239 } else {
1240 // The current rev may not meet the offset
1241 if ( !$this->mOffset || $this->mImg->getTimestamp() < $this->mOffset ) {
1242 $this->mHist[] = $this->mImg;
1243 }
1244 // Old image versions (fetch extra row for nav links)
1245 $oiLimit = count( $this->mHist ) ? $this->mLimit : $this->mLimit + 1;
1246 // Fetch the file history
1247 $this->mHist = array_merge( $this->mHist,
1248 $this->mImg->getHistory( $oiLimit, $this->mOffset, null, false ) );
1249 }
1250 $numRows = count( $this->mHist ); // Total number of query results
1251 if ( $numRows ) {
1252 # Index value of top item in the list
1253 $firstIndex = $this->mIsBackwards ?
1254 $this->mHist[$numRows - 1]->getTimestamp() : $this->mHist[0]->getTimestamp();
1255 # Discard the extra result row if there is one
1256 if ( $numRows > $this->mLimit && $numRows > 1 ) {
1257 if ( $this->mIsBackwards ) {
1258 # Index value of item past the index
1259 $this->mPastTheEndIndex = $this->mHist[0]->getTimestamp();
1260 # Index value of bottom item in the list
1261 $lastIndex = $this->mHist[1]->getTimestamp();
1262 # Display range
1263 $this->mRange = array( 1, $numRows - 1 );
1264 } else {
1265 # Index value of item past the index
1266 $this->mPastTheEndIndex = $this->mHist[$numRows - 1]->getTimestamp();
1267 # Index value of bottom item in the list
1268 $lastIndex = $this->mHist[$numRows - 2]->getTimestamp();
1269 # Display range
1270 $this->mRange = array( 0, $numRows - 2 );
1271 }
1272 } else {
1273 # Setting indexes to an empty string means that they will be
1274 # omitted if they would otherwise appear in URLs. It just so
1275 # happens that this is the right thing to do in the standard
1276 # UI, in all the relevant cases.
1277 $this->mPastTheEndIndex = '';
1278 # Index value of bottom item in the list
1279 $lastIndex = $this->mIsBackwards ?
1280 $this->mHist[0]->getTimestamp() : $this->mHist[$numRows - 1]->getTimestamp();
1281 # Display range
1282 $this->mRange = array( 0, $numRows - 1 );
1283 }
1284 } else {
1285 $firstIndex = '';
1286 $lastIndex = '';
1287 $this->mPastTheEndIndex = '';
1288 }
1289 if ( $this->mIsBackwards ) {
1290 $this->mIsFirst = ( $numRows < $queryLimit );
1291 $this->mIsLast = ( $this->mOffset == '' );
1292 $this->mLastShown = $firstIndex;
1293 $this->mFirstShown = $lastIndex;
1294 } else {
1295 $this->mIsFirst = ( $this->mOffset == '' );
1296 $this->mIsLast = ( $numRows < $queryLimit );
1297 $this->mLastShown = $lastIndex;
1298 $this->mFirstShown = $firstIndex;
1299 }
1300 $this->mQueryDone = true;
1301 }
1302
1303 /**
1304 * @param $enable bool
1305 */
1306 protected function preventClickjacking( $enable = true ) {
1307 $this->preventClickjacking = $enable;
1308 }
1309
1310 /**
1311 * @return bool
1312 */
1313 public function getPreventClickjacking() {
1314 return $this->preventClickjacking;
1315 }
1316
1317 }