MediaWiki
REL1_21
|
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(self::EMPTY_FILE => 'empty-file', 00076 self::FILE_TOO_LARGE => 'file-too-large', 00077 self::FILETYPE_MISSING => 'filetype-missing', 00078 self::FILETYPE_BADTYPE => 'filetype-banned', 00079 self::MIN_LENGTH_PARTNAME => 'filename-tooshort', 00080 self::ILLEGAL_FILENAME => 'illegal-filename', 00081 self::OVERWRITE_EXISTING_FILE => 'overwrite', 00082 self::VERIFICATION_ERROR => 'verification-error', 00083 self::HOOK_ABORTED => 'hookaborted', 00084 self::WINDOWS_NONASCII_FILENAME => 'windows-nonascii-filename', 00085 self::FILENAME_TOO_LONG => 'filename-toolong', 00086 ); 00087 if( isset( $code_to_status[$error] ) ) { 00088 return $code_to_status[$error]; 00089 } 00090 00091 return 'unknown-error'; 00092 } 00093 00099 public static function isEnabled() { 00100 global $wgEnableUploads; 00101 00102 if ( !$wgEnableUploads ) { 00103 return false; 00104 } 00105 00106 # Check php's file_uploads setting 00107 return wfIsHipHop() || wfIniGetBool( 'file_uploads' ); 00108 } 00109 00118 public static function isAllowed( $user ) { 00119 foreach ( array( 'upload', 'edit' ) as $permission ) { 00120 if ( !$user->isAllowed( $permission ) ) { 00121 return $permission; 00122 } 00123 } 00124 return true; 00125 } 00126 00127 // Upload handlers. Should probably just be a global. 00128 static $uploadHandlers = array( 'Stash', 'File', 'Url' ); 00129 00137 public static function createFromRequest( &$request, $type = null ) { 00138 $type = $type ? $type : $request->getVal( 'wpSourceType', 'File' ); 00139 00140 if( !$type ) { 00141 return null; 00142 } 00143 00144 // Get the upload class 00145 $type = ucfirst( $type ); 00146 00147 // Give hooks the chance to handle this request 00148 $className = null; 00149 wfRunHooks( 'UploadCreateFromRequest', array( $type, &$className ) ); 00150 if ( is_null( $className ) ) { 00151 $className = 'UploadFrom' . $type; 00152 wfDebug( __METHOD__ . ": class name: $className\n" ); 00153 if( !in_array( $type, self::$uploadHandlers ) ) { 00154 return null; 00155 } 00156 } 00157 00158 // Check whether this upload class is enabled 00159 if( !call_user_func( array( $className, 'isEnabled' ) ) ) { 00160 return null; 00161 } 00162 00163 // Check whether the request is valid 00164 if( !call_user_func( array( $className, 'isValidRequest' ), $request ) ) { 00165 return null; 00166 } 00167 00168 $handler = new $className; 00169 00170 $handler->initializeFromRequest( $request ); 00171 return $handler; 00172 } 00173 00179 public static function isValidRequest( $request ) { 00180 return false; 00181 } 00182 00183 public function __construct() {} 00184 00191 public function getSourceType() { return null; } 00192 00201 public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) { 00202 $this->mDesiredDestName = $name; 00203 if ( FileBackend::isStoragePath( $tempPath ) ) { 00204 throw new MWException( __METHOD__ . " given storage path `$tempPath`." ); 00205 } 00206 $this->mTempPath = $tempPath; 00207 $this->mFileSize = $fileSize; 00208 $this->mRemoveTempFile = $removeTempFile; 00209 } 00210 00214 abstract public function initializeFromRequest( &$request ); 00215 00220 public function fetchFile() { 00221 return Status::newGood(); 00222 } 00223 00228 public function isEmptyFile() { 00229 return empty( $this->mFileSize ); 00230 } 00231 00236 public function getFileSize() { 00237 return $this->mFileSize; 00238 } 00239 00244 public function getTempFileSha1Base36() { 00245 return FSFile::getSha1Base36FromPath( $this->mTempPath ); 00246 } 00247 00252 function getRealPath( $srcPath ) { 00253 wfProfileIn( __METHOD__ ); 00254 $repo = RepoGroup::singleton()->getLocalRepo(); 00255 if ( $repo->isVirtualUrl( $srcPath ) ) { 00256 // @TODO: just make uploads work with storage paths 00257 // UploadFromStash loads files via virtual URLs 00258 $tmpFile = $repo->getLocalCopy( $srcPath ); 00259 $tmpFile->bind( $this ); // keep alive with $this 00260 wfProfileOut( __METHOD__ ); 00261 return $tmpFile->getPath(); 00262 } 00263 wfProfileOut( __METHOD__ ); 00264 return $srcPath; 00265 } 00266 00271 public function verifyUpload() { 00272 wfProfileIn( __METHOD__ ); 00273 00277 if( $this->isEmptyFile() ) { 00278 wfProfileOut( __METHOD__ ); 00279 return array( 'status' => self::EMPTY_FILE ); 00280 } 00281 00285 $maxSize = self::getMaxUploadSize( $this->getSourceType() ); 00286 if( $this->mFileSize > $maxSize ) { 00287 wfProfileOut( __METHOD__ ); 00288 return array( 00289 'status' => self::FILE_TOO_LARGE, 00290 'max' => $maxSize, 00291 ); 00292 } 00293 00299 $verification = $this->verifyFile(); 00300 if( $verification !== true ) { 00301 wfProfileOut( __METHOD__ ); 00302 return array( 00303 'status' => self::VERIFICATION_ERROR, 00304 'details' => $verification 00305 ); 00306 } 00307 00311 $result = $this->validateName(); 00312 if( $result !== true ) { 00313 wfProfileOut( __METHOD__ ); 00314 return $result; 00315 } 00316 00317 $error = ''; 00318 if( !wfRunHooks( 'UploadVerification', 00319 array( $this->mDestName, $this->mTempPath, &$error ) ) ) 00320 { 00321 wfProfileOut( __METHOD__ ); 00322 return array( 'status' => self::HOOK_ABORTED, 'error' => $error ); 00323 } 00324 00325 wfProfileOut( __METHOD__ ); 00326 return array( 'status' => self::OK ); 00327 } 00328 00335 protected function validateName() { 00336 $nt = $this->getTitle(); 00337 if( is_null( $nt ) ) { 00338 $result = array( 'status' => $this->mTitleError ); 00339 if( $this->mTitleError == self::ILLEGAL_FILENAME ) { 00340 $result['filtered'] = $this->mFilteredName; 00341 } 00342 if ( $this->mTitleError == self::FILETYPE_BADTYPE ) { 00343 $result['finalExt'] = $this->mFinalExtension; 00344 if ( count( $this->mBlackListedExtensions ) ) { 00345 $result['blacklistedExt'] = $this->mBlackListedExtensions; 00346 } 00347 } 00348 return $result; 00349 } 00350 $this->mDestName = $this->getLocalFile()->getName(); 00351 00352 return true; 00353 } 00354 00363 protected function verifyMimeType( $mime ) { 00364 global $wgVerifyMimeType; 00365 wfProfileIn( __METHOD__ ); 00366 if ( $wgVerifyMimeType ) { 00367 wfDebug ( "\n\nmime: <$mime> extension: <{$this->mFinalExtension}>\n\n" ); 00368 global $wgMimeTypeBlacklist; 00369 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) { 00370 wfProfileOut( __METHOD__ ); 00371 return array( 'filetype-badmime', $mime ); 00372 } 00373 00374 # Check IE type 00375 $fp = fopen( $this->mTempPath, 'rb' ); 00376 $chunk = fread( $fp, 256 ); 00377 fclose( $fp ); 00378 00379 $magic = MimeMagic::singleton(); 00380 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension ); 00381 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath, $chunk, $extMime ); 00382 foreach ( $ieTypes as $ieType ) { 00383 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) { 00384 wfProfileOut( __METHOD__ ); 00385 return array( 'filetype-bad-ie-mime', $ieType ); 00386 } 00387 } 00388 } 00389 00390 wfProfileOut( __METHOD__ ); 00391 return true; 00392 } 00393 00399 protected function verifyFile() { 00400 global $wgVerifyMimeType; 00401 wfProfileIn( __METHOD__ ); 00402 00403 $status = $this->verifyPartialFile(); 00404 if ( $status !== true ) { 00405 wfProfileOut( __METHOD__ ); 00406 return $status; 00407 } 00408 00409 $this->mFileProps = FSFile::getPropsFromPath( $this->mTempPath, $this->mFinalExtension ); 00410 $mime = $this->mFileProps['file-mime']; 00411 00412 if ( $wgVerifyMimeType ) { 00413 # XXX: Missing extension will be caught by validateName() via getTitle() 00414 if ( $this->mFinalExtension != '' && !$this->verifyExtension( $mime, $this->mFinalExtension ) ) { 00415 wfProfileOut( __METHOD__ ); 00416 return array( 'filetype-mime-mismatch', $this->mFinalExtension, $mime ); 00417 } 00418 } 00419 00420 $handler = MediaHandler::getHandler( $mime ); 00421 if ( $handler ) { 00422 $handlerStatus = $handler->verifyUpload( $this->mTempPath ); 00423 if ( !$handlerStatus->isOK() ) { 00424 $errors = $handlerStatus->getErrorsArray(); 00425 wfProfileOut( __METHOD__ ); 00426 return reset( $errors ); 00427 } 00428 } 00429 00430 wfRunHooks( 'UploadVerifyFile', array( $this, $mime, &$status ) ); 00431 if ( $status !== true ) { 00432 wfProfileOut( __METHOD__ ); 00433 return $status; 00434 } 00435 00436 wfDebug( __METHOD__ . ": all clear; passing.\n" ); 00437 wfProfileOut( __METHOD__ ); 00438 return true; 00439 } 00440 00449 protected function verifyPartialFile() { 00450 global $wgAllowJavaUploads, $wgDisableUploadScriptChecks; 00451 wfProfileIn( __METHOD__ ); 00452 00453 # get the title, even though we are doing nothing with it, because 00454 # we need to populate mFinalExtension 00455 $this->getTitle(); 00456 00457 $this->mFileProps = FSFile::getPropsFromPath( $this->mTempPath, $this->mFinalExtension ); 00458 00459 # check mime type, if desired 00460 $mime = $this->mFileProps['file-mime']; 00461 $status = $this->verifyMimeType( $mime ); 00462 if ( $status !== true ) { 00463 wfProfileOut( __METHOD__ ); 00464 return $status; 00465 } 00466 00467 # check for htmlish code and javascript 00468 if ( !$wgDisableUploadScriptChecks ) { 00469 if( self::detectScript( $this->mTempPath, $mime, $this->mFinalExtension ) ) { 00470 wfProfileOut( __METHOD__ ); 00471 return array( 'uploadscripted' ); 00472 } 00473 if( $this->mFinalExtension == 'svg' || $mime == 'image/svg+xml' ) { 00474 $svgStatus = $this->detectScriptInSvg( $this->mTempPath ); 00475 if ( $svgStatus !== false ) { 00476 wfProfileOut( __METHOD__ ); 00477 return $svgStatus; 00478 } 00479 } 00480 } 00481 00482 # Check for Java applets, which if uploaded can bypass cross-site 00483 # restrictions. 00484 if ( !$wgAllowJavaUploads ) { 00485 $this->mJavaDetected = false; 00486 $zipStatus = ZipDirectoryReader::read( $this->mTempPath, 00487 array( $this, 'zipEntryCallback' ) ); 00488 if ( !$zipStatus->isOK() ) { 00489 $errors = $zipStatus->getErrorsArray(); 00490 $error = reset( $errors ); 00491 if ( $error[0] !== 'zip-wrong-format' ) { 00492 wfProfileOut( __METHOD__ ); 00493 return $error; 00494 } 00495 } 00496 if ( $this->mJavaDetected ) { 00497 wfProfileOut( __METHOD__ ); 00498 return array( 'uploadjava' ); 00499 } 00500 } 00501 00502 # Scan the uploaded file for viruses 00503 $virus = $this->detectVirus( $this->mTempPath ); 00504 if ( $virus ) { 00505 wfProfileOut( __METHOD__ ); 00506 return array( 'uploadvirus', $virus ); 00507 } 00508 00509 wfProfileOut( __METHOD__ ); 00510 return true; 00511 } 00512 00516 function zipEntryCallback( $entry ) { 00517 $names = array( $entry['name'] ); 00518 00519 // If there is a null character, cut off the name at it, because JDK's 00520 // ZIP_GetEntry() uses strcmp() if the name hashes match. If a file name 00521 // were constructed which had ".class\0" followed by a string chosen to 00522 // make the hash collide with the truncated name, that file could be 00523 // returned in response to a request for the .class file. 00524 $nullPos = strpos( $entry['name'], "\000" ); 00525 if ( $nullPos !== false ) { 00526 $names[] = substr( $entry['name'], 0, $nullPos ); 00527 } 00528 00529 // If there is a trailing slash in the file name, we have to strip it, 00530 // because that's what ZIP_GetEntry() does. 00531 if ( preg_grep( '!\.class/?$!', $names ) ) { 00532 $this->mJavaDetected = true; 00533 } 00534 } 00535 00543 public function verifyPermissions( $user ) { 00544 return $this->verifyTitlePermissions( $user ); 00545 } 00546 00558 public function verifyTitlePermissions( $user ) { 00563 $nt = $this->getTitle(); 00564 if( is_null( $nt ) ) { 00565 return true; 00566 } 00567 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user ); 00568 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user ); 00569 if ( !$nt->exists() ) { 00570 $permErrorsCreate = $nt->getUserPermissionsErrors( 'create', $user ); 00571 } else { 00572 $permErrorsCreate = array(); 00573 } 00574 if( $permErrors || $permErrorsUpload || $permErrorsCreate ) { 00575 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) ); 00576 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) ); 00577 return $permErrors; 00578 } 00579 00580 $overwriteError = $this->checkOverwrite( $user ); 00581 if ( $overwriteError !== true ) { 00582 return array( $overwriteError ); 00583 } 00584 00585 return true; 00586 } 00587 00595 public function checkWarnings() { 00596 global $wgLang; 00597 wfProfileIn( __METHOD__ ); 00598 00599 $warnings = array(); 00600 00601 $localFile = $this->getLocalFile(); 00602 $filename = $localFile->getName(); 00603 00608 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName ); 00609 $comparableName = Title::capitalize( $comparableName, NS_FILE ); 00610 00611 if( $this->mDesiredDestName != $filename && $comparableName != $filename ) { 00612 $warnings['badfilename'] = $filename; 00613 } 00614 00615 // Check whether the file extension is on the unwanted list 00616 global $wgCheckFileExtensions, $wgFileExtensions; 00617 if ( $wgCheckFileExtensions ) { 00618 if ( !$this->checkFileExtension( $this->mFinalExtension, $wgFileExtensions ) ) { 00619 $warnings['filetype-unwanted-type'] = array( $this->mFinalExtension, 00620 $wgLang->commaList( $wgFileExtensions ), count( $wgFileExtensions ) ); 00621 } 00622 } 00623 00624 global $wgUploadSizeWarning; 00625 if ( $wgUploadSizeWarning && ( $this->mFileSize > $wgUploadSizeWarning ) ) { 00626 $warnings['large-file'] = array( $wgUploadSizeWarning, $this->mFileSize ); 00627 } 00628 00629 if ( $this->mFileSize == 0 ) { 00630 $warnings['emptyfile'] = true; 00631 } 00632 00633 $exists = self::getExistsWarning( $localFile ); 00634 if( $exists !== false ) { 00635 $warnings['exists'] = $exists; 00636 } 00637 00638 // Check dupes against existing files 00639 $hash = $this->getTempFileSha1Base36(); 00640 $dupes = RepoGroup::singleton()->findBySha1( $hash ); 00641 $title = $this->getTitle(); 00642 // Remove all matches against self 00643 foreach ( $dupes as $key => $dupe ) { 00644 if( $title->equals( $dupe->getTitle() ) ) { 00645 unset( $dupes[$key] ); 00646 } 00647 } 00648 if( $dupes ) { 00649 $warnings['duplicate'] = $dupes; 00650 } 00651 00652 // Check dupes against archives 00653 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" ); 00654 if ( $archivedImage->getID() > 0 ) { 00655 $warnings['duplicate-archive'] = $archivedImage->getName(); 00656 } 00657 00658 wfProfileOut( __METHOD__ ); 00659 return $warnings; 00660 } 00661 00673 public function performUpload( $comment, $pageText, $watch, $user ) { 00674 wfProfileIn( __METHOD__ ); 00675 00676 $status = $this->getLocalFile()->upload( 00677 $this->mTempPath, 00678 $comment, 00679 $pageText, 00680 File::DELETE_SOURCE, 00681 $this->mFileProps, 00682 false, 00683 $user 00684 ); 00685 00686 if( $status->isGood() ) { 00687 if ( $watch ) { 00688 $user->addWatch( $this->getLocalFile()->getTitle() ); 00689 } 00690 wfRunHooks( 'UploadComplete', array( &$this ) ); 00691 } 00692 00693 wfProfileOut( __METHOD__ ); 00694 return $status; 00695 } 00696 00703 public function getTitle() { 00704 if ( $this->mTitle !== false ) { 00705 return $this->mTitle; 00706 } 00707 00708 /* Assume that if a user specified File:Something.jpg, this is an error 00709 * and that the namespace prefix needs to be stripped of. 00710 */ 00711 $title = Title::newFromText( $this->mDesiredDestName ); 00712 if ( $title && $title->getNamespace() == NS_FILE ) { 00713 $this->mFilteredName = $title->getDBkey(); 00714 } else { 00715 $this->mFilteredName = $this->mDesiredDestName; 00716 } 00717 00718 # oi_archive_name is max 255 bytes, which include a timestamp and an 00719 # exclamation mark, so restrict file name to 240 bytes. 00720 if ( strlen( $this->mFilteredName ) > 240 ) { 00721 $this->mTitleError = self::FILENAME_TOO_LONG; 00722 return $this->mTitle = null; 00723 } 00724 00730 $this->mFilteredName = wfStripIllegalFilenameChars( $this->mFilteredName ); 00731 /* Normalize to title form before we do any further processing */ 00732 $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName ); 00733 if( is_null( $nt ) ) { 00734 $this->mTitleError = self::ILLEGAL_FILENAME; 00735 return $this->mTitle = null; 00736 } 00737 $this->mFilteredName = $nt->getDBkey(); 00738 00743 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName ); 00744 00745 if( count( $ext ) ) { 00746 $this->mFinalExtension = trim( $ext[count( $ext ) - 1] ); 00747 } else { 00748 $this->mFinalExtension = ''; 00749 00750 # No extension, try guessing one 00751 $magic = MimeMagic::singleton(); 00752 $mime = $magic->guessMimeType( $this->mTempPath ); 00753 if ( $mime !== 'unknown/unknown' ) { 00754 # Get a space separated list of extensions 00755 $extList = $magic->getExtensionsForType( $mime ); 00756 if ( $extList ) { 00757 # Set the extension to the canonical extension 00758 $this->mFinalExtension = strtok( $extList, ' ' ); 00759 00760 # Fix up the other variables 00761 $this->mFilteredName .= ".{$this->mFinalExtension}"; 00762 $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName ); 00763 $ext = array( $this->mFinalExtension ); 00764 } 00765 } 00766 } 00767 00768 /* Don't allow users to override the blacklist (check file extension) */ 00769 global $wgCheckFileExtensions, $wgStrictFileExtensions; 00770 global $wgFileExtensions, $wgFileBlacklist; 00771 00772 $blackListedExtensions = $this->checkFileExtensionList( $ext, $wgFileBlacklist ); 00773 00774 if ( $this->mFinalExtension == '' ) { 00775 $this->mTitleError = self::FILETYPE_MISSING; 00776 return $this->mTitle = null; 00777 } elseif ( $blackListedExtensions || 00778 ( $wgCheckFileExtensions && $wgStrictFileExtensions && 00779 !$this->checkFileExtensionList( $ext, $wgFileExtensions ) ) ) { 00780 $this->mBlackListedExtensions = $blackListedExtensions; 00781 $this->mTitleError = self::FILETYPE_BADTYPE; 00782 return $this->mTitle = null; 00783 } 00784 00785 // Windows may be broken with special characters, see bug XXX 00786 if ( wfIsWindows() && !preg_match( '/^[\x0-\x7f]*$/', $nt->getText() ) ) { 00787 $this->mTitleError = self::WINDOWS_NONASCII_FILENAME; 00788 return $this->mTitle = null; 00789 } 00790 00791 # If there was more than one "extension", reassemble the base 00792 # filename to prevent bogus complaints about length 00793 if( count( $ext ) > 1 ) { 00794 for( $i = 0; $i < count( $ext ) - 1; $i++ ) { 00795 $partname .= '.' . $ext[$i]; 00796 } 00797 } 00798 00799 if( strlen( $partname ) < 1 ) { 00800 $this->mTitleError = self::MIN_LENGTH_PARTNAME; 00801 return $this->mTitle = null; 00802 } 00803 00804 return $this->mTitle = $nt; 00805 } 00806 00812 public function getLocalFile() { 00813 if( is_null( $this->mLocalFile ) ) { 00814 $nt = $this->getTitle(); 00815 $this->mLocalFile = is_null( $nt ) ? null : wfLocalFile( $nt ); 00816 } 00817 return $this->mLocalFile; 00818 } 00819 00832 public function stashFile( User $user = null ) { 00833 // was stashSessionFile 00834 wfProfileIn( __METHOD__ ); 00835 00836 $stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash( $user ); 00837 $file = $stash->stashFile( $this->mTempPath, $this->getSourceType() ); 00838 $this->mLocalFile = $file; 00839 00840 wfProfileOut( __METHOD__ ); 00841 return $file; 00842 } 00843 00849 public function stashFileGetKey() { 00850 return $this->stashFile()->getFileKey(); 00851 } 00852 00858 public function stashSession() { 00859 return $this->stashFileGetKey(); 00860 } 00861 00866 public function cleanupTempFile() { 00867 if ( $this->mRemoveTempFile && $this->mTempPath && file_exists( $this->mTempPath ) ) { 00868 wfDebug( __METHOD__ . ": Removing temporary file {$this->mTempPath}\n" ); 00869 unlink( $this->mTempPath ); 00870 } 00871 } 00872 00873 public function getTempPath() { 00874 return $this->mTempPath; 00875 } 00876 00886 public static function splitExtensions( $filename ) { 00887 $bits = explode( '.', $filename ); 00888 $basename = array_shift( $bits ); 00889 return array( $basename, $bits ); 00890 } 00891 00900 public static function checkFileExtension( $ext, $list ) { 00901 return in_array( strtolower( $ext ), $list ); 00902 } 00903 00912 public static function checkFileExtensionList( $ext, $list ) { 00913 return array_intersect( array_map( 'strtolower', $ext ), $list ); 00914 } 00915 00923 public static function verifyExtension( $mime, $extension ) { 00924 $magic = MimeMagic::singleton(); 00925 00926 if ( !$mime || $mime == 'unknown' || $mime == 'unknown/unknown' ) 00927 if ( !$magic->isRecognizableExtension( $extension ) ) { 00928 wfDebug( __METHOD__ . ": passing file with unknown detected mime type; " . 00929 "unrecognized extension '$extension', can't verify\n" ); 00930 return true; 00931 } else { 00932 wfDebug( __METHOD__ . ": rejecting file with unknown detected mime type; ". 00933 "recognized extension '$extension', so probably invalid file\n" ); 00934 return false; 00935 } 00936 00937 $match = $magic->isMatchingExtension( $extension, $mime ); 00938 00939 if ( $match === null ) { 00940 wfDebug( __METHOD__ . ": no file extension known for mime type $mime, passing file\n" ); 00941 return true; 00942 } elseif( $match === true ) { 00943 wfDebug( __METHOD__ . ": mime type $mime matches extension $extension, passing file\n" ); 00944 00945 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it! 00946 return true; 00947 00948 } else { 00949 wfDebug( __METHOD__ . ": mime type $mime mismatches file extension $extension, rejecting file\n" ); 00950 return false; 00951 } 00952 } 00953 00965 public static function detectScript( $file, $mime, $extension ) { 00966 global $wgAllowTitlesInSVG; 00967 wfProfileIn( __METHOD__ ); 00968 00969 # ugly hack: for text files, always look at the entire file. 00970 # For binary field, just check the first K. 00971 00972 if( strpos( $mime, 'text/' ) === 0 ) { 00973 $chunk = file_get_contents( $file ); 00974 } else { 00975 $fp = fopen( $file, 'rb' ); 00976 $chunk = fread( $fp, 1024 ); 00977 fclose( $fp ); 00978 } 00979 00980 $chunk = strtolower( $chunk ); 00981 00982 if( !$chunk ) { 00983 wfProfileOut( __METHOD__ ); 00984 return false; 00985 } 00986 00987 # decode from UTF-16 if needed (could be used for obfuscation). 00988 if( substr( $chunk, 0, 2 ) == "\xfe\xff" ) { 00989 $enc = 'UTF-16BE'; 00990 } elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" ) { 00991 $enc = 'UTF-16LE'; 00992 } else { 00993 $enc = null; 00994 } 00995 00996 if( $enc ) { 00997 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk ); 00998 } 00999 01000 $chunk = trim( $chunk ); 01001 01002 # @todo FIXME: Convert from UTF-16 if necessary! 01003 wfDebug( __METHOD__ . ": checking for embedded scripts and HTML stuff\n" ); 01004 01005 # check for HTML doctype 01006 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) { 01007 wfProfileOut( __METHOD__ ); 01008 return true; 01009 } 01010 01011 // Some browsers will interpret obscure xml encodings as UTF-8, while 01012 // PHP/expat will interpret the given encoding in the xml declaration (bug 47304) 01013 if ( $extension == 'svg' || strpos( $mime, 'image/svg' ) === 0 ) { 01014 if ( self::checkXMLEncodingMissmatch( $file ) ) { 01015 wfProfileOut( __METHOD__ ); 01016 return true; 01017 } 01018 } 01019 01035 $tags = array( 01036 '<a href', 01037 '<body', 01038 '<head', 01039 '<html', #also in safari 01040 '<img', 01041 '<pre', 01042 '<script', #also in safari 01043 '<table' 01044 ); 01045 01046 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) { 01047 $tags[] = '<title'; 01048 } 01049 01050 foreach( $tags as $tag ) { 01051 if( false !== strpos( $chunk, $tag ) ) { 01052 wfDebug( __METHOD__ . ": found something that may make it be mistaken for html: $tag\n" ); 01053 wfProfileOut( __METHOD__ ); 01054 return true; 01055 } 01056 } 01057 01058 /* 01059 * look for JavaScript 01060 */ 01061 01062 # resolve entity-refs to look at attributes. may be harsh on big files... cache result? 01063 $chunk = Sanitizer::decodeCharReferences( $chunk ); 01064 01065 # look for script-types 01066 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) { 01067 wfDebug( __METHOD__ . ": found script types\n" ); 01068 wfProfileOut( __METHOD__ ); 01069 return true; 01070 } 01071 01072 # look for html-style script-urls 01073 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) { 01074 wfDebug( __METHOD__ . ": found html-style script urls\n" ); 01075 wfProfileOut( __METHOD__ ); 01076 return true; 01077 } 01078 01079 # look for css-style script-urls 01080 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) { 01081 wfDebug( __METHOD__ . ": found css-style script urls\n" ); 01082 wfProfileOut( __METHOD__ ); 01083 return true; 01084 } 01085 01086 wfDebug( __METHOD__ . ": no scripts found\n" ); 01087 wfProfileOut( __METHOD__ ); 01088 return false; 01089 } 01090 01091 01099 public static function checkXMLEncodingMissmatch( $file ) { 01100 global $wgSVGMetadataCutoff; 01101 $contents = file_get_contents( $file, false, null, -1, $wgSVGMetadataCutoff ); 01102 $encodingRegex = '!encoding[ \t\n\r]*=[ \t\n\r]*[\'"](.*?)[\'"]!si'; 01103 01104 if ( preg_match( "!<\?xml\b(.*?)\?>!si", $contents, $matches ) ) { 01105 if ( preg_match( $encodingRegex, $matches[1], $encMatch ) 01106 && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings ) 01107 ) { 01108 wfDebug( __METHOD__ . ": Found unsafe XML encoding '{$encMatch[1]}'\n" ); 01109 return true; 01110 } 01111 } elseif ( preg_match( "!<\?xml\b!si", $contents ) ) { 01112 // Start of XML declaration without an end in the first $wgSVGMetadataCutoff 01113 // bytes. There shouldn't be a legitimate reason for this to happen. 01114 wfDebug( __METHOD__ . ": Unmatched XML declaration start\n" ); 01115 return true; 01116 } elseif ( substr( $contents, 0, 4) == "\x4C\x6F\xA7\x94" ) { 01117 // EBCDIC encoded XML 01118 wfDebug( __METHOD__ . ": EBCDIC Encoded XML\n" ); 01119 return true; 01120 } 01121 01122 // It's possible the file is encoded with multi-byte encoding, so re-encode attempt to 01123 // detect the encoding in case is specifies an encoding not whitelisted in self::$safeXmlEncodings 01124 $attemptEncodings = array( 'UTF-16', 'UTF-16BE', 'UTF-32', 'UTF-32BE' ); 01125 foreach ( $attemptEncodings as $encoding ) { 01126 wfSuppressWarnings(); 01127 $str = iconv( $encoding, 'UTF-8', $contents ); 01128 wfRestoreWarnings(); 01129 if ( $str != '' && preg_match( "!<\?xml\b(.*?)\?>!si", $str, $matches ) ) { 01130 if ( preg_match( $encodingRegex, $matches[1], $encMatch ) 01131 && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings ) 01132 ) { 01133 wfDebug( __METHOD__ . ": Found unsafe XML encoding '{$encMatch[1]}'\n" ); 01134 return true; 01135 } 01136 } elseif ( $str != '' && preg_match( "!<\?xml\b!si", $str ) ) { 01137 // Start of XML declaration without an end in the first $wgSVGMetadataCutoff 01138 // bytes. There shouldn't be a legitimate reason for this to happen. 01139 wfDebug( __METHOD__ . ": Unmatched XML declaration start\n" ); 01140 return true; 01141 } 01142 } 01143 01144 return false; 01145 } 01146 01151 protected function detectScriptInSvg( $filename ) { 01152 $this->mSVGNSError = false; 01153 $check = new XmlTypeCheck( 01154 $filename, 01155 array( $this, 'checkSvgScriptCallback' ), 01156 array( 'processing_instruction_handler' => 'UploadBase::checkSvgPICallback' ) 01157 ); 01158 if ( $check->wellFormed !== true ) { 01159 // Invalid xml (bug 58553) 01160 return array( 'uploadinvalidxml' ); 01161 } elseif ( $check->filterMatch ) { 01162 if ( $this->mSVGNSError ) { 01163 return array( 'uploadscriptednamespace', $this->mSVGNSError ); 01164 } 01165 return array( 'uploadscripted' ); 01166 } 01167 return false; 01168 } 01169 01176 public function checkSvgScriptCallback( $element, $attribs ) { 01177 list( $namespace, $strippedElement ) = $this->splitXmlNamespace( $element ); 01178 01179 static $validNamespaces = array( 01180 '', 01181 'adobe:ns:meta/', 01182 'http://creativecommons.org/ns#', 01183 'http://inkscape.sourceforge.net/dtd/sodipodi-0.dtd', 01184 'http://ns.adobe.com/adobeillustrator/10.0/', 01185 'http://ns.adobe.com/adobesvgviewerextensions/3.0/', 01186 'http://ns.adobe.com/extensibility/1.0/', 01187 'http://ns.adobe.com/flows/1.0/', 01188 'http://ns.adobe.com/illustrator/1.0/', 01189 'http://ns.adobe.com/imagereplacement/1.0/', 01190 'http://ns.adobe.com/pdf/1.3/', 01191 'http://ns.adobe.com/photoshop/1.0/', 01192 'http://ns.adobe.com/saveforweb/1.0/', 01193 'http://ns.adobe.com/variables/1.0/', 01194 'http://ns.adobe.com/xap/1.0/', 01195 'http://ns.adobe.com/xap/1.0/g/', 01196 'http://ns.adobe.com/xap/1.0/g/img/', 01197 'http://ns.adobe.com/xap/1.0/mm/', 01198 'http://ns.adobe.com/xap/1.0/rights/', 01199 'http://ns.adobe.com/xap/1.0/stype/dimensions#', 01200 'http://ns.adobe.com/xap/1.0/stype/font#', 01201 'http://ns.adobe.com/xap/1.0/stype/manifestitem#', 01202 'http://ns.adobe.com/xap/1.0/stype/resourceevent#', 01203 'http://ns.adobe.com/xap/1.0/stype/resourceref#', 01204 'http://ns.adobe.com/xap/1.0/t/pg/', 01205 'http://purl.org/dc/elements/1.1/', 01206 'http://purl.org/dc/elements/1.1', 01207 'http://schemas.microsoft.com/visio/2003/svgextensions/', 01208 'http://sodipodi.sourceforge.net/dtd/sodipodi-0.dtd', 01209 'http://web.resource.org/cc/', 01210 'http://www.freesoftware.fsf.org/bkchem/cdml', 01211 'http://www.inkscape.org/namespaces/inkscape', 01212 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', 01213 'http://www.w3.org/2000/svg', 01214 ); 01215 01216 if ( !in_array( $namespace, $validNamespaces ) ) { 01217 wfDebug( __METHOD__ . ": Non-svg namespace '$namespace' in uploaded file.\n" ); 01218 // @TODO return a status object to a closure in XmlTypeCheck, for MW1.21+ 01219 $this->mSVGNSError = $namespace; 01220 return true; 01221 } 01222 01223 /* 01224 * check for elements that can contain javascript 01225 */ 01226 if( $strippedElement == 'script' ) { 01227 wfDebug( __METHOD__ . ": Found script element '$element' in uploaded file.\n" ); 01228 return true; 01229 } 01230 01231 # 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> 01232 if( $strippedElement == 'handler' ) { 01233 wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file.\n" ); 01234 return true; 01235 } 01236 01237 # SVG reported in Feb '12 that used xml:stylesheet to generate javascript block 01238 if( $strippedElement == 'stylesheet' ) { 01239 wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file.\n" ); 01240 return true; 01241 } 01242 01243 # Block iframes, in case they pass the namespace check 01244 if ( $strippedElement == 'iframe' ) { 01245 wfDebug( __METHOD__ . ": iframe in uploaded file.\n" ); 01246 return true; 01247 } 01248 01249 01250 foreach( $attribs as $attrib => $value ) { 01251 $stripped = $this->stripXmlNamespace( $attrib ); 01252 $value = strtolower( $value ); 01253 01254 if( substr( $stripped, 0, 2 ) == 'on' ) { 01255 wfDebug( __METHOD__ . ": Found event-handler attribute '$attrib'='$value' in uploaded file.\n" ); 01256 return true; 01257 } 01258 01259 # href with non-local target (don't allow http://, javascript:, etc) 01260 if ( $stripped == 'href' 01261 && strpos( $value, 'data:' ) !== 0 01262 && strpos( $value, '#' ) !== 0 01263 ) { 01264 if ( !( $strippedElement === 'a' 01265 && preg_match( '!^https?://!im', $value ) ) 01266 ) { 01267 wfDebug( __METHOD__ . ": Found href attribute <$strippedElement " 01268 . "'$attrib'='$value' in uploaded file.\n" ); 01269 01270 return true; 01271 } 01272 } 01273 01274 # href with embedded svg as target 01275 if( $stripped == 'href' && preg_match( '!data:[^,]*image/svg[^,]*,!sim', $value ) ) { 01276 wfDebug( __METHOD__ . ": Found href to embedded svg \"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" ); 01277 return true; 01278 } 01279 01280 # href with embedded (text/xml) svg as target 01281 if( $stripped == 'href' && preg_match( '!data:[^,]*text/xml[^,]*,!sim', $value ) ) { 01282 wfDebug( __METHOD__ . ": Found href to embedded svg \"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" ); 01283 return true; 01284 } 01285 01286 # use set/animate to add event-handler attribute to parent 01287 if( ( $strippedElement == 'set' || $strippedElement == 'animate' ) && $stripped == 'attributename' && substr( $value, 0, 2 ) == 'on' ) { 01288 wfDebug( __METHOD__ . ": Found svg setting event-handler attribute with \"<$strippedElement $stripped='$value'...\" in uploaded file.\n" ); 01289 return true; 01290 } 01291 01292 # use set to add href attribute to parent element 01293 if( $strippedElement == 'set' && $stripped == 'attributename' && strpos( $value, 'href' ) !== false ) { 01294 wfDebug( __METHOD__ . ": Found svg setting href attribute '$value' in uploaded file.\n" ); 01295 return true; 01296 } 01297 01298 # use set to add a remote / data / script target to an element 01299 if( $strippedElement == 'set' && $stripped == 'to' && preg_match( '!(http|https|data|script):!sim', $value ) ) { 01300 wfDebug( __METHOD__ . ": Found svg setting attribute to '$value' in uploaded file.\n" ); 01301 return true; 01302 } 01303 01304 # use handler attribute with remote / data / script 01305 if( $stripped == 'handler' && preg_match( '!(http|https|data|script):!sim', $value ) ) { 01306 wfDebug( __METHOD__ . ": Found svg setting handler with remote/data/script '$attrib'='$value' in uploaded file.\n" ); 01307 return true; 01308 } 01309 01310 # use CSS styles to bring in remote code 01311 # catch url("http:..., url('http:..., url(http:..., but not url("#..., url('#..., url(#.... 01312 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 ) ) { 01313 foreach ( $matches[1] as $match ) { 01314 if ( !preg_match( '!(?:font|clip-path|fill|filter|marker|marker-end|marker-mid|marker-start|mask|stroke)\s*:\s*url\s*\(\s*(#|\'#|"#)!sim', $match ) ) { 01315 wfDebug( __METHOD__ . ": Found svg setting a style with remote url '$attrib'='$value' in uploaded file.\n" ); 01316 return true; 01317 } 01318 } 01319 } 01320 01321 # image filters can pull in url, which could be svg that executes scripts 01322 if( $strippedElement == 'image' && $stripped == 'filter' && preg_match( '!url\s*\(!sim', $value ) ) { 01323 wfDebug( __METHOD__ . ": Found image filter with url: \"<$strippedElement $stripped='$value'...\" in uploaded file.\n" ); 01324 return true; 01325 } 01326 01327 } 01328 01329 return false; //No scripts detected 01330 } 01331 01337 private static function splitXmlNamespace( $element ) { 01338 // 'http://www.w3.org/2000/svg:script' -> array( 'http://www.w3.org/2000/svg', 'script' ) 01339 $parts = explode( ':', strtolower( $element ) ); 01340 $name = array_pop( $parts ); 01341 $ns = implode( ':', $parts ); 01342 return array( $ns, $name ); 01343 } 01344 01351 public static function checkSvgPICallback( $target, $data ) { 01352 // Don't allow external stylesheets (bug 57550) 01353 if ( preg_match( '/xml-stylesheet/i', $target) ) { 01354 return true; 01355 } 01356 return false; 01357 } 01358 01363 private function stripXmlNamespace( $name ) { 01364 // 'http://www.w3.org/2000/svg:script' -> 'script' 01365 $parts = explode( ':', strtolower( $name ) ); 01366 return array_pop( $parts ); 01367 } 01368 01379 public static function detectVirus( $file ) { 01380 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut; 01381 wfProfileIn( __METHOD__ ); 01382 01383 if ( !$wgAntivirus ) { 01384 wfDebug( __METHOD__ . ": virus scanner disabled\n" ); 01385 wfProfileOut( __METHOD__ ); 01386 return null; 01387 } 01388 01389 if ( !$wgAntivirusSetup[$wgAntivirus] ) { 01390 wfDebug( __METHOD__ . ": unknown virus scanner: $wgAntivirus\n" ); 01391 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>", 01392 array( 'virus-badscanner', $wgAntivirus ) ); 01393 wfProfileOut( __METHOD__ ); 01394 return wfMessage( 'virus-unknownscanner' )->text() . " $wgAntivirus"; 01395 } 01396 01397 # look up scanner configuration 01398 $command = $wgAntivirusSetup[$wgAntivirus]['command']; 01399 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap']; 01400 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ? 01401 $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null; 01402 01403 if ( strpos( $command, "%f" ) === false ) { 01404 # simple pattern: append file to scan 01405 $command .= " " . wfEscapeShellArg( $file ); 01406 } else { 01407 # complex pattern: replace "%f" with file to scan 01408 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command ); 01409 } 01410 01411 wfDebug( __METHOD__ . ": running virus scan: $command \n" ); 01412 01413 # execute virus scanner 01414 $exitCode = false; 01415 01416 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too. 01417 # that does not seem to be worth the pain. 01418 # Ask me (Duesentrieb) about it if it's ever needed. 01419 $output = wfShellExec( "$command 2>&1", $exitCode ); 01420 01421 # map exit code to AV_xxx constants. 01422 $mappedCode = $exitCode; 01423 if ( $exitCodeMap ) { 01424 if ( isset( $exitCodeMap[$exitCode] ) ) { 01425 $mappedCode = $exitCodeMap[$exitCode]; 01426 } elseif ( isset( $exitCodeMap["*"] ) ) { 01427 $mappedCode = $exitCodeMap["*"]; 01428 } 01429 } 01430 01431 /* NB: AV_NO_VIRUS is 0 but AV_SCAN_FAILED is false, 01432 * so we need the strict equalities === and thus can't use a switch here 01433 */ 01434 if ( $mappedCode === AV_SCAN_FAILED ) { 01435 # scan failed (code was mapped to false by $exitCodeMap) 01436 wfDebug( __METHOD__ . ": failed to scan $file (code $exitCode).\n" ); 01437 01438 $output = $wgAntivirusRequired ? wfMessage( 'virus-scanfailed', array( $exitCode ) )->text() : null; 01439 } elseif ( $mappedCode === AV_SCAN_ABORTED ) { 01440 # scan failed because filetype is unknown (probably imune) 01441 wfDebug( __METHOD__ . ": unsupported file type $file (code $exitCode).\n" ); 01442 $output = null; 01443 } elseif ( $mappedCode === AV_NO_VIRUS ) { 01444 # no virus found 01445 wfDebug( __METHOD__ . ": file passed virus scan.\n" ); 01446 $output = false; 01447 } else { 01448 $output = trim( $output ); 01449 01450 if ( !$output ) { 01451 $output = true; #if there's no output, return true 01452 } elseif ( $msgPattern ) { 01453 $groups = array(); 01454 if ( preg_match( $msgPattern, $output, $groups ) ) { 01455 if ( $groups[1] ) { 01456 $output = $groups[1]; 01457 } 01458 } 01459 } 01460 01461 wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output \n" ); 01462 } 01463 01464 wfProfileOut( __METHOD__ ); 01465 return $output; 01466 } 01467 01476 private function checkOverwrite( $user ) { 01477 // First check whether the local file can be overwritten 01478 $file = $this->getLocalFile(); 01479 if( $file->exists() ) { 01480 if( !self::userCanReUpload( $user, $file ) ) { 01481 return array( 'fileexists-forbidden', $file->getName() ); 01482 } else { 01483 return true; 01484 } 01485 } 01486 01487 /* Check shared conflicts: if the local file does not exist, but 01488 * wfFindFile finds a file, it exists in a shared repository. 01489 */ 01490 $file = wfFindFile( $this->getTitle() ); 01491 if ( $file && !$user->isAllowed( 'reupload-shared' ) ) { 01492 return array( 'fileexists-shared-forbidden', $file->getName() ); 01493 } 01494 01495 return true; 01496 } 01497 01505 public static function userCanReUpload( User $user, $img ) { 01506 if( $user->isAllowed( 'reupload' ) ) { 01507 return true; // non-conditional 01508 } 01509 if( !$user->isAllowed( 'reupload-own' ) ) { 01510 return false; 01511 } 01512 if( is_string( $img ) ) { 01513 $img = wfLocalFile( $img ); 01514 } 01515 if ( !( $img instanceof LocalFile ) ) { 01516 return false; 01517 } 01518 01519 return $user->getId() == $img->getUser( 'id' ); 01520 } 01521 01533 public static function getExistsWarning( $file ) { 01534 if( $file->exists() ) { 01535 return array( 'warning' => 'exists', 'file' => $file ); 01536 } 01537 01538 if( $file->getTitle()->getArticleID() ) { 01539 return array( 'warning' => 'page-exists', 'file' => $file ); 01540 } 01541 01542 if ( $file->wasDeleted() && !$file->exists() ) { 01543 return array( 'warning' => 'was-deleted', 'file' => $file ); 01544 } 01545 01546 if( strpos( $file->getName(), '.' ) == false ) { 01547 $partname = $file->getName(); 01548 $extension = ''; 01549 } else { 01550 $n = strrpos( $file->getName(), '.' ); 01551 $extension = substr( $file->getName(), $n + 1 ); 01552 $partname = substr( $file->getName(), 0, $n ); 01553 } 01554 $normalizedExtension = File::normalizeExtension( $extension ); 01555 01556 if ( $normalizedExtension != $extension ) { 01557 // We're not using the normalized form of the extension. 01558 // Normal form is lowercase, using most common of alternate 01559 // extensions (eg 'jpg' rather than 'JPEG'). 01560 // 01561 // Check for another file using the normalized form... 01562 $nt_lc = Title::makeTitle( NS_FILE, "{$partname}.{$normalizedExtension}" ); 01563 $file_lc = wfLocalFile( $nt_lc ); 01564 01565 if( $file_lc->exists() ) { 01566 return array( 01567 'warning' => 'exists-normalized', 01568 'file' => $file, 01569 'normalizedFile' => $file_lc 01570 ); 01571 } 01572 } 01573 01574 // Check for files with the same name but a different extension 01575 $similarFiles = RepoGroup::singleton()->getLocalRepo()->findFilesByPrefix( 01576 "{$partname}.", 1 ); 01577 if ( count( $similarFiles ) ) { 01578 return array( 01579 'warning' => 'exists-normalized', 01580 'file' => $file, 01581 'normalizedFile' => $similarFiles[0], 01582 ); 01583 } 01584 01585 if ( self::isThumbName( $file->getName() ) ) { 01586 # Check for filenames like 50px- or 180px-, these are mostly thumbnails 01587 $nt_thb = Title::newFromText( substr( $partname, strpos( $partname, '-' ) + 1 ) . '.' . $extension, NS_FILE ); 01588 $file_thb = wfLocalFile( $nt_thb ); 01589 if( $file_thb->exists() ) { 01590 return array( 01591 'warning' => 'thumb', 01592 'file' => $file, 01593 'thumbFile' => $file_thb 01594 ); 01595 } else { 01596 // File does not exist, but we just don't like the name 01597 return array( 01598 'warning' => 'thumb-name', 01599 'file' => $file, 01600 'thumbFile' => $file_thb 01601 ); 01602 } 01603 } 01604 01605 foreach( self::getFilenamePrefixBlacklist() as $prefix ) { 01606 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) { 01607 return array( 01608 'warning' => 'bad-prefix', 01609 'file' => $file, 01610 'prefix' => $prefix 01611 ); 01612 } 01613 } 01614 01615 return false; 01616 } 01617 01623 public static function isThumbName( $filename ) { 01624 $n = strrpos( $filename, '.' ); 01625 $partname = $n ? substr( $filename, 0, $n ) : $filename; 01626 return ( 01627 substr( $partname, 3, 3 ) == 'px-' || 01628 substr( $partname, 2, 3 ) == 'px-' 01629 ) && 01630 preg_match( "/[0-9]{2}/", substr( $partname, 0, 2 ) ); 01631 } 01632 01638 public static function getFilenamePrefixBlacklist() { 01639 $blacklist = array(); 01640 $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage(); 01641 if( !$message->isDisabled() ) { 01642 $lines = explode( "\n", $message->plain() ); 01643 foreach( $lines as $line ) { 01644 // Remove comment lines 01645 $comment = substr( trim( $line ), 0, 1 ); 01646 if ( $comment == '#' || $comment == '' ) { 01647 continue; 01648 } 01649 // Remove additional comments after a prefix 01650 $comment = strpos( $line, '#' ); 01651 if ( $comment > 0 ) { 01652 $line = substr( $line, 0, $comment-1 ); 01653 } 01654 $blacklist[] = trim( $line ); 01655 } 01656 } 01657 return $blacklist; 01658 } 01659 01670 public function getImageInfo( $result ) { 01671 $file = $this->getLocalFile(); 01672 // TODO This cries out for refactoring. We really want to say $file->getAllInfo(); here. 01673 // Perhaps "info" methods should be moved into files, and the API should just wrap them in queries. 01674 if ( $file instanceof UploadStashFile ) { 01675 $imParam = ApiQueryStashImageInfo::getPropertyNames(); 01676 $info = ApiQueryStashImageInfo::getInfo( $file, array_flip( $imParam ), $result ); 01677 } else { 01678 $imParam = ApiQueryImageInfo::getPropertyNames(); 01679 $info = ApiQueryImageInfo::getInfo( $file, array_flip( $imParam ), $result ); 01680 } 01681 return $info; 01682 } 01683 01688 public function convertVerifyErrorToStatus( $error ) { 01689 $code = $error['status']; 01690 unset( $code['status'] ); 01691 return Status::newFatal( $this->getVerificationErrorCode( $code ), $error ); 01692 } 01693 01698 public static function getMaxUploadSize( $forType = null ) { 01699 global $wgMaxUploadSize; 01700 01701 if ( is_array( $wgMaxUploadSize ) ) { 01702 if ( !is_null( $forType ) && isset( $wgMaxUploadSize[$forType] ) ) { 01703 return $wgMaxUploadSize[$forType]; 01704 } else { 01705 return $wgMaxUploadSize['*']; 01706 } 01707 } else { 01708 return intval( $wgMaxUploadSize ); 01709 } 01710 } 01711 01718 public static function getSessionStatus( $statusKey ) { 01719 return isset( $_SESSION[self::SESSION_STATUS_KEY][$statusKey] ) 01720 ? $_SESSION[self::SESSION_STATUS_KEY][$statusKey] 01721 : false; 01722 } 01723 01731 public static function setSessionStatus( $statusKey, $value ) { 01732 if ( $value === false ) { 01733 unset( $_SESSION[self::SESSION_STATUS_KEY][$statusKey] ); 01734 } else { 01735 $_SESSION[self::SESSION_STATUS_KEY][$statusKey] = $value; 01736 } 01737 } 01738 }