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;
26 const MIN_LENGTH_PARTNAME
= 4;
27 const ILLEGAL_FILENAME
= 5;
28 const OVERWRITE_EXISTING_FILE
= 7;
29 const FILETYPE_MISSING
= 8;
30 const FILETYPE_BADTYPE
= 9;
31 const VERIFICATION_ERROR
= 10;
32 const UPLOAD_VERIFICATION_ERROR
= 11;
33 const HOOK_ABORTED
= 11;
35 const SESSION_VERSION
= 2;
38 * Returns true if uploads are enabled.
39 * Can be override by subclasses.
41 public static function isEnabled() {
42 global $wgEnableUploads;
43 if ( !$wgEnableUploads ) {
47 # Check php's file_uploads setting
48 if( !wfIniGetBool( 'file_uploads' ) ) {
55 * Returns true if the user can use this upload module or else a string
56 * identifying the missing permission.
57 * Can be overriden by subclasses.
59 public static function isAllowed( $user ) {
60 if( !$user->isAllowed( 'upload' ) ) {
66 // Upload handlers. Should probably just be a global.
67 static $uploadHandlers = array( 'Stash', 'File', 'Url' );
70 * Create a form of UploadBase depending on wpSourceType and initializes it
72 public static function createFromRequest( &$request, $type = null ) {
73 $type = $type ?
$type : $request->getVal( 'wpSourceType', 'File' );
79 // Get the upload class
80 $type = ucfirst( $type );
82 // Give hooks the chance to handle this request
84 wfRunHooks( 'UploadCreateFromRequest', array( $type, &$className ) );
85 if ( is_null( $className ) ) {
86 $className = 'UploadFrom' . $type;
87 wfDebug( __METHOD__
. ": class name: $className\n" );
88 if( !in_array( $type, self
::$uploadHandlers ) ) {
93 // Check whether this upload class is enabled
94 if( !call_user_func( array( $className, 'isEnabled' ) ) ) {
98 // Check whether the request is valid
99 if( !call_user_func( array( $className, 'isValidRequest' ), $request ) ) {
103 $handler = new $className;
105 $handler->initializeFromRequest( $request );
110 * Check whether a request if valid for this handler
112 public static function isValidRequest( $request ) {
116 public function __construct() {}
119 * Initialize the path information
120 * @param $name string the desired destination name
121 * @param $tempPath string the temporary path
122 * @param $fileSize int the file size
123 * @param $removeTempFile bool (false) remove the temporary file?
126 public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
127 $this->mDesiredDestName
= $name;
128 $this->mTempPath
= $tempPath;
129 $this->mFileSize
= $fileSize;
130 $this->mRemoveTempFile
= $removeTempFile;
134 * Initialize from a WebRequest. Override this in a subclass.
136 public abstract function initializeFromRequest( &$request );
139 * Fetch the file. Usually a no-op
141 public function fetchFile() {
142 return Status
::newGood();
146 * Return the file size
148 public function isEmptyFile() {
149 return empty( $this->mFileSize
);
153 * @param $srcPath String: the source path
154 * @return the real path if it was a virtual URL
156 function getRealPath( $srcPath ) {
157 $repo = RepoGroup
::singleton()->getLocalRepo();
158 if ( $repo->isVirtualUrl( $srcPath ) ) {
159 return $repo->resolveVirtualUrl( $srcPath );
165 * Verify whether the upload is sane.
166 * Returns self::OK or else an array with error information
168 public function verifyUpload() {
170 * If there was no filename or a zero size given, give up quick.
172 if( $this->isEmptyFile() ) {
173 return array( 'status' => self
::EMPTY_FILE
);
177 * Look at the contents of the file; if we can recognize the
178 * type but it's corrupt or data of the wrong type, we should
179 * probably not accept it.
181 $verification = $this->verifyFile();
182 if( $verification !== true ) {
183 if( !is_array( $verification ) ) {
184 $verification = array( $verification );
187 'status' => self
::VERIFICATION_ERROR
,
188 'details' => $verification
192 $nt = $this->getTitle();
193 if( is_null( $nt ) ) {
194 $result = array( 'status' => $this->mTitleError
);
195 if( $this->mTitleError
== self
::ILLEGAL_FILENAME
) {
196 $result['filtered'] = $this->mFilteredName
;
198 if ( $this->mTitleError
== self
::FILETYPE_BADTYPE
) {
199 $result['finalExt'] = $this->mFinalExtension
;
203 $this->mDestName
= $this->getLocalFile()->getName();
206 * In some cases we may forbid overwriting of existing files.
208 $overwrite = $this->checkOverwrite();
209 if( $overwrite !== true ) {
211 'status' => self
::OVERWRITE_EXISTING_FILE
,
212 'overwrite' => $overwrite
217 if( !wfRunHooks( 'UploadVerification',
218 array( $this->mDestName
, $this->mTempPath
, &$error ) ) ) {
219 // This status needs another name...
220 return array( 'status' => self
::HOOK_ABORTED
, 'error' => $error );
223 return array( 'status' => self
::OK
);
227 * Verifies that it's ok to include the uploaded file
229 * @return mixed true of the file is verified, a string or array otherwise.
231 protected function verifyFile() {
232 $this->mFileProps
= File
::getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
233 $this->checkMacBinary();
235 # magically determine mime type
236 $magic = MimeMagic
::singleton();
237 $mime = $magic->guessMimeType( $this->mTempPath
, false );
239 # check mime type, if desired
240 global $wgVerifyMimeType;
241 if ( $wgVerifyMimeType ) {
242 wfDebug ( "\n\nmime: <$mime> extension: <{$this->mFinalExtension}>\n\n");
243 if ( !$this->verifyExtension( $mime, $this->mFinalExtension
) ) {
244 return array( 'filetype-mime-mismatch' );
247 global $wgMimeTypeBlacklist;
248 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
249 return array( 'filetype-badmime', $mime );
253 $fp = fopen( $this->mTempPath
, 'rb' );
254 $chunk = fread( $fp, 256 );
256 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension
);
257 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath
, $chunk, $extMime );
258 foreach ( $ieTypes as $ieType ) {
259 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
260 return array( 'filetype-bad-ie-mime', $ieType );
265 # check for htmlish code and javascript
266 if( self
::detectScript( $this->mTempPath
, $mime, $this->mFinalExtension
) ) {
267 return 'uploadscripted';
269 if( $this->mFinalExtension
== 'svg' ||
$mime == 'image/svg+xml' ) {
270 if( self
::detectScriptInSvg( $this->mTempPath
) ) {
271 return 'uploadscripted';
276 * Scan the uploaded file for viruses
278 $virus = $this->detectVirus( $this->mTempPath
);
280 return array( 'uploadvirus', $virus );
282 wfDebug( __METHOD__
. ": all clear; passing.\n" );
287 * Check whether the user can edit, upload and create the image.
289 * @param $user the User object to verify the permissions against
290 * @return mixed An array as returned by getUserPermissionsErrors or true
291 * in case the user has proper permissions.
293 public function verifyPermissions( $user ) {
295 * If the image is protected, non-sysop users won't be able
296 * to modify it by uploading a new revision.
298 $nt = $this->getTitle();
299 if( is_null( $nt ) ) {
302 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
303 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
304 $permErrorsCreate = ( $nt->exists() ?
array() : $nt->getUserPermissionsErrors( 'create', $user ) );
305 if( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
306 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
307 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
314 * Check for non fatal problems with the file
316 * @return Array of warnings
318 public function checkWarnings() {
321 $localFile = $this->getLocalFile();
322 $filename = $localFile->getName();
323 $n = strrpos( $filename, '.' );
324 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
327 * Check whether the resulting filename is different from the desired one,
328 * but ignore things like ucfirst() and spaces/underscore things
330 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName
);
331 $comparableName = Title
::capitalize( $comparableName, NS_FILE
);
333 if( $this->mDesiredDestName
!= $filename && $comparableName != $filename ) {
334 $warnings['badfilename'] = $filename;
337 // Check whether the file extension is on the unwanted list
338 global $wgCheckFileExtensions, $wgFileExtensions;
339 if ( $wgCheckFileExtensions ) {
340 if ( !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) ) {
341 $warnings['filetype-unwanted-type'] = $this->mFinalExtension
;
345 global $wgUploadSizeWarning;
346 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) ) {
347 $warnings['large-file'] = $wgUploadSizeWarning;
350 if ( $this->mFileSize
== 0 ) {
351 $warnings['emptyfile'] = true;
354 $exists = self
::getExistsWarning( $localFile );
355 if( $exists !== false ) {
356 $warnings['exists'] = $exists;
359 // Check dupes against existing files
360 $hash = File
::sha1Base36( $this->mTempPath
);
361 $dupes = RepoGroup
::singleton()->findBySha1( $hash );
362 $title = $this->getTitle();
363 // Remove all matches against self
364 foreach ( $dupes as $key => $dupe ) {
365 if( $title->equals( $dupe->getTitle() ) ) {
366 unset( $dupes[$key] );
370 $warnings['duplicate'] = $dupes;
373 // Check dupes against archives
374 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
375 if ( $archivedImage->getID() > 0 ) {
376 $warnings['duplicate-archive'] = $archivedImage->getName();
383 * Really perform the upload. Stores the file in the local repo, watches
384 * if necessary and runs the UploadComplete hook.
386 * @return mixed Status indicating the whether the upload succeeded.
388 public function performUpload( $comment, $pageText, $watch, $user ) {
389 wfDebug( "\n\n\performUpload: sum:" . $comment . ' c: ' . $pageText . ' w:' . $watch );
390 $status = $this->getLocalFile()->upload( $this->mTempPath
, $comment, $pageText,
391 File
::DELETE_SOURCE
, $this->mFileProps
, false, $user );
393 if( $status->isGood() && $watch ) {
394 $user->addWatch( $this->getLocalFile()->getTitle() );
397 if( $status->isGood() ) {
398 wfRunHooks( 'UploadComplete', array( &$this ) );
405 * Returns the title of the file to be uploaded. Sets mTitleError in case
406 * the name was illegal.
408 * @return Title The title of the file or null in case the name was illegal
410 public function getTitle() {
411 if ( $this->mTitle
!== false ) {
412 return $this->mTitle
;
416 * Chop off any directories in the given filename. Then
417 * filter out illegal characters, and try to make a legible name
418 * out of it. We'll strip some silently that Title would die on.
420 $basename = $this->mDesiredDestName
;
422 $this->mFilteredName
= wfStripIllegalFilenameChars( $basename );
423 /* Normalize to title form before we do any further processing */
424 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
425 if( is_null( $nt ) ) {
426 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
427 return $this->mTitle
= null;
429 $this->mFilteredName
= $nt->getDBkey();
432 * We'll want to blacklist against *any* 'extension', and use
433 * only the final one for the whitelist.
435 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName
);
437 if( count( $ext ) ) {
438 $this->mFinalExtension
= trim( $ext[count( $ext ) - 1] );
440 $this->mFinalExtension
= '';
443 /* Don't allow users to override the blacklist (check file extension) */
444 global $wgCheckFileExtensions, $wgStrictFileExtensions;
445 global $wgFileExtensions, $wgFileBlacklist;
446 if ( $this->mFinalExtension
== '' ) {
447 $this->mTitleError
= self
::FILETYPE_MISSING
;
448 return $this->mTitle
= null;
449 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
450 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
451 !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) ) ) {
452 $this->mTitleError
= self
::FILETYPE_BADTYPE
;
453 return $this->mTitle
= null;
456 # If there was more than one "extension", reassemble the base
457 # filename to prevent bogus complaints about length
458 if( count( $ext ) > 1 ) {
459 for( $i = 0; $i < count( $ext ) - 1; $i++
) {
460 $partname .= '.' . $ext[$i];
464 if( strlen( $partname ) < 1 ) {
465 $this->mTitleError
= self
::MIN_LENGTH_PARTNAME
;
466 return $this->mTitle
= null;
469 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
470 if( is_null( $nt ) ) {
471 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
472 return $this->mTitle
= null;
474 return $this->mTitle
= $nt;
478 * Return the local file and initializes if necessary.
480 public function getLocalFile() {
481 if( is_null( $this->mLocalFile
) ) {
482 $nt = $this->getTitle();
483 $this->mLocalFile
= is_null( $nt ) ?
null : wfLocalFile( $nt );
485 return $this->mLocalFile
;
489 * Stash a file in a temporary directory for later processing
490 * after the user has confirmed it.
492 * If the user doesn't explicitly cancel or accept, these files
493 * can accumulate in the temp directory.
495 * @param $saveName String: the destination filename
496 * @param $tempSrc String: the source temporary file to save
497 * @return String: full path the stashed file, or false on failure
499 protected function saveTempUploadedFile( $saveName, $tempSrc ) {
500 $repo = RepoGroup
::singleton()->getLocalRepo();
501 $status = $repo->storeTemp( $saveName, $tempSrc );
506 * Stash a file in a temporary directory for later processing,
507 * and save the necessary descriptive info into the session.
508 * Returns a key value which will be passed through a form
509 * to pick up the path info on a later invocation.
511 * @return Integer: session key
513 public function stashSession() {
514 $status = $this->saveTempUploadedFile( $this->mDestName
, $this->mTempPath
);
515 if( !$status->isOK() ) {
516 # Couldn't save the file.
520 $key = $this->getSessionKey();
521 $_SESSION['wsUploadData'][$key] = array(
522 'mTempPath' => $status->value
,
523 'mFileSize' => $this->mFileSize
,
524 'mFileProps' => $this->mFileProps
,
525 'version' => self
::SESSION_VERSION
,
531 * Generate a random session key from stash in cases where we want to start an upload without much information
533 protected function getSessionKey() {
534 $key = mt_rand( 0, 0x7fffffff );
535 $_SESSION['wsUploadData'][$key] = array();
540 * If we've modified the upload file we need to manually remove it
541 * on exit to clean up.
543 public function cleanupTempFile() {
544 if ( $this->mRemoveTempFile
&& $this->mTempPath
&& file_exists( $this->mTempPath
) ) {
545 wfDebug( __METHOD__
. ": Removing temporary file {$this->mTempPath}\n" );
546 unlink( $this->mTempPath
);
550 public function getTempPath() {
551 return $this->mTempPath
;
555 * Split a file into a base name and all dot-delimited 'extensions'
556 * on the end. Some web server configurations will fall back to
557 * earlier pseudo-'extensions' to determine type and execute
558 * scripts, so the blacklist needs to check them all.
562 public static function splitExtensions( $filename ) {
563 $bits = explode( '.', $filename );
564 $basename = array_shift( $bits );
565 return array( $basename, $bits );
569 * Perform case-insensitive match against a list of file extensions.
570 * Returns true if the extension is in the list.
576 public static function checkFileExtension( $ext, $list ) {
577 return in_array( strtolower( $ext ), $list );
581 * Perform case-insensitive match against a list of file extensions.
582 * Returns true if any of the extensions are in the list.
588 public static function checkFileExtensionList( $ext, $list ) {
589 foreach( $ext as $e ) {
590 if( in_array( strtolower( $e ), $list ) ) {
598 * Checks if the mime type of the uploaded file matches the file extension.
600 * @param $mime String: the mime type of the uploaded file
601 * @param $extension String: the filename extension that the file is to be served with
604 public static function verifyExtension( $mime, $extension ) {
605 $magic = MimeMagic
::singleton();
607 if ( !$mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
608 if ( !$magic->isRecognizableExtension( $extension ) ) {
609 wfDebug( __METHOD__
. ": passing file with unknown detected mime type; " .
610 "unrecognized extension '$extension', can't verify\n" );
613 wfDebug( __METHOD__
. ": rejecting file with unknown detected mime type; ".
614 "recognized extension '$extension', so probably invalid file\n" );
618 $match = $magic->isMatchingExtension( $extension, $mime );
620 if ( $match === null ) {
621 wfDebug( __METHOD__
. ": no file extension known for mime type $mime, passing file\n" );
623 } elseif( $match === true ) {
624 wfDebug( __METHOD__
. ": mime type $mime matches extension $extension, passing file\n" );
626 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
630 wfDebug( __METHOD__
. ": mime type $mime mismatches file extension $extension, rejecting file\n" );
636 * Heuristic for detecting files that *could* contain JavaScript instructions or
637 * things that may look like HTML to a browser and are thus
638 * potentially harmful. The present implementation will produce false
639 * positives in some situations.
641 * @param $file String: pathname to the temporary upload file
642 * @param $mime String: the mime type of the file
643 * @param $extension String: the extension of the file
644 * @return Boolean: true if the file contains something looking like embedded scripts
646 public static function detectScript( $file, $mime, $extension ) {
647 global $wgAllowTitlesInSVG;
649 # ugly hack: for text files, always look at the entire file.
650 # For binary field, just check the first K.
652 if( strpos( $mime,'text/' ) === 0 ) {
653 $chunk = file_get_contents( $file );
655 $fp = fopen( $file, 'rb' );
656 $chunk = fread( $fp, 1024 );
660 $chunk = strtolower( $chunk );
666 # decode from UTF-16 if needed (could be used for obfuscation).
667 if( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
669 } elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
676 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
679 $chunk = trim( $chunk );
681 # FIXME: convert from UTF-16 if necessarry!
682 wfDebug( __METHOD__
. ": checking for embedded scripts and HTML stuff\n" );
684 # check for HTML doctype
685 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
690 * Internet Explorer for Windows performs some really stupid file type
691 * autodetection which can cause it to interpret valid image files as HTML
692 * and potentially execute JavaScript, creating a cross-site scripting
695 * Apple's Safari browser also performs some unsafe file type autodetection
696 * which can cause legitimate files to be interpreted as HTML if the
697 * web server is not correctly configured to send the right content-type
698 * (or if you're really uploading plain text and octet streams!)
700 * Returns true if IE is likely to mistake the given file for HTML.
701 * Also returns true if Safari would mistake the given file for HTML
702 * when served with a generic content-type.
708 '<html', #also in safari
711 '<script', #also in safari
715 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
719 foreach( $tags as $tag ) {
720 if( false !== strpos( $chunk, $tag ) ) {
726 * look for JavaScript
729 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
730 $chunk = Sanitizer
::decodeCharReferences( $chunk );
732 # look for script-types
733 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
737 # look for html-style script-urls
738 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
742 # look for css-style script-urls
743 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
747 wfDebug( __METHOD__
. ": no scripts found\n" );
751 protected function detectScriptInSvg( $filename ) {
752 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
753 return $check->filterMatch
;
757 * @todo Replace this with a whitelist filter!
759 public function checkSvgScriptCallback( $element, $attribs ) {
760 $stripped = $this->stripXmlNamespace( $element );
762 if( $stripped == 'script' ) {
763 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
767 foreach( $attribs as $attrib => $value ) {
768 $stripped = $this->stripXmlNamespace( $attrib );
769 if( substr( $stripped, 0, 2 ) == 'on' ) {
770 wfDebug( __METHOD__
. ": Found script attribute '$attrib'='value' in uploaded file.\n" );
773 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
774 wfDebug( __METHOD__
. ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
780 private function stripXmlNamespace( $name ) {
781 // 'http://www.w3.org/2000/svg:script' -> 'script'
782 $parts = explode( ':', strtolower( $name ) );
783 return array_pop( $parts );
787 * Generic wrapper function for a virus scanner program.
788 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
789 * $wgAntivirusRequired may be used to deny upload if the scan fails.
791 * @param $file String: pathname to the temporary upload file
792 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
793 * or a string containing feedback from the virus scanner if a virus was found.
794 * If textual feedback is missing but a virus was found, this function returns true.
796 public static function detectVirus( $file ) {
797 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
799 if ( !$wgAntivirus ) {
800 wfDebug( __METHOD__
. ": virus scanner disabled\n" );
804 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
805 wfDebug( __METHOD__
. ": unknown virus scanner: $wgAntivirus\n" );
806 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1</div>", array( 'virus-badscanner', $wgAntivirus ) );
807 return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
810 # look up scanner configuration
811 $command = $wgAntivirusSetup[$wgAntivirus]['command'];
812 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
813 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
814 $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
816 if ( strpos( $command, "%f" ) === false ) {
817 # simple pattern: append file to scan
818 $command .= " " . wfEscapeShellArg( $file );
820 # complex pattern: replace "%f" with file to scan
821 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
824 wfDebug( __METHOD__
. ": running virus scan: $command \n" );
826 # execute virus scanner
829 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
830 # that does not seem to be worth the pain.
831 # Ask me (Duesentrieb) about it if it's ever needed.
832 $output = wfShellExec( "$command 2>&1", $exitCode );
834 # map exit code to AV_xxx constants.
835 $mappedCode = $exitCode;
836 if ( $exitCodeMap ) {
837 if ( isset( $exitCodeMap[$exitCode] ) ) {
838 $mappedCode = $exitCodeMap[$exitCode];
839 } elseif ( isset( $exitCodeMap["*"] ) ) {
840 $mappedCode = $exitCodeMap["*"];
844 if ( $mappedCode === AV_SCAN_FAILED
) {
845 # scan failed (code was mapped to false by $exitCodeMap)
846 wfDebug( __METHOD__
. ": failed to scan $file (code $exitCode).\n" );
848 if ( $wgAntivirusRequired ) {
849 return wfMsg( 'virus-scanfailed', array( $exitCode ) );
853 } elseif ( $mappedCode === AV_SCAN_ABORTED
) {
854 # scan failed because filetype is unknown (probably imune)
855 wfDebug( __METHOD__
. ": unsupported file type $file (code $exitCode).\n" );
857 } elseif ( $mappedCode === AV_NO_VIRUS
) {
859 wfDebug( __METHOD__
. ": file passed virus scan.\n" );
862 $output = trim( $output );
865 $output = true; #if there's no output, return true
866 } elseif ( $msgPattern ) {
868 if ( preg_match( $msgPattern, $output, $groups ) ) {
870 $output = $groups[1];
875 wfDebug( __METHOD__
. ": FOUND VIRUS! scanner feedback: $output \n" );
881 * Check if the temporary file is MacBinary-encoded, as some uploads
882 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
883 * If so, the data fork will be extracted to a second temporary file,
884 * which will then be checked for validity and either kept or discarded.
886 private function checkMacBinary() {
887 $macbin = new MacBinary( $this->mTempPath
);
888 if( $macbin->isValid() ) {
889 $dataFile = tempnam( wfTempDir(), 'WikiMacBinary' );
890 $dataHandle = fopen( $dataFile, 'wb' );
892 wfDebug( __METHOD__
. ": Extracting MacBinary data fork to $dataFile\n" );
893 $macbin->extractData( $dataHandle );
895 $this->mTempPath
= $dataFile;
896 $this->mFileSize
= $macbin->dataForkLength();
898 // We'll have to manually remove the new file if it's not kept.
899 $this->mRemoveTempFile
= true;
905 * Check if there's an overwrite conflict and, if so, if restrictions
906 * forbid this user from performing the upload.
908 * @return mixed true on success, error string on failure
910 private function checkOverwrite() {
912 // First check whether the local file can be overwritten
913 $file = $this->getLocalFile();
914 if( $file->exists() ) {
915 if( !self
::userCanReUpload( $wgUser, $file ) ) {
916 return 'fileexists-forbidden';
922 /* Check shared conflicts: if the local file does not exist, but
923 * wfFindFile finds a file, it exists in a shared repository.
925 $file = wfFindFile( $this->getTitle() );
926 if ( $file && !$wgUser->isAllowed( 'reupload-shared' ) ) {
927 return 'fileexists-shared-forbidden';
934 * Check if a user is the last uploader
936 * @param $user User object
937 * @param $img String: image name
940 public static function userCanReUpload( User
$user, $img ) {
941 if( $user->isAllowed( 'reupload' ) ) {
942 return true; // non-conditional
944 if( !$user->isAllowed( 'reupload-own' ) ) {
947 if( is_string( $img ) ) {
948 $img = wfLocalFile( $img );
950 if ( !( $img instanceof LocalFile
) ) {
954 return $user->getId() == $img->getUser( 'id' );
958 * Helper function that does various existence checks for a file.
959 * The following checks are performed:
961 * - Article with the same name as the file exists
962 * - File exists with normalized extension
963 * - The file looks like a thumbnail and the original exists
965 * @param $file The File object to check
966 * @return mixed False if the file does not exists, else an array
968 public static function getExistsWarning( $file ) {
969 if( $file->exists() ) {
970 return array( 'warning' => 'exists', 'file' => $file );
973 if( $file->getTitle()->getArticleID() ) {
974 return array( 'warning' => 'page-exists', 'file' => $file );
977 if ( $file->wasDeleted() && !$file->exists() ) {
978 return array( 'warning' => 'was-deleted', 'file' => $file );
981 if( strpos( $file->getName(), '.' ) == false ) {
982 $partname = $file->getName();
985 $n = strrpos( $file->getName(), '.' );
986 $extension = substr( $file->getName(), $n +
1 );
987 $partname = substr( $file->getName(), 0, $n );
989 $normalizedExtension = File
::normalizeExtension( $extension );
991 if ( $normalizedExtension != $extension ) {
992 // We're not using the normalized form of the extension.
993 // Normal form is lowercase, using most common of alternate
994 // extensions (eg 'jpg' rather than 'JPEG').
996 // Check for another file using the normalized form...
997 $nt_lc = Title
::makeTitle( NS_FILE
, "{$partname}.{$normalizedExtension}" );
998 $file_lc = wfLocalFile( $nt_lc );
1000 if( $file_lc->exists() ) {
1002 'warning' => 'exists-normalized',
1004 'normalizedFile' => $file_lc
1009 if ( self
::isThumbName( $file->getName() ) ) {
1010 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1011 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $extension, NS_FILE
);
1012 $file_thb = wfLocalFile( $nt_thb );
1013 if( $file_thb->exists() ) {
1015 'warning' => 'thumb',
1017 'thumbFile' => $file_thb
1020 // File does not exist, but we just don't like the name
1022 'warning' => 'thumb-name',
1024 'thumbFile' => $file_thb
1030 foreach( self
::getFilenamePrefixBlacklist() as $prefix ) {
1031 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1033 'warning' => 'bad-prefix',
1044 * Helper function that checks whether the filename looks like a thumbnail
1046 public static function isThumbName( $filename ) {
1047 $n = strrpos( $filename, '.' );
1048 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
1050 substr( $partname , 3, 3 ) == 'px-' ||
1051 substr( $partname , 2, 3 ) == 'px-'
1053 preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) );
1057 * Get a list of blacklisted filename prefixes from [[MediaWiki:Filename-prefix-blacklist]]
1059 * @return array list of prefixes
1061 public static function getFilenamePrefixBlacklist() {
1062 $blacklist = array();
1063 $message = wfMsgForContent( 'filename-prefix-blacklist' );
1064 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) ||
$message == '-' ) ) {
1065 $lines = explode( "\n", $message );
1066 foreach( $lines as $line ) {
1067 // Remove comment lines
1068 $comment = substr( trim( $line ), 0, 1 );
1069 if ( $comment == '#' ||
$comment == '' ) {
1072 // Remove additional comments after a prefix
1073 $comment = strpos( $line, '#' );
1074 if ( $comment > 0 ) {
1075 $line = substr( $line, 0, $comment-1 );
1077 $blacklist[] = trim( $line );
1083 public function getImageInfo( $result ) {
1084 $file = $this->getLocalFile();
1085 $imParam = ApiQueryImageInfo
::getPropertyNames();
1086 return ApiQueryImageInfo
::getInfo( $file, array_flip( $imParam ), $result );