MediaWiki  REL1_20
UploadBase.php
Go to the documentation of this file.
00001 <?php
00040 abstract class UploadBase {
00041         protected $mTempPath;
00042         protected $mDesiredDestName, $mDestName, $mRemoveTempFile, $mSourceType;
00043         protected $mTitle = false, $mTitleError = 0;
00044         protected $mFilteredName, $mFinalExtension;
00045         protected $mLocalFile, $mFileSize, $mFileProps;
00046         protected $mBlackListedExtensions;
00047         protected $mJavaDetected;
00048 
00049         protected static $safeXmlEncodings = array( 'UTF-8', 'ISO-8859-1', 'ISO-8859-2', 'UTF-16', 'UTF-32' );
00050 
00051         const SUCCESS = 0;
00052         const OK = 0;
00053         const EMPTY_FILE = 3;
00054         const MIN_LENGTH_PARTNAME = 4;
00055         const ILLEGAL_FILENAME = 5;
00056         const OVERWRITE_EXISTING_FILE = 7; # Not used anymore; handled by verifyTitlePermissions()
00057         const FILETYPE_MISSING = 8;
00058         const FILETYPE_BADTYPE = 9;
00059         const VERIFICATION_ERROR = 10;
00060 
00061         # HOOK_ABORTED is the new name of UPLOAD_VERIFICATION_ERROR
00062         const UPLOAD_VERIFICATION_ERROR = 11;
00063         const HOOK_ABORTED = 11;
00064         const FILE_TOO_LARGE = 12;
00065         const WINDOWS_NONASCII_FILENAME = 13;
00066         const FILENAME_TOO_LONG = 14;
00067 
00072         public function getVerificationErrorCode( $error ) {
00073                 $code_to_status = array(self::EMPTY_FILE => 'empty-file',
00074                                                                 self::FILE_TOO_LARGE => 'file-too-large',
00075                                                                 self::FILETYPE_MISSING => 'filetype-missing',
00076                                                                 self::FILETYPE_BADTYPE => 'filetype-banned',
00077                                                                 self::MIN_LENGTH_PARTNAME => 'filename-tooshort',
00078                                                                 self::ILLEGAL_FILENAME => 'illegal-filename',
00079                                                                 self::OVERWRITE_EXISTING_FILE => 'overwrite',
00080                                                                 self::VERIFICATION_ERROR => 'verification-error',
00081                                                                 self::HOOK_ABORTED =>  'hookaborted',
00082                                                                 self::WINDOWS_NONASCII_FILENAME => 'windows-nonascii-filename',
00083                                                                 self::FILENAME_TOO_LONG => 'filename-toolong',
00084                 );
00085                 if( isset( $code_to_status[$error] ) ) {
00086                         return $code_to_status[$error];
00087                 }
00088 
00089                 return 'unknown-error';
00090         }
00091 
00097         public static function isEnabled() {
00098                 global $wgEnableUploads;
00099 
00100                 if ( !$wgEnableUploads ) {
00101                         return false;
00102                 }
00103 
00104                 # Check php's file_uploads setting
00105                 return wfIsHipHop() || wfIniGetBool( 'file_uploads' );
00106         }
00107 
00116         public static function isAllowed( $user ) {
00117                 foreach ( array( 'upload', 'edit' ) as $permission ) {
00118                         if ( !$user->isAllowed( $permission ) ) {
00119                                 return $permission;
00120                         }
00121                 }
00122                 return true;
00123         }
00124 
00125         // Upload handlers. Should probably just be a global.
00126         static $uploadHandlers = array( 'Stash', 'File', 'Url' );
00127 
00135         public static function createFromRequest( &$request, $type = null ) {
00136                 $type = $type ? $type : $request->getVal( 'wpSourceType', 'File' );
00137 
00138                 if( !$type ) {
00139                         return null;
00140                 }
00141 
00142                 // Get the upload class
00143                 $type = ucfirst( $type );
00144 
00145                 // Give hooks the chance to handle this request
00146                 $className = null;
00147                 wfRunHooks( 'UploadCreateFromRequest', array( $type, &$className ) );
00148                 if ( is_null( $className ) ) {
00149                         $className = 'UploadFrom' . $type;
00150                         wfDebug( __METHOD__ . ": class name: $className\n" );
00151                         if( !in_array( $type, self::$uploadHandlers ) ) {
00152                                 return null;
00153                         }
00154                 }
00155 
00156                 // Check whether this upload class is enabled
00157                 if( !call_user_func( array( $className, 'isEnabled' ) ) ) {
00158                         return null;
00159                 }
00160 
00161                 // Check whether the request is valid
00162                 if( !call_user_func( array( $className, 'isValidRequest' ), $request ) ) {
00163                         return null;
00164                 }
00165 
00166                 $handler = new $className;
00167 
00168                 $handler->initializeFromRequest( $request );
00169                 return $handler;
00170         }
00171 
00177         public static function isValidRequest( $request ) {
00178                 return false;
00179         }
00180 
00181         public function __construct() {}
00182 
00189         public function getSourceType() { return null; }
00190 
00199         public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
00200                 $this->mDesiredDestName = $name;
00201                 if ( FileBackend::isStoragePath( $tempPath ) ) {
00202                         throw new MWException( __METHOD__ . " given storage path `$tempPath`." );
00203                 }
00204                 $this->mTempPath = $tempPath;
00205                 $this->mFileSize = $fileSize;
00206                 $this->mRemoveTempFile = $removeTempFile;
00207         }
00208 
00212         public abstract function initializeFromRequest( &$request );
00213 
00218         public function fetchFile() {
00219                 return Status::newGood();
00220         }
00221 
00226         public function isEmptyFile() {
00227                 return empty( $this->mFileSize );
00228         }
00229 
00234         public function getFileSize() {
00235                 return $this->mFileSize;
00236         }
00237 
00242         function getRealPath( $srcPath ) {
00243                 wfProfileIn( __METHOD__ );
00244                 $repo = RepoGroup::singleton()->getLocalRepo();
00245                 if ( $repo->isVirtualUrl( $srcPath ) ) {
00246                         // @TODO: just make uploads work with storage paths
00247                         // UploadFromStash loads files via virtuals URLs
00248                         $tmpFile = $repo->getLocalCopy( $srcPath );
00249                         $tmpFile->bind( $this ); // keep alive with $thumb
00250                         wfProfileOut( __METHOD__ );
00251                         return $tmpFile->getPath();
00252                 }
00253                 wfProfileOut( __METHOD__ );
00254                 return $srcPath;
00255         }
00256 
00261         public function verifyUpload() {
00262                 wfProfileIn( __METHOD__ );
00263 
00267                 if( $this->isEmptyFile() ) {
00268                         wfProfileOut( __METHOD__ );
00269                         return array( 'status' => self::EMPTY_FILE );
00270                 }
00271 
00275                 $maxSize = self::getMaxUploadSize( $this->getSourceType() );
00276                 if( $this->mFileSize > $maxSize ) {
00277                         wfProfileOut( __METHOD__ );
00278                         return array(
00279                                 'status' => self::FILE_TOO_LARGE,
00280                                 'max' => $maxSize,
00281                         );
00282                 }
00283 
00289                 $verification = $this->verifyFile();
00290                 if( $verification !== true ) {
00291                         wfProfileOut( __METHOD__ );
00292                         return array(
00293                                 'status' => self::VERIFICATION_ERROR,
00294                                 'details' => $verification
00295                         );
00296                 }
00297 
00301                 $result = $this->validateName();
00302                 if( $result !== true ) {
00303                         wfProfileOut( __METHOD__ );
00304                         return $result;
00305                 }
00306 
00307                 $error = '';
00308                 if( !wfRunHooks( 'UploadVerification',
00309                         array( $this->mDestName, $this->mTempPath, &$error ) ) )
00310                 {
00311                         wfProfileOut( __METHOD__ );
00312                         return array( 'status' => self::HOOK_ABORTED, 'error' => $error );
00313                 }
00314 
00315                 wfProfileOut( __METHOD__ );
00316                 return array( 'status' => self::OK );
00317         }
00318 
00325         protected function validateName() {
00326                 $nt = $this->getTitle();
00327                 if( is_null( $nt ) ) {
00328                         $result = array( 'status' => $this->mTitleError );
00329                         if( $this->mTitleError == self::ILLEGAL_FILENAME ) {
00330                                 $result['filtered'] = $this->mFilteredName;
00331                         }
00332                         if ( $this->mTitleError == self::FILETYPE_BADTYPE ) {
00333                                 $result['finalExt'] = $this->mFinalExtension;
00334                                 if ( count( $this->mBlackListedExtensions ) ) {
00335                                         $result['blacklistedExt'] = $this->mBlackListedExtensions;
00336                                 }
00337                         }
00338                         return $result;
00339                 }
00340                 $this->mDestName = $this->getLocalFile()->getName();
00341 
00342                 return true;
00343         }
00344 
00353         protected function verifyMimeType( $mime ) {
00354                 global $wgVerifyMimeType;
00355                 wfProfileIn( __METHOD__ );
00356                 if ( $wgVerifyMimeType ) {
00357                         wfDebug ( "\n\nmime: <$mime> extension: <{$this->mFinalExtension}>\n\n");
00358                         global $wgMimeTypeBlacklist;
00359                         if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
00360                                 wfProfileOut( __METHOD__ );
00361                                 return array( 'filetype-badmime', $mime );
00362                         }
00363 
00364                         # Check IE type
00365                         $fp = fopen( $this->mTempPath, 'rb' );
00366                         $chunk = fread( $fp, 256 );
00367                         fclose( $fp );
00368 
00369                         $magic = MimeMagic::singleton();
00370                         $extMime = $magic->guessTypesForExtension( $this->mFinalExtension );
00371                         $ieTypes = $magic->getIEMimeTypes( $this->mTempPath, $chunk, $extMime );
00372                         foreach ( $ieTypes as $ieType ) {
00373                                 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
00374                                         wfProfileOut( __METHOD__ );
00375                                         return array( 'filetype-bad-ie-mime', $ieType );
00376                                 }
00377                         }
00378                 }
00379 
00380                 wfProfileOut( __METHOD__ );
00381                 return true;
00382         }
00383 
00389         protected function verifyFile() {
00390                 global $wgVerifyMimeType;
00391                 wfProfileIn( __METHOD__ );
00392 
00393                 $status = $this->verifyPartialFile();
00394                 if ( $status !== true ) {
00395                         wfProfileOut( __METHOD__ );
00396                         return $status;
00397                 }
00398 
00399                 $this->mFileProps = FSFile::getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
00400                 $mime = $this->mFileProps['file-mime'];
00401 
00402                 if ( $wgVerifyMimeType ) {
00403                         # XXX: Missing extension will be caught by validateName() via getTitle()
00404                         if ( $this->mFinalExtension != '' && !$this->verifyExtension( $mime, $this->mFinalExtension ) ) {
00405                                 wfProfileOut( __METHOD__ );
00406                                 return array( 'filetype-mime-mismatch', $this->mFinalExtension, $mime );
00407                         }
00408                 }
00409 
00410                 $handler = MediaHandler::getHandler( $mime );
00411                 if ( $handler ) {
00412                         $handlerStatus = $handler->verifyUpload( $this->mTempPath );
00413                         if ( !$handlerStatus->isOK() ) {
00414                                 $errors = $handlerStatus->getErrorsArray();
00415                                 wfProfileOut( __METHOD__ );
00416                                 return reset( $errors );
00417                         }
00418                 }
00419 
00420                 wfRunHooks( 'UploadVerifyFile', array( $this, $mime, &$status ) );
00421                 if ( $status !== true ) {
00422                         wfProfileOut( __METHOD__ );
00423                         return $status;
00424                 }
00425 
00426                 wfDebug( __METHOD__ . ": all clear; passing.\n" );
00427                 wfProfileOut( __METHOD__ );
00428                 return true;
00429         }
00430 
00439         protected function verifyPartialFile() {
00440                 global $wgAllowJavaUploads, $wgDisableUploadScriptChecks;
00441                 wfProfileIn( __METHOD__ );
00442 
00443                 # get the title, even though we are doing nothing with it, because
00444                 # we need to populate mFinalExtension
00445                 $this->getTitle();
00446 
00447                 $this->mFileProps = FSFile::getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
00448 
00449                 # check mime type, if desired
00450                 $mime = $this->mFileProps[ 'file-mime' ];
00451                 $status = $this->verifyMimeType( $mime );
00452                 if ( $status !== true ) {
00453                         wfProfileOut( __METHOD__ );
00454                         return $status;
00455                 }
00456 
00457                 # check for htmlish code and javascript
00458                 if ( !$wgDisableUploadScriptChecks ) {
00459                         if( self::detectScript( $this->mTempPath, $mime, $this->mFinalExtension ) ) {
00460                                 wfProfileOut( __METHOD__ );
00461                                 return array( 'uploadscripted' );
00462                         }
00463                         if( $this->mFinalExtension == 'svg' || $mime == 'image/svg+xml' ) {
00464                                 if( $this->detectScriptInSvg( $this->mTempPath ) ) {
00465                                         wfProfileOut( __METHOD__ );
00466                                         return array( 'uploadscripted' );
00467                                 }
00468                         }
00469                 }
00470 
00471                 # Check for Java applets, which if uploaded can bypass cross-site
00472                 # restrictions.
00473                 if ( !$wgAllowJavaUploads ) {
00474                         $this->mJavaDetected = false;
00475                         $zipStatus = ZipDirectoryReader::read( $this->mTempPath,
00476                                 array( $this, 'zipEntryCallback' ) );
00477                         if ( !$zipStatus->isOK() ) {
00478                                 $errors = $zipStatus->getErrorsArray();
00479                                 $error = reset( $errors );
00480                                 if ( $error[0] !== 'zip-wrong-format' ) {
00481                                         wfProfileOut( __METHOD__ );
00482                                         return $error;
00483                                 }
00484                         }
00485                         if ( $this->mJavaDetected ) {
00486                                 wfProfileOut( __METHOD__ );
00487                                 return array( 'uploadjava' );
00488                         }
00489                 }
00490 
00491                 # Scan the uploaded file for viruses
00492                 $virus = $this->detectVirus( $this->mTempPath );
00493                 if ( $virus ) {
00494                         wfProfileOut( __METHOD__ );
00495                         return array( 'uploadvirus', $virus );
00496                 }
00497 
00498                 wfProfileOut( __METHOD__ );
00499                 return true;
00500         }
00501 
00505         function zipEntryCallback( $entry ) {
00506                 $names = array( $entry['name'] );
00507 
00508                 // If there is a null character, cut off the name at it, because JDK's
00509                 // ZIP_GetEntry() uses strcmp() if the name hashes match. If a file name
00510                 // were constructed which had ".class\0" followed by a string chosen to
00511                 // make the hash collide with the truncated name, that file could be
00512                 // returned in response to a request for the .class file.
00513                 $nullPos = strpos( $entry['name'], "\000" );
00514                 if ( $nullPos !== false ) {
00515                         $names[] = substr( $entry['name'], 0, $nullPos );
00516                 }
00517 
00518                 // If there is a trailing slash in the file name, we have to strip it,
00519                 // because that's what ZIP_GetEntry() does.
00520                 if ( preg_grep( '!\.class/?$!', $names ) ) {
00521                         $this->mJavaDetected = true;
00522                 }
00523         }
00524 
00532         public function verifyPermissions( $user ) {
00533                 return $this->verifyTitlePermissions( $user );
00534         }
00535 
00547         public function verifyTitlePermissions( $user ) {
00552                 $nt = $this->getTitle();
00553                 if( is_null( $nt ) ) {
00554                         return true;
00555                 }
00556                 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
00557                 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
00558                 if ( !$nt->exists() ) {
00559                         $permErrorsCreate = $nt->getUserPermissionsErrors( 'create', $user );
00560                 } else {
00561                         $permErrorsCreate = array();
00562                 }
00563                 if( $permErrors || $permErrorsUpload || $permErrorsCreate ) {
00564                         $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
00565                         $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
00566                         return $permErrors;
00567                 }
00568 
00569                 $overwriteError = $this->checkOverwrite( $user );
00570                 if ( $overwriteError !== true ) {
00571                         return array( $overwriteError );
00572                 }
00573 
00574                 return true;
00575         }
00576 
00582         public function checkWarnings() {
00583                 global $wgLang;
00584                 wfProfileIn( __METHOD__ );
00585 
00586                 $warnings = array();
00587 
00588                 $localFile = $this->getLocalFile();
00589                 $filename = $localFile->getName();
00590 
00595                 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName );
00596                 $comparableName = Title::capitalize( $comparableName, NS_FILE );
00597 
00598                 if( $this->mDesiredDestName != $filename && $comparableName != $filename ) {
00599                         $warnings['badfilename'] = $filename;
00600                 }
00601 
00602                 // Check whether the file extension is on the unwanted list
00603                 global $wgCheckFileExtensions, $wgFileExtensions;
00604                 if ( $wgCheckFileExtensions ) {
00605                         if ( !$this->checkFileExtension( $this->mFinalExtension, $wgFileExtensions ) ) {
00606                                 $warnings['filetype-unwanted-type'] = array( $this->mFinalExtension,
00607                                         $wgLang->commaList( $wgFileExtensions ), count( $wgFileExtensions ) );
00608                         }
00609                 }
00610 
00611                 global $wgUploadSizeWarning;
00612                 if ( $wgUploadSizeWarning && ( $this->mFileSize > $wgUploadSizeWarning ) ) {
00613                         $warnings['large-file'] = $wgUploadSizeWarning;
00614                 }
00615 
00616                 if ( $this->mFileSize == 0 ) {
00617                         $warnings['emptyfile'] = true;
00618                 }
00619 
00620                 $exists = self::getExistsWarning( $localFile );
00621                 if( $exists !== false ) {
00622                         $warnings['exists'] = $exists;
00623                 }
00624 
00625                 // Check dupes against existing files
00626                 $hash = FSFile::getSha1Base36FromPath( $this->mTempPath );
00627                 $dupes = RepoGroup::singleton()->findBySha1( $hash );
00628                 $title = $this->getTitle();
00629                 // Remove all matches against self
00630                 foreach ( $dupes as $key => $dupe ) {
00631                         if( $title->equals( $dupe->getTitle() ) ) {
00632                                 unset( $dupes[$key] );
00633                         }
00634                 }
00635                 if( $dupes ) {
00636                         $warnings['duplicate'] = $dupes;
00637                 }
00638 
00639                 // Check dupes against archives
00640                 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
00641                 if ( $archivedImage->getID() > 0 ) {
00642                         $warnings['duplicate-archive'] = $archivedImage->getName();
00643                 }
00644 
00645                 wfProfileOut( __METHOD__ );
00646                 return $warnings;
00647         }
00648 
00660         public function performUpload( $comment, $pageText, $watch, $user ) {
00661                 wfProfileIn( __METHOD__ );
00662 
00663                 $status = $this->getLocalFile()->upload(
00664                         $this->mTempPath,
00665                         $comment,
00666                         $pageText,
00667                         File::DELETE_SOURCE,
00668                         $this->mFileProps,
00669                         false,
00670                         $user
00671                 );
00672 
00673                 if( $status->isGood() ) {
00674                         if ( $watch ) {
00675                                 $user->addWatch( $this->getLocalFile()->getTitle() );
00676                         }
00677                         wfRunHooks( 'UploadComplete', array( &$this ) );
00678                 }
00679 
00680                 wfProfileOut( __METHOD__ );
00681                 return $status;
00682         }
00683 
00690         public function getTitle() {
00691                 if ( $this->mTitle !== false ) {
00692                         return $this->mTitle;
00693                 }
00694 
00695                 /* Assume that if a user specified File:Something.jpg, this is an error
00696                  * and that the namespace prefix needs to be stripped of.
00697                  */
00698                 $title = Title::newFromText( $this->mDesiredDestName );
00699                 if ( $title && $title->getNamespace() == NS_FILE ) {
00700                         $this->mFilteredName = $title->getDBkey();
00701                 } else {
00702                         $this->mFilteredName = $this->mDesiredDestName;
00703                 }
00704 
00705                 # oi_archive_name is max 255 bytes, which include a timestamp and an
00706                 # exclamation mark, so restrict file name to 240 bytes.
00707                 if ( strlen( $this->mFilteredName ) > 240 ) {
00708                         $this->mTitleError = self::FILENAME_TOO_LONG;
00709                         return $this->mTitle = null;
00710                 }
00711 
00717                 $this->mFilteredName = wfStripIllegalFilenameChars( $this->mFilteredName );
00718                 /* Normalize to title form before we do any further processing */
00719                 $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
00720                 if( is_null( $nt ) ) {
00721                         $this->mTitleError = self::ILLEGAL_FILENAME;
00722                         return $this->mTitle = null;
00723                 }
00724                 $this->mFilteredName = $nt->getDBkey();
00725 
00726 
00727 
00732                 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName );
00733 
00734                 if( count( $ext ) ) {
00735                         $this->mFinalExtension = trim( $ext[count( $ext ) - 1] );
00736                 } else {
00737                         $this->mFinalExtension = '';
00738 
00739                         # No extension, try guessing one
00740                         $magic = MimeMagic::singleton();
00741                         $mime = $magic->guessMimeType( $this->mTempPath );
00742                         if ( $mime !== 'unknown/unknown' ) {
00743                                 # Get a space separated list of extensions
00744                                 $extList = $magic->getExtensionsForType( $mime );
00745                                 if ( $extList ) {
00746                                         # Set the extension to the canonical extension
00747                                         $this->mFinalExtension = strtok( $extList, ' ' );
00748 
00749                                         # Fix up the other variables
00750                                         $this->mFilteredName .= ".{$this->mFinalExtension}";
00751                                         $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
00752                                         $ext = array( $this->mFinalExtension );
00753                                 }
00754                         }
00755 
00756                 }
00757 
00758                 /* Don't allow users to override the blacklist (check file extension) */
00759                 global $wgCheckFileExtensions, $wgStrictFileExtensions;
00760                 global $wgFileExtensions, $wgFileBlacklist;
00761 
00762                 $blackListedExtensions = $this->checkFileExtensionList( $ext, $wgFileBlacklist );
00763 
00764                 if ( $this->mFinalExtension == '' ) {
00765                         $this->mTitleError = self::FILETYPE_MISSING;
00766                         return $this->mTitle = null;
00767                 } elseif ( $blackListedExtensions ||
00768                                 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
00769                                         !$this->checkFileExtensionList( $ext, $wgFileExtensions ) ) ) {
00770                         $this->mBlackListedExtensions = $blackListedExtensions;
00771                         $this->mTitleError = self::FILETYPE_BADTYPE;
00772                         return $this->mTitle = null;
00773                 }
00774 
00775                 // Windows may be broken with special characters, see bug XXX
00776                 if ( wfIsWindows() && !preg_match( '/^[\x0-\x7f]*$/', $nt->getText() ) ) {
00777                         $this->mTitleError = self::WINDOWS_NONASCII_FILENAME;
00778                         return $this->mTitle = null;
00779                 }
00780 
00781                 # If there was more than one "extension", reassemble the base
00782                 # filename to prevent bogus complaints about length
00783                 if( count( $ext ) > 1 ) {
00784                         for( $i = 0; $i < count( $ext ) - 1; $i++ ) {
00785                                 $partname .= '.' . $ext[$i];
00786                         }
00787                 }
00788 
00789                 if( strlen( $partname ) < 1 ) {
00790                         $this->mTitleError =  self::MIN_LENGTH_PARTNAME;
00791                         return $this->mTitle = null;
00792                 }
00793 
00794                 return $this->mTitle = $nt;
00795         }
00796 
00802         public function getLocalFile() {
00803                 if( is_null( $this->mLocalFile ) ) {
00804                         $nt = $this->getTitle();
00805                         $this->mLocalFile = is_null( $nt ) ? null : wfLocalFile( $nt );
00806                 }
00807                 return $this->mLocalFile;
00808         }
00809 
00821         public function stashFile() {
00822                 // was stashSessionFile
00823                 wfProfileIn( __METHOD__ );
00824 
00825                 $stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash();
00826                 $file = $stash->stashFile( $this->mTempPath, $this->getSourceType() );
00827                 $this->mLocalFile = $file;
00828 
00829                 wfProfileOut( __METHOD__ );
00830                 return $file;
00831         }
00832 
00838         public function stashFileGetKey() {
00839                 return $this->stashFile()->getFileKey();
00840         }
00841 
00847         public function stashSession() {
00848                 return $this->stashFileGetKey();
00849         }
00850 
00855         public function cleanupTempFile() {
00856                 if ( $this->mRemoveTempFile && $this->mTempPath && file_exists( $this->mTempPath ) ) {
00857                         wfDebug( __METHOD__ . ": Removing temporary file {$this->mTempPath}\n" );
00858                         unlink( $this->mTempPath );
00859                 }
00860         }
00861 
00862         public function getTempPath() {
00863                 return $this->mTempPath;
00864         }
00865 
00875         public static function splitExtensions( $filename ) {
00876                 $bits = explode( '.', $filename );
00877                 $basename = array_shift( $bits );
00878                 return array( $basename, $bits );
00879         }
00880 
00889         public static function checkFileExtension( $ext, $list ) {
00890                 return in_array( strtolower( $ext ), $list );
00891         }
00892 
00901         public static function checkFileExtensionList( $ext, $list ) {
00902                 return array_intersect( array_map( 'strtolower', $ext ), $list );
00903         }
00904 
00912         public static function verifyExtension( $mime, $extension ) {
00913                 $magic = MimeMagic::singleton();
00914 
00915                 if ( !$mime || $mime == 'unknown' || $mime == 'unknown/unknown' )
00916                         if ( !$magic->isRecognizableExtension( $extension ) ) {
00917                                 wfDebug( __METHOD__ . ": passing file with unknown detected mime type; " .
00918                                         "unrecognized extension '$extension', can't verify\n" );
00919                                 return true;
00920                         } else {
00921                                 wfDebug( __METHOD__ . ": rejecting file with unknown detected mime type; ".
00922                                         "recognized extension '$extension', so probably invalid file\n" );
00923                                 return false;
00924                         }
00925 
00926                 $match = $magic->isMatchingExtension( $extension, $mime );
00927 
00928                 if ( $match === null ) {
00929                         wfDebug( __METHOD__ . ": no file extension known for mime type $mime, passing file\n" );
00930                         return true;
00931                 } elseif( $match === true ) {
00932                         wfDebug( __METHOD__ . ": mime type $mime matches extension $extension, passing file\n" );
00933 
00934                         #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
00935                         return true;
00936 
00937                 } else {
00938                         wfDebug( __METHOD__ . ": mime type $mime mismatches file extension $extension, rejecting file\n" );
00939                         return false;
00940                 }
00941         }
00942 
00954         public static function detectScript( $file, $mime, $extension ) {
00955                 global $wgAllowTitlesInSVG;
00956                 wfProfileIn( __METHOD__ );
00957 
00958                 # ugly hack: for text files, always look at the entire file.
00959                 # For binary field, just check the first K.
00960 
00961                 if( strpos( $mime,'text/' ) === 0 ) {
00962                         $chunk = file_get_contents( $file );
00963                 } else {
00964                         $fp = fopen( $file, 'rb' );
00965                         $chunk = fread( $fp, 1024 );
00966                         fclose( $fp );
00967                 }
00968 
00969                 $chunk = strtolower( $chunk );
00970 
00971                 if( !$chunk ) {
00972                         wfProfileOut( __METHOD__ );
00973                         return false;
00974                 }
00975 
00976                 # decode from UTF-16 if needed (could be used for obfuscation).
00977                 if( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
00978                         $enc = 'UTF-16BE';
00979                 } elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
00980                         $enc = 'UTF-16LE';
00981                 } else {
00982                         $enc = null;
00983                 }
00984 
00985                 if( $enc ) {
00986                         $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
00987                 }
00988 
00989                 $chunk = trim( $chunk );
00990 
00991                 # @todo FIXME: Convert from UTF-16 if necessarry!
00992                 wfDebug( __METHOD__ . ": checking for embedded scripts and HTML stuff\n" );
00993 
00994                 # check for HTML doctype
00995                 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
00996                         wfProfileOut( __METHOD__ );
00997                         return true;
00998                 }
00999 
01000                 // Some browsers will interpret obscure xml encodings as UTF-8, while
01001                 // PHP/expat will interpret the given encoding in the xml declaration (bug 47304)
01002                 if ( $extension == 'svg' || strpos( $mime, 'image/svg' ) === 0 ) {
01003                         if ( self::checkXMLEncodingMissmatch( $file ) ) {
01004                                 wfProfileOut( __METHOD__ );
01005                                 return true;
01006                         }
01007                 }
01008 
01024                 $tags = array(
01025                         '<a href',
01026                         '<body',
01027                         '<head',
01028                         '<html',   #also in safari
01029                         '<img',
01030                         '<pre',
01031                         '<script', #also in safari
01032                         '<table'
01033                 );
01034 
01035                 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
01036                         $tags[] = '<title';
01037                 }
01038 
01039                 foreach( $tags as $tag ) {
01040                         if( false !== strpos( $chunk, $tag ) ) {
01041                                 wfDebug( __METHOD__ . ": found something that may make it be mistaken for html: $tag\n" );
01042                                 wfProfileOut( __METHOD__ );
01043                                 return true;
01044                         }
01045                 }
01046 
01047                 /*
01048                  * look for JavaScript
01049                  */
01050 
01051                 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
01052                 $chunk = Sanitizer::decodeCharReferences( $chunk );
01053 
01054                 # look for script-types
01055                 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
01056                         wfDebug( __METHOD__ . ": found script types\n" );
01057                         wfProfileOut( __METHOD__ );
01058                         return true;
01059                 }
01060 
01061                 # look for html-style script-urls
01062                 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
01063                         wfDebug( __METHOD__ . ": found html-style script urls\n" );
01064                         wfProfileOut( __METHOD__ );
01065                         return true;
01066                 }
01067 
01068                 # look for css-style script-urls
01069                 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
01070                         wfDebug( __METHOD__ . ": found css-style script urls\n" );
01071                         wfProfileOut( __METHOD__ );
01072                         return true;
01073                 }
01074 
01075                 wfDebug( __METHOD__ . ": no scripts found\n" );
01076                 wfProfileOut( __METHOD__ );
01077                 return false;
01078         }
01079 
01080 
01088         public static function checkXMLEncodingMissmatch( $file ) {
01089                 global $wgSVGMetadataCutoff;
01090                 $contents = file_get_contents( $file, false, null, -1, $wgSVGMetadataCutoff );
01091                 $encodingRegex = '!encoding[ \t\n\r]*=[ \t\n\r]*[\'"](.*?)[\'"]!si';
01092 
01093                 if ( preg_match( "!<\?xml\b(.*?)\?>!si", $contents, $matches ) ) {
01094                         if ( preg_match( $encodingRegex, $matches[1], $encMatch )
01095                                 && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings )
01096                         ) {
01097                                 wfDebug( __METHOD__ . ": Found unsafe XML encoding '{$encMatch[1]}'\n" );
01098                                 return true;
01099                         }
01100                 } elseif ( preg_match( "!<\?xml\b!si", $contents ) ) {
01101                         // Start of XML declaration without an end in the first $wgSVGMetadataCutoff
01102                         // bytes. There shouldn't be a legitimate reason for this to happen.
01103                         wfDebug( __METHOD__ . ": Unmatched XML declaration start\n" );
01104                         return true;
01105                 } elseif ( substr( $contents, 0, 4) == "\x4C\x6F\xA7\x94" ) {
01106                         // EBCDIC encoded XML
01107                         wfDebug( __METHOD__ . ": EBCDIC Encoded XML\n" );
01108                         return true;
01109                 }
01110 
01111                 // It's possible the file is encoded with multi-byte encoding, so re-encode attempt to
01112                 // detect the encoding in case is specifies an encoding not whitelisted in self::$safeXmlEncodings
01113                 $attemptEncodings = array( 'UTF-16', 'UTF-16BE', 'UTF-32', 'UTF-32BE' );
01114                 foreach ( $attemptEncodings as $encoding ) {
01115                         wfSuppressWarnings();
01116                         $str = iconv( $encoding, 'UTF-8', $contents );
01117                         wfRestoreWarnings();
01118                         if ( $str != '' && preg_match( "!<\?xml\b(.*?)\?>!si", $str, $matches ) ) {
01119                                 if ( preg_match( $encodingRegex, $matches[1], $encMatch )
01120                                         && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings )
01121                                 ) {
01122                                         wfDebug( __METHOD__ . ": Found unsafe XML encoding '{$encMatch[1]}'\n" );
01123                                         return true;
01124                                 }
01125                         } elseif ( $str != '' && preg_match( "!<\?xml\b!si", $str ) ) {
01126                                 // Start of XML declaration without an end in the first $wgSVGMetadataCutoff
01127                                 // bytes. There shouldn't be a legitimate reason for this to happen.
01128                                 wfDebug( __METHOD__ . ": Unmatched XML declaration start\n" );
01129                                 return true;
01130                         }
01131                 }
01132 
01133                 return false;
01134         }
01135 
01140         protected function detectScriptInSvg( $filename ) {
01141                 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
01142                 return $check->filterMatch;
01143         }
01144 
01151         public function checkSvgScriptCallback( $element, $attribs ) {
01152                 $strippedElement = $this->stripXmlNamespace( $element );
01153 
01154                 /*
01155                  * check for elements that can contain javascript
01156                  */
01157                 if( $strippedElement == 'script' ) {
01158                         wfDebug( __METHOD__ . ": Found script element '$element' in uploaded file.\n" );
01159                         return true;
01160                 }
01161 
01162                 # e.g., <svg xmlns="http://www.w3.org/2000/svg"> <handler xmlns:ev="http://www.w3.org/2001/xml-events" ev:event="load">alert(1)</handler> </svg>
01163                 if( $strippedElement == 'handler' ) {
01164                         wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file.\n" );
01165                         return true;
01166                 }
01167 
01168                 # SVG reported in Feb '12 that used xml:stylesheet to generate javascript block
01169                 if( $strippedElement == 'stylesheet' ) {
01170                         wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file.\n" );
01171                         return true;
01172                 }
01173 
01174                 foreach( $attribs as $attrib => $value ) {
01175                         $stripped = $this->stripXmlNamespace( $attrib );
01176                         $value = strtolower($value);
01177 
01178                         if( substr( $stripped, 0, 2 ) == 'on' ) {
01179                                 wfDebug( __METHOD__ . ": Found event-handler attribute '$attrib'='$value' in uploaded file.\n" );
01180                                 return true;
01181                         }
01182 
01183                         # href with javascript target
01184                         if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
01185                                 wfDebug( __METHOD__ . ": Found script in href attribute '$attrib'='$value' in uploaded file.\n" );
01186                                 return true;
01187                         }
01188 
01189                         # href with embeded svg as target
01190                         if( $stripped == 'href' && preg_match( '!data:[^,]*image/svg[^,]*,!sim', $value ) ) {
01191                                 wfDebug( __METHOD__ . ": Found href to embedded svg \"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
01192                                 return true;
01193                         }
01194 
01195                         # href with embeded (text/xml) svg as target
01196                         if( $stripped == 'href' && preg_match( '!data:[^,]*text/xml[^,]*,!sim', $value ) ) {
01197                                 wfDebug( __METHOD__ . ": Found href to embedded svg \"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
01198                                 return true;
01199                         }
01200 
01201                         # use set/animate to add event-handler attribute to parent
01202                         if( ( $strippedElement == 'set' || $strippedElement == 'animate' ) && $stripped == 'attributename' && substr( $value, 0, 2 ) == 'on' ) {
01203                                 wfDebug( __METHOD__ . ": Found svg setting event-handler attribute with \"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
01204                                 return true;
01205                         }
01206 
01207                         # use set to add href attribute to parent element
01208                         if( $strippedElement == 'set' && $stripped == 'attributename' && strpos( $value, 'href' ) !== false ) {
01209                                 wfDebug( __METHOD__ . ": Found svg setting href attibute '$value' in uploaded file.\n" );
01210                                 return true;
01211                         }
01212 
01213                         # use set to add a remote / data / script target to an element
01214                         if( $strippedElement == 'set' && $stripped == 'to' &&  preg_match( '!(http|https|data|script):!sim', $value ) ) {
01215                                 wfDebug( __METHOD__ . ": Found svg setting attibute to '$value' in uploaded file.\n" );
01216                                 return true;
01217                         }
01218 
01219 
01220                         # use handler attribute with remote / data / script
01221                         if( $stripped == 'handler' &&  preg_match( '!(http|https|data|script):!sim', $value ) ) {
01222                                 wfDebug( __METHOD__ . ": Found svg setting handler with remote/data/script '$attrib'='$value' in uploaded file.\n" );
01223                                 return true;
01224                         }
01225 
01226                         # use CSS styles to bring in remote code
01227                         # catch url("http:..., url('http:..., url(http:..., but not url("#..., url('#..., url(#....
01228                         if( $stripped == 'style' && preg_match_all( '!((?:font|clip-path|fill|filter|marker|marker-end|marker-mid|marker-start|mask|stroke)\s*:\s*url\s*\(\s*["\']?\s*[^#]+.*?\))!sim', $value, $matches ) ) {
01229                                 foreach ($matches[1] as $match) {
01230                                         if (!preg_match( '!(?:font|clip-path|fill|filter|marker|marker-end|marker-mid|marker-start|mask|stroke)\s*:\s*url\s*\(\s*(#|\'#|"#)!sim', $match ) ) {
01231                                                 wfDebug( __METHOD__ . ": Found svg setting a style with remote url '$attrib'='$value' in uploaded file.\n" );
01232                                                 return true;
01233                                         }
01234                                 }
01235                         }
01236 
01237                         # image filters can pull in url, which could be svg that executes scripts
01238                         if( $strippedElement == 'image' && $stripped == 'filter' && preg_match( '!url\s*\(!sim', $value ) ) {
01239                                 wfDebug( __METHOD__ . ": Found image filter with url: \"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
01240                                 return true;
01241                         }
01242 
01243                 }
01244 
01245                 return false; //No scripts detected
01246         }
01247 
01252         private function stripXmlNamespace( $name ) {
01253                 // 'http://www.w3.org/2000/svg:script' -> 'script'
01254                 $parts = explode( ':', strtolower( $name ) );
01255                 return array_pop( $parts );
01256         }
01257 
01268         public static function detectVirus( $file ) {
01269                 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
01270                 wfProfileIn( __METHOD__ );
01271 
01272                 if ( !$wgAntivirus ) {
01273                         wfDebug( __METHOD__ . ": virus scanner disabled\n" );
01274                         wfProfileOut( __METHOD__ );
01275                         return null;
01276                 }
01277 
01278                 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
01279                         wfDebug( __METHOD__ . ": unknown virus scanner: $wgAntivirus\n" );
01280                         $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
01281                                 array( 'virus-badscanner', $wgAntivirus ) );
01282                         wfProfileOut( __METHOD__ );
01283                         return wfMessage( 'virus-unknownscanner' )->text() . " $wgAntivirus";
01284                 }
01285 
01286                 # look up scanner configuration
01287                 $command = $wgAntivirusSetup[$wgAntivirus]['command'];
01288                 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
01289                 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
01290                         $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
01291 
01292                 if ( strpos( $command, "%f" ) === false ) {
01293                         # simple pattern: append file to scan
01294                         $command .= " " . wfEscapeShellArg( $file );
01295                 } else {
01296                         # complex pattern: replace "%f" with file to scan
01297                         $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
01298                 }
01299 
01300                 wfDebug( __METHOD__ . ": running virus scan: $command \n" );
01301 
01302                 # execute virus scanner
01303                 $exitCode = false;
01304 
01305                 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
01306                 #      that does not seem to be worth the pain.
01307                 #      Ask me (Duesentrieb) about it if it's ever needed.
01308                 $output = wfShellExec( "$command 2>&1", $exitCode );
01309 
01310                 # map exit code to AV_xxx constants.
01311                 $mappedCode = $exitCode;
01312                 if ( $exitCodeMap ) {
01313                         if ( isset( $exitCodeMap[$exitCode] ) ) {
01314                                 $mappedCode = $exitCodeMap[$exitCode];
01315                         } elseif ( isset( $exitCodeMap["*"] ) ) {
01316                                 $mappedCode = $exitCodeMap["*"];
01317                         }
01318                 }
01319 
01320                 if ( $mappedCode === AV_SCAN_FAILED ) {
01321                         # scan failed (code was mapped to false by $exitCodeMap)
01322                         wfDebug( __METHOD__ . ": failed to scan $file (code $exitCode).\n" );
01323 
01324                         if ( $wgAntivirusRequired ) {
01325                                 wfProfileOut( __METHOD__ );
01326                                 return wfMessage( 'virus-scanfailed', array( $exitCode ) )->text();
01327                         } else {
01328                                 wfProfileOut( __METHOD__ );
01329                                 return null;
01330                         }
01331                 } elseif ( $mappedCode === AV_SCAN_ABORTED ) {
01332                         # scan failed because filetype is unknown (probably imune)
01333                         wfDebug( __METHOD__ . ": unsupported file type $file (code $exitCode).\n" );
01334                         wfProfileOut( __METHOD__ );
01335                         return null;
01336                 } elseif ( $mappedCode === AV_NO_VIRUS ) {
01337                         # no virus found
01338                         wfDebug( __METHOD__ . ": file passed virus scan.\n" );
01339                         wfProfileOut( __METHOD__ );
01340                         return false;
01341                 } else {
01342                         $output = trim( $output );
01343 
01344                         if ( !$output ) {
01345                                 $output = true; #if there's no output, return true
01346                         } elseif ( $msgPattern ) {
01347                                 $groups = array();
01348                                 if ( preg_match( $msgPattern, $output, $groups ) ) {
01349                                         if ( $groups[1] ) {
01350                                                 $output = $groups[1];
01351                                         }
01352                                 }
01353                         }
01354 
01355                         wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output \n" );
01356                         wfProfileOut( __METHOD__ );
01357                         return $output;
01358                 }
01359         }
01360 
01369         private function checkOverwrite( $user ) {
01370                 // First check whether the local file can be overwritten
01371                 $file = $this->getLocalFile();
01372                 if( $file->exists() ) {
01373                         if( !self::userCanReUpload( $user, $file ) ) {
01374                                 return array( 'fileexists-forbidden', $file->getName() );
01375                         } else {
01376                                 return true;
01377                         }
01378                 }
01379 
01380                 /* Check shared conflicts: if the local file does not exist, but
01381                  * wfFindFile finds a file, it exists in a shared repository.
01382                  */
01383                 $file = wfFindFile( $this->getTitle() );
01384                 if ( $file && !$user->isAllowed( 'reupload-shared' ) ) {
01385                         return array( 'fileexists-shared-forbidden', $file->getName() );
01386                 }
01387 
01388                 return true;
01389         }
01390 
01398         public static function userCanReUpload( User $user, $img ) {
01399                 if( $user->isAllowed( 'reupload' ) ) {
01400                         return true; // non-conditional
01401                 }
01402                 if( !$user->isAllowed( 'reupload-own' ) ) {
01403                         return false;
01404                 }
01405                 if( is_string( $img ) ) {
01406                         $img = wfLocalFile( $img );
01407                 }
01408                 if ( !( $img instanceof LocalFile ) ) {
01409                         return false;
01410                 }
01411 
01412                 return $user->getId() == $img->getUser( 'id' );
01413         }
01414 
01426         public static function getExistsWarning( $file ) {
01427                 if( $file->exists() ) {
01428                         return array( 'warning' => 'exists', 'file' => $file );
01429                 }
01430 
01431                 if( $file->getTitle()->getArticleID() ) {
01432                         return array( 'warning' => 'page-exists', 'file' => $file );
01433                 }
01434 
01435                 if ( $file->wasDeleted() && !$file->exists() ) {
01436                         return array( 'warning' => 'was-deleted', 'file' => $file );
01437                 }
01438 
01439                 if( strpos( $file->getName(), '.' ) == false ) {
01440                         $partname = $file->getName();
01441                         $extension = '';
01442                 } else {
01443                         $n = strrpos( $file->getName(), '.' );
01444                         $extension = substr( $file->getName(), $n + 1 );
01445                         $partname = substr( $file->getName(), 0, $n );
01446                 }
01447                 $normalizedExtension = File::normalizeExtension( $extension );
01448 
01449                 if ( $normalizedExtension != $extension ) {
01450                         // We're not using the normalized form of the extension.
01451                         // Normal form is lowercase, using most common of alternate
01452                         // extensions (eg 'jpg' rather than 'JPEG').
01453                         //
01454                         // Check for another file using the normalized form...
01455                         $nt_lc = Title::makeTitle( NS_FILE, "{$partname}.{$normalizedExtension}" );
01456                         $file_lc = wfLocalFile( $nt_lc );
01457 
01458                         if( $file_lc->exists() ) {
01459                                 return array(
01460                                         'warning' => 'exists-normalized',
01461                                         'file' => $file,
01462                                         'normalizedFile' => $file_lc
01463                                 );
01464                         }
01465                 }
01466 
01467                 if ( self::isThumbName( $file->getName() ) ) {
01468                         # Check for filenames like 50px- or 180px-, these are mostly thumbnails
01469                         $nt_thb = Title::newFromText( substr( $partname , strpos( $partname , '-' ) +1 ) . '.' . $extension, NS_FILE );
01470                         $file_thb = wfLocalFile( $nt_thb );
01471                         if( $file_thb->exists() ) {
01472                                 return array(
01473                                         'warning' => 'thumb',
01474                                         'file' => $file,
01475                                         'thumbFile' => $file_thb
01476                                 );
01477                         } else {
01478                                 // File does not exist, but we just don't like the name
01479                                 return array(
01480                                         'warning' => 'thumb-name',
01481                                         'file' => $file,
01482                                         'thumbFile' => $file_thb
01483                                 );
01484                         }
01485                 }
01486 
01487 
01488                 foreach( self::getFilenamePrefixBlacklist() as $prefix ) {
01489                         if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
01490                                 return array(
01491                                         'warning' => 'bad-prefix',
01492                                         'file' => $file,
01493                                         'prefix' => $prefix
01494                                 );
01495                         }
01496                 }
01497 
01498                 return false;
01499         }
01500 
01506         public static function isThumbName( $filename ) {
01507                 $n = strrpos( $filename, '.' );
01508                 $partname = $n ? substr( $filename, 0, $n ) : $filename;
01509                 return (
01510                                         substr( $partname , 3, 3 ) == 'px-' ||
01511                                         substr( $partname , 2, 3 ) == 'px-'
01512                                 ) &&
01513                                 preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) );
01514         }
01515 
01521         public static function getFilenamePrefixBlacklist() {
01522                 $blacklist = array();
01523                 $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
01524                 if( !$message->isDisabled() ) {
01525                         $lines = explode( "\n", $message->plain() );
01526                         foreach( $lines as $line ) {
01527                                 // Remove comment lines
01528                                 $comment = substr( trim( $line ), 0, 1 );
01529                                 if ( $comment == '#' || $comment == '' ) {
01530                                         continue;
01531                                 }
01532                                 // Remove additional comments after a prefix
01533                                 $comment = strpos( $line, '#' );
01534                                 if ( $comment > 0 ) {
01535                                         $line = substr( $line, 0, $comment-1 );
01536                                 }
01537                                 $blacklist[] = trim( $line );
01538                         }
01539                 }
01540                 return $blacklist;
01541         }
01542 
01553         public function getImageInfo( $result ) {
01554                 $file = $this->getLocalFile();
01555                 // TODO This cries out for refactoring. We really want to say $file->getAllInfo(); here.
01556                 // Perhaps "info" methods should be moved into files, and the API should just wrap them in queries.
01557                 if ( $file instanceof UploadStashFile ) {
01558                         $imParam = ApiQueryStashImageInfo::getPropertyNames();
01559                         $info = ApiQueryStashImageInfo::getInfo( $file, array_flip( $imParam ), $result );
01560                 } else {
01561                         $imParam = ApiQueryImageInfo::getPropertyNames();
01562                         $info = ApiQueryImageInfo::getInfo( $file, array_flip( $imParam ), $result );
01563                 }
01564                 return $info;
01565         }
01566 
01571         public function convertVerifyErrorToStatus( $error ) {
01572                 $code = $error['status'];
01573                 unset( $code['status'] );
01574                 return Status::newFatal( $this->getVerificationErrorCode( $code ), $error );
01575         }
01576 
01581         public static function getMaxUploadSize( $forType = null ) {
01582                 global $wgMaxUploadSize;
01583 
01584                 if ( is_array( $wgMaxUploadSize ) ) {
01585                         if ( !is_null( $forType ) && isset( $wgMaxUploadSize[$forType] ) ) {
01586                                 return $wgMaxUploadSize[$forType];
01587                         } else {
01588                                 return $wgMaxUploadSize['*'];
01589                         }
01590                 } else {
01591                         return intval( $wgMaxUploadSize );
01592                 }
01593 
01594         }
01595 }