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