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