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