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