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