* Improved upload file type detection for OpenDocument formats
[lhc/web/wiklou.git] / includes / UploadBase.php
1 <?php
2
3 class UploadBase {
4 var $mTempPath;
5 var $mDesiredDestName, $mDestName, $mRemoveTempFile, $mSourceType;
6 var $mTitle = false, $mTitleError = 0;
7 var $mFilteredName, $mFinalExtension;
8
9 const SUCCESS = 0;
10 const OK = 0;
11 const BEFORE_PROCESSING = 1;
12 const LARGE_FILE_SERVER = 2;
13 const EMPTY_FILE = 3;
14 const MIN_LENGTH_PARTNAME = 4;
15 const ILLEGAL_FILENAME = 5;
16 const PROTECTED_PAGE = 6;
17 const OVERWRITE_EXISTING_FILE = 7;
18 const FILETYPE_MISSING = 8;
19 const FILETYPE_BADTYPE = 9;
20 const VERIFICATION_ERROR = 10;
21 const UPLOAD_VERIFICATION_ERROR = 11;
22 const UPLOAD_WARNING = 12;
23 const INTERNAL_ERROR = 13;
24
25 const SESSION_VERSION = 2;
26
27 /*
28 * Returns true if uploads are enabled.
29 * Can be overriden by subclasses.
30 */
31 static function isEnabled() {
32 global $wgEnableUploads;
33 return $wgEnableUploads;
34 }
35 /*
36 * Returns true if the user can use this upload module or else a string
37 * identifying the missing permission.
38 * Can be overriden by subclasses.
39 */
40 static function isAllowed( $user ) {
41 if( !$user->isAllowed( 'upload' ) )
42 return 'upload';
43 return true;
44 }
45
46 static $uploadHandlers = array( 'Stash', 'Upload', 'Url' );
47 static function createFromRequest( &$request, $type = null ) {
48 $type = $type ? $type : $request->getVal( 'wpSourceType' );
49 if( !$type )
50 return null;
51 $type = ucfirst($type);
52 $className = 'UploadFrom'.$type;
53 if( !in_array( $type, self::$uploadHandlers ) )
54 return null;
55 if( !call_user_func( array( $className, 'isEnabled' ) ) )
56 return null;
57 if( !call_user_func( array( $className, 'isValidRequest' ), $request ) )
58 return null;
59
60 $handler = new $className;
61 $handler->initializeFromRequest( $request );
62 return $handler;
63 }
64
65 static function isValidRequest( $request ) {
66 return false;
67 }
68
69 function __construct() {}
70
71 function initialize( $name, $tempPath, $fileSize, $removeTempFile = false ) {
72 $this->mDesiredDestName = $name;
73 $this->mTempPath = $tempPath;
74 $this->mFileSize = $fileSize;
75 $this->mRemoveTempFile = $removeTempFile;
76 }
77
78 function verifyUpload() {
79 global $wgUser;
80
81 /**
82 * If there was no filename or a zero size given, give up quick.
83 */
84 if( empty( $this->mFileSize ) )
85 return array( 'status' => self::EMPTY_FILE );
86
87 $nt = $this->getTitle();
88 if( is_null( $nt ) ) {
89 $result = array( 'status' => $this->mTitleError );
90 if( $this->mTitleError == self::ILLEGAL_FILENAME )
91 $resul['filtered'] = $this->mFilteredName;
92 if ( $this->mTitleError == self::FILETYPE_BADTYPE )
93 $result['finalExt'] = $this->mFinalExtension;
94 return $result;
95 }
96 $this->mLocalFile = wfLocalFile( $nt );
97 $this->mDestName = $this->mLocalFile->getName();
98
99 /**
100 * In some cases we may forbid overwriting of existing files.
101 */
102 $overwrite = $this->checkOverwrite( $this->mDestName );
103 if( $overwrite !== true )
104 return array( 'status' => self::OVERWRITE_EXISTING_FILE, 'overwrite' => $overwrite );
105
106 /**
107 * Look at the contents of the file; if we can recognize the
108 * type but it's corrupt or data of the wrong type, we should
109 * probably not accept it.
110 */
111 $verification = $this->verifyFile( $this->mTempPath );
112
113 if( $verification !== true ) {
114 if( !is_array( $verification ) )
115 $verification = array( $verification );
116 $verification['status'] = self::VERIFICATION_ERROR;
117 return $verification;
118 }
119
120 $error = '';
121 if( !wfRunHooks( 'UploadVerification',
122 array( $this->mDestName, $this->mTempPath, &$error ) ) ) {
123 return array( 'status' => self::UPLOAD_VERIFICATION_ERROR, 'error' => $error );
124 }
125
126 return self::OK;
127 }
128
129 /**
130 * Verifies that it's ok to include the uploaded file
131 *
132 * @param string $tmpfile the full path of the temporary file to verify
133 * @return mixed true of the file is verified, a string or array otherwise.
134 */
135 protected function verifyFile( $tmpfile ) {
136 $this->mFileProps = File::getPropsFromPath( $this->mTempPath,
137 $this->mFinalExtension );
138 $this->checkMacBinary();
139
140 #magically determine mime type
141 $magic = MimeMagic::singleton();
142 $mime = $magic->guessMimeType( $tmpfile, false );
143
144 #check mime type, if desired
145 global $wgVerifyMimeType;
146 if ( $wgVerifyMimeType ) {
147
148 wfDebug ( "\n\nmime: <$mime> extension: <{$this->mFinalExtension}>\n\n");
149 #check mime type against file extension
150 if( !self::verifyExtension( $mime, $this->mFinalExtension ) ) {
151 return 'uploadcorrupt';
152 }
153
154 #check mime type blacklist
155 global $wgMimeTypeBlacklist;
156 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
157 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
158 return array( 'filetype-badmime', $mime );
159 }
160 }
161
162 #check for htmlish code and javascript
163 if( $this->detectScript ( $tmpfile, $mime, $this->mFinalExtension ) ) {
164 return 'uploadscripted';
165 }
166
167 /**
168 * Scan the uploaded file for viruses
169 */
170 $virus = $this->detectVirus($tmpfile);
171 if ( $virus ) {
172 return array( 'uploadvirus', $virus );
173 }
174
175 wfDebug( __METHOD__.": all clear; passing.\n" );
176 return true;
177 }
178
179 function verifyPermissions( $user ) {
180 /**
181 * If the image is protected, non-sysop users won't be able
182 * to modify it by uploading a new revision.
183 */
184 $nt = $this->getTitle();
185 if( is_null( $nt ) )
186 return true;
187 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
188 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
189 $permErrorsCreate = ( $nt->exists() ? array() : $nt->getUserPermissionsErrors( 'create', $user ) );
190 if( $permErrors || $permErrorsUpload || $permErrorsCreate ) {
191 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
192 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
193 return $permErrors;
194 }
195 return true;
196 }
197
198 function checkWarnings() {
199 $warning = array();
200
201 $filename = $this->mLocalFile->getName();
202 $n = strrpos( $filename, '.' );
203 $partname = $n ? substr( $filename, 0, $n ) : $filename;
204
205 global $wgCapitalLinks;
206 if( $this->mDesiredDestName != $filename )
207 $warning['badfilename'] = $filename;
208
209 global $wgCheckFileExtensions, $wgFileExtensions;
210 if ( $wgCheckFileExtensions ) {
211 if ( !$this->checkFileExtension( $this->mFinalExtension, $wgFileExtensions ) )
212 $warning['filetype-unwanted-type'] = $this->mFinalExtension;
213 }
214
215 global $wgUploadSizeWarning;
216 if ( $wgUploadSizeWarning && ( $this->mFileSize > $wgUploadSizeWarning ) )
217 $warning['large-file'] = $wgUploadSizeWarning;
218
219 if ( $this->mFileSize == 0 )
220 $warning['emptyfile'] = true;
221
222 $exists = self::getExistsWarning( $this->mLocalFile );
223 if( $exists !== false )
224 $warning['exists'] = $exists;
225
226
227 if( $exists !== false && $exists[0] != 'thumb'
228 && self::isThumbName( $this->mLocalFile->getName() ) )
229 $warning['file-thumbnail-no'] = substr( $filename , 0,
230 strpos( $nt->getText() , '-' ) +1 );
231
232 $hash = File::sha1Base36( $this->mTempPath );
233 $dupes = RepoGroup::singleton()->findBySha1( $hash );
234 if( $dupes )
235 $warning['duplicate'] = $dupes;
236
237 $filenamePrefixBlacklist = self::getFilenamePrefixBlacklist();
238 foreach( $filenamePrefixBlacklist as $prefix ) {
239 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
240 $warning['filename-bad-prefix'] = $prefix;
241 break;
242 }
243 }
244
245 # If the file existed before and was deleted, warn the user of this
246 # Don't bother doing so if the file exists now, however
247 if( $this->mLocalFile->wasDeleted() && !$this->mLocalFile->exists() )
248 $warning['filewasdeleted'] = $this->mLocalFile->getTitle();
249
250 return $warning;
251 }
252
253 function performUpload( $comment, $pageText, $watch, $user ) {
254 $status = $this->mLocalFile->upload( $this->mTempPath, $comment, $pageText,
255 File::DELETE_SOURCE, $this->mFileProps, false, $user );
256
257 if( $status->isGood() && $watch ) {
258 $user->addWatch( $this->mLocalFile->getTitle() );
259 }
260
261 if( $status->isGood() )
262 wfRunHooks( 'UploadComplete', array( &$this ) );
263
264 return $status;
265 }
266
267 /**
268 * Returns a title or null
269 */
270 function getTitle() {
271 if ( $this->mTitle !== false )
272 return $this->mTitle;
273
274 /**
275 * Chop off any directories in the given filename. Then
276 * filter out illegal characters, and try to make a legible name
277 * out of it. We'll strip some silently that Title would die on.
278 */
279
280 $basename = $this->mDesiredDestName;
281
282 $this->mFilteredName = wfStripIllegalFilenameChars( $basename );
283
284 /**
285 * We'll want to blacklist against *any* 'extension', and use
286 * only the final one for the whitelist.
287 */
288 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName );
289
290 if( count( $ext ) ) {
291 $this->mFinalExtension = $ext[count( $ext ) - 1];
292 } else {
293 $this->mFinalExtension = '';
294 }
295
296 /* Don't allow users to override the blacklist (check file extension) */
297 global $wgCheckFileExtensions, $wgStrictFileExtensions;
298 global $wgFileExtensions, $wgFileBlacklist;
299 if ( $this->mFinalExtension == '' ) {
300 $this->mTitleError = self::FILETYPE_MISSING;
301 return $this->mTitle = null;
302 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
303 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
304 !$this->checkFileExtension( $this->mFinalExtension, $wgFileExtensions ) ) ) {
305 $this->mTitleError = self::FILETYPE_BADTYPE;
306 return $this->mTitle = null;
307 }
308
309 # If there was more than one "extension", reassemble the base
310 # filename to prevent bogus complaints about length
311 if( count( $ext ) > 1 ) {
312 for( $i = 0; $i < count( $ext ) - 1; $i++ )
313 $partname .= '.' . $ext[$i];
314 }
315
316 if( strlen( $partname ) < 1 ) {
317 $this->mTitleError = self::MIN_LENGTH_PARTNAME;
318 return $this->mTitle = null;
319 }
320
321 $nt = Title::makeTitleSafe( NS_IMAGE, $this->mFilteredName );
322 if( is_null( $nt ) ) {
323 $this->mTitleError = self::ILLEGAL_FILENAME;
324 return $this->mTitle = null;
325 }
326 return $this->mTitle = $nt;
327 }
328
329 function getLocalFile() {
330 if( is_null( $this->mLocalFile ) ) {
331 $nt = $this->getTitle();
332 $this->mLocalFile = is_null( $nt ) ? null : wfLocalFile( $nt );
333 }
334 return $this->mLocalFile;
335 }
336
337 /**
338 * Stash a file in a temporary directory for later processing
339 * after the user has confirmed it.
340 *
341 * If the user doesn't explicitly cancel or accept, these files
342 * can accumulate in the temp directory.
343 *
344 * @param string $saveName - the destination filename
345 * @param string $tempName - the source temporary file to save
346 * @return string - full path the stashed file, or false on failure
347 * @access private
348 */
349 function saveTempUploadedFile( $saveName, $tempName ) {
350 global $wgOut;
351 $repo = RepoGroup::singleton()->getLocalRepo();
352 $status = $repo->storeTemp( $saveName, $tempName );
353 return $status;
354 }
355
356 /**
357 * Stash a file in a temporary directory for later processing,
358 * and save the necessary descriptive info into the session.
359 * Returns a key value which will be passed through a form
360 * to pick up the path info on a later invocation.
361 *
362 * @return int
363 * @access private
364 */
365 function stashSession() {
366 $status = $this->saveTempUploadedFile( $this->mDestName, $this->mTempPath );
367
368 if( !$status->isGood() ) {
369 # Couldn't save the file.
370 return false;
371 }
372
373 return array(
374 'mTempPath' => $status->value,
375 'mFileSize' => $this->mFileSize,
376 'mFileProps' => $this->mFileProps,
377 'version' => self::SESSION_VERSION,
378 );
379 }
380
381 /**
382 * Remove a temporarily kept file stashed by saveTempUploadedFile().
383 * @return success
384 */
385 function unsaveUploadedFile() {
386 $repo = RepoGroup::singleton()->getLocalRepo();
387 $success = $repo->freeTemp( $this->mTempPath );
388 return $success;
389 }
390
391 /**
392 * If we've modified the upload file we need to manually remove it
393 * on exit to clean up.
394 * @access private
395 */
396 function cleanupTempFile() {
397 if ( $this->mRemoveTempFile && file_exists( $this->mTempPath ) ) {
398 wfDebug( __METHOD__.": Removing temporary file {$this->mTempPath}\n" );
399 unlink( $this->mTempPath );
400 }
401 }
402
403 function getTempPath() {
404 return $this->mTempPath;
405 }
406
407
408 /**
409 * Split a file into a base name and all dot-delimited 'extensions'
410 * on the end. Some web server configurations will fall back to
411 * earlier pseudo-'extensions' to determine type and execute
412 * scripts, so the blacklist needs to check them all.
413 *
414 * @return array
415 */
416 function splitExtensions( $filename ) {
417 $bits = explode( '.', $filename );
418 $basename = array_shift( $bits );
419 return array( $basename, $bits );
420 }
421
422 /**
423 * Perform case-insensitive match against a list of file extensions.
424 * Returns true if the extension is in the list.
425 *
426 * @param string $ext
427 * @param array $list
428 * @return bool
429 */
430 function checkFileExtension( $ext, $list ) {
431 return in_array( strtolower( $ext ), $list );
432 }
433
434 /**
435 * Perform case-insensitive match against a list of file extensions.
436 * Returns true if any of the extensions are in the list.
437 *
438 * @param array $ext
439 * @param array $list
440 * @return bool
441 */
442 function checkFileExtensionList( $ext, $list ) {
443 foreach( $ext as $e ) {
444 if( in_array( strtolower( $e ), $list ) ) {
445 return true;
446 }
447 }
448 return false;
449 }
450
451
452 /**
453 * Checks if the mime type of the uploaded file matches the file extension.
454 *
455 * @param string $mime the mime type of the uploaded file
456 * @param string $extension The filename extension that the file is to be served with
457 * @return bool
458 */
459 public static function verifyExtension( $mime, $extension ) {
460 $magic = MimeMagic::singleton();
461
462 if ( ! $mime || $mime == 'unknown' || $mime == 'unknown/unknown' )
463 if ( ! $magic->isRecognizableExtension( $extension ) ) {
464 wfDebug( __METHOD__.": passing file with unknown detected mime type; " .
465 "unrecognized extension '$extension', can't verify\n" );
466 return true;
467 } else {
468 wfDebug( __METHOD__.": rejecting file with unknown detected mime type; ".
469 "recognized extension '$extension', so probably invalid file\n" );
470 return false;
471 }
472
473 $match= $magic->isMatchingExtension($extension,$mime);
474
475 if ($match===NULL) {
476 wfDebug( __METHOD__.": no file extension known for mime type $mime, passing file\n" );
477 return true;
478 } elseif ($match===true) {
479 wfDebug( __METHOD__.": mime type $mime matches extension $extension, passing file\n" );
480
481 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
482 return true;
483
484 } else {
485 wfDebug( __METHOD__.": mime type $mime mismatches file extension $extension, rejecting file\n" );
486 return false;
487 }
488 }
489
490 /**
491 * Heuristic for detecting files that *could* contain JavaScript instructions or
492 * things that may look like HTML to a browser and are thus
493 * potentially harmful. The present implementation will produce false positives in some situations.
494 *
495 * @param string $file Pathname to the temporary upload file
496 * @param string $mime The mime type of the file
497 * @param string $extension The extension of the file
498 * @return bool true if the file contains something looking like embedded scripts
499 */
500 function detectScript($file, $mime, $extension) {
501 global $wgAllowTitlesInSVG;
502
503 #ugly hack: for text files, always look at the entire file.
504 #For binary field, just check the first K.
505
506 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
507 else {
508 $fp = fopen( $file, 'rb' );
509 $chunk = fread( $fp, 1024 );
510 fclose( $fp );
511 }
512
513 $chunk= strtolower( $chunk );
514
515 if (!$chunk) return false;
516
517 #decode from UTF-16 if needed (could be used for obfuscation).
518 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
519 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
520 else $enc= NULL;
521
522 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
523
524 $chunk= trim($chunk);
525
526 #FIXME: convert from UTF-16 if necessarry!
527
528 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
529
530 #check for HTML doctype
531 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
532
533 /**
534 * Internet Explorer for Windows performs some really stupid file type
535 * autodetection which can cause it to interpret valid image files as HTML
536 * and potentially execute JavaScript, creating a cross-site scripting
537 * attack vectors.
538 *
539 * Apple's Safari browser also performs some unsafe file type autodetection
540 * which can cause legitimate files to be interpreted as HTML if the
541 * web server is not correctly configured to send the right content-type
542 * (or if you're really uploading plain text and octet streams!)
543 *
544 * Returns true if IE is likely to mistake the given file for HTML.
545 * Also returns true if Safari would mistake the given file for HTML
546 * when served with a generic content-type.
547 */
548
549 $tags = array(
550 '<body',
551 '<head',
552 '<html', #also in safari
553 '<img',
554 '<pre',
555 '<script', #also in safari
556 '<table'
557 );
558 if( ! $wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
559 $tags[] = '<title';
560 }
561
562 foreach( $tags as $tag ) {
563 if( false !== strpos( $chunk, $tag ) ) {
564 return true;
565 }
566 }
567
568 /*
569 * look for javascript
570 */
571
572 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
573 $chunk = Sanitizer::decodeCharReferences( $chunk );
574
575 #look for script-types
576 if (preg_match('!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim',$chunk)) return true;
577
578 #look for html-style script-urls
579 if (preg_match('!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
580
581 #look for css-style script-urls
582 if (preg_match('!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
583
584 wfDebug("SpecialUpload::detectScript: no scripts found\n");
585 return false;
586 }
587
588 /**
589 * Generic wrapper function for a virus scanner program.
590 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
591 * $wgAntivirusRequired may be used to deny upload if the scan fails.
592 *
593 * @param string $file Pathname to the temporary upload file
594 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
595 * or a string containing feedback from the virus scanner if a virus was found.
596 * If textual feedback is missing but a virus was found, this function returns true.
597 */
598 function detectVirus($file) {
599 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
600
601 if ( !$wgAntivirus ) {
602 wfDebug( __METHOD__.": virus scanner disabled\n");
603 return NULL;
604 }
605
606 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
607 wfDebug( __METHOD__.": unknown virus scanner: $wgAntivirus\n" );
608 $wgOut->wrapWikiMsg( '<div class="error">$1</div>', array( 'virus-badscanner', $wgAntivirus ) );
609 return wfMsg('virus-unknownscanner') . " $wgAntivirus";
610 }
611
612 # look up scanner configuration
613 $command = $wgAntivirusSetup[$wgAntivirus]["command"];
614 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]["codemap"];
615 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]["messagepattern"] ) ?
616 $wgAntivirusSetup[$wgAntivirus]["messagepattern"] : null;
617
618 if ( strpos( $command,"%f" ) === false ) {
619 # simple pattern: append file to scan
620 $command .= " " . wfEscapeShellArg( $file );
621 } else {
622 # complex pattern: replace "%f" with file to scan
623 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
624 }
625
626 wfDebug( __METHOD__.": running virus scan: $command \n" );
627
628 # execute virus scanner
629 $exitCode = false;
630
631 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
632 # that does not seem to be worth the pain.
633 # Ask me (Duesentrieb) about it if it's ever needed.
634 $output = array();
635 if ( wfIsWindows() ) {
636 exec( "$command", $output, $exitCode );
637 } else {
638 exec( "$command 2>&1", $output, $exitCode );
639 }
640
641 # map exit code to AV_xxx constants.
642 $mappedCode = $exitCode;
643 if ( $exitCodeMap ) {
644 if ( isset( $exitCodeMap[$exitCode] ) ) {
645 $mappedCode = $exitCodeMap[$exitCode];
646 } elseif ( isset( $exitCodeMap["*"] ) ) {
647 $mappedCode = $exitCodeMap["*"];
648 }
649 }
650
651 if ( $mappedCode === AV_SCAN_FAILED ) {
652 # scan failed (code was mapped to false by $exitCodeMap)
653 wfDebug( __METHOD__.": failed to scan $file (code $exitCode).\n" );
654
655 if ( $wgAntivirusRequired ) {
656 return wfMsg('virus-scanfailed', array( $exitCode ) );
657 } else {
658 return NULL;
659 }
660 } else if ( $mappedCode === AV_SCAN_ABORTED ) {
661 # scan failed because filetype is unknown (probably imune)
662 wfDebug( __METHOD__.": unsupported file type $file (code $exitCode).\n" );
663 return NULL;
664 } else if ( $mappedCode === AV_NO_VIRUS ) {
665 # no virus found
666 wfDebug( __METHOD__.": file passed virus scan.\n" );
667 return false;
668 } else {
669 $output = join( "\n", $output );
670 $output = trim( $output );
671
672 if ( !$output ) {
673 $output = true; #if there's no output, return true
674 } elseif ( $msgPattern ) {
675 $groups = array();
676 if ( preg_match( $msgPattern, $output, $groups ) ) {
677 if ( $groups[1] ) {
678 $output = $groups[1];
679 }
680 }
681 }
682
683 wfDebug( __METHOD__.": FOUND VIRUS! scanner feedback: $output" );
684 return $output;
685 }
686 }
687
688 /**
689 * Check if the temporary file is MacBinary-encoded, as some uploads
690 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
691 * If so, the data fork will be extracted to a second temporary file,
692 * which will then be checked for validity and either kept or discarded.
693 *
694 * @access private
695 */
696 function checkMacBinary() {
697 $macbin = new MacBinary( $this->mTempPath );
698 if( $macbin->isValid() ) {
699 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
700 $dataHandle = fopen( $dataFile, 'wb' );
701
702 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
703 $macbin->extractData( $dataHandle );
704
705 $this->mTempPath = $dataFile;
706 $this->mFileSize = $macbin->dataForkLength();
707
708 // We'll have to manually remove the new file if it's not kept.
709 $this->mRemoveTempFile = true;
710 }
711 $macbin->close();
712 }
713
714 /**
715 * Check if there's an overwrite conflict and, if so, if restrictions
716 * forbid this user from performing the upload.
717 *
718 * @return mixed true on success, WikiError on failure
719 * @access private
720 */
721 function checkOverwrite() {
722 global $wgUser;
723 // First check whether the local file can be overwritten
724 if( $this->mLocalFile->exists() )
725 if( !self::userCanReUpload( $wgUser, $this->mLocalFile ) )
726 return 'fileexists-forbidden';
727
728 // Check shared conflicts
729 $file = wfFindFile( $this->mLocalFile->getName() );
730 if ( $file && ( !$wgUser->isAllowed( 'reupload' ) ||
731 !$wgUser->isAllowed( 'reupload-shared' ) ) )
732 return 'fileexists-shared-forbidden';
733
734 return true;
735
736 }
737
738 /**
739 * Check if a user is the last uploader
740 *
741 * @param User $user
742 * @param string $img, image name
743 * @return bool
744 */
745 public static function userCanReUpload( User $user, $img ) {
746 if( $user->isAllowed( 'reupload' ) )
747 return true; // non-conditional
748 if( !$user->isAllowed( 'reupload-own' ) )
749 return false;
750 if( is_string( $img ) )
751 $img = wfLocalFile( $img );
752 if ( !( $img instanceof LocalFile ) )
753 return false;
754
755 return $user->getId() == $img->getUser( 'id' );
756 }
757
758 public static function getExistsWarning( $file ) {
759 if( $file->exists() )
760 return array( 'exists', $file );
761
762 if( $file->getTitle()->getArticleID() )
763 return array( 'page-exists', $file );
764
765 if( strpos( $file->getName(), '.' ) == false ) {
766 $partname = $file->getName();
767 $rawExtension = '';
768 } else {
769 $n = strrpos( $file->getName(), '.' );
770 $rawExtension = substr( $file->getName(), $n + 1 );
771 $partname = substr( $file->getName(), 0, $n );
772 }
773
774 if ( $rawExtension != $file->getExtension() ) {
775 // We're not using the normalized form of the extension.
776 // Normal form is lowercase, using most common of alternate
777 // extensions (eg 'jpg' rather than 'JPEG').
778 //
779 // Check for another file using the normalized form...
780 $nt_lc = Title::makeTitle( NS_IMAGE, $partname . '.' . $file->getExtension() );
781 $file_lc = wfLocalFile( $nt_lc );
782
783 if( $file_lc->exists() )
784 return array( 'exists-normalized', $file_lc );
785 }
786
787 if ( self::isThumbName( $file->getName() ) ) {
788 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
789 $nt_thb = Title::newFromText( substr( $partname , strpos( $partname , '-' ) +1 ) . '.' . $rawExtension );
790 $file_thb = wfLocalFile( $nt_thb );
791 if( $file_thb->exists() )
792 return array( 'thumb', $file_thb );
793 }
794
795 return false;
796 }
797
798 public static function isThumbName( $filename ) {
799 $n = strrpos( $filename, '.' );
800 $partname = $n ? substr( $filename, 0, $n ) : $filename;
801 return (
802 substr( $partname , 3, 3 ) == 'px-' ||
803 substr( $partname , 2, 3 ) == 'px-'
804 ) &&
805 ereg( "[0-9]{2}" , substr( $partname , 0, 2) );
806 }
807
808 /**
809 * Get a list of blacklisted filename prefixes from [[MediaWiki:filename-prefix-blacklist]]
810 *
811 * @return array list of prefixes
812 */
813 public static function getFilenamePrefixBlacklist() {
814 $blacklist = array();
815 $message = wfMsgForContent( 'filename-prefix-blacklist' );
816 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) || $message == '-' ) ) {
817 $lines = explode( "\n", $message );
818 foreach( $lines as $line ) {
819 // Remove comment lines
820 $comment = substr( trim( $line ), 0, 1 );
821 if ( $comment == '#' || $comment == '' ) {
822 continue;
823 }
824 // Remove additional comments after a prefix
825 $comment = strpos( $line, '#' );
826 if ( $comment > 0 ) {
827 $line = substr( $line, 0, $comment-1 );
828 }
829 $blacklist[] = trim( $line );
830 }
831 }
832 return $blacklist;
833 }
834
835
836 }