(bug 34289) user.options CSS loaded twice. Fixed by splitting off the CSS part of...
[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->doViewUpdates( $this->getContext()->getUser() );
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->doViewUpdates( $this->getContext()->getUser() );
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, $wgSend404Code;
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 if ( count( $otherSizes ) && $this->displayImg->getRepo()->canTransformVia404() ) {
335 $msgsmall .= ' ' .
336 Html::rawElement( 'span', array( 'class' => 'mw-filepage-other-resolutions' ),
337 wfMessage( 'show-big-image-other' )->rawParams( $wgLang->pipeList( $otherSizes ) )->
338 params( count( $otherSizes ) )->parse()
339 );
340 }
341 } elseif ( $width == 0 && $height == 0 ){
342 # Some sort of audio file that doesn't have dimensions
343 # Don't output a no hi res message for such a file
344 $msgsmall = '';
345 } else {
346 # Image is small enough to show full size on image page
347 $msgsmall = wfMessage( 'file-nohires' )->parse();
348 }
349
350 $params['width'] = $width;
351 $params['height'] = $height;
352 $thumbnail = $this->displayImg->transform( $params );
353
354 $showLink = true;
355 $anchorclose = Html::rawElement( 'div', array( 'class' => 'mw-filepage-resolutioninfo' ), $msgsmall );
356
357 $isMulti = $this->displayImg->isMultipage() && $this->displayImg->pageCount() > 1;
358 if ( $isMulti ) {
359 $wgOut->addHTML( '<table class="multipageimage"><tr><td>' );
360 }
361
362 if ( $thumbnail ) {
363 $options = array(
364 'alt' => $this->displayImg->getTitle()->getPrefixedText(),
365 'file-link' => true,
366 );
367 $wgOut->addHTML( '<div class="fullImageLink" id="file">' .
368 $thumbnail->toHtml( $options ) .
369 $anchorclose . "</div>\n" );
370 }
371
372 if ( $isMulti ) {
373 $count = $this->displayImg->pageCount();
374
375 if ( $page > 1 ) {
376 $label = $wgOut->parse( wfMsg( 'imgmultipageprev' ), false );
377 $link = Linker::link(
378 $this->getTitle(),
379 $label,
380 array(),
381 array( 'page' => $page - 1 ),
382 array( 'known', 'noclasses' )
383 );
384 $thumb1 = Linker::makeThumbLinkObj( $this->getTitle(), $this->displayImg, $link, $label, 'none',
385 array( 'page' => $page - 1 ) );
386 } else {
387 $thumb1 = '';
388 }
389
390 if ( $page < $count ) {
391 $label = wfMsg( 'imgmultipagenext' );
392 $link = Linker::link(
393 $this->getTitle(),
394 $label,
395 array(),
396 array( 'page' => $page + 1 ),
397 array( 'known', 'noclasses' )
398 );
399 $thumb2 = Linker::makeThumbLinkObj( $this->getTitle(), $this->displayImg, $link, $label, 'none',
400 array( 'page' => $page + 1 ) );
401 } else {
402 $thumb2 = '';
403 }
404
405 global $wgScript;
406
407 $formParams = array(
408 'name' => 'pageselector',
409 'action' => $wgScript,
410 'onchange' => 'document.pageselector.submit();',
411 );
412 $options = array();
413 for ( $i = 1; $i <= $count; $i++ ) {
414 $options[] = Xml::option( $wgLang->formatNum( $i ), $i, $i == $page );
415 }
416 $select = Xml::tags( 'select',
417 array( 'id' => 'pageselector', 'name' => 'page' ),
418 implode( "\n", $options ) );
419
420 $wgOut->addHTML(
421 '</td><td><div class="multipageimagenavbox">' .
422 Xml::openElement( 'form', $formParams ) .
423 Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() ) .
424 wfMsgExt( 'imgmultigoto', array( 'parseinline', 'replaceafter' ), $select ) .
425 Xml::submitButton( wfMsg( 'imgmultigo' ) ) .
426 Xml::closeElement( 'form' ) .
427 "<hr />$thumb1\n$thumb2<br style=\"clear: both\" /></div></td></tr></table>"
428 );
429 }
430 } else {
431 # if direct link is allowed but it's not a renderable image, show an icon.
432 if ( $this->displayImg->isSafeFile() ) {
433 $icon = $this->displayImg->iconThumb();
434
435 $wgOut->addHTML( '<div class="fullImageLink" id="file">' .
436 $icon->toHtml( array( 'file-link' => true ) ) .
437 "</div>\n" );
438 }
439
440 $showLink = true;
441 }
442
443 if ( $showLink ) {
444 $filename = wfEscapeWikiText( $this->displayImg->getName() );
445 $linktext = $filename;
446 if ( isset( $msgbig ) ) {
447 $linktext = wfEscapeWikiText( $msgbig );
448 }
449 $medialink = "[[Media:$filename|$linktext]]";
450
451 if ( !$this->displayImg->isSafeFile() ) {
452 $warning = wfMsgNoTrans( 'mediawarning' );
453 $wgOut->addWikiText( <<<EOT
454 <div class="fullMedia"><span class="dangerousLink">{$medialink}</span>$dirmark <span class="fileInfo">$longDesc</span></div>
455 <div class="mediaWarning">$warning</div>
456 EOT
457 );
458 } else {
459 $wgOut->addWikiText( <<<EOT
460 <div class="fullMedia">{$medialink}{$dirmark} <span class="fileInfo">$longDesc</span>
461 </div>
462 EOT
463 );
464 }
465 }
466
467 if ( !$this->displayImg->isLocal() ) {
468 $this->printSharedImageText();
469 }
470 } else {
471 # Image does not exist
472 if ( $wgEnableUploads && $wgUser->isAllowed( 'upload' ) ) {
473 // Only show an upload link if the user can upload
474 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
475 $nofile = array(
476 'filepage-nofile-link',
477 $uploadTitle->getFullURL( array( 'wpDestFile' => $this->mPage->getFile()->getName() ) )
478 );
479 } else {
480 $nofile = 'filepage-nofile';
481 }
482 // Note, if there is an image description page, but
483 // no image, then this setRobotPolicy is overriden
484 // by Article::View().
485 $wgOut->setRobotPolicy( 'noindex,nofollow' );
486 $wgOut->wrapWikiMsg( "<div id='mw-imagepage-nofile' class='plainlinks'>\n$1\n</div>", $nofile );
487 if ( !$this->getID() && $wgSend404Code ) {
488 // If there is no image, no shared image, and no description page,
489 // output a 404, to be consistent with articles.
490 $wgRequest->response()->header( 'HTTP/1.1 404 Not Found' );
491 }
492 }
493 $wgOut->setFileVersion( $this->displayImg );
494 }
495
496 /**
497 * Creates an thumbnail of specified size and returns an HTML link to it
498 * @param $params array Scaler parameters
499 * @param $width int
500 * @param $height int
501 * @return string
502 */
503 private function makeSizeLink( $params, $width, $height ) {
504 $params['width'] = $width;
505 $params['height'] = $height;
506 $thumbnail = $this->displayImg->transform( $params );
507 if ( $thumbnail && !$thumbnail->isError() ) {
508 return Html::rawElement( 'a', array(
509 'href' => $thumbnail->getUrl(),
510 'class' => 'mw-thumbnail-link'
511 ), wfMessage( 'show-big-image-size' )->numParams(
512 $thumbnail->getWidth(), $thumbnail->getHeight()
513 )->parse() );
514 } else {
515 return '';
516 }
517 }
518
519 /**
520 * Show a notice that the file is from a shared repository
521 */
522 protected function printSharedImageText() {
523 global $wgOut;
524
525 $this->loadFile();
526
527 $descUrl = $this->mPage->getFile()->getDescriptionUrl();
528 $descText = $this->mPage->getFile()->getDescriptionText();
529
530 /* Add canonical to head if there is no local page for this shared file */
531 if( $descUrl && $this->mPage->getID() == 0 ) {
532 $wgOut->addLink( array( 'rel' => 'canonical', 'href' => $descUrl ) );
533 }
534
535 $wrap = "<div class=\"sharedUploadNotice\">\n$1\n</div>\n";
536 $repo = $this->mPage->getFile()->getRepo()->getDisplayName();
537
538 if ( $descUrl && $descText && wfMsgNoTrans( 'sharedupload-desc-here' ) !== '-' ) {
539 $wgOut->wrapWikiMsg( $wrap, array( 'sharedupload-desc-here', $repo, $descUrl ) );
540 } elseif ( $descUrl && wfMsgNoTrans( 'sharedupload-desc-there' ) !== '-' ) {
541 $wgOut->wrapWikiMsg( $wrap, array( 'sharedupload-desc-there', $repo, $descUrl ) );
542 } else {
543 $wgOut->wrapWikiMsg( $wrap, array( 'sharedupload', $repo ), ''/*BACKCOMPAT*/ );
544 }
545
546 if ( $descText ) {
547 $this->mExtraDescription = $descText;
548 }
549 }
550
551 public function getUploadUrl() {
552 $this->loadFile();
553 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
554 return $uploadTitle->getFullURL( array(
555 'wpDestFile' => $this->mPage->getFile()->getName(),
556 'wpForReUpload' => 1
557 ) );
558 }
559
560 /**
561 * Print out the various links at the bottom of the image page, e.g. reupload,
562 * external editing (and instructions link) etc.
563 */
564 protected function uploadLinksBox() {
565 global $wgUser, $wgOut, $wgEnableUploads, $wgUseExternalEditor;
566
567 if ( !$wgEnableUploads ) {
568 return;
569 }
570
571 $this->loadFile();
572 if ( !$this->mPage->getFile()->isLocal() ) {
573 return;
574 }
575
576 $wgOut->addHTML( "<br /><ul>\n" );
577
578 # "Upload a new version of this file" link
579 if ( UploadBase::userCanReUpload( $wgUser, $this->mPage->getFile()->name ) ) {
580 $ulink = Linker::makeExternalLink( $this->getUploadUrl(), wfMsg( 'uploadnewversion-linktext' ) );
581 $wgOut->addHTML( "<li id=\"mw-imagepage-reupload-link\"><div class=\"plainlinks\">{$ulink}</div></li>\n" );
582 }
583
584 # External editing link
585 if ( $wgUseExternalEditor ) {
586 $elink = Linker::link(
587 $this->getTitle(),
588 wfMsgHtml( 'edit-externally' ),
589 array(),
590 array(
591 'action' => 'edit',
592 'externaledit' => 'true',
593 'mode' => 'file'
594 ),
595 array( 'known', 'noclasses' )
596 );
597 $wgOut->addHTML(
598 '<li id="mw-imagepage-edit-external">' . $elink . ' <small>' .
599 wfMsgExt( 'edit-externally-help', array( 'parseinline' ) ) .
600 "</small></li>\n"
601 );
602 }
603
604 $wgOut->addHTML( "</ul>\n" );
605 }
606
607 protected function closeShowImage() { } # For overloading
608
609 /**
610 * If the page we've just displayed is in the "Image" namespace,
611 * we follow it with an upload history of the image and its usage.
612 */
613 protected function imageHistory() {
614 global $wgOut;
615
616 $this->loadFile();
617 $pager = new ImageHistoryPseudoPager( $this );
618 $wgOut->addHTML( $pager->getBody() );
619 $wgOut->preventClickjacking( $pager->getPreventClickjacking() );
620
621 $this->mPage->getFile()->resetHistory(); // free db resources
622
623 # Exist check because we don't want to show this on pages where an image
624 # doesn't exist along with the noimage message, that would suck. -ævar
625 if ( $this->mPage->getFile()->exists() ) {
626 $this->uploadLinksBox();
627 }
628 }
629
630 /**
631 * @param $target
632 * @param $limit
633 * @return ResultWrapper
634 */
635 protected function queryImageLinks( $target, $limit ) {
636 $dbr = wfGetDB( DB_SLAVE );
637
638 return $dbr->select(
639 array( 'imagelinks', 'page' ),
640 array( 'page_namespace', 'page_title', 'page_is_redirect', 'il_to' ),
641 array( 'il_to' => $target, 'il_from = page_id' ),
642 __METHOD__,
643 array( 'LIMIT' => $limit + 1, 'ORDER BY' => 'il_from', )
644 );
645 }
646
647 protected function imageLinks() {
648 global $wgOut, $wgLang;
649
650 $limit = 100;
651
652 $res = $this->queryImageLinks( $this->getTitle()->getDbKey(), $limit + 1);
653 $rows = array();
654 $redirects = array();
655 foreach ( $res as $row ) {
656 if ( $row->page_is_redirect ) {
657 $redirects[$row->page_title] = array();
658 }
659 $rows[] = $row;
660 }
661 $count = count( $rows );
662
663 $hasMore = $count > $limit;
664 if ( !$hasMore && count( $redirects ) ) {
665 $res = $this->queryImageLinks( array_keys( $redirects ),
666 $limit - count( $rows ) + 1 );
667 foreach ( $res as $row ) {
668 $redirects[$row->il_to][] = $row;
669 $count++;
670 }
671 $hasMore = ( $res->numRows() + count( $rows ) ) > $limit;
672 }
673
674 if ( $count == 0 ) {
675 $wgOut->wrapWikiMsg(
676 Html::rawElement( 'div',
677 array( 'id' => 'mw-imagepage-nolinkstoimage' ), "\n$1\n" ),
678 'nolinkstoimage'
679 );
680 return;
681 }
682
683 $wgOut->addHTML( "<div id='mw-imagepage-section-linkstoimage'>\n" );
684 if ( !$hasMore ) {
685 $wgOut->addWikiMsg( 'linkstoimage', $count );
686 } else {
687 // More links than the limit. Add a link to [[Special:Whatlinkshere]]
688 $wgOut->addWikiMsg( 'linkstoimage-more',
689 $wgLang->formatNum( $limit ),
690 $this->getTitle()->getPrefixedDBkey()
691 );
692 }
693
694 $wgOut->addHTML(
695 Html::openElement( 'ul',
696 array( 'class' => 'mw-imagepage-linkstoimage' ) ) . "\n"
697 );
698 $count = 0;
699
700 // Sort the list by namespace:title
701 usort( $rows, array( $this, 'compare' ) );
702
703 // Create links for every element
704 $currentCount = 0;
705 foreach( $rows as $element ) {
706 $currentCount++;
707 if ( $currentCount > $limit ) {
708 break;
709 }
710
711 $link = Linker::linkKnown( Title::makeTitle( $element->page_namespace, $element->page_title ) );
712 if ( !isset( $redirects[$element->page_title] ) ) {
713 $liContents = $link;
714 } else {
715 $ul = "<ul class='mw-imagepage-redirectstofile'>\n";
716 foreach ( $redirects[$element->page_title] as $row ) {
717 $currentCount++;
718 if ( $currentCount > $limit ) {
719 break;
720 }
721
722 $link2 = Linker::linkKnown( Title::makeTitle( $row->page_namespace, $row->page_title ) );
723 $ul .= Html::rawElement(
724 'li',
725 array( 'id' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ),
726 $link2
727 ) . "\n";
728 }
729 $ul .= '</ul>';
730 $liContents = wfMessage( 'linkstoimage-redirect' )->rawParams(
731 $link, $ul )->parse();
732 }
733 $wgOut->addHTML( Html::rawElement(
734 'li',
735 array( 'id' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ),
736 $liContents
737 ) . "\n"
738 );
739
740 };
741 $wgOut->addHTML( Html::closeElement( 'ul' ) . "\n" );
742 $res->free();
743
744 // Add a links to [[Special:Whatlinkshere]]
745 if ( $count > $limit ) {
746 $wgOut->addWikiMsg( 'morelinkstoimage', $this->getTitle()->getPrefixedDBkey() );
747 }
748 $wgOut->addHTML( Html::closeElement( 'div' ) . "\n" );
749 }
750
751 protected function imageDupes() {
752 global $wgOut, $wgLang;
753
754 $this->loadFile();
755
756 $dupes = $this->mPage->getDuplicates();
757 if ( count( $dupes ) == 0 ) {
758 return;
759 }
760
761 $wgOut->addHTML( "<div id='mw-imagepage-section-duplicates'>\n" );
762 $wgOut->addWikiMsg( 'duplicatesoffile',
763 $wgLang->formatNum( count( $dupes ) ), $this->getTitle()->getDBkey()
764 );
765 $wgOut->addHTML( "<ul class='mw-imagepage-duplicates'>\n" );
766
767 /**
768 * @var $file File
769 */
770 foreach ( $dupes as $file ) {
771 $fromSrc = '';
772 if ( $file->isLocal() ) {
773 $link = Linker::link(
774 $file->getTitle(),
775 null,
776 array(),
777 array(),
778 array( 'known', 'noclasses' )
779 );
780 } else {
781 $link = Linker::makeExternalLink( $file->getDescriptionUrl(),
782 $file->getTitle()->getPrefixedText() );
783 $fromSrc = wfMsg( 'shared-repo-from', $file->getRepo()->getDisplayName() );
784 }
785 $wgOut->addHTML( "<li>{$link} {$fromSrc}</li>\n" );
786 }
787 $wgOut->addHTML( "</ul></div>\n" );
788 }
789
790 /**
791 * Delete the file, or an earlier version of it
792 */
793 public function delete() {
794 $file = $this->mPage->getFile();
795 if ( !$file->exists() || !$file->isLocal() || $file->getRedirected() ) {
796 // Standard article deletion
797 parent::delete();
798 return;
799 }
800
801 $deleter = new FileDeleteForm( $file );
802 $deleter->execute();
803 }
804
805 /**
806 * Display an error with a wikitext description
807 *
808 * @param $description String
809 */
810 function showError( $description ) {
811 global $wgOut;
812 $wgOut->setPageTitle( wfMessage( 'internalerror' ) );
813 $wgOut->setRobotPolicy( 'noindex,nofollow' );
814 $wgOut->setArticleRelated( false );
815 $wgOut->enableClientCache( false );
816 $wgOut->addWikiText( $description );
817 }
818
819 /**
820 * Callback for usort() to do link sorts by (namespace, title)
821 * Function copied from Title::compare()
822 *
823 * @param $a object page to compare with
824 * @param $b object page to compare with
825 * @return Integer: result of string comparison, or namespace comparison
826 */
827 protected function compare( $a, $b ) {
828 if ( $a->page_namespace == $b->page_namespace ) {
829 return strcmp( $a->page_title, $b->page_title );
830 } else {
831 return $a->page_namespace - $b->page_namespace;
832 }
833 }
834 }
835
836 /**
837 * Builds the image revision log shown on image pages
838 *
839 * @ingroup Media
840 */
841 class ImageHistoryList {
842
843 /**
844 * @var Title
845 */
846 protected $title;
847
848 /**
849 * @var File
850 */
851 protected $img;
852
853 /**
854 * @var ImagePage
855 */
856 protected $imagePage;
857
858 /**
859 * @var File
860 */
861 protected $current;
862
863 protected $repo, $showThumb;
864 protected $preventClickjacking = false;
865
866 /**
867 * @param ImagePage $imagePage
868 */
869 public function __construct( $imagePage ) {
870 global $wgShowArchiveThumbnails;
871 $this->current = $imagePage->getFile();
872 $this->img = $imagePage->getDisplayedFile();
873 $this->title = $imagePage->getTitle();
874 $this->imagePage = $imagePage;
875 $this->showThumb = $wgShowArchiveThumbnails && $this->img->canRender();
876 }
877
878 /**
879 * @return ImagePage
880 */
881 public function getImagePage() {
882 return $this->imagePage;
883 }
884
885 /**
886 * @return File
887 */
888 public function getFile() {
889 return $this->img;
890 }
891
892 /**
893 * @param $navLinks string
894 * @return string
895 */
896 public function beginImageHistoryList( $navLinks = '' ) {
897 global $wgOut, $wgUser;
898 return Xml::element( 'h2', array( 'id' => 'filehistory' ), wfMsg( 'filehist' ) ) . "\n"
899 . "<div id=\"mw-imagepage-section-filehistory\">\n"
900 . $wgOut->parse( wfMsgNoTrans( 'filehist-help' ) )
901 . $navLinks . "\n"
902 . Xml::openElement( 'table', array( 'class' => 'wikitable filehistory' ) ) . "\n"
903 . '<tr><td></td>'
904 . ( $this->current->isLocal() && ( $wgUser->isAllowedAny( 'delete', 'deletedhistory' ) ) ? '<td></td>' : '' )
905 . '<th>' . wfMsgHtml( 'filehist-datetime' ) . '</th>'
906 . ( $this->showThumb ? '<th>' . wfMsgHtml( 'filehist-thumb' ) . '</th>' : '' )
907 . '<th>' . wfMsgHtml( 'filehist-dimensions' ) . '</th>'
908 . '<th>' . wfMsgHtml( 'filehist-user' ) . '</th>'
909 . '<th>' . wfMsgHtml( 'filehist-comment' ) . '</th>'
910 . "</tr>\n";
911 }
912
913 /**
914 * @param $navLinks string
915 * @return string
916 */
917 public function endImageHistoryList( $navLinks = '' ) {
918 return "</table>\n$navLinks\n</div>\n";
919 }
920
921 /**
922 * @param $iscur
923 * @param $file File
924 * @return string
925 */
926 public function imageHistoryLine( $iscur, $file ) {
927 global $wgUser, $wgLang, $wgContLang;
928
929 $timestamp = wfTimestamp( TS_MW, $file->getTimestamp() );
930 $img = $iscur ? $file->getName() : $file->getArchiveName();
931 $user = $file->getUser( 'id' );
932 $usertext = $file->getUser( 'text' );
933 $description = $file->getDescription();
934
935 $local = $this->current->isLocal();
936 $row = $selected = '';
937
938 // Deletion link
939 if ( $local && ( $wgUser->isAllowedAny( 'delete', 'deletedhistory' ) ) ) {
940 $row .= '<td>';
941 # Link to remove from history
942 if ( $wgUser->isAllowed( 'delete' ) ) {
943 $q = array( 'action' => 'delete' );
944 if ( !$iscur ) {
945 $q['oldimage'] = $img;
946 }
947 $row .= Linker::link(
948 $this->title,
949 wfMsgHtml( $iscur ? 'filehist-deleteall' : 'filehist-deleteone' ),
950 array(), $q, array( 'known' )
951 );
952 }
953 # Link to hide content. Don't show useless link to people who cannot hide revisions.
954 $canHide = $wgUser->isAllowed( 'deleterevision' );
955 if ( $canHide || ( $wgUser->isAllowed( 'deletedhistory' ) && $file->getVisibility() ) ) {
956 if ( $wgUser->isAllowed( 'delete' ) ) {
957 $row .= '<br />';
958 }
959 // If file is top revision or locked from this user, don't link
960 if ( $iscur || !$file->userCan( File::DELETED_RESTRICTED ) ) {
961 $del = Linker::revDeleteLinkDisabled( $canHide );
962 } else {
963 list( $ts, $name ) = explode( '!', $img, 2 );
964 $query = array(
965 'type' => 'oldimage',
966 'target' => $this->title->getPrefixedText(),
967 'ids' => $ts,
968 );
969 $del = Linker::revDeleteLink( $query,
970 $file->isDeleted( File::DELETED_RESTRICTED ), $canHide );
971 }
972 $row .= $del;
973 }
974 $row .= '</td>';
975 }
976
977 // Reversion link/current indicator
978 $row .= '<td>';
979 if ( $iscur ) {
980 $row .= wfMsgHtml( 'filehist-current' );
981 } elseif ( $local && $wgUser->isLoggedIn() && $this->title->userCan( 'edit' ) ) {
982 if ( $file->isDeleted( File::DELETED_FILE ) ) {
983 $row .= wfMsgHtml( 'filehist-revert' );
984 } else {
985 $row .= Linker::link(
986 $this->title,
987 wfMsgHtml( 'filehist-revert' ),
988 array(),
989 array(
990 'action' => 'revert',
991 'oldimage' => $img,
992 'wpEditToken' => $wgUser->getEditToken( $img )
993 ),
994 array( 'known', 'noclasses' )
995 );
996 }
997 }
998 $row .= '</td>';
999
1000 // Date/time and image link
1001 if ( $file->getTimestamp() === $this->img->getTimestamp() ) {
1002 $selected = "class='filehistory-selected'";
1003 }
1004 $row .= "<td $selected style='white-space: nowrap;'>";
1005 if ( !$file->userCan( File::DELETED_FILE ) ) {
1006 # Don't link to unviewable files
1007 $row .= '<span class="history-deleted">' . $wgLang->timeanddate( $timestamp, true ) . '</span>';
1008 } elseif ( $file->isDeleted( File::DELETED_FILE ) ) {
1009 if ( $local ) {
1010 $this->preventClickjacking();
1011 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
1012 # Make a link to review the image
1013 $url = Linker::link(
1014 $revdel,
1015 $wgLang->timeanddate( $timestamp, true ),
1016 array(),
1017 array(
1018 'target' => $this->title->getPrefixedText(),
1019 'file' => $img,
1020 'token' => $wgUser->getEditToken( $img )
1021 ),
1022 array( 'known', 'noclasses' )
1023 );
1024 } else {
1025 $url = $wgLang->timeanddate( $timestamp, true );
1026 }
1027 $row .= '<span class="history-deleted">' . $url . '</span>';
1028 } else {
1029 $url = $iscur ? $this->current->getUrl() : $this->current->getArchiveUrl( $img );
1030 $row .= Xml::element( 'a', array( 'href' => $url ), $wgLang->timeanddate( $timestamp, true ) );
1031 }
1032 $row .= "</td>";
1033
1034 // Thumbnail
1035 if ( $this->showThumb ) {
1036 $row .= '<td>' . $this->getThumbForLine( $file ) . '</td>';
1037 }
1038
1039 // Image dimensions + size
1040 $row .= '<td>';
1041 $row .= htmlspecialchars( $file->getDimensionsString() );
1042 $row .= ' <span style="white-space: nowrap;">(' . Linker::formatSize( $file->getSize() ) . ')</span>';
1043 $row .= '</td>';
1044
1045 // Uploading user
1046 $row .= '<td>';
1047 // Hide deleted usernames
1048 if ( $file->isDeleted( File::DELETED_USER ) ) {
1049 $row .= '<span class="history-deleted">' . wfMsgHtml( 'rev-deleted-user' ) . '</span>';
1050 } else {
1051 if ( $local ) {
1052 $row .= Linker::userLink( $user, $usertext ) . ' <span style="white-space: nowrap;">' .
1053 Linker::userToolLinks( $user, $usertext ) . '</span>';
1054 } else {
1055 $row .= htmlspecialchars( $usertext );
1056 }
1057 }
1058 $row .= '</td>';
1059
1060 // Don't show deleted descriptions
1061 if ( $file->isDeleted( File::DELETED_COMMENT ) ) {
1062 $row .= '<td><span class="history-deleted">' . wfMsgHtml( 'rev-deleted-comment' ) . '</span></td>';
1063 } else {
1064 $row .= '<td dir="' . $wgContLang->getDir() . '">' . Linker::formatComment( $description, $this->title ) . '</td>';
1065 }
1066
1067 $rowClass = null;
1068 wfRunHooks( 'ImagePageFileHistoryLine', array( $this, $file, &$row, &$rowClass ) );
1069 $classAttr = $rowClass ? " class='$rowClass'" : '';
1070
1071 return "<tr{$classAttr}>{$row}</tr>\n";
1072 }
1073
1074 /**
1075 * @param $file File
1076 * @return string
1077 */
1078 protected function getThumbForLine( $file ) {
1079 global $wgLang;
1080
1081 if ( $file->allowInlineDisplay() && $file->userCan( File::DELETED_FILE ) && !$file->isDeleted( File::DELETED_FILE ) ) {
1082 $params = array(
1083 'width' => '120',
1084 'height' => '120',
1085 );
1086 $timestamp = wfTimestamp( TS_MW, $file->getTimestamp() );
1087
1088 $thumbnail = $file->transform( $params );
1089 $options = array(
1090 'alt' => wfMsg( 'filehist-thumbtext',
1091 $wgLang->timeanddate( $timestamp, true ),
1092 $wgLang->date( $timestamp, true ),
1093 $wgLang->time( $timestamp, true ) ),
1094 'file-link' => true,
1095 );
1096
1097 if ( !$thumbnail ) {
1098 return wfMsgHtml( 'filehist-nothumb' );
1099 }
1100
1101 return $thumbnail->toHtml( $options );
1102 } else {
1103 return wfMsgHtml( 'filehist-nothumb' );
1104 }
1105 }
1106
1107 /**
1108 * @param $enable bool
1109 */
1110 protected function preventClickjacking( $enable = true ) {
1111 $this->preventClickjacking = $enable;
1112 }
1113
1114 /**
1115 * @return bool
1116 */
1117 public function getPreventClickjacking() {
1118 return $this->preventClickjacking;
1119 }
1120 }
1121
1122 class ImageHistoryPseudoPager extends ReverseChronologicalPager {
1123 protected $preventClickjacking = false;
1124
1125 /**
1126 * @var File
1127 */
1128 protected $mImg;
1129
1130 /**
1131 * @var Title
1132 */
1133 protected $mTitle;
1134
1135 /**
1136 * @param ImagePage $imagePage
1137 */
1138 function __construct( $imagePage ) {
1139 parent::__construct();
1140 $this->mImagePage = $imagePage;
1141 $this->mTitle = clone ( $imagePage->getTitle() );
1142 $this->mTitle->setFragment( '#filehistory' );
1143 $this->mImg = null;
1144 $this->mHist = array();
1145 $this->mRange = array( 0, 0 ); // display range
1146 }
1147
1148 /**
1149 * @return Title
1150 */
1151 function getTitle() {
1152 return $this->mTitle;
1153 }
1154
1155 function getQueryInfo() {
1156 return false;
1157 }
1158
1159 /**
1160 * @return string
1161 */
1162 function getIndexField() {
1163 return '';
1164 }
1165
1166 /**
1167 * @return string
1168 */
1169 function formatRow( $row ) {
1170 return '';
1171 }
1172
1173 /**
1174 * @return string
1175 */
1176 function getBody() {
1177 $s = '';
1178 $this->doQuery();
1179 if ( count( $this->mHist ) ) {
1180 $list = new ImageHistoryList( $this->mImagePage );
1181 # Generate prev/next links
1182 $navLink = $this->getNavigationBar();
1183 $s = $list->beginImageHistoryList( $navLink );
1184 // Skip rows there just for paging links
1185 for ( $i = $this->mRange[0]; $i <= $this->mRange[1]; $i++ ) {
1186 $file = $this->mHist[$i];
1187 $s .= $list->imageHistoryLine( !$file->isOld(), $file );
1188 }
1189 $s .= $list->endImageHistoryList( $navLink );
1190
1191 if ( $list->getPreventClickjacking() ) {
1192 $this->preventClickjacking();
1193 }
1194 }
1195 return $s;
1196 }
1197
1198 function doQuery() {
1199 if ( $this->mQueryDone ) {
1200 return;
1201 }
1202 $this->mImg = $this->mImagePage->getFile(); // ensure loading
1203 if ( !$this->mImg->exists() ) {
1204 return;
1205 }
1206 $queryLimit = $this->mLimit + 1; // limit plus extra row
1207 if ( $this->mIsBackwards ) {
1208 // Fetch the file history
1209 $this->mHist = $this->mImg->getHistory( $queryLimit, null, $this->mOffset, false );
1210 // The current rev may not meet the offset/limit
1211 $numRows = count( $this->mHist );
1212 if ( $numRows <= $this->mLimit && $this->mImg->getTimestamp() > $this->mOffset ) {
1213 $this->mHist = array_merge( array( $this->mImg ), $this->mHist );
1214 }
1215 } else {
1216 // The current rev may not meet the offset
1217 if ( !$this->mOffset || $this->mImg->getTimestamp() < $this->mOffset ) {
1218 $this->mHist[] = $this->mImg;
1219 }
1220 // Old image versions (fetch extra row for nav links)
1221 $oiLimit = count( $this->mHist ) ? $this->mLimit : $this->mLimit + 1;
1222 // Fetch the file history
1223 $this->mHist = array_merge( $this->mHist,
1224 $this->mImg->getHistory( $oiLimit, $this->mOffset, null, false ) );
1225 }
1226 $numRows = count( $this->mHist ); // Total number of query results
1227 if ( $numRows ) {
1228 # Index value of top item in the list
1229 $firstIndex = $this->mIsBackwards ?
1230 $this->mHist[$numRows - 1]->getTimestamp() : $this->mHist[0]->getTimestamp();
1231 # Discard the extra result row if there is one
1232 if ( $numRows > $this->mLimit && $numRows > 1 ) {
1233 if ( $this->mIsBackwards ) {
1234 # Index value of item past the index
1235 $this->mPastTheEndIndex = $this->mHist[0]->getTimestamp();
1236 # Index value of bottom item in the list
1237 $lastIndex = $this->mHist[1]->getTimestamp();
1238 # Display range
1239 $this->mRange = array( 1, $numRows - 1 );
1240 } else {
1241 # Index value of item past the index
1242 $this->mPastTheEndIndex = $this->mHist[$numRows - 1]->getTimestamp();
1243 # Index value of bottom item in the list
1244 $lastIndex = $this->mHist[$numRows - 2]->getTimestamp();
1245 # Display range
1246 $this->mRange = array( 0, $numRows - 2 );
1247 }
1248 } else {
1249 # Setting indexes to an empty string means that they will be
1250 # omitted if they would otherwise appear in URLs. It just so
1251 # happens that this is the right thing to do in the standard
1252 # UI, in all the relevant cases.
1253 $this->mPastTheEndIndex = '';
1254 # Index value of bottom item in the list
1255 $lastIndex = $this->mIsBackwards ?
1256 $this->mHist[0]->getTimestamp() : $this->mHist[$numRows - 1]->getTimestamp();
1257 # Display range
1258 $this->mRange = array( 0, $numRows - 1 );
1259 }
1260 } else {
1261 $firstIndex = '';
1262 $lastIndex = '';
1263 $this->mPastTheEndIndex = '';
1264 }
1265 if ( $this->mIsBackwards ) {
1266 $this->mIsFirst = ( $numRows < $queryLimit );
1267 $this->mIsLast = ( $this->mOffset == '' );
1268 $this->mLastShown = $firstIndex;
1269 $this->mFirstShown = $lastIndex;
1270 } else {
1271 $this->mIsFirst = ( $this->mOffset == '' );
1272 $this->mIsLast = ( $numRows < $queryLimit );
1273 $this->mLastShown = $lastIndex;
1274 $this->mFirstShown = $firstIndex;
1275 }
1276 $this->mQueryDone = true;
1277 }
1278
1279 /**
1280 * @param $enable bool
1281 */
1282 protected function preventClickjacking( $enable = true ) {
1283 $this->preventClickjacking = $enable;
1284 }
1285
1286 /**
1287 * @return bool
1288 */
1289 public function getPreventClickjacking() {
1290 return $this->preventClickjacking;
1291 }
1292
1293 }