746c16d0e2895145f2d099e4073ef96d694e1374
[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 XXX
803 if ( wfIsWindows() && !preg_match( '/^[\x0-\x7f]*$/', $nt->getText() ) ) {
804 $this->mTitleError = self::WINDOWS_NONASCII_FILENAME;
805 $this->mTitle = null;
806 return $this->mTitle;
807 }
808
809 # If there was more than one "extension", reassemble the base
810 # filename to prevent bogus complaints about length
811 if ( count( $ext ) > 1 ) {
812 for ( $i = 0; $i < count( $ext ) - 1; $i++ ) {
813 $partname .= '.' . $ext[$i];
814 }
815 }
816
817 if ( strlen( $partname ) < 1 ) {
818 $this->mTitleError = self::MIN_LENGTH_PARTNAME;
819 $this->mTitle = null;
820 return $this->mTitle;
821 }
822
823 $this->mTitle = $nt;
824 return $this->mTitle;
825 }
826
827 /**
828 * Return the local file and initializes if necessary.
829 *
830 * @return LocalFile|null
831 */
832 public function getLocalFile() {
833 if ( is_null( $this->mLocalFile ) ) {
834 $nt = $this->getTitle();
835 $this->mLocalFile = is_null( $nt ) ? null : wfLocalFile( $nt );
836 }
837 return $this->mLocalFile;
838 }
839
840 /**
841 * If the user does not supply all necessary information in the first upload form submission (either by accident or
842 * by design) then we may want to stash the file temporarily, get more information, and publish the file later.
843 *
844 * This method will stash a file in a temporary directory for later processing, and save the necessary descriptive info
845 * into the database.
846 * This method returns the file object, which also has a 'fileKey' property which can be passed through a form or
847 * API request to find this stashed file again.
848 *
849 * @param User $user
850 * @return UploadStashFile Stashed file
851 */
852 public function stashFile( User $user = null ) {
853 // was stashSessionFile
854 wfProfileIn( __METHOD__ );
855
856 $stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash( $user );
857 $file = $stash->stashFile( $this->mTempPath, $this->getSourceType() );
858 $this->mLocalFile = $file;
859
860 wfProfileOut( __METHOD__ );
861 return $file;
862 }
863
864 /**
865 * Stash a file in a temporary directory, returning a key which can be used to find the file again. See stashFile().
866 *
867 * @return string File key
868 */
869 public function stashFileGetKey() {
870 return $this->stashFile()->getFileKey();
871 }
872
873 /**
874 * alias for stashFileGetKey, for backwards compatibility
875 *
876 * @return string File key
877 */
878 public function stashSession() {
879 return $this->stashFileGetKey();
880 }
881
882 /**
883 * If we've modified the upload file we need to manually remove it
884 * on exit to clean up.
885 */
886 public function cleanupTempFile() {
887 if ( $this->mRemoveTempFile && $this->mTempPath && file_exists( $this->mTempPath ) ) {
888 wfDebug( __METHOD__ . ": Removing temporary file {$this->mTempPath}\n" );
889 unlink( $this->mTempPath );
890 }
891 }
892
893 public function getTempPath() {
894 return $this->mTempPath;
895 }
896
897 /**
898 * Split a file into a base name and all dot-delimited 'extensions'
899 * on the end. Some web server configurations will fall back to
900 * earlier pseudo-'extensions' to determine type and execute
901 * scripts, so the blacklist needs to check them all.
902 *
903 * @param string $filename
904 * @return array
905 */
906 public static function splitExtensions( $filename ) {
907 $bits = explode( '.', $filename );
908 $basename = array_shift( $bits );
909 return array( $basename, $bits );
910 }
911
912 /**
913 * Perform case-insensitive match against a list of file extensions.
914 * Returns true if the extension is in the list.
915 *
916 * @param string $ext
917 * @param array $list
918 * @return bool
919 */
920 public static function checkFileExtension( $ext, $list ) {
921 return in_array( strtolower( $ext ), $list );
922 }
923
924 /**
925 * Perform case-insensitive match against a list of file extensions.
926 * Returns an array of matching extensions.
927 *
928 * @param array $ext
929 * @param array $list
930 * @return bool
931 */
932 public static function checkFileExtensionList( $ext, $list ) {
933 return array_intersect( array_map( 'strtolower', $ext ), $list );
934 }
935
936 /**
937 * Checks if the mime type of the uploaded file matches the file extension.
938 *
939 * @param string $mime The mime type of the uploaded file
940 * @param string $extension The filename extension that the file is to be served with
941 * @return bool
942 */
943 public static function verifyExtension( $mime, $extension ) {
944 $magic = MimeMagic::singleton();
945
946 if ( !$mime || $mime == 'unknown' || $mime == 'unknown/unknown' ) {
947 if ( !$magic->isRecognizableExtension( $extension ) ) {
948 wfDebug( __METHOD__ . ": passing file with unknown detected mime type; " .
949 "unrecognized extension '$extension', can't verify\n" );
950 return true;
951 } else {
952 wfDebug( __METHOD__ . ": rejecting file with unknown detected mime type; " .
953 "recognized extension '$extension', so probably invalid file\n" );
954 return false;
955 }
956 }
957
958 $match = $magic->isMatchingExtension( $extension, $mime );
959
960 if ( $match === null ) {
961 if ( $magic->getTypesForExtension( $extension ) !== null ) {
962 wfDebug( __METHOD__ . ": No extension known for $mime, but we know a mime for $extension\n" );
963 return false;
964 } else {
965 wfDebug( __METHOD__ . ": no file extension known for mime type $mime, passing file\n" );
966 return true;
967 }
968 } elseif ( $match === true ) {
969 wfDebug( __METHOD__ . ": mime type $mime matches extension $extension, passing file\n" );
970
971 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
972 return true;
973
974 } else {
975 wfDebug( __METHOD__ . ": mime type $mime mismatches file extension $extension, rejecting file\n" );
976 return false;
977 }
978 }
979
980 /**
981 * Heuristic for detecting files that *could* contain JavaScript instructions or
982 * things that may look like HTML to a browser and are thus
983 * potentially harmful. The present implementation will produce false
984 * positives in some situations.
985 *
986 * @param string $file Pathname to the temporary upload file
987 * @param string $mime The mime type of the file
988 * @param string $extension The extension of the file
989 * @return bool True if the file contains something looking like embedded scripts
990 */
991 public static function detectScript( $file, $mime, $extension ) {
992 global $wgAllowTitlesInSVG;
993 wfProfileIn( __METHOD__ );
994
995 # ugly hack: for text files, always look at the entire file.
996 # For binary field, just check the first K.
997
998 if ( strpos( $mime, 'text/' ) === 0 ) {
999 $chunk = file_get_contents( $file );
1000 } else {
1001 $fp = fopen( $file, 'rb' );
1002 $chunk = fread( $fp, 1024 );
1003 fclose( $fp );
1004 }
1005
1006 $chunk = strtolower( $chunk );
1007
1008 if ( !$chunk ) {
1009 wfProfileOut( __METHOD__ );
1010 return false;
1011 }
1012
1013 # decode from UTF-16 if needed (could be used for obfuscation).
1014 if ( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
1015 $enc = 'UTF-16BE';
1016 } elseif ( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
1017 $enc = 'UTF-16LE';
1018 } else {
1019 $enc = null;
1020 }
1021
1022 if ( $enc ) {
1023 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
1024 }
1025
1026 $chunk = trim( $chunk );
1027
1028 # @todo FIXME: Convert from UTF-16 if necessary!
1029 wfDebug( __METHOD__ . ": checking for embedded scripts and HTML stuff\n" );
1030
1031 # check for HTML doctype
1032 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
1033 wfProfileOut( __METHOD__ );
1034 return true;
1035 }
1036
1037 // Some browsers will interpret obscure xml encodings as UTF-8, while
1038 // PHP/expat will interpret the given encoding in the xml declaration (bug 47304)
1039 if ( $extension == 'svg' || strpos( $mime, 'image/svg' ) === 0 ) {
1040 if ( self::checkXMLEncodingMissmatch( $file ) ) {
1041 wfProfileOut( __METHOD__ );
1042 return true;
1043 }
1044 }
1045
1046 /**
1047 * Internet Explorer for Windows performs some really stupid file type
1048 * autodetection which can cause it to interpret valid image files as HTML
1049 * and potentially execute JavaScript, creating a cross-site scripting
1050 * attack vectors.
1051 *
1052 * Apple's Safari browser also performs some unsafe file type autodetection
1053 * which can cause legitimate files to be interpreted as HTML if the
1054 * web server is not correctly configured to send the right content-type
1055 * (or if you're really uploading plain text and octet streams!)
1056 *
1057 * Returns true if IE is likely to mistake the given file for HTML.
1058 * Also returns true if Safari would mistake the given file for HTML
1059 * when served with a generic content-type.
1060 */
1061 $tags = array(
1062 '<a href',
1063 '<body',
1064 '<head',
1065 '<html', #also in safari
1066 '<img',
1067 '<pre',
1068 '<script', #also in safari
1069 '<table'
1070 );
1071
1072 if ( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1073 $tags[] = '<title';
1074 }
1075
1076 foreach ( $tags as $tag ) {
1077 if ( false !== strpos( $chunk, $tag ) ) {
1078 wfDebug( __METHOD__ . ": found something that may make it be mistaken for html: $tag\n" );
1079 wfProfileOut( __METHOD__ );
1080 return true;
1081 }
1082 }
1083
1084 /*
1085 * look for JavaScript
1086 */
1087
1088 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1089 $chunk = Sanitizer::decodeCharReferences( $chunk );
1090
1091 # look for script-types
1092 if ( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
1093 wfDebug( __METHOD__ . ": found script types\n" );
1094 wfProfileOut( __METHOD__ );
1095 return true;
1096 }
1097
1098 # look for html-style script-urls
1099 if ( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1100 wfDebug( __METHOD__ . ": found html-style script urls\n" );
1101 wfProfileOut( __METHOD__ );
1102 return true;
1103 }
1104
1105 # look for css-style script-urls
1106 if ( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1107 wfDebug( __METHOD__ . ": found css-style script urls\n" );
1108 wfProfileOut( __METHOD__ );
1109 return true;
1110 }
1111
1112 wfDebug( __METHOD__ . ": no scripts found\n" );
1113 wfProfileOut( __METHOD__ );
1114 return false;
1115 }
1116
1117 /**
1118 * Check a whitelist of xml encodings that are known not to be interpreted differently
1119 * by the server's xml parser (expat) and some common browsers.
1120 *
1121 * @param string $file Pathname to the temporary upload file
1122 * @return bool True if the file contains an encoding that could be misinterpreted
1123 */
1124 public static function checkXMLEncodingMissmatch( $file ) {
1125 global $wgSVGMetadataCutoff;
1126 $contents = file_get_contents( $file, false, null, -1, $wgSVGMetadataCutoff );
1127 $encodingRegex = '!encoding[ \t\n\r]*=[ \t\n\r]*[\'"](.*?)[\'"]!si';
1128
1129 if ( preg_match( "!<\?xml\b(.*?)\?>!si", $contents, $matches ) ) {
1130 if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1131 && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings )
1132 ) {
1133 wfDebug( __METHOD__ . ": Found unsafe XML encoding '{$encMatch[1]}'\n" );
1134 return true;
1135 }
1136 } elseif ( preg_match( "!<\?xml\b!si", $contents ) ) {
1137 // Start of XML declaration without an end in the first $wgSVGMetadataCutoff
1138 // bytes. There shouldn't be a legitimate reason for this to happen.
1139 wfDebug( __METHOD__ . ": Unmatched XML declaration start\n" );
1140 return true;
1141 } elseif ( substr( $contents, 0, 4 ) == "\x4C\x6F\xA7\x94" ) {
1142 // EBCDIC encoded XML
1143 wfDebug( __METHOD__ . ": EBCDIC Encoded XML\n" );
1144 return true;
1145 }
1146
1147 // It's possible the file is encoded with multi-byte encoding, so re-encode attempt to
1148 // detect the encoding in case is specifies an encoding not whitelisted in self::$safeXmlEncodings
1149 $attemptEncodings = array( 'UTF-16', 'UTF-16BE', 'UTF-32', 'UTF-32BE' );
1150 foreach ( $attemptEncodings as $encoding ) {
1151 wfSuppressWarnings();
1152 $str = iconv( $encoding, 'UTF-8', $contents );
1153 wfRestoreWarnings();
1154 if ( $str != '' && preg_match( "!<\?xml\b(.*?)\?>!si", $str, $matches ) ) {
1155 if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1156 && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings )
1157 ) {
1158 wfDebug( __METHOD__ . ": Found unsafe XML encoding '{$encMatch[1]}'\n" );
1159 return true;
1160 }
1161 } elseif ( $str != '' && preg_match( "!<\?xml\b!si", $str ) ) {
1162 // Start of XML declaration without an end in the first $wgSVGMetadataCutoff
1163 // bytes. There shouldn't be a legitimate reason for this to happen.
1164 wfDebug( __METHOD__ . ": Unmatched XML declaration start\n" );
1165 return true;
1166 }
1167 }
1168
1169 return false;
1170 }
1171
1172 /**
1173 * @param string $filename
1174 * @return mixed False of the file is verified (does not contain scripts), array otherwise.
1175 */
1176 protected function detectScriptInSvg( $filename ) {
1177 $this->mSVGNSError = false;
1178 $check = new XmlTypeCheck(
1179 $filename,
1180 array( $this, 'checkSvgScriptCallback' ),
1181 true,
1182 array( 'processing_instruction_handler' => 'UploadBase::checkSvgPICallback' )
1183 );
1184 if ( $check->wellFormed !== true ) {
1185 // Invalid xml (bug 58553)
1186 return array( 'uploadinvalidxml' );
1187 } elseif ( $check->filterMatch ) {
1188 if ( $this->mSVGNSError ) {
1189 return array( 'uploadscriptednamespace', $this->mSVGNSError );
1190 }
1191 return array( 'uploadscripted' );
1192 }
1193 return false;
1194 }
1195
1196 /**
1197 * Callback to filter SVG Processing Instructions.
1198 * @param string $target processing instruction name
1199 * @param string $data processing instruction attribute and value
1200 * @return bool (true if the filter identified something bad)
1201 */
1202 public static function checkSvgPICallback( $target, $data ) {
1203 // Don't allow external stylesheets (bug 57550)
1204 if ( preg_match( '/xml-stylesheet/i', $target ) ) {
1205 return true;
1206 }
1207 return false;
1208 }
1209
1210 /**
1211 * @todo Replace this with a whitelist filter!
1212 * @param string $element
1213 * @param array $attribs
1214 * @return bool
1215 */
1216 public function checkSvgScriptCallback( $element, $attribs ) {
1217 list( $namespace, $strippedElement ) = $this->splitXmlNamespace( $element );
1218
1219 static $validNamespaces = array(
1220 '',
1221 'adobe:ns:meta/',
1222 'http://creativecommons.org/ns#',
1223 'http://inkscape.sourceforge.net/dtd/sodipodi-0.dtd',
1224 'http://ns.adobe.com/adobeillustrator/10.0/',
1225 'http://ns.adobe.com/adobesvgviewerextensions/3.0/',
1226 'http://ns.adobe.com/extensibility/1.0/',
1227 'http://ns.adobe.com/flows/1.0/',
1228 'http://ns.adobe.com/illustrator/1.0/',
1229 'http://ns.adobe.com/imagereplacement/1.0/',
1230 'http://ns.adobe.com/pdf/1.3/',
1231 'http://ns.adobe.com/photoshop/1.0/',
1232 'http://ns.adobe.com/saveforweb/1.0/',
1233 'http://ns.adobe.com/variables/1.0/',
1234 'http://ns.adobe.com/xap/1.0/',
1235 'http://ns.adobe.com/xap/1.0/g/',
1236 'http://ns.adobe.com/xap/1.0/g/img/',
1237 'http://ns.adobe.com/xap/1.0/mm/',
1238 'http://ns.adobe.com/xap/1.0/rights/',
1239 'http://ns.adobe.com/xap/1.0/stype/dimensions#',
1240 'http://ns.adobe.com/xap/1.0/stype/font#',
1241 'http://ns.adobe.com/xap/1.0/stype/manifestitem#',
1242 'http://ns.adobe.com/xap/1.0/stype/resourceevent#',
1243 'http://ns.adobe.com/xap/1.0/stype/resourceref#',
1244 'http://ns.adobe.com/xap/1.0/t/pg/',
1245 'http://purl.org/dc/elements/1.1/',
1246 'http://purl.org/dc/elements/1.1',
1247 'http://schemas.microsoft.com/visio/2003/svgextensions/',
1248 'http://sodipodi.sourceforge.net/dtd/sodipodi-0.dtd',
1249 'http://web.resource.org/cc/',
1250 'http://www.freesoftware.fsf.org/bkchem/cdml',
1251 'http://www.inkscape.org/namespaces/inkscape',
1252 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
1253 'http://www.w3.org/2000/svg',
1254 );
1255
1256 if ( !in_array( $namespace, $validNamespaces ) ) {
1257 wfDebug( __METHOD__ . ": Non-svg namespace '$namespace' in uploaded file.\n" );
1258 // @TODO return a status object to a closure in XmlTypeCheck, for MW1.21+
1259 $this->mSVGNSError = $namespace;
1260 return true;
1261 }
1262
1263 /*
1264 * check for elements that can contain javascript
1265 */
1266 if ( $strippedElement == 'script' ) {
1267 wfDebug( __METHOD__ . ": Found script element '$element' in uploaded file.\n" );
1268 return true;
1269 }
1270
1271 # 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>
1272 if ( $strippedElement == 'handler' ) {
1273 wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file.\n" );
1274 return true;
1275 }
1276
1277 # SVG reported in Feb '12 that used xml:stylesheet to generate javascript block
1278 if ( $strippedElement == 'stylesheet' ) {
1279 wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file.\n" );
1280 return true;
1281 }
1282
1283 # Block iframes, in case they pass the namespace check
1284 if ( $strippedElement == 'iframe' ) {
1285 wfDebug( __METHOD__ . ": iframe in uploaded file.\n" );
1286 return true;
1287 }
1288
1289 foreach ( $attribs as $attrib => $value ) {
1290 $stripped = $this->stripXmlNamespace( $attrib );
1291 $value = strtolower( $value );
1292
1293 if ( substr( $stripped, 0, 2 ) == 'on' ) {
1294 wfDebug( __METHOD__ . ": Found event-handler attribute '$attrib'='$value' in uploaded file.\n" );
1295 return true;
1296 }
1297
1298 # href with javascript target
1299 if ( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
1300 wfDebug( __METHOD__ . ": Found script in href attribute '$attrib'='$value' in uploaded file.\n" );
1301 return true;
1302 }
1303
1304 # href with embedded svg as target
1305 if ( $stripped == 'href' && preg_match( '!data:[^,]*image/svg[^,]*,!sim', $value ) ) {
1306 wfDebug( __METHOD__ . ": Found href to embedded svg \"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1307 return true;
1308 }
1309
1310 # href with embedded (text/xml) svg as target
1311 if ( $stripped == 'href' && preg_match( '!data:[^,]*text/xml[^,]*,!sim', $value ) ) {
1312 wfDebug( __METHOD__ . ": Found href to embedded svg \"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1313 return true;
1314 }
1315
1316 # use set/animate to add event-handler attribute to parent
1317 if ( ( $strippedElement == 'set' || $strippedElement == 'animate' ) && $stripped == 'attributename' && substr( $value, 0, 2 ) == 'on' ) {
1318 wfDebug( __METHOD__ . ": Found svg setting event-handler attribute with \"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1319 return true;
1320 }
1321
1322 # use set to add href attribute to parent element
1323 if ( $strippedElement == 'set' && $stripped == 'attributename' && strpos( $value, 'href' ) !== false ) {
1324 wfDebug( __METHOD__ . ": Found svg setting href attribute '$value' in uploaded file.\n" );
1325 return true;
1326 }
1327
1328 # use set to add a remote / data / script target to an element
1329 if ( $strippedElement == 'set' && $stripped == 'to' && preg_match( '!(http|https|data|script):!sim', $value ) ) {
1330 wfDebug( __METHOD__ . ": Found svg setting attribute to '$value' in uploaded file.\n" );
1331 return true;
1332 }
1333
1334 # use handler attribute with remote / data / script
1335 if ( $stripped == 'handler' && preg_match( '!(http|https|data|script):!sim', $value ) ) {
1336 wfDebug( __METHOD__ . ": Found svg setting handler with remote/data/script '$attrib'='$value' in uploaded file.\n" );
1337 return true;
1338 }
1339
1340 # use CSS styles to bring in remote code
1341 # catch url("http:..., url('http:..., url(http:..., but not url("#..., url('#..., url(#....
1342 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 ) ) {
1343 foreach ( $matches[1] as $match ) {
1344 if ( !preg_match( '!(?:font|clip-path|fill|filter|marker|marker-end|marker-mid|marker-start|mask|stroke)\s*:\s*url\s*\(\s*(#|\'#|"#)!sim', $match ) ) {
1345 wfDebug( __METHOD__ . ": Found svg setting a style with remote url '$attrib'='$value' in uploaded file.\n" );
1346 return true;
1347 }
1348 }
1349 }
1350
1351 # image filters can pull in url, which could be svg that executes scripts
1352 if ( $strippedElement == 'image' && $stripped == 'filter' && preg_match( '!url\s*\(!sim', $value ) ) {
1353 wfDebug( __METHOD__ . ": Found image filter with url: \"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1354 return true;
1355 }
1356
1357 }
1358
1359 return false; //No scripts detected
1360 }
1361
1362 /**
1363 * Divide the element name passed by the xml parser to the callback into URI and prifix.
1364 * @param string $name
1365 * @return array Containing the namespace URI and prefix
1366 */
1367 private static function splitXmlNamespace( $element ) {
1368 // 'http://www.w3.org/2000/svg:script' -> array( 'http://www.w3.org/2000/svg', 'script' )
1369 $parts = explode( ':', strtolower( $element ) );
1370 $name = array_pop( $parts );
1371 $ns = implode( ':', $parts );
1372 return array( $ns, $name );
1373 }
1374
1375 /**
1376 * @param string $name
1377 * @return string
1378 */
1379 private function stripXmlNamespace( $name ) {
1380 // 'http://www.w3.org/2000/svg:script' -> 'script'
1381 $parts = explode( ':', strtolower( $name ) );
1382 return array_pop( $parts );
1383 }
1384
1385 /**
1386 * Generic wrapper function for a virus scanner program.
1387 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1388 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1389 *
1390 * @param string $file Pathname to the temporary upload file
1391 * @return mixed False if not virus is found, null if the scan fails or is disabled,
1392 * or a string containing feedback from the virus scanner if a virus was found.
1393 * If textual feedback is missing but a virus was found, this function returns true.
1394 */
1395 public static function detectVirus( $file ) {
1396 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1397 wfProfileIn( __METHOD__ );
1398
1399 if ( !$wgAntivirus ) {
1400 wfDebug( __METHOD__ . ": virus scanner disabled\n" );
1401 wfProfileOut( __METHOD__ );
1402 return null;
1403 }
1404
1405 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1406 wfDebug( __METHOD__ . ": unknown virus scanner: $wgAntivirus\n" );
1407 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
1408 array( 'virus-badscanner', $wgAntivirus ) );
1409 wfProfileOut( __METHOD__ );
1410 return wfMessage( 'virus-unknownscanner' )->text() . " $wgAntivirus";
1411 }
1412
1413 # look up scanner configuration
1414 $command = $wgAntivirusSetup[$wgAntivirus]['command'];
1415 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
1416 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
1417 $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
1418
1419 if ( strpos( $command, "%f" ) === false ) {
1420 # simple pattern: append file to scan
1421 $command .= " " . wfEscapeShellArg( $file );
1422 } else {
1423 # complex pattern: replace "%f" with file to scan
1424 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1425 }
1426
1427 wfDebug( __METHOD__ . ": running virus scan: $command \n" );
1428
1429 # execute virus scanner
1430 $exitCode = false;
1431
1432 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1433 # that does not seem to be worth the pain.
1434 # Ask me (Duesentrieb) about it if it's ever needed.
1435 $output = wfShellExecWithStderr( $command, $exitCode );
1436
1437 # map exit code to AV_xxx constants.
1438 $mappedCode = $exitCode;
1439 if ( $exitCodeMap ) {
1440 if ( isset( $exitCodeMap[$exitCode] ) ) {
1441 $mappedCode = $exitCodeMap[$exitCode];
1442 } elseif ( isset( $exitCodeMap["*"] ) ) {
1443 $mappedCode = $exitCodeMap["*"];
1444 }
1445 }
1446
1447 /* NB: AV_NO_VIRUS is 0 but AV_SCAN_FAILED is false,
1448 * so we need the strict equalities === and thus can't use a switch here
1449 */
1450 if ( $mappedCode === AV_SCAN_FAILED ) {
1451 # scan failed (code was mapped to false by $exitCodeMap)
1452 wfDebug( __METHOD__ . ": failed to scan $file (code $exitCode).\n" );
1453
1454 $output = $wgAntivirusRequired ? wfMessage( 'virus-scanfailed', array( $exitCode ) )->text() : null;
1455 } elseif ( $mappedCode === AV_SCAN_ABORTED ) {
1456 # scan failed because filetype is unknown (probably imune)
1457 wfDebug( __METHOD__ . ": unsupported file type $file (code $exitCode).\n" );
1458 $output = null;
1459 } elseif ( $mappedCode === AV_NO_VIRUS ) {
1460 # no virus found
1461 wfDebug( __METHOD__ . ": file passed virus scan.\n" );
1462 $output = false;
1463 } else {
1464 $output = trim( $output );
1465
1466 if ( !$output ) {
1467 $output = true; #if there's no output, return true
1468 } elseif ( $msgPattern ) {
1469 $groups = array();
1470 if ( preg_match( $msgPattern, $output, $groups ) ) {
1471 if ( $groups[1] ) {
1472 $output = $groups[1];
1473 }
1474 }
1475 }
1476
1477 wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output \n" );
1478 }
1479
1480 wfProfileOut( __METHOD__ );
1481 return $output;
1482 }
1483
1484 /**
1485 * Check if there's an overwrite conflict and, if so, if restrictions
1486 * forbid this user from performing the upload.
1487 *
1488 * @param User $user
1489 *
1490 * @return mixed True on success, array on failure
1491 */
1492 private function checkOverwrite( $user ) {
1493 // First check whether the local file can be overwritten
1494 $file = $this->getLocalFile();
1495 if ( $file->exists() ) {
1496 if ( !self::userCanReUpload( $user, $file ) ) {
1497 return array( 'fileexists-forbidden', $file->getName() );
1498 } else {
1499 return true;
1500 }
1501 }
1502
1503 /* Check shared conflicts: if the local file does not exist, but
1504 * wfFindFile finds a file, it exists in a shared repository.
1505 */
1506 $file = wfFindFile( $this->getTitle() );
1507 if ( $file && !$user->isAllowed( 'reupload-shared' ) ) {
1508 return array( 'fileexists-shared-forbidden', $file->getName() );
1509 }
1510
1511 return true;
1512 }
1513
1514 /**
1515 * Check if a user is the last uploader
1516 *
1517 * @param User $user
1518 * @param string $img Image name
1519 * @return bool
1520 */
1521 public static function userCanReUpload( User $user, $img ) {
1522 if ( $user->isAllowed( 'reupload' ) ) {
1523 return true; // non-conditional
1524 }
1525 if ( !$user->isAllowed( 'reupload-own' ) ) {
1526 return false;
1527 }
1528 if ( is_string( $img ) ) {
1529 $img = wfLocalFile( $img );
1530 }
1531 if ( !( $img instanceof LocalFile ) ) {
1532 return false;
1533 }
1534
1535 return $user->getId() == $img->getUser( 'id' );
1536 }
1537
1538 /**
1539 * Helper function that does various existence checks for a file.
1540 * The following checks are performed:
1541 * - The file exists
1542 * - Article with the same name as the file exists
1543 * - File exists with normalized extension
1544 * - The file looks like a thumbnail and the original exists
1545 *
1546 * @param File $file The File object to check
1547 * @return mixed False if the file does not exists, else an array
1548 */
1549 public static function getExistsWarning( $file ) {
1550 if ( $file->exists() ) {
1551 return array( 'warning' => 'exists', 'file' => $file );
1552 }
1553
1554 if ( $file->getTitle()->getArticleID() ) {
1555 return array( 'warning' => 'page-exists', 'file' => $file );
1556 }
1557
1558 if ( $file->wasDeleted() && !$file->exists() ) {
1559 return array( 'warning' => 'was-deleted', 'file' => $file );
1560 }
1561
1562 if ( strpos( $file->getName(), '.' ) == false ) {
1563 $partname = $file->getName();
1564 $extension = '';
1565 } else {
1566 $n = strrpos( $file->getName(), '.' );
1567 $extension = substr( $file->getName(), $n + 1 );
1568 $partname = substr( $file->getName(), 0, $n );
1569 }
1570 $normalizedExtension = File::normalizeExtension( $extension );
1571
1572 if ( $normalizedExtension != $extension ) {
1573 // We're not using the normalized form of the extension.
1574 // Normal form is lowercase, using most common of alternate
1575 // extensions (eg 'jpg' rather than 'JPEG').
1576 //
1577 // Check for another file using the normalized form...
1578 $nt_lc = Title::makeTitle( NS_FILE, "{$partname}.{$normalizedExtension}" );
1579 $file_lc = wfLocalFile( $nt_lc );
1580
1581 if ( $file_lc->exists() ) {
1582 return array(
1583 'warning' => 'exists-normalized',
1584 'file' => $file,
1585 'normalizedFile' => $file_lc
1586 );
1587 }
1588 }
1589
1590 // Check for files with the same name but a different extension
1591 $similarFiles = RepoGroup::singleton()->getLocalRepo()->findFilesByPrefix(
1592 "{$partname}.", 1 );
1593 if ( count( $similarFiles ) ) {
1594 return array(
1595 'warning' => 'exists-normalized',
1596 'file' => $file,
1597 'normalizedFile' => $similarFiles[0],
1598 );
1599 }
1600
1601 if ( self::isThumbName( $file->getName() ) ) {
1602 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1603 $nt_thb = Title::newFromText( substr( $partname, strpos( $partname, '-' ) + 1 ) . '.' . $extension, NS_FILE );
1604 $file_thb = wfLocalFile( $nt_thb );
1605 if ( $file_thb->exists() ) {
1606 return array(
1607 'warning' => 'thumb',
1608 'file' => $file,
1609 'thumbFile' => $file_thb
1610 );
1611 } else {
1612 // File does not exist, but we just don't like the name
1613 return array(
1614 'warning' => 'thumb-name',
1615 'file' => $file,
1616 'thumbFile' => $file_thb
1617 );
1618 }
1619 }
1620
1621 foreach ( self::getFilenamePrefixBlacklist() as $prefix ) {
1622 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1623 return array(
1624 'warning' => 'bad-prefix',
1625 'file' => $file,
1626 'prefix' => $prefix
1627 );
1628 }
1629 }
1630
1631 return false;
1632 }
1633
1634 /**
1635 * Helper function that checks whether the filename looks like a thumbnail
1636 * @param string $filename
1637 * @return bool
1638 */
1639 public static function isThumbName( $filename ) {
1640 $n = strrpos( $filename, '.' );
1641 $partname = $n ? substr( $filename, 0, $n ) : $filename;
1642 return (
1643 substr( $partname, 3, 3 ) == 'px-' ||
1644 substr( $partname, 2, 3 ) == 'px-'
1645 ) &&
1646 preg_match( "/[0-9]{2}/", substr( $partname, 0, 2 ) );
1647 }
1648
1649 /**
1650 * Get a list of blacklisted filename prefixes from [[MediaWiki:Filename-prefix-blacklist]]
1651 *
1652 * @return array List of prefixes
1653 */
1654 public static function getFilenamePrefixBlacklist() {
1655 $blacklist = array();
1656 $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
1657 if ( !$message->isDisabled() ) {
1658 $lines = explode( "\n", $message->plain() );
1659 foreach ( $lines as $line ) {
1660 // Remove comment lines
1661 $comment = substr( trim( $line ), 0, 1 );
1662 if ( $comment == '#' || $comment == '' ) {
1663 continue;
1664 }
1665 // Remove additional comments after a prefix
1666 $comment = strpos( $line, '#' );
1667 if ( $comment > 0 ) {
1668 $line = substr( $line, 0, $comment - 1 );
1669 }
1670 $blacklist[] = trim( $line );
1671 }
1672 }
1673 return $blacklist;
1674 }
1675
1676 /**
1677 * Gets image info about the file just uploaded.
1678 *
1679 * Also has the effect of setting metadata to be an 'indexed tag name' in returned API result if
1680 * 'metadata' was requested. Oddly, we have to pass the "result" object down just so it can do that
1681 * with the appropriate format, presumably.
1682 *
1683 * @param ApiResult $result
1684 * @return array Image info
1685 */
1686 public function getImageInfo( $result ) {
1687 $file = $this->getLocalFile();
1688 // TODO This cries out for refactoring. We really want to say $file->getAllInfo(); here.
1689 // Perhaps "info" methods should be moved into files, and the API should just wrap them in queries.
1690 if ( $file instanceof UploadStashFile ) {
1691 $imParam = ApiQueryStashImageInfo::getPropertyNames();
1692 $info = ApiQueryStashImageInfo::getInfo( $file, array_flip( $imParam ), $result );
1693 } else {
1694 $imParam = ApiQueryImageInfo::getPropertyNames();
1695 $info = ApiQueryImageInfo::getInfo( $file, array_flip( $imParam ), $result );
1696 }
1697 return $info;
1698 }
1699
1700 /**
1701 * @param array $error
1702 * @return Status
1703 */
1704 public function convertVerifyErrorToStatus( $error ) {
1705 $code = $error['status'];
1706 unset( $code['status'] );
1707 return Status::newFatal( $this->getVerificationErrorCode( $code ), $error );
1708 }
1709
1710 /**
1711 * @param null|string $forType
1712 * @return int
1713 */
1714 public static function getMaxUploadSize( $forType = null ) {
1715 global $wgMaxUploadSize;
1716
1717 if ( is_array( $wgMaxUploadSize ) ) {
1718 if ( !is_null( $forType ) && isset( $wgMaxUploadSize[$forType] ) ) {
1719 return $wgMaxUploadSize[$forType];
1720 } else {
1721 return $wgMaxUploadSize['*'];
1722 }
1723 } else {
1724 return intval( $wgMaxUploadSize );
1725 }
1726 }
1727
1728 /**
1729 * Get the current status of a chunked upload (used for polling).
1730 * The status will be read from the *current* user session.
1731 * @param string $statusKey
1732 * @return array|bool
1733 */
1734 public static function getSessionStatus( $statusKey ) {
1735 return isset( $_SESSION[self::SESSION_STATUS_KEY][$statusKey] )
1736 ? $_SESSION[self::SESSION_STATUS_KEY][$statusKey]
1737 : false;
1738 }
1739
1740 /**
1741 * Set the current status of a chunked upload (used for polling).
1742 * The status will be stored in the *current* user session.
1743 * @param string $statusKey
1744 * @param array|bool $value
1745 * @return void
1746 */
1747 public static function setSessionStatus( $statusKey, $value ) {
1748 if ( $value === false ) {
1749 unset( $_SESSION[self::SESSION_STATUS_KEY][$statusKey] );
1750 } else {
1751 $_SESSION[self::SESSION_STATUS_KEY][$statusKey] = $value;
1752 }
1753 }
1754 }