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