09d0a3796196eea8a412d0a7ef8782afa90f4561
[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' );
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 whether this may be a thumbnail
322 if( $exists !== false && $exists[0] != 'thumb'
323 && self::isThumbName( $filename ) ){
324 // Make the title
325 $nt = $this->getTitle();
326 $warnings['file-thumbnail-no'] = substr( $filename, 0,
327 strpos( $nt->getText() , '-' ) +1 );
328 }
329
330 // Check dupes against existing files
331 $hash = File::sha1Base36( $this->mTempPath );
332 $dupes = RepoGroup::singleton()->findBySha1( $hash );
333 $title = $this->getTitle();
334 // Remove all matches against self
335 foreach ( $dupes as $key => $dupe ) {
336 if( $title->equals( $dupe->getTitle() ) )
337 unset( $dupes[$key] );
338 }
339 if( $dupes )
340 $warnings['duplicate'] = $dupes;
341
342 // Check dupes against archives
343 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
344 if ( $archivedImage->getID() > 0 )
345 $warnings['duplicate-archive'] = $archivedImage->getName();
346
347 $filenamePrefixBlacklist = self::getFilenamePrefixBlacklist();
348 foreach( $filenamePrefixBlacklist as $prefix ) {
349 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
350 $warnings['filename-bad-prefix'] = $prefix;
351 break;
352 }
353 }
354
355 # If the file existed before and was deleted, warn the user of this
356 # Don't bother doing so if the file exists now, however
357 if( $localFile->wasDeleted() && !$localFile->exists() )
358 $warnings['filewasdeleted'] = $localFile->getTitle();
359
360 return $warnings;
361 }
362
363 /**
364 * Really perform the upload. Stores the file in the local repo, watches
365 * if necessary and runs the UploadComplete hook.
366 *
367 * @return mixed Status indicating the whether the upload succeeded.
368 */
369 public function performUpload( $comment, $pageText, $watch, $user ) {
370 wfDebug( "\n\n\performUpload: sum:" . $comment . ' c: ' . $pageText . ' w:' . $watch );
371 $status = $this->getLocalFile()->upload( $this->mTempPath, $comment, $pageText,
372 File::DELETE_SOURCE, $this->mFileProps, false, $user );
373
374 if( $status->isGood() && $watch )
375 $user->addWatch( $this->getLocalFile()->getTitle() );
376
377 if( $status->isGood() )
378 wfRunHooks( 'UploadComplete', array( &$this ) );
379
380 return $status;
381 }
382
383 /**
384 * Returns the title of the file to be uploaded. Sets mTitleError in case
385 * the name was illegal.
386 *
387 * @return Title The title of the file or null in case the name was illegal
388 */
389 public function getTitle() {
390 if ( $this->mTitle !== false )
391 return $this->mTitle;
392
393 /**
394 * Chop off any directories in the given filename. Then
395 * filter out illegal characters, and try to make a legible name
396 * out of it. We'll strip some silently that Title would die on.
397 */
398 $basename = $this->mDesiredDestName;
399
400 $this->mFilteredName = wfStripIllegalFilenameChars( $basename );
401 /* Normalize to title form before we do any further processing */
402 $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
403 if( is_null( $nt ) ) {
404 $this->mTitleError = self::ILLEGAL_FILENAME;
405 return $this->mTitle = null;
406 }
407 $this->mFilteredName = $nt->getDBkey();
408
409 /**
410 * We'll want to blacklist against *any* 'extension', and use
411 * only the final one for the whitelist.
412 */
413 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName );
414
415 if( count( $ext ) ) {
416 $this->mFinalExtension = trim( $ext[count( $ext ) - 1] );
417 } else {
418 $this->mFinalExtension = '';
419 }
420
421 /* Don't allow users to override the blacklist (check file extension) */
422 global $wgCheckFileExtensions, $wgStrictFileExtensions;
423 global $wgFileExtensions, $wgFileBlacklist;
424 if ( $this->mFinalExtension == '' ) {
425 $this->mTitleError = self::FILETYPE_MISSING;
426 return $this->mTitle = null;
427 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
428 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
429 !$this->checkFileExtension( $this->mFinalExtension, $wgFileExtensions ) ) ) {
430 $this->mTitleError = self::FILETYPE_BADTYPE;
431 return $this->mTitle = null;
432 }
433
434 # If there was more than one "extension", reassemble the base
435 # filename to prevent bogus complaints about length
436 if( count( $ext ) > 1 ) {
437 for( $i = 0; $i < count( $ext ) - 1; $i++ )
438 $partname .= '.' . $ext[$i];
439 }
440
441 if( strlen( $partname ) < 1 ) {
442 $this->mTitleError = self::MIN_LENGTH_PARTNAME;
443 return $this->mTitle = null;
444 }
445
446 $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
447 if( is_null( $nt ) ) {
448 $this->mTitleError = self::ILLEGAL_FILENAME;
449 return $this->mTitle = null;
450 }
451 return $this->mTitle = $nt;
452 }
453
454 /**
455 * Return the local file and initializes if necessary.
456 */
457 public function getLocalFile() {
458 if( is_null( $this->mLocalFile ) ) {
459 $nt = $this->getTitle();
460 $this->mLocalFile = is_null( $nt ) ? null : wfLocalFile( $nt );
461 }
462 return $this->mLocalFile;
463 }
464
465 /**
466 * Stash a file in a temporary directory for later processing
467 * after the user has confirmed it.
468 *
469 * If the user doesn't explicitly cancel or accept, these files
470 * can accumulate in the temp directory.
471 *
472 * @param string $saveName - the destination filename
473 * @param string $tempSrc - the source temporary file to save
474 * @return string - full path the stashed file, or false on failure
475 * @access private
476 */
477 protected function saveTempUploadedFile( $saveName, $tempSrc ) {
478 $repo = RepoGroup::singleton()->getLocalRepo();
479 $status = $repo->storeTemp( $saveName, $tempSrc );
480 return $status;
481 }
482
483 /**
484 * Append a file to a stashed file.
485 *
486 * @param string $srcPath Path to file to append from
487 * @param string $toAppendPath Path to file to append to
488 * @return Status Status
489 */
490 public function appendToUploadFile( $srcPath, $toAppendPath ){
491 $repo = RepoGroup::singleton()->getLocalRepo();
492 $status = $repo->append( $srcPath, $toAppendPath );
493 return $status;
494 }
495
496 /**
497 * Stash a file in a temporary directory for later processing,
498 * and save the necessary descriptive info into the session.
499 * Returns a key value which will be passed through a form
500 * to pick up the path info on a later invocation.
501 *
502 * @return int Session key
503 */
504 public function stashSession() {
505 $status = $this->saveTempUploadedFile( $this->mDestName, $this->mTempPath );
506 if( !$status->isOK() ) {
507 # Couldn't save the file.
508 return false;
509 }
510 if(!isset($_SESSION))
511 session_start(); // start up the session (might have been previously closed to prevent php session locking)
512 $key = $this->getSessionKey();
513 $_SESSION['wsUploadData'][$key] = array(
514 'mTempPath' => $status->value,
515 'mFileSize' => $this->mFileSize,
516 'mFileProps' => $this->mFileProps,
517 'version' => self::SESSION_VERSION,
518 );
519 return $key;
520 }
521
522 /**
523 * Generate a random session key from stash in cases where we want to start an upload without much information
524 */
525 protected function getSessionKey(){
526 $key = mt_rand( 0, 0x7fffffff );
527 $_SESSION['wsUploadData'][$key] = array();
528 return $key;
529 }
530
531 /**
532 * Remove a temporarily kept file stashed by saveTempUploadedFile().
533 * @return success
534 */
535 public function unsaveUploadedFile() {
536 $repo = RepoGroup::singleton()->getLocalRepo();
537 $success = $repo->freeTemp( $this->mTempPath );
538 return $success;
539 }
540
541 /**
542 * If we've modified the upload file we need to manually remove it
543 * on exit to clean up.
544 * @access private
545 */
546 public function cleanupTempFile() {
547 if ( $this->mRemoveTempFile && $this->mTempPath && file_exists( $this->mTempPath ) ) {
548 wfDebug( __METHOD__ . ": Removing temporary file {$this->mTempPath}\n" );
549 unlink( $this->mTempPath );
550 }
551 }
552
553 public function getTempPath() {
554 return $this->mTempPath;
555 }
556
557 /**
558 * Split a file into a base name and all dot-delimited 'extensions'
559 * on the end. Some web server configurations will fall back to
560 * earlier pseudo-'extensions' to determine type and execute
561 * scripts, so the blacklist needs to check them all.
562 *
563 * @return array
564 */
565 public static function splitExtensions( $filename ) {
566 $bits = explode( '.', $filename );
567 $basename = array_shift( $bits );
568 return array( $basename, $bits );
569 }
570
571 /**
572 * Perform case-insensitive match against a list of file extensions.
573 * Returns true if the extension is in the list.
574 *
575 * @param string $ext
576 * @param array $list
577 * @return bool
578 */
579 public static function checkFileExtension( $ext, $list ) {
580 return in_array( strtolower( $ext ), $list );
581 }
582
583 /**
584 * Perform case-insensitive match against a list of file extensions.
585 * Returns true if any of the extensions are in the list.
586 *
587 * @param array $ext
588 * @param array $list
589 * @return bool
590 */
591 public static function checkFileExtensionList( $ext, $list ) {
592 foreach( $ext as $e ) {
593 if( in_array( strtolower( $e ), $list ) ) {
594 return true;
595 }
596 }
597 return false;
598 }
599
600 /**
601 * Checks if the mime type of the uploaded file matches the file extension.
602 *
603 * @param string $mime the mime type of the uploaded file
604 * @param string $extension The filename extension that the file is to be served with
605 * @return bool
606 */
607 public static function verifyExtension( $mime, $extension ) {
608 $magic = MimeMagic::singleton();
609
610 if ( !$mime || $mime == 'unknown' || $mime == 'unknown/unknown' )
611 if ( !$magic->isRecognizableExtension( $extension ) ) {
612 wfDebug( __METHOD__ . ": passing file with unknown detected mime type; " .
613 "unrecognized extension '$extension', can't verify\n" );
614 return true;
615 } else {
616 wfDebug( __METHOD__ . ": rejecting file with unknown detected mime type; ".
617 "recognized extension '$extension', so probably invalid file\n" );
618 return false;
619 }
620
621 $match = $magic->isMatchingExtension( $extension, $mime );
622
623 if ( $match === NULL ) {
624 wfDebug( __METHOD__ . ": no file extension known for mime type $mime, passing file\n" );
625 return true;
626 } elseif( $match === true ) {
627 wfDebug( __METHOD__ . ": mime type $mime matches extension $extension, passing file\n" );
628
629 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
630 return true;
631
632 } else {
633 wfDebug( __METHOD__ . ": mime type $mime mismatches file extension $extension, rejecting file\n" );
634 return false;
635 }
636 }
637
638 /**
639 * Heuristic for detecting files that *could* contain JavaScript instructions or
640 * things that may look like HTML to a browser and are thus
641 * potentially harmful. The present implementation will produce false 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 #decode from UTF-16 if needed (could be used for obfuscation).
668 if( substr( $chunk, 0, 2 ) == "\xfe\xff" )
669 $enc = "UTF-16BE";
670 elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" )
671 $enc = "UTF-16LE";
672 else
673 $enc = NULL;
674
675 if( $enc )
676 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
677
678 $chunk = trim( $chunk );
679
680 #FIXME: convert from UTF-16 if necessarry!
681 wfDebug( __METHOD__ . ": checking for embedded scripts and HTML stuff\n" );
682
683 #check for HTML doctype
684 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) )
685 return true;
686
687 /**
688 * Internet Explorer for Windows performs some really stupid file type
689 * autodetection which can cause it to interpret valid image files as HTML
690 * and potentially execute JavaScript, creating a cross-site scripting
691 * attack vectors.
692 *
693 * Apple's Safari browser also performs some unsafe file type autodetection
694 * which can cause legitimate files to be interpreted as HTML if the
695 * web server is not correctly configured to send the right content-type
696 * (or if you're really uploading plain text and octet streams!)
697 *
698 * Returns true if IE is likely to mistake the given file for HTML.
699 * Also returns true if Safari would mistake the given file for HTML
700 * when served with a generic content-type.
701 */
702 $tags = array(
703 '<a',
704 '<body',
705 '<head',
706 '<html', #also in safari
707 '<img',
708 '<pre',
709 '<script', #also in safari
710 '<table'
711 );
712
713 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
714 $tags[] = '<title';
715 }
716
717 foreach( $tags as $tag ) {
718 if( false !== strpos( $chunk, $tag ) ) {
719 return true;
720 }
721 }
722
723 /*
724 * look for JavaScript
725 */
726
727 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
728 $chunk = Sanitizer::decodeCharReferences( $chunk );
729
730 #look for script-types
731 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) )
732 return true;
733
734 #look for html-style script-urls
735 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) )
736 return true;
737
738 #look for css-style script-urls
739 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) )
740 return true;
741
742 wfDebug( __METHOD__ . ": no scripts found\n" );
743 return false;
744 }
745
746 protected function detectScriptInSvg( $filename ) {
747 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
748 return $check->filterMatch;
749 }
750
751 /**
752 * @todo Replace this with a whitelist filter!
753 */
754 public function checkSvgScriptCallback( $element, $attribs ) {
755 $stripped = $this->stripXmlNamespace( $element );
756
757 if( $stripped == 'script' ) {
758 wfDebug( __METHOD__ . ": Found script element '$element' in uploaded file.\n" );
759 return true;
760 }
761
762 foreach( $attribs as $attrib => $value ) {
763 $stripped = $this->stripXmlNamespace( $attrib );
764 if( substr( $stripped, 0, 2 ) == 'on' ) {
765 wfDebug( __METHOD__ . ": Found script attribute '$attrib'='value' in uploaded file.\n" );
766 return true;
767 }
768 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
769 wfDebug( __METHOD__ . ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
770 return true;
771 }
772 }
773 }
774
775 private function stripXmlNamespace( $name ) {
776 // 'http://www.w3.org/2000/svg:script' -> 'script'
777 $parts = explode( ':', strtolower( $name ) );
778 return array_pop( $parts );
779 }
780
781 /**
782 * Generic wrapper function for a virus scanner program.
783 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
784 * $wgAntivirusRequired may be used to deny upload if the scan fails.
785 *
786 * @param string $file Pathname to the temporary upload file
787 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
788 * or a string containing feedback from the virus scanner if a virus was found.
789 * If textual feedback is missing but a virus was found, this function returns true.
790 */
791 public static function detectVirus( $file ) {
792 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
793
794 if ( !$wgAntivirus ) {
795 wfDebug( __METHOD__ . ": virus scanner disabled\n" );
796 return NULL;
797 }
798
799 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
800 wfDebug( __METHOD__ . ": unknown virus scanner: $wgAntivirus\n" );
801 $wgOut->wrapWikiMsg( '<div class="error">$1</div>', array( 'virus-badscanner', $wgAntivirus ) );
802 return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
803 }
804
805 # look up scanner configuration
806 $command = $wgAntivirusSetup[$wgAntivirus]["command"];
807 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]["codemap"];
808 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]["messagepattern"] ) ?
809 $wgAntivirusSetup[$wgAntivirus]["messagepattern"] : null;
810
811 if ( strpos( $command,"%f" ) === false ) {
812 # simple pattern: append file to scan
813 $command .= " " . wfEscapeShellArg( $file );
814 } else {
815 # complex pattern: replace "%f" with file to scan
816 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
817 }
818
819 wfDebug( __METHOD__ . ": running virus scan: $command \n" );
820
821 # execute virus scanner
822 $exitCode = false;
823
824 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
825 # that does not seem to be worth the pain.
826 # Ask me (Duesentrieb) about it if it's ever needed.
827 $output = array();
828 if ( wfIsWindows() ) {
829 exec( "$command", $output, $exitCode );
830 } else {
831 exec( "$command 2>&1", $output, $exitCode );
832 }
833
834 # map exit code to AV_xxx constants.
835 $mappedCode = $exitCode;
836 if ( $exitCodeMap ) {
837 if ( isset( $exitCodeMap[$exitCode] ) ) {
838 $mappedCode = $exitCodeMap[$exitCode];
839 } elseif ( isset( $exitCodeMap["*"] ) ) {
840 $mappedCode = $exitCodeMap["*"];
841 }
842 }
843
844 if ( $mappedCode === AV_SCAN_FAILED ) {
845 # scan failed (code was mapped to false by $exitCodeMap)
846 wfDebug( __METHOD__ . ": failed to scan $file (code $exitCode).\n" );
847
848 if ( $wgAntivirusRequired ) {
849 return wfMsg( 'virus-scanfailed', array( $exitCode ) );
850 } else {
851 return NULL;
852 }
853 } else if ( $mappedCode === AV_SCAN_ABORTED ) {
854 # scan failed because filetype is unknown (probably imune)
855 wfDebug( __METHOD__ . ": unsupported file type $file (code $exitCode).\n" );
856 return NULL;
857 } else if ( $mappedCode === AV_NO_VIRUS ) {
858 # no virus found
859 wfDebug( __METHOD__ . ": file passed virus scan.\n" );
860 return false;
861 } else {
862 $output = join( "\n", $output );
863 $output = trim( $output );
864
865 if ( !$output ) {
866 $output = true; #if there's no output, return true
867 } elseif ( $msgPattern ) {
868 $groups = array();
869 if ( preg_match( $msgPattern, $output, $groups ) ) {
870 if ( $groups[1] ) {
871 $output = $groups[1];
872 }
873 }
874 }
875
876 wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output \n" );
877 return $output;
878 }
879 }
880
881 /**
882 * Check if the temporary file is MacBinary-encoded, as some uploads
883 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
884 * If so, the data fork will be extracted to a second temporary file,
885 * which will then be checked for validity and either kept or discarded.
886 *
887 * @access private
888 */
889 private function checkMacBinary() {
890 $macbin = new MacBinary( $this->mTempPath );
891 if( $macbin->isValid() ) {
892 $dataFile = tempnam( wfTempDir(), 'WikiMacBinary' );
893 $dataHandle = fopen( $dataFile, 'wb' );
894
895 wfDebug( __METHOD__ . ": Extracting MacBinary data fork to $dataFile\n" );
896 $macbin->extractData( $dataHandle );
897
898 $this->mTempPath = $dataFile;
899 $this->mFileSize = $macbin->dataForkLength();
900
901 // We'll have to manually remove the new file if it's not kept.
902 $this->mRemoveTempFile = true;
903 }
904 $macbin->close();
905 }
906
907 /**
908 * Check if there's an overwrite conflict and, if so, if restrictions
909 * forbid this user from performing the upload.
910 *
911 * @return mixed true on success, error string on failure
912 * @access private
913 */
914 private function checkOverwrite() {
915 global $wgUser;
916 // First check whether the local file can be overwritten
917 $file = $this->getLocalFile();
918 if( $file->exists() )
919 if( !self::userCanReUpload( $wgUser, $file ) )
920 return 'fileexists-forbidden';
921
922 // Check shared conflicts
923 $file = wfFindFile( $file->getName() );
924 if ( $file && ( !$wgUser->isAllowed( 'reupload' ) ||
925 !$wgUser->isAllowed( 'reupload-shared' ) ) )
926 return 'fileexists-shared-forbidden';
927
928 return true;
929 }
930
931 /**
932 * Check if a user is the last uploader
933 *
934 * @param User $user
935 * @param string $img, image name
936 * @return bool
937 */
938 public static function userCanReUpload( User $user, $img ) {
939 if( $user->isAllowed( 'reupload' ) )
940 return true; // non-conditional
941 if( !$user->isAllowed( 'reupload-own' ) )
942 return false;
943 if( is_string( $img ) )
944 $img = wfLocalFile( $img );
945 if ( !( $img instanceof LocalFile ) )
946 return false;
947
948 return $user->getId() == $img->getUser( 'id' );
949 }
950
951 /**
952 * Helper function that does various existence checks for a file.
953 * The following checks are performed:
954 * - The file exists
955 * - Article with the same name as the file exists
956 * - File exists with normalized extension
957 * - The file looks like a thumbnail and the original exists
958 *
959 * @param File $file The file to check
960 * @return mixed False if the file does not exists, else an array
961 */
962 public static function getExistsWarning( $file ) {
963 if( $file->exists() )
964 return array( 'exists', $file );
965
966 if( $file->getTitle()->getArticleID() )
967 return array( 'page-exists', $file );
968
969 if( strpos( $file->getName(), '.' ) == false ) {
970 $partname = $file->getName();
971 $rawExtension = '';
972 } else {
973 $n = strrpos( $file->getName(), '.' );
974 $rawExtension = substr( $file->getName(), $n + 1 );
975 $partname = substr( $file->getName(), 0, $n );
976 }
977
978 if ( $rawExtension != $file->getExtension() ) {
979 // We're not using the normalized form of the extension.
980 // Normal form is lowercase, using most common of alternate
981 // extensions (eg 'jpg' rather than 'JPEG').
982 //
983 // Check for another file using the normalized form...
984 $nt_lc = Title::makeTitle( NS_FILE, $partname . '.' . $file->getExtension() );
985 $file_lc = wfLocalFile( $nt_lc );
986
987 if( $file_lc->exists() )
988 return array( 'exists-normalized', $file_lc );
989 }
990
991 if ( self::isThumbName( $file->getName() ) ) {
992 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
993 $nt_thb = Title::newFromText( substr( $partname , strpos( $partname , '-' ) +1 ) . '.' . $rawExtension );
994 $file_thb = wfLocalFile( $nt_thb );
995 if( $file_thb->exists() )
996 return array( 'thumb', $file_thb );
997 else
998 // File does not exist, but we just don't like the name
999 return array( 'thumb-name', $file_thb );
1000 }
1001
1002 return false;
1003 }
1004
1005 /**
1006 * Helper function that checks whether the filename looks like a thumbnail
1007 */
1008 public static function isThumbName( $filename ) {
1009 $n = strrpos( $filename, '.' );
1010 $partname = $n ? substr( $filename, 0, $n ) : $filename;
1011 return (
1012 substr( $partname , 3, 3 ) == 'px-' ||
1013 substr( $partname , 2, 3 ) == 'px-'
1014 ) &&
1015 preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) );
1016 }
1017
1018 /**
1019 * Get a list of blacklisted filename prefixes from [[MediaWiki:filename-prefix-blacklist]]
1020 *
1021 * @return array list of prefixes
1022 */
1023 public static function getFilenamePrefixBlacklist() {
1024 $blacklist = array();
1025 $message = wfMsgForContent( 'filename-prefix-blacklist' );
1026 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) || $message == '-' ) ) {
1027 $lines = explode( "\n", $message );
1028 foreach( $lines as $line ) {
1029 // Remove comment lines
1030 $comment = substr( trim( $line ), 0, 1 );
1031 if ( $comment == '#' || $comment == '' ) {
1032 continue;
1033 }
1034 // Remove additional comments after a prefix
1035 $comment = strpos( $line, '#' );
1036 if ( $comment > 0 ) {
1037 $line = substr( $line, 0, $comment-1 );
1038 }
1039 $blacklist[] = trim( $line );
1040 }
1041 }
1042 return $blacklist;
1043 }
1044
1045 }