URL-encode the content-disposition suggested filename for XML export data.
[lhc/web/wiklou.git] / includes / ImagePage.php
index 1105661..3265b7f 100644 (file)
@@ -1,72 +1,96 @@
 <?php
 /**
- * @package MediaWiki
  */
 
 /**
  *
  */
 if( !defined( 'MEDIAWIKI' ) )
-       die();
-
-require_once( 'Image.php' );
+       die( 1 );
 
 /**
  * Special handling for image description pages
- * @package MediaWiki
+ *
+ * @addtogroup Media
  */
 class ImagePage extends Article {
 
        /* private */ var $img;  // Image object this page is shown for
        var $mExtraDescription = false;
 
+       function __construct( $title ) {
+               parent::__construct( $title );
+               $this->img = wfFindFile( $this->mTitle );
+               if ( !$this->img ) {
+                       $this->img = wfLocalFile( $this->mTitle );
+               }
+       }
+
+       /**
+        * Handler for action=render
+        * Include body text only; none of the image extras
+        */
        function render() {
                global $wgOut;
-               $wgOut->setArticleBodyOnly(true);
-               $wgOut->addWikitext($this->getContent(true));
+               $wgOut->setArticleBodyOnly( true );
+               $wgOut->addSecondaryWikitext( $this->getContent() );
        }
 
        function view() {
-               global $wgUseExternalEditor, $wgOut, $wgShowEXIF;
-
-               $this->img = new Image( $this->mTitle );
+               global $wgOut, $wgShowEXIF, $wgRequest, $wgUser;
 
-               if( $this->mTitle->getNamespace() == NS_IMAGE  ) {
-                       if ($wgShowEXIF && $this->img->exists()) {
-                               $exif = $this->img->getExifData();
-                               $showmeta = count($exif) ? true : false;
-                       } else {
-                               $exif = false;
-                               $showmeta = false;
-                       }
+               $diff = $wgRequest->getVal( 'diff' );
+               $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
 
-                       if ($this->img->exists())
-                               $wgOut->addHTML($this->showTOC($showmeta));
+               if ( $this->mTitle->getNamespace() != NS_IMAGE || ( isset( $diff ) && $diffOnly ) )
+                       return Article::view();
 
-                       $this->openShowImage();
-                       if ($exif)
-                               $wgOut->addWikiText($this->makeMetadataTable($exif));
+               if ($wgShowEXIF && $this->img->exists()) {
+                       $exif = $this->img->getExifData();
+                       $showmeta = count($exif) ? true : false;
+               } else {
+                       $exif = false;
+                       $showmeta = false;
+               }
 
-                       # No need to display noarticletext, we use our own message, output in openShowImage()
-                       if( $this->getID() ) {
-                               Article::view();
-                       } else {
-                               # Just need to set the right headers
-                               $wgOut->setArticleFlag( true );
-                               $wgOut->setRobotpolicy( 'index,follow' );
-                               $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
-                               $wgOut->addMetaTags();
-                               $this->viewUpdates();
-                       }
+               if ($this->img->exists())
+                       $wgOut->addHTML($this->showTOC($showmeta));
 
-                       if ($this->mExtraDescription)
-                               $wgOut->addWikiText($this->mExtraDescription);
+               $this->openShowImage();
 
-                       $this->closeShowImage();
-                       $this->imageHistory();
-                       $this->imageLinks();
-               } else {
+               # No need to display noarticletext, we use our own message, output in openShowImage()
+               if ( $this->getID() ) {
                        Article::view();
+               } else {
+                       # Just need to set the right headers
+                       $wgOut->setArticleFlag( true );
+                       $wgOut->setRobotpolicy( 'index,follow' );
+                       $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
+                       $this->viewUpdates();
+               }
+
+               # Show shared description, if needed
+               if ( $this->mExtraDescription ) {
+                       $fol = wfMsg( 'shareddescriptionfollows' );
+                       if( $fol != '-' && !wfEmptyMsg( 'shareddescriptionfollows', $fol ) ) {
+                               $wgOut->addWikiText( $fol );
+                       }
+                       $wgOut->addHTML( '<div id="shared-image-desc">' . $this->mExtraDescription . '</div>' );
+               }
+
+               $this->closeShowImage();
+               $this->imageHistory();
+               $this->imageLinks();
+
+               if ( $exif ) {
+                       global $wgStylePath, $wgStyleVersion;
+                       $expand = htmlspecialchars( wfEscapeJsString( wfMsg( 'metadata-expand' ) ) );
+                       $collapse = htmlspecialchars( wfEscapeJsString( wfMsg( 'metadata-collapse' ) ) );
+                       $wgOut->addHTML( Xml::element( 'h2', array( 'id' => 'metadata' ), wfMsg( 'metadata' ) ). "\n" );
+                       $wgOut->addWikiText( $this->makeMetadataTable( $exif ) );
+                       $wgOut->addHTML(
+                               "<script type=\"text/javascript\" src=\"$wgStylePath/common/metadata.js?$wgStyleVersion\"></script>\n" .
+                               "<script type=\"text/javascript\">attachMetadataToggle('mw_metadata', '$expand', '$collapse');</script>\n" );
                }
        }
 
@@ -81,10 +105,10 @@ class ImagePage extends Article {
        function showTOC( $metadata ) {
                global $wgLang;
                $r = '<ul id="filetoc">
-                       <li><a href="#file">' . $wgLang->getNsText( NS_IMAGE ) . '</a></li>' .
-                       ($metadata ? '<li><a href="#metadata">' . wfMsg( 'metadata' ) . '</a></li>' : '') . '
-                       <li><a href="#filehistory">' . wfMsg( 'imghistory' ) . '</a></li>
-                       <li><a href="#filelinks">' . wfMsg( 'imagelinks' ) . '</a></li>
+                       <li><a href="#file">' . $wgLang->getNsText( NS_IMAGE ) . '</a></li>
+                       <li><a href="#filehistory">' . wfMsgHtml( 'imghistory' ) . '</a></li>
+                       <li><a href="#filelinks">' . wfMsgHtml( 'imagelinks' ) . '</a></li>' .
+                       ($metadata ? ' <li><a href="#metadata">' . wfMsgHtml( 'metadata' ) . '</a></li>' : '') . '
                </ul>';
                return $r;
        }
@@ -98,47 +122,71 @@ class ImagePage extends Article {
         * @return string
         */
        function makeMetadataTable( $exif ) {
-               $r = "{| class=metadata align=right width=250px\n";
-               $r .= '|+ id=metadata | '. htmlspecialchars( wfMsg( 'metadata' ) ) . "\n";
+               $r = wfMsg( 'metadata-help' ) . "\n\n";
+               $r .= "{| id=mw_metadata class=mw_metadata\n";
+               $visibleFields = $this->visibleMetadataFields();
                foreach( $exif as $k => $v ) {
                        $tag = strtolower( $k );
-                       $r .= "! class=$tag |" . wfMsg( "exif-$tag" ) . "\n";
-                       $r .= "| class=$tag |" . htmlspecialchars( $v ) . "\n";
-                       $r .= "|-\n";
+                       $msg = wfMsg( "exif-$tag" );
+                       $class = "exif-$tag";
+                       if( !in_array( $tag, $visibleFields ) ) {
+                               $class .= ' collapsable';
+                       }
+                       $r .= "|- class=\"$class\"\n";
+                       $r .= "!| $msg\n";
+                       $r .= "|| $v\n";
                }
-               return substr($r, 0, -3) . '|}';
+               $r .= '|}';
+               return $r;
        }
 
        /**
-        * Overloading Article's getContent method.
-        * Omit noarticletext if sharedupload
+        * Get a list of EXIF metadata items which should be displayed when
+        * the metadata table is collapsed.
         *
-        * @param $noredir If true, do not follow redirects
+        * @return array of strings
+        * @access private
         */
-       function getContent( $noredir )
-       {
-               if ( $this->img && $this->img->fromSharedDirectory && 0 == $this->getID() ) {
-                       return '';
+       function visibleMetadataFields() {
+               $fields = array();
+               $lines = explode( "\n", wfMsgForContent( 'metadata-fields' ) );
+               foreach( $lines as $line ) {
+                       $matches = array();
+                       if( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
+                               $fields[] = $matches[1];
+                       }
                }
-               return Article::getContent( $noredir );
+               return $fields;
        }
 
-       function openShowImage()
-       {
-               global $wgOut, $wgUser, $wgImageLimits, $wgRequest,
-                      $wgUseImageResize, $wgRepositoryBaseUrl,
-                      $wgUseExternalEditor, $wgServer, $wgFetchCommonsDescriptions;
-               $full_url  = $this->img->getViewURL();
-               $anchoropen = '';
-               $anchorclose = '';
-
-               if( $wgUser->getOption( 'imagesize' ) == '' ) {
-                       $sizeSel = User::getDefaultOption( 'imagesize' );
-               } else {
-                       $sizeSel = IntVal( $wgUser->getOption( 'imagesize' ) );
+       /**
+        * Overloading Article's getContent method.
+        * 
+        * Omit noarticletext if sharedupload; text will be fetched from the
+        * shared upload server if possible.
+        */
+       function getContent() {
+               if( $this->img && !$this->img->isLocal() && 0 == $this->getID() ) {
+                       return '';
                }
+               return Article::getContent();
+       }
+
+       function openShowImage() {
+               global $wgOut, $wgUser, $wgImageLimits, $wgRequest, $wgLang;
+
+               $full_url  = $this->img->getURL();
+               $linkAttribs = false;
+               $sizeSel = intval( $wgUser->getOption( 'imagesize') );
                if( !isset( $wgImageLimits[$sizeSel] ) ) {
                        $sizeSel = User::getDefaultOption( 'imagesize' );
+
+                       // The user offset might still be incorrect, specially if
+                       // $wgImageLimits got changed (see bug #8858).
+                       if( !isset( $wgImageLimits[$sizeSel] ) ) {
+                               // Default to the first offset in $wgImageLimits
+                               $sizeSel = 0;
+                       }
                }
                $max = $wgImageLimits[$sizeSel];
                $maxWidth = $max[0];
@@ -147,46 +195,118 @@ class ImagePage extends Article {
 
                if ( $this->img->exists() ) {
                        # image
-                       $width = $this->img->getWidth();
-                       $height = $this->img->getHeight();
+                       $page = $wgRequest->getIntOrNull( 'page' );
+                       if ( is_null( $page ) ) {
+                               $params = array();
+                               $page = 1;
+                       } else {
+                               $params = array( 'page' => $page );
+                       }
+                       $width_orig = $this->img->getWidth();
+                       $width = $width_orig;
+                       $height_orig = $this->img->getHeight();
+                       $height = $height_orig;
+                       $mime = $this->img->getMimeType();
                        $showLink = false;
+                       $linkAttribs = array( 'href' => $full_url );
+
+      wfRunHooks( 'ImageOpenShowImageInlineBefore', array( &$this , &$wgOut ) )        ;
 
                        if ( $this->img->allowInlineDisplay() and $width and $height) {
                                # image
 
                                # "Download high res version" link below the image
-                               $msg = wfMsg('showbigimage', $width, $height, intval( $this->img->getSize()/1024 ) );
-                               if ( $width > $maxWidth ) {
-                                       $height = floor( $height * $maxWidth / $width );
-                                       $width  = $maxWidth;
+                               $msgsize = wfMsgHtml('file-info-size', $width_orig, $height_orig, $sk->formatSize( $this->img->getSize() ), $mime );
+                               # We'll show a thumbnail of this image
+                               if ( $width > $maxWidth || $height > $maxHeight ) {
+                                       # Calculate the thumbnail size.
+                                       # First case, the limiting factor is the width, not the height.
+                                       if ( $width / $height >= $maxWidth / $maxHeight ) {
+                                               $height = round( $height * $maxWidth / $width);
+                                               $width = $maxWidth;
+                                               # Note that $height <= $maxHeight now.
+                                       } else {
+                                               $newwidth = floor( $width * $maxHeight / $height);
+                                               $height = round( $height * $newwidth / $width );
+                                               $width = $newwidth;
+                                               # Note that $height <= $maxHeight now, but might not be identical
+                                               # because of rounding.
+                                       }
+                                       $msgbig  = wfMsgHtml( 'show-big-image' );
+                                       $msgsmall = wfMsgExt( 'show-big-image-thumb',
+                                               array( 'parseinline' ), $width, $height );
+                               } else {
+                                       # Image is small enough to show full size on image page
+                                       $msgbig = htmlspecialchars( $this->img->getName() );
+                                       $msgsmall = wfMsgExt( 'file-nohires', array( 'parseinline' ) );
+                               }
+
+                               $params['width'] = $width;
+                               $thumbnail = $this->img->transform( $params );
+
+                               $anchorclose = "<br />";
+                               if( $this->img->mustRender() ) {
+                                       $showLink = true;
+                               } else {
+                                       $anchorclose .= 
+                                               $msgsmall .
+                                               '<br />' . Xml::tags( 'a', $linkAttribs,  $msgbig ) . ' ' . $msgsize;
+                               }
+
+                               if ( $this->img->isMultipage() ) {
+                                       $wgOut->addHTML( '<table class="multipageimage"><tr><td>' );
                                }
-                               if ( $height > $maxHeight ) {
-                                       $width = floor( $width * $maxHeight / $height );
-                                       $height = $maxHeight;
+
+                               $imgAttribs = array(
+                                       'border' => 0,
+                                       'alt' => $this->img->getTitle()->getPrefixedText()
+                               );
+
+                               if ( $thumbnail ) {
+                                       $wgOut->addHTML( '<div class="fullImageLink" id="file">' . 
+                                               $thumbnail->toHtml( $imgAttribs, $linkAttribs ) .
+                                               $anchorclose . '</div>' );
                                }
-                               if ( !$this->img->mustRender()
-                                  && ( $width != $this->img->getWidth() || $height != $this->img->getHeight() ) ) {
-                                       if( $wgUseImageResize ) {
-                                               $thumbnail = $this->img->getThumbnail( $width );
-                                               if ( $thumbnail == null ) {
-                                                       $url = $full_url;
-                                               } else {
-                                                       $url = $thumbnail->getUrl();
-                                               }
+
+                               if ( $this->img->isMultipage() ) {
+                                       $count = $this->img->pageCount();
+
+                                       if ( $page > 1 ) {
+                                               $label = $wgOut->parse( wfMsg( 'imgmultipageprev' ), false );
+                                               $link = $sk->makeKnownLinkObj( $this->mTitle, $label, 'page='. ($page-1) );
+                                               $thumb1 = $sk->makeThumbLinkObj( $this->mTitle, $this->img, $link, $label, 'none', 
+                                                       array( 'page' => $page - 1 ) );
                                        } else {
-                                               # No resize ability? Show the full image, but scale
-                                               # it down in the browser so it fits on the page.
-                                               $url = $full_url;
+                                               $thumb1 = '';
                                        }
-                                       $anchoropen  = "<a href=\"{$full_url}\">";
-                                       $anchorclose = "</a><br />\n$anchoropen{$msg}</a>";
-                               } else {
-                                       $url = $full_url;
-                                       $showLink = $this->img->mustRender();
+
+                                       if ( $page < $count ) {
+                                               $label = wfMsg( 'imgmultipagenext' );
+                                               $link = $sk->makeKnownLinkObj( $this->mTitle, $label, 'page='. ($page+1) );
+                                               $thumb2 = $sk->makeThumbLinkObj( $this->mTitle, $this->img, $link, $label, 'none', 
+                                                       array( 'page' => $page + 1 ) );
+                                       } else {
+                                               $thumb2 = '';
+                                       }
+
+                                       global $wgScript;
+                                       $select = '<form name="pageselector" action="' . 
+                                               htmlspecialchars( $wgScript ) .
+                                               '" method="get" onchange="document.pageselector.submit();">' .
+                                               Xml::hidden( 'title', $this->getTitle()->getPrefixedDbKey() );
+                                       $select .= $wgOut->parse( wfMsg( 'imgmultigotopre' ), false ) .
+                                               ' <select id="pageselector" name="page">';
+                                       for ( $i=1; $i <= $count; $i++ ) {
+                                               $select .= Xml::option( $wgLang->formatNum( $i ), $i,
+                                                       $i == $page );
+                                       }
+                                       $select .= '</select>' . $wgOut->parse( wfMsg( 'imgmultigotopost' ), false ) .
+                                               '<input type="submit" value="' .
+                                               htmlspecialchars( wfMsg( 'imgmultigo' ) ) . '"></form>';
+
+                                       $wgOut->addHTML( '</td><td><div class="multipageimagenavbox">' .
+                                               "$select<hr />$thumb1\n$thumb2<br clear=\"all\" /></div></td></tr></table>" );
                                }
-                               $wgOut->addHTML( '<div class="fullImageLink" id="file">' . $anchoropen .
-                                    "<img border=\"0\" src=\"{$url}\" width=\"{$width}\" height=\"{$height}\" alt=\"" .
-                                    htmlspecialchars( $wgRequest->getVal( 'image' ) ).'" />' . $anchorclose . '</div>' );
                        } else {
                                #if direct link is allowed but it's not a renderable image, show an icon.
                                if ($this->img->isSafeFile()) {
@@ -202,88 +322,104 @@ class ImagePage extends Article {
 
 
                        if ($showLink) {
-                               $s= $sk->makeMediaLink( $this->img->getName(), '', '', true );
-                               $info= wfMsg( 'fileinfo', ceil($this->img->getSize()/1024.0), $this->img->getMimeType() );
+                               // Workaround for incorrect MIME type on SVGs uploaded in previous versions
+                               if ($mime == 'image/svg') $mime = 'image/svg+xml';
 
-                               if (!$this->img->isSafeFile()) {
-                                       $wgOut->addHTML("<div class=\"fullMedia\">");
-                                       $wgOut->addHTML("<span class=\"dangerousLink\">");
-                                       $wgOut->addHTML($s);
-                                       $wgOut->addHTML("</span>");
-
-                                       $wgOut->addHTML("<span class=\"fileInfo\"> (");
-                                       $wgOut->addWikiText( $info, false );
-                                       $wgOut->addHTML(")</span>");
-                                       $wgOut->addHTML("</div>");
+                               $filename = wfEscapeWikiText( $this->img->getName() );
+                               $info = wfMsg( 'file-info', $sk->formatSize( $this->img->getSize() ), $mime );
+                               $infores = '';
 
-                                       #this should be formated a little nicer. Is CSS sufficient?
-                                       $wgOut->addHTML("<div class=\"mediaWarning\">");
-                                       $wgOut->addWikiText( wfMsg( 'mediawarning' ) );
-                                       $wgOut->addHTML('</div>');
+                               // Check for MIME type. Other types may have more information in the future.
+                               if (substr($mime,0,9) == 'image/svg' ) {
+                                       $infores = wfMsg('file-svg', $width_orig, $height_orig ) . '<br />';
+                               }
 
+                               global $wgContLang;
+                               $dirmark = $wgContLang->getDirMark();
+                               if (!$this->img->isSafeFile()) {
+                                       $warning = wfMsg( 'mediawarning' );
+                                       $wgOut->addWikiText( <<<EOT
+<div class="fullMedia">$infores
+<span class="dangerousLink">[[Media:$filename|$filename]]</span>$dirmark
+<span class="fileInfo"> $info</span>
+</div>
+
+<div class="mediaWarning">$warning</div>
+EOT
+                                               );
                                } else {
-                                       $wgOut->addHTML("<div class=\"fullMedia\">");
-                                       $wgOut->addHTML($s);
-
-                                       $wgOut->addHTML("<span class=\"fileInfo\"> (");
-                                       $wgOut->addWikiText( $info, false );
-                                       $wgOut->addHTML(")</span>");
-
-                                       $wgOut->addHTML("</div>");
+                                       $wgOut->addWikiText( <<<EOT
+<div class="fullMedia">$infores
+[[Media:$filename|$filename]]$dirmark <span class="fileInfo"> $info</span>
+</div>
+EOT
+                                               );
                                }
                        }
 
-                       if($this->img->fromSharedDirectory) {
+                       if(!$this->img->isLocal()) {
                                $this->printSharedImageText();
                        }
                } else {
                        # Image does not exist
-                       $wgOut->addWikiText( wfMsg( 'noimage', $this->getUploadUrl() ) );
+
+                       $title = SpecialPage::getTitleFor( 'Upload' );
+                       $link = $sk->makeKnownLinkObj($title, wfMsgHtml('noimage-linktext'),
+                               'wpDestFile=' . urlencode( $this->img->getName() ) );
+                       $wgOut->addHTML( wfMsgWikiHtml( 'noimage', $link ) );
                }
        }
 
        function printSharedImageText() {
-               global $wgRepositoryBaseUrl, $wgFetchCommonsDescriptions, $wgOut;
-
-               $url = $wgRepositoryBaseUrl . urlencode($this->mTitle->getDBkey());
-               $sharedtext = "<div class='sharedUploadNotice'>" . wfMsg("sharedupload");
-               if ($wgRepositoryBaseUrl && !$wgFetchCommonsDescriptions) {
-                       $sharedtext .= " " . wfMsg("shareduploadwiki", $url);
+               global $wgOut, $wgUser;
+
+               $descUrl = $this->img->getDescriptionUrl();
+               $descText = $this->img->getDescriptionText();
+               $s = "<div class='sharedUploadNotice'>" . wfMsgWikiHtml("sharedupload");
+               if ( $descUrl && !$descText) {
+                       $sk = $wgUser->getSkin();
+                       $link = $sk->makeExternalLink( $descUrl, wfMsg('shareduploadwiki-linktext') );
+                       $s .= " " . wfMsgWikiHtml('shareduploadwiki', $link);
                }
-               $sharedtext .= "</div>";
-               $wgOut->addWikiText($sharedtext);
+               $s .= "</div>";
+               $wgOut->addHTML($s);
 
-               if ($wgRepositoryBaseUrl && $wgFetchCommonsDescriptions) {
-                       $ur = ini_set('allow_url_fopen', true);
-                       $text = wfGetHTTP($url . '?action=render');
-                       ini_set('allow_url_fopen', $ur);
-                       if ($text)
-                               $this->mExtraDescription = $text;
+               if ( $descText ) {
+                       $this->mExtraDescription = $descText;
                }
        }
 
        function getUploadUrl() {
                global $wgServer;
-               $uploadTitle = Title::makeTitle( NS_SPECIAL, 'Upload' );
+               $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
                return $wgServer . $uploadTitle->getLocalUrl( 'wpDestFile=' . urlencode( $this->img->getName() ) );
        }
 
-
-       function uploadLinksBox()
-       {
+       /**
+        * Print out the various links at the bottom of the image page, e.g. reupload,
+        * external editing (and instructions link) etc.
+        */
+       function uploadLinksBox() {
                global $wgUser, $wgOut;
 
-               if ($this->img->fromSharedDirectory)
+               if( !$this->img->isLocal() )
                        return;
 
                $sk = $wgUser->getSkin();
-               $wgOut->addHTML( '<br /><ul><li>' );
-               $wgOut->addWikiText( '<div>'. wfMsg( 'uploadnewversion', $this->getUploadUrl() ) .'</div>' );
-               $wgOut->addHTML( '</li><li>' );
-               $wgOut->addHTML( $sk->makeKnownLinkObj( $this->mTitle,
-                       wfMsg( 'edit-externally' ), "action=edit&externaledit=true&mode=file" ) );
-               $wgOut->addWikiText( '<div>' .  wfMsg('edit-externally-help') . '</div>' );
-               $wgOut->addHTML( '</li></ul>' );
+               
+               $wgOut->addHtml( '<br /><ul>' );
+               
+               # "Upload a new version of this file" link
+               if( UploadForm::userCanReUpload($wgUser,$this->img->name) ) {
+                       $ulink = $sk->makeExternalLink( $this->getUploadUrl(), wfMsg( 'uploadnewversion-linktext' ) );
+                       $wgOut->addHtml( "<li><div class='plainlinks'>{$ulink}</div></li>" );
+               }
+               
+               # External editing link
+               $elink = $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'edit-externally' ), 'action=edit&externaledit=true&mode=file' );
+               $wgOut->addHtml( '<li>' . $elink . '<div>' . wfMsgWikiHtml( 'edit-externally-help' ) . '</div></li>' );
+               
+               $wgOut->addHtml( '</ul>' );
        }
 
        function closeShowImage()
@@ -305,21 +441,27 @@ class ImagePage extends Article {
                $line = $this->img->nextHistoryLine();
 
                if ( $line ) {
-                       $list =& new ImageHistoryList( $sk );
+                       $list = new ImageHistoryList( $sk, $this->img );
                        $s = $list->beginImageHistoryList() .
-                               $list->imageHistoryLine( true, $line->img_timestamp,
+                               $list->imageHistoryLine( true, wfTimestamp(TS_MW, $line->img_timestamp),
                                        $this->mTitle->getDBkey(),  $line->img_user,
-                                       $line->img_user_text, $line->img_size, $line->img_description );
+                                       $line->img_user_text, $line->img_size, $line->img_description,
+                                       $line->img_width, $line->img_height
+                               );
 
                        while ( $line = $this->img->nextHistoryLine() ) {
                                $s .= $list->imageHistoryLine( false, $line->img_timestamp,
-                               $line->oi_archive_name, $line->img_user,
-                               $line->img_user_text, $line->img_size, $line->img_description );
+                                       $line->oi_archive_name, $line->img_user,
+                                       $line->img_user_text, $line->img_size, $line->img_description,
+                                       $line->img_width, $line->img_height
+                               );
                        }
                        $s .= $list->endImageHistoryList();
                } else { $s=''; }
                $wgOut->addHTML( $s );
 
+               $this->img->resetHistory();     // free db resources
+
                # Exist check because we don't want to show this on pages where an image
                # doesn't exist along with the noimage message, that would suck. -ævar
                if( $wgUseExternalEditor && $this->img->exists() ) {
@@ -332,15 +474,15 @@ class ImagePage extends Article {
        {
                global $wgUser, $wgOut;
 
-               $wgOut->addHTML( '<h2 id="filelinks">' . wfMsg( 'imagelinks' ) . "</h2>\n" );
+               $wgOut->addHTML( Xml::element( 'h2', array( 'id' => 'filelinks' ), wfMsg( 'imagelinks' ) ) . "\n" );
 
-               $dbr =& wfGetDB( DB_SLAVE );
+               $dbr = wfGetDB( DB_SLAVE );
                $page = $dbr->tableName( 'page' );
                $imagelinks = $dbr->tableName( 'imagelinks' );
 
                $sql = "SELECT page_namespace,page_title FROM $imagelinks,$page WHERE il_to=" .
-                 $dbr->addQuotes( $this->mTitle->getDBkey() ) . " AND il_from=page_id"
-                 . " LIMIT 500"; # quickie emergency brake
+                 $dbr->addQuotes( $this->mTitle->getDBkey() ) . " AND il_from=page_id";
+               $sql = $dbr->limitResult($sql, 500, 0);
                $res = $dbr->query( $sql, "ImagePage::imageLinks" );
 
                if ( 0 == $dbr->numRows( $res ) ) {
@@ -362,18 +504,26 @@ class ImagePage extends Article {
        {
                global $wgUser, $wgOut, $wgRequest;
 
-               $confirm = $wgRequest->getBool( 'wpConfirmB' );
+               if ( !$this->img->exists() || !$this->img->isLocal() ) {
+                       # Use standard article deletion
+                       Article::delete();
+                       return;
+               }
+
+               $confirm = $wgRequest->wasPosted();
+               $reason = $wgRequest->getVal( 'wpReason' );
                $image = $wgRequest->getVal( 'image' );
                $oldimage = $wgRequest->getVal( 'oldimage' );
 
                # Only sysops can delete images. Previously ordinary users could delete
                # old revisions, but this is no longer the case.
                if ( !$wgUser->isAllowed('delete') ) {
-                       $wgOut->sysopRequired();
+                       $wgOut->permissionRequired( 'delete' );
                        return;
                }
                if ( $wgUser->isBlocked() ) {
-                       return $this->blockedIPpage();
+                       $wgOut->blockedPage();
+                       return;
                }
                if ( wfReadOnly() ) {
                        $wgOut->readOnlyPage();
@@ -384,18 +534,16 @@ class ImagePage extends Article {
                $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
                if ( ( !is_null( $image ) )
                  && ( '' == trim( $image ) ) ) {
-                       $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
+                       $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
                        return;
                }
 
-               $this->img  = new Image( $this->mTitle );
-
                # Deleting old images doesn't require confirmation
                if ( !is_null( $oldimage ) || $confirm ) {
                        if( $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ), $oldimage ) ) {
-                               $this->doDelete();
+                               $this->doDeleteImage( $reason );
                        } else {
-                               $wgOut->fatalError( wfMsg( 'sessionfailure' ) );
+                               $wgOut->showFatalError( wfMsg( 'sessionfailure' ) );
                        }
                        return;
                }
@@ -410,88 +558,46 @@ class ImagePage extends Article {
                return $this->confirmDelete( $q, $wgRequest->getText( 'wpReason' ) );
        }
 
-       function doDelete()
-       {
-               global $wgOut, $wgUser, $wgContLang, $wgRequest;
-               global $wgUseSquid, $wgInternalServer, $wgPostCommitUpdateList;
-               $fname = 'ImagePage::doDelete';
+       /*
+        * Delete an image.
+        * Called doDeleteImage() not doDelete() so that Article::delete() doesn't 
+        * call back to here.
+        *
+        * @param $reason User provided reason for deletion.
+        */
+       function doDeleteImage( $reason ) {
+               global $wgOut, $wgRequest;
 
-               $reason = $wgRequest->getVal( 'wpReason' );
                $oldimage = $wgRequest->getVal( 'oldimage' );
 
-               $dbw =& wfGetDB( DB_MASTER );
-
                if ( !is_null( $oldimage ) ) {
                        if ( strlen( $oldimage ) < 16 ) {
-                               $wgOut->unexpectedValueError( 'oldimage', htmlspecialchars($oldimage) );
+                               $wgOut->showUnexpectedValueError( 'oldimage', htmlspecialchars($oldimage) );
                                return;
                        }
                        if ( strstr( $oldimage, "/" ) || strstr( $oldimage, "\\" ) ) {
-                               $wgOut->unexpectedValueError( 'oldimage', htmlspecialchars($oldimage) );
+                               $wgOut->showUnexpectedValueError( 'oldimage', htmlspecialchars($oldimage) );
                                return;
                        }
-
-                       # Invalidate description page cache
-                       $this->mTitle->invalidateCache();
-
-                       # Squid purging
-                       if ( $wgUseSquid ) {
-                               $urlArr = Array(
-                                       $wgInternalServer.wfImageArchiveUrl( $oldimage ),
-                                       $wgInternalServer.$this->mTitle->getFullURL()
-                               );
-                               wfPurgeSquidServers($urlArr);
+                       if ( !$this->doDeleteOldImage( $oldimage ) ) {
+                               return;
                        }
-                       $this->doDeleteOldImage( $oldimage );
-                       $dbw->delete( 'oldimage', array( 'oi_archive_name' => $oldimage ) );
                        $deleted = $oldimage;
                } else {
-                       $image = $this->mTitle->getDBkey();
-                       $dest = wfImageDir( $image );
-                       $archive = wfImageDir( $image );
-
-                       # Delete the image file if it exists; due to sync problems
-                       # or manual trimming sometimes the file will be missing.
-                       $targetFile = "{$dest}/{$image}";
-                       if( file_exists( $targetFile ) && ! @unlink( $targetFile ) ) {
+                       $ok = $this->img->delete( $reason );
+                       if( !$ok ) {
                                # If the deletion operation actually failed, bug out:
-                               $wgOut->fileDeleteError( $targetFile );
+                               $wgOut->showFileDeleteError( $this->img->getName() );
                                return;
                        }
-                       $dbw->delete( 'image', array( 'img_name' => $image ) );
-                       $res = $dbw->select( 'oldimage', array( 'oi_archive_name' ), array( 'oi_name' => $image ) );
-
-                       # Purge archive URLs from the squid
-                       $urlArr = Array();
-                       while ( $s = $dbw->fetchObject( $res ) ) {
-                               $this->doDeleteOldImage( $s->oi_archive_name );
-                               $urlArr[] = $wgInternalServer.wfImageArchiveUrl( $s->oi_archive_name );
-                       }
-
-                       # And also the HTML of all pages using this image
-                       $linksTo = $this->img->getLinksTo();
-                       if ( $wgUseSquid ) {
-                               $u = SquidUpdate::newFromTitles( $linksTo, $urlArr );
-                               array_push( $wgPostCommitUpdateList, $u );
-                       }
-
-                       $dbw->delete( 'oldimage', array( 'oi_name' => $image ) );
-
+                       
                        # Image itself is now gone, and database is cleaned.
                        # Now we remove the image description page.
-
+       
                        $article = new Article( $this->mTitle );
                        $article->doDeleteArticle( $reason ); # ignore errors
 
-                       # Invalidate parser cache and client cache for pages using this image
-                       # This is left until relatively late to reduce lock time
-                       Title::touchArray( $linksTo );
-
-                       /* Delete thumbnails and refresh image metadata cache */
-                       $this->img->purgeCache();
-
-
-                       $deleted = $image;
+                       $deleted = $this->img->getName();
                }
 
                $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
@@ -505,43 +611,36 @@ class ImagePage extends Article {
                $wgOut->returnToMain( false, $this->mTitle->getPrefixedText() );
        }
 
+       /**
+        * @return success
+        */
        function doDeleteOldImage( $oldimage )
        {
                global $wgOut;
 
-               $name = substr( $oldimage, 15 );
-               $archive = wfImageArchiveDir( $name );
-
-               # Delete the image if it exists. Sometimes the file will be missing
-               # due to manual intervention or weird sync problems; treat that
-               # condition gracefully and continue to delete the database entry.
-               # Also some records may end up with an empty oi_archive_name field
-               # if the original file was missing when a new upload was made;
-               # don't try to delete the directory then!
-               #
-               $targetFile = "{$archive}/{$oldimage}";
-               if( $oldimage != '' && file_exists( $targetFile ) && !@unlink( $targetFile ) ) {
+               $ok = $this->img->deleteOld( $oldimage, '' );
+               if( !$ok ) {
                        # If we actually have a file and can't delete it, throw an error.
-                       $wgOut->fileDeleteError( "{$archive}/{$oldimage}" );
+                       # Something went awry...
+                       $wgOut->showFileDeleteError( "$oldimage" );
                } else {
                        # Log the deletion
                        $log = new LogPage( 'delete' );
                        $log->addEntry( 'delete', $this->mTitle, wfMsg('deletedrevision',$oldimage) );
                }
+               return $ok;
        }
 
-       function revert()
-       {
+       function revert() {
                global $wgOut, $wgRequest, $wgUser;
-               global $wgUseSquid, $wgInternalServer, $wgDeferredUpdateList;
 
                $oldimage = $wgRequest->getText( 'oldimage' );
                if ( strlen( $oldimage ) < 16 ) {
-                       $wgOut->unexpectedValueError( 'oldimage', htmlspecialchars($oldimage) );
+                       $wgOut->showUnexpectedValueError( 'oldimage', htmlspecialchars($oldimage) );
                        return;
                }
                if ( strstr( $oldimage, "/" ) || strstr( $oldimage, "\\" ) ) {
-                       $wgOut->unexpectedValueError( 'oldimage', htmlspecialchars($oldimage) );
+                       $wgOut->showUnexpectedValueError( 'oldimage', htmlspecialchars($oldimage) );
                        return;
                }
 
@@ -550,75 +649,84 @@ class ImagePage extends Article {
                        return;
                }
                if( $wgUser->isAnon() ) {
-                       $wgOut->errorpage( 'uploadnologin', 'uploadnologintext' );
+                       $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
                        return;
                }
-               if ( ! $this->mTitle->userCanEdit() ) {
-                       $wgOut->sysopRequired();
+               if ( ! $this->mTitle->userCan( 'edit' ) ) {
+                       $wgOut->readOnlyPage( $this->getContent(), true );
                        return;
                }
                if ( $wgUser->isBlocked() ) {
-                       return $this->blockedIPpage();
-               }
-               if( !$wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ), $oldimage ) ) {
-                       $wgOut->errorpage( 'internalerror', 'sessionfailure' );
+                       $wgOut->blockedPage();
                        return;
                }
-               $name = substr( $oldimage, 15 );
-
-               $dest = wfImageDir( $name );
-               $archive = wfImageArchiveDir( $name );
-               $curfile = "{$dest}/{$name}";
-
-               if ( ! is_file( $curfile ) ) {
-                       $wgOut->fileNotFoundError( htmlspecialchars( $curfile ) );
+               if( !$wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ), $oldimage ) ) {
+                       $wgOut->showErrorPage( 'internalerror', 'sessionfailure' );
                        return;
                }
-               $oldver = wfTimestampNow() . "!{$name}";
 
-               $dbr =& wfGetDB( DB_SLAVE );
-               $size = $dbr->selectField( 'oldimage', 'oi_size', array( 'oi_archive_name' => $oldimage )  );
+               $sourcePath = $this->img->getArchiveVirtualUrl( $oldimage );
+               $comment = wfMsg( "reverted" );
+               $result = $this->img->upload( $sourcePath, $comment, $comment );
 
-               if ( ! rename( $curfile, "${archive}/{$oldver}" ) ) {
-                       $wgOut->fileRenameError( $curfile, "${archive}/{$oldver}" );
+               if ( WikiError::isError( $result ) ) {
+                       $this->showError( $result );
                        return;
                }
-               if ( ! copy( "{$archive}/{$oldimage}", $curfile ) ) {
-                       $wgOut->fileCopyError( "${archive}/{$oldimage}", $curfile );
-               }
-
-               # Record upload and update metadata cache
-               $img = Image::newFromName( $name );
-               $img->recordUpload( $oldver, wfMsg( "reverted" ) );
 
                $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
                $wgOut->setRobotpolicy( 'noindex,nofollow' );
                $wgOut->addHTML( wfMsg( 'imagereverted' ) );
 
-               $descTitle = $img->getTitle();
+               $descTitle = $this->img->getTitle();
                $wgOut->returnToMain( false, $descTitle->getPrefixedText() );
        }
+       
+       /**
+        * Override handling of action=purge
+        */
+       function doPurge() {
+               if( $this->img->exists() ) {
+                       wfDebug( "ImagePage::doPurge purging " . $this->img->getName() . "\n" );
+                       $update = new HTMLCacheUpdate( $this->mTitle, 'imagelinks' );
+                       $update->doUpdate();
+                       $this->img->upgradeRow();
+                       $this->img->purgeCache();
+               } else {
+                       wfDebug( "ImagePage::doPurge no image\n" );
+               }
+               parent::doPurge();
+       }
 
-       function blockedIPpage() {
-               require_once( 'EditPage.php' );
-               $edit = new EditPage( $this );
-               return $edit->blockedIPpage();
+       /**
+        * Display an error from a wikitext-formatted WikiError object
+        */
+       function showError( WikiError $error ) {
+               global $wgOut;
+               $wgOut->setPageTitle( wfMsg( "internalerror" ) );
+               $wgOut->setRobotpolicy( "noindex,nofollow" );
+               $wgOut->setArticleRelated( false );
+               $wgOut->enableClientCache( false );
+               $wgOut->addWikiText( $error->getMessage() );
        }
 
 }
 
 /**
  * @todo document
- * @package MediaWiki
+ * @addtogroup Media
  */
 class ImageHistoryList {
-       function ImageHistoryList( &$skin ) {
-               $this->skin =& $skin;
+       var $img, $skin;
+       function ImageHistoryList( $skin, $img ) {
+               $this->skin = $skin;
+               $this->img = $img;
        }
 
        function beginImageHistoryList() {
-               $s = "\n<h2 id=\"filehistory\">" . wfMsg( 'imghistory' ) . "</h2>\n" .
-                 "<p>" . wfMsg( 'imghistlegend' ) . "</p>\n".'<ul class="special">';
+               $s = "\n" .
+                       Xml::element( 'h2', array( 'id' => 'filehistory' ), wfMsg( 'imghistory' ) ) .
+                       "\n<p>" . wfMsg( 'imghistlegend' ) . "</p>\n".'<ul class="special">';
                return $s;
        }
 
@@ -627,18 +735,19 @@ class ImageHistoryList {
                return $s;
        }
 
-       function imageHistoryLine( $iscur, $timestamp, $img, $user, $usertext, $size, $description ) {
-               global $wgUser, $wgLang, $wgContLang, $wgTitle;
+       function imageHistoryLine( $iscur, $timestamp, $img, $user, $usertext, $size, $description, $width, $height ) {
+               global $wgUser, $wgLang, $wgTitle, $wgContLang;
 
                $datetime = $wgLang->timeanddate( $timestamp, true );
-               $del = wfMsg( 'deleteimg' );
-               $delall = wfMsg( 'deleteimgcompletely' );
-               $cur = wfMsg( 'cur' );
+               $del = wfMsgHtml( 'deleteimg' );
+               $delall = wfMsgHtml( 'deleteimgcompletely' );
+               $cur = wfMsgHtml( 'cur' );
+               $local = $this->img->isLocal();
 
                if ( $iscur ) {
-                       $url = Image::imageUrl( $img );
+                       $url = htmlspecialchars( $this->img->getURL() );
                        $rlink = $cur;
-                       if ( $wgUser->isAllowed('delete') ) {
+                       if ( $local && $wgUser->isAllowed('delete') ) {
                                $link = $wgTitle->escapeLocalURL( 'image=' . $wgTitle->getPartialURL() .
                                  '&action=delete' );
                                $style = $this->skin->getInternalLinkAttributes( $link, $delall );
@@ -648,11 +757,11 @@ class ImageHistoryList {
                                $dlink = $del;
                        }
                } else {
-                       $url = htmlspecialchars( wfImageArchiveUrl( $img ) );
-                       if( $wgUser->getID() != 0 && $wgTitle->userCanEdit() ) {
+                       $url = htmlspecialchars( $this->img->getArchiveUrl( $img ) );
+                       if( $local && $wgUser->getID() != 0 && $wgTitle->userCan( 'edit' ) ) {
                                $token = urlencode( $wgUser->editToken( $img ) );
                                $rlink = $this->skin->makeKnownLinkObj( $wgTitle,
-                                          wfMsg( 'revertimg' ), 'action=revert&oldimage=' .
+                                          wfMsgHtml( 'revertimg' ), 'action=revert&oldimage=' .
                                           urlencode( $img ) . "&wpEditToken=$token" );
                                $dlink = $this->skin->makeKnownLinkObj( $wgTitle,
                                           $del, 'action=delete&oldimage=' . urlencode( $img ) .
@@ -661,29 +770,28 @@ class ImageHistoryList {
                                # Having live active links for non-logged in users
                                # means that bots and spiders crawling our site can
                                # inadvertently change content. Baaaad idea.
-                               $rlink = wfMsg( 'revertimg' );
+                               $rlink = wfMsgHtml( 'revertimg' );
                                $dlink = $del;
                        }
                }
-               if ( 0 == $user ) {
-                       $userlink = $usertext;
+
+               if ( $local ) {
+                       $userlink = $this->skin->userLink( $user, $usertext ) . $this->skin->userToolLinks( $user, $usertext );
                } else {
-                       $userlink = $this->skin->makeLinkObj(
-                               Title::makeTitle( NS_USER, $usertext ),
-                               $usertext );
+                       $userlink = htmlspecialchars( $usertext );
                }
-               $nbytes = wfMsg( 'nbytes', $size );
+               $nbytes = wfMsgExt( 'nbytes', array( 'parsemag', 'escape' ),
+                       $wgLang->formatNum( $size ) );
+               $widthheight = wfMsgHtml( 'widthheight', $width, $height );
                $style = $this->skin->getInternalLinkAttributes( $url, $datetime );
 
-               $s = "<li> ({$dlink}) ({$rlink}) <a href=\"{$url}\"{$style}>{$datetime}</a>"
-                 . " . . {$userlink} ({$nbytes})";
+               $s = "<li> ({$dlink}) ({$rlink}) <a href=\"{$url}\"{$style}>{$datetime}</a> . . {$userlink} . . {$widthheight} ({$nbytes})";
 
                $s .= $this->skin->commentBlock( $description, $wgTitle );
                $s .= "</li>\n";
                return $s;
        }
-
 }
 
 
-?>
+