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