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