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