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