Reverted r111188: backport conflict fodder
[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 $this->showRedirectedFromHeader();
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 parent::view();
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 getContent 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 getContent() {
257 $this->loadFile();
258 if ( $this->mPage->getFile() && !$this->mPage->getFile()->isLocal() && 0 == $this->getID() ) {
259 return '';
260 }
261 return parent::getContent();
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->getDirMark();
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 $wgOut->addWikiText( <<<EOT
455 <div class="fullMedia"><span class="dangerousLink">{$medialink}</span>$dirmark <span class="fileInfo">$longDesc</span></div>
456 <div class="mediaWarning">$warning</div>
457 EOT
458 );
459 } else {
460 $wgOut->addWikiText( <<<EOT
461 <div class="fullMedia">{$medialink}{$dirmark} <span class="fileInfo">$longDesc</span>
462 </div>
463 EOT
464 );
465 }
466 }
467
468 if ( !$this->displayImg->isLocal() ) {
469 $this->printSharedImageText();
470 }
471 } else {
472 # Image does not exist
473 if ( $wgEnableUploads && $wgUser->isAllowed( 'upload' ) ) {
474 // Only show an upload link if the user can upload
475 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
476 $nofile = array(
477 'filepage-nofile-link',
478 $uploadTitle->getFullURL( array( 'wpDestFile' => $this->mPage->getFile()->getName() ) )
479 );
480 } else {
481 $nofile = 'filepage-nofile';
482 }
483 // Note, if there is an image description page, but
484 // no image, then this setRobotPolicy is overriden
485 // by Article::View().
486 $wgOut->setRobotPolicy( 'noindex,nofollow' );
487 $wgOut->wrapWikiMsg( "<div id='mw-imagepage-nofile' class='plainlinks'>\n$1\n</div>", $nofile );
488 if ( !$this->getID() && $wgSend404Code ) {
489 // If there is no image, no shared image, and no description page,
490 // output a 404, to be consistent with articles.
491 $wgRequest->response()->header( 'HTTP/1.1 404 Not Found' );
492 }
493 }
494 $wgOut->setFileVersion( $this->displayImg );
495 }
496
497 /**
498 * Creates an thumbnail of specified size and returns an HTML link to it
499 * @param $params array Scaler parameters
500 * @param $width int
501 * @param $height int
502 * @return string
503 */
504 private function makeSizeLink( $params, $width, $height ) {
505 $params['width'] = $width;
506 $params['height'] = $height;
507 $thumbnail = $this->displayImg->transform( $params );
508 if ( $thumbnail && !$thumbnail->isError() ) {
509 return Html::rawElement( 'a', array(
510 'href' => $thumbnail->getUrl(),
511 'class' => 'mw-thumbnail-link'
512 ), wfMessage( 'show-big-image-size' )->numParams(
513 $thumbnail->getWidth(), $thumbnail->getHeight()
514 )->parse() );
515 } else {
516 return '';
517 }
518 }
519
520 /**
521 * Show a notice that the file is from a shared repository
522 */
523 protected function printSharedImageText() {
524 global $wgOut;
525
526 $this->loadFile();
527
528 $descUrl = $this->mPage->getFile()->getDescriptionUrl();
529 $descText = $this->mPage->getFile()->getDescriptionText();
530
531 /* Add canonical to head if there is no local page for this shared file */
532 if( $descUrl && $this->mPage->getID() == 0 ) {
533 $wgOut->addLink( array( 'rel' => 'canonical', 'href' => $descUrl ) );
534 }
535
536 $wrap = "<div class=\"sharedUploadNotice\">\n$1\n</div>\n";
537 $repo = $this->mPage->getFile()->getRepo()->getDisplayName();
538
539 if ( $descUrl && $descText && wfMsgNoTrans( 'sharedupload-desc-here' ) !== '-' ) {
540 $wgOut->wrapWikiMsg( $wrap, array( 'sharedupload-desc-here', $repo, $descUrl ) );
541 } elseif ( $descUrl && wfMsgNoTrans( 'sharedupload-desc-there' ) !== '-' ) {
542 $wgOut->wrapWikiMsg( $wrap, array( 'sharedupload-desc-there', $repo, $descUrl ) );
543 } else {
544 $wgOut->wrapWikiMsg( $wrap, array( 'sharedupload', $repo ), ''/*BACKCOMPAT*/ );
545 }
546
547 if ( $descText ) {
548 $this->mExtraDescription = $descText;
549 }
550 }
551
552 public function getUploadUrl() {
553 $this->loadFile();
554 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
555 return $uploadTitle->getFullURL( array(
556 'wpDestFile' => $this->mPage->getFile()->getName(),
557 'wpForReUpload' => 1
558 ) );
559 }
560
561 /**
562 * Print out the various links at the bottom of the image page, e.g. reupload,
563 * external editing (and instructions link) etc.
564 */
565 protected function uploadLinksBox() {
566 global $wgUser, $wgOut, $wgEnableUploads, $wgUseExternalEditor;
567
568 if ( !$wgEnableUploads ) {
569 return;
570 }
571
572 $this->loadFile();
573 if ( !$this->mPage->getFile()->isLocal() ) {
574 return;
575 }
576
577 $wgOut->addHTML( "<br /><ul>\n" );
578
579 # "Upload a new version of this file" link
580 if ( UploadBase::userCanReUpload( $wgUser, $this->mPage->getFile()->name ) ) {
581 $ulink = Linker::makeExternalLink( $this->getUploadUrl(), wfMsg( 'uploadnewversion-linktext' ) );
582 $wgOut->addHTML( "<li id=\"mw-imagepage-reupload-link\"><div class=\"plainlinks\">{$ulink}</div></li>\n" );
583 }
584
585 # External editing link
586 if ( $wgUseExternalEditor ) {
587 $elink = Linker::link(
588 $this->getTitle(),
589 wfMsgHtml( 'edit-externally' ),
590 array(),
591 array(
592 'action' => 'edit',
593 'externaledit' => 'true',
594 'mode' => 'file'
595 ),
596 array( 'known', 'noclasses' )
597 );
598 $wgOut->addHTML(
599 '<li id="mw-imagepage-edit-external">' . $elink . ' <small>' .
600 wfMsgExt( 'edit-externally-help', array( 'parseinline' ) ) .
601 "</small></li>\n"
602 );
603 }
604
605 $wgOut->addHTML( "</ul>\n" );
606 }
607
608 protected function closeShowImage() { } # For overloading
609
610 /**
611 * If the page we've just displayed is in the "Image" namespace,
612 * we follow it with an upload history of the image and its usage.
613 */
614 protected function imageHistory() {
615 global $wgOut;
616
617 $this->loadFile();
618 $pager = new ImageHistoryPseudoPager( $this );
619 $wgOut->addHTML( $pager->getBody() );
620 $wgOut->preventClickjacking( $pager->getPreventClickjacking() );
621
622 $this->mPage->getFile()->resetHistory(); // free db resources
623
624 # Exist check because we don't want to show this on pages where an image
625 # doesn't exist along with the noimage message, that would suck. -ævar
626 if ( $this->mPage->getFile()->exists() ) {
627 $this->uploadLinksBox();
628 }
629 }
630
631 /**
632 * @param $target
633 * @param $limit
634 * @return ResultWrapper
635 */
636 protected function queryImageLinks( $target, $limit ) {
637 $dbr = wfGetDB( DB_SLAVE );
638
639 return $dbr->select(
640 array( 'imagelinks', 'page' ),
641 array( 'page_namespace', 'page_title', 'page_is_redirect', 'il_to' ),
642 array( 'il_to' => $target, 'il_from = page_id' ),
643 __METHOD__,
644 array( 'LIMIT' => $limit + 1, 'ORDER BY' => 'il_from', )
645 );
646 }
647
648 protected function imageLinks() {
649 global $wgOut, $wgLang;
650
651 $limit = 100;
652
653 $res = $this->queryImageLinks( $this->getTitle()->getDbKey(), $limit + 1);
654 $rows = array();
655 $redirects = array();
656 foreach ( $res as $row ) {
657 if ( $row->page_is_redirect ) {
658 $redirects[$row->page_title] = array();
659 }
660 $rows[] = $row;
661 }
662 $count = count( $rows );
663
664 $hasMore = $count > $limit;
665 if ( !$hasMore && count( $redirects ) ) {
666 $res = $this->queryImageLinks( array_keys( $redirects ),
667 $limit - count( $rows ) + 1 );
668 foreach ( $res as $row ) {
669 $redirects[$row->il_to][] = $row;
670 $count++;
671 }
672 $hasMore = ( $res->numRows() + count( $rows ) ) > $limit;
673 }
674
675 if ( $count == 0 ) {
676 $wgOut->wrapWikiMsg(
677 Html::rawElement( 'div',
678 array( 'id' => 'mw-imagepage-nolinkstoimage' ), "\n$1\n" ),
679 'nolinkstoimage'
680 );
681 return;
682 }
683
684 $wgOut->addHTML( "<div id='mw-imagepage-section-linkstoimage'>\n" );
685 if ( !$hasMore ) {
686 $wgOut->addWikiMsg( 'linkstoimage', $count );
687 } else {
688 // More links than the limit. Add a link to [[Special:Whatlinkshere]]
689 $wgOut->addWikiMsg( 'linkstoimage-more',
690 $wgLang->formatNum( $limit ),
691 $this->getTitle()->getPrefixedDBkey()
692 );
693 }
694
695 $wgOut->addHTML(
696 Html::openElement( 'ul',
697 array( 'class' => 'mw-imagepage-linkstoimage' ) ) . "\n"
698 );
699 $count = 0;
700
701 // Sort the list by namespace:title
702 usort( $rows, array( $this, 'compare' ) );
703
704 // Create links for every element
705 $currentCount = 0;
706 foreach( $rows as $element ) {
707 $currentCount++;
708 if ( $currentCount > $limit ) {
709 break;
710 }
711
712 $link = Linker::linkKnown( Title::makeTitle( $element->page_namespace, $element->page_title ) );
713 if ( !isset( $redirects[$element->page_title] ) ) {
714 $liContents = $link;
715 } else {
716 $ul = "<ul class='mw-imagepage-redirectstofile'>\n";
717 foreach ( $redirects[$element->page_title] as $row ) {
718 $currentCount++;
719 if ( $currentCount > $limit ) {
720 break;
721 }
722
723 $link2 = Linker::linkKnown( Title::makeTitle( $row->page_namespace, $row->page_title ) );
724 $ul .= Html::rawElement(
725 'li',
726 array( 'id' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ),
727 $link2
728 ) . "\n";
729 }
730 $ul .= '</ul>';
731 $liContents = wfMessage( 'linkstoimage-redirect' )->rawParams(
732 $link, $ul )->parse();
733 }
734 $wgOut->addHTML( Html::rawElement(
735 'li',
736 array( 'id' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ),
737 $liContents
738 ) . "\n"
739 );
740
741 };
742 $wgOut->addHTML( Html::closeElement( 'ul' ) . "\n" );
743 $res->free();
744
745 // Add a links to [[Special:Whatlinkshere]]
746 if ( $count > $limit ) {
747 $wgOut->addWikiMsg( 'morelinkstoimage', $this->getTitle()->getPrefixedDBkey() );
748 }
749 $wgOut->addHTML( Html::closeElement( 'div' ) . "\n" );
750 }
751
752 protected function imageDupes() {
753 global $wgOut, $wgLang;
754
755 $this->loadFile();
756
757 $dupes = $this->mPage->getDuplicates();
758 if ( count( $dupes ) == 0 ) {
759 return;
760 }
761
762 $wgOut->addHTML( "<div id='mw-imagepage-section-duplicates'>\n" );
763 $wgOut->addWikiMsg( 'duplicatesoffile',
764 $wgLang->formatNum( count( $dupes ) ), $this->getTitle()->getDBkey()
765 );
766 $wgOut->addHTML( "<ul class='mw-imagepage-duplicates'>\n" );
767
768 /**
769 * @var $file File
770 */
771 foreach ( $dupes as $file ) {
772 $fromSrc = '';
773 if ( $file->isLocal() ) {
774 $link = Linker::link(
775 $file->getTitle(),
776 null,
777 array(),
778 array(),
779 array( 'known', 'noclasses' )
780 );
781 } else {
782 $link = Linker::makeExternalLink( $file->getDescriptionUrl(),
783 $file->getTitle()->getPrefixedText() );
784 $fromSrc = wfMsg( 'shared-repo-from', $file->getRepo()->getDisplayName() );
785 }
786 $wgOut->addHTML( "<li>{$link} {$fromSrc}</li>\n" );
787 }
788 $wgOut->addHTML( "</ul></div>\n" );
789 }
790
791 /**
792 * Delete the file, or an earlier version of it
793 */
794 public function delete() {
795 $file = $this->mPage->getFile();
796 if ( !$file->exists() || !$file->isLocal() || $file->getRedirected() ) {
797 // Standard article deletion
798 parent::delete();
799 return;
800 }
801
802 $deleter = new FileDeleteForm( $file );
803 $deleter->execute();
804 }
805
806 /**
807 * Display an error with a wikitext description
808 *
809 * @param $description String
810 */
811 function showError( $description ) {
812 global $wgOut;
813 $wgOut->setPageTitle( wfMessage( 'internalerror' ) );
814 $wgOut->setRobotPolicy( 'noindex,nofollow' );
815 $wgOut->setArticleRelated( false );
816 $wgOut->enableClientCache( false );
817 $wgOut->addWikiText( $description );
818 }
819
820 /**
821 * Callback for usort() to do link sorts by (namespace, title)
822 * Function copied from Title::compare()
823 *
824 * @param $a object page to compare with
825 * @param $b object page to compare with
826 * @return Integer: result of string comparison, or namespace comparison
827 */
828 protected function compare( $a, $b ) {
829 if ( $a->page_namespace == $b->page_namespace ) {
830 return strcmp( $a->page_title, $b->page_title );
831 } else {
832 return $a->page_namespace - $b->page_namespace;
833 }
834 }
835 }
836
837 /**
838 * Builds the image revision log shown on image pages
839 *
840 * @ingroup Media
841 */
842 class ImageHistoryList {
843
844 /**
845 * @var Title
846 */
847 protected $title;
848
849 /**
850 * @var File
851 */
852 protected $img;
853
854 /**
855 * @var ImagePage
856 */
857 protected $imagePage;
858
859 /**
860 * @var File
861 */
862 protected $current;
863
864 protected $repo, $showThumb;
865 protected $preventClickjacking = false;
866
867 /**
868 * @param ImagePage $imagePage
869 */
870 public function __construct( $imagePage ) {
871 global $wgShowArchiveThumbnails;
872 $this->current = $imagePage->getFile();
873 $this->img = $imagePage->getDisplayedFile();
874 $this->title = $imagePage->getTitle();
875 $this->imagePage = $imagePage;
876 $this->showThumb = $wgShowArchiveThumbnails && $this->img->canRender();
877 }
878
879 /**
880 * @return ImagePage
881 */
882 public function getImagePage() {
883 return $this->imagePage;
884 }
885
886 /**
887 * @return File
888 */
889 public function getFile() {
890 return $this->img;
891 }
892
893 /**
894 * @param $navLinks string
895 * @return string
896 */
897 public function beginImageHistoryList( $navLinks = '' ) {
898 global $wgOut, $wgUser;
899 return Xml::element( 'h2', array( 'id' => 'filehistory' ), wfMsg( 'filehist' ) ) . "\n"
900 . "<div id=\"mw-imagepage-section-filehistory\">\n"
901 . $wgOut->parse( wfMsgNoTrans( 'filehist-help' ) )
902 . $navLinks . "\n"
903 . Xml::openElement( 'table', array( 'class' => 'wikitable filehistory' ) ) . "\n"
904 . '<tr><td></td>'
905 . ( $this->current->isLocal() && ( $wgUser->isAllowedAny( 'delete', 'deletedhistory' ) ) ? '<td></td>' : '' )
906 . '<th>' . wfMsgHtml( 'filehist-datetime' ) . '</th>'
907 . ( $this->showThumb ? '<th>' . wfMsgHtml( 'filehist-thumb' ) . '</th>' : '' )
908 . '<th>' . wfMsgHtml( 'filehist-dimensions' ) . '</th>'
909 . '<th>' . wfMsgHtml( 'filehist-user' ) . '</th>'
910 . '<th>' . wfMsgHtml( 'filehist-comment' ) . '</th>'
911 . "</tr>\n";
912 }
913
914 /**
915 * @param $navLinks string
916 * @return string
917 */
918 public function endImageHistoryList( $navLinks = '' ) {
919 return "</table>\n$navLinks\n</div>\n";
920 }
921
922 /**
923 * @param $iscur
924 * @param $file File
925 * @return string
926 */
927 public function imageHistoryLine( $iscur, $file ) {
928 global $wgUser, $wgLang, $wgContLang;
929
930 $timestamp = wfTimestamp( TS_MW, $file->getTimestamp() );
931 $img = $iscur ? $file->getName() : $file->getArchiveName();
932 $user = $file->getUser( 'id' );
933 $usertext = $file->getUser( 'text' );
934 $description = $file->getDescription();
935
936 $local = $this->current->isLocal();
937 $row = $selected = '';
938
939 // Deletion link
940 if ( $local && ( $wgUser->isAllowedAny( 'delete', 'deletedhistory' ) ) ) {
941 $row .= '<td>';
942 # Link to remove from history
943 if ( $wgUser->isAllowed( 'delete' ) ) {
944 $q = array( 'action' => 'delete' );
945 if ( !$iscur ) {
946 $q['oldimage'] = $img;
947 }
948 $row .= Linker::link(
949 $this->title,
950 wfMsgHtml( $iscur ? 'filehist-deleteall' : 'filehist-deleteone' ),
951 array(), $q, array( 'known' )
952 );
953 }
954 # Link to hide content. Don't show useless link to people who cannot hide revisions.
955 $canHide = $wgUser->isAllowed( 'deleterevision' );
956 if ( $canHide || ( $wgUser->isAllowed( 'deletedhistory' ) && $file->getVisibility() ) ) {
957 if ( $wgUser->isAllowed( 'delete' ) ) {
958 $row .= '<br />';
959 }
960 // If file is top revision or locked from this user, don't link
961 if ( $iscur || !$file->userCan( File::DELETED_RESTRICTED ) ) {
962 $del = Linker::revDeleteLinkDisabled( $canHide );
963 } else {
964 list( $ts, $name ) = explode( '!', $img, 2 );
965 $query = array(
966 'type' => 'oldimage',
967 'target' => $this->title->getPrefixedText(),
968 'ids' => $ts,
969 );
970 $del = Linker::revDeleteLink( $query,
971 $file->isDeleted( File::DELETED_RESTRICTED ), $canHide );
972 }
973 $row .= $del;
974 }
975 $row .= '</td>';
976 }
977
978 // Reversion link/current indicator
979 $row .= '<td>';
980 if ( $iscur ) {
981 $row .= wfMsgHtml( 'filehist-current' );
982 } elseif ( $local && $wgUser->isLoggedIn() && $this->title->userCan( 'edit' ) ) {
983 if ( $file->isDeleted( File::DELETED_FILE ) ) {
984 $row .= wfMsgHtml( 'filehist-revert' );
985 } else {
986 $row .= Linker::link(
987 $this->title,
988 wfMsgHtml( 'filehist-revert' ),
989 array(),
990 array(
991 'action' => 'revert',
992 'oldimage' => $img,
993 'wpEditToken' => $wgUser->getEditToken( $img )
994 ),
995 array( 'known', 'noclasses' )
996 );
997 }
998 }
999 $row .= '</td>';
1000
1001 // Date/time and image link
1002 if ( $file->getTimestamp() === $this->img->getTimestamp() ) {
1003 $selected = "class='filehistory-selected'";
1004 }
1005 $row .= "<td $selected style='white-space: nowrap;'>";
1006 if ( !$file->userCan( File::DELETED_FILE ) ) {
1007 # Don't link to unviewable files
1008 $row .= '<span class="history-deleted">' . $wgLang->timeanddate( $timestamp, true ) . '</span>';
1009 } elseif ( $file->isDeleted( File::DELETED_FILE ) ) {
1010 if ( $local ) {
1011 $this->preventClickjacking();
1012 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
1013 # Make a link to review the image
1014 $url = Linker::link(
1015 $revdel,
1016 $wgLang->timeanddate( $timestamp, true ),
1017 array(),
1018 array(
1019 'target' => $this->title->getPrefixedText(),
1020 'file' => $img,
1021 'token' => $wgUser->getEditToken( $img )
1022 ),
1023 array( 'known', 'noclasses' )
1024 );
1025 } else {
1026 $url = $wgLang->timeanddate( $timestamp, true );
1027 }
1028 $row .= '<span class="history-deleted">' . $url . '</span>';
1029 } else {
1030 $url = $iscur ? $this->current->getUrl() : $this->current->getArchiveUrl( $img );
1031 $row .= Xml::element( 'a', array( 'href' => $url ), $wgLang->timeanddate( $timestamp, true ) );
1032 }
1033 $row .= "</td>";
1034
1035 // Thumbnail
1036 if ( $this->showThumb ) {
1037 $row .= '<td>' . $this->getThumbForLine( $file ) . '</td>';
1038 }
1039
1040 // Image dimensions + size
1041 $row .= '<td>';
1042 $row .= htmlspecialchars( $file->getDimensionsString() );
1043 $row .= ' <span style="white-space: nowrap;">(' . Linker::formatSize( $file->getSize() ) . ')</span>';
1044 $row .= '</td>';
1045
1046 // Uploading user
1047 $row .= '<td>';
1048 // Hide deleted usernames
1049 if ( $file->isDeleted( File::DELETED_USER ) ) {
1050 $row .= '<span class="history-deleted">' . wfMsgHtml( 'rev-deleted-user' ) . '</span>';
1051 } else {
1052 if ( $local ) {
1053 $row .= Linker::userLink( $user, $usertext ) . ' <span style="white-space: nowrap;">' .
1054 Linker::userToolLinks( $user, $usertext ) . '</span>';
1055 } else {
1056 $row .= htmlspecialchars( $usertext );
1057 }
1058 }
1059 $row .= '</td>';
1060
1061 // Don't show deleted descriptions
1062 if ( $file->isDeleted( File::DELETED_COMMENT ) ) {
1063 $row .= '<td><span class="history-deleted">' . wfMsgHtml( 'rev-deleted-comment' ) . '</span></td>';
1064 } else {
1065 $row .= '<td dir="' . $wgContLang->getDir() . '">' . Linker::formatComment( $description, $this->title ) . '</td>';
1066 }
1067
1068 $rowClass = null;
1069 wfRunHooks( 'ImagePageFileHistoryLine', array( $this, $file, &$row, &$rowClass ) );
1070 $classAttr = $rowClass ? " class='$rowClass'" : '';
1071
1072 return "<tr{$classAttr}>{$row}</tr>\n";
1073 }
1074
1075 /**
1076 * @param $file File
1077 * @return string
1078 */
1079 protected function getThumbForLine( $file ) {
1080 global $wgLang;
1081
1082 if ( $file->allowInlineDisplay() && $file->userCan( File::DELETED_FILE ) && !$file->isDeleted( File::DELETED_FILE ) ) {
1083 $params = array(
1084 'width' => '120',
1085 'height' => '120',
1086 );
1087 $timestamp = wfTimestamp( TS_MW, $file->getTimestamp() );
1088
1089 $thumbnail = $file->transform( $params );
1090 $options = array(
1091 'alt' => wfMsg( 'filehist-thumbtext',
1092 $wgLang->timeanddate( $timestamp, true ),
1093 $wgLang->date( $timestamp, true ),
1094 $wgLang->time( $timestamp, true ) ),
1095 'file-link' => true,
1096 );
1097
1098 if ( !$thumbnail ) {
1099 return wfMsgHtml( 'filehist-nothumb' );
1100 }
1101
1102 return $thumbnail->toHtml( $options );
1103 } else {
1104 return wfMsgHtml( 'filehist-nothumb' );
1105 }
1106 }
1107
1108 /**
1109 * @param $enable bool
1110 */
1111 protected function preventClickjacking( $enable = true ) {
1112 $this->preventClickjacking = $enable;
1113 }
1114
1115 /**
1116 * @return bool
1117 */
1118 public function getPreventClickjacking() {
1119 return $this->preventClickjacking;
1120 }
1121 }
1122
1123 class ImageHistoryPseudoPager extends ReverseChronologicalPager {
1124 protected $preventClickjacking = false;
1125
1126 /**
1127 * @var File
1128 */
1129 protected $mImg;
1130
1131 /**
1132 * @var Title
1133 */
1134 protected $mTitle;
1135
1136 /**
1137 * @param ImagePage $imagePage
1138 */
1139 function __construct( $imagePage ) {
1140 parent::__construct();
1141 $this->mImagePage = $imagePage;
1142 $this->mTitle = clone ( $imagePage->getTitle() );
1143 $this->mTitle->setFragment( '#filehistory' );
1144 $this->mImg = null;
1145 $this->mHist = array();
1146 $this->mRange = array( 0, 0 ); // display range
1147 }
1148
1149 /**
1150 * @return Title
1151 */
1152 function getTitle() {
1153 return $this->mTitle;
1154 }
1155
1156 function getQueryInfo() {
1157 return false;
1158 }
1159
1160 /**
1161 * @return string
1162 */
1163 function getIndexField() {
1164 return '';
1165 }
1166
1167 /**
1168 * @return string
1169 */
1170 function formatRow( $row ) {
1171 return '';
1172 }
1173
1174 /**
1175 * @return string
1176 */
1177 function getBody() {
1178 $s = '';
1179 $this->doQuery();
1180 if ( count( $this->mHist ) ) {
1181 $list = new ImageHistoryList( $this->mImagePage );
1182 # Generate prev/next links
1183 $navLink = $this->getNavigationBar();
1184 $s = $list->beginImageHistoryList( $navLink );
1185 // Skip rows there just for paging links
1186 for ( $i = $this->mRange[0]; $i <= $this->mRange[1]; $i++ ) {
1187 $file = $this->mHist[$i];
1188 $s .= $list->imageHistoryLine( !$file->isOld(), $file );
1189 }
1190 $s .= $list->endImageHistoryList( $navLink );
1191
1192 if ( $list->getPreventClickjacking() ) {
1193 $this->preventClickjacking();
1194 }
1195 }
1196 return $s;
1197 }
1198
1199 function doQuery() {
1200 if ( $this->mQueryDone ) {
1201 return;
1202 }
1203 $this->mImg = $this->mImagePage->getFile(); // ensure loading
1204 if ( !$this->mImg->exists() ) {
1205 return;
1206 }
1207 $queryLimit = $this->mLimit + 1; // limit plus extra row
1208 if ( $this->mIsBackwards ) {
1209 // Fetch the file history
1210 $this->mHist = $this->mImg->getHistory( $queryLimit, null, $this->mOffset, false );
1211 // The current rev may not meet the offset/limit
1212 $numRows = count( $this->mHist );
1213 if ( $numRows <= $this->mLimit && $this->mImg->getTimestamp() > $this->mOffset ) {
1214 $this->mHist = array_merge( array( $this->mImg ), $this->mHist );
1215 }
1216 } else {
1217 // The current rev may not meet the offset
1218 if ( !$this->mOffset || $this->mImg->getTimestamp() < $this->mOffset ) {
1219 $this->mHist[] = $this->mImg;
1220 }
1221 // Old image versions (fetch extra row for nav links)
1222 $oiLimit = count( $this->mHist ) ? $this->mLimit : $this->mLimit + 1;
1223 // Fetch the file history
1224 $this->mHist = array_merge( $this->mHist,
1225 $this->mImg->getHistory( $oiLimit, $this->mOffset, null, false ) );
1226 }
1227 $numRows = count( $this->mHist ); // Total number of query results
1228 if ( $numRows ) {
1229 # Index value of top item in the list
1230 $firstIndex = $this->mIsBackwards ?
1231 $this->mHist[$numRows - 1]->getTimestamp() : $this->mHist[0]->getTimestamp();
1232 # Discard the extra result row if there is one
1233 if ( $numRows > $this->mLimit && $numRows > 1 ) {
1234 if ( $this->mIsBackwards ) {
1235 # Index value of item past the index
1236 $this->mPastTheEndIndex = $this->mHist[0]->getTimestamp();
1237 # Index value of bottom item in the list
1238 $lastIndex = $this->mHist[1]->getTimestamp();
1239 # Display range
1240 $this->mRange = array( 1, $numRows - 1 );
1241 } else {
1242 # Index value of item past the index
1243 $this->mPastTheEndIndex = $this->mHist[$numRows - 1]->getTimestamp();
1244 # Index value of bottom item in the list
1245 $lastIndex = $this->mHist[$numRows - 2]->getTimestamp();
1246 # Display range
1247 $this->mRange = array( 0, $numRows - 2 );
1248 }
1249 } else {
1250 # Setting indexes to an empty string means that they will be
1251 # omitted if they would otherwise appear in URLs. It just so
1252 # happens that this is the right thing to do in the standard
1253 # UI, in all the relevant cases.
1254 $this->mPastTheEndIndex = '';
1255 # Index value of bottom item in the list
1256 $lastIndex = $this->mIsBackwards ?
1257 $this->mHist[0]->getTimestamp() : $this->mHist[$numRows - 1]->getTimestamp();
1258 # Display range
1259 $this->mRange = array( 0, $numRows - 1 );
1260 }
1261 } else {
1262 $firstIndex = '';
1263 $lastIndex = '';
1264 $this->mPastTheEndIndex = '';
1265 }
1266 if ( $this->mIsBackwards ) {
1267 $this->mIsFirst = ( $numRows < $queryLimit );
1268 $this->mIsLast = ( $this->mOffset == '' );
1269 $this->mLastShown = $firstIndex;
1270 $this->mFirstShown = $lastIndex;
1271 } else {
1272 $this->mIsFirst = ( $this->mOffset == '' );
1273 $this->mIsLast = ( $numRows < $queryLimit );
1274 $this->mLastShown = $lastIndex;
1275 $this->mFirstShown = $firstIndex;
1276 }
1277 $this->mQueryDone = true;
1278 }
1279
1280 /**
1281 * @param $enable bool
1282 */
1283 protected function preventClickjacking( $enable = true ) {
1284 $this->preventClickjacking = $enable;
1285 }
1286
1287 /**
1288 * @return bool
1289 */
1290 public function getPreventClickjacking() {
1291 return $this->preventClickjacking;
1292 }
1293
1294 }