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