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