Merge "TitleInputWidget: Allow config to disable validation"
[lhc/web/wiklou.git] / includes / upload / UploadBase.php
1 <?php
2 /**
3 * Base class for the backend of file upload.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Upload
22 */
23
24 /**
25 * @defgroup Upload Upload related
26 */
27
28 /**
29 * @ingroup Upload
30 *
31 * UploadBase and subclasses are the backend of MediaWiki's file uploads.
32 * The frontends are formed by ApiUpload and SpecialUpload.
33 *
34 * @author Brion Vibber
35 * @author Bryan Tong Minh
36 * @author Michael Dale
37 */
38 abstract class UploadBase {
39 protected $mTempPath;
40 protected $mDesiredDestName, $mDestName, $mRemoveTempFile, $mSourceType;
41 protected $mTitle = false, $mTitleError = 0;
42 protected $mFilteredName, $mFinalExtension;
43 protected $mLocalFile, $mFileSize, $mFileProps;
44 protected $mBlackListedExtensions;
45 protected $mJavaDetected, $mSVGNSError;
46
47 protected static $safeXmlEncodings = array(
48 'UTF-8',
49 'ISO-8859-1',
50 'ISO-8859-2',
51 'UTF-16',
52 'UTF-32'
53 );
54
55 const SUCCESS = 0;
56 const OK = 0;
57 const EMPTY_FILE = 3;
58 const MIN_LENGTH_PARTNAME = 4;
59 const ILLEGAL_FILENAME = 5;
60 const OVERWRITE_EXISTING_FILE = 7; # Not used anymore; handled by verifyTitlePermissions()
61 const FILETYPE_MISSING = 8;
62 const FILETYPE_BADTYPE = 9;
63 const VERIFICATION_ERROR = 10;
64 const HOOK_ABORTED = 11;
65 const FILE_TOO_LARGE = 12;
66 const WINDOWS_NONASCII_FILENAME = 13;
67 const FILENAME_TOO_LONG = 14;
68
69 /**
70 * @param int $error
71 * @return string
72 */
73 public function getVerificationErrorCode( $error ) {
74 $code_to_status = array(
75 self::EMPTY_FILE => 'empty-file',
76 self::FILE_TOO_LARGE => 'file-too-large',
77 self::FILETYPE_MISSING => 'filetype-missing',
78 self::FILETYPE_BADTYPE => 'filetype-banned',
79 self::MIN_LENGTH_PARTNAME => 'filename-tooshort',
80 self::ILLEGAL_FILENAME => 'illegal-filename',
81 self::OVERWRITE_EXISTING_FILE => 'overwrite',
82 self::VERIFICATION_ERROR => 'verification-error',
83 self::HOOK_ABORTED => 'hookaborted',
84 self::WINDOWS_NONASCII_FILENAME => 'windows-nonascii-filename',
85 self::FILENAME_TOO_LONG => 'filename-toolong',
86 );
87 if ( isset( $code_to_status[$error] ) ) {
88 return $code_to_status[$error];
89 }
90
91 return 'unknown-error';
92 }
93
94 /**
95 * Returns true if uploads are enabled.
96 * Can be override by subclasses.
97 * @return bool
98 */
99 public static function isEnabled() {
100 global $wgEnableUploads;
101
102 if ( !$wgEnableUploads ) {
103 return false;
104 }
105
106 # Check php's file_uploads setting
107 return wfIsHHVM() || wfIniGetBool( 'file_uploads' );
108 }
109
110 /**
111 * Returns true if the user can use this upload module or else a string
112 * identifying the missing permission.
113 * Can be overridden by subclasses.
114 *
115 * @param User $user
116 * @return bool|string
117 */
118 public static function isAllowed( $user ) {
119 foreach ( array( 'upload', 'edit' ) as $permission ) {
120 if ( !$user->isAllowed( $permission ) ) {
121 return $permission;
122 }
123 }
124
125 return true;
126 }
127
128 /**
129 * Returns true if the user has surpassed the upload rate limit, false otherwise.
130 *
131 * @param User $user
132 * @return bool
133 */
134 public static function isThrottled( $user ) {
135 return $user->pingLimiter( 'upload' );
136 }
137
138 // Upload handlers. Should probably just be a global.
139 private static $uploadHandlers = array( 'Stash', 'File', 'Url' );
140
141 /**
142 * Create a form of UploadBase depending on wpSourceType and initializes it
143 *
144 * @param WebRequest $request
145 * @param string|null $type
146 * @return null|UploadBase
147 */
148 public static function createFromRequest( &$request, $type = null ) {
149 $type = $type ? $type : $request->getVal( 'wpSourceType', 'File' );
150
151 if ( !$type ) {
152 return null;
153 }
154
155 // Get the upload class
156 $type = ucfirst( $type );
157
158 // Give hooks the chance to handle this request
159 $className = null;
160 Hooks::run( 'UploadCreateFromRequest', array( $type, &$className ) );
161 if ( is_null( $className ) ) {
162 $className = 'UploadFrom' . $type;
163 wfDebug( __METHOD__ . ": class name: $className\n" );
164 if ( !in_array( $type, self::$uploadHandlers ) ) {
165 return null;
166 }
167 }
168
169 // Check whether this upload class is enabled
170 if ( !call_user_func( array( $className, 'isEnabled' ) ) ) {
171 return null;
172 }
173
174 // Check whether the request is valid
175 if ( !call_user_func( array( $className, 'isValidRequest' ), $request ) ) {
176 return null;
177 }
178
179 /** @var UploadBase $handler */
180 $handler = new $className;
181
182 $handler->initializeFromRequest( $request );
183
184 return $handler;
185 }
186
187 /**
188 * Check whether a request if valid for this handler
189 * @param WebRequest $request
190 * @return bool
191 */
192 public static function isValidRequest( $request ) {
193 return false;
194 }
195
196 public function __construct() {
197 }
198
199 /**
200 * Returns the upload type. Should be overridden by child classes
201 *
202 * @since 1.18
203 * @return string
204 */
205 public function getSourceType() {
206 return null;
207 }
208
209 /**
210 * Initialize the path information
211 * @param string $name The desired destination name
212 * @param string $tempPath The temporary path
213 * @param int $fileSize The file size
214 * @param bool $removeTempFile (false) remove the temporary file?
215 * @throws MWException
216 */
217 public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
218 $this->mDesiredDestName = $name;
219 if ( FileBackend::isStoragePath( $tempPath ) ) {
220 throw new MWException( __METHOD__ . " given storage path `$tempPath`." );
221 }
222 $this->mTempPath = $tempPath;
223 $this->mFileSize = $fileSize;
224 $this->mRemoveTempFile = $removeTempFile;
225 }
226
227 /**
228 * Initialize from a WebRequest. Override this in a subclass.
229 *
230 * @param WebRequest $request
231 */
232 abstract public function initializeFromRequest( &$request );
233
234 /**
235 * Fetch the file. Usually a no-op
236 * @return Status
237 */
238 public function fetchFile() {
239 return Status::newGood();
240 }
241
242 /**
243 * Return true if the file is empty
244 * @return bool
245 */
246 public function isEmptyFile() {
247 return empty( $this->mFileSize );
248 }
249
250 /**
251 * Return the file size
252 * @return int
253 */
254 public function getFileSize() {
255 return $this->mFileSize;
256 }
257
258 /**
259 * Get the base 36 SHA1 of the file
260 * @return string
261 */
262 public function getTempFileSha1Base36() {
263 return FSFile::getSha1Base36FromPath( $this->mTempPath );
264 }
265
266 /**
267 * @param string $srcPath The source path
268 * @return string|bool The real path if it was a virtual URL Returns false on failure
269 */
270 function getRealPath( $srcPath ) {
271 $repo = RepoGroup::singleton()->getLocalRepo();
272 if ( $repo->isVirtualUrl( $srcPath ) ) {
273 /** @todo Just make uploads work with storage paths UploadFromStash
274 * loads files via virtual URLs.
275 */
276 $tmpFile = $repo->getLocalCopy( $srcPath );
277 if ( $tmpFile ) {
278 $tmpFile->bind( $this ); // keep alive with $this
279 }
280 $path = $tmpFile ? $tmpFile->getPath() : false;
281 } else {
282 $path = $srcPath;
283 }
284
285 return $path;
286 }
287
288 /**
289 * Verify whether the upload is sane.
290 * @return mixed Const self::OK or else an array with error information
291 */
292 public function verifyUpload() {
293
294 /**
295 * If there was no filename or a zero size given, give up quick.
296 */
297 if ( $this->isEmptyFile() ) {
298 return array( 'status' => self::EMPTY_FILE );
299 }
300
301 /**
302 * Honor $wgMaxUploadSize
303 */
304 $maxSize = self::getMaxUploadSize( $this->getSourceType() );
305 if ( $this->mFileSize > $maxSize ) {
306 return array(
307 'status' => self::FILE_TOO_LARGE,
308 'max' => $maxSize,
309 );
310 }
311
312 /**
313 * Look at the contents of the file; if we can recognize the
314 * type but it's corrupt or data of the wrong type, we should
315 * probably not accept it.
316 */
317 $verification = $this->verifyFile();
318 if ( $verification !== true ) {
319 return array(
320 'status' => self::VERIFICATION_ERROR,
321 'details' => $verification
322 );
323 }
324
325 /**
326 * Make sure this file can be created
327 */
328 $result = $this->validateName();
329 if ( $result !== true ) {
330 return $result;
331 }
332
333 $error = '';
334 if ( !Hooks::run( 'UploadVerification',
335 array( $this->mDestName, $this->mTempPath, &$error ) )
336 ) {
337 return array( 'status' => self::HOOK_ABORTED, 'error' => $error );
338 }
339
340 return array( 'status' => self::OK );
341 }
342
343 /**
344 * Verify that the name is valid and, if necessary, that we can overwrite
345 *
346 * @return mixed True if valid, otherwise and array with 'status'
347 * and other keys
348 */
349 public function validateName() {
350 $nt = $this->getTitle();
351 if ( is_null( $nt ) ) {
352 $result = array( 'status' => $this->mTitleError );
353 if ( $this->mTitleError == self::ILLEGAL_FILENAME ) {
354 $result['filtered'] = $this->mFilteredName;
355 }
356 if ( $this->mTitleError == self::FILETYPE_BADTYPE ) {
357 $result['finalExt'] = $this->mFinalExtension;
358 if ( count( $this->mBlackListedExtensions ) ) {
359 $result['blacklistedExt'] = $this->mBlackListedExtensions;
360 }
361 }
362
363 return $result;
364 }
365 $this->mDestName = $this->getLocalFile()->getName();
366
367 return true;
368 }
369
370 /**
371 * Verify the MIME type.
372 *
373 * @note Only checks that it is not an evil MIME. The "does it have
374 * correct extension given its MIME type?" check is in verifyFile.
375 * in `verifyFile()` that MIME type and file extension correlate.
376 * @param string $mime Representing the MIME
377 * @return mixed True if the file is verified, an array otherwise
378 */
379 protected function verifyMimeType( $mime ) {
380 global $wgVerifyMimeType;
381 if ( $wgVerifyMimeType ) {
382 wfDebug( "mime: <$mime> extension: <{$this->mFinalExtension}>\n" );
383 global $wgMimeTypeBlacklist;
384 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
385 return array( 'filetype-badmime', $mime );
386 }
387
388 # Check what Internet Explorer would detect
389 $fp = fopen( $this->mTempPath, 'rb' );
390 $chunk = fread( $fp, 256 );
391 fclose( $fp );
392
393 $magic = MimeMagic::singleton();
394 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension );
395 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath, $chunk, $extMime );
396 foreach ( $ieTypes as $ieType ) {
397 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
398 return array( 'filetype-bad-ie-mime', $ieType );
399 }
400 }
401 }
402
403 return true;
404 }
405
406 /**
407 * Verifies that it's ok to include the uploaded file
408 *
409 * @return mixed True of the file is verified, array otherwise.
410 */
411 protected function verifyFile() {
412 global $wgVerifyMimeType, $wgDisableUploadScriptChecks;
413
414 $status = $this->verifyPartialFile();
415 if ( $status !== true ) {
416 return $status;
417 }
418
419 $this->mFileProps = FSFile::getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
420 $mime = $this->mFileProps['mime'];
421
422 if ( $wgVerifyMimeType ) {
423 # XXX: Missing extension will be caught by validateName() via getTitle()
424 if ( $this->mFinalExtension != '' && !$this->verifyExtension( $mime, $this->mFinalExtension ) ) {
425 return array( 'filetype-mime-mismatch', $this->mFinalExtension, $mime );
426 }
427 }
428
429 # check for htmlish code and javascript
430 if ( !$wgDisableUploadScriptChecks ) {
431 if ( $this->mFinalExtension == 'svg' || $mime == 'image/svg+xml' ) {
432 $svgStatus = $this->detectScriptInSvg( $this->mTempPath, false );
433 if ( $svgStatus !== false ) {
434 return $svgStatus;
435 }
436 }
437 }
438
439 $handler = MediaHandler::getHandler( $mime );
440 if ( $handler ) {
441 $handlerStatus = $handler->verifyUpload( $this->mTempPath );
442 if ( !$handlerStatus->isOK() ) {
443 $errors = $handlerStatus->getErrorsArray();
444
445 return reset( $errors );
446 }
447 }
448
449 Hooks::run( 'UploadVerifyFile', array( $this, $mime, &$status ) );
450 if ( $status !== true ) {
451 return $status;
452 }
453
454 wfDebug( __METHOD__ . ": all clear; passing.\n" );
455
456 return true;
457 }
458
459 /**
460 * A verification routine suitable for partial files
461 *
462 * Runs the blacklist checks, but not any checks that may
463 * assume the entire file is present.
464 *
465 * @return mixed True for valid or array with error message key.
466 */
467 protected function verifyPartialFile() {
468 global $wgAllowJavaUploads, $wgDisableUploadScriptChecks;
469
470 # getTitle() sets some internal parameters like $this->mFinalExtension
471 $this->getTitle();
472
473 $this->mFileProps = FSFile::getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
474
475 # check MIME type, if desired
476 $mime = $this->mFileProps['file-mime'];
477 $status = $this->verifyMimeType( $mime );
478 if ( $status !== true ) {
479 return $status;
480 }
481
482 # check for htmlish code and javascript
483 if ( !$wgDisableUploadScriptChecks ) {
484 if ( self::detectScript( $this->mTempPath, $mime, $this->mFinalExtension ) ) {
485 return array( 'uploadscripted' );
486 }
487 if ( $this->mFinalExtension == 'svg' || $mime == 'image/svg+xml' ) {
488 $svgStatus = $this->detectScriptInSvg( $this->mTempPath, true );
489 if ( $svgStatus !== false ) {
490 return $svgStatus;
491 }
492 }
493 }
494
495 # Check for Java applets, which if uploaded can bypass cross-site
496 # restrictions.
497 if ( !$wgAllowJavaUploads ) {
498 $this->mJavaDetected = false;
499 $zipStatus = ZipDirectoryReader::read( $this->mTempPath,
500 array( $this, 'zipEntryCallback' ) );
501 if ( !$zipStatus->isOK() ) {
502 $errors = $zipStatus->getErrorsArray();
503 $error = reset( $errors );
504 if ( $error[0] !== 'zip-wrong-format' ) {
505 return $error;
506 }
507 }
508 if ( $this->mJavaDetected ) {
509 return array( 'uploadjava' );
510 }
511 }
512
513 # Scan the uploaded file for viruses
514 $virus = $this->detectVirus( $this->mTempPath );
515 if ( $virus ) {
516 return array( 'uploadvirus', $virus );
517 }
518
519 return true;
520 }
521
522 /**
523 * Callback for ZipDirectoryReader to detect Java class files.
524 *
525 * @param array $entry
526 */
527 function zipEntryCallback( $entry ) {
528 $names = array( $entry['name'] );
529
530 // If there is a null character, cut off the name at it, because JDK's
531 // ZIP_GetEntry() uses strcmp() if the name hashes match. If a file name
532 // were constructed which had ".class\0" followed by a string chosen to
533 // make the hash collide with the truncated name, that file could be
534 // returned in response to a request for the .class file.
535 $nullPos = strpos( $entry['name'], "\000" );
536 if ( $nullPos !== false ) {
537 $names[] = substr( $entry['name'], 0, $nullPos );
538 }
539
540 // If there is a trailing slash in the file name, we have to strip it,
541 // because that's what ZIP_GetEntry() does.
542 if ( preg_grep( '!\.class/?$!', $names ) ) {
543 $this->mJavaDetected = true;
544 }
545 }
546
547 /**
548 * Alias for verifyTitlePermissions. The function was originally
549 * 'verifyPermissions', but that suggests it's checking the user, when it's
550 * really checking the title + user combination.
551 *
552 * @param User $user User object to verify the permissions against
553 * @return mixed An array as returned by getUserPermissionsErrors or true
554 * in case the user has proper permissions.
555 */
556 public function verifyPermissions( $user ) {
557 return $this->verifyTitlePermissions( $user );
558 }
559
560 /**
561 * Check whether the user can edit, upload and create the image. This
562 * checks only against the current title; if it returns errors, it may
563 * very well be that another title will not give errors. Therefore
564 * isAllowed() should be called as well for generic is-user-blocked or
565 * can-user-upload checking.
566 *
567 * @param User $user User object to verify the permissions against
568 * @return mixed An array as returned by getUserPermissionsErrors or true
569 * in case the user has proper permissions.
570 */
571 public function verifyTitlePermissions( $user ) {
572 /**
573 * If the image is protected, non-sysop users won't be able
574 * to modify it by uploading a new revision.
575 */
576 $nt = $this->getTitle();
577 if ( is_null( $nt ) ) {
578 return true;
579 }
580 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
581 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
582 if ( !$nt->exists() ) {
583 $permErrorsCreate = $nt->getUserPermissionsErrors( 'create', $user );
584 } else {
585 $permErrorsCreate = array();
586 }
587 if ( $permErrors || $permErrorsUpload || $permErrorsCreate ) {
588 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
589 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
590
591 return $permErrors;
592 }
593
594 $overwriteError = $this->checkOverwrite( $user );
595 if ( $overwriteError !== true ) {
596 return array( $overwriteError );
597 }
598
599 return true;
600 }
601
602 /**
603 * Check for non fatal problems with the file.
604 *
605 * This should not assume that mTempPath is set.
606 *
607 * @return array Array of warnings
608 */
609 public function checkWarnings() {
610 global $wgLang;
611
612 $warnings = array();
613
614 $localFile = $this->getLocalFile();
615 $localFile->load( File::READ_LATEST );
616 $filename = $localFile->getName();
617
618 /**
619 * Check whether the resulting filename is different from the desired one,
620 * but ignore things like ucfirst() and spaces/underscore things
621 */
622 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName );
623 $comparableName = Title::capitalize( $comparableName, NS_FILE );
624
625 if ( $this->mDesiredDestName != $filename && $comparableName != $filename ) {
626 $warnings['badfilename'] = $filename;
627 // Debugging for bug 62241
628 wfDebugLog( 'upload', "Filename: '$filename', mDesiredDestName: "
629 . "'$this->mDesiredDestName', comparableName: '$comparableName'" );
630 }
631
632 // Check whether the file extension is on the unwanted list
633 global $wgCheckFileExtensions, $wgFileExtensions;
634 if ( $wgCheckFileExtensions ) {
635 $extensions = array_unique( $wgFileExtensions );
636 if ( !$this->checkFileExtension( $this->mFinalExtension, $extensions ) ) {
637 $warnings['filetype-unwanted-type'] = array( $this->mFinalExtension,
638 $wgLang->commaList( $extensions ), count( $extensions ) );
639 }
640 }
641
642 global $wgUploadSizeWarning;
643 if ( $wgUploadSizeWarning && ( $this->mFileSize > $wgUploadSizeWarning ) ) {
644 $warnings['large-file'] = array( $wgUploadSizeWarning, $this->mFileSize );
645 }
646
647 if ( $this->mFileSize == 0 ) {
648 $warnings['emptyfile'] = true;
649 }
650
651 $exists = self::getExistsWarning( $localFile );
652 if ( $exists !== false ) {
653 $warnings['exists'] = $exists;
654 }
655
656 if ( $localFile->wasDeleted() && !$localFile->exists() ) {
657 $warnings['was-deleted'] = $filename;
658 }
659
660 // Check dupes against existing files
661 $hash = $this->getTempFileSha1Base36();
662 $dupes = RepoGroup::singleton()->findBySha1( $hash );
663 $title = $this->getTitle();
664 // Remove all matches against self
665 foreach ( $dupes as $key => $dupe ) {
666 if ( $title->equals( $dupe->getTitle() ) ) {
667 unset( $dupes[$key] );
668 }
669 }
670 if ( $dupes ) {
671 $warnings['duplicate'] = $dupes;
672 }
673
674 // Check dupes against archives
675 $archivedFile = new ArchivedFile( null, 0, '', $hash );
676 if ( $archivedFile->getID() > 0 ) {
677 if ( $archivedFile->userCan( File::DELETED_FILE ) ) {
678 $warnings['duplicate-archive'] = $archivedFile->getName();
679 } else {
680 $warnings['duplicate-archive'] = '';
681 }
682 }
683
684 return $warnings;
685 }
686
687 /**
688 * Really perform the upload. Stores the file in the local repo, watches
689 * if necessary and runs the UploadComplete hook.
690 *
691 * @param string $comment
692 * @param string $pageText
693 * @param bool $watch
694 * @param User $user
695 * @param string[] $tags Change tags to add to the log entry and page revision.
696 * @return Status Indicating the whether the upload succeeded.
697 */
698 public function performUpload( $comment, $pageText, $watch, $user, $tags = array() ) {
699 $this->getLocalFile()->load( File::READ_LATEST );
700
701 $status = $this->getLocalFile()->upload(
702 $this->mTempPath,
703 $comment,
704 $pageText,
705 File::DELETE_SOURCE,
706 $this->mFileProps,
707 false,
708 $user,
709 $tags
710 );
711
712 if ( $status->isGood() ) {
713 if ( $watch ) {
714 WatchAction::doWatch(
715 $this->getLocalFile()->getTitle(),
716 $user,
717 WatchedItem::IGNORE_USER_RIGHTS
718 );
719 }
720 Hooks::run( 'UploadComplete', array( &$this ) );
721
722 $this->postProcessUpload();
723 }
724
725 return $status;
726 }
727
728 /**
729 * Perform extra steps after a successful upload.
730 *
731 * @since 1.25
732 */
733 public function postProcessUpload() {
734 global $wgUploadThumbnailRenderMap;
735
736 $jobs = array();
737
738 $sizes = $wgUploadThumbnailRenderMap;
739 rsort( $sizes );
740
741 $file = $this->getLocalFile();
742
743 foreach ( $sizes as $size ) {
744 if ( $file->isVectorized() || $file->getWidth() > $size ) {
745 $jobs[] = new ThumbnailRenderJob(
746 $file->getTitle(),
747 array( 'transformParams' => array( 'width' => $size ) )
748 );
749 }
750 }
751
752 if ( $jobs ) {
753 JobQueueGroup::singleton()->push( $jobs );
754 }
755 }
756
757 /**
758 * Returns the title of the file to be uploaded. Sets mTitleError in case
759 * the name was illegal.
760 *
761 * @return Title The title of the file or null in case the name was illegal
762 */
763 public function getTitle() {
764 if ( $this->mTitle !== false ) {
765 return $this->mTitle;
766 }
767 if ( !is_string( $this->mDesiredDestName ) ) {
768 $this->mTitleError = self::ILLEGAL_FILENAME;
769 $this->mTitle = null;
770
771 return $this->mTitle;
772 }
773 /* Assume that if a user specified File:Something.jpg, this is an error
774 * and that the namespace prefix needs to be stripped of.
775 */
776 $title = Title::newFromText( $this->mDesiredDestName );
777 if ( $title && $title->getNamespace() == NS_FILE ) {
778 $this->mFilteredName = $title->getDBkey();
779 } else {
780 $this->mFilteredName = $this->mDesiredDestName;
781 }
782
783 # oi_archive_name is max 255 bytes, which include a timestamp and an
784 # exclamation mark, so restrict file name to 240 bytes.
785 if ( strlen( $this->mFilteredName ) > 240 ) {
786 $this->mTitleError = self::FILENAME_TOO_LONG;
787 $this->mTitle = null;
788
789 return $this->mTitle;
790 }
791
792 /**
793 * Chop off any directories in the given filename. Then
794 * filter out illegal characters, and try to make a legible name
795 * out of it. We'll strip some silently that Title would die on.
796 */
797 $this->mFilteredName = wfStripIllegalFilenameChars( $this->mFilteredName );
798 /* Normalize to title form before we do any further processing */
799 $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
800 if ( is_null( $nt ) ) {
801 $this->mTitleError = self::ILLEGAL_FILENAME;
802 $this->mTitle = null;
803
804 return $this->mTitle;
805 }
806 $this->mFilteredName = $nt->getDBkey();
807
808 /**
809 * We'll want to blacklist against *any* 'extension', and use
810 * only the final one for the whitelist.
811 */
812 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName );
813
814 if ( count( $ext ) ) {
815 $this->mFinalExtension = trim( $ext[count( $ext ) - 1] );
816 } else {
817 $this->mFinalExtension = '';
818
819 # No extension, try guessing one
820 $magic = MimeMagic::singleton();
821 $mime = $magic->guessMimeType( $this->mTempPath );
822 if ( $mime !== 'unknown/unknown' ) {
823 # Get a space separated list of extensions
824 $extList = $magic->getExtensionsForType( $mime );
825 if ( $extList ) {
826 # Set the extension to the canonical extension
827 $this->mFinalExtension = strtok( $extList, ' ' );
828
829 # Fix up the other variables
830 $this->mFilteredName .= ".{$this->mFinalExtension}";
831 $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
832 $ext = array( $this->mFinalExtension );
833 }
834 }
835 }
836
837 /* Don't allow users to override the blacklist (check file extension) */
838 global $wgCheckFileExtensions, $wgStrictFileExtensions;
839 global $wgFileExtensions, $wgFileBlacklist;
840
841 $blackListedExtensions = $this->checkFileExtensionList( $ext, $wgFileBlacklist );
842
843 if ( $this->mFinalExtension == '' ) {
844 $this->mTitleError = self::FILETYPE_MISSING;
845 $this->mTitle = null;
846
847 return $this->mTitle;
848 } elseif ( $blackListedExtensions ||
849 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
850 !$this->checkFileExtension( $this->mFinalExtension, $wgFileExtensions ) )
851 ) {
852 $this->mBlackListedExtensions = $blackListedExtensions;
853 $this->mTitleError = self::FILETYPE_BADTYPE;
854 $this->mTitle = null;
855
856 return $this->mTitle;
857 }
858
859 // Windows may be broken with special characters, see bug 1780
860 if ( !preg_match( '/^[\x0-\x7f]*$/', $nt->getText() )
861 && !RepoGroup::singleton()->getLocalRepo()->backendSupportsUnicodePaths()
862 ) {
863 $this->mTitleError = self::WINDOWS_NONASCII_FILENAME;
864 $this->mTitle = null;
865
866 return $this->mTitle;
867 }
868
869 # If there was more than one "extension", reassemble the base
870 # filename to prevent bogus complaints about length
871 if ( count( $ext ) > 1 ) {
872 $iterations = count( $ext ) - 1;
873 for ( $i = 0; $i < $iterations; $i++ ) {
874 $partname .= '.' . $ext[$i];
875 }
876 }
877
878 if ( strlen( $partname ) < 1 ) {
879 $this->mTitleError = self::MIN_LENGTH_PARTNAME;
880 $this->mTitle = null;
881
882 return $this->mTitle;
883 }
884
885 $this->mTitle = $nt;
886
887 return $this->mTitle;
888 }
889
890 /**
891 * Return the local file and initializes if necessary.
892 *
893 * @return LocalFile|UploadStashFile|null
894 */
895 public function getLocalFile() {
896 if ( is_null( $this->mLocalFile ) ) {
897 $nt = $this->getTitle();
898 $this->mLocalFile = is_null( $nt ) ? null : wfLocalFile( $nt );
899 }
900
901 return $this->mLocalFile;
902 }
903
904 /**
905 * If the user does not supply all necessary information in the first upload
906 * form submission (either by accident or by design) then we may want to
907 * stash the file temporarily, get more information, and publish the file
908 * later.
909 *
910 * This method will stash a file in a temporary directory for later
911 * processing, and save the necessary descriptive info into the database.
912 * This method returns the file object, which also has a 'fileKey' property
913 * which can be passed through a form or API request to find this stashed
914 * file again.
915 *
916 * @param User $user
917 * @return UploadStashFile Stashed file
918 */
919 public function stashFile( User $user = null ) {
920 // was stashSessionFile
921
922 $stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash( $user );
923 $file = $stash->stashFile( $this->mTempPath, $this->getSourceType() );
924 $this->mLocalFile = $file;
925
926 return $file;
927 }
928
929 /**
930 * Stash a file in a temporary directory, returning a key which can be used
931 * to find the file again. See stashFile().
932 *
933 * @return string File key
934 */
935 public function stashFileGetKey() {
936 return $this->stashFile()->getFileKey();
937 }
938
939 /**
940 * alias for stashFileGetKey, for backwards compatibility
941 *
942 * @return string File key
943 */
944 public function stashSession() {
945 return $this->stashFileGetKey();
946 }
947
948 /**
949 * If we've modified the upload file we need to manually remove it
950 * on exit to clean up.
951 */
952 public function cleanupTempFile() {
953 if ( $this->mRemoveTempFile && $this->mTempPath && file_exists( $this->mTempPath ) ) {
954 wfDebug( __METHOD__ . ": Removing temporary file {$this->mTempPath}\n" );
955 unlink( $this->mTempPath );
956 }
957 }
958
959 public function getTempPath() {
960 return $this->mTempPath;
961 }
962
963 /**
964 * Split a file into a base name and all dot-delimited 'extensions'
965 * on the end. Some web server configurations will fall back to
966 * earlier pseudo-'extensions' to determine type and execute
967 * scripts, so the blacklist needs to check them all.
968 *
969 * @param string $filename
970 * @return array
971 */
972 public static function splitExtensions( $filename ) {
973 $bits = explode( '.', $filename );
974 $basename = array_shift( $bits );
975
976 return array( $basename, $bits );
977 }
978
979 /**
980 * Perform case-insensitive match against a list of file extensions.
981 * Returns true if the extension is in the list.
982 *
983 * @param string $ext
984 * @param array $list
985 * @return bool
986 */
987 public static function checkFileExtension( $ext, $list ) {
988 return in_array( strtolower( $ext ), $list );
989 }
990
991 /**
992 * Perform case-insensitive match against a list of file extensions.
993 * Returns an array of matching extensions.
994 *
995 * @param array $ext
996 * @param array $list
997 * @return bool
998 */
999 public static function checkFileExtensionList( $ext, $list ) {
1000 return array_intersect( array_map( 'strtolower', $ext ), $list );
1001 }
1002
1003 /**
1004 * Checks if the MIME type of the uploaded file matches the file extension.
1005 *
1006 * @param string $mime The MIME type of the uploaded file
1007 * @param string $extension The filename extension that the file is to be served with
1008 * @return bool
1009 */
1010 public static function verifyExtension( $mime, $extension ) {
1011 $magic = MimeMagic::singleton();
1012
1013 if ( !$mime || $mime == 'unknown' || $mime == 'unknown/unknown' ) {
1014 if ( !$magic->isRecognizableExtension( $extension ) ) {
1015 wfDebug( __METHOD__ . ": passing file with unknown detected mime type; " .
1016 "unrecognized extension '$extension', can't verify\n" );
1017
1018 return true;
1019 } else {
1020 wfDebug( __METHOD__ . ": rejecting file with unknown detected mime type; " .
1021 "recognized extension '$extension', so probably invalid file\n" );
1022
1023 return false;
1024 }
1025 }
1026
1027 $match = $magic->isMatchingExtension( $extension, $mime );
1028
1029 if ( $match === null ) {
1030 if ( $magic->getTypesForExtension( $extension ) !== null ) {
1031 wfDebug( __METHOD__ . ": No extension known for $mime, but we know a mime for $extension\n" );
1032
1033 return false;
1034 } else {
1035 wfDebug( __METHOD__ . ": no file extension known for mime type $mime, passing file\n" );
1036
1037 return true;
1038 }
1039 } elseif ( $match === true ) {
1040 wfDebug( __METHOD__ . ": mime type $mime matches extension $extension, passing file\n" );
1041
1042 /** @todo If it's a bitmap, make sure PHP or ImageMagick resp. can handle it! */
1043 return true;
1044 } else {
1045 wfDebug( __METHOD__
1046 . ": mime type $mime mismatches file extension $extension, rejecting file\n" );
1047
1048 return false;
1049 }
1050 }
1051
1052 /**
1053 * Heuristic for detecting files that *could* contain JavaScript instructions or
1054 * things that may look like HTML to a browser and are thus
1055 * potentially harmful. The present implementation will produce false
1056 * positives in some situations.
1057 *
1058 * @param string $file Pathname to the temporary upload file
1059 * @param string $mime The MIME type of the file
1060 * @param string $extension The extension of the file
1061 * @return bool True if the file contains something looking like embedded scripts
1062 */
1063 public static function detectScript( $file, $mime, $extension ) {
1064 global $wgAllowTitlesInSVG;
1065
1066 # ugly hack: for text files, always look at the entire file.
1067 # For binary field, just check the first K.
1068
1069 if ( strpos( $mime, 'text/' ) === 0 ) {
1070 $chunk = file_get_contents( $file );
1071 } else {
1072 $fp = fopen( $file, 'rb' );
1073 $chunk = fread( $fp, 1024 );
1074 fclose( $fp );
1075 }
1076
1077 $chunk = strtolower( $chunk );
1078
1079 if ( !$chunk ) {
1080 return false;
1081 }
1082
1083 # decode from UTF-16 if needed (could be used for obfuscation).
1084 if ( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
1085 $enc = 'UTF-16BE';
1086 } elseif ( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
1087 $enc = 'UTF-16LE';
1088 } else {
1089 $enc = null;
1090 }
1091
1092 if ( $enc ) {
1093 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
1094 }
1095
1096 $chunk = trim( $chunk );
1097
1098 /** @todo FIXME: Convert from UTF-16 if necessary! */
1099 wfDebug( __METHOD__ . ": checking for embedded scripts and HTML stuff\n" );
1100
1101 # check for HTML doctype
1102 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
1103 return true;
1104 }
1105
1106 // Some browsers will interpret obscure xml encodings as UTF-8, while
1107 // PHP/expat will interpret the given encoding in the xml declaration (bug 47304)
1108 if ( $extension == 'svg' || strpos( $mime, 'image/svg' ) === 0 ) {
1109 if ( self::checkXMLEncodingMissmatch( $file ) ) {
1110 return true;
1111 }
1112 }
1113
1114 /**
1115 * Internet Explorer for Windows performs some really stupid file type
1116 * autodetection which can cause it to interpret valid image files as HTML
1117 * and potentially execute JavaScript, creating a cross-site scripting
1118 * attack vectors.
1119 *
1120 * Apple's Safari browser also performs some unsafe file type autodetection
1121 * which can cause legitimate files to be interpreted as HTML if the
1122 * web server is not correctly configured to send the right content-type
1123 * (or if you're really uploading plain text and octet streams!)
1124 *
1125 * Returns true if IE is likely to mistake the given file for HTML.
1126 * Also returns true if Safari would mistake the given file for HTML
1127 * when served with a generic content-type.
1128 */
1129 $tags = array(
1130 '<a href',
1131 '<body',
1132 '<head',
1133 '<html', # also in safari
1134 '<img',
1135 '<pre',
1136 '<script', # also in safari
1137 '<table'
1138 );
1139
1140 if ( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1141 $tags[] = '<title';
1142 }
1143
1144 foreach ( $tags as $tag ) {
1145 if ( false !== strpos( $chunk, $tag ) ) {
1146 wfDebug( __METHOD__ . ": found something that may make it be mistaken for html: $tag\n" );
1147
1148 return true;
1149 }
1150 }
1151
1152 /*
1153 * look for JavaScript
1154 */
1155
1156 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1157 $chunk = Sanitizer::decodeCharReferences( $chunk );
1158
1159 # look for script-types
1160 if ( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
1161 wfDebug( __METHOD__ . ": found script types\n" );
1162
1163 return true;
1164 }
1165
1166 # look for html-style script-urls
1167 if ( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1168 wfDebug( __METHOD__ . ": found html-style script urls\n" );
1169
1170 return true;
1171 }
1172
1173 # look for css-style script-urls
1174 if ( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1175 wfDebug( __METHOD__ . ": found css-style script urls\n" );
1176
1177 return true;
1178 }
1179
1180 wfDebug( __METHOD__ . ": no scripts found\n" );
1181
1182 return false;
1183 }
1184
1185 /**
1186 * Check a whitelist of xml encodings that are known not to be interpreted differently
1187 * by the server's xml parser (expat) and some common browsers.
1188 *
1189 * @param string $file Pathname to the temporary upload file
1190 * @return bool True if the file contains an encoding that could be misinterpreted
1191 */
1192 public static function checkXMLEncodingMissmatch( $file ) {
1193 global $wgSVGMetadataCutoff;
1194 $contents = file_get_contents( $file, false, null, -1, $wgSVGMetadataCutoff );
1195 $encodingRegex = '!encoding[ \t\n\r]*=[ \t\n\r]*[\'"](.*?)[\'"]!si';
1196
1197 if ( preg_match( "!<\?xml\b(.*?)\?>!si", $contents, $matches ) ) {
1198 if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1199 && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings )
1200 ) {
1201 wfDebug( __METHOD__ . ": Found unsafe XML encoding '{$encMatch[1]}'\n" );
1202
1203 return true;
1204 }
1205 } elseif ( preg_match( "!<\?xml\b!si", $contents ) ) {
1206 // Start of XML declaration without an end in the first $wgSVGMetadataCutoff
1207 // bytes. There shouldn't be a legitimate reason for this to happen.
1208 wfDebug( __METHOD__ . ": Unmatched XML declaration start\n" );
1209
1210 return true;
1211 } elseif ( substr( $contents, 0, 4 ) == "\x4C\x6F\xA7\x94" ) {
1212 // EBCDIC encoded XML
1213 wfDebug( __METHOD__ . ": EBCDIC Encoded XML\n" );
1214
1215 return true;
1216 }
1217
1218 // It's possible the file is encoded with multi-byte encoding, so re-encode attempt to
1219 // detect the encoding in case is specifies an encoding not whitelisted in self::$safeXmlEncodings
1220 $attemptEncodings = array( 'UTF-16', 'UTF-16BE', 'UTF-32', 'UTF-32BE' );
1221 foreach ( $attemptEncodings as $encoding ) {
1222 MediaWiki\suppressWarnings();
1223 $str = iconv( $encoding, 'UTF-8', $contents );
1224 MediaWiki\restoreWarnings();
1225 if ( $str != '' && preg_match( "!<\?xml\b(.*?)\?>!si", $str, $matches ) ) {
1226 if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1227 && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings )
1228 ) {
1229 wfDebug( __METHOD__ . ": Found unsafe XML encoding '{$encMatch[1]}'\n" );
1230
1231 return true;
1232 }
1233 } elseif ( $str != '' && preg_match( "!<\?xml\b!si", $str ) ) {
1234 // Start of XML declaration without an end in the first $wgSVGMetadataCutoff
1235 // bytes. There shouldn't be a legitimate reason for this to happen.
1236 wfDebug( __METHOD__ . ": Unmatched XML declaration start\n" );
1237
1238 return true;
1239 }
1240 }
1241
1242 return false;
1243 }
1244
1245 /**
1246 * @param string $filename
1247 * @param bool $partial
1248 * @return mixed False of the file is verified (does not contain scripts), array otherwise.
1249 */
1250 protected function detectScriptInSvg( $filename, $partial ) {
1251 $this->mSVGNSError = false;
1252 $check = new XmlTypeCheck(
1253 $filename,
1254 array( $this, 'checkSvgScriptCallback' ),
1255 true,
1256 array( 'processing_instruction_handler' => 'UploadBase::checkSvgPICallback' )
1257 );
1258 if ( $check->wellFormed !== true ) {
1259 // Invalid xml (bug 58553)
1260 // But only when non-partial (bug 65724)
1261 return $partial ? false : array( 'uploadinvalidxml' );
1262 } elseif ( $check->filterMatch ) {
1263 if ( $this->mSVGNSError ) {
1264 return array( 'uploadscriptednamespace', $this->mSVGNSError );
1265 }
1266
1267 return $check->filterMatchType;
1268 }
1269
1270 return false;
1271 }
1272
1273 /**
1274 * Callback to filter SVG Processing Instructions.
1275 * @param string $target Processing instruction name
1276 * @param string $data Processing instruction attribute and value
1277 * @return bool (true if the filter identified something bad)
1278 */
1279 public static function checkSvgPICallback( $target, $data ) {
1280 // Don't allow external stylesheets (bug 57550)
1281 if ( preg_match( '/xml-stylesheet/i', $target ) ) {
1282 return array( 'upload-scripted-pi-callback' );
1283 }
1284
1285 return false;
1286 }
1287
1288 /**
1289 * @todo Replace this with a whitelist filter!
1290 * @param string $element
1291 * @param array $attribs
1292 * @return bool
1293 */
1294 public function checkSvgScriptCallback( $element, $attribs, $data = null ) {
1295
1296 list( $namespace, $strippedElement ) = $this->splitXmlNamespace( $element );
1297
1298 // We specifically don't include:
1299 // http://www.w3.org/1999/xhtml (bug 60771)
1300 static $validNamespaces = array(
1301 '',
1302 'adobe:ns:meta/',
1303 'http://creativecommons.org/ns#',
1304 'http://inkscape.sourceforge.net/dtd/sodipodi-0.dtd',
1305 'http://ns.adobe.com/adobeillustrator/10.0/',
1306 'http://ns.adobe.com/adobesvgviewerextensions/3.0/',
1307 'http://ns.adobe.com/extensibility/1.0/',
1308 'http://ns.adobe.com/flows/1.0/',
1309 'http://ns.adobe.com/illustrator/1.0/',
1310 'http://ns.adobe.com/imagereplacement/1.0/',
1311 'http://ns.adobe.com/pdf/1.3/',
1312 'http://ns.adobe.com/photoshop/1.0/',
1313 'http://ns.adobe.com/saveforweb/1.0/',
1314 'http://ns.adobe.com/variables/1.0/',
1315 'http://ns.adobe.com/xap/1.0/',
1316 'http://ns.adobe.com/xap/1.0/g/',
1317 'http://ns.adobe.com/xap/1.0/g/img/',
1318 'http://ns.adobe.com/xap/1.0/mm/',
1319 'http://ns.adobe.com/xap/1.0/rights/',
1320 'http://ns.adobe.com/xap/1.0/stype/dimensions#',
1321 'http://ns.adobe.com/xap/1.0/stype/font#',
1322 'http://ns.adobe.com/xap/1.0/stype/manifestitem#',
1323 'http://ns.adobe.com/xap/1.0/stype/resourceevent#',
1324 'http://ns.adobe.com/xap/1.0/stype/resourceref#',
1325 'http://ns.adobe.com/xap/1.0/t/pg/',
1326 'http://purl.org/dc/elements/1.1/',
1327 'http://purl.org/dc/elements/1.1',
1328 'http://schemas.microsoft.com/visio/2003/svgextensions/',
1329 'http://sodipodi.sourceforge.net/dtd/sodipodi-0.dtd',
1330 'http://taptrix.com/inkpad/svg_extensions',
1331 'http://web.resource.org/cc/',
1332 'http://www.freesoftware.fsf.org/bkchem/cdml',
1333 'http://www.inkscape.org/namespaces/inkscape',
1334 'http://www.opengis.net/gml',
1335 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
1336 'http://www.w3.org/2000/svg',
1337 'http://www.w3.org/tr/rec-rdf-syntax/',
1338 );
1339
1340 if ( !in_array( $namespace, $validNamespaces ) ) {
1341 wfDebug( __METHOD__ . ": Non-svg namespace '$namespace' in uploaded file.\n" );
1342 /** @todo Return a status object to a closure in XmlTypeCheck, for MW1.21+ */
1343 $this->mSVGNSError = $namespace;
1344
1345 return true;
1346 }
1347
1348 /*
1349 * check for elements that can contain javascript
1350 */
1351 if ( $strippedElement == 'script' ) {
1352 wfDebug( __METHOD__ . ": Found script element '$element' in uploaded file.\n" );
1353
1354 return array( 'uploaded-script-svg', $strippedElement );
1355 }
1356
1357 # e.g., <svg xmlns="http://www.w3.org/2000/svg">
1358 # <handler xmlns:ev="http://www.w3.org/2001/xml-events" ev:event="load">alert(1)</handler> </svg>
1359 if ( $strippedElement == 'handler' ) {
1360 wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file.\n" );
1361
1362 return array( 'uploaded-script-svg', $strippedElement );
1363 }
1364
1365 # SVG reported in Feb '12 that used xml:stylesheet to generate javascript block
1366 if ( $strippedElement == 'stylesheet' ) {
1367 wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file.\n" );
1368
1369 return array( 'uploaded-script-svg', $strippedElement );
1370 }
1371
1372 # Block iframes, in case they pass the namespace check
1373 if ( $strippedElement == 'iframe' ) {
1374 wfDebug( __METHOD__ . ": iframe in uploaded file.\n" );
1375
1376 return array( 'uploaded-script-svg', $strippedElement );
1377 }
1378
1379 # Check <style> css
1380 if ( $strippedElement == 'style'
1381 && self::checkCssFragment( Sanitizer::normalizeCss( $data ) )
1382 ) {
1383 wfDebug( __METHOD__ . ": hostile css in style element.\n" );
1384 return array( 'uploaded-hostile-svg' );
1385 }
1386
1387 foreach ( $attribs as $attrib => $value ) {
1388 $stripped = $this->stripXmlNamespace( $attrib );
1389 $value = strtolower( $value );
1390
1391 if ( substr( $stripped, 0, 2 ) == 'on' ) {
1392 wfDebug( __METHOD__
1393 . ": Found event-handler attribute '$attrib'='$value' in uploaded file.\n" );
1394
1395 return array( 'uploaded-event-handler-on-svg', $attrib, $value );
1396 }
1397
1398 # href with non-local target (don't allow http://, javascript:, etc)
1399 if ( $stripped == 'href'
1400 && strpos( $value, 'data:' ) !== 0
1401 && strpos( $value, '#' ) !== 0
1402 ) {
1403 if ( !( $strippedElement === 'a'
1404 && preg_match( '!^https?://!im', $value ) )
1405 ) {
1406 wfDebug( __METHOD__ . ": Found href attribute <$strippedElement "
1407 . "'$attrib'='$value' in uploaded file.\n" );
1408
1409 return array( 'uploaded-href-attribute-svg', $strippedElement, $attrib, $value );
1410 }
1411 }
1412
1413 # only allow data: targets that should be safe. This prevents vectors like,
1414 # image/svg, text/xml, application/xml, and text/html, which can contain scripts
1415 if ( $stripped == 'href' && strncasecmp( 'data:', $value, 5 ) === 0 ) {
1416 // rfc2397 parameters. This is only slightly slower than (;[\w;]+)*.
1417 // @codingStandardsIgnoreStart Generic.Files.LineLength
1418 $parameters = '(?>;[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+=(?>[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+|"(?>[\0-\x0c\x0e-\x21\x23-\x5b\x5d-\x7f]+|\\\\[\0-\x7f])*"))*(?:;base64)?';
1419 // @codingStandardsIgnoreEnd
1420
1421 if ( !preg_match( "!^data:\s*image/(gif|jpeg|jpg|png)$parameters,!i", $value ) ) {
1422 wfDebug( __METHOD__ . ": Found href to unwhitelisted data: uri "
1423 . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1424 return array( 'uploaded-href-unsafe-target-svg', $strippedElement, $attrib, $value );
1425 }
1426 }
1427
1428 # Change href with animate from (http://html5sec.org/#137).
1429 if ( $stripped === 'attributename'
1430 && $strippedElement === 'animate'
1431 && $this->stripXmlNamespace( $value ) == 'href'
1432 ) {
1433 wfDebug( __METHOD__ . ": Found animate that might be changing href using from "
1434 . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1435
1436 return array( 'uploaded-animate-svg', $strippedElement, $attrib, $value );
1437 }
1438
1439 # use set/animate to add event-handler attribute to parent
1440 if ( ( $strippedElement == 'set' || $strippedElement == 'animate' )
1441 && $stripped == 'attributename'
1442 && substr( $value, 0, 2 ) == 'on'
1443 ) {
1444 wfDebug( __METHOD__ . ": Found svg setting event-handler attribute with "
1445 . "\"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1446
1447 return array( 'uploaded-setting-event-handler-svg', $strippedElement, $stripped, $value );
1448 }
1449
1450 # use set to add href attribute to parent element
1451 if ( $strippedElement == 'set'
1452 && $stripped == 'attributename'
1453 && strpos( $value, 'href' ) !== false
1454 ) {
1455 wfDebug( __METHOD__ . ": Found svg setting href attribute '$value' in uploaded file.\n" );
1456
1457 return array( 'uploaded-setting-href-svg' );
1458 }
1459
1460 # use set to add a remote / data / script target to an element
1461 if ( $strippedElement == 'set'
1462 && $stripped == 'to'
1463 && preg_match( '!(http|https|data|script):!sim', $value )
1464 ) {
1465 wfDebug( __METHOD__ . ": Found svg setting attribute to '$value' in uploaded file.\n" );
1466
1467 return array( 'uploaded-wrong-setting-svg', $value );
1468 }
1469
1470 # use handler attribute with remote / data / script
1471 if ( $stripped == 'handler' && preg_match( '!(http|https|data|script):!sim', $value ) ) {
1472 wfDebug( __METHOD__ . ": Found svg setting handler with remote/data/script "
1473 . "'$attrib'='$value' in uploaded file.\n" );
1474
1475 return array( 'uploaded-setting-handler-svg', $attrib, $value );
1476 }
1477
1478 # use CSS styles to bring in remote code
1479 if ( $stripped == 'style'
1480 && self::checkCssFragment( Sanitizer::normalizeCss( $value ) )
1481 ) {
1482 wfDebug( __METHOD__ . ": Found svg setting a style with "
1483 . "remote url '$attrib'='$value' in uploaded file.\n" );
1484 return array( 'uploaded-remote-url-svg', $attrib, $value );
1485 }
1486
1487 # Several attributes can include css, css character escaping isn't allowed
1488 $cssAttrs = array( 'font', 'clip-path', 'fill', 'filter', 'marker',
1489 'marker-end', 'marker-mid', 'marker-start', 'mask', 'stroke' );
1490 if ( in_array( $stripped, $cssAttrs )
1491 && self::checkCssFragment( $value )
1492 ) {
1493 wfDebug( __METHOD__ . ": Found svg setting a style with "
1494 . "remote url '$attrib'='$value' in uploaded file.\n" );
1495 return array( 'uploaded-remote-url-svg', $attrib, $value );
1496 }
1497
1498 # image filters can pull in url, which could be svg that executes scripts
1499 if ( $strippedElement == 'image'
1500 && $stripped == 'filter'
1501 && preg_match( '!url\s*\(!sim', $value )
1502 ) {
1503 wfDebug( __METHOD__ . ": Found image filter with url: "
1504 . "\"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1505
1506 return array( 'uploaded-image-filter-svg', $strippedElement, $stripped, $value );
1507 }
1508 }
1509
1510 return false; // No scripts detected
1511 }
1512
1513 /**
1514 * Check a block of CSS or CSS fragment for anything that looks like
1515 * it is bringing in remote code.
1516 * @param string $value a string of CSS
1517 * @param bool $propOnly only check css properties (start regex with :)
1518 * @return bool true if the CSS contains an illegal string, false if otherwise
1519 */
1520 private static function checkCssFragment( $value ) {
1521
1522 # Forbid external stylesheets, for both reliability and to protect viewer's privacy
1523 if ( stripos( $value, '@import' ) !== false ) {
1524 return true;
1525 }
1526
1527 # We allow @font-face to embed fonts with data: urls, so we snip the string
1528 # 'url' out so this case won't match when we check for urls below
1529 $pattern = '!(@font-face\s*{[^}]*src:)url(\("data:;base64,)!im';
1530 $value = preg_replace( $pattern, '$1$2', $value );
1531
1532 # Check for remote and executable CSS. Unlike in Sanitizer::checkCss, the CSS
1533 # properties filter and accelerator don't seem to be useful for xss in SVG files.
1534 # Expression and -o-link don't seem to work either, but filtering them here in case.
1535 # Additionally, we catch remote urls like url("http:..., url('http:..., url(http:...,
1536 # but not local ones such as url("#..., url('#..., url(#....
1537 if ( preg_match( '!expression
1538 | -o-link\s*:
1539 | -o-link-source\s*:
1540 | -o-replace\s*:!imx', $value ) ) {
1541 return true;
1542 }
1543
1544 if ( preg_match_all(
1545 "!(\s*(url|image|image-set)\s*\(\s*[\"']?\s*[^#]+.*?\))!sim",
1546 $value,
1547 $matches
1548 ) !== 0
1549 ) {
1550 # TODO: redo this in one regex. Until then, url("#whatever") matches the first
1551 foreach ( $matches[1] as $match ) {
1552 if ( !preg_match( "!\s*(url|image|image-set)\s*\(\s*(#|'#|\"#)!im", $match ) ) {
1553 return true;
1554 }
1555 }
1556 }
1557
1558 if ( preg_match( '/[\000-\010\013\016-\037\177]/', $value ) ) {
1559 return true;
1560 }
1561
1562 return false;
1563 }
1564
1565 /**
1566 * Divide the element name passed by the xml parser to the callback into URI and prifix.
1567 * @param string $element
1568 * @return array Containing the namespace URI and prefix
1569 */
1570 private static function splitXmlNamespace( $element ) {
1571 // 'http://www.w3.org/2000/svg:script' -> array( 'http://www.w3.org/2000/svg', 'script' )
1572 $parts = explode( ':', strtolower( $element ) );
1573 $name = array_pop( $parts );
1574 $ns = implode( ':', $parts );
1575
1576 return array( $ns, $name );
1577 }
1578
1579 /**
1580 * @param string $name
1581 * @return string
1582 */
1583 private function stripXmlNamespace( $name ) {
1584 // 'http://www.w3.org/2000/svg:script' -> 'script'
1585 $parts = explode( ':', strtolower( $name ) );
1586
1587 return array_pop( $parts );
1588 }
1589
1590 /**
1591 * Generic wrapper function for a virus scanner program.
1592 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1593 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1594 *
1595 * @param string $file Pathname to the temporary upload file
1596 * @return mixed False if not virus is found, null if the scan fails or is disabled,
1597 * or a string containing feedback from the virus scanner if a virus was found.
1598 * If textual feedback is missing but a virus was found, this function returns true.
1599 */
1600 public static function detectVirus( $file ) {
1601 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1602
1603 if ( !$wgAntivirus ) {
1604 wfDebug( __METHOD__ . ": virus scanner disabled\n" );
1605
1606 return null;
1607 }
1608
1609 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1610 wfDebug( __METHOD__ . ": unknown virus scanner: $wgAntivirus\n" );
1611 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
1612 array( 'virus-badscanner', $wgAntivirus ) );
1613
1614 return wfMessage( 'virus-unknownscanner' )->text() . " $wgAntivirus";
1615 }
1616
1617 # look up scanner configuration
1618 $command = $wgAntivirusSetup[$wgAntivirus]['command'];
1619 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
1620 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
1621 $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
1622
1623 if ( strpos( $command, "%f" ) === false ) {
1624 # simple pattern: append file to scan
1625 $command .= " " . wfEscapeShellArg( $file );
1626 } else {
1627 # complex pattern: replace "%f" with file to scan
1628 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1629 }
1630
1631 wfDebug( __METHOD__ . ": running virus scan: $command \n" );
1632
1633 # execute virus scanner
1634 $exitCode = false;
1635
1636 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1637 # that does not seem to be worth the pain.
1638 # Ask me (Duesentrieb) about it if it's ever needed.
1639 $output = wfShellExecWithStderr( $command, $exitCode );
1640
1641 # map exit code to AV_xxx constants.
1642 $mappedCode = $exitCode;
1643 if ( $exitCodeMap ) {
1644 if ( isset( $exitCodeMap[$exitCode] ) ) {
1645 $mappedCode = $exitCodeMap[$exitCode];
1646 } elseif ( isset( $exitCodeMap["*"] ) ) {
1647 $mappedCode = $exitCodeMap["*"];
1648 }
1649 }
1650
1651 /* NB: AV_NO_VIRUS is 0 but AV_SCAN_FAILED is false,
1652 * so we need the strict equalities === and thus can't use a switch here
1653 */
1654 if ( $mappedCode === AV_SCAN_FAILED ) {
1655 # scan failed (code was mapped to false by $exitCodeMap)
1656 wfDebug( __METHOD__ . ": failed to scan $file (code $exitCode).\n" );
1657
1658 $output = $wgAntivirusRequired
1659 ? wfMessage( 'virus-scanfailed', array( $exitCode ) )->text()
1660 : null;
1661 } elseif ( $mappedCode === AV_SCAN_ABORTED ) {
1662 # scan failed because filetype is unknown (probably imune)
1663 wfDebug( __METHOD__ . ": unsupported file type $file (code $exitCode).\n" );
1664 $output = null;
1665 } elseif ( $mappedCode === AV_NO_VIRUS ) {
1666 # no virus found
1667 wfDebug( __METHOD__ . ": file passed virus scan.\n" );
1668 $output = false;
1669 } else {
1670 $output = trim( $output );
1671
1672 if ( !$output ) {
1673 $output = true; # if there's no output, return true
1674 } elseif ( $msgPattern ) {
1675 $groups = array();
1676 if ( preg_match( $msgPattern, $output, $groups ) ) {
1677 if ( $groups[1] ) {
1678 $output = $groups[1];
1679 }
1680 }
1681 }
1682
1683 wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output \n" );
1684 }
1685
1686 return $output;
1687 }
1688
1689 /**
1690 * Check if there's an overwrite conflict and, if so, if restrictions
1691 * forbid this user from performing the upload.
1692 *
1693 * @param User $user
1694 *
1695 * @return mixed True on success, array on failure
1696 */
1697 private function checkOverwrite( $user ) {
1698 // First check whether the local file can be overwritten
1699 $file = $this->getLocalFile();
1700 $file->load( File::READ_LATEST );
1701 if ( $file->exists() ) {
1702 if ( !self::userCanReUpload( $user, $file ) ) {
1703 return array( 'fileexists-forbidden', $file->getName() );
1704 } else {
1705 return true;
1706 }
1707 }
1708
1709 /* Check shared conflicts: if the local file does not exist, but
1710 * wfFindFile finds a file, it exists in a shared repository.
1711 */
1712 $file = wfFindFile( $this->getTitle(), array( 'latest' => true ) );
1713 if ( $file && !$user->isAllowed( 'reupload-shared' ) ) {
1714 return array( 'fileexists-shared-forbidden', $file->getName() );
1715 }
1716
1717 return true;
1718 }
1719
1720 /**
1721 * Check if a user is the last uploader
1722 *
1723 * @param User $user
1724 * @param File $img
1725 * @return bool
1726 */
1727 public static function userCanReUpload( User $user, File $img ) {
1728 if ( $user->isAllowed( 'reupload' ) ) {
1729 return true; // non-conditional
1730 } elseif ( !$user->isAllowed( 'reupload-own' ) ) {
1731 return false;
1732 }
1733
1734 if ( !( $img instanceof LocalFile ) ) {
1735 return false;
1736 }
1737
1738 $img->load();
1739
1740 return $user->getId() == $img->getUser( 'id' );
1741 }
1742
1743 /**
1744 * Helper function that does various existence checks for a file.
1745 * The following checks are performed:
1746 * - The file exists
1747 * - Article with the same name as the file exists
1748 * - File exists with normalized extension
1749 * - The file looks like a thumbnail and the original exists
1750 *
1751 * @param File $file The File object to check
1752 * @return mixed False if the file does not exists, else an array
1753 */
1754 public static function getExistsWarning( $file ) {
1755 if ( $file->exists() ) {
1756 return array( 'warning' => 'exists', 'file' => $file );
1757 }
1758
1759 if ( $file->getTitle()->getArticleID() ) {
1760 return array( 'warning' => 'page-exists', 'file' => $file );
1761 }
1762
1763 if ( strpos( $file->getName(), '.' ) == false ) {
1764 $partname = $file->getName();
1765 $extension = '';
1766 } else {
1767 $n = strrpos( $file->getName(), '.' );
1768 $extension = substr( $file->getName(), $n + 1 );
1769 $partname = substr( $file->getName(), 0, $n );
1770 }
1771 $normalizedExtension = File::normalizeExtension( $extension );
1772
1773 if ( $normalizedExtension != $extension ) {
1774 // We're not using the normalized form of the extension.
1775 // Normal form is lowercase, using most common of alternate
1776 // extensions (eg 'jpg' rather than 'JPEG').
1777
1778 // Check for another file using the normalized form...
1779 $nt_lc = Title::makeTitle( NS_FILE, "{$partname}.{$normalizedExtension}" );
1780 $file_lc = wfLocalFile( $nt_lc );
1781
1782 if ( $file_lc->exists() ) {
1783 return array(
1784 'warning' => 'exists-normalized',
1785 'file' => $file,
1786 'normalizedFile' => $file_lc
1787 );
1788 }
1789 }
1790
1791 // Check for files with the same name but a different extension
1792 $similarFiles = RepoGroup::singleton()->getLocalRepo()->findFilesByPrefix(
1793 "{$partname}.", 1 );
1794 if ( count( $similarFiles ) ) {
1795 return array(
1796 'warning' => 'exists-normalized',
1797 'file' => $file,
1798 'normalizedFile' => $similarFiles[0],
1799 );
1800 }
1801
1802 if ( self::isThumbName( $file->getName() ) ) {
1803 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1804 $nt_thb = Title::newFromText(
1805 substr( $partname, strpos( $partname, '-' ) + 1 ) . '.' . $extension,
1806 NS_FILE
1807 );
1808 $file_thb = wfLocalFile( $nt_thb );
1809 if ( $file_thb->exists() ) {
1810 return array(
1811 'warning' => 'thumb',
1812 'file' => $file,
1813 'thumbFile' => $file_thb
1814 );
1815 } else {
1816 // File does not exist, but we just don't like the name
1817 return array(
1818 'warning' => 'thumb-name',
1819 'file' => $file,
1820 'thumbFile' => $file_thb
1821 );
1822 }
1823 }
1824
1825 foreach ( self::getFilenamePrefixBlacklist() as $prefix ) {
1826 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1827 return array(
1828 'warning' => 'bad-prefix',
1829 'file' => $file,
1830 'prefix' => $prefix
1831 );
1832 }
1833 }
1834
1835 return false;
1836 }
1837
1838 /**
1839 * Helper function that checks whether the filename looks like a thumbnail
1840 * @param string $filename
1841 * @return bool
1842 */
1843 public static function isThumbName( $filename ) {
1844 $n = strrpos( $filename, '.' );
1845 $partname = $n ? substr( $filename, 0, $n ) : $filename;
1846
1847 return (
1848 substr( $partname, 3, 3 ) == 'px-' ||
1849 substr( $partname, 2, 3 ) == 'px-'
1850 ) &&
1851 preg_match( "/[0-9]{2}/", substr( $partname, 0, 2 ) );
1852 }
1853
1854 /**
1855 * Get a list of blacklisted filename prefixes from [[MediaWiki:Filename-prefix-blacklist]]
1856 *
1857 * @return array List of prefixes
1858 */
1859 public static function getFilenamePrefixBlacklist() {
1860 $blacklist = array();
1861 $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
1862 if ( !$message->isDisabled() ) {
1863 $lines = explode( "\n", $message->plain() );
1864 foreach ( $lines as $line ) {
1865 // Remove comment lines
1866 $comment = substr( trim( $line ), 0, 1 );
1867 if ( $comment == '#' || $comment == '' ) {
1868 continue;
1869 }
1870 // Remove additional comments after a prefix
1871 $comment = strpos( $line, '#' );
1872 if ( $comment > 0 ) {
1873 $line = substr( $line, 0, $comment - 1 );
1874 }
1875 $blacklist[] = trim( $line );
1876 }
1877 }
1878
1879 return $blacklist;
1880 }
1881
1882 /**
1883 * Gets image info about the file just uploaded.
1884 *
1885 * Also has the effect of setting metadata to be an 'indexed tag name' in
1886 * returned API result if 'metadata' was requested. Oddly, we have to pass
1887 * the "result" object down just so it can do that with the appropriate
1888 * format, presumably.
1889 *
1890 * @param ApiResult $result
1891 * @return array Image info
1892 */
1893 public function getImageInfo( $result ) {
1894 $file = $this->getLocalFile();
1895 /** @todo This cries out for refactoring.
1896 * We really want to say $file->getAllInfo(); here.
1897 * Perhaps "info" methods should be moved into files, and the API should
1898 * just wrap them in queries.
1899 */
1900 if ( $file instanceof UploadStashFile ) {
1901 $imParam = ApiQueryStashImageInfo::getPropertyNames();
1902 $info = ApiQueryStashImageInfo::getInfo( $file, array_flip( $imParam ), $result );
1903 } else {
1904 $imParam = ApiQueryImageInfo::getPropertyNames();
1905 $info = ApiQueryImageInfo::getInfo( $file, array_flip( $imParam ), $result );
1906 }
1907
1908 return $info;
1909 }
1910
1911 /**
1912 * @param array $error
1913 * @return Status
1914 */
1915 public function convertVerifyErrorToStatus( $error ) {
1916 $code = $error['status'];
1917 unset( $code['status'] );
1918
1919 return Status::newFatal( $this->getVerificationErrorCode( $code ), $error );
1920 }
1921
1922 /**
1923 * Get the MediaWiki maximum uploaded file size for given type of upload, based on
1924 * $wgMaxUploadSize.
1925 *
1926 * @param null|string $forType
1927 * @return int
1928 */
1929 public static function getMaxUploadSize( $forType = null ) {
1930 global $wgMaxUploadSize;
1931
1932 if ( is_array( $wgMaxUploadSize ) ) {
1933 if ( !is_null( $forType ) && isset( $wgMaxUploadSize[$forType] ) ) {
1934 return $wgMaxUploadSize[$forType];
1935 } else {
1936 return $wgMaxUploadSize['*'];
1937 }
1938 } else {
1939 return intval( $wgMaxUploadSize );
1940 }
1941 }
1942
1943 /**
1944 * Get the PHP maximum uploaded file size, based on ini settings. If there is no limit or the
1945 * limit can't be guessed, returns a very large number (PHP_INT_MAX).
1946 *
1947 * @since 1.27
1948 * @return int
1949 */
1950 public static function getMaxPhpUploadSize() {
1951 $phpMaxFileSize = wfShorthandToInteger(
1952 ini_get( 'upload_max_filesize' ) ?: ini_get( 'hhvm.server.upload.upload_max_file_size' ),
1953 PHP_INT_MAX
1954 );
1955 $phpMaxPostSize = wfShorthandToInteger(
1956 ini_get( 'post_max_size' ) ?: ini_get( 'hhvm.server.max_post_size' ),
1957 PHP_INT_MAX
1958 ) ?: PHP_INT_MAX;
1959 return min( $phpMaxFileSize, $phpMaxPostSize );
1960 }
1961
1962 /**
1963 * Get the current status of a chunked upload (used for polling)
1964 *
1965 * The value will be read from cache.
1966 *
1967 * @param User $user
1968 * @param string $statusKey
1969 * @return Status[]|bool
1970 */
1971 public static function getSessionStatus( User $user, $statusKey ) {
1972 $key = wfMemcKey( 'uploadstatus', $user->getId() ?: md5( $user->getName() ), $statusKey );
1973
1974 return ObjectCache::getMainStashInstance()->get( $key );
1975 }
1976
1977 /**
1978 * Set the current status of a chunked upload (used for polling)
1979 *
1980 * The value will be set in cache for 1 day
1981 *
1982 * @param User $user
1983 * @param string $statusKey
1984 * @param array|bool $value
1985 * @return void
1986 */
1987 public static function setSessionStatus( User $user, $statusKey, $value ) {
1988 $key = wfMemcKey( 'uploadstatus', $user->getId() ?: md5( $user->getName() ), $statusKey );
1989
1990 $cache = ObjectCache::getMainStashInstance();
1991 if ( $value === false ) {
1992 $cache->delete( $key );
1993 } else {
1994 $cache->set( $key, $value, $cache::TTL_DAY );
1995 }
1996 }
1997 }