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