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