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