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