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