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