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