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