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