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