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