* Changed action=revert to use a subclass of Action
[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 # When $wgBetterDirectionality is enabled, NS_FILE is in the user language,
128 # but this section (the actual wikitext) 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 $sk = $wgUser->getSkin();
276 $dirmark = wfUILang()->getDirMark();
277
278 if ( $this->displayImg->exists() ) {
279 # image
280 $page = $wgRequest->getIntOrNull( 'page' );
281 if ( is_null( $page ) ) {
282 $params = array();
283 $page = 1;
284 } else {
285 $params = array( 'page' => $page );
286 }
287 $width_orig = $this->displayImg->getWidth( $page );
288 $width = $width_orig;
289 $height_orig = $this->displayImg->getHeight( $page );
290 $height = $height_orig;
291
292 $longDesc = wfMsg( 'parentheses', $this->displayImg->getLongDesc() );
293
294 wfRunHooks( 'ImageOpenShowImageInlineBefore', array( &$this, &$wgOut ) );
295
296 if ( $this->displayImg->allowInlineDisplay() ) {
297 # image
298
299 # "Download high res version" link below the image
300 # $msgsize = wfMsgHtml( 'file-info-size', $width_orig, $height_orig, $sk->formatSize( $this->displayImg->getSize() ), $mime );
301 # We'll show a thumbnail of this image
302 if ( $width > $maxWidth || $height > $maxHeight ) {
303 # Calculate the thumbnail size.
304 # First case, the limiting factor is the width, not the height.
305 if ( $width / $height >= $maxWidth / $maxHeight ) {
306 $height = round( $height * $maxWidth / $width );
307 $width = $maxWidth;
308 # Note that $height <= $maxHeight now.
309 } else {
310 $newwidth = floor( $width * $maxHeight / $height );
311 $height = round( $height * $newwidth / $width );
312 $width = $newwidth;
313 # Note that $height <= $maxHeight now, but might not be identical
314 # because of rounding.
315 }
316 $msgbig = wfMsgHtml( 'show-big-image' );
317 $otherSizes = array();
318 foreach ( $wgImageLimits as $size ) {
319 if ( $size[0] < $width_orig && $size[1] < $height_orig &&
320 $size[0] != $width && $size[1] != $height ) {
321 $otherSizes[] = $this->makeSizeLink( $params, $size[0], $size[1] );
322 }
323 }
324 $msgsmall = wfMessage( 'show-big-image-preview' )->
325 rawParams( $this->makeSizeLink( $params, $width, $height ) )->
326 parse() . ' ' .
327 wfMessage( 'show-big-image-other' )->
328 rawParams( $wgLang->pipeList( $otherSizes ) )->parse();
329 } else {
330 # Image is small enough to show full size on image page
331 $msgsmall = wfMsgExt( 'file-nohires', array( 'parseinline' ) );
332 }
333
334 $params['width'] = $width;
335 $params['height'] = $height;
336 $thumbnail = $this->displayImg->transform( $params );
337
338 $showLink = true;
339 $anchorclose = '<br />' . $msgsmall;
340
341 $isMulti = $this->displayImg->isMultipage() && $this->displayImg->pageCount() > 1;
342 if ( $isMulti ) {
343 $wgOut->addHTML( '<table class="multipageimage"><tr><td>' );
344 }
345
346 if ( $thumbnail ) {
347 $options = array(
348 'alt' => $this->displayImg->getTitle()->getPrefixedText(),
349 'file-link' => true,
350 );
351 $wgOut->addHTML( '<div class="fullImageLink" id="file">' .
352 $thumbnail->toHtml( $options ) .
353 $anchorclose . "</div>\n" );
354 }
355
356 if ( $isMulti ) {
357 $count = $this->displayImg->pageCount();
358
359 if ( $page > 1 ) {
360 $label = $wgOut->parse( wfMsg( 'imgmultipageprev' ), false );
361 $link = $sk->link(
362 $this->getTitle(),
363 $label,
364 array(),
365 array( 'page' => $page - 1 ),
366 array( 'known', 'noclasses' )
367 );
368 $thumb1 = $sk->makeThumbLinkObj( $this->getTitle(), $this->displayImg, $link, $label, 'none',
369 array( 'page' => $page - 1 ) );
370 } else {
371 $thumb1 = '';
372 }
373
374 if ( $page < $count ) {
375 $label = wfMsg( 'imgmultipagenext' );
376 $link = $sk->link(
377 $this->getTitle(),
378 $label,
379 array(),
380 array( 'page' => $page + 1 ),
381 array( 'known', 'noclasses' )
382 );
383 $thumb2 = $sk->makeThumbLinkObj( $this->getTitle(), $this->displayImg, $link, $label, 'none',
384 array( 'page' => $page + 1 ) );
385 } else {
386 $thumb2 = '';
387 }
388
389 global $wgScript;
390
391 $formParams = array(
392 'name' => 'pageselector',
393 'action' => $wgScript,
394 'onchange' => 'document.pageselector.submit();',
395 );
396
397 for ( $i = 1; $i <= $count; $i++ ) {
398 $options[] = Xml::option( $wgLang->formatNum( $i ), $i, $i == $page );
399 }
400 $select = Xml::tags( 'select',
401 array( 'id' => 'pageselector', 'name' => 'page' ),
402 implode( "\n", $options ) );
403
404 $wgOut->addHTML(
405 '</td><td><div class="multipageimagenavbox">' .
406 Xml::openElement( 'form', $formParams ) .
407 Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() ) .
408 wfMsgExt( 'imgmultigoto', array( 'parseinline', 'replaceafter' ), $select ) .
409 Xml::submitButton( wfMsg( 'imgmultigo' ) ) .
410 Xml::closeElement( 'form' ) .
411 "<hr />$thumb1\n$thumb2<br clear=\"all\" /></div></td></tr></table>"
412 );
413 }
414 } else {
415 # if direct link is allowed but it's not a renderable image, show an icon.
416 if ( $this->displayImg->isSafeFile() ) {
417 $icon = $this->displayImg->iconThumb();
418
419 $wgOut->addHTML( '<div class="fullImageLink" id="file">' .
420 $icon->toHtml( array( 'file-link' => true ) ) .
421 "</div>\n" );
422 }
423
424 $showLink = true;
425 }
426
427 if ( $showLink ) {
428 $filename = wfEscapeWikiText( $this->displayImg->getName() );
429 $linktext = $filename;
430 if ( isset( $msgbig ) ) {
431 $linktext = wfEscapeWikiText( $msgbig );
432 }
433 $medialink = "[[Media:$filename|$linktext]]";
434
435 if ( !$this->displayImg->isSafeFile() ) {
436 $warning = wfMsgNoTrans( 'mediawarning' );
437 $wgOut->addWikiText( <<<EOT
438 <div class="fullMedia"><span class="dangerousLink">{$medialink}</span>$dirmark <span class="fileInfo">$longDesc</span></div>
439 <div class="mediaWarning">$warning</div>
440 EOT
441 );
442 } else {
443 $wgOut->addWikiText( <<<EOT
444 <div class="fullMedia">{$medialink}{$dirmark} <span class="fileInfo">$longDesc</span>
445 </div>
446 EOT
447 );
448 }
449 }
450
451 if ( !$this->displayImg->isLocal() ) {
452 $this->printSharedImageText();
453 }
454 } else {
455 # Image does not exist
456 if ( $wgEnableUploads && $wgUser->isAllowed( 'upload' ) ) {
457 // Only show an upload link if the user can upload
458 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
459 $nofile = array(
460 'filepage-nofile-link',
461 $uploadTitle->getFullURL( array( 'wpDestFile' => $this->mPage->getFile()->getName() ) )
462 );
463 } else {
464 $nofile = 'filepage-nofile';
465 }
466 // Note, if there is an image description page, but
467 // no image, then this setRobotPolicy is overriden
468 // by Article::View().
469 $wgOut->setRobotPolicy( 'noindex,nofollow' );
470 $wgOut->wrapWikiMsg( "<div id='mw-imagepage-nofile' class='plainlinks'>\n$1\n</div>", $nofile );
471 if ( !$this->getID() ) {
472 // If there is no image, no shared image, and no description page,
473 // output a 404, to be consistent with articles.
474 $wgRequest->response()->header( 'HTTP/1.1 404 Not Found' );
475 }
476 }
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 $sk = $wgUser->getSkin();
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 = $sk->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 = $sk->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 $wgUser, $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 $sk = $wgUser->getSkin();
678 $count = 0;
679
680 // Sort the list by namespace:title
681 usort( $rows, array( $this, 'compare' ) );
682
683 // Create links for every element
684 $currentCount = 0;
685 foreach( $rows as $element ) {
686 $currentCount++;
687 if ( $currentCount > $limit ) {
688 break;
689 }
690
691 $link = $sk->linkKnown( Title::makeTitle( $element->page_namespace, $element->page_title ) );
692 if ( !isset( $redirects[$element->page_title] ) ) {
693 $liContents = $link;
694 } else {
695 $ul = "<ul class='mw-imagepage-redirectstofile'>\n";
696 foreach ( $redirects[$element->page_title] as $row ) {
697 $currentCount++;
698 if ( $currentCount > $limit ) {
699 break;
700 }
701
702 $link2 = $sk->linkKnown( Title::makeTitle( $row->page_namespace, $row->page_title ) );
703 $ul .= Html::rawElement(
704 'li',
705 array( 'id' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ),
706 $link2
707 ) . "\n";
708 }
709 $ul .= '</ul>';
710 $liContents = wfMessage( 'linkstoimage-redirect' )->rawParams(
711 $link, $ul )->parse();
712 }
713 $wgOut->addHTML( Html::rawElement(
714 'li',
715 array( 'id' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ),
716 $liContents
717 ) . "\n"
718 );
719
720 };
721 $wgOut->addHTML( Html::closeElement( 'ul' ) . "\n" );
722 $res->free();
723
724 // Add a links to [[Special:Whatlinkshere]]
725 if ( $count > $limit ) {
726 $wgOut->addWikiMsg( 'morelinkstoimage', $this->getTitle()->getPrefixedDBkey() );
727 }
728 $wgOut->addHTML( Html::closeElement( 'div' ) . "\n" );
729 }
730
731 protected function imageDupes() {
732 global $wgOut, $wgUser, $wgLang;
733
734 $this->loadFile();
735
736 $dupes = $this->mPage->getDuplicates();
737 if ( count( $dupes ) == 0 ) {
738 return;
739 }
740
741 $wgOut->addHTML( "<div id='mw-imagepage-section-duplicates'>\n" );
742 $wgOut->addWikiMsg( 'duplicatesoffile',
743 $wgLang->formatNum( count( $dupes ) ), $this->getTitle()->getDBkey()
744 );
745 $wgOut->addHTML( "<ul class='mw-imagepage-duplicates'>\n" );
746
747 $sk = $wgUser->getSkin();
748 foreach ( $dupes as $file ) {
749 $fromSrc = '';
750 if ( $file->isLocal() ) {
751 $link = $sk->link(
752 $file->getTitle(),
753 null,
754 array(),
755 array(),
756 array( 'known', 'noclasses' )
757 );
758 } else {
759 $link = $sk->makeExternalLink( $file->getDescriptionUrl(),
760 $file->getTitle()->getPrefixedText() );
761 $fromSrc = wfMsg( 'shared-repo-from', $file->getRepo()->getDisplayName() );
762 }
763 $wgOut->addHTML( "<li>{$link} {$fromSrc}</li>\n" );
764 }
765 $wgOut->addHTML( "</ul></div>\n" );
766 }
767
768 /**
769 * Delete the file, or an earlier version of it
770 */
771 public function delete() {
772 global $wgUploadMaintenance;
773 if ( $wgUploadMaintenance && $this->getTitle() && $this->getTitle()->getNamespace() == NS_FILE ) {
774 global $wgOut;
775 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n", array( 'filedelete-maintenance' ) );
776 return;
777 }
778
779 $this->loadFile();
780 if ( !$this->mPage->getFile()->exists() || !$this->mPage->getFile()->isLocal() || $this->mPage->getFile()->getRedirected() ) {
781 // Standard article deletion
782 parent::delete();
783 return;
784 }
785 $deleter = new FileDeleteForm( $this->mPage->getFile() );
786 $deleter->execute();
787 }
788
789 /**
790 * Override handling of action=purge
791 */
792 public function doPurge() {
793 $this->loadFile();
794 if ( $this->mPage->getFile()->exists() ) {
795 wfDebug( 'ImagePage::doPurge purging ' . $this->mPage->getFile()->getName() . "\n" );
796 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
797 $update->doUpdate();
798 $this->mPage->getFile()->upgradeRow();
799 $this->mPage->getFile()->purgeCache();
800 } else {
801 wfDebug( 'ImagePage::doPurge no image for ' . $this->mPage->getFile()->getName() . "; limiting purge to cache only\n" );
802 // even if the file supposedly doesn't exist, force any cached information
803 // to be updated (in case the cached information is wrong)
804 $this->mPage->getFile()->purgeCache();
805 }
806 parent::doPurge();
807 }
808
809 /**
810 * Display an error with a wikitext description
811 */
812 function showError( $description ) {
813 global $wgOut;
814 $wgOut->setPageTitle( wfMsg( 'internalerror' ) );
815 $wgOut->setRobotPolicy( 'noindex,nofollow' );
816 $wgOut->setArticleRelated( false );
817 $wgOut->enableClientCache( false );
818 $wgOut->addWikiText( $description );
819 }
820
821 /**
822 * Callback for usort() to do link sorts by (namespace, title)
823 * Function copied from Title::compare()
824 *
825 * @param $a object page to compare with
826 * @param $b object page to compare with
827 * @return Integer: result of string comparison, or namespace comparison
828 */
829 protected function compare( $a, $b ) {
830 if ( $a->page_namespace == $b->page_namespace ) {
831 return strcmp( $a->page_title, $b->page_title );
832 } else {
833 return $a->page_namespace - $b->page_namespace;
834 }
835 }
836 }
837
838 /**
839 * Builds the image revision log shown on image pages
840 *
841 * @ingroup Media
842 */
843 class ImageHistoryList {
844
845 /**
846 * @var Title
847 */
848 protected $title;
849
850 /**
851 * @var File
852 */
853 protected $img;
854
855 /**
856 * @var ImagePage
857 */
858 protected $imagePage;
859
860 /**
861 * @var Skin
862 */
863 protected $skin;
864
865 protected $repo, $showThumb;
866 protected $preventClickjacking = false;
867
868 /**
869 * @param ImagePage $imagePage
870 */
871 public function __construct( $imagePage ) {
872 global $wgUser, $wgShowArchiveThumbnails;
873 $this->skin = $wgUser->getSkin();
874 $this->current = $imagePage->getFile();
875 $this->img = $imagePage->getDisplayedFile();
876 $this->title = $imagePage->getTitle();
877 $this->imagePage = $imagePage;
878 $this->showThumb = $wgShowArchiveThumbnails && $this->img->canRender();
879 }
880
881 public function getImagePage() {
882 return $this->imagePage;
883 }
884
885 public function getSkin() {
886 return $this->skin;
887 }
888
889 public function getFile() {
890 return $this->img;
891 }
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 public function endImageHistoryList( $navLinks = '' ) {
911 return "</table>\n$navLinks\n</div>\n";
912 }
913
914 /**
915 * @param $iscur
916 * @param $file File
917 * @return string
918 */
919 public function imageHistoryLine( $iscur, $file ) {
920 global $wgUser, $wgLang;
921
922 $timestamp = wfTimestamp( TS_MW, $file->getTimestamp() );
923 $img = $iscur ? $file->getName() : $file->getArchiveName();
924 $user = $file->getUser( 'id' );
925 $usertext = $file->getUser( 'text' );
926 $description = $file->getDescription();
927
928 $local = $this->current->isLocal();
929 $row = $selected = '';
930
931 // Deletion link
932 if ( $local && ( $wgUser->isAllowedAny( 'delete', 'deletedhistory' ) ) ) {
933 $row .= '<td>';
934 # Link to remove from history
935 if ( $wgUser->isAllowed( 'delete' ) ) {
936 $q = array( 'action' => 'delete' );
937 if ( !$iscur ) {
938 $q['oldimage'] = $img;
939 }
940 $row .= $this->skin->link(
941 $this->title,
942 wfMsgHtml( $iscur ? 'filehist-deleteall' : 'filehist-deleteone' ),
943 array(), $q, array( 'known' )
944 );
945 }
946 # Link to hide content. Don't show useless link to people who cannot hide revisions.
947 $canHide = $wgUser->isAllowed( 'deleterevision' );
948 if ( $canHide || ( $wgUser->isAllowed( 'deletedhistory' ) && $file->getVisibility() ) ) {
949 if ( $wgUser->isAllowed( 'delete' ) ) {
950 $row .= '<br />';
951 }
952 // If file is top revision or locked from this user, don't link
953 if ( $iscur || !$file->userCan( File::DELETED_RESTRICTED ) ) {
954 $del = $this->skin->revDeleteLinkDisabled( $canHide );
955 } else {
956 list( $ts, $name ) = explode( '!', $img, 2 );
957 $query = array(
958 'type' => 'oldimage',
959 'target' => $this->title->getPrefixedText(),
960 'ids' => $ts,
961 );
962 $del = $this->skin->revDeleteLink( $query,
963 $file->isDeleted( File::DELETED_RESTRICTED ), $canHide );
964 }
965 $row .= $del;
966 }
967 $row .= '</td>';
968 }
969
970 // Reversion link/current indicator
971 $row .= '<td>';
972 if ( $iscur ) {
973 $row .= wfMsgHtml( 'filehist-current' );
974 } elseif ( $local && $wgUser->isLoggedIn() && $this->title->userCan( 'edit' ) ) {
975 if ( $file->isDeleted( File::DELETED_FILE ) ) {
976 $row .= wfMsgHtml( 'filehist-revert' );
977 } else {
978 $row .= $this->skin->link(
979 $this->title,
980 wfMsgHtml( 'filehist-revert' ),
981 array(),
982 array(
983 'action' => 'revert',
984 'oldimage' => $img,
985 'wpEditToken' => $wgUser->editToken( $img )
986 ),
987 array( 'known', 'noclasses' )
988 );
989 }
990 }
991 $row .= '</td>';
992
993 // Date/time and image link
994 if ( $file->getTimestamp() === $this->img->getTimestamp() ) {
995 $selected = "class='filehistory-selected'";
996 }
997 $row .= "<td $selected style='white-space: nowrap;'>";
998 if ( !$file->userCan( File::DELETED_FILE ) ) {
999 # Don't link to unviewable files
1000 $row .= '<span class="history-deleted">' . $wgLang->timeAndDate( $timestamp, true ) . '</span>';
1001 } elseif ( $file->isDeleted( File::DELETED_FILE ) ) {
1002 if ( $local ) {
1003 $this->preventClickjacking();
1004 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
1005 # Make a link to review the image
1006 $url = $this->skin->link(
1007 $revdel,
1008 $wgLang->timeAndDate( $timestamp, true ),
1009 array(),
1010 array(
1011 'target' => $this->title->getPrefixedText(),
1012 'file' => $img,
1013 'token' => $wgUser->editToken( $img )
1014 ),
1015 array( 'known', 'noclasses' )
1016 );
1017 } else {
1018 $url = $wgLang->timeAndDate( $timestamp, true );
1019 }
1020 $row .= '<span class="history-deleted">' . $url . '</span>';
1021 } else {
1022 $url = $iscur ? $this->current->getUrl() : $this->current->getArchiveUrl( $img );
1023 $row .= Xml::element( 'a', array( 'href' => $url ), $wgLang->timeAndDate( $timestamp, true ) );
1024 }
1025 $row .= "</td>";
1026
1027 // Thumbnail
1028 if ( $this->showThumb ) {
1029 $row .= '<td>' . $this->getThumbForLine( $file ) . '</td>';
1030 }
1031
1032 // Image dimensions + size
1033 $row .= '<td>';
1034 $row .= htmlspecialchars( $file->getDimensionsString() );
1035 $row .= ' <span style="white-space: nowrap;">(' . $this->skin->formatSize( $file->getSize() ) . ')</span>';
1036 $row .= '</td>';
1037
1038 // Uploading user
1039 $row .= '<td>';
1040 // Hide deleted usernames
1041 if ( $file->isDeleted( File::DELETED_USER ) ) {
1042 $row .= '<span class="history-deleted">' . wfMsgHtml( 'rev-deleted-user' ) . '</span>';
1043 } else {
1044 if ( $local ) {
1045 $row .= $this->skin->userLink( $user, $usertext ) . ' <span style="white-space: nowrap;">' .
1046 $this->skin->userToolLinks( $user, $usertext ) . '</span>';
1047 } else {
1048 $row .= htmlspecialchars( $usertext );
1049 }
1050 }
1051 $row .= '</td><td>';
1052
1053 // Don't show deleted descriptions
1054 if ( $file->isDeleted( File::DELETED_COMMENT ) ) {
1055 $row .= '<span class="history-deleted">' . wfMsgHtml( 'rev-deleted-comment' ) . '</span>';
1056 } else {
1057 $row .= $this->skin->commentBlock( $description, $this->title );
1058 }
1059 $row .= '</td>';
1060
1061 $rowClass = null;
1062 wfRunHooks( 'ImagePageFileHistoryLine', array( $this, $file, &$row, &$rowClass ) );
1063 $classAttr = $rowClass ? " class='$rowClass'" : '';
1064
1065 return "<tr{$classAttr}>{$row}</tr>\n";
1066 }
1067
1068 /**
1069 * @param $file File
1070 * @return string
1071 */
1072 protected function getThumbForLine( $file ) {
1073 global $wgLang;
1074
1075 if ( $file->allowInlineDisplay() && $file->userCan( File::DELETED_FILE ) && !$file->isDeleted( File::DELETED_FILE ) ) {
1076 $params = array(
1077 'width' => '120',
1078 'height' => '120',
1079 );
1080 $timestamp = wfTimestamp( TS_MW, $file->getTimestamp() );
1081
1082 $thumbnail = $file->transform( $params );
1083 $options = array(
1084 'alt' => wfMsg( 'filehist-thumbtext',
1085 $wgLang->timeAndDate( $timestamp, true ),
1086 $wgLang->date( $timestamp, true ),
1087 $wgLang->time( $timestamp, true ) ),
1088 'file-link' => true,
1089 );
1090
1091 if ( !$thumbnail ) {
1092 return wfMsgHtml( 'filehist-nothumb' );
1093 }
1094
1095 return $thumbnail->toHtml( $options );
1096 } else {
1097 return wfMsgHtml( 'filehist-nothumb' );
1098 }
1099 }
1100
1101 protected function preventClickjacking( $enable = true ) {
1102 $this->preventClickjacking = $enable;
1103 }
1104
1105 public function getPreventClickjacking() {
1106 return $this->preventClickjacking;
1107 }
1108 }
1109
1110 class ImageHistoryPseudoPager extends ReverseChronologicalPager {
1111 protected $preventClickjacking = false;
1112
1113 /**
1114 * @var File
1115 */
1116 protected $mImg;
1117
1118 /**
1119 * @var Title
1120 */
1121 protected $mTitle;
1122
1123 /**
1124 * @param ImagePage $imagePage
1125 */
1126 function __construct( $imagePage ) {
1127 parent::__construct();
1128 $this->mImagePage = $imagePage;
1129 $this->mTitle = clone ( $imagePage->getTitle() );
1130 $this->mTitle->setFragment( '#filehistory' );
1131 $this->mImg = null;
1132 $this->mHist = array();
1133 $this->mRange = array( 0, 0 ); // display range
1134 }
1135
1136 function getTitle() {
1137 return $this->mTitle;
1138 }
1139
1140 function getQueryInfo() {
1141 return false;
1142 }
1143
1144 function getIndexField() {
1145 return '';
1146 }
1147
1148 function formatRow( $row ) {
1149 return '';
1150 }
1151
1152 function getBody() {
1153 $s = '';
1154 $this->doQuery();
1155 if ( count( $this->mHist ) ) {
1156 $list = new ImageHistoryList( $this->mImagePage );
1157 # Generate prev/next links
1158 $navLink = $this->getNavigationBar();
1159 $s = $list->beginImageHistoryList( $navLink );
1160 // Skip rows there just for paging links
1161 for ( $i = $this->mRange[0]; $i <= $this->mRange[1]; $i++ ) {
1162 $file = $this->mHist[$i];
1163 $s .= $list->imageHistoryLine( !$file->isOld(), $file );
1164 }
1165 $s .= $list->endImageHistoryList( $navLink );
1166
1167 if ( $list->getPreventClickjacking() ) {
1168 $this->preventClickjacking();
1169 }
1170 }
1171 return $s;
1172 }
1173
1174 function doQuery() {
1175 if ( $this->mQueryDone ) {
1176 return;
1177 }
1178 $this->mImg = $this->mImagePage->getFile(); // ensure loading
1179 if ( !$this->mImg->exists() ) {
1180 return;
1181 }
1182 $queryLimit = $this->mLimit + 1; // limit plus extra row
1183 if ( $this->mIsBackwards ) {
1184 // Fetch the file history
1185 $this->mHist = $this->mImg->getHistory( $queryLimit, null, $this->mOffset, false );
1186 // The current rev may not meet the offset/limit
1187 $numRows = count( $this->mHist );
1188 if ( $numRows <= $this->mLimit && $this->mImg->getTimestamp() > $this->mOffset ) {
1189 $this->mHist = array_merge( array( $this->mImg ), $this->mHist );
1190 }
1191 } else {
1192 // The current rev may not meet the offset
1193 if ( !$this->mOffset || $this->mImg->getTimestamp() < $this->mOffset ) {
1194 $this->mHist[] = $this->mImg;
1195 }
1196 // Old image versions (fetch extra row for nav links)
1197 $oiLimit = count( $this->mHist ) ? $this->mLimit : $this->mLimit + 1;
1198 // Fetch the file history
1199 $this->mHist = array_merge( $this->mHist,
1200 $this->mImg->getHistory( $oiLimit, $this->mOffset, null, false ) );
1201 }
1202 $numRows = count( $this->mHist ); // Total number of query results
1203 if ( $numRows ) {
1204 # Index value of top item in the list
1205 $firstIndex = $this->mIsBackwards ?
1206 $this->mHist[$numRows - 1]->getTimestamp() : $this->mHist[0]->getTimestamp();
1207 # Discard the extra result row if there is one
1208 if ( $numRows > $this->mLimit && $numRows > 1 ) {
1209 if ( $this->mIsBackwards ) {
1210 # Index value of item past the index
1211 $this->mPastTheEndIndex = $this->mHist[0]->getTimestamp();
1212 # Index value of bottom item in the list
1213 $lastIndex = $this->mHist[1]->getTimestamp();
1214 # Display range
1215 $this->mRange = array( 1, $numRows - 1 );
1216 } else {
1217 # Index value of item past the index
1218 $this->mPastTheEndIndex = $this->mHist[$numRows - 1]->getTimestamp();
1219 # Index value of bottom item in the list
1220 $lastIndex = $this->mHist[$numRows - 2]->getTimestamp();
1221 # Display range
1222 $this->mRange = array( 0, $numRows - 2 );
1223 }
1224 } else {
1225 # Setting indexes to an empty string means that they will be
1226 # omitted if they would otherwise appear in URLs. It just so
1227 # happens that this is the right thing to do in the standard
1228 # UI, in all the relevant cases.
1229 $this->mPastTheEndIndex = '';
1230 # Index value of bottom item in the list
1231 $lastIndex = $this->mIsBackwards ?
1232 $this->mHist[0]->getTimestamp() : $this->mHist[$numRows - 1]->getTimestamp();
1233 # Display range
1234 $this->mRange = array( 0, $numRows - 1 );
1235 }
1236 } else {
1237 $firstIndex = '';
1238 $lastIndex = '';
1239 $this->mPastTheEndIndex = '';
1240 }
1241 if ( $this->mIsBackwards ) {
1242 $this->mIsFirst = ( $numRows < $queryLimit );
1243 $this->mIsLast = ( $this->mOffset == '' );
1244 $this->mLastShown = $firstIndex;
1245 $this->mFirstShown = $lastIndex;
1246 } else {
1247 $this->mIsFirst = ( $this->mOffset == '' );
1248 $this->mIsLast = ( $numRows < $queryLimit );
1249 $this->mLastShown = $lastIndex;
1250 $this->mFirstShown = $firstIndex;
1251 }
1252 $this->mQueryDone = true;
1253 }
1254
1255 protected function preventClickjacking( $enable = true ) {
1256 $this->preventClickjacking = $enable;
1257 }
1258
1259 public function getPreventClickjacking() {
1260 return $this->preventClickjacking;
1261 }
1262
1263 }