More documentation
[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' )->
336 rawParams( $wgLang->pipeList( $otherSizes ), count( $otherSizes ) )->parse()
337 );
338 } else {
339 # Image is small enough to show full size on image page
340 $msgsmall = wfMessage( 'file-nohires' )->parse();
341 }
342
343 $params['width'] = $width;
344 $params['height'] = $height;
345 $thumbnail = $this->displayImg->transform( $params );
346
347 $showLink = true;
348 $anchorclose = Html::rawElement( 'div', array( 'class' => 'mw-filepage-resolutioninfo' ), $msgsmall );
349
350 $isMulti = $this->displayImg->isMultipage() && $this->displayImg->pageCount() > 1;
351 if ( $isMulti ) {
352 $wgOut->addHTML( '<table class="multipageimage"><tr><td>' );
353 }
354
355 if ( $thumbnail ) {
356 $options = array(
357 'alt' => $this->displayImg->getTitle()->getPrefixedText(),
358 'file-link' => true,
359 );
360 $wgOut->addHTML( '<div class="fullImageLink" id="file">' .
361 $thumbnail->toHtml( $options ) .
362 $anchorclose . "</div>\n" );
363 }
364
365 if ( $isMulti ) {
366 $count = $this->displayImg->pageCount();
367
368 if ( $page > 1 ) {
369 $label = $wgOut->parse( wfMsg( 'imgmultipageprev' ), false );
370 $link = Linker::link(
371 $this->getTitle(),
372 $label,
373 array(),
374 array( 'page' => $page - 1 ),
375 array( 'known', 'noclasses' )
376 );
377 $thumb1 = Linker::makeThumbLinkObj( $this->getTitle(), $this->displayImg, $link, $label, 'none',
378 array( 'page' => $page - 1 ) );
379 } else {
380 $thumb1 = '';
381 }
382
383 if ( $page < $count ) {
384 $label = wfMsg( 'imgmultipagenext' );
385 $link = Linker::link(
386 $this->getTitle(),
387 $label,
388 array(),
389 array( 'page' => $page + 1 ),
390 array( 'known', 'noclasses' )
391 );
392 $thumb2 = Linker::makeThumbLinkObj( $this->getTitle(), $this->displayImg, $link, $label, 'none',
393 array( 'page' => $page + 1 ) );
394 } else {
395 $thumb2 = '';
396 }
397
398 global $wgScript;
399
400 $formParams = array(
401 'name' => 'pageselector',
402 'action' => $wgScript,
403 'onchange' => 'document.pageselector.submit();',
404 );
405 $options = array();
406 for ( $i = 1; $i <= $count; $i++ ) {
407 $options[] = Xml::option( $wgLang->formatNum( $i ), $i, $i == $page );
408 }
409 $select = Xml::tags( 'select',
410 array( 'id' => 'pageselector', 'name' => 'page' ),
411 implode( "\n", $options ) );
412
413 $wgOut->addHTML(
414 '</td><td><div class="multipageimagenavbox">' .
415 Xml::openElement( 'form', $formParams ) .
416 Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() ) .
417 wfMsgExt( 'imgmultigoto', array( 'parseinline', 'replaceafter' ), $select ) .
418 Xml::submitButton( wfMsg( 'imgmultigo' ) ) .
419 Xml::closeElement( 'form' ) .
420 "<hr />$thumb1\n$thumb2<br clear=\"all\" /></div></td></tr></table>"
421 );
422 }
423 } else {
424 # if direct link is allowed but it's not a renderable image, show an icon.
425 if ( $this->displayImg->isSafeFile() ) {
426 $icon = $this->displayImg->iconThumb();
427
428 $wgOut->addHTML( '<div class="fullImageLink" id="file">' .
429 $icon->toHtml( array( 'file-link' => true ) ) .
430 "</div>\n" );
431 }
432
433 $showLink = true;
434 }
435
436 if ( $showLink ) {
437 $filename = wfEscapeWikiText( $this->displayImg->getName() );
438 $linktext = $filename;
439 if ( isset( $msgbig ) ) {
440 $linktext = wfEscapeWikiText( $msgbig );
441 }
442 $medialink = "[[Media:$filename|$linktext]]";
443
444 if ( !$this->displayImg->isSafeFile() ) {
445 $warning = wfMsgNoTrans( 'mediawarning' );
446 $wgOut->addWikiText( <<<EOT
447 <div class="fullMedia"><span class="dangerousLink">{$medialink}</span>$dirmark <span class="fileInfo">$longDesc</span></div>
448 <div class="mediaWarning">$warning</div>
449 EOT
450 );
451 } else {
452 $wgOut->addWikiText( <<<EOT
453 <div class="fullMedia">{$medialink}{$dirmark} <span class="fileInfo">$longDesc</span>
454 </div>
455 EOT
456 );
457 }
458 }
459
460 if ( !$this->displayImg->isLocal() ) {
461 $this->printSharedImageText();
462 }
463 } else {
464 # Image does not exist
465 if ( $wgEnableUploads && $wgUser->isAllowed( 'upload' ) ) {
466 // Only show an upload link if the user can upload
467 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
468 $nofile = array(
469 'filepage-nofile-link',
470 $uploadTitle->getFullURL( array( 'wpDestFile' => $this->mPage->getFile()->getName() ) )
471 );
472 } else {
473 $nofile = 'filepage-nofile';
474 }
475 // Note, if there is an image description page, but
476 // no image, then this setRobotPolicy is overriden
477 // by Article::View().
478 $wgOut->setRobotPolicy( 'noindex,nofollow' );
479 $wgOut->wrapWikiMsg( "<div id='mw-imagepage-nofile' class='plainlinks'>\n$1\n</div>", $nofile );
480 if ( !$this->getID() ) {
481 // If there is no image, no shared image, and no description page,
482 // output a 404, to be consistent with articles.
483 $wgRequest->response()->header( 'HTTP/1.1 404 Not Found' );
484 }
485 }
486 $wgOut->setFileVersion( $this->displayImg );
487 }
488
489 /**
490 * Creates an thumbnail of specified size and returns an HTML link to it
491 * @param $params array Scaler parameters
492 * @param $width int
493 * @param $height int
494 * @return string
495 */
496 private function makeSizeLink( $params, $width, $height ) {
497 $params['width'] = $width;
498 $params['height'] = $height;
499 $thumbnail = $this->displayImg->transform( $params );
500 if ( $thumbnail && !$thumbnail->isError() ) {
501 return Html::rawElement( 'a', array(
502 'href' => $thumbnail->getUrl(),
503 'class' => 'mw-thumbnail-link'
504 ), wfMessage( 'show-big-image-size' )->numParams(
505 $thumbnail->getWidth(), $thumbnail->getHeight()
506 )->parse() );
507 } else {
508 return '';
509 }
510 }
511
512 /**
513 * Show a notice that the file is from a shared repository
514 */
515 protected function printSharedImageText() {
516 global $wgOut;
517
518 $this->loadFile();
519
520 $descUrl = $this->mPage->getFile()->getDescriptionUrl();
521 $descText = $this->mPage->getFile()->getDescriptionText();
522
523 /* Add canonical to head if there is no local page for this shared file */
524 if( $descUrl && $this->mPage->getID() == 0 ) {
525 $wgOut->addLink( array( 'rel' => 'canonical', 'href' => $descUrl ) );
526 }
527
528 $wrap = "<div class=\"sharedUploadNotice\">\n$1\n</div>\n";
529 $repo = $this->mPage->getFile()->getRepo()->getDisplayName();
530
531 if ( $descUrl && $descText && wfMsgNoTrans( 'sharedupload-desc-here' ) !== '-' ) {
532 $wgOut->wrapWikiMsg( $wrap, array( 'sharedupload-desc-here', $repo, $descUrl ) );
533 } elseif ( $descUrl && wfMsgNoTrans( 'sharedupload-desc-there' ) !== '-' ) {
534 $wgOut->wrapWikiMsg( $wrap, array( 'sharedupload-desc-there', $repo, $descUrl ) );
535 } else {
536 $wgOut->wrapWikiMsg( $wrap, array( 'sharedupload', $repo ), ''/*BACKCOMPAT*/ );
537 }
538
539 if ( $descText ) {
540 $this->mExtraDescription = $descText;
541 }
542 }
543
544 public function getUploadUrl() {
545 $this->loadFile();
546 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
547 return $uploadTitle->getFullURL( array(
548 'wpDestFile' => $this->mPage->getFile()->getName(),
549 'wpForReUpload' => 1
550 ) );
551 }
552
553 /**
554 * Print out the various links at the bottom of the image page, e.g. reupload,
555 * external editing (and instructions link) etc.
556 */
557 protected function uploadLinksBox() {
558 global $wgUser, $wgOut, $wgEnableUploads, $wgUseExternalEditor;
559
560 if ( !$wgEnableUploads ) {
561 return;
562 }
563
564 $this->loadFile();
565 if ( !$this->mPage->getFile()->isLocal() ) {
566 return;
567 }
568
569 $wgOut->addHTML( "<br /><ul>\n" );
570
571 # "Upload a new version of this file" link
572 if ( UploadBase::userCanReUpload( $wgUser, $this->mPage->getFile()->name ) ) {
573 $ulink = Linker::makeExternalLink( $this->getUploadUrl(), wfMsg( 'uploadnewversion-linktext' ) );
574 $wgOut->addHTML( "<li id=\"mw-imagepage-reupload-link\"><div class=\"plainlinks\">{$ulink}</div></li>\n" );
575 }
576
577 # External editing link
578 if ( $wgUseExternalEditor ) {
579 $elink = Linker::link(
580 $this->getTitle(),
581 wfMsgHtml( 'edit-externally' ),
582 array(),
583 array(
584 'action' => 'edit',
585 'externaledit' => 'true',
586 'mode' => 'file'
587 ),
588 array( 'known', 'noclasses' )
589 );
590 $wgOut->addHTML(
591 '<li id="mw-imagepage-edit-external">' . $elink . ' <small>' .
592 wfMsgExt( 'edit-externally-help', array( 'parseinline' ) ) .
593 "</small></li>\n"
594 );
595 }
596
597 $wgOut->addHTML( "</ul>\n" );
598 }
599
600 protected function closeShowImage() { } # For overloading
601
602 /**
603 * If the page we've just displayed is in the "Image" namespace,
604 * we follow it with an upload history of the image and its usage.
605 */
606 protected function imageHistory() {
607 global $wgOut;
608
609 $this->loadFile();
610 $pager = new ImageHistoryPseudoPager( $this );
611 $wgOut->addHTML( $pager->getBody() );
612 $wgOut->preventClickjacking( $pager->getPreventClickjacking() );
613
614 $this->mPage->getFile()->resetHistory(); // free db resources
615
616 # Exist check because we don't want to show this on pages where an image
617 # doesn't exist along with the noimage message, that would suck. -ævar
618 if ( $this->mPage->getFile()->exists() ) {
619 $this->uploadLinksBox();
620 }
621 }
622
623 /**
624 * @param $target
625 * @param $limit
626 * @return ResultWrapper
627 */
628 protected function queryImageLinks( $target, $limit ) {
629 $dbr = wfGetDB( DB_SLAVE );
630
631 return $dbr->select(
632 array( 'imagelinks', 'page' ),
633 array( 'page_namespace', 'page_title', 'page_is_redirect', 'il_to' ),
634 array( 'il_to' => $target, 'il_from = page_id' ),
635 __METHOD__,
636 array( 'LIMIT' => $limit + 1, 'ORDER BY' => 'il_from', )
637 );
638 }
639
640 protected function imageLinks() {
641 global $wgOut, $wgLang;
642
643 $limit = 100;
644
645 $res = $this->queryImageLinks( $this->getTitle()->getDbKey(), $limit + 1);
646 $rows = array();
647 $redirects = array();
648 foreach ( $res as $row ) {
649 if ( $row->page_is_redirect ) {
650 $redirects[$row->page_title] = array();
651 }
652 $rows[] = $row;
653 }
654 $count = count( $rows );
655
656 $hasMore = $count > $limit;
657 if ( !$hasMore && count( $redirects ) ) {
658 $res = $this->queryImageLinks( array_keys( $redirects ),
659 $limit - count( $rows ) + 1 );
660 foreach ( $res as $row ) {
661 $redirects[$row->il_to][] = $row;
662 $count++;
663 }
664 $hasMore = ( $res->numRows() + count( $rows ) ) > $limit;
665 }
666
667 if ( $count == 0 ) {
668 $wgOut->wrapWikiMsg(
669 Html::rawElement( 'div',
670 array( 'id' => 'mw-imagepage-nolinkstoimage' ), "\n$1\n" ),
671 'nolinkstoimage'
672 );
673 return;
674 }
675
676 $wgOut->addHTML( "<div id='mw-imagepage-section-linkstoimage'>\n" );
677 if ( !$hasMore ) {
678 $wgOut->addWikiMsg( 'linkstoimage', $count );
679 } else {
680 // More links than the limit. Add a link to [[Special:Whatlinkshere]]
681 $wgOut->addWikiMsg( 'linkstoimage-more',
682 $wgLang->formatNum( $limit ),
683 $this->getTitle()->getPrefixedDBkey()
684 );
685 }
686
687 $wgOut->addHTML(
688 Html::openElement( 'ul',
689 array( 'class' => 'mw-imagepage-linkstoimage' ) ) . "\n"
690 );
691 $count = 0;
692
693 // Sort the list by namespace:title
694 usort( $rows, array( $this, 'compare' ) );
695
696 // Create links for every element
697 $currentCount = 0;
698 foreach( $rows as $element ) {
699 $currentCount++;
700 if ( $currentCount > $limit ) {
701 break;
702 }
703
704 $link = Linker::linkKnown( Title::makeTitle( $element->page_namespace, $element->page_title ) );
705 if ( !isset( $redirects[$element->page_title] ) ) {
706 $liContents = $link;
707 } else {
708 $ul = "<ul class='mw-imagepage-redirectstofile'>\n";
709 foreach ( $redirects[$element->page_title] as $row ) {
710 $currentCount++;
711 if ( $currentCount > $limit ) {
712 break;
713 }
714
715 $link2 = Linker::linkKnown( Title::makeTitle( $row->page_namespace, $row->page_title ) );
716 $ul .= Html::rawElement(
717 'li',
718 array( 'id' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ),
719 $link2
720 ) . "\n";
721 }
722 $ul .= '</ul>';
723 $liContents = wfMessage( 'linkstoimage-redirect' )->rawParams(
724 $link, $ul )->parse();
725 }
726 $wgOut->addHTML( Html::rawElement(
727 'li',
728 array( 'id' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ),
729 $liContents
730 ) . "\n"
731 );
732
733 };
734 $wgOut->addHTML( Html::closeElement( 'ul' ) . "\n" );
735 $res->free();
736
737 // Add a links to [[Special:Whatlinkshere]]
738 if ( $count > $limit ) {
739 $wgOut->addWikiMsg( 'morelinkstoimage', $this->getTitle()->getPrefixedDBkey() );
740 }
741 $wgOut->addHTML( Html::closeElement( 'div' ) . "\n" );
742 }
743
744 protected function imageDupes() {
745 global $wgOut, $wgLang;
746
747 $this->loadFile();
748
749 $dupes = $this->mPage->getDuplicates();
750 if ( count( $dupes ) == 0 ) {
751 return;
752 }
753
754 $wgOut->addHTML( "<div id='mw-imagepage-section-duplicates'>\n" );
755 $wgOut->addWikiMsg( 'duplicatesoffile',
756 $wgLang->formatNum( count( $dupes ) ), $this->getTitle()->getDBkey()
757 );
758 $wgOut->addHTML( "<ul class='mw-imagepage-duplicates'>\n" );
759
760 /**
761 * @var $file File
762 */
763 foreach ( $dupes as $file ) {
764 $fromSrc = '';
765 if ( $file->isLocal() ) {
766 $link = Linker::link(
767 $file->getTitle(),
768 null,
769 array(),
770 array(),
771 array( 'known', 'noclasses' )
772 );
773 } else {
774 $link = Linker::makeExternalLink( $file->getDescriptionUrl(),
775 $file->getTitle()->getPrefixedText() );
776 $fromSrc = wfMsg( 'shared-repo-from', $file->getRepo()->getDisplayName() );
777 }
778 $wgOut->addHTML( "<li>{$link} {$fromSrc}</li>\n" );
779 }
780 $wgOut->addHTML( "</ul></div>\n" );
781 }
782
783 /**
784 * Delete the file, or an earlier version of it
785 */
786 public function delete() {
787 global $wgUploadMaintenance;
788 if ( $wgUploadMaintenance && $this->getTitle() && $this->getTitle()->getNamespace() == NS_FILE ) {
789 global $wgOut;
790 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n", array( 'filedelete-maintenance' ) );
791 return;
792 }
793
794 $this->loadFile();
795 if ( !$this->mPage->getFile()->exists() || !$this->mPage->getFile()->isLocal() || $this->mPage->getFile()->getRedirected() ) {
796 // Standard article deletion
797 parent::delete();
798 return;
799 }
800 $deleter = new FileDeleteForm( $this->mPage->getFile() );
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 }