removed session_write_close(); per bug 19932
[lhc/web/wiklou.git] / includes / upload / UploadBase.php
1 <?php
2
3 class UploadBase {
4 var $mTempPath;
5 var $mDesiredDestName, $mDestName, $mRemoveTempFile, $mSourceType;
6 var $mTitle = false, $mTitleError = 0;
7 var $mFilteredName, $mFinalExtension;
8
9 const SUCCESS = 0;
10 const OK = 0;
11 const BEFORE_PROCESSING = 1;
12 const LARGE_FILE_SERVER = 2;
13 const EMPTY_FILE = 3;
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;
25
26 const SESSION_VERSION = 2;
27
28 /**
29 * Returns true if uploads are enabled.
30 * Can be override by subclasses.
31 */
32 static function isEnabled() {
33 global $wgEnableUploads;
34 if ( !$wgEnableUploads )
35 return false;
36
37 # Check php's file_uploads setting
38 if( !wfIniGetBool( 'file_uploads' ) ) {
39 return false;
40 }
41 return true;
42 }
43
44 /**
45 * Returns true if the user can use this upload module or else a string
46 * identifying the missing permission.
47 * Can be overriden by subclasses.
48 */
49 static function isAllowed( $user ) {
50 if( !$user->isAllowed( 'upload' ) )
51 return 'upload';
52 return true;
53 }
54
55 // Upload handlers. Should probably just be a global
56 static $uploadHandlers = array( 'Stash', 'File', 'Url' );
57
58 /**
59 * Create a form of UploadBase depending on wpSourceType and initializes it
60 */
61 static function createFromRequest( &$request, $type = null ) {
62 $type = $type ? $type : $request->getVal( 'wpSourceType' );
63
64 if( !$type )
65 return null;
66
67 $type = ucfirst( $type );
68 $className = 'UploadFrom' . $type;
69 wfDebug( __METHOD__ . ": class name: $className\n" );
70 if( !in_array( $type, self::$uploadHandlers ) )
71 return null;
72
73 if( !call_user_func( array( $className, 'isEnabled' ) ) )
74 return null;
75
76 if( !call_user_func( array( $className, 'isValidRequest' ), $request ) )
77 return null;
78
79 $handler = new $className;
80
81 $handler->initializeFromRequest( $request );
82 return $handler;
83 }
84
85 /**
86 * Check whether a request if valid for this handler
87 */
88 static function isValidRequest( $request ) {
89 return false;
90 }
91
92 function __construct() {}
93
94 /**
95 * Do the real variable initialization
96 */
97 function initialize( $name, $tempPath, $fileSize, $removeTempFile = false ) {
98 $this->mDesiredDestName = $name;
99 $this->mTempPath = $tempPath;
100 $this->mFileSize = $fileSize;
101 $this->mRemoveTempFile = $removeTempFile;
102 }
103
104 /**
105 * Fetch the file. Usually a no-op
106 */
107 function fetchFile() {
108 return Status::newGood();
109 }
110
111 /**
112 * Return the file size
113 */
114 function isEmptyFile(){
115 return empty( $this->mFileSize );
116 }
117
118 /**
119 * Verify whether the upload is sane.
120 * Returns self::OK or else an array with error information
121 */
122 function verifyUpload() {
123 /**
124 * If there was no filename or a zero size given, give up quick.
125 */
126 if( $this->isEmptyFile() )
127 return array( 'status' => self::EMPTY_FILE );
128
129 $nt = $this->getTitle();
130 if( is_null( $nt ) ) {
131 $result = array( 'status' => $this->mTitleError );
132 if( $this->mTitleError == self::ILLEGAL_FILENAME )
133 $result['filtered'] = $this->mFilteredName;
134 if ( $this->mTitleError == self::FILETYPE_BADTYPE )
135 $result['finalExt'] = $this->mFinalExtension;
136 return $result;
137 }
138 $this->mLocalFile = wfLocalFile( $nt );
139 $this->mDestName = $this->mLocalFile->getName();
140
141 /**
142 * In some cases we may forbid overwriting of existing files.
143 */
144 $overwrite = $this->checkOverwrite();
145 if( $overwrite !== true )
146 return array( 'status' => self::OVERWRITE_EXISTING_FILE, 'overwrite' => $overwrite );
147
148 /**
149 * Look at the contents of the file; if we can recognize the
150 * type but it's corrupt or data of the wrong type, we should
151 * probably not accept it.
152 */
153 $verification = $this->verifyFile( $this->mTempPath );
154
155 if( $verification !== true ) {
156 if( !is_array( $verification ) )
157 $verification = array( $verification );
158 $verification['status'] = self::VERIFICATION_ERROR;
159 return $verification;
160 }
161
162 $error = '';
163 if( !wfRunHooks( 'UploadVerification',
164 array( $this->mDestName, $this->mTempPath, &$error ) ) ) {
165 return array( 'status' => self::UPLOAD_VERIFICATION_ERROR, 'error' => $error );
166 }
167
168 return self::OK;
169 }
170
171 /**
172 * Verifies that it's ok to include the uploaded file
173 *
174 * this function seems to intermixes tmpfile and $this->mTempPath .. no idea why this is
175 *
176 * @param string $tmpfile the full path of the temporary file to verify
177 * @return mixed true of the file is verified, a string or array otherwise.
178 */
179 protected function verifyFile( $tmpfile ) {
180 $this->mFileProps = File::getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
181 $this->checkMacBinary();
182
183 #magically determine mime type
184 $magic = MimeMagic::singleton();
185 $mime = $magic->guessMimeType( $tmpfile, false );
186
187 #check mime type, if desired
188 global $wgVerifyMimeType;
189 if( isset( $wgMimeTypeBlacklist ) && !is_null( $wgMimeTypeBlacklist ) ) {
190 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) )
191 return array( 'filetype-badmime', $mime );
192
193 # Check IE type
194 $fp = fopen( $tmpfile, 'rb' );
195 $chunk = fread( $fp, 256 );
196 fclose( $fp );
197 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension );
198 $ieTypes = $magic->getIEMimeTypes( $tmpfile, $chunk, $extMime );
199 foreach ( $ieTypes as $ieType ) {
200 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
201 return array( 'filetype-bad-ie-mime', $ieType );
202 }
203 }
204 }
205
206 #check for htmlish code and javascript
207 if( $this->detectScript( $tmpfile, $mime, $this->mFinalExtension ) ) {
208 return 'uploadscripted';
209 }
210 if( $this->mFinalExtension == 'svg' || $mime == 'image/svg+xml' ) {
211 if( $this->detectScriptInSvg( $tmpfile ) ) {
212 return 'uploadscripted';
213 }
214 }
215
216 /**
217 * Scan the uploaded file for viruses
218 */
219 $virus = $this->detectVirus( $tmpfile );
220 if ( $virus ) {
221 return array( 'uploadvirus', $virus );
222 }
223 wfDebug( __METHOD__ . ": all clear; passing.\n" );
224 return true;
225 }
226
227 /**
228 * Check whether the user can edit, upload and create the image
229 */
230 function verifyPermissions( $user ) {
231 /**
232 * If the image is protected, non-sysop users won't be able
233 * to modify it by uploading a new revision.
234 */
235 $nt = $this->getTitle();
236 if( is_null( $nt ) )
237 return true;
238 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
239 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
240 $permErrorsCreate = ( $nt->exists() ? array() : $nt->getUserPermissionsErrors( 'create', $user ) );
241 if( $permErrors || $permErrorsUpload || $permErrorsCreate ) {
242 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
243 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
244 return $permErrors;
245 }
246 return true;
247 }
248
249 /**
250 * Check for non fatal problems with the file
251 */
252 function checkWarnings() {
253 $warning = array();
254
255 $filename = $this->mLocalFile->getName();
256 $n = strrpos( $filename, '.' );
257 $partname = $n ? substr( $filename, 0, $n ) : $filename;
258
259 /*
260 * Check whether the resulting filename is different from the desired one,
261 * but ignore things like ucfirst() and spaces/underscore things
262 */
263 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName );
264 global $wgCapitalLinks, $wgContLang;
265 if ( $wgCapitalLinks ) {
266 $comparableName = $wgContLang->ucfirst( $comparableName );
267 }
268 if( $this->mDesiredDestName != $filename && $comparableName != $filename )
269 $warning['badfilename'] = $filename;
270
271 // Check whether the file extension is on the unwanted list
272 global $wgCheckFileExtensions, $wgFileExtensions;
273 if ( $wgCheckFileExtensions ) {
274 if ( !$this->checkFileExtension( $this->mFinalExtension, $wgFileExtensions ) )
275 $warning['filetype-unwanted-type'] = $this->mFinalExtension;
276 }
277
278 global $wgUploadSizeWarning;
279 if ( $wgUploadSizeWarning && ( $this->mFileSize > $wgUploadSizeWarning ) )
280 $warning['large-file'] = $wgUploadSizeWarning;
281
282 if ( $this->mFileSize == 0 )
283 $warning['emptyfile'] = true;
284
285
286 $exists = self::getExistsWarning( $this->mLocalFile );
287 if( $exists !== false )
288 $warning['exists'] = $exists;
289
290 // Check whether this may be a thumbnail
291 if( $exists !== false && $exists[0] != 'thumb'
292 && self::isThumbName( $this->mLocalFile->getName() ) ){
293 //make the title:
294 $nt = $this->getTitle();
295 $warning['file-thumbnail-no'] = substr( $filename, 0,
296 strpos( $nt->getText() , '-' ) +1 );
297 }
298
299 // Check dupes against existing files
300 $hash = File::sha1Base36( $this->mTempPath );
301 $dupes = RepoGroup::singleton()->findBySha1( $hash );
302 $title = $this->getTitle();
303 // Remove all matches against self
304 foreach ( $dupes as $key => $dupe ) {
305 if( $title->equals( $dupe->getTitle() ) )
306 unset( $dupes[$key] );
307 }
308 if( $dupes )
309 $warning['duplicate'] = $dupes;
310
311 // Check dupes against archives
312 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
313 if ( $archivedImage->getID() > 0 )
314 $warning['duplicate-archive'] = $archivedImage->getName();
315
316 $filenamePrefixBlacklist = self::getFilenamePrefixBlacklist();
317 foreach( $filenamePrefixBlacklist as $prefix ) {
318 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
319 $warning['filename-bad-prefix'] = $prefix;
320 break;
321 }
322 }
323
324 # If the file existed before and was deleted, warn the user of this
325 # Don't bother doing so if the file exists now, however
326 if( $this->mLocalFile->wasDeleted() && !$this->mLocalFile->exists() )
327 $warning['filewasdeleted'] = $this->mLocalFile->getTitle();
328
329 return $warning;
330 }
331
332 /**
333 * Really perform the upload.
334 */
335 function performUpload( $comment, $pageText, $watch, $user ) {
336 wfDebug( "\n\n\performUpload: sum:" . $comment . ' c: ' . $pageText . ' w:' . $watch );
337 $status = $this->mLocalFile->upload( $this->mTempPath, $comment, $pageText,
338 File::DELETE_SOURCE, $this->mFileProps, false, $user );
339
340 if( $status->isGood() && $watch )
341 $user->addWatch( $this->mLocalFile->getTitle() );
342
343 if( $status->isGood() )
344 wfRunHooks( 'UploadComplete', array( &$this ) );
345
346 return $status;
347 }
348
349 /**
350 * Returns a title or null
351 */
352 function getTitle() {
353 if ( $this->mTitle !== false )
354 return $this->mTitle;
355
356 /**
357 * Chop off any directories in the given filename. Then
358 * filter out illegal characters, and try to make a legible name
359 * out of it. We'll strip some silently that Title would die on.
360 */
361 $basename = $this->mDesiredDestName;
362
363 $this->mFilteredName = wfStripIllegalFilenameChars( $basename );
364 /* Normalize to title form before we do any further processing */
365 $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
366 if( is_null( $nt ) ) {
367 $this->mTitleError = self::ILLEGAL_FILENAME;
368 return $this->mTitle = null;
369 }
370 $this->mFilteredName = $nt->getDBkey();
371
372 /**
373 * We'll want to blacklist against *any* 'extension', and use
374 * only the final one for the whitelist.
375 */
376 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName );
377
378 if( count( $ext ) ) {
379 $this->mFinalExtension = trim( $ext[count( $ext ) - 1] );
380 } else {
381 $this->mFinalExtension = '';
382 }
383
384 /* Don't allow users to override the blacklist (check file extension) */
385 global $wgCheckFileExtensions, $wgStrictFileExtensions;
386 global $wgFileExtensions, $wgFileBlacklist;
387 if ( $this->mFinalExtension == '' ) {
388 $this->mTitleError = self::FILETYPE_MISSING;
389 return $this->mTitle = null;
390 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
391 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
392 !$this->checkFileExtension( $this->mFinalExtension, $wgFileExtensions ) ) ) {
393 $this->mTitleError = self::FILETYPE_BADTYPE;
394 return $this->mTitle = null;
395 }
396
397 # If there was more than one "extension", reassemble the base
398 # filename to prevent bogus complaints about length
399 if( count( $ext ) > 1 ) {
400 for( $i = 0; $i < count( $ext ) - 1; $i++ )
401 $partname .= '.' . $ext[$i];
402 }
403
404 if( strlen( $partname ) < 1 ) {
405 $this->mTitleError = self::MIN_LENGTH_PARTNAME;
406 return $this->mTitle = null;
407 }
408
409 $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
410 if( is_null( $nt ) ) {
411 $this->mTitleError = self::ILLEGAL_FILENAME;
412 return $this->mTitle = null;
413 }
414 return $this->mTitle = $nt;
415 }
416
417 function getLocalFile() {
418 if( is_null( $this->mLocalFile ) ) {
419 $nt = $this->getTitle();
420 $this->mLocalFile = is_null( $nt ) ? null : wfLocalFile( $nt );
421 }
422 return $this->mLocalFile;
423 }
424
425 /**
426 * Stash a file in a temporary directory for later processing
427 * after the user has confirmed it.
428 *
429 * If the user doesn't explicitly cancel or accept, these files
430 * can accumulate in the temp directory.
431 *
432 * @param string $saveName - the destination filename
433 * @param string $tempName - the source temporary file to save
434 * @return string - full path the stashed file, or false on failure
435 * @access private
436 */
437 function saveTempUploadedFile( $saveName, $tempName ) {
438 $repo = RepoGroup::singleton()->getLocalRepo();
439 $status = $repo->storeTemp( $saveName, $tempName );
440 return $status;
441 }
442
443 /* append to a stashed file */
444 function appendToUploadFile( $srcPath, $toAppendPath ){
445 $repo = RepoGroup::singleton()->getLocalRepo();
446 $status = $repo->append( $srcPath, $toAppendPath );
447 return $status;
448 }
449
450 /**
451 * Stash a file in a temporary directory for later processing,
452 * and save the necessary descriptive info into the session.
453 * Returns a key value which will be passed through a form
454 * to pick up the path info on a later invocation.
455 *
456 * @return int
457 * @access private
458 */
459 function stashSession() {
460 $status = $this->saveTempUploadedFile( $this->mDestName, $this->mTempPath );
461 if( !$status->isOK() ) {
462 # Couldn't save the file.
463 return false;
464 }
465 $mTempPath = $status->value;
466 if(!isset($_SESSION))
467 session_start(); // start up the session (might have been previously closed to prevent php session locking)
468 $key = $this->getSessionKey();
469 $_SESSION['wsUploadData'][$key] = array(
470 'mTempPath' => $mTempPath,
471 'mFileSize' => $this->mFileSize,
472 'mFileProps' => $this->mFileProps,
473 'version' => self::SESSION_VERSION,
474 );
475 return $key;
476 }
477
478 /**
479 * Pull session key gen from stash in cases where we want to start an upload without much information
480 */
481 function getSessionKey(){
482 $key = mt_rand( 0, 0x7fffffff );
483 $_SESSION['wsUploadData'][$key] = array();
484 return $key;
485 }
486
487 /**
488 * Remove a temporarily kept file stashed by saveTempUploadedFile().
489 * @return success
490 */
491 function unsaveUploadedFile() {
492 $repo = RepoGroup::singleton()->getLocalRepo();
493 $success = $repo->freeTemp( $this->mTempPath );
494 return $success;
495 }
496
497 /**
498 * If we've modified the upload file we need to manually remove it
499 * on exit to clean up.
500 * @access private
501 */
502 function cleanupTempFile() {
503 if ( $this->mRemoveTempFile && $this->mTempPath && file_exists( $this->mTempPath ) ) {
504 wfDebug( __METHOD__ . ": Removing temporary file {$this->mTempPath}\n" );
505 unlink( $this->mTempPath );
506 }
507 }
508
509 function getTempPath() {
510 return $this->mTempPath;
511 }
512
513 /**
514 * Split a file into a base name and all dot-delimited 'extensions'
515 * on the end. Some web server configurations will fall back to
516 * earlier pseudo-'extensions' to determine type and execute
517 * scripts, so the blacklist needs to check them all.
518 *
519 * @return array
520 */
521 public static function splitExtensions( $filename ) {
522 $bits = explode( '.', $filename );
523 $basename = array_shift( $bits );
524 return array( $basename, $bits );
525 }
526
527 /**
528 * Perform case-insensitive match against a list of file extensions.
529 * Returns true if the extension is in the list.
530 *
531 * @param string $ext
532 * @param array $list
533 * @return bool
534 */
535 public static function checkFileExtension( $ext, $list ) {
536 return in_array( strtolower( $ext ), $list );
537 }
538
539 /**
540 * Perform case-insensitive match against a list of file extensions.
541 * Returns true if any of the extensions are in the list.
542 *
543 * @param array $ext
544 * @param array $list
545 * @return bool
546 */
547 public static function checkFileExtensionList( $ext, $list ) {
548 foreach( $ext as $e ) {
549 if( in_array( strtolower( $e ), $list ) ) {
550 return true;
551 }
552 }
553 return false;
554 }
555
556 /**
557 * Checks if the mime type of the uploaded file matches the file extension.
558 *
559 * @param string $mime the mime type of the uploaded file
560 * @param string $extension The filename extension that the file is to be served with
561 * @return bool
562 */
563 public static function verifyExtension( $mime, $extension ) {
564 $magic = MimeMagic::singleton();
565
566 if ( !$mime || $mime == 'unknown' || $mime == 'unknown/unknown' )
567 if ( !$magic->isRecognizableExtension( $extension ) ) {
568 wfDebug( __METHOD__ . ": passing file with unknown detected mime type; " .
569 "unrecognized extension '$extension', can't verify\n" );
570 return true;
571 } else {
572 wfDebug( __METHOD__ . ": rejecting file with unknown detected mime type; ".
573 "recognized extension '$extension', so probably invalid file\n" );
574 return false;
575 }
576
577 $match = $magic->isMatchingExtension( $extension, $mime );
578
579 if ( $match === NULL ) {
580 wfDebug( __METHOD__ . ": no file extension known for mime type $mime, passing file\n" );
581 return true;
582 } elseif( $match === true ) {
583 wfDebug( __METHOD__ . ": mime type $mime matches extension $extension, passing file\n" );
584
585 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
586 return true;
587
588 } else {
589 wfDebug( __METHOD__ . ": mime type $mime mismatches file extension $extension, rejecting file\n" );
590 return false;
591 }
592 }
593
594 /**
595 * Heuristic for detecting files that *could* contain JavaScript instructions or
596 * things that may look like HTML to a browser and are thus
597 * potentially harmful. The present implementation will produce false positives in some situations.
598 *
599 * @param string $file Pathname to the temporary upload file
600 * @param string $mime The mime type of the file
601 * @param string $extension The extension of the file
602 * @return bool true if the file contains something looking like embedded scripts
603 */
604 function detectScript( $file, $mime, $extension ) {
605 global $wgAllowTitlesInSVG;
606
607 #ugly hack: for text files, always look at the entire file.
608 #For binary field, just check the first K.
609
610 if( strpos( $mime,'text/' ) === 0 )
611 $chunk = file_get_contents( $file );
612 else {
613 $fp = fopen( $file, 'rb' );
614 $chunk = fread( $fp, 1024 );
615 fclose( $fp );
616 }
617
618 $chunk = strtolower( $chunk );
619
620 if( !$chunk )
621 return false;
622
623 #decode from UTF-16 if needed (could be used for obfuscation).
624 if( substr( $chunk, 0, 2 ) == "\xfe\xff" )
625 $enc = "UTF-16BE";
626 elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" )
627 $enc = "UTF-16LE";
628 else
629 $enc = NULL;
630
631 if( $enc )
632 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
633
634 $chunk = trim( $chunk );
635
636 #FIXME: convert from UTF-16 if necessarry!
637 wfDebug( __METHOD__ . ": checking for embedded scripts and HTML stuff\n" );
638
639 #check for HTML doctype
640 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) )
641 return true;
642
643 /**
644 * Internet Explorer for Windows performs some really stupid file type
645 * autodetection which can cause it to interpret valid image files as HTML
646 * and potentially execute JavaScript, creating a cross-site scripting
647 * attack vectors.
648 *
649 * Apple's Safari browser also performs some unsafe file type autodetection
650 * which can cause legitimate files to be interpreted as HTML if the
651 * web server is not correctly configured to send the right content-type
652 * (or if you're really uploading plain text and octet streams!)
653 *
654 * Returns true if IE is likely to mistake the given file for HTML.
655 * Also returns true if Safari would mistake the given file for HTML
656 * when served with a generic content-type.
657 */
658 $tags = array(
659 '<a',
660 '<body',
661 '<head',
662 '<html', #also in safari
663 '<img',
664 '<pre',
665 '<script', #also in safari
666 '<table'
667 );
668
669 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
670 $tags[] = '<title';
671 }
672
673 foreach( $tags as $tag ) {
674 if( false !== strpos( $chunk, $tag ) ) {
675 return true;
676 }
677 }
678
679 /*
680 * look for JavaScript
681 */
682
683 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
684 $chunk = Sanitizer::decodeCharReferences( $chunk );
685
686 #look for script-types
687 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) )
688 return true;
689
690 #look for html-style script-urls
691 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) )
692 return true;
693
694 #look for css-style script-urls
695 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) )
696 return true;
697
698 wfDebug( __METHOD__ . ": no scripts found\n" );
699 return false;
700 }
701
702 function detectScriptInSvg( $filename ) {
703 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
704 return $check->filterMatch;
705 }
706
707 /**
708 * @todo Replace this with a whitelist filter!
709 */
710 function checkSvgScriptCallback( $element, $attribs ) {
711 $stripped = $this->stripXmlNamespace( $element );
712
713 if( $stripped == 'script' ) {
714 wfDebug( __METHOD__ . ": Found script element '$element' in uploaded file.\n" );
715 return true;
716 }
717
718 foreach( $attribs as $attrib => $value ) {
719 $stripped = $this->stripXmlNamespace( $attrib );
720 if( substr( $stripped, 0, 2 ) == 'on' ) {
721 wfDebug( __METHOD__ . ": Found script attribute '$attrib'='value' in uploaded file.\n" );
722 return true;
723 }
724 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
725 wfDebug( __METHOD__ . ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
726 return true;
727 }
728 }
729 }
730
731 private function stripXmlNamespace( $name ) {
732 // 'http://www.w3.org/2000/svg:script' -> 'script'
733 $parts = explode( ':', strtolower( $name ) );
734 return array_pop( $parts );
735 }
736
737 /**
738 * Generic wrapper function for a virus scanner program.
739 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
740 * $wgAntivirusRequired may be used to deny upload if the scan fails.
741 *
742 * @param string $file Pathname to the temporary upload file
743 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
744 * or a string containing feedback from the virus scanner if a virus was found.
745 * If textual feedback is missing but a virus was found, this function returns true.
746 */
747 function detectVirus( $file ) {
748 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
749
750 if ( !$wgAntivirus ) {
751 wfDebug( __METHOD__ . ": virus scanner disabled\n" );
752 return NULL;
753 }
754
755 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
756 wfDebug( __METHOD__ . ": unknown virus scanner: $wgAntivirus\n" );
757 $wgOut->wrapWikiMsg( '<div class="error">$1</div>', array( 'virus-badscanner', $wgAntivirus ) );
758 return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
759 }
760
761 # look up scanner configuration
762 $command = $wgAntivirusSetup[$wgAntivirus]["command"];
763 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]["codemap"];
764 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]["messagepattern"] ) ?
765 $wgAntivirusSetup[$wgAntivirus]["messagepattern"] : null;
766
767 if ( strpos( $command,"%f" ) === false ) {
768 # simple pattern: append file to scan
769 $command .= " " . wfEscapeShellArg( $file );
770 } else {
771 # complex pattern: replace "%f" with file to scan
772 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
773 }
774
775 wfDebug( __METHOD__ . ": running virus scan: $command \n" );
776
777 # execute virus scanner
778 $exitCode = false;
779
780 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
781 # that does not seem to be worth the pain.
782 # Ask me (Duesentrieb) about it if it's ever needed.
783 $output = array();
784 if ( wfIsWindows() ) {
785 exec( "$command", $output, $exitCode );
786 } else {
787 exec( "$command 2>&1", $output, $exitCode );
788 }
789
790 # map exit code to AV_xxx constants.
791 $mappedCode = $exitCode;
792 if ( $exitCodeMap ) {
793 if ( isset( $exitCodeMap[$exitCode] ) ) {
794 $mappedCode = $exitCodeMap[$exitCode];
795 } elseif ( isset( $exitCodeMap["*"] ) ) {
796 $mappedCode = $exitCodeMap["*"];
797 }
798 }
799
800 if ( $mappedCode === AV_SCAN_FAILED ) {
801 # scan failed (code was mapped to false by $exitCodeMap)
802 wfDebug( __METHOD__ . ": failed to scan $file (code $exitCode).\n" );
803
804 if ( $wgAntivirusRequired ) {
805 return wfMsg( 'virus-scanfailed', array( $exitCode ) );
806 } else {
807 return NULL;
808 }
809 } else if ( $mappedCode === AV_SCAN_ABORTED ) {
810 # scan failed because filetype is unknown (probably imune)
811 wfDebug( __METHOD__ . ": unsupported file type $file (code $exitCode).\n" );
812 return NULL;
813 } else if ( $mappedCode === AV_NO_VIRUS ) {
814 # no virus found
815 wfDebug( __METHOD__ . ": file passed virus scan.\n" );
816 return false;
817 } else {
818 $output = join( "\n", $output );
819 $output = trim( $output );
820
821 if ( !$output ) {
822 $output = true; #if there's no output, return true
823 } elseif ( $msgPattern ) {
824 $groups = array();
825 if ( preg_match( $msgPattern, $output, $groups ) ) {
826 if ( $groups[1] ) {
827 $output = $groups[1];
828 }
829 }
830 }
831
832 wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output \n" );
833 return $output;
834 }
835 }
836
837 /**
838 * Check if the temporary file is MacBinary-encoded, as some uploads
839 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
840 * If so, the data fork will be extracted to a second temporary file,
841 * which will then be checked for validity and either kept or discarded.
842 *
843 * @access private
844 */
845 function checkMacBinary() {
846 $macbin = new MacBinary( $this->mTempPath );
847 if( $macbin->isValid() ) {
848 $dataFile = tempnam( wfTempDir(), 'WikiMacBinary' );
849 $dataHandle = fopen( $dataFile, 'wb' );
850
851 wfDebug( __METHOD__ . ": Extracting MacBinary data fork to $dataFile\n" );
852 $macbin->extractData( $dataHandle );
853
854 $this->mTempPath = $dataFile;
855 $this->mFileSize = $macbin->dataForkLength();
856
857 // We'll have to manually remove the new file if it's not kept.
858 $this->mRemoveTempFile = true;
859 }
860 $macbin->close();
861 }
862
863 /**
864 * Check if there's an overwrite conflict and, if so, if restrictions
865 * forbid this user from performing the upload.
866 *
867 * @return mixed true on success, WikiError on failure
868 * @access private
869 */
870 function checkOverwrite() {
871 global $wgUser;
872 // First check whether the local file can be overwritten
873 if( $this->mLocalFile->exists() )
874 if( !self::userCanReUpload( $wgUser, $this->mLocalFile ) )
875 return 'fileexists-forbidden';
876
877 // Check shared conflicts
878 $file = wfFindFile( $this->mLocalFile->getName() );
879 if ( $file && ( !$wgUser->isAllowed( 'reupload' ) ||
880 !$wgUser->isAllowed( 'reupload-shared' ) ) )
881 return 'fileexists-shared-forbidden';
882
883 return true;
884 }
885
886 /**
887 * Check if a user is the last uploader
888 *
889 * @param User $user
890 * @param string $img, image name
891 * @return bool
892 */
893 public static function userCanReUpload( User $user, $img ) {
894 if( $user->isAllowed( 'reupload' ) )
895 return true; // non-conditional
896 if( !$user->isAllowed( 'reupload-own' ) )
897 return false;
898 if( is_string( $img ) )
899 $img = wfLocalFile( $img );
900 if ( !( $img instanceof LocalFile ) )
901 return false;
902
903 return $user->getId() == $img->getUser( 'id' );
904 }
905
906 public static function getExistsWarning( $file ) {
907 if( $file->exists() )
908 return array( 'exists', $file );
909
910 if( $file->getTitle()->getArticleID() )
911 return array( 'page-exists', $file );
912
913 if( strpos( $file->getName(), '.' ) == false ) {
914 $partname = $file->getName();
915 $rawExtension = '';
916 } else {
917 $n = strrpos( $file->getName(), '.' );
918 $rawExtension = substr( $file->getName(), $n + 1 );
919 $partname = substr( $file->getName(), 0, $n );
920 }
921
922 if ( $rawExtension != $file->getExtension() ) {
923 // We're not using the normalized form of the extension.
924 // Normal form is lowercase, using most common of alternate
925 // extensions (eg 'jpg' rather than 'JPEG').
926 //
927 // Check for another file using the normalized form...
928 $nt_lc = Title::makeTitle( NS_FILE, $partname . '.' . $file->getExtension() );
929 $file_lc = wfLocalFile( $nt_lc );
930
931 if( $file_lc->exists() )
932 return array( 'exists-normalized', $file_lc );
933 }
934
935 if ( self::isThumbName( $file->getName() ) ) {
936 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
937 $nt_thb = Title::newFromText( substr( $partname , strpos( $partname , '-' ) +1 ) . '.' . $rawExtension );
938 $file_thb = wfLocalFile( $nt_thb );
939 if( $file_thb->exists() )
940 return array( 'thumb', $file_thb );
941 }
942
943 return false;
944 }
945
946 public static function isThumbName( $filename ) {
947 $n = strrpos( $filename, '.' );
948 $partname = $n ? substr( $filename, 0, $n ) : $filename;
949 return (
950 substr( $partname , 3, 3 ) == 'px-' ||
951 substr( $partname , 2, 3 ) == 'px-'
952 ) &&
953 preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) );
954 }
955
956 /**
957 * Get a list of blacklisted filename prefixes from [[MediaWiki:filename-prefix-blacklist]]
958 *
959 * @return array list of prefixes
960 */
961 public static function getFilenamePrefixBlacklist() {
962 $blacklist = array();
963 $message = wfMsgForContent( 'filename-prefix-blacklist' );
964 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) || $message == '-' ) ) {
965 $lines = explode( "\n", $message );
966 foreach( $lines as $line ) {
967 // Remove comment lines
968 $comment = substr( trim( $line ), 0, 1 );
969 if ( $comment == '#' || $comment == '' ) {
970 continue;
971 }
972 // Remove additional comments after a prefix
973 $comment = strpos( $line, '#' );
974 if ( $comment > 0 ) {
975 $line = substr( $line, 0, $comment-1 );
976 }
977 $blacklist[] = trim( $line );
978 }
979 }
980 return $blacklist;
981 }
982
983 }