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