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