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