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