Cleanup, html-safety and output
[mediawiki.git] / includes / ImagePage.php
blobf7aec171763b7e58c2b2f44809bda6fbeadc4774
1 <?php
2 /**
3 * @package MediaWiki
4 */
6 /**
8 */
9 if( !defined( 'MEDIAWIKI' ) )
10 die();
12 require_once( 'Image.php' );
14 /**
15 * Special handling for image description pages
16 * @package MediaWiki
18 class ImagePage extends Article {
20 /* private */ var $img; // Image object this page is shown for
21 var $mExtraDescription = false;
23 function render() {
24 global $wgOut;
25 $wgOut->setArticleBodyOnly(true);
26 $wgOut->addWikitext($this->getContent(true));
29 function view() {
30 global $wgUseExternalEditor, $wgOut, $wgShowEXIF;
32 $this->img = new Image( $this->mTitle );
34 if( $this->mTitle->getNamespace() == NS_IMAGE ) {
35 if ($wgShowEXIF && $this->img->exists()) {
36 $exif = $this->img->getExifData();
37 $showmeta = count($exif) ? true : false;
38 } else {
39 $exif = false;
40 $showmeta = false;
43 if ($this->img->exists())
44 $wgOut->addHTML($this->showTOC($showmeta));
46 $this->openShowImage();
47 if ($exif)
48 $wgOut->addWikiText($this->makeMetadataTable($exif));
50 # No need to display noarticletext, we use our own message, output in openShowImage()
51 if( $this->getID() ) {
52 Article::view();
53 } else {
54 # Just need to set the right headers
55 $wgOut->setArticleFlag( true );
56 $wgOut->setRobotpolicy( 'index,follow' );
57 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
58 $wgOut->addMetaTags();
59 $this->viewUpdates();
62 if ($this->mExtraDescription) {
63 $fol = wfMsg('shareddescriptionfollows');
64 if ($fol != '-')
65 $wgOut->addWikiText(wfMsg('shareddescriptionfollows'));
66 $wgOut->addHTML($this->mExtraDescription);
69 $this->closeShowImage();
70 $this->imageHistory();
71 $this->imageLinks();
72 } else {
73 Article::view();
77 /**
78 * Create the TOC
80 * @access private
82 * @param bool $metadata Whether or not to show the metadata link
83 * @return string
85 function showTOC( $metadata ) {
86 global $wgLang;
87 $r = '<ul id="filetoc">
88 <li><a href="#file">' . $wgLang->getNsText( NS_IMAGE ) . '</a></li>' .
89 ($metadata ? '<li><a href="#metadata">' . wfMsg( 'metadata' ) . '</a></li>' : '') . '
90 <li><a href="#filehistory">' . wfMsg( 'imghistory' ) . '</a></li>
91 <li><a href="#filelinks">' . wfMsg( 'imagelinks' ) . '</a></li>
92 </ul>';
93 return $r;
96 /**
97 * Make a table with metadata to be shown in the output page.
99 * @access private
101 * @param array $exif The array containing the EXIF data
102 * @return string
104 function makeMetadataTable( $exif ) {
105 $r = "{| class=metadata align=right width=250px\n";
106 $r .= '|+ id=metadata | '. htmlspecialchars( wfMsg( 'metadata' ) ) . "\n";
107 foreach( $exif as $k => $v ) {
108 $tag = strtolower( $k );
109 $r .= "! class=$tag |" . wfMsg( "exif-$tag" ) . "\n";
110 $r .= "| class=$tag |" . htmlspecialchars( $v ) . "\n";
111 $r .= "|-\n";
113 return substr($r, 0, -3) . '|}';
117 * Overloading Article's getContent method.
118 * Omit noarticletext if sharedupload
120 * @param $noredir If true, do not follow redirects
122 function getContent( $noredir )
124 if ( $this->img && $this->img->fromSharedDirectory && 0 == $this->getID() ) {
125 return '';
127 return Article::getContent( $noredir );
130 function openShowImage()
132 global $wgOut, $wgUser, $wgImageLimits, $wgRequest,
133 $wgUseImageResize, $wgRepositoryBaseUrl,
134 $wgUseExternalEditor, $wgServer, $wgFetchCommonsDescriptions;
135 $full_url = $this->img->getViewURL();
136 $anchoropen = '';
137 $anchorclose = '';
139 if( $wgUser->getOption( 'imagesize' ) == '' ) {
140 $sizeSel = User::getDefaultOption( 'imagesize' );
141 } else {
142 $sizeSel = IntVal( $wgUser->getOption( 'imagesize' ) );
144 if( !isset( $wgImageLimits[$sizeSel] ) ) {
145 $sizeSel = User::getDefaultOption( 'imagesize' );
147 $max = $wgImageLimits[$sizeSel];
148 $maxWidth = $max[0];
149 $maxHeight = $max[1];
150 $sk = $wgUser->getSkin();
152 if ( $this->img->exists() ) {
153 # image
154 $width = $this->img->getWidth();
155 $height = $this->img->getHeight();
156 $showLink = false;
158 if ( $this->img->allowInlineDisplay() and $width and $height) {
159 # image
161 # "Download high res version" link below the image
162 $msg = wfMsg('showbigimage', $width, $height, intval( $this->img->getSize()/1024 ) );
163 if ( $width > $maxWidth ) {
164 $height = floor( $height * $maxWidth / $width );
165 $width = $maxWidth;
167 if ( $height > $maxHeight ) {
168 $width = floor( $width * $maxHeight / $height );
169 $height = $maxHeight;
171 if ( !$this->img->mustRender()
172 && ( $width != $this->img->getWidth() || $height != $this->img->getHeight() ) ) {
173 if( $wgUseImageResize ) {
174 $thumbnail = $this->img->getThumbnail( $width );
175 if ( $thumbnail == null ) {
176 $url = $full_url;
177 } else {
178 $url = $thumbnail->getUrl();
180 } else {
181 # No resize ability? Show the full image, but scale
182 # it down in the browser so it fits on the page.
183 $url = $full_url;
185 $anchoropen = "<a href=\"{$full_url}\">";
186 $anchorclose = "</a><br />\n$anchoropen{$msg}</a>";
187 } else {
188 $url = $full_url;
189 $showLink = $this->img->mustRender();
191 $wgOut->addHTML( '<div class="fullImageLink" id="file">' . $anchoropen .
192 "<img border=\"0\" src=\"{$url}\" width=\"{$width}\" height=\"{$height}\" alt=\"" .
193 htmlspecialchars( $wgRequest->getVal( 'image' ) ).'" />' . $anchorclose . '</div>' );
194 } else {
195 #if direct link is allowed but it's not a renderable image, show an icon.
196 if ($this->img->isSafeFile()) {
197 $icon= $this->img->iconThumb();
199 $wgOut->addHTML( '<div class="fullImageLink" id="file"><a href="' . $full_url . '">' .
200 $icon->toHtml() .
201 '</a></div>' );
204 $showLink = true;
208 if ($showLink) {
209 $filename = wfEscapeWikiText( $this->img->getName() );
210 $info = wfMsg( 'fileinfo',
211 ceil($this->img->getSize()/1024.0),
212 $this->img->getMimeType() );
214 if (!$this->img->isSafeFile()) {
215 $warning = wfMsg( 'mediawarning' );
216 $wgOut->addWikiText( <<<END
217 <div class="fullMedia">
218 <span class="dangerousLink">[[Media:$filename|$filename]]</span>
219 <span class="fileInfo"> ($info)</span>
220 </div>
222 <div class="mediaWarning">$warning</div>
225 } else {
226 $wgOut->addWikiText( <<<END
227 <div class="fullMedia">
228 [[Media:$filename|$filename]] <span class="fileInfo"> ($info)</span>
229 </div>
235 if($this->img->fromSharedDirectory) {
236 $this->printSharedImageText();
238 } else {
239 # Image does not exist
240 $wgOut->addWikiText( wfMsg( 'noimage', $this->getUploadUrl() ) );
244 function printSharedImageText() {
245 global $wgRepositoryBaseUrl, $wgFetchCommonsDescriptions, $wgOut;
247 $url = $wgRepositoryBaseUrl . urlencode($this->mTitle->getDBkey());
248 $sharedtext = "<div class='sharedUploadNotice'>" . wfMsg("sharedupload");
249 if ($wgRepositoryBaseUrl && !$wgFetchCommonsDescriptions) {
250 $sharedtext .= " " . wfMsg("shareduploadwiki", $url);
252 $sharedtext .= "</div>";
253 $wgOut->addWikiText($sharedtext);
255 if ($wgRepositoryBaseUrl && $wgFetchCommonsDescriptions) {
256 require_once("HttpFunctions.php");
257 $ur = ini_set('allow_url_fopen', true);
258 $text = wfGetHTTP($url . '?action=render');
259 ini_set('allow_url_fopen', $ur);
260 if ($text)
261 $this->mExtraDescription = $text;
265 function getUploadUrl() {
266 global $wgServer;
267 $uploadTitle = Title::makeTitle( NS_SPECIAL, 'Upload' );
268 return $wgServer . $uploadTitle->getLocalUrl( 'wpDestFile=' . urlencode( $this->img->getName() ) );
272 function uploadLinksBox()
274 global $wgUser, $wgOut;
276 if ($this->img->fromSharedDirectory)
277 return;
279 $sk = $wgUser->getSkin();
280 $wgOut->addHTML( '<br /><ul><li>' );
281 $wgOut->addWikiText( '<div>'. wfMsg( 'uploadnewversion', $this->getUploadUrl() ) .'</div>' );
282 $wgOut->addHTML( '</li><li>' );
283 $wgOut->addHTML( $sk->makeKnownLinkObj( $this->mTitle,
284 wfMsg( 'edit-externally' ), "action=edit&externaledit=true&mode=file" ) );
285 $wgOut->addWikiText( '<div>' . wfMsg('edit-externally-help') . '</div>' );
286 $wgOut->addHTML( '</li></ul>' );
289 function closeShowImage()
291 # For overloading
296 * If the page we've just displayed is in the "Image" namespace,
297 * we follow it with an upload history of the image and its usage.
299 function imageHistory()
301 global $wgUser, $wgOut, $wgUseExternalEditor;
303 $sk = $wgUser->getSkin();
305 $line = $this->img->nextHistoryLine();
307 if ( $line ) {
308 $list =& new ImageHistoryList( $sk );
309 $s = $list->beginImageHistoryList() .
310 $list->imageHistoryLine( true, wfTimestamp(TS_MW, $line->img_timestamp),
311 $this->mTitle->getDBkey(), $line->img_user,
312 $line->img_user_text, $line->img_size, $line->img_description );
314 while ( $line = $this->img->nextHistoryLine() ) {
315 $s .= $list->imageHistoryLine( false, $line->img_timestamp,
316 $line->oi_archive_name, $line->img_user,
317 $line->img_user_text, $line->img_size, $line->img_description );
319 $s .= $list->endImageHistoryList();
320 } else { $s=''; }
321 $wgOut->addHTML( $s );
323 # Exist check because we don't want to show this on pages where an image
324 # doesn't exist along with the noimage message, that would suck. -ævar
325 if( $wgUseExternalEditor && $this->img->exists() ) {
326 $this->uploadLinksBox();
331 function imageLinks()
333 global $wgUser, $wgOut;
335 $wgOut->addHTML( '<h2 id="filelinks">' . wfMsg( 'imagelinks' ) . "</h2>\n" );
337 $dbr =& wfGetDB( DB_SLAVE );
338 $page = $dbr->tableName( 'page' );
339 $imagelinks = $dbr->tableName( 'imagelinks' );
341 $sql = "SELECT page_namespace,page_title FROM $imagelinks,$page WHERE il_to=" .
342 $dbr->addQuotes( $this->mTitle->getDBkey() ) . " AND il_from=page_id";
343 $sql = $dbr->limitResult($sql, 500, 0);
344 $res = $dbr->query( $sql, "ImagePage::imageLinks" );
346 if ( 0 == $dbr->numRows( $res ) ) {
347 $wgOut->addHtml( '<p>' . wfMsg( "nolinkstoimage" ) . "</p>\n" );
348 return;
350 $wgOut->addHTML( '<p>' . wfMsg( 'linkstoimage' ) . "</p>\n<ul>" );
352 $sk = $wgUser->getSkin();
353 while ( $s = $dbr->fetchObject( $res ) ) {
354 $name = Title::MakeTitle( $s->page_namespace, $s->page_title );
355 $link = $sk->makeKnownLinkObj( $name, "" );
356 $wgOut->addHTML( "<li>{$link}</li>\n" );
358 $wgOut->addHTML( "</ul>\n" );
361 function delete()
363 global $wgUser, $wgOut, $wgRequest;
365 $confirm = $wgRequest->getBool( 'wpConfirmB' );
366 $image = $wgRequest->getVal( 'image' );
367 $oldimage = $wgRequest->getVal( 'oldimage' );
369 # Only sysops can delete images. Previously ordinary users could delete
370 # old revisions, but this is no longer the case.
371 if ( !$wgUser->isAllowed('delete') ) {
372 $wgOut->sysopRequired();
373 return;
375 if ( $wgUser->isBlocked() ) {
376 return $this->blockedIPpage();
378 if ( wfReadOnly() ) {
379 $wgOut->readOnlyPage();
380 return;
383 # Better double-check that it hasn't been deleted yet!
384 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
385 if ( ( !is_null( $image ) )
386 && ( '' == trim( $image ) ) ) {
387 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
388 return;
391 $this->img = new Image( $this->mTitle );
393 # Deleting old images doesn't require confirmation
394 if ( !is_null( $oldimage ) || $confirm ) {
395 if( $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ), $oldimage ) ) {
396 $this->doDelete();
397 } else {
398 $wgOut->fatalError( wfMsg( 'sessionfailure' ) );
400 return;
403 if ( !is_null( $image ) ) {
404 $q = '&image=' . urlencode( $image );
405 } else if ( !is_null( $oldimage ) ) {
406 $q = '&oldimage=' . urlencode( $oldimage );
407 } else {
408 $q = '';
410 return $this->confirmDelete( $q, $wgRequest->getText( 'wpReason' ) );
413 function doDelete()
415 global $wgOut, $wgUser, $wgContLang, $wgRequest;
416 global $wgUseSquid, $wgInternalServer, $wgPostCommitUpdateList;
417 $fname = 'ImagePage::doDelete';
419 $reason = $wgRequest->getVal( 'wpReason' );
420 $oldimage = $wgRequest->getVal( 'oldimage' );
422 $dbw =& wfGetDB( DB_MASTER );
424 if ( !is_null( $oldimage ) ) {
425 if ( strlen( $oldimage ) < 16 ) {
426 $wgOut->unexpectedValueError( 'oldimage', htmlspecialchars($oldimage) );
427 return;
429 if ( strstr( $oldimage, "/" ) || strstr( $oldimage, "\\" ) ) {
430 $wgOut->unexpectedValueError( 'oldimage', htmlspecialchars($oldimage) );
431 return;
434 # Invalidate description page cache
435 $this->mTitle->invalidateCache();
437 # Squid purging
438 if ( $wgUseSquid ) {
439 $urlArr = Array(
440 $wgInternalServer.wfImageArchiveUrl( $oldimage ),
441 $wgInternalServer.$this->mTitle->getFullURL()
443 wfPurgeSquidServers($urlArr);
445 $this->doDeleteOldImage( $oldimage );
446 $dbw->delete( 'oldimage', array( 'oi_archive_name' => $oldimage ) );
447 $deleted = $oldimage;
448 } else {
449 $image = $this->mTitle->getDBkey();
450 $dest = wfImageDir( $image );
451 $archive = wfImageDir( $image );
453 # Delete the image file if it exists; due to sync problems
454 # or manual trimming sometimes the file will be missing.
455 $targetFile = "{$dest}/{$image}";
456 if( file_exists( $targetFile ) && ! @unlink( $targetFile ) ) {
457 # If the deletion operation actually failed, bug out:
458 $wgOut->fileDeleteError( $targetFile );
459 return;
461 $dbw->delete( 'image', array( 'img_name' => $image ) );
462 $res = $dbw->select( 'oldimage', array( 'oi_archive_name' ), array( 'oi_name' => $image ) );
464 # Purge archive URLs from the squid
465 $urlArr = Array();
466 while ( $s = $dbw->fetchObject( $res ) ) {
467 $this->doDeleteOldImage( $s->oi_archive_name );
468 $urlArr[] = $wgInternalServer.wfImageArchiveUrl( $s->oi_archive_name );
471 # And also the HTML of all pages using this image
472 $linksTo = $this->img->getLinksTo();
473 if ( $wgUseSquid ) {
474 $u = SquidUpdate::newFromTitles( $linksTo, $urlArr );
475 array_push( $wgPostCommitUpdateList, $u );
478 $dbw->delete( 'oldimage', array( 'oi_name' => $image ) );
480 # Image itself is now gone, and database is cleaned.
481 # Now we remove the image description page.
483 $article = new Article( $this->mTitle );
484 $article->doDeleteArticle( $reason ); # ignore errors
486 # Invalidate parser cache and client cache for pages using this image
487 # This is left until relatively late to reduce lock time
488 Title::touchArray( $linksTo );
490 /* Delete thumbnails and refresh image metadata cache */
491 $this->img->purgeCache();
494 $deleted = $image;
497 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
498 $wgOut->setRobotpolicy( 'noindex,nofollow' );
500 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
501 $text = wfMsg( 'deletedtext', $deleted, $loglink );
503 $wgOut->addWikiText( $text );
505 $wgOut->returnToMain( false, $this->mTitle->getPrefixedText() );
508 function doDeleteOldImage( $oldimage )
510 global $wgOut;
512 $name = substr( $oldimage, 15 );
513 $archive = wfImageArchiveDir( $name );
515 # Delete the image if it exists. Sometimes the file will be missing
516 # due to manual intervention or weird sync problems; treat that
517 # condition gracefully and continue to delete the database entry.
518 # Also some records may end up with an empty oi_archive_name field
519 # if the original file was missing when a new upload was made;
520 # don't try to delete the directory then!
522 $targetFile = "{$archive}/{$oldimage}";
523 if( $oldimage != '' && file_exists( $targetFile ) && !@unlink( $targetFile ) ) {
524 # If we actually have a file and can't delete it, throw an error.
525 $wgOut->fileDeleteError( "{$archive}/{$oldimage}" );
526 } else {
527 # Log the deletion
528 $log = new LogPage( 'delete' );
529 $log->addEntry( 'delete', $this->mTitle, wfMsg('deletedrevision',$oldimage) );
533 function revert()
535 global $wgOut, $wgRequest, $wgUser;
536 global $wgUseSquid, $wgInternalServer, $wgDeferredUpdateList;
538 $oldimage = $wgRequest->getText( 'oldimage' );
539 if ( strlen( $oldimage ) < 16 ) {
540 $wgOut->unexpectedValueError( 'oldimage', htmlspecialchars($oldimage) );
541 return;
543 if ( strstr( $oldimage, "/" ) || strstr( $oldimage, "\\" ) ) {
544 $wgOut->unexpectedValueError( 'oldimage', htmlspecialchars($oldimage) );
545 return;
548 if ( wfReadOnly() ) {
549 $wgOut->readOnlyPage();
550 return;
552 if( $wgUser->isAnon() ) {
553 $wgOut->errorpage( 'uploadnologin', 'uploadnologintext' );
554 return;
556 if ( ! $this->mTitle->userCanEdit() ) {
557 $wgOut->sysopRequired();
558 return;
560 if ( $wgUser->isBlocked() ) {
561 return $this->blockedIPpage();
563 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ), $oldimage ) ) {
564 $wgOut->errorpage( 'internalerror', 'sessionfailure' );
565 return;
567 $name = substr( $oldimage, 15 );
569 $dest = wfImageDir( $name );
570 $archive = wfImageArchiveDir( $name );
571 $curfile = "{$dest}/{$name}";
573 if ( ! is_file( $curfile ) ) {
574 $wgOut->fileNotFoundError( htmlspecialchars( $curfile ) );
575 return;
577 $oldver = wfTimestampNow() . "!{$name}";
579 $dbr =& wfGetDB( DB_SLAVE );
580 $size = $dbr->selectField( 'oldimage', 'oi_size', array( 'oi_archive_name' => $oldimage ) );
582 if ( ! rename( $curfile, "${archive}/{$oldver}" ) ) {
583 $wgOut->fileRenameError( $curfile, "${archive}/{$oldver}" );
584 return;
586 if ( ! copy( "{$archive}/{$oldimage}", $curfile ) ) {
587 $wgOut->fileCopyError( "${archive}/{$oldimage}", $curfile );
590 # Record upload and update metadata cache
591 $img = Image::newFromName( $name );
592 $img->recordUpload( $oldver, wfMsg( "reverted" ) );
594 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
595 $wgOut->setRobotpolicy( 'noindex,nofollow' );
596 $wgOut->addHTML( wfMsg( 'imagereverted' ) );
598 $descTitle = $img->getTitle();
599 $wgOut->returnToMain( false, $descTitle->getPrefixedText() );
602 function blockedIPpage() {
603 require_once( 'EditPage.php' );
604 $edit = new EditPage( $this );
605 return $edit->blockedIPpage();
611 * @todo document
612 * @package MediaWiki
614 class ImageHistoryList {
615 function ImageHistoryList( &$skin ) {
616 $this->skin =& $skin;
619 function beginImageHistoryList() {
620 $s = "\n<h2 id=\"filehistory\">" . wfMsg( 'imghistory' ) . "</h2>\n" .
621 "<p>" . wfMsg( 'imghistlegend' ) . "</p>\n".'<ul class="special">';
622 return $s;
625 function endImageHistoryList() {
626 $s = "</ul>\n";
627 return $s;
630 function imageHistoryLine( $iscur, $timestamp, $img, $user, $usertext, $size, $description ) {
631 global $wgUser, $wgLang, $wgContLang, $wgTitle;
633 $datetime = $wgLang->timeanddate( $timestamp, true );
634 $del = wfMsg( 'deleteimg' );
635 $delall = wfMsg( 'deleteimgcompletely' );
636 $cur = wfMsg( 'cur' );
638 if ( $iscur ) {
639 $url = Image::imageUrl( $img );
640 $rlink = $cur;
641 if ( $wgUser->isAllowed('delete') ) {
642 $link = $wgTitle->escapeLocalURL( 'image=' . $wgTitle->getPartialURL() .
643 '&action=delete' );
644 $style = $this->skin->getInternalLinkAttributes( $link, $delall );
646 $dlink = '<a href="'.$link.'"'.$style.'>'.$delall.'</a>';
647 } else {
648 $dlink = $del;
650 } else {
651 $url = htmlspecialchars( wfImageArchiveUrl( $img ) );
652 if( $wgUser->getID() != 0 && $wgTitle->userCanEdit() ) {
653 $token = urlencode( $wgUser->editToken( $img ) );
654 $rlink = $this->skin->makeKnownLinkObj( $wgTitle,
655 wfMsg( 'revertimg' ), 'action=revert&oldimage=' .
656 urlencode( $img ) . "&wpEditToken=$token" );
657 $dlink = $this->skin->makeKnownLinkObj( $wgTitle,
658 $del, 'action=delete&oldimage=' . urlencode( $img ) .
659 "&wpEditToken=$token" );
660 } else {
661 # Having live active links for non-logged in users
662 # means that bots and spiders crawling our site can
663 # inadvertently change content. Baaaad idea.
664 $rlink = wfMsg( 'revertimg' );
665 $dlink = $del;
668 if ( 0 == $user ) {
669 $userlink = $usertext;
670 } else {
671 $userlink = $this->skin->makeLinkObj(
672 Title::makeTitle( NS_USER, $usertext ),
673 $usertext );
675 $nbytes = wfMsg( 'nbytes', $size );
676 $style = $this->skin->getInternalLinkAttributes( $url, $datetime );
678 $s = "<li> ({$dlink}) ({$rlink}) <a href=\"{$url}\"{$style}>{$datetime}</a>"
679 . " . . {$userlink} ({$nbytes})";
681 $s .= $this->skin->commentBlock( $description, $wgTitle );
682 $s .= "</li>\n";
683 return $s;