6 * UploadBase and subclasses are the backend of MediaWiki's file uploads.
7 * The frontends are formed by ApiUpload and SpecialUpload.
9 * See also includes/docs/upload.txt
11 * @author Brion Vibber
12 * @author Bryan Tong Minh
13 * @author Michael Dale
16 abstract class UploadBase
{
18 protected $mDesiredDestName, $mDestName, $mRemoveTempFile, $mSourceType;
19 protected $mTitle = false, $mTitleError = 0;
20 protected $mFilteredName, $mFinalExtension;
21 protected $mLocalFile;
25 const BEFORE_PROCESSING
= 1;
26 const LARGE_FILE_SERVER
= 2;
28 const MIN_LENGTH_PARTNAME
= 4;
29 const ILLEGAL_FILENAME
= 5;
30 const PROTECTED_PAGE
= 6;
31 const OVERWRITE_EXISTING_FILE
= 7;
32 const FILETYPE_MISSING
= 8;
33 const FILETYPE_BADTYPE
= 9;
34 const VERIFICATION_ERROR
= 10;
35 const UPLOAD_VERIFICATION_ERROR
= 11;
36 const UPLOAD_WARNING
= 12;
37 const INTERNAL_ERROR
= 13;
38 const MIN_LENGHT_PARTNAME
= 14;
40 const SESSION_VERSION
= 2;
43 * Returns true if uploads are enabled.
44 * Can be override by subclasses.
46 public static function isEnabled() {
47 global $wgEnableUploads;
48 if ( !$wgEnableUploads )
51 # Check php's file_uploads setting
52 if( !wfIniGetBool( 'file_uploads' ) ) {
59 * Returns true if the user can use this upload module or else a string
60 * identifying the missing permission.
61 * Can be overriden by subclasses.
63 public static function isAllowed( $user ) {
64 if( !$user->isAllowed( 'upload' ) )
69 // Upload handlers. Should probably just be a global
70 static $uploadHandlers = array( 'Stash', 'File', 'Url' );
73 * Create a form of UploadBase depending on wpSourceType and initializes it
75 public static function createFromRequest( &$request, $type = null ) {
76 $type = $type ?
$type : $request->getVal( 'wpSourceType', 'File' );
81 // Get the upload class
82 $type = ucfirst( $type );
83 $className = 'UploadFrom' . $type;
84 wfDebug( __METHOD__
. ": class name: $className\n" );
85 if( !in_array( $type, self
::$uploadHandlers ) )
88 // Check whether this upload class is enabled
89 if( !call_user_func( array( $className, 'isEnabled' ) ) )
92 // Check whether the request is valid
93 if( !call_user_func( array( $className, 'isValidRequest' ), $request ) )
96 $handler = new $className;
98 $handler->initializeFromRequest( $request );
103 * Check whether a request if valid for this handler
105 public static function isValidRequest( $request ) {
109 public function __construct() {}
112 * Do the real variable initialization
114 public function initialize( $name, $tempPath, $fileSize, $removeTempFile = false ) {
115 $this->mDesiredDestName
= $name;
116 $this->mTempPath
= $tempPath;
117 $this->mFileSize
= $fileSize;
118 $this->mRemoveTempFile
= $removeTempFile;
122 * Initialize from a WebRequest. Override this in a subclass.
124 public abstract function initializeFromRequest( &$request );
127 * Fetch the file. Usually a no-op
129 public function fetchFile() {
130 return Status
::newGood();
134 * Return the file size
136 public function isEmptyFile(){
137 return empty( $this->mFileSize
);
142 * @param string $srcPath the source path
143 * @returns the real path if it was a virtual url
145 function getRealPath( $srcPath ){
146 $repo = RepoGroup
::singleton()->getLocalRepo();
147 if ( $repo->isVirtualUrl( $srcPath ) ) {
148 return $repo->resolveVirtualUrl( $srcPath );
154 * Verify whether the upload is sane.
155 * Returns self::OK or else an array with error information
157 public function verifyUpload() {
159 * If there was no filename or a zero size given, give up quick.
161 if( $this->isEmptyFile() )
162 return array( 'status' => self
::EMPTY_FILE
);
164 $nt = $this->getTitle();
165 if( is_null( $nt ) ) {
166 $result = array( 'status' => $this->mTitleError
);
167 if( $this->mTitleError
== self
::ILLEGAL_FILENAME
)
168 $result['filtered'] = $this->mFilteredName
;
169 if ( $this->mTitleError
== self
::FILETYPE_BADTYPE
)
170 $result['finalExt'] = $this->mFinalExtension
;
173 $this->mDestName
= $this->getLocalFile()->getName();
176 * In some cases we may forbid overwriting of existing files.
178 $overwrite = $this->checkOverwrite();
179 if( $overwrite !== true )
180 return array( 'status' => self
::OVERWRITE_EXISTING_FILE
, 'overwrite' => $overwrite );
183 * Look at the contents of the file; if we can recognize the
184 * type but it's corrupt or data of the wrong type, we should
185 * probably not accept it.
187 $verification = $this->verifyFile();
189 if( $verification !== true ) {
190 if( !is_array( $verification ) )
191 $verification = array( $verification );
192 return array( 'status' => self
::VERIFICATION_ERROR
,
193 'details' => $verification );
198 if( !wfRunHooks( 'UploadVerification',
199 array( $this->mDestName
, $this->mTempPath
, &$error ) ) ) {
200 // This status needs another name...
201 return array( 'status' => self
::UPLOAD_VERIFICATION_ERROR
, 'error' => $error );
204 return array( 'status' => self
::OK
);
208 * Verifies that it's ok to include the uploaded file
210 * FIXME: this function seems to intermixes tmpfile and $this->mTempPath .. no idea why this is
212 * @param string $tmpfile the full path of the temporary file to verify
213 * @return mixed true of the file is verified, a string or array otherwise.
215 protected function verifyFile() {
216 $this->mFileProps
= File
::getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
217 $this->checkMacBinary();
219 #magically determine mime type
220 $magic = MimeMagic
::singleton();
221 $mime = $magic->guessMimeType( $this->mTempPath
, false );
223 #check mime type, if desired
224 global $wgVerifyMimeType;
225 if ( $wgVerifyMimeType ) {
226 global $wgMimeTypeBlacklist;
227 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) )
228 return array( 'filetype-badmime', $mime );
231 $fp = fopen( $this->mTempPath
, 'rb' );
232 $chunk = fread( $fp, 256 );
234 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension
);
235 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath
, $chunk, $extMime );
236 foreach ( $ieTypes as $ieType ) {
237 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
238 return array( 'filetype-bad-ie-mime', $ieType );
243 #check for htmlish code and javascript
244 if( self
::detectScript( $this->mTempPath
, $mime, $this->mFinalExtension
) ) {
245 return 'uploadscripted';
247 if( $this->mFinalExtension
== 'svg' ||
$mime == 'image/svg+xml' ) {
248 if( self
::detectScriptInSvg( $this->mTempPath
) ) {
249 return 'uploadscripted';
254 * Scan the uploaded file for viruses
256 $virus = $this->detectVirus( $this->mTempPath
);
258 return array( 'uploadvirus', $virus );
260 wfDebug( __METHOD__
. ": all clear; passing.\n" );
265 * Check whether the user can edit, upload and create the image.
267 * @param User $user the user to verify the permissions against
268 * @return mixed An array as returned by getUserPermissionsErrors or true
269 * in case the user has proper permissions.
271 public function verifyPermissions( $user ) {
273 * If the image is protected, non-sysop users won't be able
274 * to modify it by uploading a new revision.
276 $nt = $this->getTitle();
279 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
280 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
281 $permErrorsCreate = ( $nt->exists() ?
array() : $nt->getUserPermissionsErrors( 'create', $user ) );
282 if( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
283 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
284 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
291 * Check for non fatal problems with the file
293 * @return array Array of warnings
295 public function checkWarnings() {
298 $localFile = $this->getLocalFile();
299 $filename = $localFile->getName();
300 $n = strrpos( $filename, '.' );
301 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
304 * Check whether the resulting filename is different from the desired one,
305 * but ignore things like ucfirst() and spaces/underscore things
307 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName
);
308 global $wgCapitalLinks, $wgContLang;
309 if ( $wgCapitalLinks ) {
310 $comparableName = $wgContLang->ucfirst( $comparableName );
312 if( $this->mDesiredDestName
!= $filename && $comparableName != $filename )
313 $warnings['badfilename'] = $filename;
315 // Check whether the file extension is on the unwanted list
316 global $wgCheckFileExtensions, $wgFileExtensions;
317 if ( $wgCheckFileExtensions ) {
318 if ( !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) )
319 $warnings['filetype-unwanted-type'] = $this->mFinalExtension
;
322 global $wgUploadSizeWarning;
323 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) )
324 $warnings['large-file'] = $wgUploadSizeWarning;
326 if ( $this->mFileSize
== 0 )
327 $warnings['emptyfile'] = true;
330 $exists = self
::getExistsWarning( $localFile );
331 if( $exists !== false )
332 $warnings['exists'] = $exists;
334 // Check dupes against existing files
335 $hash = File
::sha1Base36( $this->mTempPath
);
336 $dupes = RepoGroup
::singleton()->findBySha1( $hash );
337 $title = $this->getTitle();
338 // Remove all matches against self
339 foreach ( $dupes as $key => $dupe ) {
340 if( $title->equals( $dupe->getTitle() ) )
341 unset( $dupes[$key] );
344 $warnings['duplicate'] = $dupes;
346 // Check dupes against archives
347 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
348 if ( $archivedImage->getID() > 0 )
349 $warnings['duplicate-archive'] = $archivedImage->getName();
355 * Really perform the upload. Stores the file in the local repo, watches
356 * if necessary and runs the UploadComplete hook.
358 * @return mixed Status indicating the whether the upload succeeded.
360 public function performUpload( $comment, $pageText, $watch, $user ) {
361 wfDebug( "\n\n\performUpload: sum:" . $comment . ' c: ' . $pageText . ' w:' . $watch );
362 $status = $this->getLocalFile()->upload( $this->mTempPath
, $comment, $pageText,
363 File
::DELETE_SOURCE
, $this->mFileProps
, false, $user );
365 if( $status->isGood() && $watch )
366 $user->addWatch( $this->getLocalFile()->getTitle() );
368 if( $status->isGood() )
369 wfRunHooks( 'UploadComplete', array( &$this ) );
375 * Returns the title of the file to be uploaded. Sets mTitleError in case
376 * the name was illegal.
378 * @return Title The title of the file or null in case the name was illegal
380 public function getTitle() {
381 if ( $this->mTitle
!== false )
382 return $this->mTitle
;
385 * Chop off any directories in the given filename. Then
386 * filter out illegal characters, and try to make a legible name
387 * out of it. We'll strip some silently that Title would die on.
389 $basename = $this->mDesiredDestName
;
391 $this->mFilteredName
= wfStripIllegalFilenameChars( $basename );
392 /* Normalize to title form before we do any further processing */
393 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
394 if( is_null( $nt ) ) {
395 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
396 return $this->mTitle
= null;
398 $this->mFilteredName
= $nt->getDBkey();
401 * We'll want to blacklist against *any* 'extension', and use
402 * only the final one for the whitelist.
404 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName
);
406 if( count( $ext ) ) {
407 $this->mFinalExtension
= trim( $ext[count( $ext ) - 1] );
409 $this->mFinalExtension
= '';
412 /* Don't allow users to override the blacklist (check file extension) */
413 global $wgCheckFileExtensions, $wgStrictFileExtensions;
414 global $wgFileExtensions, $wgFileBlacklist;
415 if ( $this->mFinalExtension
== '' ) {
416 $this->mTitleError
= self
::FILETYPE_MISSING
;
417 return $this->mTitle
= null;
418 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
419 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
420 !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) ) ) {
421 $this->mTitleError
= self
::FILETYPE_BADTYPE
;
422 return $this->mTitle
= null;
425 # If there was more than one "extension", reassemble the base
426 # filename to prevent bogus complaints about length
427 if( count( $ext ) > 1 ) {
428 for( $i = 0; $i < count( $ext ) - 1; $i++
)
429 $partname .= '.' . $ext[$i];
432 if( strlen( $partname ) < 1 ) {
433 $this->mTitleError
= self
::MIN_LENGTH_PARTNAME
;
434 return $this->mTitle
= null;
437 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
438 if( is_null( $nt ) ) {
439 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
440 return $this->mTitle
= null;
442 return $this->mTitle
= $nt;
446 * Return the local file and initializes if necessary.
448 public function getLocalFile() {
449 if( is_null( $this->mLocalFile
) ) {
450 $nt = $this->getTitle();
451 $this->mLocalFile
= is_null( $nt ) ?
null : wfLocalFile( $nt );
453 return $this->mLocalFile
;
457 * Stash a file in a temporary directory for later processing
458 * after the user has confirmed it.
460 * If the user doesn't explicitly cancel or accept, these files
461 * can accumulate in the temp directory.
463 * @param string $saveName - the destination filename
464 * @param string $tempSrc - the source temporary file to save
465 * @return string - full path the stashed file, or false on failure
468 protected function saveTempUploadedFile( $saveName, $tempSrc ) {
469 $repo = RepoGroup
::singleton()->getLocalRepo();
470 $status = $repo->storeTemp( $saveName, $tempSrc );
475 * Append a file to a stashed file.
477 * @param string $srcPath Path to file to append from
478 * @param string $toAppendPath Path to file to append to
479 * @return Status Status
481 public function appendToUploadFile( $srcPath, $toAppendPath ){
482 $repo = RepoGroup
::singleton()->getLocalRepo();
483 $status = $repo->append( $srcPath, $toAppendPath );
488 * Stash a file in a temporary directory for later processing,
489 * and save the necessary descriptive info into the session.
490 * Returns a key value which will be passed through a form
491 * to pick up the path info on a later invocation.
493 * @return int Session key
495 public function stashSession() {
496 $status = $this->saveTempUploadedFile( $this->mDestName
, $this->mTempPath
);
497 if( !$status->isOK() ) {
498 # Couldn't save the file.
501 if(!isset($_SESSION))
502 session_start(); // start up the session (might have been previously closed to prevent php session locking)
503 $key = $this->getSessionKey();
504 $_SESSION['wsUploadData'][$key] = array(
505 'mTempPath' => $status->value
,
506 'mFileSize' => $this->mFileSize
,
507 'mFileProps' => $this->mFileProps
,
508 'version' => self
::SESSION_VERSION
,
514 * Generate a random session key from stash in cases where we want to start an upload without much information
516 protected function getSessionKey(){
517 $key = mt_rand( 0, 0x7fffffff );
518 $_SESSION['wsUploadData'][$key] = array();
523 * Remove a temporarily kept file stashed by saveTempUploadedFile().
526 public function unsaveUploadedFile() {
527 $repo = RepoGroup
::singleton()->getLocalRepo();
528 $success = $repo->freeTemp( $this->mTempPath
);
533 * If we've modified the upload file we need to manually remove it
534 * on exit to clean up.
537 public function cleanupTempFile() {
538 if ( $this->mRemoveTempFile
&& $this->mTempPath
&& file_exists( $this->mTempPath
) ) {
539 wfDebug( __METHOD__
. ": Removing temporary file {$this->mTempPath}\n" );
540 unlink( $this->mTempPath
);
544 public function getTempPath() {
545 return $this->mTempPath
;
549 * Split a file into a base name and all dot-delimited 'extensions'
550 * on the end. Some web server configurations will fall back to
551 * earlier pseudo-'extensions' to determine type and execute
552 * scripts, so the blacklist needs to check them all.
556 public static function splitExtensions( $filename ) {
557 $bits = explode( '.', $filename );
558 $basename = array_shift( $bits );
559 return array( $basename, $bits );
563 * Perform case-insensitive match against a list of file extensions.
564 * Returns true if the extension is in the list.
570 public static function checkFileExtension( $ext, $list ) {
571 return in_array( strtolower( $ext ), $list );
575 * Perform case-insensitive match against a list of file extensions.
576 * Returns true if any of the extensions are in the list.
582 public static function checkFileExtensionList( $ext, $list ) {
583 foreach( $ext as $e ) {
584 if( in_array( strtolower( $e ), $list ) ) {
592 * Checks if the mime type of the uploaded file matches the file extension.
594 * @param string $mime the mime type of the uploaded file
595 * @param string $extension The filename extension that the file is to be served with
598 public static function verifyExtension( $mime, $extension ) {
599 $magic = MimeMagic
::singleton();
601 if ( !$mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
602 if ( !$magic->isRecognizableExtension( $extension ) ) {
603 wfDebug( __METHOD__
. ": passing file with unknown detected mime type; " .
604 "unrecognized extension '$extension', can't verify\n" );
607 wfDebug( __METHOD__
. ": rejecting file with unknown detected mime type; ".
608 "recognized extension '$extension', so probably invalid file\n" );
612 $match = $magic->isMatchingExtension( $extension, $mime );
614 if ( $match === NULL ) {
615 wfDebug( __METHOD__
. ": no file extension known for mime type $mime, passing file\n" );
617 } elseif( $match === true ) {
618 wfDebug( __METHOD__
. ": mime type $mime matches extension $extension, passing file\n" );
620 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
624 wfDebug( __METHOD__
. ": mime type $mime mismatches file extension $extension, rejecting file\n" );
630 * Heuristic for detecting files that *could* contain JavaScript instructions or
631 * things that may look like HTML to a browser and are thus
632 * potentially harmful. The present implementation will produce false positives in some situations.
634 * @param string $file Pathname to the temporary upload file
635 * @param string $mime The mime type of the file
636 * @param string $extension The extension of the file
637 * @return bool true if the file contains something looking like embedded scripts
639 public static function detectScript( $file, $mime, $extension ) {
640 global $wgAllowTitlesInSVG;
642 #ugly hack: for text files, always look at the entire file.
643 #For binary field, just check the first K.
645 if( strpos( $mime,'text/' ) === 0 )
646 $chunk = file_get_contents( $file );
648 $fp = fopen( $file, 'rb' );
649 $chunk = fread( $fp, 1024 );
653 $chunk = strtolower( $chunk );
658 #decode from UTF-16 if needed (could be used for obfuscation).
659 if( substr( $chunk, 0, 2 ) == "\xfe\xff" )
661 elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" )
667 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
669 $chunk = trim( $chunk );
671 #FIXME: convert from UTF-16 if necessarry!
672 wfDebug( __METHOD__
. ": checking for embedded scripts and HTML stuff\n" );
674 #check for HTML doctype
675 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) )
679 * Internet Explorer for Windows performs some really stupid file type
680 * autodetection which can cause it to interpret valid image files as HTML
681 * and potentially execute JavaScript, creating a cross-site scripting
684 * Apple's Safari browser also performs some unsafe file type autodetection
685 * which can cause legitimate files to be interpreted as HTML if the
686 * web server is not correctly configured to send the right content-type
687 * (or if you're really uploading plain text and octet streams!)
689 * Returns true if IE is likely to mistake the given file for HTML.
690 * Also returns true if Safari would mistake the given file for HTML
691 * when served with a generic content-type.
697 '<html', #also in safari
700 '<script', #also in safari
704 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
708 foreach( $tags as $tag ) {
709 if( false !== strpos( $chunk, $tag ) ) {
715 * look for JavaScript
718 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
719 $chunk = Sanitizer
::decodeCharReferences( $chunk );
721 #look for script-types
722 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) )
725 #look for html-style script-urls
726 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) )
729 #look for css-style script-urls
730 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) )
733 wfDebug( __METHOD__
. ": no scripts found\n" );
737 protected function detectScriptInSvg( $filename ) {
738 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
739 return $check->filterMatch
;
743 * @todo Replace this with a whitelist filter!
745 public function checkSvgScriptCallback( $element, $attribs ) {
746 $stripped = $this->stripXmlNamespace( $element );
748 if( $stripped == 'script' ) {
749 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
753 foreach( $attribs as $attrib => $value ) {
754 $stripped = $this->stripXmlNamespace( $attrib );
755 if( substr( $stripped, 0, 2 ) == 'on' ) {
756 wfDebug( __METHOD__
. ": Found script attribute '$attrib'='value' in uploaded file.\n" );
759 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
760 wfDebug( __METHOD__
. ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
766 private function stripXmlNamespace( $name ) {
767 // 'http://www.w3.org/2000/svg:script' -> 'script'
768 $parts = explode( ':', strtolower( $name ) );
769 return array_pop( $parts );
773 * Generic wrapper function for a virus scanner program.
774 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
775 * $wgAntivirusRequired may be used to deny upload if the scan fails.
777 * @param string $file Pathname to the temporary upload file
778 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
779 * or a string containing feedback from the virus scanner if a virus was found.
780 * If textual feedback is missing but a virus was found, this function returns true.
782 public static function detectVirus( $file ) {
783 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
785 if ( !$wgAntivirus ) {
786 wfDebug( __METHOD__
. ": virus scanner disabled\n" );
790 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
791 wfDebug( __METHOD__
. ": unknown virus scanner: $wgAntivirus\n" );
792 $wgOut->wrapWikiMsg( '<div class="error">$1</div>', array( 'virus-badscanner', $wgAntivirus ) );
793 return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
796 # look up scanner configuration
797 $command = $wgAntivirusSetup[$wgAntivirus]["command"];
798 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]["codemap"];
799 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]["messagepattern"] ) ?
800 $wgAntivirusSetup[$wgAntivirus]["messagepattern"] : null;
802 if ( strpos( $command,"%f" ) === false ) {
803 # simple pattern: append file to scan
804 $command .= " " . wfEscapeShellArg( $file );
806 # complex pattern: replace "%f" with file to scan
807 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
810 wfDebug( __METHOD__
. ": running virus scan: $command \n" );
812 # execute virus scanner
815 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
816 # that does not seem to be worth the pain.
817 # Ask me (Duesentrieb) about it if it's ever needed.
819 if ( wfIsWindows() ) {
820 exec( "$command", $output, $exitCode );
822 exec( "$command 2>&1", $output, $exitCode );
825 # map exit code to AV_xxx constants.
826 $mappedCode = $exitCode;
827 if ( $exitCodeMap ) {
828 if ( isset( $exitCodeMap[$exitCode] ) ) {
829 $mappedCode = $exitCodeMap[$exitCode];
830 } elseif ( isset( $exitCodeMap["*"] ) ) {
831 $mappedCode = $exitCodeMap["*"];
835 if ( $mappedCode === AV_SCAN_FAILED
) {
836 # scan failed (code was mapped to false by $exitCodeMap)
837 wfDebug( __METHOD__
. ": failed to scan $file (code $exitCode).\n" );
839 if ( $wgAntivirusRequired ) {
840 return wfMsg( 'virus-scanfailed', array( $exitCode ) );
844 } else if ( $mappedCode === AV_SCAN_ABORTED
) {
845 # scan failed because filetype is unknown (probably imune)
846 wfDebug( __METHOD__
. ": unsupported file type $file (code $exitCode).\n" );
848 } else if ( $mappedCode === AV_NO_VIRUS
) {
850 wfDebug( __METHOD__
. ": file passed virus scan.\n" );
853 $output = join( "\n", $output );
854 $output = trim( $output );
857 $output = true; #if there's no output, return true
858 } elseif ( $msgPattern ) {
860 if ( preg_match( $msgPattern, $output, $groups ) ) {
862 $output = $groups[1];
867 wfDebug( __METHOD__
. ": FOUND VIRUS! scanner feedback: $output \n" );
873 * Check if the temporary file is MacBinary-encoded, as some uploads
874 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
875 * If so, the data fork will be extracted to a second temporary file,
876 * which will then be checked for validity and either kept or discarded.
880 private function checkMacBinary() {
881 $macbin = new MacBinary( $this->mTempPath
);
882 if( $macbin->isValid() ) {
883 $dataFile = tempnam( wfTempDir(), 'WikiMacBinary' );
884 $dataHandle = fopen( $dataFile, 'wb' );
886 wfDebug( __METHOD__
. ": Extracting MacBinary data fork to $dataFile\n" );
887 $macbin->extractData( $dataHandle );
889 $this->mTempPath
= $dataFile;
890 $this->mFileSize
= $macbin->dataForkLength();
892 // We'll have to manually remove the new file if it's not kept.
893 $this->mRemoveTempFile
= true;
899 * Check if there's an overwrite conflict and, if so, if restrictions
900 * forbid this user from performing the upload.
902 * @return mixed true on success, error string on failure
905 private function checkOverwrite() {
907 // First check whether the local file can be overwritten
908 $file = $this->getLocalFile();
909 if( $file->exists() ) {
910 if( !self
::userCanReUpload( $wgUser, $file ) )
911 return 'fileexists-forbidden';
916 /* Check shared conflicts: if the local file does not exist, but
917 * wfFindFile finds a file, it exists in a shared repository.
919 $file = wfFindFile( $this->getTitle() );
920 if ( $file && !$wgUser->isAllowed( 'reupload-shared' ) )
921 return 'fileexists-shared-forbidden';
927 * Check if a user is the last uploader
930 * @param string $img, image name
933 public static function userCanReUpload( User
$user, $img ) {
934 if( $user->isAllowed( 'reupload' ) )
935 return true; // non-conditional
936 if( !$user->isAllowed( 'reupload-own' ) )
938 if( is_string( $img ) )
939 $img = wfLocalFile( $img );
940 if ( !( $img instanceof LocalFile
) )
943 return $user->getId() == $img->getUser( 'id' );
947 * Helper function that does various existence checks for a file.
948 * The following checks are performed:
950 * - Article with the same name as the file exists
951 * - File exists with normalized extension
952 * - The file looks like a thumbnail and the original exists
954 * @param File $file The file to check
955 * @return mixed False if the file does not exists, else an array
957 public static function getExistsWarning( $file ) {
958 if( $file->exists() )
959 return array( 'warning' => 'exists', 'file' => $file );
961 if( $file->getTitle()->getArticleID() )
962 return array( 'warning' => 'page-exists', 'file' => $file );
964 if ( $file->wasDeleted() && !$file->exists() )
965 return array( 'warning' => 'was-deleted', 'file' => $file );
967 if( strpos( $file->getName(), '.' ) == false ) {
968 $partname = $file->getName();
971 $n = strrpos( $file->getName(), '.' );
972 $extension = substr( $file->getName(), $n +
1 );
973 $partname = substr( $file->getName(), 0, $n );
975 $normalizedExtension = File
::normalizeExtension( $extension );
977 if ( $normalizedExtension != $extension ) {
978 // We're not using the normalized form of the extension.
979 // Normal form is lowercase, using most common of alternate
980 // extensions (eg 'jpg' rather than 'JPEG').
982 // Check for another file using the normalized form...
983 $nt_lc = Title
::makeTitle( NS_FILE
, "{$partname}.{$normalizedExtension}" );
984 $file_lc = wfLocalFile( $nt_lc );
986 if( $file_lc->exists() )
987 return array( 'warning' => 'exists-normalized', 'file' => $file, 'normalizedFile' => $file_lc );
990 if ( self
::isThumbName( $file->getName() ) ) {
991 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
992 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $extension, NS_FILE
);
993 $file_thb = wfLocalFile( $nt_thb );
994 if( $file_thb->exists() )
995 return array( 'warning' => 'thumb', 'file' => $file, 'thumbFile' => $file_thb );
997 // File does not exist, but we just don't like the name
998 return array( 'warning' => 'thumb-name', 'file' => $file, 'thumbFile' => $file_thb );
1002 foreach( self
::getFilenamePrefixBlacklist() as $prefix ) {
1003 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix )
1004 return array( 'warning' => 'bad-prefix', 'file' => $file, 'prefix' => $prefix );
1013 * Helper function that checks whether the filename looks like a thumbnail
1015 public static function isThumbName( $filename ) {
1016 $n = strrpos( $filename, '.' );
1017 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
1019 substr( $partname , 3, 3 ) == 'px-' ||
1020 substr( $partname , 2, 3 ) == 'px-'
1022 preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) );
1026 * Get a list of blacklisted filename prefixes from [[MediaWiki:filename-prefix-blacklist]]
1028 * @return array list of prefixes
1030 public static function getFilenamePrefixBlacklist() {
1031 $blacklist = array();
1032 $message = wfMsgForContent( 'filename-prefix-blacklist' );
1033 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) ||
$message == '-' ) ) {
1034 $lines = explode( "\n", $message );
1035 foreach( $lines as $line ) {
1036 // Remove comment lines
1037 $comment = substr( trim( $line ), 0, 1 );
1038 if ( $comment == '#' ||
$comment == '' ) {
1041 // Remove additional comments after a prefix
1042 $comment = strpos( $line, '#' );
1043 if ( $comment > 0 ) {
1044 $line = substr( $line, 0, $comment-1 );
1046 $blacklist[] = trim( $line );