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