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