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