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