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