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