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