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