Fixing part of bug 14688 (upload restrictions):
[lhc/web/wiklou.git] / includes / ImagePage.php
1 <?php
2
3 if( !defined( 'MEDIAWIKI' ) )
4 die( 1 );
5
6 /**
7 * Special handling for image description pages
8 *
9 * @ingroup Media
10 */
11 class ImagePage extends Article {
12
13 /* private */ var $img; // Image object
14 /* private */ var $displayImg;
15 /* private */ var $repo;
16 /* private */ var $fileLoaded;
17 var $mExtraDescription = false;
18 var $dupes;
19
20 function __construct( $title ) {
21 parent::__construct( $title );
22 $this->dupes = null;
23 $this->repo = null;
24 }
25
26 public function setFile( $file ) {
27 $this->displayImg = $file;
28 $this->img = $file;
29 $this->fileLoaded = true;
30 }
31
32 protected function loadFile() {
33 if( $this->fileLoaded ) {
34 return true;
35 }
36 $this->fileLoaded = true;
37
38 $this->displayImg = $this->img = false;
39 wfRunHooks( 'ImagePageFindFile', array( $this, &$this->img, &$this->displayImg ) );
40 if( !$this->img ) {
41 $this->img = wfFindFile( $this->mTitle );
42 if( !$this->img ) {
43 $this->img = wfLocalFile( $this->mTitle );
44 }
45 }
46 if( !$this->displayImg ) {
47 $this->displayImg = $this->img;
48 }
49 $this->repo = $this->img->getRepo();
50 }
51
52 /**
53 * Handler for action=render
54 * Include body text only; none of the image extras
55 */
56 public function render() {
57 global $wgOut;
58 $wgOut->setArticleBodyOnly( true );
59 parent::view();
60 }
61
62 public function view() {
63 global $wgOut, $wgShowEXIF, $wgRequest, $wgUser;
64 $this->loadFile();
65
66 if( $this->mTitle->getNamespace() == NS_FILE && $this->img->getRedirected() ) {
67 if( $this->mTitle->getDBkey() == $this->img->getName() ) {
68 // mTitle is the same as the redirect target so ask Article
69 // to perform the redirect for us.
70 return Article::view();
71 } else {
72 // mTitle is not the same as the redirect target so it is
73 // probably the redirect page itself. Fake the redirect symbol
74 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
75 $wgOut->addHTML( $this->viewRedirect( Title::makeTitle( NS_FILE, $this->img->getName() ),
76 /* $appendSubtitle */ true, /* $forceKnown */ true ) );
77 $this->viewUpdates();
78 return;
79 }
80 }
81
82 $diff = $wgRequest->getVal( 'diff' );
83 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
84
85 if( $this->mTitle->getNamespace() != NS_FILE || ( isset( $diff ) && $diffOnly ) )
86 return Article::view();
87
88 if( $wgShowEXIF && $this->displayImg->exists() ) {
89 // FIXME: bad interface, see note on MediaHandler::formatMetadata().
90 $formattedMetadata = $this->displayImg->formatMetadata();
91 $showmeta = $formattedMetadata !== false;
92 } else {
93 $showmeta = false;
94 }
95
96 if( !$diff && $this->displayImg->exists() )
97 $wgOut->addHTML( $this->showTOC($showmeta) );
98
99 if( !$diff )
100 $this->openShowImage();
101
102 # No need to display noarticletext, we use our own message, output in openShowImage()
103 if( $this->getID() ) {
104 Article::view();
105 } else {
106 # Just need to set the right headers
107 $wgOut->setArticleFlag( true );
108 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
109 $this->viewUpdates();
110 }
111
112 # Show shared description, if needed
113 if( $this->mExtraDescription ) {
114 $fol = wfMsgNoTrans( 'shareddescriptionfollows' );
115 if( $fol != '-' && !wfEmptyMsg( 'shareddescriptionfollows', $fol ) ) {
116 $wgOut->addWikiText( $fol );
117 }
118 $wgOut->addHTML( '<div id="shared-image-desc">' . $this->mExtraDescription . "</div>\n" );
119 }
120
121 $this->closeShowImage();
122 $this->imageHistory();
123 // TODO: Cleanup the following
124
125 $wgOut->addHTML( Xml::element( 'h2',
126 array( 'id' => 'filelinks' ),
127 wfMsg( 'imagelinks' ) ) . "\n" );
128 $this->imageDupes();
129 # TODO! FIXME! For some freaky reason, we can't redirect to foreign images.
130 # Yet we return metadata about the target. Definitely an issue in the FileRepo
131 $this->imageRedirects();
132 $this->imageLinks();
133
134 if( $showmeta ) {
135 global $wgStylePath, $wgStyleVersion;
136 $expand = htmlspecialchars( Xml::escapeJsString( wfMsg( 'metadata-expand' ) ) );
137 $collapse = htmlspecialchars( Xml::escapeJsString( wfMsg( 'metadata-collapse' ) ) );
138 $wgOut->addHTML( Xml::element( 'h2', array( 'id' => 'metadata' ), wfMsg( 'metadata' ) ) . "\n" );
139 $wgOut->addWikiText( $this->makeMetadataTable( $formattedMetadata ) );
140 $wgOut->addScriptFile( 'metadata.js' );
141 $wgOut->addHTML(
142 "<script type=\"text/javascript\">attachMetadataToggle('mw_metadata', '$expand', '$collapse');</script>\n" );
143 }
144 }
145
146 public function getRedirectTarget() {
147 $this->loadFile();
148 if( $this->img->isLocal() ) {
149 return parent::getRedirectTarget();
150 }
151 // Foreign image page
152 $from = $this->img->getRedirected();
153 $to = $this->img->getName();
154 if( $from == $to ) {
155 return null;
156 }
157 return $this->mRedirectTarget = Title::makeTitle( NS_FILE, $to );
158 }
159 public function followRedirect() {
160 $this->loadFile();
161 if( $this->img->isLocal() ) {
162 return parent::followRedirect();
163 }
164 $from = $this->img->getRedirected();
165 $to = $this->img->getName();
166 if( $from == $to ) {
167 return false;
168 }
169 return Title::makeTitle( NS_FILE, $to );
170 }
171 public function isRedirect( $text = false ) {
172 $this->loadFile();
173 if( $this->img->isLocal() )
174 return parent::isRedirect( $text );
175
176 return (bool)$this->img->getRedirected();
177 }
178
179 public function isLocal() {
180 $this->loadFile();
181 return $this->img->isLocal();
182 }
183
184 public function getFile() {
185 $this->loadFile();
186 return $this->img;
187 }
188
189 public function getDisplayedFile() {
190 $this->loadFile();
191 return $this->displayImg;
192 }
193
194 public function getDuplicates() {
195 $this->loadFile();
196 if( !is_null($this->dupes) ) {
197 return $this->dupes;
198 }
199 if( !( $hash = $this->img->getSha1() ) ) {
200 return $this->dupes = array();
201 }
202 $dupes = RepoGroup::singleton()->findBySha1( $hash );
203 // Remove duplicates with self and non matching file sizes
204 $self = $this->img->getRepoName().':'.$this->img->getName();
205 $size = $this->img->getSize();
206 foreach ( $dupes as $index => $file ) {
207 $key = $file->getRepoName().':'.$file->getName();
208 if( $key == $self )
209 unset( $dupes[$index] );
210 if( $file->getSize() != $size )
211 unset( $dupes[$index] );
212 }
213 return $this->dupes = $dupes;
214
215 }
216
217
218 /**
219 * Create the TOC
220 *
221 * @param bool $metadata Whether or not to show the metadata link
222 * @return string
223 */
224 protected function showTOC( $metadata ) {
225 global $wgLang;
226 $r = '<ul id="filetoc">
227 <li><a href="#file">' . $wgLang->getNsText( NS_FILE ) . '</a></li>
228 <li><a href="#filehistory">' . wfMsgHtml( 'filehist' ) . '</a></li>
229 <li><a href="#filelinks">' . wfMsgHtml( 'imagelinks' ) . "</a></li>\n" .
230 ($metadata ? ' <li><a href="#metadata">' . wfMsgHtml( 'metadata' ) . '</a></li>' : '') . "
231 </ul>\n";
232 return $r;
233 }
234
235 /**
236 * Make a table with metadata to be shown in the output page.
237 *
238 * FIXME: bad interface, see note on MediaHandler::formatMetadata().
239 *
240 * @param array $exif The array containing the EXIF data
241 * @return string
242 */
243 protected function makeMetadataTable( $metadata ) {
244 $r = "<div class=\"mw-imagepage-section-metadata\">\n";
245 $r .= wfMsg( 'metadata-help' );
246 $r .= "<table id=\"mw_metadata\" class=\"mw_metadata\">\n";
247 foreach ( $metadata as $type => $stuff ) {
248 foreach ( $stuff as $v ) {
249 # FIXME, why is this using escapeId for a class?!
250 $class = Sanitizer::escapeId( $v['id'] );
251 if( $type == 'collapsed' ) {
252 $class .= ' collapsable';
253 }
254 $r .= "<tr class=\"$class\">\n";
255 $r .= "<th>{$v['name']}</th>\n";
256 $r .= "<td>{$v['value']}</td>\n</tr>";
257 }
258 }
259 $r .= "</table>\n</div>\n";
260 return $r;
261 }
262
263 /**
264 * Overloading Article's getContent method.
265 *
266 * Omit noarticletext if sharedupload; text will be fetched from the
267 * shared upload server if possible.
268 */
269 public function getContent() {
270 $this->loadFile();
271 if( $this->img && !$this->img->isLocal() && 0 == $this->getID() ) {
272 return '';
273 }
274 return Article::getContent();
275 }
276
277 protected function openShowImage() {
278 global $wgOut, $wgUser, $wgImageLimits, $wgRequest,
279 $wgLang, $wgContLang, $wgEnableUploads;
280
281 $this->loadFile();
282
283 $full_url = $this->displayImg->getURL();
284 $linkAttribs = false;
285 $sizeSel = intval( $wgUser->getOption( 'imagesize') );
286 if( !isset( $wgImageLimits[$sizeSel] ) ) {
287 $sizeSel = User::getDefaultOption( 'imagesize' );
288
289 // The user offset might still be incorrect, specially if
290 // $wgImageLimits got changed (see bug #8858).
291 if( !isset( $wgImageLimits[$sizeSel] ) ) {
292 // Default to the first offset in $wgImageLimits
293 $sizeSel = 0;
294 }
295 }
296 $max = $wgImageLimits[$sizeSel];
297 $maxWidth = $max[0];
298 $maxHeight = $max[1];
299 $sk = $wgUser->getSkin();
300 $dirmark = $wgContLang->getDirMark();
301
302 if( $this->displayImg->exists() ) {
303 # image
304 $page = $wgRequest->getIntOrNull( 'page' );
305 if( is_null( $page ) ) {
306 $params = array();
307 $page = 1;
308 } else {
309 $params = array( 'page' => $page );
310 }
311 $width_orig = $this->displayImg->getWidth();
312 $width = $width_orig;
313 $height_orig = $this->displayImg->getHeight();
314 $height = $height_orig;
315 $mime = $this->displayImg->getMimeType();
316 $showLink = false;
317 $linkAttribs = array( 'href' => $full_url );
318 $longDesc = $this->displayImg->getLongDesc();
319
320 wfRunHooks( 'ImageOpenShowImageInlineBefore', array( &$this , &$wgOut ) ) ;
321
322 if( $this->displayImg->allowInlineDisplay() ) {
323 # image
324
325 # "Download high res version" link below the image
326 #$msgsize = wfMsgHtml('file-info-size', $width_orig, $height_orig, $sk->formatSize( $this->displayImg->getSize() ), $mime );
327 # We'll show a thumbnail of this image
328 if( $width > $maxWidth || $height > $maxHeight ) {
329 # Calculate the thumbnail size.
330 # First case, the limiting factor is the width, not the height.
331 if( $width / $height >= $maxWidth / $maxHeight ) {
332 $height = round( $height * $maxWidth / $width);
333 $width = $maxWidth;
334 # Note that $height <= $maxHeight now.
335 } else {
336 $newwidth = floor( $width * $maxHeight / $height);
337 $height = round( $height * $newwidth / $width );
338 $width = $newwidth;
339 # Note that $height <= $maxHeight now, but might not be identical
340 # because of rounding.
341 }
342 $msgbig = wfMsgHtml( 'show-big-image' );
343 $msgsmall = wfMsgExt( 'show-big-image-thumb', 'parseinline',
344 $wgLang->formatNum( $width ),
345 $wgLang->formatNum( $height )
346 );
347 } else {
348 # Image is small enough to show full size on image page
349 $msgbig = htmlspecialchars( $this->displayImg->getName() );
350 $msgsmall = wfMsgExt( 'file-nohires', array( 'parseinline' ) );
351 }
352
353 $params['width'] = $width;
354 $thumbnail = $this->displayImg->transform( $params );
355
356 $anchorclose = "<br />";
357 if( $this->displayImg->mustRender() ) {
358 $showLink = true;
359 } else {
360 $anchorclose .=
361 $msgsmall .
362 '<br />' . Xml::tags( 'a', $linkAttribs, $msgbig ) . "$dirmark " . $longDesc;
363 }
364
365 if( $this->displayImg->isMultipage() ) {
366 $wgOut->addHTML( '<table class="multipageimage"><tr><td>' );
367 }
368
369 if( $thumbnail ) {
370 $options = array(
371 'alt' => $this->displayImg->getTitle()->getPrefixedText(),
372 'file-link' => true,
373 );
374 $wgOut->addHTML( '<div class="fullImageLink" id="file">' .
375 $thumbnail->toHtml( $options ) .
376 $anchorclose . "</div>\n" );
377 }
378
379 if( $this->displayImg->isMultipage() ) {
380 $count = $this->displayImg->pageCount();
381
382 if( $page > 1 ) {
383 $label = $wgOut->parse( wfMsg( 'imgmultipageprev' ), false );
384 $link = $sk->makeKnownLinkObj( $this->mTitle, $label, 'page='. ($page-1) );
385 $thumb1 = $sk->makeThumbLinkObj( $this->mTitle, $this->displayImg, $link, $label, 'none',
386 array( 'page' => $page - 1 ) );
387 } else {
388 $thumb1 = '';
389 }
390
391 if( $page < $count ) {
392 $label = wfMsg( 'imgmultipagenext' );
393 $link = $sk->makeKnownLinkObj( $this->mTitle, $label, 'page='. ($page+1) );
394 $thumb2 = $sk->makeThumbLinkObj( $this->mTitle, $this->displayImg, $link, $label, 'none',
395 array( 'page' => $page + 1 ) );
396 } else {
397 $thumb2 = '';
398 }
399
400 global $wgScript;
401
402 $formParams = array(
403 'name' => 'pageselector',
404 'action' => $wgScript,
405 'onchange' => 'document.pageselector.submit();',
406 );
407
408 $option = array();
409 for ( $i=1; $i <= $count; $i++ ) {
410 $options[] = Xml::option( $wgLang->formatNum($i), $i, $i == $page );
411 }
412 $select = Xml::tags( 'select',
413 array( 'id' => 'pageselector', 'name' => 'page' ),
414 implode( "\n", $options ) );
415
416 $wgOut->addHTML(
417 '</td><td><div class="multipageimagenavbox">' .
418 Xml::openElement( 'form', $formParams ) .
419 Xml::hidden( 'title', $this->getTitle()->getPrefixedDbKey() ) .
420 wfMsgExt( 'imgmultigoto', array( 'parseinline', 'replaceafter' ), $select ) .
421 Xml::submitButton( wfMsg( 'imgmultigo' ) ) .
422 Xml::closeElement( 'form' ) .
423 "<hr />$thumb1\n$thumb2<br clear=\"all\" /></div></td></tr></table>"
424 );
425 }
426 } else {
427 #if direct link is allowed but it's not a renderable image, show an icon.
428 if( $this->displayImg->isSafeFile() ) {
429 $icon= $this->displayImg->iconThumb();
430
431 $wgOut->addHTML( '<div class="fullImageLink" id="file">' .
432 $icon->toHtml( array( 'desc-link' => true ) ) .
433 "</div>\n" );
434 }
435
436 $showLink = true;
437 }
438
439
440 if($showLink) {
441 $filename = wfEscapeWikiText( $this->displayImg->getName() );
442 $medialink = $this->displayImg->isMissing() ?
443 "'''$filename'''" :
444 "[[Media:$filename|$filename]]";
445
446 if( !$this->displayImg->isSafeFile() ) {
447 $warning = wfMsgNoTrans( 'mediawarning' );
448 $wgOut->addWikiText( <<<EOT
449 <div class="fullMedia">
450 <span class="dangerousLink">{$medialink}</span>$dirmark
451 <span class="fileInfo">$longDesc</span>
452 </div>
453 <div class="mediaWarning">$warning</div>
454 EOT
455 );
456 } else {
457 $wgOut->addWikiText( <<<EOT
458 <div class="fullMedia">
459 {$medialink}{$dirmark}
460 <span class="fileInfo">$longDesc</span>
461 </div>
462 EOT
463 );
464 }
465 }
466
467 if( !$this->displayImg->isLocal() ) {
468 $this->printSharedImageText();
469 }
470 } else {
471 # Image does not exist
472 $nofile = wfMsgHtml( 'filepage-nofile' );
473 if ( $wgEnableUploads && $wgUser->isAllowed( 'upload' ) ) {
474 // Only show an upload link if the user can upload
475 $nofile .= ' '.$sk->makeKnownLinkObj(
476 SpecialPage::getTitleFor( 'Upload' ),
477 wfMsgHtml('filepage-nofile-link'),
478 'wpDestFile=' . urlencode( $this->displayImg->getName() )
479 );
480 }
481 $wgOut->setRobotPolicy( 'noindex,nofollow' );
482 $wgOut->addHTML( '<div id="mw-imagepage-nofile">' . $nofile . '</div>' );
483 }
484 }
485
486 /**
487 * Show a notice that the file is from a shared repository
488 */
489 protected function printSharedImageText() {
490 global $wgOut;
491
492 $this->loadFile();
493
494 $descUrl = $this->img->getDescriptionUrl();
495 $descText = $this->img->getDescriptionText();
496
497 $wrap = "<div class=\"sharedUploadNotice\">\n$1\n</div>\n";
498 $repo = $this->img->getRepo()->getDisplayName();
499
500 $msg = '';
501 if( $descUrl && $descText && wfMsgNoTrans( 'sharedupload-desc-here' ) !== '-' ) {
502 $wgOut->wrapWikiMsg( $wrap, array( 'sharedupload-desc-here', $repo, $descUrl ) );
503 } elseif ( $descUrl && wfMsgNoTrans( 'sharedupload-desc-there' ) !== '-' ) {
504 $wgOut->wrapWikiMsg( $wrap, array( 'sharedupload-desc-there', $repo, $descUrl ) );
505 } else {
506 $wgOut->wrapWikiMsg( $wrap, array( 'sharedupload', $repo ), ''/*BACKCOMPAT*/ );
507 }
508
509 if( $descText ) {
510 $this->mExtraDescription = $descText;
511 }
512 }
513
514 public function getUploadUrl() {
515 $this->loadFile();
516 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
517 return $uploadTitle->getFullUrl( 'wpDestFile=' . urlencode( $this->img->getName() ) . '&wpForReUpload=1' );
518 }
519
520 /**
521 * Print out the various links at the bottom of the image page, e.g. reupload,
522 * external editing (and instructions link) etc.
523 */
524 protected function uploadLinksBox() {
525 global $wgUser, $wgOut, $wgEnableUploads;
526
527 if( !$wgEnableUploads ) { return; }
528
529 $this->loadFile();
530 if( !$this->img->isLocal() )
531 return;
532
533 $sk = $wgUser->getSkin();
534
535 $wgOut->addHTML( "<br /><ul>\n" );
536
537 # "Upload a new version of this file" link
538 if( UploadForm::userCanReUpload($wgUser,$this->img->name) ) {
539 $ulink = $sk->makeExternalLink( $this->getUploadUrl(), wfMsg( 'uploadnewversion-linktext' ) );
540 $wgOut->addHTML( "<li id=\"mw-imagepage-reupload-link\"><div class=\"plainlinks\">{$ulink}</div></li>\n" );
541 }
542
543 # External editing link
544 $elink = $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'edit-externally' ), 'action=edit&externaledit=true&mode=file' );
545 $wgOut->addHTML( '<li id="mw-imagepage-edit-external">' . $elink . ' <small>' . wfMsgExt( 'edit-externally-help', array( 'parseinline' ) ) . "</small></li>\n" );
546
547 $wgOut->addHTML( "</ul>\n" );
548 }
549
550 protected function closeShowImage() {} # For overloading
551
552 /**
553 * If the page we've just displayed is in the "Image" namespace,
554 * we follow it with an upload history of the image and its usage.
555 */
556 protected function imageHistory() {
557 global $wgOut, $wgUseExternalEditor;
558
559 $this->loadFile();
560 $pager = new ImageHistoryPseudoPager( $this );
561 $wgOut->addHTML( $pager->getBody() );
562
563 $this->img->resetHistory(); // free db resources
564
565 # Exist check because we don't want to show this on pages where an image
566 # doesn't exist along with the noimage message, that would suck. -ævar
567 if( $wgUseExternalEditor && $this->img->exists() ) {
568 $this->uploadLinksBox();
569 }
570 }
571
572 protected function imageLinks() {
573 global $wgUser, $wgOut, $wgLang;
574
575 $limit = 100;
576
577 $dbr = wfGetDB( DB_SLAVE );
578
579 $res = $dbr->select(
580 array( 'imagelinks', 'page' ),
581 array( 'page_namespace', 'page_title' ),
582 array( 'il_to' => $this->mTitle->getDBkey(), 'il_from = page_id' ),
583 __METHOD__,
584 array( 'LIMIT' => $limit + 1)
585 );
586 $count = $dbr->numRows( $res );
587 if( $count == 0 ) {
588 $wgOut->addHTML( "<div id='mw-imagepage-nolinkstoimage'>\n" );
589 $wgOut->addWikiMsg( 'nolinkstoimage' );
590 $wgOut->addHTML( "</div>\n" );
591 return;
592 }
593
594 $wgOut->addHTML( "<div id='mw-imagepage-section-linkstoimage'>\n" );
595 if( $count <= $limit - 1 ) {
596 $wgOut->addWikiMsg( 'linkstoimage', $count );
597 } else {
598 // More links than the limit. Add a link to [[Special:Whatlinkshere]]
599 $wgOut->addWikiMsg( 'linkstoimage-more',
600 $wgLang->formatNum( $limit ),
601 $this->mTitle->getPrefixedDBkey()
602 );
603 }
604
605 $wgOut->addHTML( "<ul class='mw-imagepage-linkstoimage'>\n" );
606 $sk = $wgUser->getSkin();
607 $count = 0;
608 while ( $s = $res->fetchObject() ) {
609 $count++;
610 if( $count <= $limit ) {
611 // We have not yet reached the extra one that tells us there is more to fetch
612 $name = Title::makeTitle( $s->page_namespace, $s->page_title );
613 $link = $sk->makeKnownLinkObj( $name, "" );
614 $wgOut->addHTML( "<li>{$link}</li>\n" );
615 }
616 }
617 $wgOut->addHTML( "</ul>\n" );
618 $res->free();
619
620 // Add a links to [[Special:Whatlinkshere]]
621 if( $count > $limit )
622 $wgOut->addWikiMsg( 'morelinkstoimage', $this->mTitle->getPrefixedDBkey() );
623 $wgOut->addHTML( "</div>\n" );
624 }
625
626 protected function imageRedirects() {
627 global $wgUser, $wgOut, $wgLang;
628
629 $redirects = $this->getTitle()->getRedirectsHere( NS_FILE );
630 if( count( $redirects ) == 0 ) return;
631
632 $wgOut->addHTML( "<div id='mw-imagepage-section-redirectstofile'>\n" );
633 $wgOut->addWikiMsg( 'redirectstofile',
634 $wgLang->formatNum( count( $redirects ) )
635 );
636 $wgOut->addHTML( "<ul class='mw-imagepage-redirectstofile'>\n" );
637
638 $sk = $wgUser->getSkin();
639 foreach ( $redirects as $title ) {
640 $link = $sk->makeKnownLinkObj( $title, "", "redirect=no" );
641 $wgOut->addHTML( "<li>{$link}</li>\n" );
642 }
643 $wgOut->addHTML( "</ul></div>\n" );
644
645 }
646
647 protected function imageDupes() {
648 global $wgOut, $wgUser, $wgLang;
649
650 $this->loadFile();
651
652 $dupes = $this->getDuplicates();
653 if( count( $dupes ) == 0 ) return;
654
655 $wgOut->addHTML( "<div id='mw-imagepage-section-duplicates'>\n" );
656 $wgOut->addWikiMsg( 'duplicatesoffile',
657 $wgLang->formatNum( count( $dupes ) ), $this->mTitle->getDBkey()
658 );
659 $wgOut->addHTML( "<ul class='mw-imagepage-duplicates'>\n" );
660
661 $sk = $wgUser->getSkin();
662 foreach ( $dupes as $file ) {
663 $fromSrc = '';
664 if( $file->isLocal() )
665 $link = $sk->makeKnownLinkObj( $file->getTitle(), "" );
666 else {
667 $link = $sk->makeExternalLink( $file->getDescriptionUrl(),
668 $file->getTitle()->getPrefixedText() );
669 $fromSrc = wfMsg( 'shared-repo-from', $file->getRepo()->getDisplayName() );
670 }
671 $wgOut->addHTML( "<li>{$link} {$fromSrc}</li>\n" );
672 }
673 $wgOut->addHTML( "</ul></div>\n" );
674 }
675
676 /**
677 * Delete the file, or an earlier version of it
678 */
679 public function delete() {
680 $this->loadFile();
681 if( !$this->img->exists() || !$this->img->isLocal() || $this->img->getRedirected() ) {
682 // Standard article deletion
683 Article::delete();
684 return;
685 }
686 $deleter = new FileDeleteForm( $this->img );
687 $deleter->execute();
688 }
689
690 /**
691 * Revert the file to an earlier version
692 */
693 public function revert() {
694 $this->loadFile();
695 $reverter = new FileRevertForm( $this->img );
696 $reverter->execute();
697 }
698
699 /**
700 * Override handling of action=purge
701 */
702 public function doPurge() {
703 $this->loadFile();
704 if( $this->img->exists() ) {
705 wfDebug( "ImagePage::doPurge purging " . $this->img->getName() . "\n" );
706 $update = new HTMLCacheUpdate( $this->mTitle, 'imagelinks' );
707 $update->doUpdate();
708 $this->img->upgradeRow();
709 $this->img->purgeCache();
710 } else {
711 wfDebug( "ImagePage::doPurge no image for " . $this->img->getName() . "; limiting purge to cache only\n" );
712 // even if the file supposedly doesn't exist, force any cached information
713 // to be updated (in case the cached information is wrong)
714 $this->img->purgeCache();
715 }
716 parent::doPurge();
717 }
718
719 /**
720 * Display an error with a wikitext description
721 */
722 function showError( $description ) {
723 global $wgOut;
724 $wgOut->setPageTitle( wfMsg( "internalerror" ) );
725 $wgOut->setRobotPolicy( "noindex,nofollow" );
726 $wgOut->setArticleRelated( false );
727 $wgOut->enableClientCache( false );
728 $wgOut->addWikiText( $description );
729 }
730
731 }
732
733 /**
734 * Builds the image revision log shown on image pages
735 *
736 * @ingroup Media
737 */
738 class ImageHistoryList {
739
740 protected $imagePage, $img, $skin, $title, $repo;
741
742 public function __construct( $imagePage ) {
743 global $wgUser;
744 $this->skin = $wgUser->getSkin();
745 $this->current = $imagePage->getFile();
746 $this->img = $imagePage->getDisplayedFile();
747 $this->title = $imagePage->getTitle();
748 $this->imagePage = $imagePage;
749 }
750
751 public function getImagePage() {
752 return $this->imagePage;
753 }
754
755 public function getSkin() {
756 return $this->skin;
757 }
758
759 public function getFile() {
760 return $this->img;
761 }
762
763 public function beginImageHistoryList( $navLinks = '' ) {
764 global $wgOut, $wgUser;
765 return Xml::element( 'h2', array( 'id' => 'filehistory' ), wfMsg( 'filehist' ) ) . "\n"
766 . "<div id=\"mw-imagepage-section-filehistory\">\n"
767 . $wgOut->parse( wfMsgNoTrans( 'filehist-help' ) )
768 . $navLinks . "\n"
769 . Xml::openElement( 'table', array( 'class' => 'filehistory' ) ) . "\n"
770 . '<tr><td></td>'
771 . ( $this->current->isLocal() && ($wgUser->isAllowed('delete') || $wgUser->isAllowed('deleterevision') ) ? '<td></td>' : '' )
772 . '<th>' . wfMsgHtml( 'filehist-datetime' ) . '</th>'
773 . '<th>' . wfMsgHtml( 'filehist-thumb' ) . '</th>'
774 . '<th>' . wfMsgHtml( 'filehist-dimensions' ) . '</th>'
775 . '<th>' . wfMsgHtml( 'filehist-user' ) . '</th>'
776 . '<th>' . wfMsgHtml( 'filehist-comment' ) . '</th>'
777 . "</tr>\n";
778 }
779
780 public function endImageHistoryList( $navLinks = '' ) {
781 return "</table>\n$navLinks\n</div>\n";
782 }
783
784 public function imageHistoryLine( $iscur, $file ) {
785 global $wgUser, $wgLang, $wgContLang, $wgTitle;
786
787 $timestamp = wfTimestamp(TS_MW, $file->getTimestamp());
788 $img = $iscur ? $file->getName() : $file->getArchiveName();
789 $user = $file->getUser('id');
790 $usertext = $file->getUser('text');
791 $description = $file->getDescription();
792 $sha1 = $file->getSha1();
793
794 $local = $this->current->isLocal();
795 $row = $css = $selected = '';
796
797 // Deletion link
798 if( $local && ($wgUser->isAllowed('delete') || $wgUser->isAllowed('deleterevision') ) ) {
799 $row .= '<td>';
800 # Link to remove from history
801 if( $wgUser->isAllowed( 'delete' ) ) {
802 $q = array( 'action' => 'delete' );
803 if( !$iscur )
804 $q['oldimage'] = $img;
805 $row .= $this->skin->link(
806 $this->title,
807 wfMsgHtml( $iscur ? 'filehist-deleteall' : 'filehist-deleteone' ),
808 array(), $q, array( 'known' )
809 );
810 }
811 # Link to hide content
812 if( $wgUser->isAllowed( 'deleterevision' ) ) {
813 if( $wgUser->isAllowed('delete') ) {
814 $row .= '<br/>';
815 }
816 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
817 // If file is top revision or locked from this user, don't link
818 if( $iscur || !$file->userCan(File::DELETED_RESTRICTED) ) {
819 $del = wfMsgHtml( 'rev-delundel' );
820 } else {
821 // If the file was hidden, link to sha-1
822 list( $ts, $name ) = explode( '!', $img, 2 );
823 $del = $this->skin->link( $revdel, wfMsgHtml( 'rev-delundel' ),
824 array(),
825 array( 'target' => $wgTitle->getPrefixedText(), 'oldimage' => $ts ),
826 array( 'known' )
827 );
828 // Bolden oversighted content
829 if( $file->isDeleted(File::DELETED_RESTRICTED) )
830 $del = "<strong>$del</strong>";
831 }
832 $row .= "<tt style='white-space: nowrap;'><small>$del</small></tt>";
833 }
834 $row .= '</td>';
835 }
836
837 // Reversion link/current indicator
838 $row .= '<td>';
839 if( $iscur ) {
840 $row .= wfMsgHtml( 'filehist-current' );
841 } elseif( $local && $wgUser->isLoggedIn() && $this->title->userCan( 'edit' ) ) {
842 if( $file->isDeleted(File::DELETED_FILE) ) {
843 $row .= wfMsgHtml('filehist-revert');
844 } else {
845 $q = array();
846 $q[] = 'action=revert';
847 $q[] = 'oldimage=' . urlencode( $img );
848 $q[] = 'wpEditToken=' . urlencode( $wgUser->editToken( $img ) );
849 $row .= $this->skin->makeKnownLinkObj( $this->title,
850 wfMsgHtml( 'filehist-revert' ),
851 implode( '&', $q ) );
852 }
853 }
854 $row .= '</td>';
855
856 // Date/time and image link
857 if( $file->getTimestamp() === $this->img->getTimestamp() ) {
858 $selected = "class='filehistory-selected'";
859 }
860 $row .= "<td $selected style='white-space: nowrap;'>";
861 if( !$file->userCan(File::DELETED_FILE) ) {
862 # Don't link to unviewable files
863 $row .= '<span class="history-deleted">' . $wgLang->timeAndDate( $timestamp, true ) . '</span>';
864 } elseif( $file->isDeleted(File::DELETED_FILE) ) {
865 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
866 # Make a link to review the image
867 $url = $this->skin->makeKnownLinkObj( $revdel, $wgLang->timeAndDate( $timestamp, true ),
868 "target=".$wgTitle->getPrefixedText()."&file=$sha1.".$this->current->getExtension() );
869 $row .= '<span class="history-deleted">'.$url.'</span>';
870 } elseif( $file->isMissing() ) {
871 # Don't link to missing files
872 $row .= $wgLang->timeAndDate( $timestamp, true );
873 } else {
874 $url = $iscur ? $this->current->getUrl() : $this->current->getArchiveUrl( $img );
875 $row .= Xml::element( 'a', array( 'href' => $url ), $wgLang->timeAndDate( $timestamp, true ) );
876 }
877 $row .= "</td>";
878
879 // Thumbnail
880 $row .= '<td>' . $this->getThumbForLine( $file ) . '</td>';
881
882 // Image dimensions + size
883 $row .= '<td>';
884 $row .= htmlspecialchars( $file->getDimensionsString() );
885 $row .= " <span style='white-space: nowrap;'>(" . $this->skin->formatSize( $file->getSize() ) . ')</span>';
886 $row .= '</td>';
887
888 // Uploading user
889 $row .= '<td>';
890 if( $local ) {
891 // Hide deleted usernames
892 if( $file->isDeleted(File::DELETED_USER) ) {
893 $row .= '<span class="history-deleted">' . wfMsgHtml( 'rev-deleted-user' ) . '</span>';
894 } else {
895 $row .= $this->skin->userLink( $user, $usertext ) . " <span style='white-space: nowrap;'>" .
896 $this->skin->userToolLinks( $user, $usertext ) . "</span>";
897 }
898 } else {
899 $row .= htmlspecialchars( $usertext );
900 }
901 $row .= '</td><td>';
902
903 // Don't show deleted descriptions
904 if( $file->isDeleted(File::DELETED_COMMENT) ) {
905 $row .= '<span class="history-deleted">' . wfMsgHtml('rev-deleted-comment') . '</span>';
906 } else {
907 $row .= $this->skin->commentBlock( $description, $this->title );
908 }
909 $row .= '</td>';
910
911 wfRunHooks( 'ImagePageFileHistoryLine', array( $this, $file, &$row, &$rowClass ) );
912 $classAttr = $rowClass ? " class='$rowClass'" : "";
913
914 return "<tr{$classAttr}>{$row}</tr>\n";
915 }
916
917 protected function getThumbForLine( $file ) {
918 global $wgLang;
919
920 if( $file->isMissing() ) {
921 return '<strong class="error">' . wfMsgHtml( 'filehist-missing' ) . '</strong>';
922 } elseif( $file->allowInlineDisplay() && $file->userCan( File::DELETED_FILE ) && !$file->isDeleted( File::DELETED_FILE ) ) {
923 $params = array(
924 'width' => '120',
925 'height' => '120',
926 );
927 $timestamp = wfTimestamp(TS_MW, $file->getTimestamp());
928
929 $thumbnail = $file->transform( $params );
930 $options = array(
931 'alt' => wfMsg( 'filehist-thumbtext', $wgLang->timeAndDate( $timestamp, true ) ),
932 'file-link' => true,
933 );
934
935 if ( !$thumbnail ) return wfMsgHtml( 'filehist-nothumb' );
936
937 return $thumbnail->toHtml( $options );
938 } else {
939 return wfMsgHtml( 'filehist-nothumb' );
940 }
941 }
942 }
943
944 class ImageHistoryPseudoPager extends ReverseChronologicalPager {
945 function __construct( $imagePage ) {
946 parent::__construct();
947 $this->mImagePage = $imagePage;
948 $this->mTitle = clone( $imagePage->getTitle() );
949 $this->mTitle->setFragment( '#filehistory' );
950 $this->mImg = NULL;
951 $this->mHist = array();
952 $this->mRange = array( 0, 0 ); // display range
953 }
954
955 function getTitle() {
956 return $this->mTitle;
957 }
958
959 function getQueryInfo() {
960 return false;
961 }
962
963 function getIndexField() {
964 return '';
965 }
966
967 function formatRow( $row ) {
968 return '';
969 }
970
971 function getBody() {
972 $s = '';
973 $this->doQuery();
974 if( count($this->mHist) ) {
975 $list = new ImageHistoryList( $this->mImagePage );
976 # Generate prev/next links
977 $navLink = $this->getNavigationBar();
978 $s = $list->beginImageHistoryList($navLink);
979 // Skip rows there just for paging links
980 for( $i = $this->mRange[0]; $i <= $this->mRange[1]; $i++ ) {
981 $file = $this->mHist[$i];
982 $s .= $list->imageHistoryLine( !$file->isOld(), $file );
983 }
984 $s .= $list->endImageHistoryList($navLink);
985 }
986 return $s;
987 }
988
989 function doQuery() {
990 if( $this->mQueryDone ) return;
991 $this->mImg = $this->mImagePage->getFile(); // ensure loading
992 if( !$this->mImg->exists() ) {
993 return;
994 }
995 $queryLimit = $this->mLimit + 1; // limit plus extra row
996 if( $this->mIsBackwards ) {
997 // Fetch the file history
998 $this->mHist = $this->mImg->getHistory($queryLimit,null,$this->mOffset,false);
999 // The current rev may not meet the offset/limit
1000 $numRows = count($this->mHist);
1001 if( $numRows <= $this->mLimit && $this->mImg->getTimestamp() > $this->mOffset ) {
1002 $this->mHist = array_merge( array($this->mImg), $this->mHist );
1003 }
1004 } else {
1005 // The current rev may not meet the offset
1006 if( !$this->mOffset || $this->mImg->getTimestamp() < $this->mOffset ) {
1007 $this->mHist[] = $this->mImg;
1008 }
1009 // Old image versions (fetch extra row for nav links)
1010 $oiLimit = count($this->mHist) ? $this->mLimit : $this->mLimit+1;
1011 // Fetch the file history
1012 $this->mHist = array_merge( $this->mHist,
1013 $this->mImg->getHistory($oiLimit,$this->mOffset,null,false) );
1014 }
1015 $numRows = count($this->mHist); // Total number of query results
1016 if( $numRows ) {
1017 # Index value of top item in the list
1018 $firstIndex = $this->mIsBackwards ?
1019 $this->mHist[$numRows-1]->getTimestamp() : $this->mHist[0]->getTimestamp();
1020 # Discard the extra result row if there is one
1021 if( $numRows > $this->mLimit && $numRows > 1 ) {
1022 if( $this->mIsBackwards ) {
1023 # Index value of item past the index
1024 $this->mPastTheEndIndex = $this->mHist[0]->getTimestamp();
1025 # Index value of bottom item in the list
1026 $lastIndex = $this->mHist[1]->getTimestamp();
1027 # Display range
1028 $this->mRange = array( 1, $numRows-1 );
1029 } else {
1030 # Index value of item past the index
1031 $this->mPastTheEndIndex = $this->mHist[$numRows-1]->getTimestamp();
1032 # Index value of bottom item in the list
1033 $lastIndex = $this->mHist[$numRows-2]->getTimestamp();
1034 # Display range
1035 $this->mRange = array( 0, $numRows-2 );
1036 }
1037 } else {
1038 # Setting indexes to an empty string means that they will be
1039 # omitted if they would otherwise appear in URLs. It just so
1040 # happens that this is the right thing to do in the standard
1041 # UI, in all the relevant cases.
1042 $this->mPastTheEndIndex = '';
1043 # Index value of bottom item in the list
1044 $lastIndex = $this->mIsBackwards ?
1045 $this->mHist[0]->getTimestamp() : $this->mHist[$numRows-1]->getTimestamp();
1046 # Display range
1047 $this->mRange = array( 0, $numRows-1 );
1048 }
1049 } else {
1050 $firstIndex = '';
1051 $lastIndex = '';
1052 $this->mPastTheEndIndex = '';
1053 }
1054 if( $this->mIsBackwards ) {
1055 $this->mIsFirst = ( $numRows < $queryLimit );
1056 $this->mIsLast = ( $this->mOffset == '' );
1057 $this->mLastShown = $firstIndex;
1058 $this->mFirstShown = $lastIndex;
1059 } else {
1060 $this->mIsFirst = ( $this->mOffset == '' );
1061 $this->mIsLast = ( $numRows < $queryLimit );
1062 $this->mLastShown = $lastIndex;
1063 $this->mFirstShown = $firstIndex;
1064 }
1065 $this->mQueryDone = true;
1066 }
1067 }