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