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