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