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