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