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