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