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