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