2bb89479d4f1f28467067761bf488b78456389a3
[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
35 const SESSION_VERSION = 2;
36
37 /**
38 * Returns true if uploads are enabled.
39 * Can be override by subclasses.
40 */
41 public static function isEnabled() {
42 global $wgEnableUploads;
43 if ( !$wgEnableUploads )
44 return false;
45
46 # Check php's file_uploads setting
47 if( !wfIniGetBool( 'file_uploads' ) ) {
48 return false;
49 }
50 return true;
51 }
52
53 /**
54 * Returns true if the user can use this upload module or else a string
55 * identifying the missing permission.
56 * Can be overriden by subclasses.
57 */
58 public static function isAllowed( $user ) {
59 if( !$user->isAllowed( 'upload' ) )
60 return 'upload';
61 return true;
62 }
63
64 // Upload handlers. Should probably just be a global
65 static $uploadHandlers = array( 'Stash', 'File', 'Url' );
66
67 /**
68 * Create a form of UploadBase depending on wpSourceType and initializes it
69 */
70 public static function createFromRequest( &$request, $type = null ) {
71 $type = $type ? $type : $request->getVal( 'wpSourceType', 'File' );
72
73 if( !$type )
74 return null;
75
76 // Get the upload class
77 $type = ucfirst( $type );
78
79 // Give hooks the chance to handle this request
80 $className = null;
81 wfRunHooks( 'UploadCreateFromRequest', array( $type, &$className ) );
82 if ( is_null( $className ) ) {
83 $className = 'UploadFrom' . $type;
84 wfDebug( __METHOD__ . ": class name: $className\n" );
85 if( !in_array( $type, self::$uploadHandlers ) )
86 return null;
87 }
88
89 // Check whether this upload class is enabled
90 if( !call_user_func( array( $className, 'isEnabled' ) ) )
91 return null;
92
93 // Check whether the request is valid
94 if( !call_user_func( array( $className, 'isValidRequest' ), $request ) )
95 return null;
96
97 $handler = new $className;
98
99 $handler->initializeFromRequest( $request );
100 return $handler;
101 }
102
103 /**
104 * Check whether a request if valid for this handler
105 */
106 public static function isValidRequest( $request ) {
107 return false;
108 }
109
110 public function __construct() {}
111
112 /**
113 * Do the real variable initialization
114 */
115 public function initialize( $name, $tempPath, $fileSize, $removeTempFile = false ) {
116 $this->mDesiredDestName = $name;
117 $this->mTempPath = $tempPath;
118 $this->mFileSize = $fileSize;
119 $this->mRemoveTempFile = $removeTempFile;
120 }
121
122 /**
123 * Initialize from a WebRequest. Override this in a subclass.
124 */
125 public abstract function initializeFromRequest( &$request );
126
127 /**
128 * Fetch the file. Usually a no-op
129 */
130 public function fetchFile() {
131 return Status::newGood();
132 }
133
134 /**
135 * Return the file size
136 */
137 public function isEmptyFile(){
138 return empty( $this->mFileSize );
139 }
140
141 /**
142 * getRealPath
143 * @param string $srcPath the source path
144 * @returns the real path if it was a virtual url
145 */
146 function getRealPath( $srcPath ){
147 $repo = RepoGroup::singleton()->getLocalRepo();
148 if ( $repo->isVirtualUrl( $srcPath ) ) {
149 return $repo->resolveVirtualUrl( $srcPath );
150 }
151 return $srcPath;
152 }
153
154 /**
155 * Verify whether the upload is sane.
156 * Returns self::OK or else an array with error information
157 */
158 public function verifyUpload() {
159 /**
160 * If there was no filename or a zero size given, give up quick.
161 */
162 if( $this->isEmptyFile() )
163 return array( 'status' => self::EMPTY_FILE );
164
165 /**
166 * Look at the contents of the file; if we can recognize the
167 * type but it's corrupt or data of the wrong type, we should
168 * probably not accept it.
169 */
170 $verification = $this->verifyFile();
171 if( $verification !== true ) {
172 if( !is_array( $verification ) )
173 $verification = array( $verification );
174 return array( 'status' => self::VERIFICATION_ERROR,
175 'details' => $verification );
176
177 }
178
179 $nt = $this->getTitle();
180 if( is_null( $nt ) ) {
181 $result = array( 'status' => $this->mTitleError );
182 if( $this->mTitleError == self::ILLEGAL_FILENAME )
183 $result['filtered'] = $this->mFilteredName;
184 if ( $this->mTitleError == self::FILETYPE_BADTYPE )
185 $result['finalExt'] = $this->mFinalExtension;
186 return $result;
187 }
188 $this->mDestName = $this->getLocalFile()->getName();
189
190 /**
191 * In some cases we may forbid overwriting of existing files.
192 */
193 $overwrite = $this->checkOverwrite();
194 if( $overwrite !== true )
195 return array( 'status' => self::OVERWRITE_EXISTING_FILE, 'overwrite' => $overwrite );
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::HOOK_ABORTED, '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 * Stash a file in a temporary directory for later processing,
476 * and save the necessary descriptive info into the session.
477 * Returns a key value which will be passed through a form
478 * to pick up the path info on a later invocation.
479 *
480 * @return int Session key
481 */
482 public function stashSession() {
483 $status = $this->saveTempUploadedFile( $this->mDestName, $this->mTempPath );
484 if( !$status->isOK() ) {
485 # Couldn't save the file.
486 return false;
487 }
488 if(!isset($_SESSION))
489 session_start(); // start up the session (might have been previously closed to prevent php session locking)
490 $key = $this->getSessionKey();
491 $_SESSION['wsUploadData'][$key] = array(
492 'mTempPath' => $status->value,
493 'mFileSize' => $this->mFileSize,
494 'mFileProps' => $this->mFileProps,
495 'version' => self::SESSION_VERSION,
496 );
497 return $key;
498 }
499
500 /**
501 * Generate a random session key from stash in cases where we want to start an upload without much information
502 */
503 protected function getSessionKey(){
504 $key = mt_rand( 0, 0x7fffffff );
505 $_SESSION['wsUploadData'][$key] = array();
506 return $key;
507 }
508
509
510 /**
511 * If we've modified the upload file we need to manually remove it
512 * on exit to clean up.
513 * @access private
514 */
515 public function cleanupTempFile() {
516 if ( $this->mRemoveTempFile && $this->mTempPath && file_exists( $this->mTempPath ) ) {
517 wfDebug( __METHOD__ . ": Removing temporary file {$this->mTempPath}\n" );
518 unlink( $this->mTempPath );
519 }
520 }
521
522 public function getTempPath() {
523 return $this->mTempPath;
524 }
525
526 /**
527 * Split a file into a base name and all dot-delimited 'extensions'
528 * on the end. Some web server configurations will fall back to
529 * earlier pseudo-'extensions' to determine type and execute
530 * scripts, so the blacklist needs to check them all.
531 *
532 * @return array
533 */
534 public static function splitExtensions( $filename ) {
535 $bits = explode( '.', $filename );
536 $basename = array_shift( $bits );
537 return array( $basename, $bits );
538 }
539
540 /**
541 * Perform case-insensitive match against a list of file extensions.
542 * Returns true if the extension is in the list.
543 *
544 * @param string $ext
545 * @param array $list
546 * @return bool
547 */
548 public static function checkFileExtension( $ext, $list ) {
549 return in_array( strtolower( $ext ), $list );
550 }
551
552 /**
553 * Perform case-insensitive match against a list of file extensions.
554 * Returns true if any of the extensions are in the list.
555 *
556 * @param array $ext
557 * @param array $list
558 * @return bool
559 */
560 public static function checkFileExtensionList( $ext, $list ) {
561 foreach( $ext as $e ) {
562 if( in_array( strtolower( $e ), $list ) ) {
563 return true;
564 }
565 }
566 return false;
567 }
568
569 /**
570 * Checks if the mime type of the uploaded file matches the file extension.
571 *
572 * @param string $mime the mime type of the uploaded file
573 * @param string $extension The filename extension that the file is to be served with
574 * @return bool
575 */
576 public static function verifyExtension( $mime, $extension ) {
577 $magic = MimeMagic::singleton();
578
579 if ( !$mime || $mime == 'unknown' || $mime == 'unknown/unknown' )
580 if ( !$magic->isRecognizableExtension( $extension ) ) {
581 wfDebug( __METHOD__ . ": passing file with unknown detected mime type; " .
582 "unrecognized extension '$extension', can't verify\n" );
583 return true;
584 } else {
585 wfDebug( __METHOD__ . ": rejecting file with unknown detected mime type; ".
586 "recognized extension '$extension', so probably invalid file\n" );
587 return false;
588 }
589
590 $match = $magic->isMatchingExtension( $extension, $mime );
591
592 if ( $match === NULL ) {
593 wfDebug( __METHOD__ . ": no file extension known for mime type $mime, passing file\n" );
594 return true;
595 } elseif( $match === true ) {
596 wfDebug( __METHOD__ . ": mime type $mime matches extension $extension, passing file\n" );
597
598 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
599 return true;
600
601 } else {
602 wfDebug( __METHOD__ . ": mime type $mime mismatches file extension $extension, rejecting file\n" );
603 return false;
604 }
605 }
606
607 /**
608 * Heuristic for detecting files that *could* contain JavaScript instructions or
609 * things that may look like HTML to a browser and are thus
610 * potentially harmful. The present implementation will produce false positives in some situations.
611 *
612 * @param string $file Pathname to the temporary upload file
613 * @param string $mime The mime type of the file
614 * @param string $extension The extension of the file
615 * @return bool true if the file contains something looking like embedded scripts
616 */
617 public static function detectScript( $file, $mime, $extension ) {
618 global $wgAllowTitlesInSVG;
619
620 #ugly hack: for text files, always look at the entire file.
621 #For binary field, just check the first K.
622
623 if( strpos( $mime,'text/' ) === 0 )
624 $chunk = file_get_contents( $file );
625 else {
626 $fp = fopen( $file, 'rb' );
627 $chunk = fread( $fp, 1024 );
628 fclose( $fp );
629 }
630
631 $chunk = strtolower( $chunk );
632
633 if( !$chunk )
634 return false;
635
636 #decode from UTF-16 if needed (could be used for obfuscation).
637 if( substr( $chunk, 0, 2 ) == "\xfe\xff" )
638 $enc = "UTF-16BE";
639 elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" )
640 $enc = "UTF-16LE";
641 else
642 $enc = NULL;
643
644 if( $enc )
645 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
646
647 $chunk = trim( $chunk );
648
649 #FIXME: convert from UTF-16 if necessarry!
650 wfDebug( __METHOD__ . ": checking for embedded scripts and HTML stuff\n" );
651
652 #check for HTML doctype
653 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) )
654 return true;
655
656 /**
657 * Internet Explorer for Windows performs some really stupid file type
658 * autodetection which can cause it to interpret valid image files as HTML
659 * and potentially execute JavaScript, creating a cross-site scripting
660 * attack vectors.
661 *
662 * Apple's Safari browser also performs some unsafe file type autodetection
663 * which can cause legitimate files to be interpreted as HTML if the
664 * web server is not correctly configured to send the right content-type
665 * (or if you're really uploading plain text and octet streams!)
666 *
667 * Returns true if IE is likely to mistake the given file for HTML.
668 * Also returns true if Safari would mistake the given file for HTML
669 * when served with a generic content-type.
670 */
671 $tags = array(
672 '<a href',
673 '<body',
674 '<head',
675 '<html', #also in safari
676 '<img',
677 '<pre',
678 '<script', #also in safari
679 '<table'
680 );
681
682 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
683 $tags[] = '<title';
684 }
685
686 foreach( $tags as $tag ) {
687 if( false !== strpos( $chunk, $tag ) ) {
688 return true;
689 }
690 }
691
692 /*
693 * look for JavaScript
694 */
695
696 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
697 $chunk = Sanitizer::decodeCharReferences( $chunk );
698
699 #look for script-types
700 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) )
701 return true;
702
703 #look for html-style script-urls
704 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) )
705 return true;
706
707 #look for css-style script-urls
708 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) )
709 return true;
710
711 wfDebug( __METHOD__ . ": no scripts found\n" );
712 return false;
713 }
714
715 protected function detectScriptInSvg( $filename ) {
716 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
717 return $check->filterMatch;
718 }
719
720 /**
721 * @todo Replace this with a whitelist filter!
722 */
723 public function checkSvgScriptCallback( $element, $attribs ) {
724 $stripped = $this->stripXmlNamespace( $element );
725
726 if( $stripped == 'script' ) {
727 wfDebug( __METHOD__ . ": Found script element '$element' in uploaded file.\n" );
728 return true;
729 }
730
731 foreach( $attribs as $attrib => $value ) {
732 $stripped = $this->stripXmlNamespace( $attrib );
733 if( substr( $stripped, 0, 2 ) == 'on' ) {
734 wfDebug( __METHOD__ . ": Found script attribute '$attrib'='value' in uploaded file.\n" );
735 return true;
736 }
737 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
738 wfDebug( __METHOD__ . ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
739 return true;
740 }
741 }
742 }
743
744 private function stripXmlNamespace( $name ) {
745 // 'http://www.w3.org/2000/svg:script' -> 'script'
746 $parts = explode( ':', strtolower( $name ) );
747 return array_pop( $parts );
748 }
749
750 /**
751 * Generic wrapper function for a virus scanner program.
752 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
753 * $wgAntivirusRequired may be used to deny upload if the scan fails.
754 *
755 * @param string $file Pathname to the temporary upload file
756 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
757 * or a string containing feedback from the virus scanner if a virus was found.
758 * If textual feedback is missing but a virus was found, this function returns true.
759 */
760 public static function detectVirus( $file ) {
761 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
762
763 if ( !$wgAntivirus ) {
764 wfDebug( __METHOD__ . ": virus scanner disabled\n" );
765 return NULL;
766 }
767
768 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
769 wfDebug( __METHOD__ . ": unknown virus scanner: $wgAntivirus\n" );
770 $wgOut->wrapWikiMsg( '<div class="error">$1</div>', array( 'virus-badscanner', $wgAntivirus ) );
771 return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
772 }
773
774 # look up scanner configuration
775 $command = $wgAntivirusSetup[$wgAntivirus]["command"];
776 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]["codemap"];
777 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]["messagepattern"] ) ?
778 $wgAntivirusSetup[$wgAntivirus]["messagepattern"] : null;
779
780 if ( strpos( $command,"%f" ) === false ) {
781 # simple pattern: append file to scan
782 $command .= " " . wfEscapeShellArg( $file );
783 } else {
784 # complex pattern: replace "%f" with file to scan
785 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
786 }
787
788 wfDebug( __METHOD__ . ": running virus scan: $command \n" );
789
790 # execute virus scanner
791 $exitCode = false;
792
793 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
794 # that does not seem to be worth the pain.
795 # Ask me (Duesentrieb) about it if it's ever needed.
796 $output = array();
797 if ( wfIsWindows() ) {
798 exec( "$command", $output, $exitCode );
799 } else {
800 exec( "$command 2>&1", $output, $exitCode );
801 }
802
803 # map exit code to AV_xxx constants.
804 $mappedCode = $exitCode;
805 if ( $exitCodeMap ) {
806 if ( isset( $exitCodeMap[$exitCode] ) ) {
807 $mappedCode = $exitCodeMap[$exitCode];
808 } elseif ( isset( $exitCodeMap["*"] ) ) {
809 $mappedCode = $exitCodeMap["*"];
810 }
811 }
812
813 if ( $mappedCode === AV_SCAN_FAILED ) {
814 # scan failed (code was mapped to false by $exitCodeMap)
815 wfDebug( __METHOD__ . ": failed to scan $file (code $exitCode).\n" );
816
817 if ( $wgAntivirusRequired ) {
818 return wfMsg( 'virus-scanfailed', array( $exitCode ) );
819 } else {
820 return NULL;
821 }
822 } else if ( $mappedCode === AV_SCAN_ABORTED ) {
823 # scan failed because filetype is unknown (probably imune)
824 wfDebug( __METHOD__ . ": unsupported file type $file (code $exitCode).\n" );
825 return NULL;
826 } else if ( $mappedCode === AV_NO_VIRUS ) {
827 # no virus found
828 wfDebug( __METHOD__ . ": file passed virus scan.\n" );
829 return false;
830 } else {
831 $output = join( "\n", $output );
832 $output = trim( $output );
833
834 if ( !$output ) {
835 $output = true; #if there's no output, return true
836 } elseif ( $msgPattern ) {
837 $groups = array();
838 if ( preg_match( $msgPattern, $output, $groups ) ) {
839 if ( $groups[1] ) {
840 $output = $groups[1];
841 }
842 }
843 }
844
845 wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output \n" );
846 return $output;
847 }
848 }
849
850 /**
851 * Check if the temporary file is MacBinary-encoded, as some uploads
852 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
853 * If so, the data fork will be extracted to a second temporary file,
854 * which will then be checked for validity and either kept or discarded.
855 *
856 * @access private
857 */
858 private function checkMacBinary() {
859 $macbin = new MacBinary( $this->mTempPath );
860 if( $macbin->isValid() ) {
861 $dataFile = tempnam( wfTempDir(), 'WikiMacBinary' );
862 $dataHandle = fopen( $dataFile, 'wb' );
863
864 wfDebug( __METHOD__ . ": Extracting MacBinary data fork to $dataFile\n" );
865 $macbin->extractData( $dataHandle );
866
867 $this->mTempPath = $dataFile;
868 $this->mFileSize = $macbin->dataForkLength();
869
870 // We'll have to manually remove the new file if it's not kept.
871 $this->mRemoveTempFile = true;
872 }
873 $macbin->close();
874 }
875
876 /**
877 * Check if there's an overwrite conflict and, if so, if restrictions
878 * forbid this user from performing the upload.
879 *
880 * @return mixed true on success, error string on failure
881 * @access private
882 */
883 private function checkOverwrite() {
884 global $wgUser;
885 // First check whether the local file can be overwritten
886 $file = $this->getLocalFile();
887 if( $file->exists() ) {
888 if( !self::userCanReUpload( $wgUser, $file ) )
889 return 'fileexists-forbidden';
890 else
891 return true;
892 }
893
894 /* Check shared conflicts: if the local file does not exist, but
895 * wfFindFile finds a file, it exists in a shared repository.
896 */
897 $file = wfFindFile( $this->getTitle() );
898 if ( $file && !$wgUser->isAllowed( 'reupload-shared' ) )
899 return 'fileexists-shared-forbidden';
900
901 return true;
902 }
903
904 /**
905 * Check if a user is the last uploader
906 *
907 * @param User $user
908 * @param string $img, image name
909 * @return bool
910 */
911 public static function userCanReUpload( User $user, $img ) {
912 if( $user->isAllowed( 'reupload' ) )
913 return true; // non-conditional
914 if( !$user->isAllowed( 'reupload-own' ) )
915 return false;
916 if( is_string( $img ) )
917 $img = wfLocalFile( $img );
918 if ( !( $img instanceof LocalFile ) )
919 return false;
920
921 return $user->getId() == $img->getUser( 'id' );
922 }
923
924 /**
925 * Helper function that does various existence checks for a file.
926 * The following checks are performed:
927 * - The file exists
928 * - Article with the same name as the file exists
929 * - File exists with normalized extension
930 * - The file looks like a thumbnail and the original exists
931 *
932 * @param File $file The file to check
933 * @return mixed False if the file does not exists, else an array
934 */
935 public static function getExistsWarning( $file ) {
936 if( $file->exists() )
937 return array( 'warning' => 'exists', 'file' => $file );
938
939 if( $file->getTitle()->getArticleID() )
940 return array( 'warning' => 'page-exists', 'file' => $file );
941
942 if ( $file->wasDeleted() && !$file->exists() )
943 return array( 'warning' => 'was-deleted', 'file' => $file );
944
945 if( strpos( $file->getName(), '.' ) == false ) {
946 $partname = $file->getName();
947 $extension = '';
948 } else {
949 $n = strrpos( $file->getName(), '.' );
950 $extension = substr( $file->getName(), $n + 1 );
951 $partname = substr( $file->getName(), 0, $n );
952 }
953 $normalizedExtension = File::normalizeExtension( $extension );
954
955 if ( $normalizedExtension != $extension ) {
956 // We're not using the normalized form of the extension.
957 // Normal form is lowercase, using most common of alternate
958 // extensions (eg 'jpg' rather than 'JPEG').
959 //
960 // Check for another file using the normalized form...
961 $nt_lc = Title::makeTitle( NS_FILE, "{$partname}.{$normalizedExtension}" );
962 $file_lc = wfLocalFile( $nt_lc );
963
964 if( $file_lc->exists() )
965 return array( 'warning' => 'exists-normalized', 'file' => $file, 'normalizedFile' => $file_lc );
966 }
967
968 if ( self::isThumbName( $file->getName() ) ) {
969 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
970 $nt_thb = Title::newFromText( substr( $partname , strpos( $partname , '-' ) +1 ) . '.' . $extension, NS_FILE );
971 $file_thb = wfLocalFile( $nt_thb );
972 if( $file_thb->exists() )
973 return array( 'warning' => 'thumb', 'file' => $file, 'thumbFile' => $file_thb );
974 else
975 // File does not exist, but we just don't like the name
976 return array( 'warning' => 'thumb-name', 'file' => $file, 'thumbFile' => $file_thb );
977 }
978
979
980 foreach( self::getFilenamePrefixBlacklist() as $prefix ) {
981 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix )
982 return array( 'warning' => 'bad-prefix', 'file' => $file, 'prefix' => $prefix );
983 }
984
985
986
987 return false;
988 }
989
990 /**
991 * Helper function that checks whether the filename looks like a thumbnail
992 */
993 public static function isThumbName( $filename ) {
994 $n = strrpos( $filename, '.' );
995 $partname = $n ? substr( $filename, 0, $n ) : $filename;
996 return (
997 substr( $partname , 3, 3 ) == 'px-' ||
998 substr( $partname , 2, 3 ) == 'px-'
999 ) &&
1000 preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) );
1001 }
1002
1003 /**
1004 * Get a list of blacklisted filename prefixes from [[MediaWiki:filename-prefix-blacklist]]
1005 *
1006 * @return array list of prefixes
1007 */
1008 public static function getFilenamePrefixBlacklist() {
1009 $blacklist = array();
1010 $message = wfMsgForContent( 'filename-prefix-blacklist' );
1011 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) || $message == '-' ) ) {
1012 $lines = explode( "\n", $message );
1013 foreach( $lines as $line ) {
1014 // Remove comment lines
1015 $comment = substr( trim( $line ), 0, 1 );
1016 if ( $comment == '#' || $comment == '' ) {
1017 continue;
1018 }
1019 // Remove additional comments after a prefix
1020 $comment = strpos( $line, '#' );
1021 if ( $comment > 0 ) {
1022 $line = substr( $line, 0, $comment-1 );
1023 }
1024 $blacklist[] = trim( $line );
1025 }
1026 }
1027 return $blacklist;
1028 }
1029
1030 }