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