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