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