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