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