coding style cleanup for upload stuff
authorJack Phoenix <ashley@users.mediawiki.org>
Wed, 15 Jul 2009 19:18:12 +0000 (19:18 +0000)
committerJack Phoenix <ashley@users.mediawiki.org>
Wed, 15 Jul 2009 19:18:12 +0000 (19:18 +0000)
includes/upload/UploadBase.php
includes/upload/UploadFromChunks.php
includes/upload/UploadFromStash.php
includes/upload/UploadFromUrl.php

index 8cb4b28..758a490 100644 (file)
@@ -40,6 +40,7 @@ class UploadBase {
                }
                return true;
        }
+
        /**
         * Returns true if the user can use this upload module or else a string
         * identifying the missing permission.
@@ -53,6 +54,7 @@ class UploadBase {
 
        // Upload handlers. Should probably just be a global
        static $uploadHandlers = array( 'Stash', 'File', 'Url' );
+
        /**
         * Create a form of UploadBase depending on wpSourceType and initializes it
         */
@@ -62,16 +64,15 @@ class UploadBase {
                if( !$type )
                        return null;
 
-               $type = ucfirst($type);
-               $className = 'UploadFrom'.$type;
-               wfDebug( __METHOD__.": class name: $className");
+               $type = ucfirst( $type );
+               $className = 'UploadFrom' . $type;
+               wfDebug( __METHOD__ . ": class name: $className" );
                if( !in_array( $type, self::$uploadHandlers ) )
                        return null;
 
                if( !call_user_func( array( $className, 'isEnabled' ) ) )
                        return null;
 
-
                if( !call_user_func( array( $className, 'isValidRequest' ), $request ) )
                        return null;
 
@@ -80,6 +81,7 @@ class UploadBase {
                $handler->initializeFromRequest( $request );
                return $handler;
        }
+
        /**
         * Check whether a request if valid for this handler
         */
@@ -105,10 +107,14 @@ class UploadBase {
        function fetchFile() {
                return Status::newGood();
        }
-       //return the file size
+
+       /**
+        * Return the file size
+        */
        function isEmptyFile(){
-               return empty( $this->mFileSize);
+               return empty( $this->mFileSize );
        }
+
        /**
         * Verify whether the upload is sane.
         * Returns self::OK or else an array with error information
@@ -117,7 +123,6 @@ class UploadBase {
                /**
                 * If there was no filename or a zero size given, give up quick.
                 */
-
                if( $this->isEmptyFile() )
                        return array( 'status' => self::EMPTY_FILE );
 
@@ -173,7 +178,7 @@ class UploadBase {
         */
        protected function verifyFile( $tmpfile ) {
                $this->mFileProps = File::getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
-               $this->checkMacBinary( );
+               $this->checkMacBinary();
 
                #magically determine mime type
                $magic = MimeMagic::singleton();
@@ -181,7 +186,7 @@ class UploadBase {
 
                #check mime type, if desired
                global $wgVerifyMimeType;
-               if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist) ) {
+               if( isset( $wgMimeTypeBlacklist ) && !is_null( $wgMimeTypeBlacklist ) ) {
                        if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) )
                                return array( 'filetype-badmime', $mime );
 
@@ -198,9 +203,8 @@ class UploadBase {
                        }
                }
 
-
                #check for htmlish code and javascript
-               if( $this->detectScript ( $tmpfile, $mime, $this->mFinalExtension ) ) {
+               if( $this->detectScript( $tmpfile, $mime, $this->mFinalExtension ) ) {
                        return 'uploadscripted';
                }
                if( $this->mFinalExtension == 'svg' || $mime == 'image/svg+xml' ) {
@@ -212,11 +216,11 @@ class UploadBase {
                /**
                * Scan the uploaded file for viruses
                */
-               $virus = $this->detectVirus($tmpfile);
+               $virus = $this->detectVirus( $tmpfile );
                if ( $virus ) {
                        return array( 'uploadvirus', $virus );
                }
-               wfDebug( __METHOD__.": all clear; passing.\n" );
+               wfDebug( __METHOD__ . ": all clear; passing.\n" );
                return true;
        }
 
@@ -255,7 +259,7 @@ class UploadBase {
                /*
                 * Check whether the resulting filename is different from the desired one,
                 * but ignore things like ucfirst() and spaces/underscore things
-                **/
+                */
                $comparableName = str_replace( ' ', '_', $this->mDesiredDestName );
                global $wgCapitalLinks, $wgContLang;
                if ( $wgCapitalLinks ) {
@@ -288,7 +292,7 @@ class UploadBase {
                                && self::isThumbName( $this->mLocalFile->getName() ) ){
                        //make the title:
                        $nt = $this->getTitle();
-                       $warning['file-thumbnail-no'] = substr( $filename , 0,
+                       $warning['file-thumbnail-no'] = substr( $filename, 0,
                                strpos( $nt->getText() , '-' ) +1 );
                }
 
@@ -329,7 +333,7 @@ class UploadBase {
         * Really perform the upload.
         */
        function performUpload( $comment, $pageText, $watch, $user ) {
-           wfDebug("\n\n\performUpload: sum:" . $comment . ' c: ' . $pageText . ' w:' .$watch);
+               wfDebug( "\n\n\performUpload: sum:" . $comment . ' c: ' . $pageText . ' w:' . $watch );
                $status = $this->mLocalFile->upload( $this->mTempPath, $comment, $pageText,
                        File::DELETE_SOURCE, $this->mFileProps, false, $user );
 
@@ -354,7 +358,6 @@ class UploadBase {
                 * filter out illegal characters, and try to make a legible name
                 * out of it. We'll strip some silently that Title would die on.
                 */
-
                $basename = $this->mDesiredDestName;
 
                $this->mFilteredName = wfStripIllegalFilenameChars( $basename );
@@ -436,10 +439,11 @@ class UploadBase {
                $status = $repo->storeTemp( $saveName, $tempName );
                return $status;
        }
+
        /* append to a stashed file */
-       function appendToUploadFile($srcPath, $toAppendPath ){
+       function appendToUploadFile( $srcPath, $toAppendPath ){
                $repo = RepoGroup::singleton()->getLocalRepo();
-               $status = $repo->append($srcPath, $toAppendPath);
+               $status = $repo->append( $srcPath, $toAppendPath );
                return $status;
        }
 
@@ -459,19 +463,22 @@ class UploadBase {
                        return false;
                }
                $mTempPath = $status->value;
-               session_start();//start up the session (might have been previously closed to prevent php session locking)
-               $key = $this->getSessionKey ();
+               session_start(); // start up the session (might have been previously closed to prevent php session locking)
+               $key = $this->getSessionKey();
                $_SESSION['wsUploadData'][$key] = array(
                        'mTempPath'       => $mTempPath,
                        'mFileSize'       => $this->mFileSize,
                        'mSrcName'        => $this->mSrcName,
                        'mFileProps'      => $this->mFileProps,
                        'version'         => self::SESSION_VERSION,
-               );
-               session_write_close();
+               );
+               session_write_close();
                return $key;
        }
-       //pull session Key gen from stash in cases where we want to start an upload without much information
+
+       /**
+        * Pull session key gen from stash in cases where we want to start an upload without much information
+        */
        function getSessionKey(){
                $key = mt_rand( 0, 0x7fffffff );
                $_SESSION['wsUploadData'][$key] = array();
@@ -495,7 +502,7 @@ class UploadBase {
         */
        function cleanupTempFile() {
                if ( $this->mRemoveTempFile && $this->mTempPath && file_exists( $this->mTempPath ) ) {
-                       wfDebug( __METHOD__.": Removing temporary file {$this->mTempPath}\n" );
+                       wfDebug( __METHOD__ . ": Removing temporary file {$this->mTempPath}\n" );
                        unlink( $this->mTempPath );
                }
        }
@@ -504,8 +511,7 @@ class UploadBase {
                return $this->mTempPath;
        }
 
-
-               /**
+       /**
         * Split a file into a base name and all dot-delimited 'extensions'
         * on the end. Some web server configurations will fall back to
         * earlier pseudo-'extensions' to determine type and execute
@@ -548,7 +554,6 @@ class UploadBase {
                return false;
        }
 
-
        /**
         * Checks if the mime type of the uploaded file matches the file extension.
         *
@@ -559,30 +564,30 @@ class UploadBase {
        public static function verifyExtension( $mime, $extension ) {
                $magic = MimeMagic::singleton();
 
-               if ( ! $mime || $mime == 'unknown' || $mime == 'unknown/unknown' )
-                       if ( ! $magic->isRecognizableExtension( $extension ) ) {
-                               wfDebug( __METHOD__.": passing file with unknown detected mime type; " .
+               if ( !$mime || $mime == 'unknown' || $mime == 'unknown/unknown' )
+                       if ( !$magic->isRecognizableExtension( $extension ) ) {
+                               wfDebug( __METHOD__ . ": passing file with unknown detected mime type; " .
                                        "unrecognized extension '$extension', can't verify\n" );
                                return true;
                        } else {
-                               wfDebug( __METHOD__.": rejecting file with unknown detected mime type; ".
+                               wfDebug( __METHOD__ . ": rejecting file with unknown detected mime type; ".
                                        "recognized extension '$extension', so probably invalid file\n" );
                                return false;
                        }
 
-               $match= $magic->isMatchingExtension($extension,$mime);
+               $match = $magic->isMatchingExtension( $extension, $mime );
 
-               if ($match===NULL) {
-                       wfDebug( __METHOD__.": no file extension known for mime type $mime, passing file\n" );
+               if ( $match === NULL ) {
+                       wfDebug( __METHOD__ . ": no file extension known for mime type $mime, passing file\n" );
                        return true;
-               } elseif ($match===true) {
-                       wfDebug( __METHOD__.": mime type $mime matches extension $extension, passing file\n" );
+               } elseif( $match === true ) {
+                       wfDebug( __METHOD__ . ": mime type $mime matches extension $extension, passing file\n" );
 
                        #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
                        return true;
 
                } else {
-                       wfDebug( __METHOD__.": mime type $mime mismatches file extension $extension, rejecting file\n" );
+                       wfDebug( __METHOD__ . ": mime type $mime mismatches file extension $extension, rejecting file\n" );
                        return false;
                }
        }
@@ -597,38 +602,44 @@ class UploadBase {
         * @param string $extension The extension of the file
         * @return bool true if the file contains something looking like embedded scripts
         */
-       function detectScript($file, $mime, $extension) {
+       function detectScript( $file, $mime, $extension ) {
                global $wgAllowTitlesInSVG;
 
                #ugly hack: for text files, always look at the entire file.
                #For binary field, just check the first K.
 
-               if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
+               if( strpos( $mime,'text/' ) === 0 )
+                       $chunk = file_get_contents( $file );
                else {
                        $fp = fopen( $file, 'rb' );
                        $chunk = fread( $fp, 1024 );
                        fclose( $fp );
                }
 
-               $chunk= strtolower( $chunk );
+               $chunk = strtolower( $chunk );
 
-               if (!$chunk) return false;
+               if( !$chunk )
+                       return false;
 
                #decode from UTF-16 if needed (could be used for obfuscation).
-               if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
-               elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
-               else $enc= NULL;
+               if( substr( $chunk, 0, 2 ) == "\xfe\xff" )
+                       $enc = "UTF-16BE";
+               elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" )
+                       $enc = "UTF-16LE";
+               else
+                       $enc = NULL;
 
-               if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
+               if( $enc )
+                       $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
 
-               $chunk= trim($chunk);
+               $chunk = trim( $chunk );
 
                #FIXME: convert from UTF-16 if necessarry!
-
-               wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
+               wfDebug( __METHOD__ . ": checking for embedded scripts and HTML stuff\n" );
 
                #check for HTML doctype
-               if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
+               if( eregi( "<!DOCTYPE *X?HTML", $chunk ) )
+                       return true;
 
                /**
                * Internet Explorer for Windows performs some really stupid file type
@@ -645,7 +656,6 @@ class UploadBase {
                * Also returns true if Safari would mistake the given file for HTML
                * when served with a generic content-type.
                */
-
                $tags = array(
                        '<a',
                        '<body',
@@ -655,8 +665,9 @@ class UploadBase {
                        '<pre',
                        '<script', #also in safari
                        '<table'
-                       );
-               if( ! $wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
+               );
+
+               if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
                        $tags[] = '<title';
                }
 
@@ -667,22 +678,25 @@ class UploadBase {
                }
 
                /*
-               * look for javascript
-               */
+                * look for JavaScript
+                */
 
                #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
                $chunk = Sanitizer::decodeCharReferences( $chunk );
 
                #look for script-types
-               if (preg_match('!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim',$chunk)) return true;
+               if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) )
+                       return true;
 
                #look for html-style script-urls
-               if (preg_match('!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
+               if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) )
+                       return true;
 
                #look for css-style script-urls
-               if (preg_match('!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
+               if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) )
+                       return true;
 
-               wfDebug("SpecialUpload::detectScript: no scripts found\n");
+               wfDebug( __METHOD__ . ": no scripts found\n" );
                return false;
        }
 
@@ -721,8 +735,6 @@ class UploadBase {
                return array_pop( $parts );
        }
 
-
-
        /**
         * Generic wrapper function for a virus scanner program.
         * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
@@ -733,18 +745,18 @@ class UploadBase {
         *         or a string containing feedback from the virus scanner if a virus was found.
         *         If textual feedback is missing but a virus was found, this function returns true.
         */
-       function detectVirus($file) {
+       function detectVirus( $file ) {
                global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
 
                if ( !$wgAntivirus ) {
-                       wfDebug( __METHOD__.": virus scanner disabled\n");
+                       wfDebug( __METHOD__ . ": virus scanner disabled\n" );
                        return NULL;
                }
 
                if ( !$wgAntivirusSetup[$wgAntivirus] ) {
-                       wfDebug( __METHOD__.": unknown virus scanner: $wgAntivirus\n" );
+                       wfDebug( __METHOD__ . ": unknown virus scanner: $wgAntivirus\n" );
                        $wgOut->wrapWikiMsg( '<div class="error">$1</div>', array( 'virus-badscanner', $wgAntivirus ) );
-                       return wfMsg('virus-unknownscanner') . " $wgAntivirus";
+                       return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
                }
 
                # look up scanner configuration
@@ -761,7 +773,7 @@ class UploadBase {
                        $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
                }
 
-               wfDebug( __METHOD__.": running virus scan: $command \n" );
+               wfDebug( __METHOD__ . ": running virus scan: $command \n" );
 
                # execute virus scanner
                $exitCode = false;
@@ -788,20 +800,20 @@ class UploadBase {
 
                if ( $mappedCode === AV_SCAN_FAILED ) {
                        # scan failed (code was mapped to false by $exitCodeMap)
-                       wfDebug( __METHOD__.": failed to scan $file (code $exitCode).\n" );
+                       wfDebug( __METHOD__ . ": failed to scan $file (code $exitCode).\n" );
 
                        if ( $wgAntivirusRequired ) {
-                               return wfMsg('virus-scanfailed', array( $exitCode ) );
+                               return wfMsg( 'virus-scanfailed', array( $exitCode ) );
                        } else {
                                return NULL;
                        }
                } else if ( $mappedCode === AV_SCAN_ABORTED ) {
                        # scan failed because filetype is unknown (probably imune)
-                       wfDebug( __METHOD__.": unsupported file type $file (code $exitCode).\n" );
+                       wfDebug( __METHOD__ . ": unsupported file type $file (code $exitCode).\n" );
                        return NULL;
                } else if ( $mappedCode === AV_NO_VIRUS ) {
                        # no virus found
-                       wfDebug( __METHOD__.": file passed virus scan.\n" );
+                       wfDebug( __METHOD__ . ": file passed virus scan.\n" );
                        return false;
                } else {
                        $output = join( "\n", $output );
@@ -818,7 +830,7 @@ class UploadBase {
                                }
                        }
 
-                       wfDebug( __METHOD__.": FOUND VIRUS! scanner feedback: $output \n" );
+                       wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output \n" );
                        return $output;
                }
        }
@@ -834,10 +846,10 @@ class UploadBase {
        function checkMacBinary() {
                $macbin = new MacBinary( $this->mTempPath );
                if( $macbin->isValid() ) {
-                       $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
+                       $dataFile = tempnam( wfTempDir(), 'WikiMacBinary' );
                        $dataHandle = fopen( $dataFile, 'wb' );
 
-                       wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
+                       wfDebug( __METHOD__ . ": Extracting MacBinary data fork to $dataFile\n" );
                        $macbin->extractData( $dataHandle );
 
                        $this->mTempPath = $dataFile;
@@ -870,8 +882,8 @@ class UploadBase {
                        return 'fileexists-shared-forbidden';
 
                return true;
-
        }
+
        /**
         * Check if a user is the last uploader
         *
@@ -969,5 +981,4 @@ class UploadBase {
                return $blacklist;
        }
 
-
 }
index c822e18..5e67fe4 100644 (file)
@@ -1,13 +1,13 @@
 <?php
-/*
-* first destination checks are made (if ignorewarnings is not checked) errors / warning is returned.
-*
-* we return the uploadUrl
-* we then accept chunk uploads from the client.
-* return chunk id on each POSTED chunk
-* once the client posts done=1 concatenated the files together.
-* more info at: http://firefogg.org/dev/chunk_post.html
-*/
+/**
+ * first destination checks are made (if ignorewarnings is not checked) errors / warning is returned.
+ *
+ * we return the uploadUrl
+ * we then accept chunk uploads from the client.
+ * return chunk id on each POSTED chunk
+ * once the client posts done=1 concatenated the files together.
+ * more info at: http://firefogg.org/dev/chunk_post.html
+ */
 class UploadFromChunks extends UploadBase {
 
        var $chunk_mode; //init, chunk, done
@@ -18,24 +18,23 @@ class UploadFromChunks extends UploadBase {
        const CHUNK = 2;
        const DONE      = 3;
 
-       function initializeFromParams( $param , &$request) {
+       function initializeFromParams( $param, &$request ) {
                $this->initFromSessionKey( $param['chunksessionkey'], $request );
-               //set the chunk mode:
+               // set the chunk mode:
                if( !$this->mSessionKey && !$param['done'] ){
-                       //session key not set init the chunk upload system:
+                       // session key not set init the chunk upload system:
                        $this->chunk_mode = UploadFromChunks::INIT;
                        $this->mDesiredDestName = $param['filename'];
-
-               }else if( $this->mSessionKey && !$param['done']){
-                       //this is a chunk piece
+               } else if( $this->mSessionKey && !$param['done'] ){
+                       // this is a chunk piece
                        $this->chunk_mode = UploadFromChunks::CHUNK;
-               }else if( $this->mSessionKey && $param['done']){
-                       //this is the last chunk
+               } else if( $this->mSessionKey && $param['done'] ){
+                       // this is the last chunk
                        $this->chunk_mode = UploadFromChunks::DONE;
                }
                if( $this->chunk_mode == UploadFromChunks::CHUNK ||
-                   $this->chunk_mode == UploadFromChunks::DONE ){
-                               //set chunk related vars:
+                       $this->chunk_mode == UploadFromChunks::DONE ){
+                               // set chunk related vars:
                                $this->mTempPath = $request->getFileTempName( 'chunk' );
                                $this->mFileSize = $request->getFileSize( 'chunk' );
                }
@@ -44,188 +43,197 @@ class UploadFromChunks extends UploadBase {
        }
 
        static function isValidRequest( $request ) {
-               $sessionData = $request->getSessionData('wsUploadData');
-               if(self::isValidSessionKey(
+               $sessionData = $request->getSessionData( 'wsUploadData' );
+               if( !self::isValidSessionKey(
                        $request->getInt( 'wpSessionKey' ),
-                       $sessionData) )
+                       $sessionData ) )
                                return false;
-               //check for the file:
+               // check for the file:
                return (bool)$request->getFileTempName( 'file' );
        }
 
-       /* check warnings depending on chunk_mode*/
+       /* check warnings depending on chunk_mode */
        function checkWarnings(){
                $warning = array();
                return $warning;
        }
 
        function isEmptyFile(){
-               //does not apply to chunk init
-               if(  $this->chunk_mode ==  UploadFromChunks::INIT ){
+               // does not apply to chunk init
+               if( $this->chunk_mode == UploadFromChunks::INIT ){
                        return false;
-               }else{
+               } else {
                        return parent::isEmptyFile();
                }
        }
-       /* Verify whether the upload is sane.
+
+       /**
+        * Verify whether the upload is sane.
         * Returns self::OK or else an array with error information
         */
        function verifyUpload( $resultDetails ) {
-               //no checks on chunk upload mode:
+               // no checks on chunk upload mode:
                if( $this->chunk_mode ==  UploadFromChunks::INIT )
                        return self::OK;
 
-               //verify on init and last chunk request
+               // verify on init and last chunk request
                if(     $this->chunk_mode == UploadFromChunks::CHUNK ||
                        $this->chunk_mode == UploadFromChunks::DONE )
                        return parent::verifyUpload( $resultDetails );
        }
-       //only run verifyFile on completed uploaded chunks
+
+       // only run verifyFile on completed uploaded chunks
        function verifyFile( $tmpFile ){
                if( $this->chunk_mode == UploadFromChunks::DONE ){
-                       //first append last chunk (so we can do a real verifyFile check... (check file type etc)
+                       // first append last chunk (so we can do a real verifyFile check... (check file type etc)
                        $status = $this->doChunkAppend();
                        if( $status->isOK() ){
                                $this->mTempPath = $this->getRealPath( $this->mTempAppendPath );
-                               //verify the completed merged chunks as if it was the file that got uploaded:
-                               return parent::verifyFile( $this->mTempPath ) ;
-                       }else{
-                               //conflict of status returns (have to return the error ary) ... why we don't consistantly use a status object is beyond me..
+                               // verify the completed merged chunks as if it was the file that got uploaded:
+                               return parent::verifyFile( $this->mTempPath );
+                       } else {
+                               // conflict of status returns (have to return the error ary) ... why we don't consistantly use a status object is beyond me..
                                return $status->getErrorsArray();
                        }
-               }else{
+               } else {
                        return true;
                }
        }
-       function getRealPath($srcPath){
+
+       function getRealPath( $srcPath ){
                $repo = RepoGroup::singleton()->getLocalRepo();
-               if ( $repo->isVirtualUrl( $srcPath) ) {
+               if ( $repo->isVirtualUrl( $srcPath ) ) {
                        return $repo->resolveVirtualUrl( $srcPath );
                }
        }
-       //pretty ugly inter-mixing of mParam and local vars
+
+       // pretty ugly inter-mixing of mParam and local vars
        function setupChunkSession( $summary, $comment, $watch ) {
                $this->mSessionKey = $this->getSessionKey();
-               $_SESSION['wsUploadData'][ $this->mSessionKey ] = array(
+               $_SESSION['wsUploadData'][$this->mSessionKey] = array(
                        'mComment'                      => $comment,
                    'mSummary'                  => $summary,
                        'mWatch'                        => $watch,
                        'mFilteredName'         => $this->mFilteredName,
-                       'mTempAppendPath'       => null, //the repo append path (not temporary local node mTempPath)
+                       'mTempAppendPath'       => null, // the repo append path (not temporary local node mTempPath)
                        'mDesiredDestName'      => $this->mDesiredDestName,
-                       'version'               => self::SESSION_VERSION,
-               );
-               return $this->mSessionKey;
+                       'version'                       => self::SESSION_VERSION,
+               );
+               return $this->mSessionKey;
        }
-    function initFromSessionKey( $sessionKey, $request ){
+
+       function initFromSessionKey( $sessionKey, $request ){
                if( !$sessionKey || empty( $sessionKey ) ){
                        return false;
                }
                $this->mSessionKey = $sessionKey;
-               //load the sessionData array:
-               $sessionData = $request->getSessionData('wsUploadData');
+               // load the sessionData array:
+               $sessionData = $request->getSessionData( 'wsUploadData' );
 
                if( isset( $sessionData[$this->mSessionKey]['version'] ) &&
                        $sessionData[$this->mSessionKey]['version'] == self::SESSION_VERSION ) {
-                       //update the local object from the session                      //
-                       $this->mComment          = $sessionData[ $this->mSessionKey ][ 'mComment' ];
-                       $this->mSummary          = $sessionData[ $this->mSessionKey ][ 'mSummary' ];
-                       $this->mWatch            = $sessionData[ $this->mSessionKey ][ 'mWatch' ];
-            $this->mIgnorewarnings   = $sessionData[ $this->mSessionKey ][ 'mIgnorewarnings' ];
-                       $this->mFilteredName     = $sessionData[ $this->mSessionKey ][ 'mFilteredName' ];
-                       $this->mTempAppendPath   = $sessionData[ $this->mSessionKey ][ 'mTempAppendPath' ];
-                       $this->mDesiredDestName  = $sessionData[ $this->mSessionKey ][ 'mDesiredDestName' ];
-               }else{
-                       $this->status = Array( 'error'=> 'missing session data');
+                       // update the local object from the session
+                       $this->mComment          = $sessionData[$this->mSessionKey]['mComment'];
+                       $this->mSummary          = $sessionData[$this->mSessionKey]['mSummary'];
+                       $this->mWatch            = $sessionData[$this->mSessionKey]['mWatch'];
+                       $this->mIgnorewarnings   = $sessionData[$this->mSessionKey]['mIgnorewarnings'];
+                       $this->mFilteredName     = $sessionData[$this->mSessionKey]['mFilteredName'];
+                       $this->mTempAppendPath   = $sessionData[$this->mSessionKey]['mTempAppendPath'];
+                       $this->mDesiredDestName  = $sessionData[$this->mSessionKey]['mDesiredDestName'];
+               } else {
+                       $this->status = array( 'error' => 'missing session data' );
                        return false;
                }
        }
-       //lets us return an api result (as flow for chunk uploads is kind of different than others.
-       function performUpload($summary='', $comment='', $watch='', $user){
+
+       // Lets us return an api result (as flow for chunk uploads is kind of different than others.
+       function performUpload( $summary = '', $comment = '', $watch = '', $user ){
                global $wgServer, $wgScriptPath, $wgUser;
+
                if( $this->chunk_mode == UploadFromChunks::INIT ){
-                       //firefogg expects a specific result per:
-                       //http://www.firefogg.org/dev/chunk_post.html
+                       // firefogg expects a specific result per:
+                       // http://www.firefogg.org/dev/chunk_post.html
 
-                       //its oky to return the token here because
-                       //a) the user must have requested the token to get here and
-                       //b) should only happen over POST
-                       //c) (we need the token to validate chunks are coming from a non-xss request)
+                       // it's okay to return the token here because
+                       // a) the user must have requested the token to get here and
+                       // b) should only happen over POST
+                       // c) (we need the token to validate chunks are coming from a non-xss request)
                        $token = urlencode( $wgUser->editToken() );
                        ob_clean();
                        echo ApiFormatJson::getJsonEncode( array(
-                                       "uploadUrl" => "{$wgServer}{$wgScriptPath}/api.php?action=upload&".
+                                       'uploadUrl' => "{$wgServer}{$wgScriptPath}/api.php?action=upload&".
                                                                        "token={$token}&format=json&enablechunks=true&chunksessionkey=".
                                                                        $this->setupChunkSession($summary, $comment, $watch ) ) );
-                       exit(0);
-               }else if( $this->chunk_mode == UploadFromChunks::CHUNK ){
+                       exit( 0 );
+               } else if( $this->chunk_mode == UploadFromChunks::CHUNK ){
                        $status = $this->doChunkAppend();
                        if( $status->isOK() ){
-                               //return success:
-                               //firefogg expects a specific result per:
-                               //http://www.firefogg.org/dev/chunk_post.html
+                               // return success:
+                               // firefogg expects a specific result per:
+                               // http://www.firefogg.org/dev/chunk_post.html
                                ob_clean();
                                echo ApiFormatJson::getJsonEncode( array(
-                                               "result"=>1,
-                                               "filesize"=> filesize( $this->getRealPath( $this->mTempAppendPath ) )
+                                               'result' => 1,
+                                               'filesize' => filesize( $this->getRealPath( $this->mTempAppendPath ) )
                                        )
                                );
-                               exit(0);
+                               exit( 0 );
                                /*return array(
                                        'result' => 1
                                );*/
-                       }else{
+                       } else {
                                return $status;
                        }
-               }else if( $this->chunk_mode == UploadFromChunks::DONE ){
-                   //update the values from the local (session init) if not paseed again)
-            if($summary == '')
-                $summary = $this->mSummary;
+               } else if( $this->chunk_mode == UploadFromChunks::DONE ){
+                       // update the values from the local (session init) if not paseed again)
+                       if( $summary == '' )
+                               $summary = $this->mSummary;
 
-            if($comment == '')
-                $comment = $this->mComment;
+                       if( $comment == '' )
+                               $comment = $this->mComment;
 
-            if($watch == '')
-                $watch = $this->mWatch;
-                       $status = parent::performUpload($summary, $comment, $watch, $user );
+                       if( $watch == '' )
+                               $watch = $this->mWatch;
+                       $status = parent::performUpload( $summary, $comment, $watch, $user );
                        if( !$status->isGood() ) {
                                return $status;
                        }
                        $file = $this->getLocalFile();
-                       //firefogg expects a specific result per:
-                       //http://www.firefogg.org/dev/chunk_post.html
+                       // firefogg expects a specific result per:
+                       // http://www.firefogg.org/dev/chunk_post.html
                        ob_clean();
                        echo ApiFormatJson::getJsonEncode( array(
-                                       "result"=>1,
-                                       "done"=>1,
-                                       "resultUrl"=> $file->getDescriptionUrl()
+                                       'result' => 1,
+                                       'done' => 1,
+                                       'resultUrl' => $file->getDescriptionUrl()
                                )
                        );
-                       exit(0);
+                       exit( 0 );
 
                }
        }
-       //append the given chunk to the temporary uploaded file. (if no temporary uploaded file exists created it.
+
+       // append the given chunk to the temporary uploaded file. (if no temporary uploaded file exists created it.
        function doChunkAppend(){
-               //if we don't have a mTempAppendPath to generate a file from the chunk packaged var:
-               if( ! $this->mTempAppendPath ){
-                       //die();
-                       //get temp name:
-                       //make a chunk store path. (append tmp file to chunk)
+               // if we don't have a mTempAppendPath to generate a file from the chunk packaged var:
+               if( !$this->mTempAppendPath ){
+                       // get temp name:
+                       // make a chunk store path. (append tmp file to chunk)
                        $status = $this->saveTempUploadedFile( $this->mDestName, $this->mTempPath );
 
                        if( $status->isOK() ) {
                                $this->mTempAppendPath = $status->value;
-                               $_SESSION[ 'wsUploadData' ][ $this->mSessionKey ][ 'mTempAppendPath' ] = $this->mTempAppendPath;
+                               $_SESSION['wsUploadData'][$this->mSessionKey]['mTempAppendPath'] = $this->mTempAppendPath;
                        }
                        return $status;
-               }else{
+               } else {
                        if( is_file( $this->getRealPath( $this->mTempAppendPath ) ) ){
-                               $status = $this->appendToUploadFile( $this->mTempAppendPath,  $this->mTempPath );
-                       }else{
+                               $status = $this->appendToUploadFile( $this->mTempAppendPath, $this->mTempPath );
+                       } else {
                                $status->fatal( 'filenotfound', $this->mTempAppendPath );
                        }
                        return $status;
                }
        }
+
 }
index 03de698..6144e4e 100644 (file)
@@ -1,56 +1,61 @@
 <?php
+
 class UploadFromStash extends UploadBase {
+
        static function isValidSessionKey( $key, $sessionData ) {
                return !empty( $key ) && 
                        is_array( $sessionData ) && 
                        isset( $sessionData[$key] ) && 
                        isset( $sessionData[$key]['version'] ) && 
-                       $sessionData[$key]['version'] == self::SESSION_VERSION
-               ;
+                       $sessionData[$key]['version'] == self::SESSION_VERSION;
        }
-       static function isValidRequest(& $request ) {           
-               $sessionData = $request->getSessionData('wsUploadData');                
+
+       static function isValidRequest( &$request ) {
+               $sessionData = $request->getSessionData( 'wsUploadData' );
                return self::isValidSessionKey( 
                        $request->getInt( 'wpSessionKey' ),
                        $sessionData
                );
-       }       
+       }
+
        function initialize( $name, $sessionData ) {
                        /**
                         * Confirming a temporarily stashed upload.
                         * We don't want path names to be forged, so we keep
                         * them in the session on the server and just give
                         * an opaque key to the user agent.
-                        */                                             
-                       parent::initialize( $name, 
-                               $sessionData['mTempPath'], 
+                        */
+                       parent::initialize( $name,
+                               $sessionData['mTempPath'],
                                $sessionData['mFileSize'],
                                false
                        );
 
-                       $this->mFileProps        = $sessionData['mFileProps'];
+                       $this->mFileProps = $sessionData['mFileProps'];
        }
-       function initializeFromRequest( &$request ) {           
+
+       function initializeFromRequest( &$request ) {
                $sessionKey = $request->getInt( 'wpSessionKey' );
                $sessionData = $request->getSessionData('wsUploadData');
-               
+
                $desiredDestName = $request->getText( 'wpDestFile' );
                if( !$desiredDestName )
-                       $desiredDestName = $request->getText( 'wpUploadFile' );         
+                       $desiredDestName = $request->getText( 'wpUploadFile' );
                return $this->initialize( $desiredDestName, $sessionData[$sessionKey] );
        }
-       
+
        /**
         * File has been previously verified so no need to do so again.
         */
        protected function verifyFile( $tmpfile ) {
                return true;
        }
+
        /**
         * We're here from "ignore warnings anyway" so return just OK
         */
        function checkWarnings() {
                return array();
        }
-}
-?>
\ No newline at end of file
+
+}
\ No newline at end of file
index e10f0bd..f9a7a3d 100644 (file)
 <?php
+
 class UploadFromUrl extends UploadBase {
        protected $mTempDownloadPath;
-       
-       //by default do a SYNC_DOWNLOAD 
+
+       // by default do a SYNC_DOWNLOAD 
        protected $dl_mode = null;
-       
+
+       /**
+        * Checks if the user is allowed to use the upload-by-URL feature
+        */
        static function isAllowed( $user ) {
                if( !$user->isAllowed( 'upload_by_url' ) )
                        return 'upload_by_url';
                return parent::isAllowed( $user );
        }
+
+       /**
+        * Checks if the upload from URL feature is enabled
+        */
        static function isEnabled() {
                global $wgAllowCopyUploads;
                return $wgAllowCopyUploads && parent::isEnabled();
-       }       
-       /*entry point for Api upload:: ASYNC_DOWNLOAD (if possible) */
-       function initialize( $name, $url, $asyncdownload = false) {             
-               global $wgTmpDirectory, $wgPhpCliPath;                          
-                       
-               //check for $asyncdownload request: 
-               if($asyncdownload !== false){
-                       if($wgPhpCliPath && wfShellExecEnabled() ){
+       }
+
+       /* entry point for API upload:: ASYNC_DOWNLOAD (if possible) */
+       function initialize( $name, $url, $asyncdownload = false ) {
+               global $wgTmpDirectory, $wgPhpCliPath;
+
+               // check for $asyncdownload request: 
+               if( $asyncdownload !== false){
+                       if( $wgPhpCliPath && wfShellExecEnabled() ){
                                $this->dl_mode = Http::ASYNC_DOWNLOAD;
-                       }else{
-                               $this->dl_mode = Http::SYNC_DOWNLOAD;   
+                       } else {
+                               $this->dl_mode = Http::SYNC_DOWNLOAD;
                        }
                }
-               
+
                $local_file = tempnam( $wgTmpDirectory, 'WEBUPLOAD' );
                parent::initialize( $name, $local_file, 0, true );
-                               
-               $this->mUrl = trim( $url );             
+
+               $this->mUrl = trim( $url );
        }
+
        public function isAsync(){
                return $this->dl_mode == Http::ASYNC_DOWNLOAD;
        }
-       /*entry point for SpecialUpload no ASYNC_DOWNLOAD possible: */
-       function initializeFromRequest( &$request ) {           
 
-               //set dl mode if not set:
-               if(!$this->dl_mode)
+       /**
+        * Entry point for SpecialUpload no ASYNC_DOWNLOAD possible
+        * @param $request Object: WebRequest object
+        */
+       function initializeFromRequest( &$request ) {
+
+               // set dl mode if not set:
+               if( !$this->dl_mode )
                        $this->dl_mode = Http::SYNC_DOWNLOAD;   
-                       
+
                $desiredDestName = $request->getText( 'wpDestFile' );
                if( !$desiredDestName )
-                       $desiredDestName = $request->getText( 'wpUploadFile' );         
-               return $this->initialize( 
-                       $desiredDestName, 
-                       $request->getVal('wpUploadFileURL')
+                       $desiredDestName = $request->getText( 'wpUploadFile' );
+               return $this->initialize(
+                       $desiredDestName,
+                       $request->getVal( 'wpUploadFileURL' )
                );
        }
+
        /**
         * Do the real fetching stuff
         */
-       function fetchFile( ) {                 
-               //entry point for SpecialUplaod 
-               if( self::isValidURI($this->mUrl) === false) {
-                       return Status::newFatal('upload-proto-error');
-               }                               
-               //now do the actual download to the target file:                        
-               $status = Http::doDownload ( $this->mUrl, $this->mTempPath, $this->dl_mode );                                           
-               
-               //update the local filesize var: 
-               $this->mFileSize = filesize( $this->mTempPath );                                        
-                                               
-               return $status;                                 
+       function fetchFile() {
+               // entry point for SpecialUplaod 
+               if( self::isValidURI( $this->mUrl ) === false ) {
+                       return Status::newFatal( 'upload-proto-error' );
+               }
+
+               // now do the actual download to the target file:
+               $status = Http::doDownload( $this->mUrl, $this->mTempPath, $this->dl_mode );
+
+               // update the local filesize var: 
+               $this->mFileSize = filesize( $this->mTempPath );
+
+               return $status;
        }
-       
+
+       /**
+        * @param $request Object: WebRequest object
+        */
        static function isValidRequest( $request ){
-               if( !$request->getVal('wpUploadFileURL') )
+               if( !$request->getVal( 'wpUploadFileURL' ) )
                        return false;
-               //check that is a valid url:
-               return self::isValidURI( $request->getVal('wpUploadFileURL') );
+               // check that is a valid url:
+               return self::isValidURI( $request->getVal( 'wpUploadFileURL' ) );
        }
+
+       /**
+        * Checks that the given URI is a valid one
+        * @param $uri Mixed: URI to check for validity
+        */
        static function isValidURI( $uri ){
-               return preg_match('/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/',
-                                                 $uri, $matches);
+               return preg_match(
+                       '/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/',
+                       $uri,
+                       $matches
+               );
        }
+
 }
\ No newline at end of file