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