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