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