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