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