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