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