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