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