coding style cleanup for upload stuff
[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" );
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 session_start(); // start up the session (might have been previously closed to prevent php session locking)
467 $key = $this->getSessionKey();
468 $_SESSION['wsUploadData'][$key] = array(
469 'mTempPath' => $mTempPath,
470 'mFileSize' => $this->mFileSize,
471 'mSrcName' => $this->mSrcName,
472 'mFileProps' => $this->mFileProps,
473 'version' => self::SESSION_VERSION,
474 );
475 session_write_close();
476 return $key;
477 }
478
479 /**
480 * Pull session key gen from stash in cases where we want to start an upload without much information
481 */
482 function getSessionKey(){
483 $key = mt_rand( 0, 0x7fffffff );
484 $_SESSION['wsUploadData'][$key] = array();
485 return $key;
486 }
487
488 /**
489 * Remove a temporarily kept file stashed by saveTempUploadedFile().
490 * @return success
491 */
492 function unsaveUploadedFile() {
493 $repo = RepoGroup::singleton()->getLocalRepo();
494 $success = $repo->freeTemp( $this->mTempPath );
495 return $success;
496 }
497
498 /**
499 * If we've modified the upload file we need to manually remove it
500 * on exit to clean up.
501 * @access private
502 */
503 function cleanupTempFile() {
504 if ( $this->mRemoveTempFile && $this->mTempPath && file_exists( $this->mTempPath ) ) {
505 wfDebug( __METHOD__ . ": Removing temporary file {$this->mTempPath}\n" );
506 unlink( $this->mTempPath );
507 }
508 }
509
510 function getTempPath() {
511 return $this->mTempPath;
512 }
513
514 /**
515 * Split a file into a base name and all dot-delimited 'extensions'
516 * on the end. Some web server configurations will fall back to
517 * earlier pseudo-'extensions' to determine type and execute
518 * scripts, so the blacklist needs to check them all.
519 *
520 * @return array
521 */
522 public static function splitExtensions( $filename ) {
523 $bits = explode( '.', $filename );
524 $basename = array_shift( $bits );
525 return array( $basename, $bits );
526 }
527
528 /**
529 * Perform case-insensitive match against a list of file extensions.
530 * Returns true if the extension is in the list.
531 *
532 * @param string $ext
533 * @param array $list
534 * @return bool
535 */
536 public static function checkFileExtension( $ext, $list ) {
537 return in_array( strtolower( $ext ), $list );
538 }
539
540 /**
541 * Perform case-insensitive match against a list of file extensions.
542 * Returns true if any of the extensions are in the list.
543 *
544 * @param array $ext
545 * @param array $list
546 * @return bool
547 */
548 public static function checkFileExtensionList( $ext, $list ) {
549 foreach( $ext as $e ) {
550 if( in_array( strtolower( $e ), $list ) ) {
551 return true;
552 }
553 }
554 return false;
555 }
556
557 /**
558 * Checks if the mime type of the uploaded file matches the file extension.
559 *
560 * @param string $mime the mime type of the uploaded file
561 * @param string $extension The filename extension that the file is to be served with
562 * @return bool
563 */
564 public static function verifyExtension( $mime, $extension ) {
565 $magic = MimeMagic::singleton();
566
567 if ( !$mime || $mime == 'unknown' || $mime == 'unknown/unknown' )
568 if ( !$magic->isRecognizableExtension( $extension ) ) {
569 wfDebug( __METHOD__ . ": passing file with unknown detected mime type; " .
570 "unrecognized extension '$extension', can't verify\n" );
571 return true;
572 } else {
573 wfDebug( __METHOD__ . ": rejecting file with unknown detected mime type; ".
574 "recognized extension '$extension', so probably invalid file\n" );
575 return false;
576 }
577
578 $match = $magic->isMatchingExtension( $extension, $mime );
579
580 if ( $match === NULL ) {
581 wfDebug( __METHOD__ . ": no file extension known for mime type $mime, passing file\n" );
582 return true;
583 } elseif( $match === true ) {
584 wfDebug( __METHOD__ . ": mime type $mime matches extension $extension, passing file\n" );
585
586 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
587 return true;
588
589 } else {
590 wfDebug( __METHOD__ . ": mime type $mime mismatches file extension $extension, rejecting file\n" );
591 return false;
592 }
593 }
594
595 /**
596 * Heuristic for detecting files that *could* contain JavaScript instructions or
597 * things that may look like HTML to a browser and are thus
598 * potentially harmful. The present implementation will produce false positives in some situations.
599 *
600 * @param string $file Pathname to the temporary upload file
601 * @param string $mime The mime type of the file
602 * @param string $extension The extension of the file
603 * @return bool true if the file contains something looking like embedded scripts
604 */
605 function detectScript( $file, $mime, $extension ) {
606 global $wgAllowTitlesInSVG;
607
608 #ugly hack: for text files, always look at the entire file.
609 #For binary field, just check the first K.
610
611 if( strpos( $mime,'text/' ) === 0 )
612 $chunk = file_get_contents( $file );
613 else {
614 $fp = fopen( $file, 'rb' );
615 $chunk = fread( $fp, 1024 );
616 fclose( $fp );
617 }
618
619 $chunk = strtolower( $chunk );
620
621 if( !$chunk )
622 return false;
623
624 #decode from UTF-16 if needed (could be used for obfuscation).
625 if( substr( $chunk, 0, 2 ) == "\xfe\xff" )
626 $enc = "UTF-16BE";
627 elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" )
628 $enc = "UTF-16LE";
629 else
630 $enc = NULL;
631
632 if( $enc )
633 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
634
635 $chunk = trim( $chunk );
636
637 #FIXME: convert from UTF-16 if necessarry!
638 wfDebug( __METHOD__ . ": checking for embedded scripts and HTML stuff\n" );
639
640 #check for HTML doctype
641 if( eregi( "<!DOCTYPE *X?HTML", $chunk ) )
642 return true;
643
644 /**
645 * Internet Explorer for Windows performs some really stupid file type
646 * autodetection which can cause it to interpret valid image files as HTML
647 * and potentially execute JavaScript, creating a cross-site scripting
648 * attack vectors.
649 *
650 * Apple's Safari browser also performs some unsafe file type autodetection
651 * which can cause legitimate files to be interpreted as HTML if the
652 * web server is not correctly configured to send the right content-type
653 * (or if you're really uploading plain text and octet streams!)
654 *
655 * Returns true if IE is likely to mistake the given file for HTML.
656 * Also returns true if Safari would mistake the given file for HTML
657 * when served with a generic content-type.
658 */
659 $tags = array(
660 '<a',
661 '<body',
662 '<head',
663 '<html', #also in safari
664 '<img',
665 '<pre',
666 '<script', #also in safari
667 '<table'
668 );
669
670 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
671 $tags[] = '<title';
672 }
673
674 foreach( $tags as $tag ) {
675 if( false !== strpos( $chunk, $tag ) ) {
676 return true;
677 }
678 }
679
680 /*
681 * look for JavaScript
682 */
683
684 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
685 $chunk = Sanitizer::decodeCharReferences( $chunk );
686
687 #look for script-types
688 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) )
689 return true;
690
691 #look for html-style script-urls
692 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) )
693 return true;
694
695 #look for css-style script-urls
696 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) )
697 return true;
698
699 wfDebug( __METHOD__ . ": no scripts found\n" );
700 return false;
701 }
702
703 function detectScriptInSvg( $filename ) {
704 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
705 return $check->filterMatch;
706 }
707
708 /**
709 * @todo Replace this with a whitelist filter!
710 */
711 function checkSvgScriptCallback( $element, $attribs ) {
712 $stripped = $this->stripXmlNamespace( $element );
713
714 if( $stripped == 'script' ) {
715 wfDebug( __METHOD__ . ": Found script element '$element' in uploaded file.\n" );
716 return true;
717 }
718
719 foreach( $attribs as $attrib => $value ) {
720 $stripped = $this->stripXmlNamespace( $attrib );
721 if( substr( $stripped, 0, 2 ) == 'on' ) {
722 wfDebug( __METHOD__ . ": Found script attribute '$attrib'='value' in uploaded file.\n" );
723 return true;
724 }
725 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
726 wfDebug( __METHOD__ . ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
727 return true;
728 }
729 }
730 }
731
732 private function stripXmlNamespace( $name ) {
733 // 'http://www.w3.org/2000/svg:script' -> 'script'
734 $parts = explode( ':', strtolower( $name ) );
735 return array_pop( $parts );
736 }
737
738 /**
739 * Generic wrapper function for a virus scanner program.
740 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
741 * $wgAntivirusRequired may be used to deny upload if the scan fails.
742 *
743 * @param string $file Pathname to the temporary upload file
744 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
745 * or a string containing feedback from the virus scanner if a virus was found.
746 * If textual feedback is missing but a virus was found, this function returns true.
747 */
748 function detectVirus( $file ) {
749 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
750
751 if ( !$wgAntivirus ) {
752 wfDebug( __METHOD__ . ": virus scanner disabled\n" );
753 return NULL;
754 }
755
756 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
757 wfDebug( __METHOD__ . ": unknown virus scanner: $wgAntivirus\n" );
758 $wgOut->wrapWikiMsg( '<div class="error">$1</div>', array( 'virus-badscanner', $wgAntivirus ) );
759 return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
760 }
761
762 # look up scanner configuration
763 $command = $wgAntivirusSetup[$wgAntivirus]["command"];
764 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]["codemap"];
765 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]["messagepattern"] ) ?
766 $wgAntivirusSetup[$wgAntivirus]["messagepattern"] : null;
767
768 if ( strpos( $command,"%f" ) === false ) {
769 # simple pattern: append file to scan
770 $command .= " " . wfEscapeShellArg( $file );
771 } else {
772 # complex pattern: replace "%f" with file to scan
773 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
774 }
775
776 wfDebug( __METHOD__ . ": running virus scan: $command \n" );
777
778 # execute virus scanner
779 $exitCode = false;
780
781 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
782 # that does not seem to be worth the pain.
783 # Ask me (Duesentrieb) about it if it's ever needed.
784 $output = array();
785 if ( wfIsWindows() ) {
786 exec( "$command", $output, $exitCode );
787 } else {
788 exec( "$command 2>&1", $output, $exitCode );
789 }
790
791 # map exit code to AV_xxx constants.
792 $mappedCode = $exitCode;
793 if ( $exitCodeMap ) {
794 if ( isset( $exitCodeMap[$exitCode] ) ) {
795 $mappedCode = $exitCodeMap[$exitCode];
796 } elseif ( isset( $exitCodeMap["*"] ) ) {
797 $mappedCode = $exitCodeMap["*"];
798 }
799 }
800
801 if ( $mappedCode === AV_SCAN_FAILED ) {
802 # scan failed (code was mapped to false by $exitCodeMap)
803 wfDebug( __METHOD__ . ": failed to scan $file (code $exitCode).\n" );
804
805 if ( $wgAntivirusRequired ) {
806 return wfMsg( 'virus-scanfailed', array( $exitCode ) );
807 } else {
808 return NULL;
809 }
810 } else if ( $mappedCode === AV_SCAN_ABORTED ) {
811 # scan failed because filetype is unknown (probably imune)
812 wfDebug( __METHOD__ . ": unsupported file type $file (code $exitCode).\n" );
813 return NULL;
814 } else if ( $mappedCode === AV_NO_VIRUS ) {
815 # no virus found
816 wfDebug( __METHOD__ . ": file passed virus scan.\n" );
817 return false;
818 } else {
819 $output = join( "\n", $output );
820 $output = trim( $output );
821
822 if ( !$output ) {
823 $output = true; #if there's no output, return true
824 } elseif ( $msgPattern ) {
825 $groups = array();
826 if ( preg_match( $msgPattern, $output, $groups ) ) {
827 if ( $groups[1] ) {
828 $output = $groups[1];
829 }
830 }
831 }
832
833 wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output \n" );
834 return $output;
835 }
836 }
837
838 /**
839 * Check if the temporary file is MacBinary-encoded, as some uploads
840 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
841 * If so, the data fork will be extracted to a second temporary file,
842 * which will then be checked for validity and either kept or discarded.
843 *
844 * @access private
845 */
846 function checkMacBinary() {
847 $macbin = new MacBinary( $this->mTempPath );
848 if( $macbin->isValid() ) {
849 $dataFile = tempnam( wfTempDir(), 'WikiMacBinary' );
850 $dataHandle = fopen( $dataFile, 'wb' );
851
852 wfDebug( __METHOD__ . ": Extracting MacBinary data fork to $dataFile\n" );
853 $macbin->extractData( $dataHandle );
854
855 $this->mTempPath = $dataFile;
856 $this->mFileSize = $macbin->dataForkLength();
857
858 // We'll have to manually remove the new file if it's not kept.
859 $this->mRemoveTempFile = true;
860 }
861 $macbin->close();
862 }
863
864 /**
865 * Check if there's an overwrite conflict and, if so, if restrictions
866 * forbid this user from performing the upload.
867 *
868 * @return mixed true on success, WikiError on failure
869 * @access private
870 */
871 function checkOverwrite() {
872 global $wgUser;
873 // First check whether the local file can be overwritten
874 if( $this->mLocalFile->exists() )
875 if( !self::userCanReUpload( $wgUser, $this->mLocalFile ) )
876 return 'fileexists-forbidden';
877
878 // Check shared conflicts
879 $file = wfFindFile( $this->mLocalFile->getName() );
880 if ( $file && ( !$wgUser->isAllowed( 'reupload' ) ||
881 !$wgUser->isAllowed( 'reupload-shared' ) ) )
882 return 'fileexists-shared-forbidden';
883
884 return true;
885 }
886
887 /**
888 * Check if a user is the last uploader
889 *
890 * @param User $user
891 * @param string $img, image name
892 * @return bool
893 */
894 public static function userCanReUpload( User $user, $img ) {
895 if( $user->isAllowed( 'reupload' ) )
896 return true; // non-conditional
897 if( !$user->isAllowed( 'reupload-own' ) )
898 return false;
899 if( is_string( $img ) )
900 $img = wfLocalFile( $img );
901 if ( !( $img instanceof LocalFile ) )
902 return false;
903
904 return $user->getId() == $img->getUser( 'id' );
905 }
906
907 public static function getExistsWarning( $file ) {
908 if( $file->exists() )
909 return array( 'exists', $file );
910
911 if( $file->getTitle()->getArticleID() )
912 return array( 'page-exists', $file );
913
914 if( strpos( $file->getName(), '.' ) == false ) {
915 $partname = $file->getName();
916 $rawExtension = '';
917 } else {
918 $n = strrpos( $file->getName(), '.' );
919 $rawExtension = substr( $file->getName(), $n + 1 );
920 $partname = substr( $file->getName(), 0, $n );
921 }
922
923 if ( $rawExtension != $file->getExtension() ) {
924 // We're not using the normalized form of the extension.
925 // Normal form is lowercase, using most common of alternate
926 // extensions (eg 'jpg' rather than 'JPEG').
927 //
928 // Check for another file using the normalized form...
929 $nt_lc = Title::makeTitle( NS_FILE, $partname . '.' . $file->getExtension() );
930 $file_lc = wfLocalFile( $nt_lc );
931
932 if( $file_lc->exists() )
933 return array( 'exists-normalized', $file_lc );
934 }
935
936 if ( self::isThumbName( $file->getName() ) ) {
937 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
938 $nt_thb = Title::newFromText( substr( $partname , strpos( $partname , '-' ) +1 ) . '.' . $rawExtension );
939 $file_thb = wfLocalFile( $nt_thb );
940 if( $file_thb->exists() )
941 return array( 'thumb', $file_thb );
942 }
943
944 return false;
945 }
946
947 public static function isThumbName( $filename ) {
948 $n = strrpos( $filename, '.' );
949 $partname = $n ? substr( $filename, 0, $n ) : $filename;
950 return (
951 substr( $partname , 3, 3 ) == 'px-' ||
952 substr( $partname , 2, 3 ) == 'px-'
953 ) &&
954 ereg( "[0-9]{2}" , substr( $partname , 0, 2) );
955 }
956
957 /**
958 * Get a list of blacklisted filename prefixes from [[MediaWiki:filename-prefix-blacklist]]
959 *
960 * @return array list of prefixes
961 */
962 public static function getFilenamePrefixBlacklist() {
963 $blacklist = array();
964 $message = wfMsgForContent( 'filename-prefix-blacklist' );
965 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) || $message == '-' ) ) {
966 $lines = explode( "\n", $message );
967 foreach( $lines as $line ) {
968 // Remove comment lines
969 $comment = substr( trim( $line ), 0, 1 );
970 if ( $comment == '#' || $comment == '' ) {
971 continue;
972 }
973 // Remove additional comments after a prefix
974 $comment = strpos( $line, '#' );
975 if ( $comment > 0 ) {
976 $line = substr( $line, 0, $comment-1 );
977 }
978 $blacklist[] = trim( $line );
979 }
980 }
981 return $blacklist;
982 }
983
984 }