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