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