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