(bug 30202) Restrict file names on upload to 240 bytes, because wfTimestamp( TS_MW...
[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( 'create', $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 && $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 # oi_archive_name is max 255 bytes, which include a timestamp and an
635 # exclamation mark, so restrict file name to 240 bytes. Return
636 # ILLEGAL_FILENAME, just like would have happened for >255 bytes
637 if ( strlen( $this->mFilteredName ) > 240 ) {
638 $this->mTitleError = self::ILLEGAL_FILENAME;
639 return $this->mTitle = null;
640 }
641
642 /**
643 * We'll want to blacklist against *any* 'extension', and use
644 * only the final one for the whitelist.
645 */
646 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName );
647
648 if( count( $ext ) ) {
649 $this->mFinalExtension = trim( $ext[count( $ext ) - 1] );
650 } else {
651 $this->mFinalExtension = '';
652
653 # No extension, try guessing one
654 $magic = MimeMagic::singleton();
655 $mime = $magic->guessMimeType( $this->mTempPath );
656 if ( $mime !== 'unknown/unknown' ) {
657 # Get a space separated list of extensions
658 $extList = $magic->getExtensionsForType( $mime );
659 if ( $extList ) {
660 # Set the extension to the canonical extension
661 $this->mFinalExtension = strtok( $extList, ' ' );
662
663 # Fix up the other variables
664 $this->mFilteredName .= ".{$this->mFinalExtension}";
665 $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
666 $ext = array( $this->mFinalExtension );
667 }
668 }
669
670 }
671
672 /* Don't allow users to override the blacklist (check file extension) */
673 global $wgCheckFileExtensions, $wgStrictFileExtensions;
674 global $wgFileExtensions, $wgFileBlacklist;
675
676 $blackListedExtensions = $this->checkFileExtensionList( $ext, $wgFileBlacklist );
677
678 if ( $this->mFinalExtension == '' ) {
679 $this->mTitleError = self::FILETYPE_MISSING;
680 return $this->mTitle = null;
681 } elseif ( $blackListedExtensions ||
682 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
683 !$this->checkFileExtensionList( $ext, $wgFileExtensions ) ) ) {
684 $this->mBlackListedExtensions = $blackListedExtensions;
685 $this->mTitleError = self::FILETYPE_BADTYPE;
686 return $this->mTitle = null;
687 }
688
689 // Windows may be broken with special characters, see bug XXX
690 if ( wfIsWindows() && !preg_match( '/^[\x0-\x7f]*$/', $nt->getText() ) ) {
691 $this->mTitleError = self::WINDOWS_NONASCII_FILENAME;
692 return $this->mTitle = null;
693 }
694
695 # If there was more than one "extension", reassemble the base
696 # filename to prevent bogus complaints about length
697 if( count( $ext ) > 1 ) {
698 for( $i = 0; $i < count( $ext ) - 1; $i++ ) {
699 $partname .= '.' . $ext[$i];
700 }
701 }
702
703 if( strlen( $partname ) < 1 ) {
704 $this->mTitleError = self::MIN_LENGTH_PARTNAME;
705 return $this->mTitle = null;
706 }
707
708 return $this->mTitle = $nt;
709 }
710
711 /**
712 * Return the local file and initializes if necessary.
713 *
714 * @return LocalFile
715 */
716 public function getLocalFile() {
717 if( is_null( $this->mLocalFile ) ) {
718 $nt = $this->getTitle();
719 $this->mLocalFile = is_null( $nt ) ? null : wfLocalFile( $nt );
720 }
721 return $this->mLocalFile;
722 }
723
724 /**
725 * NOTE: Probably should be deprecated in favor of UploadStash, but this is sometimes
726 * called outside that context.
727 *
728 * Stash a file in a temporary directory for later processing
729 * after the user has confirmed it.
730 *
731 * If the user doesn't explicitly cancel or accept, these files
732 * can accumulate in the temp directory.
733 *
734 * @param $saveName String: the destination filename
735 * @param $tempSrc String: the source temporary file to save
736 * @return String: full path the stashed file, or false on failure
737 */
738 protected function saveTempUploadedFile( $saveName, $tempSrc ) {
739 $repo = RepoGroup::singleton()->getLocalRepo();
740 $status = $repo->storeTemp( $saveName, $tempSrc );
741 return $status;
742 }
743
744 /**
745 * If the user does not supply all necessary information in the first upload form submission (either by accident or
746 * by design) then we may want to stash the file temporarily, get more information, and publish the file later.
747 *
748 * This method will stash a file in a temporary directory for later processing, and save the necessary descriptive info
749 * into the database.
750 * This method returns the file object, which also has a 'fileKey' property which can be passed through a form or
751 * API request to find this stashed file again.
752 *
753 * @return UploadStashFile stashed file
754 */
755 public function stashFile() {
756 // was stashSessionFile
757 $stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash();
758
759 $file = $stash->stashFile( $this->mTempPath, $this->getSourceType() );
760 $this->mLocalFile = $file;
761 return $file;
762 }
763
764 /**
765 * Stash a file in a temporary directory, returning a key which can be used to find the file again. See stashFile().
766 *
767 * @return String: file key
768 */
769 public function stashFileGetKey() {
770 return $this->stashFile()->getFileKey();
771 }
772
773 /**
774 * alias for stashFileGetKey, for backwards compatibility
775 *
776 * @return String: file key
777 */
778 public function stashSession() {
779 return $this->stashFileGetKey();
780 }
781
782 /**
783 * If we've modified the upload file we need to manually remove it
784 * on exit to clean up.
785 */
786 public function cleanupTempFile() {
787 if ( $this->mRemoveTempFile && $this->mTempPath && file_exists( $this->mTempPath ) ) {
788 wfDebug( __METHOD__ . ": Removing temporary file {$this->mTempPath}\n" );
789 unlink( $this->mTempPath );
790 }
791 }
792
793 public function getTempPath() {
794 return $this->mTempPath;
795 }
796
797 /**
798 * Split a file into a base name and all dot-delimited 'extensions'
799 * on the end. Some web server configurations will fall back to
800 * earlier pseudo-'extensions' to determine type and execute
801 * scripts, so the blacklist needs to check them all.
802 *
803 * @return array
804 */
805 public static function splitExtensions( $filename ) {
806 $bits = explode( '.', $filename );
807 $basename = array_shift( $bits );
808 return array( $basename, $bits );
809 }
810
811 /**
812 * Perform case-insensitive match against a list of file extensions.
813 * Returns true if the extension is in the list.
814 *
815 * @param $ext String
816 * @param $list Array
817 * @return Boolean
818 */
819 public static function checkFileExtension( $ext, $list ) {
820 return in_array( strtolower( $ext ), $list );
821 }
822
823 /**
824 * Perform case-insensitive match against a list of file extensions.
825 * Returns an array of matching extensions.
826 *
827 * @param $ext Array
828 * @param $list Array
829 * @return Boolean
830 */
831 public static function checkFileExtensionList( $ext, $list ) {
832 return array_intersect( array_map( 'strtolower', $ext ), $list );
833 }
834
835 /**
836 * Checks if the mime type of the uploaded file matches the file extension.
837 *
838 * @param $mime String: the mime type of the uploaded file
839 * @param $extension String: the filename extension that the file is to be served with
840 * @return Boolean
841 */
842 public static function verifyExtension( $mime, $extension ) {
843 $magic = MimeMagic::singleton();
844
845 if ( !$mime || $mime == 'unknown' || $mime == 'unknown/unknown' )
846 if ( !$magic->isRecognizableExtension( $extension ) ) {
847 wfDebug( __METHOD__ . ": passing file with unknown detected mime type; " .
848 "unrecognized extension '$extension', can't verify\n" );
849 return true;
850 } else {
851 wfDebug( __METHOD__ . ": rejecting file with unknown detected mime type; ".
852 "recognized extension '$extension', so probably invalid file\n" );
853 return false;
854 }
855
856 $match = $magic->isMatchingExtension( $extension, $mime );
857
858 if ( $match === null ) {
859 wfDebug( __METHOD__ . ": no file extension known for mime type $mime, passing file\n" );
860 return true;
861 } elseif( $match === true ) {
862 wfDebug( __METHOD__ . ": mime type $mime matches extension $extension, passing file\n" );
863
864 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
865 return true;
866
867 } else {
868 wfDebug( __METHOD__ . ": mime type $mime mismatches file extension $extension, rejecting file\n" );
869 return false;
870 }
871 }
872
873 /**
874 * Heuristic for detecting files that *could* contain JavaScript instructions or
875 * things that may look like HTML to a browser and are thus
876 * potentially harmful. The present implementation will produce false
877 * positives in some situations.
878 *
879 * @param $file String: pathname to the temporary upload file
880 * @param $mime String: the mime type of the file
881 * @param $extension String: the extension of the file
882 * @return Boolean: true if the file contains something looking like embedded scripts
883 */
884 public static function detectScript( $file, $mime, $extension ) {
885 global $wgAllowTitlesInSVG;
886
887 # ugly hack: for text files, always look at the entire file.
888 # For binary field, just check the first K.
889
890 if( strpos( $mime,'text/' ) === 0 ) {
891 $chunk = file_get_contents( $file );
892 } else {
893 $fp = fopen( $file, 'rb' );
894 $chunk = fread( $fp, 1024 );
895 fclose( $fp );
896 }
897
898 $chunk = strtolower( $chunk );
899
900 if( !$chunk ) {
901 return false;
902 }
903
904 # decode from UTF-16 if needed (could be used for obfuscation).
905 if( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
906 $enc = 'UTF-16BE';
907 } elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
908 $enc = 'UTF-16LE';
909 } else {
910 $enc = null;
911 }
912
913 if( $enc ) {
914 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
915 }
916
917 $chunk = trim( $chunk );
918
919 # @todo FIXME: Convert from UTF-16 if necessarry!
920 wfDebug( __METHOD__ . ": checking for embedded scripts and HTML stuff\n" );
921
922 # check for HTML doctype
923 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
924 return true;
925 }
926
927 /**
928 * Internet Explorer for Windows performs some really stupid file type
929 * autodetection which can cause it to interpret valid image files as HTML
930 * and potentially execute JavaScript, creating a cross-site scripting
931 * attack vectors.
932 *
933 * Apple's Safari browser also performs some unsafe file type autodetection
934 * which can cause legitimate files to be interpreted as HTML if the
935 * web server is not correctly configured to send the right content-type
936 * (or if you're really uploading plain text and octet streams!)
937 *
938 * Returns true if IE is likely to mistake the given file for HTML.
939 * Also returns true if Safari would mistake the given file for HTML
940 * when served with a generic content-type.
941 */
942 $tags = array(
943 '<a href',
944 '<body',
945 '<head',
946 '<html', #also in safari
947 '<img',
948 '<pre',
949 '<script', #also in safari
950 '<table'
951 );
952
953 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
954 $tags[] = '<title';
955 }
956
957 foreach( $tags as $tag ) {
958 if( false !== strpos( $chunk, $tag ) ) {
959 wfDebug( __METHOD__ . ": found something that may make it be mistaken for html: $tag\n" );
960 return true;
961 }
962 }
963
964 /*
965 * look for JavaScript
966 */
967
968 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
969 $chunk = Sanitizer::decodeCharReferences( $chunk );
970
971 # look for script-types
972 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
973 wfDebug( __METHOD__ . ": found script types\n" );
974 return true;
975 }
976
977 # look for html-style script-urls
978 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
979 wfDebug( __METHOD__ . ": found html-style script urls\n" );
980 return true;
981 }
982
983 # look for css-style script-urls
984 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
985 wfDebug( __METHOD__ . ": found css-style script urls\n" );
986 return true;
987 }
988
989 wfDebug( __METHOD__ . ": no scripts found\n" );
990 return false;
991 }
992
993 protected function detectScriptInSvg( $filename ) {
994 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
995 return $check->filterMatch;
996 }
997
998 /**
999 * @todo Replace this with a whitelist filter!
1000 */
1001 public function checkSvgScriptCallback( $element, $attribs ) {
1002 $stripped = $this->stripXmlNamespace( $element );
1003
1004 if( $stripped == 'script' ) {
1005 wfDebug( __METHOD__ . ": Found script element '$element' in uploaded file.\n" );
1006 return true;
1007 }
1008
1009 foreach( $attribs as $attrib => $value ) {
1010 $stripped = $this->stripXmlNamespace( $attrib );
1011 if( substr( $stripped, 0, 2 ) == 'on' ) {
1012 wfDebug( __METHOD__ . ": Found script attribute '$attrib'='value' in uploaded file.\n" );
1013 return true;
1014 }
1015 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
1016 wfDebug( __METHOD__ . ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
1017 return true;
1018 }
1019 }
1020 }
1021
1022 private function stripXmlNamespace( $name ) {
1023 // 'http://www.w3.org/2000/svg:script' -> 'script'
1024 $parts = explode( ':', strtolower( $name ) );
1025 return array_pop( $parts );
1026 }
1027
1028 /**
1029 * Generic wrapper function for a virus scanner program.
1030 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1031 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1032 *
1033 * @param $file String: pathname to the temporary upload file
1034 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1035 * or a string containing feedback from the virus scanner if a virus was found.
1036 * If textual feedback is missing but a virus was found, this function returns true.
1037 */
1038 public static function detectVirus( $file ) {
1039 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1040
1041 if ( !$wgAntivirus ) {
1042 wfDebug( __METHOD__ . ": virus scanner disabled\n" );
1043 return null;
1044 }
1045
1046 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1047 wfDebug( __METHOD__ . ": unknown virus scanner: $wgAntivirus\n" );
1048 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
1049 array( 'virus-badscanner', $wgAntivirus ) );
1050 return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
1051 }
1052
1053 # look up scanner configuration
1054 $command = $wgAntivirusSetup[$wgAntivirus]['command'];
1055 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
1056 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
1057 $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
1058
1059 if ( strpos( $command, "%f" ) === false ) {
1060 # simple pattern: append file to scan
1061 $command .= " " . wfEscapeShellArg( $file );
1062 } else {
1063 # complex pattern: replace "%f" with file to scan
1064 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1065 }
1066
1067 wfDebug( __METHOD__ . ": running virus scan: $command \n" );
1068
1069 # execute virus scanner
1070 $exitCode = false;
1071
1072 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1073 # that does not seem to be worth the pain.
1074 # Ask me (Duesentrieb) about it if it's ever needed.
1075 $output = wfShellExec( "$command 2>&1", $exitCode );
1076
1077 # map exit code to AV_xxx constants.
1078 $mappedCode = $exitCode;
1079 if ( $exitCodeMap ) {
1080 if ( isset( $exitCodeMap[$exitCode] ) ) {
1081 $mappedCode = $exitCodeMap[$exitCode];
1082 } elseif ( isset( $exitCodeMap["*"] ) ) {
1083 $mappedCode = $exitCodeMap["*"];
1084 }
1085 }
1086
1087 if ( $mappedCode === AV_SCAN_FAILED ) {
1088 # scan failed (code was mapped to false by $exitCodeMap)
1089 wfDebug( __METHOD__ . ": failed to scan $file (code $exitCode).\n" );
1090
1091 if ( $wgAntivirusRequired ) {
1092 return wfMsg( 'virus-scanfailed', array( $exitCode ) );
1093 } else {
1094 return null;
1095 }
1096 } elseif ( $mappedCode === AV_SCAN_ABORTED ) {
1097 # scan failed because filetype is unknown (probably imune)
1098 wfDebug( __METHOD__ . ": unsupported file type $file (code $exitCode).\n" );
1099 return null;
1100 } elseif ( $mappedCode === AV_NO_VIRUS ) {
1101 # no virus found
1102 wfDebug( __METHOD__ . ": file passed virus scan.\n" );
1103 return false;
1104 } else {
1105 $output = trim( $output );
1106
1107 if ( !$output ) {
1108 $output = true; #if there's no output, return true
1109 } elseif ( $msgPattern ) {
1110 $groups = array();
1111 if ( preg_match( $msgPattern, $output, $groups ) ) {
1112 if ( $groups[1] ) {
1113 $output = $groups[1];
1114 }
1115 }
1116 }
1117
1118 wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output \n" );
1119 return $output;
1120 }
1121 }
1122
1123 /**
1124 * Check if there's an overwrite conflict and, if so, if restrictions
1125 * forbid this user from performing the upload.
1126 *
1127 * @param $user User
1128 *
1129 * @return mixed true on success, array on failure
1130 */
1131 private function checkOverwrite( $user ) {
1132 // First check whether the local file can be overwritten
1133 $file = $this->getLocalFile();
1134 if( $file->exists() ) {
1135 if( !self::userCanReUpload( $user, $file ) ) {
1136 return array( 'fileexists-forbidden', $file->getName() );
1137 } else {
1138 return true;
1139 }
1140 }
1141
1142 /* Check shared conflicts: if the local file does not exist, but
1143 * wfFindFile finds a file, it exists in a shared repository.
1144 */
1145 $file = wfFindFile( $this->getTitle() );
1146 if ( $file && !$user->isAllowed( 'reupload-shared' ) ) {
1147 return array( 'fileexists-shared-forbidden', $file->getName() );
1148 }
1149
1150 return true;
1151 }
1152
1153 /**
1154 * Check if a user is the last uploader
1155 *
1156 * @param $user User object
1157 * @param $img String: image name
1158 * @return Boolean
1159 */
1160 public static function userCanReUpload( User $user, $img ) {
1161 if( $user->isAllowed( 'reupload' ) ) {
1162 return true; // non-conditional
1163 }
1164 if( !$user->isAllowed( 'reupload-own' ) ) {
1165 return false;
1166 }
1167 if( is_string( $img ) ) {
1168 $img = wfLocalFile( $img );
1169 }
1170 if ( !( $img instanceof LocalFile ) ) {
1171 return false;
1172 }
1173
1174 return $user->getId() == $img->getUser( 'id' );
1175 }
1176
1177 /**
1178 * Helper function that does various existence checks for a file.
1179 * The following checks are performed:
1180 * - The file exists
1181 * - Article with the same name as the file exists
1182 * - File exists with normalized extension
1183 * - The file looks like a thumbnail and the original exists
1184 *
1185 * @param $file File The File object to check
1186 * @return mixed False if the file does not exists, else an array
1187 */
1188 public static function getExistsWarning( $file ) {
1189 if( $file->exists() ) {
1190 return array( 'warning' => 'exists', 'file' => $file );
1191 }
1192
1193 if( $file->getTitle()->getArticleID() ) {
1194 return array( 'warning' => 'page-exists', 'file' => $file );
1195 }
1196
1197 if ( $file->wasDeleted() && !$file->exists() ) {
1198 return array( 'warning' => 'was-deleted', 'file' => $file );
1199 }
1200
1201 if( strpos( $file->getName(), '.' ) == false ) {
1202 $partname = $file->getName();
1203 $extension = '';
1204 } else {
1205 $n = strrpos( $file->getName(), '.' );
1206 $extension = substr( $file->getName(), $n + 1 );
1207 $partname = substr( $file->getName(), 0, $n );
1208 }
1209 $normalizedExtension = File::normalizeExtension( $extension );
1210
1211 if ( $normalizedExtension != $extension ) {
1212 // We're not using the normalized form of the extension.
1213 // Normal form is lowercase, using most common of alternate
1214 // extensions (eg 'jpg' rather than 'JPEG').
1215 //
1216 // Check for another file using the normalized form...
1217 $nt_lc = Title::makeTitle( NS_FILE, "{$partname}.{$normalizedExtension}" );
1218 $file_lc = wfLocalFile( $nt_lc );
1219
1220 if( $file_lc->exists() ) {
1221 return array(
1222 'warning' => 'exists-normalized',
1223 'file' => $file,
1224 'normalizedFile' => $file_lc
1225 );
1226 }
1227 }
1228
1229 if ( self::isThumbName( $file->getName() ) ) {
1230 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1231 $nt_thb = Title::newFromText( substr( $partname , strpos( $partname , '-' ) +1 ) . '.' . $extension, NS_FILE );
1232 $file_thb = wfLocalFile( $nt_thb );
1233 if( $file_thb->exists() ) {
1234 return array(
1235 'warning' => 'thumb',
1236 'file' => $file,
1237 'thumbFile' => $file_thb
1238 );
1239 } else {
1240 // File does not exist, but we just don't like the name
1241 return array(
1242 'warning' => 'thumb-name',
1243 'file' => $file,
1244 'thumbFile' => $file_thb
1245 );
1246 }
1247 }
1248
1249
1250 foreach( self::getFilenamePrefixBlacklist() as $prefix ) {
1251 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1252 return array(
1253 'warning' => 'bad-prefix',
1254 'file' => $file,
1255 'prefix' => $prefix
1256 );
1257 }
1258 }
1259
1260 return false;
1261 }
1262
1263 /**
1264 * Helper function that checks whether the filename looks like a thumbnail
1265 */
1266 public static function isThumbName( $filename ) {
1267 $n = strrpos( $filename, '.' );
1268 $partname = $n ? substr( $filename, 0, $n ) : $filename;
1269 return (
1270 substr( $partname , 3, 3 ) == 'px-' ||
1271 substr( $partname , 2, 3 ) == 'px-'
1272 ) &&
1273 preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) );
1274 }
1275
1276 /**
1277 * Get a list of blacklisted filename prefixes from [[MediaWiki:Filename-prefix-blacklist]]
1278 *
1279 * @return array list of prefixes
1280 */
1281 public static function getFilenamePrefixBlacklist() {
1282 $blacklist = array();
1283 $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
1284 if( !$message->isDisabled() ) {
1285 $lines = explode( "\n", $message->plain() );
1286 foreach( $lines as $line ) {
1287 // Remove comment lines
1288 $comment = substr( trim( $line ), 0, 1 );
1289 if ( $comment == '#' || $comment == '' ) {
1290 continue;
1291 }
1292 // Remove additional comments after a prefix
1293 $comment = strpos( $line, '#' );
1294 if ( $comment > 0 ) {
1295 $line = substr( $line, 0, $comment-1 );
1296 }
1297 $blacklist[] = trim( $line );
1298 }
1299 }
1300 return $blacklist;
1301 }
1302
1303 /**
1304 * Gets image info about the file just uploaded.
1305 *
1306 * Also has the effect of setting metadata to be an 'indexed tag name' in returned API result if
1307 * 'metadata' was requested. Oddly, we have to pass the "result" object down just so it can do that
1308 * with the appropriate format, presumably.
1309 *
1310 * @param $result ApiResult:
1311 * @return Array: image info
1312 */
1313 public function getImageInfo( $result ) {
1314 $file = $this->getLocalFile();
1315 // TODO This cries out for refactoring. We really want to say $file->getAllInfo(); here.
1316 // Perhaps "info" methods should be moved into files, and the API should just wrap them in queries.
1317 if ( $file instanceof UploadStashFile ) {
1318 $imParam = ApiQueryStashImageInfo::getPropertyNames();
1319 $info = ApiQueryStashImageInfo::getInfo( $file, array_flip( $imParam ), $result );
1320 } else {
1321 $imParam = ApiQueryImageInfo::getPropertyNames();
1322 $info = ApiQueryImageInfo::getInfo( $file, array_flip( $imParam ), $result );
1323 }
1324 return $info;
1325 }
1326
1327
1328 public function convertVerifyErrorToStatus( $error ) {
1329 $code = $error['status'];
1330 unset( $code['status'] );
1331 return Status::newFatal( $this->getVerificationErrorCode( $code ), $error );
1332 }
1333
1334 public static function getMaxUploadSize( $forType = null ) {
1335 global $wgMaxUploadSize;
1336
1337 if ( is_array( $wgMaxUploadSize ) ) {
1338 if ( !is_null( $forType ) && isset( $wgMaxUploadSize[$forType] ) ) {
1339 return $wgMaxUploadSize[$forType];
1340 } else {
1341 return $wgMaxUploadSize['*'];
1342 }
1343 } else {
1344 return intval( $wgMaxUploadSize );
1345 }
1346
1347 }
1348 }