UploadBase::getTitle():
[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;
22
23 const SUCCESS = 0;
24 const OK = 0;
25 const EMPTY_FILE = 3;
26 const MIN_LENGTH_PARTNAME = 4;
27 const ILLEGAL_FILENAME = 5;
28 const OVERWRITE_EXISTING_FILE = 7;
29 const FILETYPE_MISSING = 8;
30 const FILETYPE_BADTYPE = 9;
31 const VERIFICATION_ERROR = 10;
32 const UPLOAD_VERIFICATION_ERROR = 11;
33 const HOOK_ABORTED = 11;
34
35 const SESSION_VERSION = 2;
36
37 /**
38 * Returns true if uploads are enabled.
39 * Can be override by subclasses.
40 */
41 public static function isEnabled() {
42 global $wgEnableUploads;
43 if ( !$wgEnableUploads ) {
44 return false;
45 }
46
47 # Check php's file_uploads setting
48 if( !wfIniGetBool( 'file_uploads' ) ) {
49 return false;
50 }
51 return true;
52 }
53
54 /**
55 * Returns true if the user can use this upload module or else a string
56 * identifying the missing permission.
57 * Can be overriden by subclasses.
58 */
59 public static function isAllowed( $user ) {
60 if( !$user->isAllowed( 'upload' ) ) {
61 return 'upload';
62 }
63 return true;
64 }
65
66 // Upload handlers. Should probably just be a global.
67 static $uploadHandlers = array( 'Stash', 'File', 'Url' );
68
69 /**
70 * Create a form of UploadBase depending on wpSourceType and initializes it
71 */
72 public static function createFromRequest( &$request, $type = null ) {
73 $type = $type ? $type : $request->getVal( 'wpSourceType', 'File' );
74
75 if( !$type ) {
76 return null;
77 }
78
79 // Get the upload class
80 $type = ucfirst( $type );
81
82 // Give hooks the chance to handle this request
83 $className = null;
84 wfRunHooks( 'UploadCreateFromRequest', array( $type, &$className ) );
85 if ( is_null( $className ) ) {
86 $className = 'UploadFrom' . $type;
87 wfDebug( __METHOD__ . ": class name: $className\n" );
88 if( !in_array( $type, self::$uploadHandlers ) ) {
89 return null;
90 }
91 }
92
93 // Check whether this upload class is enabled
94 if( !call_user_func( array( $className, 'isEnabled' ) ) ) {
95 return null;
96 }
97
98 // Check whether the request is valid
99 if( !call_user_func( array( $className, 'isValidRequest' ), $request ) ) {
100 return null;
101 }
102
103 $handler = new $className;
104
105 $handler->initializeFromRequest( $request );
106 return $handler;
107 }
108
109 /**
110 * Check whether a request if valid for this handler
111 */
112 public static function isValidRequest( $request ) {
113 return false;
114 }
115
116 public function __construct() {}
117
118 /**
119 * Initialize the path information
120 * @param $name string the desired destination name
121 * @param $tempPath string the temporary path
122 * @param $fileSize int the file size
123 * @param $removeTempFile bool (false) remove the temporary file?
124 * @return null
125 */
126 public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
127 $this->mDesiredDestName = $name;
128 $this->mTempPath = $tempPath;
129 $this->mFileSize = $fileSize;
130 $this->mRemoveTempFile = $removeTempFile;
131 }
132
133 /**
134 * Initialize from a WebRequest. Override this in a subclass.
135 */
136 public abstract function initializeFromRequest( &$request );
137
138 /**
139 * Fetch the file. Usually a no-op
140 */
141 public function fetchFile() {
142 return Status::newGood();
143 }
144
145 /**
146 * Return the file size
147 */
148 public function isEmptyFile() {
149 return empty( $this->mFileSize );
150 }
151
152 /**
153 * @param $srcPath String: the source path
154 * @return the real path if it was a virtual URL
155 */
156 function getRealPath( $srcPath ) {
157 $repo = RepoGroup::singleton()->getLocalRepo();
158 if ( $repo->isVirtualUrl( $srcPath ) ) {
159 return $repo->resolveVirtualUrl( $srcPath );
160 }
161 return $srcPath;
162 }
163
164 /**
165 * Verify whether the upload is sane.
166 * Returns self::OK or else an array with error information
167 */
168 public function verifyUpload() {
169 /**
170 * If there was no filename or a zero size given, give up quick.
171 */
172 if( $this->isEmptyFile() ) {
173 return array( 'status' => self::EMPTY_FILE );
174 }
175
176 /**
177 * Look at the contents of the file; if we can recognize the
178 * type but it's corrupt or data of the wrong type, we should
179 * probably not accept it.
180 */
181 $verification = $this->verifyFile();
182 if( $verification !== true ) {
183 if( !is_array( $verification ) ) {
184 $verification = array( $verification );
185 }
186 return array(
187 'status' => self::VERIFICATION_ERROR,
188 'details' => $verification
189 );
190 }
191
192 $nt = $this->getTitle();
193 if( is_null( $nt ) ) {
194 $result = array( 'status' => $this->mTitleError );
195 if( $this->mTitleError == self::ILLEGAL_FILENAME ) {
196 $result['filtered'] = $this->mFilteredName;
197 }
198 if ( $this->mTitleError == self::FILETYPE_BADTYPE ) {
199 $result['finalExt'] = $this->mFinalExtension;
200 }
201 return $result;
202 }
203 $this->mDestName = $this->getLocalFile()->getName();
204
205 /**
206 * In some cases we may forbid overwriting of existing files.
207 */
208 $overwrite = $this->checkOverwrite();
209 if( $overwrite !== true ) {
210 return array(
211 'status' => self::OVERWRITE_EXISTING_FILE,
212 'overwrite' => $overwrite
213 );
214 }
215
216 $error = '';
217 if( !wfRunHooks( 'UploadVerification',
218 array( $this->mDestName, $this->mTempPath, &$error ) ) ) {
219 // This status needs another name...
220 return array( 'status' => self::HOOK_ABORTED, 'error' => $error );
221 }
222
223 return array( 'status' => self::OK );
224 }
225
226 /**
227 * Verifies that it's ok to include the uploaded file
228 *
229 * @return mixed true of the file is verified, a string or array otherwise.
230 */
231 protected function verifyFile() {
232 $this->mFileProps = File::getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
233 $this->checkMacBinary();
234
235 # magically determine mime type
236 $magic = MimeMagic::singleton();
237 $mime = $magic->guessMimeType( $this->mTempPath, false );
238
239 # check mime type, if desired
240 global $wgVerifyMimeType;
241 if ( $wgVerifyMimeType ) {
242 wfDebug ( "\n\nmime: <$mime> extension: <{$this->mFinalExtension}>\n\n");
243 if ( !$this->verifyExtension( $mime, $this->mFinalExtension ) ) {
244 return array( 'filetype-mime-mismatch' );
245 }
246
247 global $wgMimeTypeBlacklist;
248 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
249 return array( 'filetype-badmime', $mime );
250 }
251
252 # Check IE type
253 $fp = fopen( $this->mTempPath, 'rb' );
254 $chunk = fread( $fp, 256 );
255 fclose( $fp );
256 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension );
257 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath, $chunk, $extMime );
258 foreach ( $ieTypes as $ieType ) {
259 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
260 return array( 'filetype-bad-ie-mime', $ieType );
261 }
262 }
263 }
264
265 # check for htmlish code and javascript
266 if( self::detectScript( $this->mTempPath, $mime, $this->mFinalExtension ) ) {
267 return 'uploadscripted';
268 }
269 if( $this->mFinalExtension == 'svg' || $mime == 'image/svg+xml' ) {
270 if( self::detectScriptInSvg( $this->mTempPath ) ) {
271 return 'uploadscripted';
272 }
273 }
274
275 /**
276 * Scan the uploaded file for viruses
277 */
278 $virus = $this->detectVirus( $this->mTempPath );
279 if ( $virus ) {
280 return array( 'uploadvirus', $virus );
281 }
282 wfDebug( __METHOD__ . ": all clear; passing.\n" );
283 return true;
284 }
285
286 /**
287 * Check whether the user can edit, upload and create the image.
288 *
289 * @param $user the User object to verify the permissions against
290 * @return mixed An array as returned by getUserPermissionsErrors or true
291 * in case the user has proper permissions.
292 */
293 public function verifyPermissions( $user ) {
294 /**
295 * If the image is protected, non-sysop users won't be able
296 * to modify it by uploading a new revision.
297 */
298 $nt = $this->getTitle();
299 if( is_null( $nt ) ) {
300 return true;
301 }
302 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
303 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
304 $permErrorsCreate = ( $nt->exists() ? array() : $nt->getUserPermissionsErrors( 'create', $user ) );
305 if( $permErrors || $permErrorsUpload || $permErrorsCreate ) {
306 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
307 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
308 return $permErrors;
309 }
310 return true;
311 }
312
313 /**
314 * Check for non fatal problems with the file
315 *
316 * @return Array of warnings
317 */
318 public function checkWarnings() {
319 $warnings = array();
320
321 $localFile = $this->getLocalFile();
322 $filename = $localFile->getName();
323 $n = strrpos( $filename, '.' );
324 $partname = $n ? substr( $filename, 0, $n ) : $filename;
325
326 /**
327 * Check whether the resulting filename is different from the desired one,
328 * but ignore things like ucfirst() and spaces/underscore things
329 */
330 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName );
331 $comparableName = Title::capitalize( $comparableName, NS_FILE );
332
333 if( $this->mDesiredDestName != $filename && $comparableName != $filename ) {
334 $warnings['badfilename'] = $filename;
335 }
336
337 // Check whether the file extension is on the unwanted list
338 global $wgCheckFileExtensions, $wgFileExtensions;
339 if ( $wgCheckFileExtensions ) {
340 if ( !$this->checkFileExtension( $this->mFinalExtension, $wgFileExtensions ) ) {
341 $warnings['filetype-unwanted-type'] = $this->mFinalExtension;
342 }
343 }
344
345 global $wgUploadSizeWarning;
346 if ( $wgUploadSizeWarning && ( $this->mFileSize > $wgUploadSizeWarning ) ) {
347 $warnings['large-file'] = $wgUploadSizeWarning;
348 }
349
350 if ( $this->mFileSize == 0 ) {
351 $warnings['emptyfile'] = true;
352 }
353
354 $exists = self::getExistsWarning( $localFile );
355 if( $exists !== false ) {
356 $warnings['exists'] = $exists;
357 }
358
359 // Check dupes against existing files
360 $hash = File::sha1Base36( $this->mTempPath );
361 $dupes = RepoGroup::singleton()->findBySha1( $hash );
362 $title = $this->getTitle();
363 // Remove all matches against self
364 foreach ( $dupes as $key => $dupe ) {
365 if( $title->equals( $dupe->getTitle() ) ) {
366 unset( $dupes[$key] );
367 }
368 }
369 if( $dupes ) {
370 $warnings['duplicate'] = $dupes;
371 }
372
373 // Check dupes against archives
374 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
375 if ( $archivedImage->getID() > 0 ) {
376 $warnings['duplicate-archive'] = $archivedImage->getName();
377 }
378
379 return $warnings;
380 }
381
382 /**
383 * Really perform the upload. Stores the file in the local repo, watches
384 * if necessary and runs the UploadComplete hook.
385 *
386 * @return mixed Status indicating the whether the upload succeeded.
387 */
388 public function performUpload( $comment, $pageText, $watch, $user ) {
389 wfDebug( "\n\n\performUpload: sum:" . $comment . ' c: ' . $pageText . ' w:' . $watch );
390 $status = $this->getLocalFile()->upload( $this->mTempPath, $comment, $pageText,
391 File::DELETE_SOURCE, $this->mFileProps, false, $user );
392
393 if( $status->isGood() && $watch ) {
394 $user->addWatch( $this->getLocalFile()->getTitle() );
395 }
396
397 if( $status->isGood() ) {
398 wfRunHooks( 'UploadComplete', array( &$this ) );
399 }
400
401 return $status;
402 }
403
404 /**
405 * Returns the title of the file to be uploaded. Sets mTitleError in case
406 * the name was illegal.
407 *
408 * @return Title The title of the file or null in case the name was illegal
409 */
410 public function getTitle() {
411 if ( $this->mTitle !== false ) {
412 return $this->mTitle;
413 }
414
415 /**
416 * Chop off any directories in the given filename. Then
417 * filter out illegal characters, and try to make a legible name
418 * out of it. We'll strip some silently that Title would die on.
419 */
420 $this->mFilteredName = wfStripIllegalFilenameChars( $this->mDesiredDestName );
421 /* Normalize to title form before we do any further processing */
422 $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
423 if( is_null( $nt ) ) {
424 $this->mTitleError = self::ILLEGAL_FILENAME;
425 return $this->mTitle = null;
426 }
427 $this->mFilteredName = $nt->getDBkey();
428
429 /**
430 * We'll want to blacklist against *any* 'extension', and use
431 * only the final one for the whitelist.
432 */
433 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName );
434
435 if( count( $ext ) ) {
436 $this->mFinalExtension = trim( $ext[count( $ext ) - 1] );
437 } else {
438 $this->mFinalExtension = '';
439 }
440
441 /* Don't allow users to override the blacklist (check file extension) */
442 global $wgCheckFileExtensions, $wgStrictFileExtensions;
443 global $wgFileExtensions, $wgFileBlacklist;
444 if ( $this->mFinalExtension == '' ) {
445 $this->mTitleError = self::FILETYPE_MISSING;
446 return $this->mTitle = null;
447 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
448 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
449 !$this->checkFileExtension( $this->mFinalExtension, $wgFileExtensions ) ) ) {
450 $this->mTitleError = self::FILETYPE_BADTYPE;
451 return $this->mTitle = null;
452 }
453
454 # If there was more than one "extension", reassemble the base
455 # filename to prevent bogus complaints about length
456 if( count( $ext ) > 1 ) {
457 for( $i = 0; $i < count( $ext ) - 1; $i++ ) {
458 $partname .= '.' . $ext[$i];
459 }
460 }
461
462 if( strlen( $partname ) < 1 ) {
463 $this->mTitleError = self::MIN_LENGTH_PARTNAME;
464 return $this->mTitle = null;
465 }
466
467 return $this->mTitle = $nt;
468 }
469
470 /**
471 * Return the local file and initializes if necessary.
472 */
473 public function getLocalFile() {
474 if( is_null( $this->mLocalFile ) ) {
475 $nt = $this->getTitle();
476 $this->mLocalFile = is_null( $nt ) ? null : wfLocalFile( $nt );
477 }
478 return $this->mLocalFile;
479 }
480
481 /**
482 * Stash a file in a temporary directory for later processing
483 * after the user has confirmed it.
484 *
485 * If the user doesn't explicitly cancel or accept, these files
486 * can accumulate in the temp directory.
487 *
488 * @param $saveName String: the destination filename
489 * @param $tempSrc String: the source temporary file to save
490 * @return String: full path the stashed file, or false on failure
491 */
492 protected function saveTempUploadedFile( $saveName, $tempSrc ) {
493 $repo = RepoGroup::singleton()->getLocalRepo();
494 $status = $repo->storeTemp( $saveName, $tempSrc );
495 return $status;
496 }
497
498 /**
499 * Stash a file in a temporary directory for later processing,
500 * and save the necessary descriptive info into the session.
501 * Returns a key value which will be passed through a form
502 * to pick up the path info on a later invocation.
503 *
504 * @return Integer: session key
505 */
506 public function stashSession() {
507 $status = $this->saveTempUploadedFile( $this->mDestName, $this->mTempPath );
508 if( !$status->isOK() ) {
509 # Couldn't save the file.
510 return false;
511 }
512
513 $key = $this->getSessionKey();
514 $_SESSION['wsUploadData'][$key] = array(
515 'mTempPath' => $status->value,
516 'mFileSize' => $this->mFileSize,
517 'mFileProps' => $this->mFileProps,
518 'version' => self::SESSION_VERSION,
519 );
520 return $key;
521 }
522
523 /**
524 * Generate a random session key from stash in cases where we want to start an upload without much information
525 */
526 protected function getSessionKey() {
527 $key = mt_rand( 0, 0x7fffffff );
528 $_SESSION['wsUploadData'][$key] = array();
529 return $key;
530 }
531
532 /**
533 * If we've modified the upload file we need to manually remove it
534 * on exit to clean up.
535 */
536 public function cleanupTempFile() {
537 if ( $this->mRemoveTempFile && $this->mTempPath && file_exists( $this->mTempPath ) ) {
538 wfDebug( __METHOD__ . ": Removing temporary file {$this->mTempPath}\n" );
539 unlink( $this->mTempPath );
540 }
541 }
542
543 public function getTempPath() {
544 return $this->mTempPath;
545 }
546
547 /**
548 * Split a file into a base name and all dot-delimited 'extensions'
549 * on the end. Some web server configurations will fall back to
550 * earlier pseudo-'extensions' to determine type and execute
551 * scripts, so the blacklist needs to check them all.
552 *
553 * @return array
554 */
555 public static function splitExtensions( $filename ) {
556 $bits = explode( '.', $filename );
557 $basename = array_shift( $bits );
558 return array( $basename, $bits );
559 }
560
561 /**
562 * Perform case-insensitive match against a list of file extensions.
563 * Returns true if the extension is in the list.
564 *
565 * @param $ext String
566 * @param $list Array
567 * @return Boolean
568 */
569 public static function checkFileExtension( $ext, $list ) {
570 return in_array( strtolower( $ext ), $list );
571 }
572
573 /**
574 * Perform case-insensitive match against a list of file extensions.
575 * Returns true if any of the extensions are in the list.
576 *
577 * @param $ext Array
578 * @param $list Array
579 * @return Boolean
580 */
581 public static function checkFileExtensionList( $ext, $list ) {
582 foreach( $ext as $e ) {
583 if( in_array( strtolower( $e ), $list ) ) {
584 return true;
585 }
586 }
587 return false;
588 }
589
590 /**
591 * Checks if the mime type of the uploaded file matches the file extension.
592 *
593 * @param $mime String: the mime type of the uploaded file
594 * @param $extension String: the filename extension that the file is to be served with
595 * @return Boolean
596 */
597 public static function verifyExtension( $mime, $extension ) {
598 $magic = MimeMagic::singleton();
599
600 if ( !$mime || $mime == 'unknown' || $mime == 'unknown/unknown' )
601 if ( !$magic->isRecognizableExtension( $extension ) ) {
602 wfDebug( __METHOD__ . ": passing file with unknown detected mime type; " .
603 "unrecognized extension '$extension', can't verify\n" );
604 return true;
605 } else {
606 wfDebug( __METHOD__ . ": rejecting file with unknown detected mime type; ".
607 "recognized extension '$extension', so probably invalid file\n" );
608 return false;
609 }
610
611 $match = $magic->isMatchingExtension( $extension, $mime );
612
613 if ( $match === null ) {
614 wfDebug( __METHOD__ . ": no file extension known for mime type $mime, passing file\n" );
615 return true;
616 } elseif( $match === true ) {
617 wfDebug( __METHOD__ . ": mime type $mime matches extension $extension, passing file\n" );
618
619 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
620 return true;
621
622 } else {
623 wfDebug( __METHOD__ . ": mime type $mime mismatches file extension $extension, rejecting file\n" );
624 return false;
625 }
626 }
627
628 /**
629 * Heuristic for detecting files that *could* contain JavaScript instructions or
630 * things that may look like HTML to a browser and are thus
631 * potentially harmful. The present implementation will produce false
632 * positives in some situations.
633 *
634 * @param $file String: pathname to the temporary upload file
635 * @param $mime String: the mime type of the file
636 * @param $extension String: the extension of the file
637 * @return Boolean: true if the file contains something looking like embedded scripts
638 */
639 public static function detectScript( $file, $mime, $extension ) {
640 global $wgAllowTitlesInSVG;
641
642 # ugly hack: for text files, always look at the entire file.
643 # For binary field, just check the first K.
644
645 if( strpos( $mime,'text/' ) === 0 ) {
646 $chunk = file_get_contents( $file );
647 } else {
648 $fp = fopen( $file, 'rb' );
649 $chunk = fread( $fp, 1024 );
650 fclose( $fp );
651 }
652
653 $chunk = strtolower( $chunk );
654
655 if( !$chunk ) {
656 return false;
657 }
658
659 # decode from UTF-16 if needed (could be used for obfuscation).
660 if( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
661 $enc = 'UTF-16BE';
662 } elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
663 $enc = 'UTF-16LE';
664 } else {
665 $enc = null;
666 }
667
668 if( $enc ) {
669 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
670 }
671
672 $chunk = trim( $chunk );
673
674 # FIXME: convert from UTF-16 if necessarry!
675 wfDebug( __METHOD__ . ": checking for embedded scripts and HTML stuff\n" );
676
677 # check for HTML doctype
678 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
679 return true;
680 }
681
682 /**
683 * Internet Explorer for Windows performs some really stupid file type
684 * autodetection which can cause it to interpret valid image files as HTML
685 * and potentially execute JavaScript, creating a cross-site scripting
686 * attack vectors.
687 *
688 * Apple's Safari browser also performs some unsafe file type autodetection
689 * which can cause legitimate files to be interpreted as HTML if the
690 * web server is not correctly configured to send the right content-type
691 * (or if you're really uploading plain text and octet streams!)
692 *
693 * Returns true if IE is likely to mistake the given file for HTML.
694 * Also returns true if Safari would mistake the given file for HTML
695 * when served with a generic content-type.
696 */
697 $tags = array(
698 '<a href',
699 '<body',
700 '<head',
701 '<html', #also in safari
702 '<img',
703 '<pre',
704 '<script', #also in safari
705 '<table'
706 );
707
708 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
709 $tags[] = '<title';
710 }
711
712 foreach( $tags as $tag ) {
713 if( false !== strpos( $chunk, $tag ) ) {
714 return true;
715 }
716 }
717
718 /*
719 * look for JavaScript
720 */
721
722 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
723 $chunk = Sanitizer::decodeCharReferences( $chunk );
724
725 # look for script-types
726 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
727 return true;
728 }
729
730 # look for html-style script-urls
731 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
732 return true;
733 }
734
735 # look for css-style script-urls
736 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
737 return true;
738 }
739
740 wfDebug( __METHOD__ . ": no scripts found\n" );
741 return false;
742 }
743
744 protected function detectScriptInSvg( $filename ) {
745 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
746 return $check->filterMatch;
747 }
748
749 /**
750 * @todo Replace this with a whitelist filter!
751 */
752 public function checkSvgScriptCallback( $element, $attribs ) {
753 $stripped = $this->stripXmlNamespace( $element );
754
755 if( $stripped == 'script' ) {
756 wfDebug( __METHOD__ . ": Found script element '$element' in uploaded file.\n" );
757 return true;
758 }
759
760 foreach( $attribs as $attrib => $value ) {
761 $stripped = $this->stripXmlNamespace( $attrib );
762 if( substr( $stripped, 0, 2 ) == 'on' ) {
763 wfDebug( __METHOD__ . ": Found script attribute '$attrib'='value' in uploaded file.\n" );
764 return true;
765 }
766 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
767 wfDebug( __METHOD__ . ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
768 return true;
769 }
770 }
771 }
772
773 private function stripXmlNamespace( $name ) {
774 // 'http://www.w3.org/2000/svg:script' -> 'script'
775 $parts = explode( ':', strtolower( $name ) );
776 return array_pop( $parts );
777 }
778
779 /**
780 * Generic wrapper function for a virus scanner program.
781 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
782 * $wgAntivirusRequired may be used to deny upload if the scan fails.
783 *
784 * @param $file String: pathname to the temporary upload file
785 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
786 * or a string containing feedback from the virus scanner if a virus was found.
787 * If textual feedback is missing but a virus was found, this function returns true.
788 */
789 public static function detectVirus( $file ) {
790 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
791
792 if ( !$wgAntivirus ) {
793 wfDebug( __METHOD__ . ": virus scanner disabled\n" );
794 return null;
795 }
796
797 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
798 wfDebug( __METHOD__ . ": unknown virus scanner: $wgAntivirus\n" );
799 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1</div>", array( 'virus-badscanner', $wgAntivirus ) );
800 return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
801 }
802
803 # look up scanner configuration
804 $command = $wgAntivirusSetup[$wgAntivirus]['command'];
805 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
806 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
807 $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
808
809 if ( strpos( $command, "%f" ) === false ) {
810 # simple pattern: append file to scan
811 $command .= " " . wfEscapeShellArg( $file );
812 } else {
813 # complex pattern: replace "%f" with file to scan
814 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
815 }
816
817 wfDebug( __METHOD__ . ": running virus scan: $command \n" );
818
819 # execute virus scanner
820 $exitCode = false;
821
822 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
823 # that does not seem to be worth the pain.
824 # Ask me (Duesentrieb) about it if it's ever needed.
825 $output = wfShellExec( "$command 2>&1", $exitCode );
826
827 # map exit code to AV_xxx constants.
828 $mappedCode = $exitCode;
829 if ( $exitCodeMap ) {
830 if ( isset( $exitCodeMap[$exitCode] ) ) {
831 $mappedCode = $exitCodeMap[$exitCode];
832 } elseif ( isset( $exitCodeMap["*"] ) ) {
833 $mappedCode = $exitCodeMap["*"];
834 }
835 }
836
837 if ( $mappedCode === AV_SCAN_FAILED ) {
838 # scan failed (code was mapped to false by $exitCodeMap)
839 wfDebug( __METHOD__ . ": failed to scan $file (code $exitCode).\n" );
840
841 if ( $wgAntivirusRequired ) {
842 return wfMsg( 'virus-scanfailed', array( $exitCode ) );
843 } else {
844 return null;
845 }
846 } elseif ( $mappedCode === AV_SCAN_ABORTED ) {
847 # scan failed because filetype is unknown (probably imune)
848 wfDebug( __METHOD__ . ": unsupported file type $file (code $exitCode).\n" );
849 return null;
850 } elseif ( $mappedCode === AV_NO_VIRUS ) {
851 # no virus found
852 wfDebug( __METHOD__ . ": file passed virus scan.\n" );
853 return false;
854 } else {
855 $output = trim( $output );
856
857 if ( !$output ) {
858 $output = true; #if there's no output, return true
859 } elseif ( $msgPattern ) {
860 $groups = array();
861 if ( preg_match( $msgPattern, $output, $groups ) ) {
862 if ( $groups[1] ) {
863 $output = $groups[1];
864 }
865 }
866 }
867
868 wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output \n" );
869 return $output;
870 }
871 }
872
873 /**
874 * Check if the temporary file is MacBinary-encoded, as some uploads
875 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
876 * If so, the data fork will be extracted to a second temporary file,
877 * which will then be checked for validity and either kept or discarded.
878 */
879 private function checkMacBinary() {
880 $macbin = new MacBinary( $this->mTempPath );
881 if( $macbin->isValid() ) {
882 $dataFile = tempnam( wfTempDir(), 'WikiMacBinary' );
883 $dataHandle = fopen( $dataFile, 'wb' );
884
885 wfDebug( __METHOD__ . ": Extracting MacBinary data fork to $dataFile\n" );
886 $macbin->extractData( $dataHandle );
887
888 $this->mTempPath = $dataFile;
889 $this->mFileSize = $macbin->dataForkLength();
890
891 // We'll have to manually remove the new file if it's not kept.
892 $this->mRemoveTempFile = true;
893 }
894 $macbin->close();
895 }
896
897 /**
898 * Check if there's an overwrite conflict and, if so, if restrictions
899 * forbid this user from performing the upload.
900 *
901 * @return mixed true on success, error string on failure
902 */
903 private function checkOverwrite() {
904 global $wgUser;
905 // First check whether the local file can be overwritten
906 $file = $this->getLocalFile();
907 if( $file->exists() ) {
908 if( !self::userCanReUpload( $wgUser, $file ) ) {
909 return 'fileexists-forbidden';
910 } else {
911 return true;
912 }
913 }
914
915 /* Check shared conflicts: if the local file does not exist, but
916 * wfFindFile finds a file, it exists in a shared repository.
917 */
918 $file = wfFindFile( $this->getTitle() );
919 if ( $file && !$wgUser->isAllowed( 'reupload-shared' ) ) {
920 return 'fileexists-shared-forbidden';
921 }
922
923 return true;
924 }
925
926 /**
927 * Check if a user is the last uploader
928 *
929 * @param $user User object
930 * @param $img String: image name
931 * @return Boolean
932 */
933 public static function userCanReUpload( User $user, $img ) {
934 if( $user->isAllowed( 'reupload' ) ) {
935 return true; // non-conditional
936 }
937 if( !$user->isAllowed( 'reupload-own' ) ) {
938 return false;
939 }
940 if( is_string( $img ) ) {
941 $img = wfLocalFile( $img );
942 }
943 if ( !( $img instanceof LocalFile ) ) {
944 return false;
945 }
946
947 return $user->getId() == $img->getUser( 'id' );
948 }
949
950 /**
951 * Helper function that does various existence checks for a file.
952 * The following checks are performed:
953 * - The file exists
954 * - Article with the same name as the file exists
955 * - File exists with normalized extension
956 * - The file looks like a thumbnail and the original exists
957 *
958 * @param $file The File object to check
959 * @return mixed False if the file does not exists, else an array
960 */
961 public static function getExistsWarning( $file ) {
962 if( $file->exists() ) {
963 return array( 'warning' => 'exists', 'file' => $file );
964 }
965
966 if( $file->getTitle()->getArticleID() ) {
967 return array( 'warning' => 'page-exists', 'file' => $file );
968 }
969
970 if ( $file->wasDeleted() && !$file->exists() ) {
971 return array( 'warning' => 'was-deleted', 'file' => $file );
972 }
973
974 if( strpos( $file->getName(), '.' ) == false ) {
975 $partname = $file->getName();
976 $extension = '';
977 } else {
978 $n = strrpos( $file->getName(), '.' );
979 $extension = substr( $file->getName(), $n + 1 );
980 $partname = substr( $file->getName(), 0, $n );
981 }
982 $normalizedExtension = File::normalizeExtension( $extension );
983
984 if ( $normalizedExtension != $extension ) {
985 // We're not using the normalized form of the extension.
986 // Normal form is lowercase, using most common of alternate
987 // extensions (eg 'jpg' rather than 'JPEG').
988 //
989 // Check for another file using the normalized form...
990 $nt_lc = Title::makeTitle( NS_FILE, "{$partname}.{$normalizedExtension}" );
991 $file_lc = wfLocalFile( $nt_lc );
992
993 if( $file_lc->exists() ) {
994 return array(
995 'warning' => 'exists-normalized',
996 'file' => $file,
997 'normalizedFile' => $file_lc
998 );
999 }
1000 }
1001
1002 if ( self::isThumbName( $file->getName() ) ) {
1003 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1004 $nt_thb = Title::newFromText( substr( $partname , strpos( $partname , '-' ) +1 ) . '.' . $extension, NS_FILE );
1005 $file_thb = wfLocalFile( $nt_thb );
1006 if( $file_thb->exists() ) {
1007 return array(
1008 'warning' => 'thumb',
1009 'file' => $file,
1010 'thumbFile' => $file_thb
1011 );
1012 } else {
1013 // File does not exist, but we just don't like the name
1014 return array(
1015 'warning' => 'thumb-name',
1016 'file' => $file,
1017 'thumbFile' => $file_thb
1018 );
1019 }
1020 }
1021
1022
1023 foreach( self::getFilenamePrefixBlacklist() as $prefix ) {
1024 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1025 return array(
1026 'warning' => 'bad-prefix',
1027 'file' => $file,
1028 'prefix' => $prefix
1029 );
1030 }
1031 }
1032
1033 return false;
1034 }
1035
1036 /**
1037 * Helper function that checks whether the filename looks like a thumbnail
1038 */
1039 public static function isThumbName( $filename ) {
1040 $n = strrpos( $filename, '.' );
1041 $partname = $n ? substr( $filename, 0, $n ) : $filename;
1042 return (
1043 substr( $partname , 3, 3 ) == 'px-' ||
1044 substr( $partname , 2, 3 ) == 'px-'
1045 ) &&
1046 preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) );
1047 }
1048
1049 /**
1050 * Get a list of blacklisted filename prefixes from [[MediaWiki:Filename-prefix-blacklist]]
1051 *
1052 * @return array list of prefixes
1053 */
1054 public static function getFilenamePrefixBlacklist() {
1055 $blacklist = array();
1056 $message = wfMsgForContent( 'filename-prefix-blacklist' );
1057 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) || $message == '-' ) ) {
1058 $lines = explode( "\n", $message );
1059 foreach( $lines as $line ) {
1060 // Remove comment lines
1061 $comment = substr( trim( $line ), 0, 1 );
1062 if ( $comment == '#' || $comment == '' ) {
1063 continue;
1064 }
1065 // Remove additional comments after a prefix
1066 $comment = strpos( $line, '#' );
1067 if ( $comment > 0 ) {
1068 $line = substr( $line, 0, $comment-1 );
1069 }
1070 $blacklist[] = trim( $line );
1071 }
1072 }
1073 return $blacklist;
1074 }
1075
1076 public function getImageInfo( $result ) {
1077 $file = $this->getLocalFile();
1078 $imParam = ApiQueryImageInfo::getPropertyNames();
1079 return ApiQueryImageInfo::getInfo( $file, array_flip( $imParam ), $result );
1080 }
1081
1082 }