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