* bug 21063 http copy upload and upload from stash give different file path types...
[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 global $wgCapitalLinks, $wgContLang;
309 if ( $wgCapitalLinks ) {
310 $comparableName = $wgContLang->ucfirst( $comparableName );
311 }
312 if( $this->mDesiredDestName != $filename && $comparableName != $filename )
313 $warnings['badfilename'] = $filename;
314
315 // Check whether the file extension is on the unwanted list
316 global $wgCheckFileExtensions, $wgFileExtensions;
317 if ( $wgCheckFileExtensions ) {
318 if ( !$this->checkFileExtension( $this->mFinalExtension, $wgFileExtensions ) )
319 $warnings['filetype-unwanted-type'] = $this->mFinalExtension;
320 }
321
322 global $wgUploadSizeWarning;
323 if ( $wgUploadSizeWarning && ( $this->mFileSize > $wgUploadSizeWarning ) )
324 $warnings['large-file'] = $wgUploadSizeWarning;
325
326 if ( $this->mFileSize == 0 )
327 $warnings['emptyfile'] = true;
328
329
330 $exists = self::getExistsWarning( $localFile );
331 if( $exists !== false )
332 $warnings['exists'] = $exists;
333
334 // Check dupes against existing files
335 $hash = File::sha1Base36( $this->mTempPath );
336 $dupes = RepoGroup::singleton()->findBySha1( $hash );
337 $title = $this->getTitle();
338 // Remove all matches against self
339 foreach ( $dupes as $key => $dupe ) {
340 if( $title->equals( $dupe->getTitle() ) )
341 unset( $dupes[$key] );
342 }
343 if( $dupes )
344 $warnings['duplicate'] = $dupes;
345
346 // Check dupes against archives
347 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
348 if ( $archivedImage->getID() > 0 )
349 $warnings['duplicate-archive'] = $archivedImage->getName();
350
351 return $warnings;
352 }
353
354 /**
355 * Really perform the upload. Stores the file in the local repo, watches
356 * if necessary and runs the UploadComplete hook.
357 *
358 * @return mixed Status indicating the whether the upload succeeded.
359 */
360 public function performUpload( $comment, $pageText, $watch, $user ) {
361 wfDebug( "\n\n\performUpload: sum:" . $comment . ' c: ' . $pageText . ' w:' . $watch );
362 $status = $this->getLocalFile()->upload( $this->mTempPath, $comment, $pageText,
363 File::DELETE_SOURCE, $this->mFileProps, false, $user );
364
365 if( $status->isGood() && $watch )
366 $user->addWatch( $this->getLocalFile()->getTitle() );
367
368 if( $status->isGood() )
369 wfRunHooks( 'UploadComplete', array( &$this ) );
370
371 return $status;
372 }
373
374 /**
375 * Returns the title of the file to be uploaded. Sets mTitleError in case
376 * the name was illegal.
377 *
378 * @return Title The title of the file or null in case the name was illegal
379 */
380 public function getTitle() {
381 if ( $this->mTitle !== false )
382 return $this->mTitle;
383
384 /**
385 * Chop off any directories in the given filename. Then
386 * filter out illegal characters, and try to make a legible name
387 * out of it. We'll strip some silently that Title would die on.
388 */
389 $basename = $this->mDesiredDestName;
390
391 $this->mFilteredName = wfStripIllegalFilenameChars( $basename );
392 /* Normalize to title form before we do any further processing */
393 $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
394 if( is_null( $nt ) ) {
395 $this->mTitleError = self::ILLEGAL_FILENAME;
396 return $this->mTitle = null;
397 }
398 $this->mFilteredName = $nt->getDBkey();
399
400 /**
401 * We'll want to blacklist against *any* 'extension', and use
402 * only the final one for the whitelist.
403 */
404 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName );
405
406 if( count( $ext ) ) {
407 $this->mFinalExtension = trim( $ext[count( $ext ) - 1] );
408 } else {
409 $this->mFinalExtension = '';
410 }
411
412 /* Don't allow users to override the blacklist (check file extension) */
413 global $wgCheckFileExtensions, $wgStrictFileExtensions;
414 global $wgFileExtensions, $wgFileBlacklist;
415 if ( $this->mFinalExtension == '' ) {
416 $this->mTitleError = self::FILETYPE_MISSING;
417 return $this->mTitle = null;
418 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
419 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
420 !$this->checkFileExtension( $this->mFinalExtension, $wgFileExtensions ) ) ) {
421 $this->mTitleError = self::FILETYPE_BADTYPE;
422 return $this->mTitle = null;
423 }
424
425 # If there was more than one "extension", reassemble the base
426 # filename to prevent bogus complaints about length
427 if( count( $ext ) > 1 ) {
428 for( $i = 0; $i < count( $ext ) - 1; $i++ )
429 $partname .= '.' . $ext[$i];
430 }
431
432 if( strlen( $partname ) < 1 ) {
433 $this->mTitleError = self::MIN_LENGTH_PARTNAME;
434 return $this->mTitle = null;
435 }
436
437 $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
438 if( is_null( $nt ) ) {
439 $this->mTitleError = self::ILLEGAL_FILENAME;
440 return $this->mTitle = null;
441 }
442 return $this->mTitle = $nt;
443 }
444
445 /**
446 * Return the local file and initializes if necessary.
447 */
448 public function getLocalFile() {
449 if( is_null( $this->mLocalFile ) ) {
450 $nt = $this->getTitle();
451 $this->mLocalFile = is_null( $nt ) ? null : wfLocalFile( $nt );
452 }
453 return $this->mLocalFile;
454 }
455
456 /**
457 * Stash a file in a temporary directory for later processing
458 * after the user has confirmed it.
459 *
460 * If the user doesn't explicitly cancel or accept, these files
461 * can accumulate in the temp directory.
462 *
463 * @param string $saveName - the destination filename
464 * @param string $tempSrc - the source temporary file to save
465 * @return string - full path the stashed file, or false on failure
466 * @access private
467 */
468 protected function saveTempUploadedFile( $saveName, $tempSrc ) {
469 $repo = RepoGroup::singleton()->getLocalRepo();
470 $status = $repo->storeTemp( $saveName, $tempSrc );
471 return $status;
472 }
473
474 /**
475 * Append a file to a stashed file.
476 *
477 * @param string $srcPath Path to file to append from
478 * @param string $toAppendPath Path to file to append to
479 * @return Status Status
480 */
481 public function appendToUploadFile( $srcPath, $toAppendPath ){
482 $repo = RepoGroup::singleton()->getLocalRepo();
483 $status = $repo->append( $srcPath, $toAppendPath );
484 return $status;
485 }
486
487 /**
488 * Stash a file in a temporary directory for later processing,
489 * and save the necessary descriptive info into the session.
490 * Returns a key value which will be passed through a form
491 * to pick up the path info on a later invocation.
492 *
493 * @return int Session key
494 */
495 public function stashSession() {
496 $status = $this->saveTempUploadedFile( $this->mDestName, $this->mTempPath );
497 if( !$status->isOK() ) {
498 # Couldn't save the file.
499 return false;
500 }
501 if(!isset($_SESSION))
502 session_start(); // start up the session (might have been previously closed to prevent php session locking)
503 $key = $this->getSessionKey();
504 $_SESSION['wsUploadData'][$key] = array(
505 'mTempPath' => $status->value,
506 'mFileSize' => $this->mFileSize,
507 'mFileProps' => $this->mFileProps,
508 'version' => self::SESSION_VERSION,
509 );
510 return $key;
511 }
512
513 /**
514 * Generate a random session key from stash in cases where we want to start an upload without much information
515 */
516 protected function getSessionKey(){
517 $key = mt_rand( 0, 0x7fffffff );
518 $_SESSION['wsUploadData'][$key] = array();
519 return $key;
520 }
521
522 /**
523 * Remove a temporarily kept file stashed by saveTempUploadedFile().
524 * @return success
525 */
526 public function unsaveUploadedFile() {
527 $repo = RepoGroup::singleton()->getLocalRepo();
528 $success = $repo->freeTemp( $this->mTempPath );
529 return $success;
530 }
531
532 /**
533 * If we've modified the upload file we need to manually remove it
534 * on exit to clean up.
535 * @access private
536 */
537 public function cleanupTempFile() {
538 if ( $this->mRemoveTempFile && $this->mTempPath && file_exists( $this->mTempPath ) ) {
539 wfDebug( __METHOD__ . ": Removing temporary file {$this->mTempPath}\n" );
540 unlink( $this->mTempPath );
541 }
542 }
543
544 public function getTempPath() {
545 return $this->mTempPath;
546 }
547
548 /**
549 * Split a file into a base name and all dot-delimited 'extensions'
550 * on the end. Some web server configurations will fall back to
551 * earlier pseudo-'extensions' to determine type and execute
552 * scripts, so the blacklist needs to check them all.
553 *
554 * @return array
555 */
556 public static function splitExtensions( $filename ) {
557 $bits = explode( '.', $filename );
558 $basename = array_shift( $bits );
559 return array( $basename, $bits );
560 }
561
562 /**
563 * Perform case-insensitive match against a list of file extensions.
564 * Returns true if the extension is in the list.
565 *
566 * @param string $ext
567 * @param array $list
568 * @return bool
569 */
570 public static function checkFileExtension( $ext, $list ) {
571 return in_array( strtolower( $ext ), $list );
572 }
573
574 /**
575 * Perform case-insensitive match against a list of file extensions.
576 * Returns true if any of the extensions are in the list.
577 *
578 * @param array $ext
579 * @param array $list
580 * @return bool
581 */
582 public static function checkFileExtensionList( $ext, $list ) {
583 foreach( $ext as $e ) {
584 if( in_array( strtolower( $e ), $list ) ) {
585 return true;
586 }
587 }
588 return false;
589 }
590
591 /**
592 * Checks if the mime type of the uploaded file matches the file extension.
593 *
594 * @param string $mime the mime type of the uploaded file
595 * @param string $extension The filename extension that the file is to be served with
596 * @return bool
597 */
598 public static function verifyExtension( $mime, $extension ) {
599 $magic = MimeMagic::singleton();
600
601 if ( !$mime || $mime == 'unknown' || $mime == 'unknown/unknown' )
602 if ( !$magic->isRecognizableExtension( $extension ) ) {
603 wfDebug( __METHOD__ . ": passing file with unknown detected mime type; " .
604 "unrecognized extension '$extension', can't verify\n" );
605 return true;
606 } else {
607 wfDebug( __METHOD__ . ": rejecting file with unknown detected mime type; ".
608 "recognized extension '$extension', so probably invalid file\n" );
609 return false;
610 }
611
612 $match = $magic->isMatchingExtension( $extension, $mime );
613
614 if ( $match === NULL ) {
615 wfDebug( __METHOD__ . ": no file extension known for mime type $mime, passing file\n" );
616 return true;
617 } elseif( $match === true ) {
618 wfDebug( __METHOD__ . ": mime type $mime matches extension $extension, passing file\n" );
619
620 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
621 return true;
622
623 } else {
624 wfDebug( __METHOD__ . ": mime type $mime mismatches file extension $extension, rejecting file\n" );
625 return false;
626 }
627 }
628
629 /**
630 * Heuristic for detecting files that *could* contain JavaScript instructions or
631 * things that may look like HTML to a browser and are thus
632 * potentially harmful. The present implementation will produce false positives in some situations.
633 *
634 * @param string $file Pathname to the temporary upload file
635 * @param string $mime The mime type of the file
636 * @param string $extension The extension of the file
637 * @return bool true if the file contains something looking like embedded scripts
638 */
639 public static function detectScript( $file, $mime, $extension ) {
640 global $wgAllowTitlesInSVG;
641
642 #ugly hack: for text files, always look at the entire file.
643 #For binary field, just check the first K.
644
645 if( strpos( $mime,'text/' ) === 0 )
646 $chunk = file_get_contents( $file );
647 else {
648 $fp = fopen( $file, 'rb' );
649 $chunk = fread( $fp, 1024 );
650 fclose( $fp );
651 }
652
653 $chunk = strtolower( $chunk );
654
655 if( !$chunk )
656 return false;
657
658 #decode from UTF-16 if needed (could be used for obfuscation).
659 if( substr( $chunk, 0, 2 ) == "\xfe\xff" )
660 $enc = "UTF-16BE";
661 elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" )
662 $enc = "UTF-16LE";
663 else
664 $enc = NULL;
665
666 if( $enc )
667 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
668
669 $chunk = trim( $chunk );
670
671 #FIXME: convert from UTF-16 if necessarry!
672 wfDebug( __METHOD__ . ": checking for embedded scripts and HTML stuff\n" );
673
674 #check for HTML doctype
675 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) )
676 return true;
677
678 /**
679 * Internet Explorer for Windows performs some really stupid file type
680 * autodetection which can cause it to interpret valid image files as HTML
681 * and potentially execute JavaScript, creating a cross-site scripting
682 * attack vectors.
683 *
684 * Apple's Safari browser also performs some unsafe file type autodetection
685 * which can cause legitimate files to be interpreted as HTML if the
686 * web server is not correctly configured to send the right content-type
687 * (or if you're really uploading plain text and octet streams!)
688 *
689 * Returns true if IE is likely to mistake the given file for HTML.
690 * Also returns true if Safari would mistake the given file for HTML
691 * when served with a generic content-type.
692 */
693 $tags = array(
694 '<a href',
695 '<body',
696 '<head',
697 '<html', #also in safari
698 '<img',
699 '<pre',
700 '<script', #also in safari
701 '<table'
702 );
703
704 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
705 $tags[] = '<title';
706 }
707
708 foreach( $tags as $tag ) {
709 if( false !== strpos( $chunk, $tag ) ) {
710 return true;
711 }
712 }
713
714 /*
715 * look for JavaScript
716 */
717
718 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
719 $chunk = Sanitizer::decodeCharReferences( $chunk );
720
721 #look for script-types
722 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) )
723 return true;
724
725 #look for html-style script-urls
726 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) )
727 return true;
728
729 #look for css-style script-urls
730 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) )
731 return true;
732
733 wfDebug( __METHOD__ . ": no scripts found\n" );
734 return false;
735 }
736
737 protected function detectScriptInSvg( $filename ) {
738 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
739 return $check->filterMatch;
740 }
741
742 /**
743 * @todo Replace this with a whitelist filter!
744 */
745 public function checkSvgScriptCallback( $element, $attribs ) {
746 $stripped = $this->stripXmlNamespace( $element );
747
748 if( $stripped == 'script' ) {
749 wfDebug( __METHOD__ . ": Found script element '$element' in uploaded file.\n" );
750 return true;
751 }
752
753 foreach( $attribs as $attrib => $value ) {
754 $stripped = $this->stripXmlNamespace( $attrib );
755 if( substr( $stripped, 0, 2 ) == 'on' ) {
756 wfDebug( __METHOD__ . ": Found script attribute '$attrib'='value' in uploaded file.\n" );
757 return true;
758 }
759 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
760 wfDebug( __METHOD__ . ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
761 return true;
762 }
763 }
764 }
765
766 private function stripXmlNamespace( $name ) {
767 // 'http://www.w3.org/2000/svg:script' -> 'script'
768 $parts = explode( ':', strtolower( $name ) );
769 return array_pop( $parts );
770 }
771
772 /**
773 * Generic wrapper function for a virus scanner program.
774 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
775 * $wgAntivirusRequired may be used to deny upload if the scan fails.
776 *
777 * @param string $file Pathname to the temporary upload file
778 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
779 * or a string containing feedback from the virus scanner if a virus was found.
780 * If textual feedback is missing but a virus was found, this function returns true.
781 */
782 public static function detectVirus( $file ) {
783 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
784
785 if ( !$wgAntivirus ) {
786 wfDebug( __METHOD__ . ": virus scanner disabled\n" );
787 return NULL;
788 }
789
790 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
791 wfDebug( __METHOD__ . ": unknown virus scanner: $wgAntivirus\n" );
792 $wgOut->wrapWikiMsg( '<div class="error">$1</div>', array( 'virus-badscanner', $wgAntivirus ) );
793 return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
794 }
795
796 # look up scanner configuration
797 $command = $wgAntivirusSetup[$wgAntivirus]["command"];
798 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]["codemap"];
799 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]["messagepattern"] ) ?
800 $wgAntivirusSetup[$wgAntivirus]["messagepattern"] : null;
801
802 if ( strpos( $command,"%f" ) === false ) {
803 # simple pattern: append file to scan
804 $command .= " " . wfEscapeShellArg( $file );
805 } else {
806 # complex pattern: replace "%f" with file to scan
807 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
808 }
809
810 wfDebug( __METHOD__ . ": running virus scan: $command \n" );
811
812 # execute virus scanner
813 $exitCode = false;
814
815 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
816 # that does not seem to be worth the pain.
817 # Ask me (Duesentrieb) about it if it's ever needed.
818 $output = array();
819 if ( wfIsWindows() ) {
820 exec( "$command", $output, $exitCode );
821 } else {
822 exec( "$command 2>&1", $output, $exitCode );
823 }
824
825 # map exit code to AV_xxx constants.
826 $mappedCode = $exitCode;
827 if ( $exitCodeMap ) {
828 if ( isset( $exitCodeMap[$exitCode] ) ) {
829 $mappedCode = $exitCodeMap[$exitCode];
830 } elseif ( isset( $exitCodeMap["*"] ) ) {
831 $mappedCode = $exitCodeMap["*"];
832 }
833 }
834
835 if ( $mappedCode === AV_SCAN_FAILED ) {
836 # scan failed (code was mapped to false by $exitCodeMap)
837 wfDebug( __METHOD__ . ": failed to scan $file (code $exitCode).\n" );
838
839 if ( $wgAntivirusRequired ) {
840 return wfMsg( 'virus-scanfailed', array( $exitCode ) );
841 } else {
842 return NULL;
843 }
844 } else if ( $mappedCode === AV_SCAN_ABORTED ) {
845 # scan failed because filetype is unknown (probably imune)
846 wfDebug( __METHOD__ . ": unsupported file type $file (code $exitCode).\n" );
847 return NULL;
848 } else if ( $mappedCode === AV_NO_VIRUS ) {
849 # no virus found
850 wfDebug( __METHOD__ . ": file passed virus scan.\n" );
851 return false;
852 } else {
853 $output = join( "\n", $output );
854 $output = trim( $output );
855
856 if ( !$output ) {
857 $output = true; #if there's no output, return true
858 } elseif ( $msgPattern ) {
859 $groups = array();
860 if ( preg_match( $msgPattern, $output, $groups ) ) {
861 if ( $groups[1] ) {
862 $output = $groups[1];
863 }
864 }
865 }
866
867 wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output \n" );
868 return $output;
869 }
870 }
871
872 /**
873 * Check if the temporary file is MacBinary-encoded, as some uploads
874 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
875 * If so, the data fork will be extracted to a second temporary file,
876 * which will then be checked for validity and either kept or discarded.
877 *
878 * @access private
879 */
880 private function checkMacBinary() {
881 $macbin = new MacBinary( $this->mTempPath );
882 if( $macbin->isValid() ) {
883 $dataFile = tempnam( wfTempDir(), 'WikiMacBinary' );
884 $dataHandle = fopen( $dataFile, 'wb' );
885
886 wfDebug( __METHOD__ . ": Extracting MacBinary data fork to $dataFile\n" );
887 $macbin->extractData( $dataHandle );
888
889 $this->mTempPath = $dataFile;
890 $this->mFileSize = $macbin->dataForkLength();
891
892 // We'll have to manually remove the new file if it's not kept.
893 $this->mRemoveTempFile = true;
894 }
895 $macbin->close();
896 }
897
898 /**
899 * Check if there's an overwrite conflict and, if so, if restrictions
900 * forbid this user from performing the upload.
901 *
902 * @return mixed true on success, error string on failure
903 * @access private
904 */
905 private function checkOverwrite() {
906 global $wgUser;
907 // First check whether the local file can be overwritten
908 $file = $this->getLocalFile();
909 if( $file->exists() ) {
910 if( !self::userCanReUpload( $wgUser, $file ) )
911 return 'fileexists-forbidden';
912 else
913 return true;
914 }
915
916 /* Check shared conflicts: if the local file does not exist, but
917 * wfFindFile finds a file, it exists in a shared repository.
918 */
919 $file = wfFindFile( $this->getTitle() );
920 if ( $file && !$wgUser->isAllowed( 'reupload-shared' ) )
921 return 'fileexists-shared-forbidden';
922
923 return true;
924 }
925
926 /**
927 * Check if a user is the last uploader
928 *
929 * @param User $user
930 * @param string $img, image name
931 * @return bool
932 */
933 public static function userCanReUpload( User $user, $img ) {
934 if( $user->isAllowed( 'reupload' ) )
935 return true; // non-conditional
936 if( !$user->isAllowed( 'reupload-own' ) )
937 return false;
938 if( is_string( $img ) )
939 $img = wfLocalFile( $img );
940 if ( !( $img instanceof LocalFile ) )
941 return false;
942
943 return $user->getId() == $img->getUser( 'id' );
944 }
945
946 /**
947 * Helper function that does various existence checks for a file.
948 * The following checks are performed:
949 * - The file exists
950 * - Article with the same name as the file exists
951 * - File exists with normalized extension
952 * - The file looks like a thumbnail and the original exists
953 *
954 * @param File $file The file to check
955 * @return mixed False if the file does not exists, else an array
956 */
957 public static function getExistsWarning( $file ) {
958 if( $file->exists() )
959 return array( 'warning' => 'exists', 'file' => $file );
960
961 if( $file->getTitle()->getArticleID() )
962 return array( 'warning' => 'page-exists', 'file' => $file );
963
964 if ( $file->wasDeleted() && !$file->exists() )
965 return array( 'warning' => 'was-deleted', 'file' => $file );
966
967 if( strpos( $file->getName(), '.' ) == false ) {
968 $partname = $file->getName();
969 $extension = '';
970 } else {
971 $n = strrpos( $file->getName(), '.' );
972 $extension = substr( $file->getName(), $n + 1 );
973 $partname = substr( $file->getName(), 0, $n );
974 }
975 $normalizedExtension = File::normalizeExtension( $extension );
976
977 if ( $normalizedExtension != $extension ) {
978 // We're not using the normalized form of the extension.
979 // Normal form is lowercase, using most common of alternate
980 // extensions (eg 'jpg' rather than 'JPEG').
981 //
982 // Check for another file using the normalized form...
983 $nt_lc = Title::makeTitle( NS_FILE, "{$partname}.{$normalizedExtension}" );
984 $file_lc = wfLocalFile( $nt_lc );
985
986 if( $file_lc->exists() )
987 return array( 'warning' => 'exists-normalized', 'file' => $file, 'normalizedFile' => $file_lc );
988 }
989
990 if ( self::isThumbName( $file->getName() ) ) {
991 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
992 $nt_thb = Title::newFromText( substr( $partname , strpos( $partname , '-' ) +1 ) . '.' . $extension, NS_FILE );
993 $file_thb = wfLocalFile( $nt_thb );
994 if( $file_thb->exists() )
995 return array( 'warning' => 'thumb', 'file' => $file, 'thumbFile' => $file_thb );
996 else
997 // File does not exist, but we just don't like the name
998 return array( 'warning' => 'thumb-name', 'file' => $file, 'thumbFile' => $file_thb );
999 }
1000
1001
1002 foreach( self::getFilenamePrefixBlacklist() as $prefix ) {
1003 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix )
1004 return array( 'warning' => 'bad-prefix', 'file' => $file, 'prefix' => $prefix );
1005 }
1006
1007
1008
1009 return false;
1010 }
1011
1012 /**
1013 * Helper function that checks whether the filename looks like a thumbnail
1014 */
1015 public static function isThumbName( $filename ) {
1016 $n = strrpos( $filename, '.' );
1017 $partname = $n ? substr( $filename, 0, $n ) : $filename;
1018 return (
1019 substr( $partname , 3, 3 ) == 'px-' ||
1020 substr( $partname , 2, 3 ) == 'px-'
1021 ) &&
1022 preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) );
1023 }
1024
1025 /**
1026 * Get a list of blacklisted filename prefixes from [[MediaWiki:filename-prefix-blacklist]]
1027 *
1028 * @return array list of prefixes
1029 */
1030 public static function getFilenamePrefixBlacklist() {
1031 $blacklist = array();
1032 $message = wfMsgForContent( 'filename-prefix-blacklist' );
1033 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) || $message == '-' ) ) {
1034 $lines = explode( "\n", $message );
1035 foreach( $lines as $line ) {
1036 // Remove comment lines
1037 $comment = substr( trim( $line ), 0, 1 );
1038 if ( $comment == '#' || $comment == '' ) {
1039 continue;
1040 }
1041 // Remove additional comments after a prefix
1042 $comment = strpos( $line, '#' );
1043 if ( $comment > 0 ) {
1044 $line = substr( $line, 0, $comment-1 );
1045 }
1046 $blacklist[] = trim( $line );
1047 }
1048 }
1049 return $blacklist;
1050 }
1051
1052 }