MediaWiki
REL1_22
|
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, $mSVGNSError; 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 00068 const SESSION_STATUS_KEY = 'wsUploadStatusData'; 00069 00074 public function getVerificationErrorCode( $error ) { 00075 $code_to_status = array( 00076 self::EMPTY_FILE => 'empty-file', 00077 self::FILE_TOO_LARGE => 'file-too-large', 00078 self::FILETYPE_MISSING => 'filetype-missing', 00079 self::FILETYPE_BADTYPE => 'filetype-banned', 00080 self::MIN_LENGTH_PARTNAME => 'filename-tooshort', 00081 self::ILLEGAL_FILENAME => 'illegal-filename', 00082 self::OVERWRITE_EXISTING_FILE => 'overwrite', 00083 self::VERIFICATION_ERROR => 'verification-error', 00084 self::HOOK_ABORTED => 'hookaborted', 00085 self::WINDOWS_NONASCII_FILENAME => 'windows-nonascii-filename', 00086 self::FILENAME_TOO_LONG => 'filename-toolong', 00087 ); 00088 if ( isset( $code_to_status[$error] ) ) { 00089 return $code_to_status[$error]; 00090 } 00091 00092 return 'unknown-error'; 00093 } 00094 00100 public static function isEnabled() { 00101 global $wgEnableUploads; 00102 00103 if ( !$wgEnableUploads ) { 00104 return false; 00105 } 00106 00107 # Check php's file_uploads setting 00108 return wfIsHipHop() || wfIniGetBool( 'file_uploads' ); 00109 } 00110 00119 public static function isAllowed( $user ) { 00120 foreach ( array( 'upload', 'edit' ) as $permission ) { 00121 if ( !$user->isAllowed( $permission ) ) { 00122 return $permission; 00123 } 00124 } 00125 return true; 00126 } 00127 00128 // Upload handlers. Should probably just be a global. 00129 static $uploadHandlers = array( 'Stash', 'File', 'Url' ); 00130 00138 public static function createFromRequest( &$request, $type = null ) { 00139 $type = $type ? $type : $request->getVal( 'wpSourceType', 'File' ); 00140 00141 if ( !$type ) { 00142 return null; 00143 } 00144 00145 // Get the upload class 00146 $type = ucfirst( $type ); 00147 00148 // Give hooks the chance to handle this request 00149 $className = null; 00150 wfRunHooks( 'UploadCreateFromRequest', array( $type, &$className ) ); 00151 if ( is_null( $className ) ) { 00152 $className = 'UploadFrom' . $type; 00153 wfDebug( __METHOD__ . ": class name: $className\n" ); 00154 if ( !in_array( $type, self::$uploadHandlers ) ) { 00155 return null; 00156 } 00157 } 00158 00159 // Check whether this upload class is enabled 00160 if ( !call_user_func( array( $className, 'isEnabled' ) ) ) { 00161 return null; 00162 } 00163 00164 // Check whether the request is valid 00165 if ( !call_user_func( array( $className, 'isValidRequest' ), $request ) ) { 00166 return null; 00167 } 00168 00169 $handler = new $className; 00170 00171 $handler->initializeFromRequest( $request ); 00172 return $handler; 00173 } 00174 00180 public static function isValidRequest( $request ) { 00181 return false; 00182 } 00183 00184 public function __construct() {} 00185 00192 public function getSourceType() { 00193 return null; 00194 } 00195 00204 public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) { 00205 $this->mDesiredDestName = $name; 00206 if ( FileBackend::isStoragePath( $tempPath ) ) { 00207 throw new MWException( __METHOD__ . " given storage path `$tempPath`." ); 00208 } 00209 $this->mTempPath = $tempPath; 00210 $this->mFileSize = $fileSize; 00211 $this->mRemoveTempFile = $removeTempFile; 00212 } 00213 00217 abstract public function initializeFromRequest( &$request ); 00218 00223 public function fetchFile() { 00224 return Status::newGood(); 00225 } 00226 00231 public function isEmptyFile() { 00232 return empty( $this->mFileSize ); 00233 } 00234 00239 public function getFileSize() { 00240 return $this->mFileSize; 00241 } 00242 00247 public function getTempFileSha1Base36() { 00248 return FSFile::getSha1Base36FromPath( $this->mTempPath ); 00249 } 00250 00255 function getRealPath( $srcPath ) { 00256 wfProfileIn( __METHOD__ ); 00257 $repo = RepoGroup::singleton()->getLocalRepo(); 00258 if ( $repo->isVirtualUrl( $srcPath ) ) { 00259 // @todo just make uploads work with storage paths 00260 // UploadFromStash loads files via virtual URLs 00261 $tmpFile = $repo->getLocalCopy( $srcPath ); 00262 if ( $tmpFile ) { 00263 $tmpFile->bind( $this ); // keep alive with $this 00264 } 00265 $path = $tmpFile ? $tmpFile->getPath() : false; 00266 } else { 00267 $path = $srcPath; 00268 } 00269 wfProfileOut( __METHOD__ ); 00270 return $path; 00271 } 00272 00277 public function verifyUpload() { 00278 wfProfileIn( __METHOD__ ); 00279 00283 if ( $this->isEmptyFile() ) { 00284 wfProfileOut( __METHOD__ ); 00285 return array( 'status' => self::EMPTY_FILE ); 00286 } 00287 00291 $maxSize = self::getMaxUploadSize( $this->getSourceType() ); 00292 if ( $this->mFileSize > $maxSize ) { 00293 wfProfileOut( __METHOD__ ); 00294 return array( 00295 'status' => self::FILE_TOO_LARGE, 00296 'max' => $maxSize, 00297 ); 00298 } 00299 00305 $verification = $this->verifyFile(); 00306 if ( $verification !== true ) { 00307 wfProfileOut( __METHOD__ ); 00308 return array( 00309 'status' => self::VERIFICATION_ERROR, 00310 'details' => $verification 00311 ); 00312 } 00313 00317 $result = $this->validateName(); 00318 if ( $result !== true ) { 00319 wfProfileOut( __METHOD__ ); 00320 return $result; 00321 } 00322 00323 $error = ''; 00324 if ( !wfRunHooks( 'UploadVerification', 00325 array( $this->mDestName, $this->mTempPath, &$error ) ) ) 00326 { 00327 wfProfileOut( __METHOD__ ); 00328 return array( 'status' => self::HOOK_ABORTED, 'error' => $error ); 00329 } 00330 00331 wfProfileOut( __METHOD__ ); 00332 return array( 'status' => self::OK ); 00333 } 00334 00341 public function validateName() { 00342 $nt = $this->getTitle(); 00343 if ( is_null( $nt ) ) { 00344 $result = array( 'status' => $this->mTitleError ); 00345 if ( $this->mTitleError == self::ILLEGAL_FILENAME ) { 00346 $result['filtered'] = $this->mFilteredName; 00347 } 00348 if ( $this->mTitleError == self::FILETYPE_BADTYPE ) { 00349 $result['finalExt'] = $this->mFinalExtension; 00350 if ( count( $this->mBlackListedExtensions ) ) { 00351 $result['blacklistedExt'] = $this->mBlackListedExtensions; 00352 } 00353 } 00354 return $result; 00355 } 00356 $this->mDestName = $this->getLocalFile()->getName(); 00357 00358 return true; 00359 } 00360 00369 protected function verifyMimeType( $mime ) { 00370 global $wgVerifyMimeType; 00371 wfProfileIn( __METHOD__ ); 00372 if ( $wgVerifyMimeType ) { 00373 wfDebug( "\n\nmime: <$mime> extension: <{$this->mFinalExtension}>\n\n" ); 00374 global $wgMimeTypeBlacklist; 00375 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) { 00376 wfProfileOut( __METHOD__ ); 00377 return array( 'filetype-badmime', $mime ); 00378 } 00379 00380 # Check IE type 00381 $fp = fopen( $this->mTempPath, 'rb' ); 00382 $chunk = fread( $fp, 256 ); 00383 fclose( $fp ); 00384 00385 $magic = MimeMagic::singleton(); 00386 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension ); 00387 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath, $chunk, $extMime ); 00388 foreach ( $ieTypes as $ieType ) { 00389 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) { 00390 wfProfileOut( __METHOD__ ); 00391 return array( 'filetype-bad-ie-mime', $ieType ); 00392 } 00393 } 00394 } 00395 00396 wfProfileOut( __METHOD__ ); 00397 return true; 00398 } 00399 00400 00406 protected function verifyFile() { 00407 global $wgVerifyMimeType; 00408 wfProfileIn( __METHOD__ ); 00409 00410 $status = $this->verifyPartialFile(); 00411 if ( $status !== true ) { 00412 wfProfileOut( __METHOD__ ); 00413 return $status; 00414 } 00415 00416 $this->mFileProps = FSFile::getPropsFromPath( $this->mTempPath, $this->mFinalExtension ); 00417 $mime = $this->mFileProps['file-mime']; 00418 00419 if ( $wgVerifyMimeType ) { 00420 # XXX: Missing extension will be caught by validateName() via getTitle() 00421 if ( $this->mFinalExtension != '' && !$this->verifyExtension( $mime, $this->mFinalExtension ) ) { 00422 wfProfileOut( __METHOD__ ); 00423 return array( 'filetype-mime-mismatch', $this->mFinalExtension, $mime ); 00424 } 00425 } 00426 00427 00428 $handler = MediaHandler::getHandler( $mime ); 00429 if ( $handler ) { 00430 $handlerStatus = $handler->verifyUpload( $this->mTempPath ); 00431 if ( !$handlerStatus->isOK() ) { 00432 $errors = $handlerStatus->getErrorsArray(); 00433 wfProfileOut( __METHOD__ ); 00434 return reset( $errors ); 00435 } 00436 } 00437 00438 wfRunHooks( 'UploadVerifyFile', array( $this, $mime, &$status ) ); 00439 if ( $status !== true ) { 00440 wfProfileOut( __METHOD__ ); 00441 return $status; 00442 } 00443 00444 wfDebug( __METHOD__ . ": all clear; passing.\n" ); 00445 wfProfileOut( __METHOD__ ); 00446 return true; 00447 } 00448 00457 protected function verifyPartialFile() { 00458 global $wgAllowJavaUploads, $wgDisableUploadScriptChecks; 00459 wfProfileIn( __METHOD__ ); 00460 00461 # getTitle() sets some internal parameters like $this->mFinalExtension 00462 $this->getTitle(); 00463 00464 $this->mFileProps = FSFile::getPropsFromPath( $this->mTempPath, $this->mFinalExtension ); 00465 00466 # check mime type, if desired 00467 $mime = $this->mFileProps['file-mime']; 00468 $status = $this->verifyMimeType( $mime ); 00469 if ( $status !== true ) { 00470 wfProfileOut( __METHOD__ ); 00471 return $status; 00472 } 00473 00474 # check for htmlish code and javascript 00475 if ( !$wgDisableUploadScriptChecks ) { 00476 if ( self::detectScript( $this->mTempPath, $mime, $this->mFinalExtension ) ) { 00477 wfProfileOut( __METHOD__ ); 00478 return array( 'uploadscripted' ); 00479 } 00480 if ( $this->mFinalExtension == 'svg' || $mime == 'image/svg+xml' ) { 00481 $svgStatus = $this->detectScriptInSvg( $this->mTempPath ); 00482 if ( $svgStatus !== false ) { 00483 wfProfileOut( __METHOD__ ); 00484 return $svgStatus; 00485 } 00486 } 00487 } 00488 00489 # Check for Java applets, which if uploaded can bypass cross-site 00490 # restrictions. 00491 if ( !$wgAllowJavaUploads ) { 00492 $this->mJavaDetected = false; 00493 $zipStatus = ZipDirectoryReader::read( $this->mTempPath, 00494 array( $this, 'zipEntryCallback' ) ); 00495 if ( !$zipStatus->isOK() ) { 00496 $errors = $zipStatus->getErrorsArray(); 00497 $error = reset( $errors ); 00498 if ( $error[0] !== 'zip-wrong-format' ) { 00499 wfProfileOut( __METHOD__ ); 00500 return $error; 00501 } 00502 } 00503 if ( $this->mJavaDetected ) { 00504 wfProfileOut( __METHOD__ ); 00505 return array( 'uploadjava' ); 00506 } 00507 } 00508 00509 # Scan the uploaded file for viruses 00510 $virus = $this->detectVirus( $this->mTempPath ); 00511 if ( $virus ) { 00512 wfProfileOut( __METHOD__ ); 00513 return array( 'uploadvirus', $virus ); 00514 } 00515 00516 wfProfileOut( __METHOD__ ); 00517 return true; 00518 } 00519 00523 function zipEntryCallback( $entry ) { 00524 $names = array( $entry['name'] ); 00525 00526 // If there is a null character, cut off the name at it, because JDK's 00527 // ZIP_GetEntry() uses strcmp() if the name hashes match. If a file name 00528 // were constructed which had ".class\0" followed by a string chosen to 00529 // make the hash collide with the truncated name, that file could be 00530 // returned in response to a request for the .class file. 00531 $nullPos = strpos( $entry['name'], "\000" ); 00532 if ( $nullPos !== false ) { 00533 $names[] = substr( $entry['name'], 0, $nullPos ); 00534 } 00535 00536 // If there is a trailing slash in the file name, we have to strip it, 00537 // because that's what ZIP_GetEntry() does. 00538 if ( preg_grep( '!\.class/?$!', $names ) ) { 00539 $this->mJavaDetected = true; 00540 } 00541 } 00542 00550 public function verifyPermissions( $user ) { 00551 return $this->verifyTitlePermissions( $user ); 00552 } 00553 00565 public function verifyTitlePermissions( $user ) { 00570 $nt = $this->getTitle(); 00571 if ( is_null( $nt ) ) { 00572 return true; 00573 } 00574 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user ); 00575 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user ); 00576 if ( !$nt->exists() ) { 00577 $permErrorsCreate = $nt->getUserPermissionsErrors( 'create', $user ); 00578 } else { 00579 $permErrorsCreate = array(); 00580 } 00581 if ( $permErrors || $permErrorsUpload || $permErrorsCreate ) { 00582 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) ); 00583 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) ); 00584 return $permErrors; 00585 } 00586 00587 $overwriteError = $this->checkOverwrite( $user ); 00588 if ( $overwriteError !== true ) { 00589 return array( $overwriteError ); 00590 } 00591 00592 return true; 00593 } 00594 00602 public function checkWarnings() { 00603 global $wgLang; 00604 wfProfileIn( __METHOD__ ); 00605 00606 $warnings = array(); 00607 00608 $localFile = $this->getLocalFile(); 00609 $filename = $localFile->getName(); 00610 00615 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName ); 00616 $comparableName = Title::capitalize( $comparableName, NS_FILE ); 00617 00618 if ( $this->mDesiredDestName != $filename && $comparableName != $filename ) { 00619 $warnings['badfilename'] = $filename; 00620 } 00621 00622 // Check whether the file extension is on the unwanted list 00623 global $wgCheckFileExtensions, $wgFileExtensions; 00624 if ( $wgCheckFileExtensions ) { 00625 $extensions = array_unique( $wgFileExtensions ); 00626 if ( !$this->checkFileExtension( $this->mFinalExtension, $extensions ) ) { 00627 $warnings['filetype-unwanted-type'] = array( $this->mFinalExtension, 00628 $wgLang->commaList( $extensions ), count( $extensions ) ); 00629 } 00630 } 00631 00632 global $wgUploadSizeWarning; 00633 if ( $wgUploadSizeWarning && ( $this->mFileSize > $wgUploadSizeWarning ) ) { 00634 $warnings['large-file'] = array( $wgUploadSizeWarning, $this->mFileSize ); 00635 } 00636 00637 if ( $this->mFileSize == 0 ) { 00638 $warnings['emptyfile'] = true; 00639 } 00640 00641 $exists = self::getExistsWarning( $localFile ); 00642 if ( $exists !== false ) { 00643 $warnings['exists'] = $exists; 00644 } 00645 00646 // Check dupes against existing files 00647 $hash = $this->getTempFileSha1Base36(); 00648 $dupes = RepoGroup::singleton()->findBySha1( $hash ); 00649 $title = $this->getTitle(); 00650 // Remove all matches against self 00651 foreach ( $dupes as $key => $dupe ) { 00652 if ( $title->equals( $dupe->getTitle() ) ) { 00653 unset( $dupes[$key] ); 00654 } 00655 } 00656 if ( $dupes ) { 00657 $warnings['duplicate'] = $dupes; 00658 } 00659 00660 // Check dupes against archives 00661 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" ); 00662 if ( $archivedImage->getID() > 0 ) { 00663 $warnings['duplicate-archive'] = $archivedImage->getName(); 00664 } 00665 00666 wfProfileOut( __METHOD__ ); 00667 return $warnings; 00668 } 00669 00681 public function performUpload( $comment, $pageText, $watch, $user ) { 00682 wfProfileIn( __METHOD__ ); 00683 00684 $status = $this->getLocalFile()->upload( 00685 $this->mTempPath, 00686 $comment, 00687 $pageText, 00688 File::DELETE_SOURCE, 00689 $this->mFileProps, 00690 false, 00691 $user 00692 ); 00693 00694 if ( $status->isGood() ) { 00695 if ( $watch ) { 00696 WatchAction::doWatch( $this->getLocalFile()->getTitle(), $user, WatchedItem::IGNORE_USER_RIGHTS ); 00697 } 00698 wfRunHooks( 'UploadComplete', array( &$this ) ); 00699 } 00700 00701 wfProfileOut( __METHOD__ ); 00702 return $status; 00703 } 00704 00711 public function getTitle() { 00712 if ( $this->mTitle !== false ) { 00713 return $this->mTitle; 00714 } 00715 /* Assume that if a user specified File:Something.jpg, this is an error 00716 * and that the namespace prefix needs to be stripped of. 00717 */ 00718 $title = Title::newFromText( $this->mDesiredDestName ); 00719 if ( $title && $title->getNamespace() == NS_FILE ) { 00720 $this->mFilteredName = $title->getDBkey(); 00721 } else { 00722 $this->mFilteredName = $this->mDesiredDestName; 00723 } 00724 00725 # oi_archive_name is max 255 bytes, which include a timestamp and an 00726 # exclamation mark, so restrict file name to 240 bytes. 00727 if ( strlen( $this->mFilteredName ) > 240 ) { 00728 $this->mTitleError = self::FILENAME_TOO_LONG; 00729 return $this->mTitle = null; 00730 } 00731 00737 $this->mFilteredName = wfStripIllegalFilenameChars( $this->mFilteredName ); 00738 /* Normalize to title form before we do any further processing */ 00739 $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName ); 00740 if ( is_null( $nt ) ) { 00741 $this->mTitleError = self::ILLEGAL_FILENAME; 00742 return $this->mTitle = null; 00743 } 00744 $this->mFilteredName = $nt->getDBkey(); 00745 00750 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName ); 00751 00752 if ( count( $ext ) ) { 00753 $this->mFinalExtension = trim( $ext[count( $ext ) - 1] ); 00754 } else { 00755 $this->mFinalExtension = ''; 00756 00757 # No extension, try guessing one 00758 $magic = MimeMagic::singleton(); 00759 $mime = $magic->guessMimeType( $this->mTempPath ); 00760 if ( $mime !== 'unknown/unknown' ) { 00761 # Get a space separated list of extensions 00762 $extList = $magic->getExtensionsForType( $mime ); 00763 if ( $extList ) { 00764 # Set the extension to the canonical extension 00765 $this->mFinalExtension = strtok( $extList, ' ' ); 00766 00767 # Fix up the other variables 00768 $this->mFilteredName .= ".{$this->mFinalExtension}"; 00769 $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName ); 00770 $ext = array( $this->mFinalExtension ); 00771 } 00772 } 00773 } 00774 00775 /* Don't allow users to override the blacklist (check file extension) */ 00776 global $wgCheckFileExtensions, $wgStrictFileExtensions; 00777 global $wgFileExtensions, $wgFileBlacklist; 00778 00779 $blackListedExtensions = $this->checkFileExtensionList( $ext, $wgFileBlacklist ); 00780 00781 if ( $this->mFinalExtension == '' ) { 00782 $this->mTitleError = self::FILETYPE_MISSING; 00783 return $this->mTitle = null; 00784 } elseif ( $blackListedExtensions || 00785 ( $wgCheckFileExtensions && $wgStrictFileExtensions && 00786 !$this->checkFileExtensionList( $ext, $wgFileExtensions ) ) ) { 00787 $this->mBlackListedExtensions = $blackListedExtensions; 00788 $this->mTitleError = self::FILETYPE_BADTYPE; 00789 return $this->mTitle = null; 00790 } 00791 00792 // Windows may be broken with special characters, see bug XXX 00793 if ( wfIsWindows() && !preg_match( '/^[\x0-\x7f]*$/', $nt->getText() ) ) { 00794 $this->mTitleError = self::WINDOWS_NONASCII_FILENAME; 00795 return $this->mTitle = null; 00796 } 00797 00798 # If there was more than one "extension", reassemble the base 00799 # filename to prevent bogus complaints about length 00800 if ( count( $ext ) > 1 ) { 00801 for ( $i = 0; $i < count( $ext ) - 1; $i++ ) { 00802 $partname .= '.' . $ext[$i]; 00803 } 00804 } 00805 00806 if ( strlen( $partname ) < 1 ) { 00807 $this->mTitleError = self::MIN_LENGTH_PARTNAME; 00808 return $this->mTitle = null; 00809 } 00810 00811 return $this->mTitle = $nt; 00812 } 00813 00819 public function getLocalFile() { 00820 if ( is_null( $this->mLocalFile ) ) { 00821 $nt = $this->getTitle(); 00822 $this->mLocalFile = is_null( $nt ) ? null : wfLocalFile( $nt ); 00823 } 00824 return $this->mLocalFile; 00825 } 00826 00839 public function stashFile( User $user = null ) { 00840 // was stashSessionFile 00841 wfProfileIn( __METHOD__ ); 00842 00843 $stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash( $user ); 00844 $file = $stash->stashFile( $this->mTempPath, $this->getSourceType() ); 00845 $this->mLocalFile = $file; 00846 00847 wfProfileOut( __METHOD__ ); 00848 return $file; 00849 } 00850 00856 public function stashFileGetKey() { 00857 return $this->stashFile()->getFileKey(); 00858 } 00859 00865 public function stashSession() { 00866 return $this->stashFileGetKey(); 00867 } 00868 00873 public function cleanupTempFile() { 00874 if ( $this->mRemoveTempFile && $this->mTempPath && file_exists( $this->mTempPath ) ) { 00875 wfDebug( __METHOD__ . ": Removing temporary file {$this->mTempPath}\n" ); 00876 unlink( $this->mTempPath ); 00877 } 00878 } 00879 00880 public function getTempPath() { 00881 return $this->mTempPath; 00882 } 00883 00893 public static function splitExtensions( $filename ) { 00894 $bits = explode( '.', $filename ); 00895 $basename = array_shift( $bits ); 00896 return array( $basename, $bits ); 00897 } 00898 00907 public static function checkFileExtension( $ext, $list ) { 00908 return in_array( strtolower( $ext ), $list ); 00909 } 00910 00919 public static function checkFileExtensionList( $ext, $list ) { 00920 return array_intersect( array_map( 'strtolower', $ext ), $list ); 00921 } 00922 00930 public static function verifyExtension( $mime, $extension ) { 00931 $magic = MimeMagic::singleton(); 00932 00933 if ( !$mime || $mime == 'unknown' || $mime == 'unknown/unknown' ) { 00934 if ( !$magic->isRecognizableExtension( $extension ) ) { 00935 wfDebug( __METHOD__ . ": passing file with unknown detected mime type; " . 00936 "unrecognized extension '$extension', can't verify\n" ); 00937 return true; 00938 } else { 00939 wfDebug( __METHOD__ . ": rejecting file with unknown detected mime type; " . 00940 "recognized extension '$extension', so probably invalid file\n" ); 00941 return false; 00942 } 00943 } 00944 00945 $match = $magic->isMatchingExtension( $extension, $mime ); 00946 00947 if ( $match === null ) { 00948 if ( $magic->getTypesForExtension( $extension ) !== null ) { 00949 wfDebug( __METHOD__ . ": No extension known for $mime, but we know a mime for $extension\n" ); 00950 return false; 00951 } else { 00952 wfDebug( __METHOD__ . ": no file extension known for mime type $mime, passing file\n" ); 00953 return true; 00954 } 00955 } elseif ( $match === true ) { 00956 wfDebug( __METHOD__ . ": mime type $mime matches extension $extension, passing file\n" ); 00957 00958 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it! 00959 return true; 00960 00961 } else { 00962 wfDebug( __METHOD__ . ": mime type $mime mismatches file extension $extension, rejecting file\n" ); 00963 return false; 00964 } 00965 } 00966 00978 public static function detectScript( $file, $mime, $extension ) { 00979 global $wgAllowTitlesInSVG; 00980 wfProfileIn( __METHOD__ ); 00981 00982 # ugly hack: for text files, always look at the entire file. 00983 # For binary field, just check the first K. 00984 00985 if ( strpos( $mime, 'text/' ) === 0 ) { 00986 $chunk = file_get_contents( $file ); 00987 } else { 00988 $fp = fopen( $file, 'rb' ); 00989 $chunk = fread( $fp, 1024 ); 00990 fclose( $fp ); 00991 } 00992 00993 $chunk = strtolower( $chunk ); 00994 00995 if ( !$chunk ) { 00996 wfProfileOut( __METHOD__ ); 00997 return false; 00998 } 00999 01000 # decode from UTF-16 if needed (could be used for obfuscation). 01001 if ( substr( $chunk, 0, 2 ) == "\xfe\xff" ) { 01002 $enc = 'UTF-16BE'; 01003 } elseif ( substr( $chunk, 0, 2 ) == "\xff\xfe" ) { 01004 $enc = 'UTF-16LE'; 01005 } else { 01006 $enc = null; 01007 } 01008 01009 if ( $enc ) { 01010 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk ); 01011 } 01012 01013 $chunk = trim( $chunk ); 01014 01015 # @todo FIXME: Convert from UTF-16 if necessary! 01016 wfDebug( __METHOD__ . ": checking for embedded scripts and HTML stuff\n" ); 01017 01018 # check for HTML doctype 01019 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) { 01020 wfProfileOut( __METHOD__ ); 01021 return true; 01022 } 01023 01024 // Some browsers will interpret obscure xml encodings as UTF-8, while 01025 // PHP/expat will interpret the given encoding in the xml declaration (bug 47304) 01026 if ( $extension == 'svg' || strpos( $mime, 'image/svg' ) === 0 ) { 01027 if ( self::checkXMLEncodingMissmatch( $file ) ) { 01028 wfProfileOut( __METHOD__ ); 01029 return true; 01030 } 01031 } 01032 01048 $tags = array( 01049 '<a href', 01050 '<body', 01051 '<head', 01052 '<html', #also in safari 01053 '<img', 01054 '<pre', 01055 '<script', #also in safari 01056 '<table' 01057 ); 01058 01059 if ( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) { 01060 $tags[] = '<title'; 01061 } 01062 01063 foreach ( $tags as $tag ) { 01064 if ( false !== strpos( $chunk, $tag ) ) { 01065 wfDebug( __METHOD__ . ": found something that may make it be mistaken for html: $tag\n" ); 01066 wfProfileOut( __METHOD__ ); 01067 return true; 01068 } 01069 } 01070 01071 /* 01072 * look for JavaScript 01073 */ 01074 01075 # resolve entity-refs to look at attributes. may be harsh on big files... cache result? 01076 $chunk = Sanitizer::decodeCharReferences( $chunk ); 01077 01078 # look for script-types 01079 if ( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) { 01080 wfDebug( __METHOD__ . ": found script types\n" ); 01081 wfProfileOut( __METHOD__ ); 01082 return true; 01083 } 01084 01085 # look for html-style script-urls 01086 if ( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) { 01087 wfDebug( __METHOD__ . ": found html-style script urls\n" ); 01088 wfProfileOut( __METHOD__ ); 01089 return true; 01090 } 01091 01092 # look for css-style script-urls 01093 if ( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) { 01094 wfDebug( __METHOD__ . ": found css-style script urls\n" ); 01095 wfProfileOut( __METHOD__ ); 01096 return true; 01097 } 01098 01099 wfDebug( __METHOD__ . ": no scripts found\n" ); 01100 wfProfileOut( __METHOD__ ); 01101 return false; 01102 } 01103 01104 01112 public static function checkXMLEncodingMissmatch( $file ) { 01113 global $wgSVGMetadataCutoff; 01114 $contents = file_get_contents( $file, false, null, -1, $wgSVGMetadataCutoff ); 01115 $encodingRegex = '!encoding[ \t\n\r]*=[ \t\n\r]*[\'"](.*?)[\'"]!si'; 01116 01117 if ( preg_match( "!<\?xml\b(.*?)\?>!si", $contents, $matches ) ) { 01118 if ( preg_match( $encodingRegex, $matches[1], $encMatch ) 01119 && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings ) 01120 ) { 01121 wfDebug( __METHOD__ . ": Found unsafe XML encoding '{$encMatch[1]}'\n" ); 01122 return true; 01123 } 01124 } elseif ( preg_match( "!<\?xml\b!si", $contents ) ) { 01125 // Start of XML declaration without an end in the first $wgSVGMetadataCutoff 01126 // bytes. There shouldn't be a legitimate reason for this to happen. 01127 wfDebug( __METHOD__ . ": Unmatched XML declaration start\n" ); 01128 return true; 01129 } elseif ( substr( $contents, 0, 4 ) == "\x4C\x6F\xA7\x94" ) { 01130 // EBCDIC encoded XML 01131 wfDebug( __METHOD__ . ": EBCDIC Encoded XML\n" ); 01132 return true; 01133 } 01134 01135 // It's possible the file is encoded with multi-byte encoding, so re-encode attempt to 01136 // detect the encoding in case is specifies an encoding not whitelisted in self::$safeXmlEncodings 01137 $attemptEncodings = array( 'UTF-16', 'UTF-16BE', 'UTF-32', 'UTF-32BE' ); 01138 foreach ( $attemptEncodings as $encoding ) { 01139 wfSuppressWarnings(); 01140 $str = iconv( $encoding, 'UTF-8', $contents ); 01141 wfRestoreWarnings(); 01142 if ( $str != '' && preg_match( "!<\?xml\b(.*?)\?>!si", $str, $matches ) ) { 01143 if ( preg_match( $encodingRegex, $matches[1], $encMatch ) 01144 && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings ) 01145 ) { 01146 wfDebug( __METHOD__ . ": Found unsafe XML encoding '{$encMatch[1]}'\n" ); 01147 return true; 01148 } 01149 } elseif ( $str != '' && preg_match( "!<\?xml\b!si", $str ) ) { 01150 // Start of XML declaration without an end in the first $wgSVGMetadataCutoff 01151 // bytes. There shouldn't be a legitimate reason for this to happen. 01152 wfDebug( __METHOD__ . ": Unmatched XML declaration start\n" ); 01153 return true; 01154 } 01155 } 01156 01157 return false; 01158 } 01159 01164 protected function detectScriptInSvg( $filename ) { 01165 $this->mSVGNSError = false; 01166 $check = new XmlTypeCheck( 01167 $filename, 01168 array( $this, 'checkSvgScriptCallback' ), 01169 true, 01170 array( 'processing_instruction_handler' => 'UploadBase::checkSvgPICallback' ) 01171 ); 01172 if ( $check->wellFormed !== true ) { 01173 // Invalid xml (bug 58553) 01174 return array( 'uploadinvalidxml' ); 01175 } elseif ( $check->filterMatch ) { 01176 if ( $this->mSVGNSError ) { 01177 return array( 'uploadscriptednamespace', $this->mSVGNSError ); 01178 } 01179 return array( 'uploadscripted' ); 01180 } 01181 return false; 01182 } 01183 01190 public static function checkSvgPICallback( $target, $data ) { 01191 // Don't allow external stylesheets (bug 57550) 01192 if ( preg_match( '/xml-stylesheet/i', $target) ) { 01193 return true; 01194 } 01195 return false; 01196 } 01197 01204 public function checkSvgScriptCallback( $element, $attribs, $data = null ) { 01205 01206 list( $namespace, $strippedElement ) = $this->splitXmlNamespace( $element ); 01207 01208 static $validNamespaces = array( 01209 '', 01210 'adobe:ns:meta/', 01211 'http://creativecommons.org/ns#', 01212 'http://inkscape.sourceforge.net/dtd/sodipodi-0.dtd', 01213 'http://ns.adobe.com/adobeillustrator/10.0/', 01214 'http://ns.adobe.com/adobesvgviewerextensions/3.0/', 01215 'http://ns.adobe.com/extensibility/1.0/', 01216 'http://ns.adobe.com/flows/1.0/', 01217 'http://ns.adobe.com/illustrator/1.0/', 01218 'http://ns.adobe.com/imagereplacement/1.0/', 01219 'http://ns.adobe.com/pdf/1.3/', 01220 'http://ns.adobe.com/photoshop/1.0/', 01221 'http://ns.adobe.com/saveforweb/1.0/', 01222 'http://ns.adobe.com/variables/1.0/', 01223 'http://ns.adobe.com/xap/1.0/', 01224 'http://ns.adobe.com/xap/1.0/g/', 01225 'http://ns.adobe.com/xap/1.0/g/img/', 01226 'http://ns.adobe.com/xap/1.0/mm/', 01227 'http://ns.adobe.com/xap/1.0/rights/', 01228 'http://ns.adobe.com/xap/1.0/stype/dimensions#', 01229 'http://ns.adobe.com/xap/1.0/stype/font#', 01230 'http://ns.adobe.com/xap/1.0/stype/manifestitem#', 01231 'http://ns.adobe.com/xap/1.0/stype/resourceevent#', 01232 'http://ns.adobe.com/xap/1.0/stype/resourceref#', 01233 'http://ns.adobe.com/xap/1.0/t/pg/', 01234 'http://purl.org/dc/elements/1.1/', 01235 'http://purl.org/dc/elements/1.1', 01236 'http://schemas.microsoft.com/visio/2003/svgextensions/', 01237 'http://sodipodi.sourceforge.net/dtd/sodipodi-0.dtd', 01238 'http://web.resource.org/cc/', 01239 'http://www.freesoftware.fsf.org/bkchem/cdml', 01240 'http://www.inkscape.org/namespaces/inkscape', 01241 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', 01242 'http://www.w3.org/2000/svg', 01243 ); 01244 01245 if ( !in_array( $namespace, $validNamespaces ) ) { 01246 wfDebug( __METHOD__ . ": Non-svg namespace '$namespace' in uploaded file.\n" ); 01247 // @TODO return a status object to a closure in XmlTypeCheck, for MW1.21+ 01248 $this->mSVGNSError = $namespace; 01249 return true; 01250 } 01251 01252 /* 01253 * check for elements that can contain javascript 01254 */ 01255 if ( $strippedElement == 'script' ) { 01256 wfDebug( __METHOD__ . ": Found script element '$element' in uploaded file.\n" ); 01257 return true; 01258 } 01259 01260 # 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> 01261 if ( $strippedElement == 'handler' ) { 01262 wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file.\n" ); 01263 return true; 01264 } 01265 01266 # SVG reported in Feb '12 that used xml:stylesheet to generate javascript block 01267 if ( $strippedElement == 'stylesheet' ) { 01268 wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file.\n" ); 01269 return true; 01270 } 01271 01272 # Block iframes, in case they pass the namespace check 01273 if ( $strippedElement == 'iframe' ) { 01274 wfDebug( __METHOD__ . ": iframe in uploaded file.\n" ); 01275 return true; 01276 } 01277 01278 # Check <style> css 01279 if ( $strippedElement == 'style' 01280 && self::checkCssFragment( Sanitizer::normalizeCss( $data ) ) 01281 ) { 01282 wfDebug( __METHOD__ . ": hostile css in style element.\n" ); 01283 return true; 01284 } 01285 01286 foreach ( $attribs as $attrib => $value ) { 01287 $stripped = $this->stripXmlNamespace( $attrib ); 01288 $value = strtolower( $value ); 01289 01290 if ( substr( $stripped, 0, 2 ) == 'on' ) { 01291 wfDebug( __METHOD__ . ": Found event-handler attribute '$attrib'='$value' in uploaded file.\n" ); 01292 return true; 01293 } 01294 01295 # href with non-local target (don't allow http://, javascript:, etc) 01296 if ( $stripped == 'href' 01297 && strpos( $value, 'data:' ) !== 0 01298 && strpos( $value, '#' ) !== 0 01299 ) { 01300 if ( !( $strippedElement === 'a' 01301 && preg_match( '!^https?://!im', $value ) ) 01302 ) { 01303 wfDebug( __METHOD__ . ": Found href attribute <$strippedElement " 01304 . "'$attrib'='$value' in uploaded file.\n" ); 01305 01306 return true; 01307 } 01308 } 01309 01310 # href with embedded svg as target 01311 if ( $stripped == 'href' && preg_match( '!data:[^,]*image/svg[^,]*,!sim', $value ) ) { 01312 wfDebug( __METHOD__ . ": Found href to embedded svg \"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" ); 01313 return true; 01314 } 01315 01316 # href with embedded (text/xml) svg as target 01317 if ( $stripped == 'href' && preg_match( '!data:[^,]*text/xml[^,]*,!sim', $value ) ) { 01318 wfDebug( __METHOD__ . ": Found href to embedded svg \"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" ); 01319 return true; 01320 } 01321 01322 # Change href with animate from (http://html5sec.org/#137). This doesn't seem 01323 # possible without embedding the svg, but filter here in case. 01324 if ( $stripped == 'from' 01325 && $strippedElement === 'animate' 01326 && !preg_match( '!^https?://!im', $value ) 01327 ) { 01328 wfDebug( __METHOD__ . ": Found animate that might be changing href using from " 01329 . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" ); 01330 01331 return true; 01332 } 01333 01334 # use set/animate to add event-handler attribute to parent 01335 if ( ( $strippedElement == 'set' || $strippedElement == 'animate' ) && $stripped == 'attributename' && substr( $value, 0, 2 ) == 'on' ) { 01336 wfDebug( __METHOD__ . ": Found svg setting event-handler attribute with \"<$strippedElement $stripped='$value'...\" in uploaded file.\n" ); 01337 return true; 01338 } 01339 01340 # use set to add href attribute to parent element 01341 if ( $strippedElement == 'set' && $stripped == 'attributename' && strpos( $value, 'href' ) !== false ) { 01342 wfDebug( __METHOD__ . ": Found svg setting href attribute '$value' in uploaded file.\n" ); 01343 return true; 01344 } 01345 01346 # use set to add a remote / data / script target to an element 01347 if ( $strippedElement == 'set' && $stripped == 'to' && preg_match( '!(http|https|data|script):!sim', $value ) ) { 01348 wfDebug( __METHOD__ . ": Found svg setting attribute to '$value' in uploaded file.\n" ); 01349 return true; 01350 } 01351 01352 # use handler attribute with remote / data / script 01353 if ( $stripped == 'handler' && preg_match( '!(http|https|data|script):!sim', $value ) ) { 01354 wfDebug( __METHOD__ . ": Found svg setting handler with remote/data/script '$attrib'='$value' in uploaded file.\n" ); 01355 return true; 01356 } 01357 01358 # use CSS styles to bring in remote code 01359 if ( $stripped == 'style' 01360 && self::checkCssFragment( Sanitizer::normalizeCss( $value ) ) 01361 ) { 01362 wfDebug( __METHOD__ . ": Found svg setting a style with " 01363 . "remote url '$attrib'='$value' in uploaded file.\n" ); 01364 return true; 01365 } 01366 01367 # Several attributes can include css, css character escaping isn't allowed 01368 $cssAttrs = array( 'font', 'clip-path', 'fill', 'filter', 'marker', 01369 'marker-end', 'marker-mid', 'marker-start', 'mask', 'stroke' ); 01370 if ( in_array( $stripped, $cssAttrs ) 01371 && self::checkCssFragment( $value ) 01372 ) { 01373 wfDebug( __METHOD__ . ": Found svg setting a style with " 01374 . "remote url '$attrib'='$value' in uploaded file.\n" ); 01375 return true; 01376 } 01377 01378 # image filters can pull in url, which could be svg that executes scripts 01379 if ( $strippedElement == 'image' && $stripped == 'filter' && preg_match( '!url\s*\(!sim', $value ) ) { 01380 wfDebug( __METHOD__ . ": Found image filter with url: \"<$strippedElement $stripped='$value'...\" in uploaded file.\n" ); 01381 return true; 01382 } 01383 01384 } 01385 01386 return false; //No scripts detected 01387 } 01388 01396 private static function checkCssFragment( $value ) { 01397 01398 # Forbid external stylesheets, for both reliability and to protect viewer's privacy 01399 if ( strpos( $value, '@import' ) !== false ) { 01400 return true; 01401 } 01402 01403 # We allow @font-face to embed fonts with data: urls, so we snip the string 01404 # 'url' out so this case won't match when we check for urls below 01405 $pattern = '!(@font-face\s*{[^}]*src:)url(\("data:;base64,)!im'; 01406 $value = preg_replace( $pattern, '$1$2', $value ); 01407 01408 # Check for remote and executable CSS. Unlike in Sanitizer::checkCss, the CSS 01409 # properties filter and accelerator don't seem to be useful for xss in SVG files. 01410 # Expression and -o-link don't seem to work either, but filtering them here in case. 01411 # Additionally, we catch remote urls like url("http:..., url('http:..., url(http:..., 01412 # but not local ones such as url("#..., url('#..., url(#.... 01413 if ( preg_match( '!expression 01414 | -o-link\s*: 01415 | -o-link-source\s*: 01416 | -o-replace\s*:!imx', $value ) ) { 01417 return true; 01418 } 01419 01420 if ( preg_match_all( 01421 "!(\s*(url|image|image-set)\s*\(\s*[\"']?\s*[^#]+.*?\))!sim", 01422 $value, 01423 $matches 01424 ) !== 0 01425 ) { 01426 # TODO: redo this in one regex. Until then, url("#whatever") matches the first 01427 foreach ( $matches[1] as $match ) { 01428 if ( !preg_match( "!\s*(url|image|image-set)\s*\(\s*(#|'#|\"#)!im", $match ) ) { 01429 return true; 01430 } 01431 } 01432 } 01433 01434 if ( preg_match( '/[\000-\010\013\016-\037\177]/', $value ) ) { 01435 return true; 01436 } 01437 01438 return false; 01439 } 01440 01446 private static function splitXmlNamespace( $element ) { 01447 // 'http://www.w3.org/2000/svg:script' -> array( 'http://www.w3.org/2000/svg', 'script' ) 01448 $parts = explode( ':', strtolower( $element ) ); 01449 $name = array_pop( $parts ); 01450 $ns = implode( ':', $parts ); 01451 return array( $ns, $name ); 01452 } 01453 01458 private function stripXmlNamespace( $name ) { 01459 // 'http://www.w3.org/2000/svg:script' -> 'script' 01460 $parts = explode( ':', strtolower( $name ) ); 01461 return array_pop( $parts ); 01462 } 01463 01474 public static function detectVirus( $file ) { 01475 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut; 01476 wfProfileIn( __METHOD__ ); 01477 01478 if ( !$wgAntivirus ) { 01479 wfDebug( __METHOD__ . ": virus scanner disabled\n" ); 01480 wfProfileOut( __METHOD__ ); 01481 return null; 01482 } 01483 01484 if ( !$wgAntivirusSetup[$wgAntivirus] ) { 01485 wfDebug( __METHOD__ . ": unknown virus scanner: $wgAntivirus\n" ); 01486 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>", 01487 array( 'virus-badscanner', $wgAntivirus ) ); 01488 wfProfileOut( __METHOD__ ); 01489 return wfMessage( 'virus-unknownscanner' )->text() . " $wgAntivirus"; 01490 } 01491 01492 # look up scanner configuration 01493 $command = $wgAntivirusSetup[$wgAntivirus]['command']; 01494 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap']; 01495 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ? 01496 $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null; 01497 01498 if ( strpos( $command, "%f" ) === false ) { 01499 # simple pattern: append file to scan 01500 $command .= " " . wfEscapeShellArg( $file ); 01501 } else { 01502 # complex pattern: replace "%f" with file to scan 01503 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command ); 01504 } 01505 01506 wfDebug( __METHOD__ . ": running virus scan: $command \n" ); 01507 01508 # execute virus scanner 01509 $exitCode = false; 01510 01511 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too. 01512 # that does not seem to be worth the pain. 01513 # Ask me (Duesentrieb) about it if it's ever needed. 01514 $output = wfShellExecWithStderr( $command, $exitCode ); 01515 01516 # map exit code to AV_xxx constants. 01517 $mappedCode = $exitCode; 01518 if ( $exitCodeMap ) { 01519 if ( isset( $exitCodeMap[$exitCode] ) ) { 01520 $mappedCode = $exitCodeMap[$exitCode]; 01521 } elseif ( isset( $exitCodeMap["*"] ) ) { 01522 $mappedCode = $exitCodeMap["*"]; 01523 } 01524 } 01525 01526 /* NB: AV_NO_VIRUS is 0 but AV_SCAN_FAILED is false, 01527 * so we need the strict equalities === and thus can't use a switch here 01528 */ 01529 if ( $mappedCode === AV_SCAN_FAILED ) { 01530 # scan failed (code was mapped to false by $exitCodeMap) 01531 wfDebug( __METHOD__ . ": failed to scan $file (code $exitCode).\n" ); 01532 01533 $output = $wgAntivirusRequired ? wfMessage( 'virus-scanfailed', array( $exitCode ) )->text() : null; 01534 } elseif ( $mappedCode === AV_SCAN_ABORTED ) { 01535 # scan failed because filetype is unknown (probably imune) 01536 wfDebug( __METHOD__ . ": unsupported file type $file (code $exitCode).\n" ); 01537 $output = null; 01538 } elseif ( $mappedCode === AV_NO_VIRUS ) { 01539 # no virus found 01540 wfDebug( __METHOD__ . ": file passed virus scan.\n" ); 01541 $output = false; 01542 } else { 01543 $output = trim( $output ); 01544 01545 if ( !$output ) { 01546 $output = true; #if there's no output, return true 01547 } elseif ( $msgPattern ) { 01548 $groups = array(); 01549 if ( preg_match( $msgPattern, $output, $groups ) ) { 01550 if ( $groups[1] ) { 01551 $output = $groups[1]; 01552 } 01553 } 01554 } 01555 01556 wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output \n" ); 01557 } 01558 01559 wfProfileOut( __METHOD__ ); 01560 return $output; 01561 } 01562 01571 private function checkOverwrite( $user ) { 01572 // First check whether the local file can be overwritten 01573 $file = $this->getLocalFile(); 01574 if ( $file->exists() ) { 01575 if ( !self::userCanReUpload( $user, $file ) ) { 01576 return array( 'fileexists-forbidden', $file->getName() ); 01577 } else { 01578 return true; 01579 } 01580 } 01581 01582 /* Check shared conflicts: if the local file does not exist, but 01583 * wfFindFile finds a file, it exists in a shared repository. 01584 */ 01585 $file = wfFindFile( $this->getTitle() ); 01586 if ( $file && !$user->isAllowed( 'reupload-shared' ) ) { 01587 return array( 'fileexists-shared-forbidden', $file->getName() ); 01588 } 01589 01590 return true; 01591 } 01592 01600 public static function userCanReUpload( User $user, $img ) { 01601 if ( $user->isAllowed( 'reupload' ) ) { 01602 return true; // non-conditional 01603 } 01604 if ( !$user->isAllowed( 'reupload-own' ) ) { 01605 return false; 01606 } 01607 if ( is_string( $img ) ) { 01608 $img = wfLocalFile( $img ); 01609 } 01610 if ( !( $img instanceof LocalFile ) ) { 01611 return false; 01612 } 01613 01614 return $user->getId() == $img->getUser( 'id' ); 01615 } 01616 01628 public static function getExistsWarning( $file ) { 01629 if ( $file->exists() ) { 01630 return array( 'warning' => 'exists', 'file' => $file ); 01631 } 01632 01633 if ( $file->getTitle()->getArticleID() ) { 01634 return array( 'warning' => 'page-exists', 'file' => $file ); 01635 } 01636 01637 if ( $file->wasDeleted() && !$file->exists() ) { 01638 return array( 'warning' => 'was-deleted', 'file' => $file ); 01639 } 01640 01641 if ( strpos( $file->getName(), '.' ) == false ) { 01642 $partname = $file->getName(); 01643 $extension = ''; 01644 } else { 01645 $n = strrpos( $file->getName(), '.' ); 01646 $extension = substr( $file->getName(), $n + 1 ); 01647 $partname = substr( $file->getName(), 0, $n ); 01648 } 01649 $normalizedExtension = File::normalizeExtension( $extension ); 01650 01651 if ( $normalizedExtension != $extension ) { 01652 // We're not using the normalized form of the extension. 01653 // Normal form is lowercase, using most common of alternate 01654 // extensions (eg 'jpg' rather than 'JPEG'). 01655 // 01656 // Check for another file using the normalized form... 01657 $nt_lc = Title::makeTitle( NS_FILE, "{$partname}.{$normalizedExtension}" ); 01658 $file_lc = wfLocalFile( $nt_lc ); 01659 01660 if ( $file_lc->exists() ) { 01661 return array( 01662 'warning' => 'exists-normalized', 01663 'file' => $file, 01664 'normalizedFile' => $file_lc 01665 ); 01666 } 01667 } 01668 01669 // Check for files with the same name but a different extension 01670 $similarFiles = RepoGroup::singleton()->getLocalRepo()->findFilesByPrefix( 01671 "{$partname}.", 1 ); 01672 if ( count( $similarFiles ) ) { 01673 return array( 01674 'warning' => 'exists-normalized', 01675 'file' => $file, 01676 'normalizedFile' => $similarFiles[0], 01677 ); 01678 } 01679 01680 if ( self::isThumbName( $file->getName() ) ) { 01681 # Check for filenames like 50px- or 180px-, these are mostly thumbnails 01682 $nt_thb = Title::newFromText( substr( $partname, strpos( $partname, '-' ) + 1 ) . '.' . $extension, NS_FILE ); 01683 $file_thb = wfLocalFile( $nt_thb ); 01684 if ( $file_thb->exists() ) { 01685 return array( 01686 'warning' => 'thumb', 01687 'file' => $file, 01688 'thumbFile' => $file_thb 01689 ); 01690 } else { 01691 // File does not exist, but we just don't like the name 01692 return array( 01693 'warning' => 'thumb-name', 01694 'file' => $file, 01695 'thumbFile' => $file_thb 01696 ); 01697 } 01698 } 01699 01700 foreach ( self::getFilenamePrefixBlacklist() as $prefix ) { 01701 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) { 01702 return array( 01703 'warning' => 'bad-prefix', 01704 'file' => $file, 01705 'prefix' => $prefix 01706 ); 01707 } 01708 } 01709 01710 return false; 01711 } 01712 01718 public static function isThumbName( $filename ) { 01719 $n = strrpos( $filename, '.' ); 01720 $partname = $n ? substr( $filename, 0, $n ) : $filename; 01721 return ( 01722 substr( $partname, 3, 3 ) == 'px-' || 01723 substr( $partname, 2, 3 ) == 'px-' 01724 ) && 01725 preg_match( "/[0-9]{2}/", substr( $partname, 0, 2 ) ); 01726 } 01727 01733 public static function getFilenamePrefixBlacklist() { 01734 $blacklist = array(); 01735 $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage(); 01736 if ( !$message->isDisabled() ) { 01737 $lines = explode( "\n", $message->plain() ); 01738 foreach ( $lines as $line ) { 01739 // Remove comment lines 01740 $comment = substr( trim( $line ), 0, 1 ); 01741 if ( $comment == '#' || $comment == '' ) { 01742 continue; 01743 } 01744 // Remove additional comments after a prefix 01745 $comment = strpos( $line, '#' ); 01746 if ( $comment > 0 ) { 01747 $line = substr( $line, 0, $comment - 1 ); 01748 } 01749 $blacklist[] = trim( $line ); 01750 } 01751 } 01752 return $blacklist; 01753 } 01754 01765 public function getImageInfo( $result ) { 01766 $file = $this->getLocalFile(); 01767 // TODO This cries out for refactoring. We really want to say $file->getAllInfo(); here. 01768 // Perhaps "info" methods should be moved into files, and the API should just wrap them in queries. 01769 if ( $file instanceof UploadStashFile ) { 01770 $imParam = ApiQueryStashImageInfo::getPropertyNames(); 01771 $info = ApiQueryStashImageInfo::getInfo( $file, array_flip( $imParam ), $result ); 01772 } else { 01773 $imParam = ApiQueryImageInfo::getPropertyNames(); 01774 $info = ApiQueryImageInfo::getInfo( $file, array_flip( $imParam ), $result ); 01775 } 01776 return $info; 01777 } 01778 01783 public function convertVerifyErrorToStatus( $error ) { 01784 $code = $error['status']; 01785 unset( $code['status'] ); 01786 return Status::newFatal( $this->getVerificationErrorCode( $code ), $error ); 01787 } 01788 01793 public static function getMaxUploadSize( $forType = null ) { 01794 global $wgMaxUploadSize; 01795 01796 if ( is_array( $wgMaxUploadSize ) ) { 01797 if ( !is_null( $forType ) && isset( $wgMaxUploadSize[$forType] ) ) { 01798 return $wgMaxUploadSize[$forType]; 01799 } else { 01800 return $wgMaxUploadSize['*']; 01801 } 01802 } else { 01803 return intval( $wgMaxUploadSize ); 01804 } 01805 } 01806 01813 public static function getSessionStatus( $statusKey ) { 01814 return isset( $_SESSION[self::SESSION_STATUS_KEY][$statusKey] ) 01815 ? $_SESSION[self::SESSION_STATUS_KEY][$statusKey] 01816 : false; 01817 } 01818 01826 public static function setSessionStatus( $statusKey, $value ) { 01827 if ( $value === false ) { 01828 unset( $_SESSION[self::SESSION_STATUS_KEY][$statusKey] ); 01829 } else { 01830 $_SESSION[self::SESSION_STATUS_KEY][$statusKey] = $value; 01831 } 01832 } 01833 }