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