5 var $mDesiredDestName, $mDestName, $mRemoveTempFile, $mSourceType;
6 var $mTitle = false, $mTitleError = 0;
7 var $mFilteredName, $mFinalExtension;
11 const BEFORE_PROCESSING
= 1;
12 const LARGE_FILE_SERVER
= 2;
14 const MIN_LENGTH_PARTNAME
= 4;
15 const ILLEGAL_FILENAME
= 5;
16 const PROTECTED_PAGE
= 6;
17 const OVERWRITE_EXISTING_FILE
= 7;
18 const FILETYPE_MISSING
= 8;
19 const FILETYPE_BADTYPE
= 9;
20 const VERIFICATION_ERROR
= 10;
21 const UPLOAD_VERIFICATION_ERROR
= 11;
22 const UPLOAD_WARNING
= 12;
23 const INTERNAL_ERROR
= 13;
24 const MIN_LENGHT_PARTNAME
= 14;
26 const SESSION_VERSION
= 2;
29 * Returns true if uploads are enabled.
30 * Can be override by subclasses.
32 static function isEnabled() {
33 global $wgEnableUploads;
34 if ( !$wgEnableUploads )
37 # Check php's file_uploads setting
38 if( !wfIniGetBool( 'file_uploads' ) ) {
44 * Returns true if the user can use this upload module or else a string
45 * identifying the missing permission.
46 * Can be overriden by subclasses.
48 static function isAllowed( $user ) {
49 if( !$user->isAllowed( 'upload' ) )
54 // Upload handlers. Should probably just be a global
55 static $uploadHandlers = array( 'Stash', 'File', 'Url' );
57 * Create a form of UploadBase depending on wpSourceType and initializes it
59 static function createFromRequest( &$request, $type = null ) {
60 $type = $type ?
$type : $request->getVal( 'wpSourceType' );
65 $type = ucfirst($type);
66 $className = 'UploadFrom'.$type;
67 wfDebug( __METHOD__
.": class name: $className");
68 if( !in_array( $type, self
::$uploadHandlers ) )
71 if( !call_user_func( array( $className, 'isEnabled' ) ) )
75 if( !call_user_func( array( $className, 'isValidRequest' ), $request ) )
78 $handler = new $className;
80 $handler->initializeFromRequest( $request );
84 * Check whether a request if valid for this handler
86 static function isValidRequest( $request ) {
90 function __construct() {}
93 * Do the real variable initialization
95 function initialize( $name, $tempPath, $fileSize, $removeTempFile = false ) {
96 $this->mDesiredDestName
= $name;
97 $this->mTempPath
= $tempPath;
98 $this->mFileSize
= $fileSize;
99 $this->mRemoveTempFile
= $removeTempFile;
103 * Fetch the file. Usually a no-op
105 function fetchFile() {
106 return Status
::newGood();
108 //return the file size
109 function isEmptyFile(){
110 return empty( $this->mFileSize
);
113 * Verify whether the upload is sane.
114 * Returns self::OK or else an array with error information
116 function verifyUpload() {
118 * If there was no filename or a zero size given, give up quick.
121 if( $this->isEmptyFile() )
122 return array( 'status' => self
::EMPTY_FILE
);
124 $nt = $this->getTitle();
125 if( is_null( $nt ) ) {
126 $result = array( 'status' => $this->mTitleError
);
127 if( $this->mTitleError
== self
::ILLEGAL_FILENAME
)
128 $result['filtered'] = $this->mFilteredName
;
129 if ( $this->mTitleError
== self
::FILETYPE_BADTYPE
)
130 $result['finalExt'] = $this->mFinalExtension
;
133 $this->mLocalFile
= wfLocalFile( $nt );
134 $this->mDestName
= $this->mLocalFile
->getName();
137 * In some cases we may forbid overwriting of existing files.
139 $overwrite = $this->checkOverwrite();
140 if( $overwrite !== true )
141 return array( 'status' => self
::OVERWRITE_EXISTING_FILE
, 'overwrite' => $overwrite );
144 * Look at the contents of the file; if we can recognize the
145 * type but it's corrupt or data of the wrong type, we should
146 * probably not accept it.
148 $verification = $this->verifyFile( $this->mTempPath
);
150 if( $verification !== true ) {
151 if( !is_array( $verification ) )
152 $verification = array( $verification );
153 $verification['status'] = self
::VERIFICATION_ERROR
;
154 return $verification;
158 if( !wfRunHooks( 'UploadVerification',
159 array( $this->mDestName
, $this->mTempPath
, &$error ) ) ) {
160 return array( 'status' => self
::UPLOAD_VERIFICATION_ERROR
, 'error' => $error );
167 * Verifies that it's ok to include the uploaded file
169 * this function seems to intermixes tmpfile and $this->mTempPath .. no idea why this is
171 * @param string $tmpfile the full path of the temporary file to verify
172 * @return mixed true of the file is verified, a string or array otherwise.
174 protected function verifyFile( $tmpfile ) {
175 $this->mFileProps
= File
::getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
176 $this->checkMacBinary( );
178 #magically determine mime type
179 $magic = MimeMagic
::singleton();
180 $mime = $magic->guessMimeType( $tmpfile, false );
182 #check mime type, if desired
183 global $wgVerifyMimeType;
184 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist) ) {
185 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) )
186 return array( 'filetype-badmime', $mime );
189 $fp = fopen( $tmpfile, 'rb' );
190 $chunk = fread( $fp, 256 );
192 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension
);
193 $ieTypes = $magic->getIEMimeTypes( $tmpfile, $chunk, $extMime );
194 foreach ( $ieTypes as $ieType ) {
195 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
196 return array( 'filetype-bad-ie-mime', $ieType );
202 #check for htmlish code and javascript
203 if( $this->detectScript ( $tmpfile, $mime, $this->mFinalExtension
) ) {
204 return 'uploadscripted';
206 if( $this->mFinalExtension
== 'svg' ||
$mime == 'image/svg+xml' ) {
207 if( $this->detectScriptInSvg( $tmpfile ) ) {
208 return 'uploadscripted';
213 * Scan the uploaded file for viruses
215 $virus = $this->detectVirus($tmpfile);
217 return array( 'uploadvirus', $virus );
219 wfDebug( __METHOD__
.": all clear; passing.\n" );
224 * Check whether the user can edit, upload and create the image
226 function verifyPermissions( $user ) {
228 * If the image is protected, non-sysop users won't be able
229 * to modify it by uploading a new revision.
231 $nt = $this->getTitle();
234 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
235 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
236 $permErrorsCreate = ( $nt->exists() ?
array() : $nt->getUserPermissionsErrors( 'create', $user ) );
237 if( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
238 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
239 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
246 * Check for non fatal problems with the file
248 function checkWarnings() {
251 $filename = $this->mLocalFile
->getName();
252 $n = strrpos( $filename, '.' );
253 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
256 * Check whether the resulting filename is different from the desired one,
257 * but ignore things like ucfirst() and spaces/underscore things
259 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName
);
260 global $wgCapitalLinks, $wgContLang;
261 if ( $wgCapitalLinks ) {
262 $comparableName = $wgContLang->ucfirst( $comparableName );
264 if( $this->mDesiredDestName
!= $filename && $comparableName != $filename )
265 $warning['badfilename'] = $filename;
267 // Check whether the file extension is on the unwanted list
268 global $wgCheckFileExtensions, $wgFileExtensions;
269 if ( $wgCheckFileExtensions ) {
270 if ( !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) )
271 $warning['filetype-unwanted-type'] = $this->mFinalExtension
;
274 global $wgUploadSizeWarning;
275 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) )
276 $warning['large-file'] = $wgUploadSizeWarning;
278 if ( $this->mFileSize
== 0 )
279 $warning['emptyfile'] = true;
282 $exists = self
::getExistsWarning( $this->mLocalFile
);
283 if( $exists !== false )
284 $warning['exists'] = $exists;
286 // Check whether this may be a thumbnail
287 if( $exists !== false && $exists[0] != 'thumb'
288 && self
::isThumbName( $this->mLocalFile
->getName() ) ){
290 $nt = $this->getTitle();
291 $warning['file-thumbnail-no'] = substr( $filename , 0,
292 strpos( $nt->getText() , '-' ) +
1 );
295 // Check dupes against existing files
296 $hash = File
::sha1Base36( $this->mTempPath
);
297 $dupes = RepoGroup
::singleton()->findBySha1( $hash );
298 $title = $this->getTitle();
299 // Remove all matches against self
300 foreach ( $dupes as $key => $dupe ) {
301 if( $title->equals( $dupe->getTitle() ) )
302 unset( $dupes[$key] );
305 $warning['duplicate'] = $dupes;
307 // Check dupes against archives
308 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
309 if ( $archivedImage->getID() > 0 )
310 $warning['duplicate-archive'] = $archivedImage->getName();
312 $filenamePrefixBlacklist = self
::getFilenamePrefixBlacklist();
313 foreach( $filenamePrefixBlacklist as $prefix ) {
314 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
315 $warning['filename-bad-prefix'] = $prefix;
320 # If the file existed before and was deleted, warn the user of this
321 # Don't bother doing so if the file exists now, however
322 if( $this->mLocalFile
->wasDeleted() && !$this->mLocalFile
->exists() )
323 $warning['filewasdeleted'] = $this->mLocalFile
->getTitle();
329 * Really perform the upload.
331 function performUpload( $comment, $pageText, $watch, $user ) {
332 wfDebug("\n\n\performUpload: sum:" . $comment . ' c: ' . $pageText . ' w:' .$watch);
333 $status = $this->mLocalFile
->upload( $this->mTempPath
, $comment, $pageText,
334 File
::DELETE_SOURCE
, $this->mFileProps
, false, $user );
336 if( $status->isGood() && $watch )
337 $user->addWatch( $this->mLocalFile
->getTitle() );
339 if( $status->isGood() )
340 wfRunHooks( 'UploadComplete', array( &$this ) );
346 * Returns a title or null
348 function getTitle() {
349 if ( $this->mTitle
!== false )
350 return $this->mTitle
;
353 * Chop off any directories in the given filename. Then
354 * filter out illegal characters, and try to make a legible name
355 * out of it. We'll strip some silently that Title would die on.
358 $basename = $this->mDesiredDestName
;
360 $this->mFilteredName
= wfStripIllegalFilenameChars( $basename );
361 /* Normalize to title form before we do any further processing */
362 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
363 if( is_null( $nt ) ) {
364 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
365 return $this->mTitle
= null;
367 $this->mFilteredName
= $nt->getDBkey();
370 * We'll want to blacklist against *any* 'extension', and use
371 * only the final one for the whitelist.
373 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName
);
375 if( count( $ext ) ) {
376 $this->mFinalExtension
= trim( $ext[count( $ext ) - 1] );
378 $this->mFinalExtension
= '';
381 /* Don't allow users to override the blacklist (check file extension) */
382 global $wgCheckFileExtensions, $wgStrictFileExtensions;
383 global $wgFileExtensions, $wgFileBlacklist;
384 if ( $this->mFinalExtension
== '' ) {
385 $this->mTitleError
= self
::FILETYPE_MISSING
;
386 return $this->mTitle
= null;
387 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
388 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
389 !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) ) ) {
390 $this->mTitleError
= self
::FILETYPE_BADTYPE
;
391 return $this->mTitle
= null;
394 # If there was more than one "extension", reassemble the base
395 # filename to prevent bogus complaints about length
396 if( count( $ext ) > 1 ) {
397 for( $i = 0; $i < count( $ext ) - 1; $i++
)
398 $partname .= '.' . $ext[$i];
401 if( strlen( $partname ) < 1 ) {
402 $this->mTitleError
= self
::MIN_LENGTH_PARTNAME
;
403 return $this->mTitle
= null;
406 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
407 if( is_null( $nt ) ) {
408 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
409 return $this->mTitle
= null;
411 return $this->mTitle
= $nt;
414 function getLocalFile() {
415 if( is_null( $this->mLocalFile
) ) {
416 $nt = $this->getTitle();
417 $this->mLocalFile
= is_null( $nt ) ?
null : wfLocalFile( $nt );
419 return $this->mLocalFile
;
423 * Stash a file in a temporary directory for later processing
424 * after the user has confirmed it.
426 * If the user doesn't explicitly cancel or accept, these files
427 * can accumulate in the temp directory.
429 * @param string $saveName - the destination filename
430 * @param string $tempName - the source temporary file to save
431 * @return string - full path the stashed file, or false on failure
434 function saveTempUploadedFile( $saveName, $tempName ) {
435 $repo = RepoGroup
::singleton()->getLocalRepo();
436 $status = $repo->storeTemp( $saveName, $tempName );
439 /* append to a stashed file */
440 function appendToUploadFile($srcPath, $toAppendPath ){
441 $repo = RepoGroup
::singleton()->getLocalRepo();
442 $status = $repo->append($srcPath, $toAppendPath);
447 * Stash a file in a temporary directory for later processing,
448 * and save the necessary descriptive info into the session.
449 * Returns a key value which will be passed through a form
450 * to pick up the path info on a later invocation.
455 function stashSession() {
456 $status = $this->saveTempUploadedFile( $this->mDestName
, $this->mTempPath
);
457 if( !$status->isOK() ) {
458 # Couldn't save the file.
461 $mTempPath = $status->value
;
462 session_start();//start up the session (might have been previously closed to prevent php session locking)
463 $key = $this->getSessionKey ();
464 $_SESSION['wsUploadData'][$key] = array(
465 'mTempPath' => $mTempPath,
466 'mFileSize' => $this->mFileSize
,
467 'mSrcName' => $this->mSrcName
,
468 'mFileProps' => $this->mFileProps
,
469 'version' => self
::SESSION_VERSION
,
471 session_write_close();
474 //pull session Key gen from stash in cases where we want to start an upload without much information
475 function getSessionKey(){
476 $key = mt_rand( 0, 0x7fffffff );
477 $_SESSION['wsUploadData'][$key] = array();
482 * Remove a temporarily kept file stashed by saveTempUploadedFile().
485 function unsaveUploadedFile() {
486 $repo = RepoGroup
::singleton()->getLocalRepo();
487 $success = $repo->freeTemp( $this->mTempPath
);
492 * If we've modified the upload file we need to manually remove it
493 * on exit to clean up.
496 function cleanupTempFile() {
497 if ( $this->mRemoveTempFile
&& $this->mTempPath
&& file_exists( $this->mTempPath
) ) {
498 wfDebug( __METHOD__
.": Removing temporary file {$this->mTempPath}\n" );
499 unlink( $this->mTempPath
);
503 function getTempPath() {
504 return $this->mTempPath
;
509 * Split a file into a base name and all dot-delimited 'extensions'
510 * on the end. Some web server configurations will fall back to
511 * earlier pseudo-'extensions' to determine type and execute
512 * scripts, so the blacklist needs to check them all.
516 public static function splitExtensions( $filename ) {
517 $bits = explode( '.', $filename );
518 $basename = array_shift( $bits );
519 return array( $basename, $bits );
523 * Perform case-insensitive match against a list of file extensions.
524 * Returns true if the extension is in the list.
530 public static function checkFileExtension( $ext, $list ) {
531 return in_array( strtolower( $ext ), $list );
535 * Perform case-insensitive match against a list of file extensions.
536 * Returns true if any of the extensions are in the list.
542 public static function checkFileExtensionList( $ext, $list ) {
543 foreach( $ext as $e ) {
544 if( in_array( strtolower( $e ), $list ) ) {
553 * Checks if the mime type of the uploaded file matches the file extension.
555 * @param string $mime the mime type of the uploaded file
556 * @param string $extension The filename extension that the file is to be served with
559 public static function verifyExtension( $mime, $extension ) {
560 $magic = MimeMagic
::singleton();
562 if ( ! $mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
563 if ( ! $magic->isRecognizableExtension( $extension ) ) {
564 wfDebug( __METHOD__
.": passing file with unknown detected mime type; " .
565 "unrecognized extension '$extension', can't verify\n" );
568 wfDebug( __METHOD__
.": rejecting file with unknown detected mime type; ".
569 "recognized extension '$extension', so probably invalid file\n" );
573 $match= $magic->isMatchingExtension($extension,$mime);
576 wfDebug( __METHOD__
.": no file extension known for mime type $mime, passing file\n" );
578 } elseif ($match===true) {
579 wfDebug( __METHOD__
.": mime type $mime matches extension $extension, passing file\n" );
581 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
585 wfDebug( __METHOD__
.": mime type $mime mismatches file extension $extension, rejecting file\n" );
591 * Heuristic for detecting files that *could* contain JavaScript instructions or
592 * things that may look like HTML to a browser and are thus
593 * potentially harmful. The present implementation will produce false positives in some situations.
595 * @param string $file Pathname to the temporary upload file
596 * @param string $mime The mime type of the file
597 * @param string $extension The extension of the file
598 * @return bool true if the file contains something looking like embedded scripts
600 function detectScript($file, $mime, $extension) {
601 global $wgAllowTitlesInSVG;
603 #ugly hack: for text files, always look at the entire file.
604 #For binary field, just check the first K.
606 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
608 $fp = fopen( $file, 'rb' );
609 $chunk = fread( $fp, 1024 );
613 $chunk= strtolower( $chunk );
615 if (!$chunk) return false;
617 #decode from UTF-16 if needed (could be used for obfuscation).
618 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
619 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
622 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
624 $chunk= trim($chunk);
626 #FIXME: convert from UTF-16 if necessarry!
628 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
630 #check for HTML doctype
631 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
634 * Internet Explorer for Windows performs some really stupid file type
635 * autodetection which can cause it to interpret valid image files as HTML
636 * and potentially execute JavaScript, creating a cross-site scripting
639 * Apple's Safari browser also performs some unsafe file type autodetection
640 * which can cause legitimate files to be interpreted as HTML if the
641 * web server is not correctly configured to send the right content-type
642 * (or if you're really uploading plain text and octet streams!)
644 * Returns true if IE is likely to mistake the given file for HTML.
645 * Also returns true if Safari would mistake the given file for HTML
646 * when served with a generic content-type.
653 '<html', #also in safari
656 '<script', #also in safari
659 if( ! $wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
663 foreach( $tags as $tag ) {
664 if( false !== strpos( $chunk, $tag ) ) {
670 * look for javascript
673 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
674 $chunk = Sanitizer
::decodeCharReferences( $chunk );
676 #look for script-types
677 if (preg_match('!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim',$chunk)) return true;
679 #look for html-style script-urls
680 if (preg_match('!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
682 #look for css-style script-urls
683 if (preg_match('!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
685 wfDebug("SpecialUpload::detectScript: no scripts found\n");
689 function detectScriptInSvg( $filename ) {
690 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
691 return $check->filterMatch
;
695 * @todo Replace this with a whitelist filter!
697 function checkSvgScriptCallback( $element, $attribs ) {
698 $stripped = $this->stripXmlNamespace( $element );
700 if( $stripped == 'script' ) {
701 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
705 foreach( $attribs as $attrib => $value ) {
706 $stripped = $this->stripXmlNamespace( $attrib );
707 if( substr( $stripped, 0, 2 ) == 'on' ) {
708 wfDebug( __METHOD__
. ": Found script attribute '$attrib'='value' in uploaded file.\n" );
711 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
712 wfDebug( __METHOD__
. ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
718 private function stripXmlNamespace( $name ) {
719 // 'http://www.w3.org/2000/svg:script' -> 'script'
720 $parts = explode( ':', strtolower( $name ) );
721 return array_pop( $parts );
727 * Generic wrapper function for a virus scanner program.
728 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
729 * $wgAntivirusRequired may be used to deny upload if the scan fails.
731 * @param string $file Pathname to the temporary upload file
732 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
733 * or a string containing feedback from the virus scanner if a virus was found.
734 * If textual feedback is missing but a virus was found, this function returns true.
736 function detectVirus($file) {
737 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
739 if ( !$wgAntivirus ) {
740 wfDebug( __METHOD__
.": virus scanner disabled\n");
744 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
745 wfDebug( __METHOD__
.": unknown virus scanner: $wgAntivirus\n" );
746 $wgOut->wrapWikiMsg( '<div class="error">$1</div>', array( 'virus-badscanner', $wgAntivirus ) );
747 return wfMsg('virus-unknownscanner') . " $wgAntivirus";
750 # look up scanner configuration
751 $command = $wgAntivirusSetup[$wgAntivirus]["command"];
752 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]["codemap"];
753 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]["messagepattern"] ) ?
754 $wgAntivirusSetup[$wgAntivirus]["messagepattern"] : null;
756 if ( strpos( $command,"%f" ) === false ) {
757 # simple pattern: append file to scan
758 $command .= " " . wfEscapeShellArg( $file );
760 # complex pattern: replace "%f" with file to scan
761 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
764 wfDebug( __METHOD__
.": running virus scan: $command \n" );
766 # execute virus scanner
769 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
770 # that does not seem to be worth the pain.
771 # Ask me (Duesentrieb) about it if it's ever needed.
773 if ( wfIsWindows() ) {
774 exec( "$command", $output, $exitCode );
776 exec( "$command 2>&1", $output, $exitCode );
779 # map exit code to AV_xxx constants.
780 $mappedCode = $exitCode;
781 if ( $exitCodeMap ) {
782 if ( isset( $exitCodeMap[$exitCode] ) ) {
783 $mappedCode = $exitCodeMap[$exitCode];
784 } elseif ( isset( $exitCodeMap["*"] ) ) {
785 $mappedCode = $exitCodeMap["*"];
789 if ( $mappedCode === AV_SCAN_FAILED
) {
790 # scan failed (code was mapped to false by $exitCodeMap)
791 wfDebug( __METHOD__
.": failed to scan $file (code $exitCode).\n" );
793 if ( $wgAntivirusRequired ) {
794 return wfMsg('virus-scanfailed', array( $exitCode ) );
798 } else if ( $mappedCode === AV_SCAN_ABORTED
) {
799 # scan failed because filetype is unknown (probably imune)
800 wfDebug( __METHOD__
.": unsupported file type $file (code $exitCode).\n" );
802 } else if ( $mappedCode === AV_NO_VIRUS
) {
804 wfDebug( __METHOD__
.": file passed virus scan.\n" );
807 $output = join( "\n", $output );
808 $output = trim( $output );
811 $output = true; #if there's no output, return true
812 } elseif ( $msgPattern ) {
814 if ( preg_match( $msgPattern, $output, $groups ) ) {
816 $output = $groups[1];
821 wfDebug( __METHOD__
.": FOUND VIRUS! scanner feedback: $output \n" );
827 * Check if the temporary file is MacBinary-encoded, as some uploads
828 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
829 * If so, the data fork will be extracted to a second temporary file,
830 * which will then be checked for validity and either kept or discarded.
834 function checkMacBinary() {
835 $macbin = new MacBinary( $this->mTempPath
);
836 if( $macbin->isValid() ) {
837 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
838 $dataHandle = fopen( $dataFile, 'wb' );
840 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
841 $macbin->extractData( $dataHandle );
843 $this->mTempPath
= $dataFile;
844 $this->mFileSize
= $macbin->dataForkLength();
846 // We'll have to manually remove the new file if it's not kept.
847 $this->mRemoveTempFile
= true;
853 * Check if there's an overwrite conflict and, if so, if restrictions
854 * forbid this user from performing the upload.
856 * @return mixed true on success, WikiError on failure
859 function checkOverwrite() {
861 // First check whether the local file can be overwritten
862 if( $this->mLocalFile
->exists() )
863 if( !self
::userCanReUpload( $wgUser, $this->mLocalFile
) )
864 return 'fileexists-forbidden';
866 // Check shared conflicts
867 $file = wfFindFile( $this->mLocalFile
->getName() );
868 if ( $file && ( !$wgUser->isAllowed( 'reupload' ) ||
869 !$wgUser->isAllowed( 'reupload-shared' ) ) )
870 return 'fileexists-shared-forbidden';
876 * Check if a user is the last uploader
879 * @param string $img, image name
882 public static function userCanReUpload( User
$user, $img ) {
883 if( $user->isAllowed( 'reupload' ) )
884 return true; // non-conditional
885 if( !$user->isAllowed( 'reupload-own' ) )
887 if( is_string( $img ) )
888 $img = wfLocalFile( $img );
889 if ( !( $img instanceof LocalFile
) )
892 return $user->getId() == $img->getUser( 'id' );
895 public static function getExistsWarning( $file ) {
896 if( $file->exists() )
897 return array( 'exists', $file );
899 if( $file->getTitle()->getArticleID() )
900 return array( 'page-exists', $file );
902 if( strpos( $file->getName(), '.' ) == false ) {
903 $partname = $file->getName();
906 $n = strrpos( $file->getName(), '.' );
907 $rawExtension = substr( $file->getName(), $n +
1 );
908 $partname = substr( $file->getName(), 0, $n );
911 if ( $rawExtension != $file->getExtension() ) {
912 // We're not using the normalized form of the extension.
913 // Normal form is lowercase, using most common of alternate
914 // extensions (eg 'jpg' rather than 'JPEG').
916 // Check for another file using the normalized form...
917 $nt_lc = Title
::makeTitle( NS_FILE
, $partname . '.' . $file->getExtension() );
918 $file_lc = wfLocalFile( $nt_lc );
920 if( $file_lc->exists() )
921 return array( 'exists-normalized', $file_lc );
924 if ( self
::isThumbName( $file->getName() ) ) {
925 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
926 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $rawExtension );
927 $file_thb = wfLocalFile( $nt_thb );
928 if( $file_thb->exists() )
929 return array( 'thumb', $file_thb );
935 public static function isThumbName( $filename ) {
936 $n = strrpos( $filename, '.' );
937 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
939 substr( $partname , 3, 3 ) == 'px-' ||
940 substr( $partname , 2, 3 ) == 'px-'
942 ereg( "[0-9]{2}" , substr( $partname , 0, 2) );
946 * Get a list of blacklisted filename prefixes from [[MediaWiki:filename-prefix-blacklist]]
948 * @return array list of prefixes
950 public static function getFilenamePrefixBlacklist() {
951 $blacklist = array();
952 $message = wfMsgForContent( 'filename-prefix-blacklist' );
953 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) ||
$message == '-' ) ) {
954 $lines = explode( "\n", $message );
955 foreach( $lines as $line ) {
956 // Remove comment lines
957 $comment = substr( trim( $line ), 0, 1 );
958 if ( $comment == '#' ||
$comment == '' ) {
961 // Remove additional comments after a prefix
962 $comment = strpos( $line, '#' );
963 if ( $comment > 0 ) {
964 $line = substr( $line, 0, $comment-1 );
966 $blacklist[] = trim( $line );