* (bug 3069) Warning on upload of scaled down images
[lhc/web/wiklou.git] / includes / SpecialUpload.php
1 <?php
2 /**
3 *
4 * @addtogroup SpecialPage
5 */
6
7
8 /**
9 * Entry point
10 */
11 function wfSpecialUpload() {
12 global $wgRequest;
13 $form = new UploadForm( $wgRequest );
14 $form->execute();
15 }
16
17 /**
18 *
19 * @addtogroup SpecialPage
20 */
21 class UploadForm {
22 /**#@+
23 * @access private
24 */
25 var $mUploadFile, $mUploadDescription, $mLicense ,$mIgnoreWarning, $mUploadError;
26 var $mUploadSaveName, $mUploadTempName, $mUploadSize, $mUploadOldVersion;
27 var $mUploadCopyStatus, $mUploadSource, $mReUpload, $mAction, $mUpload;
28 var $mOname, $mSessionKey, $mStashed, $mDestFile, $mRemoveTempFile, $mSourceType;
29 var $mUploadTempFileSize = 0;
30
31 # Placeholders for text injection by hooks (must be HTML)
32 # extensions should take care to _append_ to the present value
33 var $uploadFormTextTop;
34 var $uploadFormTextAfterSummary;
35
36 /**#@-*/
37
38 /**
39 * Constructor : initialise object
40 * Get data POSTed through the form and assign them to the object
41 * @param $request Data posted.
42 */
43 function UploadForm( &$request ) {
44 global $wgAllowCopyUploads;
45 $this->mDestFile = $request->getText( 'wpDestFile' );
46
47 if( !$request->wasPosted() ) {
48 # GET requests just give the main form; no data except wpDestfile.
49 return;
50 }
51
52 # Placeholders for text injection by hooks (empty per default)
53 $this->uploadFormTextTop = "";
54 $this->uploadFormTextAfterSummary = "";
55
56 $this->mIgnoreWarning = $request->getCheck( 'wpIgnoreWarning' );
57 $this->mReUpload = $request->getCheck( 'wpReUpload' );
58 $this->mUpload = $request->getCheck( 'wpUpload' );
59
60 $this->mUploadDescription = $request->getText( 'wpUploadDescription' );
61 $this->mLicense = $request->getText( 'wpLicense' );
62 $this->mUploadCopyStatus = $request->getText( 'wpUploadCopyStatus' );
63 $this->mUploadSource = $request->getText( 'wpUploadSource' );
64 $this->mWatchthis = $request->getBool( 'wpWatchthis' );
65 $this->mSourceType = $request->getText( 'wpSourceType' );
66 wfDebug( "UploadForm: watchthis is: '$this->mWatchthis'\n" );
67
68 $this->mAction = $request->getVal( 'action' );
69
70 $this->mSessionKey = $request->getInt( 'wpSessionKey' );
71 if( !empty( $this->mSessionKey ) &&
72 isset( $_SESSION['wsUploadData'][$this->mSessionKey] ) ) {
73 /**
74 * Confirming a temporarily stashed upload.
75 * We don't want path names to be forged, so we keep
76 * them in the session on the server and just give
77 * an opaque key to the user agent.
78 */
79 $data = $_SESSION['wsUploadData'][$this->mSessionKey];
80 $this->mUploadTempName = $data['mUploadTempName'];
81 $this->mUploadSize = $data['mUploadSize'];
82 $this->mOname = $data['mOname'];
83 $this->mUploadError = 0/*UPLOAD_ERR_OK*/;
84 $this->mStashed = true;
85 $this->mRemoveTempFile = false;
86 } else {
87 /**
88 *Check for a newly uploaded file.
89 */
90 if( $wgAllowCopyUploads && $this->mSourceType == 'web' ) {
91 $this->initializeFromUrl( $request );
92 } else {
93 $this->initializeFromUpload( $request );
94 }
95 }
96 }
97
98 /**
99 * Initialize the uploaded file from PHP data
100 * @access private
101 */
102 function initializeFromUpload( $request ) {
103 $this->mUploadTempName = $request->getFileTempName( 'wpUploadFile' );
104 $this->mUploadSize = $request->getFileSize( 'wpUploadFile' );
105 $this->mOname = $request->getFileName( 'wpUploadFile' );
106 $this->mUploadError = $request->getUploadError( 'wpUploadFile' );
107 $this->mSessionKey = false;
108 $this->mStashed = false;
109 $this->mRemoveTempFile = false; // PHP will handle this
110 }
111
112 /**
113 * Copy a web file to a temporary file
114 * @access private
115 */
116 function initializeFromUrl( $request ) {
117 global $wgTmpDirectory;
118 $url = $request->getText( 'wpUploadFileURL' );
119 $local_file = tempnam( $wgTmpDirectory, 'WEBUPLOAD' );
120
121 $this->mUploadTempName = $local_file;
122 $this->mUploadError = $this->curlCopy( $url, $local_file );
123 $this->mUploadSize = $this->mUploadTempFileSize;
124 $this->mOname = array_pop( explode( '/', $url ) );
125 $this->mSessionKey = false;
126 $this->mStashed = false;
127
128 // PHP won't auto-cleanup the file
129 $this->mRemoveTempFile = file_exists( $local_file );
130 }
131
132 /**
133 * Safe copy from URL
134 * Returns true if there was an error, false otherwise
135 */
136 private function curlCopy( $url, $dest ) {
137 global $wgUser, $wgOut;
138
139 if( !$wgUser->isAllowed( 'upload_by_url' ) ) {
140 $wgOut->permissionRequired( 'upload_by_url' );
141 return true;
142 }
143
144 # Maybe remove some pasting blanks :-)
145 $url = trim( $url );
146 if( stripos($url, 'http://') !== 0 && stripos($url, 'ftp://') !== 0 ) {
147 # Only HTTP or FTP URLs
148 $wgOut->errorPage( 'upload-proto-error', 'upload-proto-error-text' );
149 return true;
150 }
151
152 # Open temporary file
153 $this->mUploadTempFile = @fopen( $this->mUploadTempName, "wb" );
154 if( $this->mUploadTempFile === false ) {
155 # Could not open temporary file to write in
156 $wgOut->errorPage( 'upload-file-error', 'upload-file-error-text');
157 return true;
158 }
159
160 $ch = curl_init();
161 curl_setopt( $ch, CURLOPT_HTTP_VERSION, 1.0); # Probably not needed, but apparently can work around some bug
162 curl_setopt( $ch, CURLOPT_TIMEOUT, 10); # 10 seconds timeout
163 curl_setopt( $ch, CURLOPT_LOW_SPEED_LIMIT, 512); # 0.5KB per second minimum transfer speed
164 curl_setopt( $ch, CURLOPT_URL, $url);
165 curl_setopt( $ch, CURLOPT_WRITEFUNCTION, array( $this, 'uploadCurlCallback' ) );
166 curl_exec( $ch );
167 $error = curl_errno( $ch ) ? true : false;
168 $errornum = curl_errno( $ch );
169 // if ( $error ) print curl_error ( $ch ) ; # Debugging output
170 curl_close( $ch );
171
172 fclose( $this->mUploadTempFile );
173 unset( $this->mUploadTempFile );
174 if( $error ) {
175 unlink( $dest );
176 if( wfEmptyMsg( "upload-curl-error$errornum", wfMsg("upload-curl-error$errornum") ) )
177 $wgOut->errorPage( 'upload-misc-error', 'upload-misc-error-text' );
178 else
179 $wgOut->errorPage( "upload-curl-error$errornum", "upload-curl-error$errornum-text" );
180 }
181
182 return $error;
183 }
184
185 /**
186 * Callback function for CURL-based web transfer
187 * Write data to file unless we've passed the length limit;
188 * if so, abort immediately.
189 * @access private
190 */
191 function uploadCurlCallback( $ch, $data ) {
192 global $wgMaxUploadSize;
193 $length = strlen( $data );
194 $this->mUploadTempFileSize += $length;
195 if( $this->mUploadTempFileSize > $wgMaxUploadSize ) {
196 return 0;
197 }
198 fwrite( $this->mUploadTempFile, $data );
199 return $length;
200 }
201
202 /**
203 * Start doing stuff
204 * @access public
205 */
206 function execute() {
207 global $wgUser, $wgOut;
208 global $wgEnableUploads, $wgUploadDirectory;
209
210 # Check uploading enabled
211 if( !$wgEnableUploads ) {
212 $wgOut->showErrorPage( 'uploaddisabled', 'uploaddisabledtext' );
213 return;
214 }
215
216 # Check permissions
217 if( !$wgUser->isAllowed( 'upload' ) ) {
218 if( !$wgUser->isLoggedIn() ) {
219 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
220 } else {
221 $wgOut->permissionRequired( 'upload' );
222 }
223 return;
224 }
225
226 # Check blocks
227 if( $wgUser->isBlocked() ) {
228 $wgOut->blockedPage();
229 return;
230 }
231
232 if( wfReadOnly() ) {
233 $wgOut->readOnlyPage();
234 return;
235 }
236
237 /** Check if the image directory is writeable, this is a common mistake */
238 if( !is_writeable( $wgUploadDirectory ) ) {
239 $wgOut->addWikiText( wfMsg( 'upload_directory_read_only', $wgUploadDirectory ) );
240 return;
241 }
242
243 if( $this->mReUpload ) {
244 if( !$this->unsaveUploadedFile() ) {
245 return;
246 }
247 $this->mainUploadForm();
248 } else if( 'submit' == $this->mAction || $this->mUpload ) {
249 $this->processUpload();
250 } else {
251 $this->mainUploadForm();
252 }
253
254 $this->cleanupTempFile();
255 }
256
257 /* -------------------------------------------------------------- */
258
259 /**
260 * Really do the upload
261 * Checks are made in SpecialUpload::execute()
262 * @access private
263 */
264 function processUpload() {
265 global $wgUser, $wgOut;
266
267 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) )
268 {
269 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file." );
270 return false;
271 }
272
273 /* Check for PHP error if any, requires php 4.2 or newer */
274 if( $this->mUploadError == 1/*UPLOAD_ERR_INI_SIZE*/ ) {
275 $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
276 return;
277 }
278
279 /**
280 * If there was no filename or a zero size given, give up quick.
281 */
282 if( trim( $this->mOname ) == '' || empty( $this->mUploadSize ) ) {
283 $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
284 return;
285 }
286
287 # Chop off any directories in the given filename
288 if( $this->mDestFile ) {
289 $basename = wfBaseName( $this->mDestFile );
290 } else {
291 $basename = wfBaseName( $this->mOname );
292 }
293
294 /**
295 * We'll want to blacklist against *any* 'extension', and use
296 * only the final one for the whitelist.
297 */
298 list( $partname, $ext ) = $this->splitExtensions( $basename );
299
300 if( count( $ext ) ) {
301 $finalExt = $ext[count( $ext ) - 1];
302 } else {
303 $finalExt = '';
304 }
305
306 # If there was more than one "extension", reassemble the base
307 # filename to prevent bogus complaints about length
308 if( count( $ext ) > 1 ) {
309 for( $i = 0; $i < count( $ext ) - 1; $i++ )
310 $partname .= '.' . $ext[$i];
311 }
312
313 if( strlen( $partname ) < 3 ) {
314 $this->mainUploadForm( wfMsgHtml( 'minlength' ) );
315 return;
316 }
317
318 /**
319 * Filter out illegal characters, and try to make a legible name
320 * out of it. We'll strip some silently that Title would die on.
321 */
322 $filtered = preg_replace ( "/[^".Title::legalChars()."]|:/", '-', $basename );
323 $nt = Title::newFromText( $filtered );
324 if( is_null( $nt ) ) {
325 $this->uploadError( wfMsgWikiHtml( 'illegalfilename', htmlspecialchars( $filtered ) ) );
326 return;
327 }
328 $nt =& Title::makeTitle( NS_IMAGE, $nt->getDBkey() );
329 $this->mUploadSaveName = $nt->getDBkey();
330
331 /**
332 * If the image is protected, non-sysop users won't be able
333 * to modify it by uploading a new revision.
334 */
335 if( !$nt->userCan( 'edit' ) ) {
336 return $this->uploadError( wfMsgWikiHtml( 'protectedpage' ) );
337 }
338
339 /**
340 * In some cases we may forbid overwriting of existing files.
341 */
342 $overwrite = $this->checkOverwrite( $this->mUploadSaveName );
343 if( WikiError::isError( $overwrite ) ) {
344 return $this->uploadError( $overwrite->toString() );
345 }
346
347 /* Don't allow users to override the blacklist (check file extension) */
348 global $wgStrictFileExtensions;
349 global $wgFileExtensions, $wgFileBlacklist;
350 if ($finalExt == '') {
351 return $this->uploadError( wfMsgExt( 'filetype-missing', array ( 'parseinline' ) ) );
352 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
353 ($wgStrictFileExtensions &&
354 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
355 return $this->uploadError( wfMsgExt( 'filetype-badtype', array ( 'parseinline' ), htmlspecialchars( $finalExt ), implode ( ', ', $wgFileExtensions ) ) );
356 }
357
358 /**
359 * Look at the contents of the file; if we can recognize the
360 * type but it's corrupt or data of the wrong type, we should
361 * probably not accept it.
362 */
363 if( !$this->mStashed ) {
364 $this->checkMacBinary();
365 $veri = $this->verify( $this->mUploadTempName, $finalExt );
366
367 if( $veri !== true ) { //it's a wiki error...
368 return $this->uploadError( $veri->toString() );
369 }
370 }
371
372 /**
373 * Provide an opportunity for extensions to add futher checks
374 */
375 $error = '';
376 if( !wfRunHooks( 'UploadVerification',
377 array( $this->mUploadSaveName, $this->mUploadTempName, &$error ) ) ) {
378 return $this->uploadError( $error );
379 }
380
381 /**
382 * Check for non-fatal conditions
383 */
384 if ( ! $this->mIgnoreWarning ) {
385 $warning = '';
386
387 global $wgCapitalLinks;
388 if( $wgCapitalLinks ) {
389 $filtered = ucfirst( $filtered );
390 }
391 if( $this->mUploadSaveName != $filtered ) {
392 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mUploadSaveName ) ).'</li>';
393 }
394
395 global $wgCheckFileExtensions;
396 if ( $wgCheckFileExtensions ) {
397 if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
398 $warning .= '<li>'.wfMsgExt( 'filetype-badtype', array ( 'parseinline' ), htmlspecialchars( $finalExt ), implode ( ', ', $wgFileExtensions ) ).'</li>';
399 }
400 }
401
402 global $wgUploadSizeWarning;
403 if ( $wgUploadSizeWarning && ( $this->mUploadSize > $wgUploadSizeWarning ) ) {
404 $skin = $wgUser->getSkin();
405 $wsize = $skin->formatSize( $wgUploadSizeWarning );
406 $asize = $skin->formatSize( $this->mUploadSize );
407 $warning .= '<li>' . wfMsgHtml( 'large-file', $wsize, $asize ) . '</li>';
408 }
409 if ( $this->mUploadSize == 0 ) {
410 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
411 }
412
413 global $wgUser;
414 $sk = $wgUser->getSkin();
415 $image = new Image( $nt );
416
417 // Check for uppercase extension. We allow these filenames but check if an image
418 // with lowercase extension exists already
419 if ( $finalExt != strtolower( $finalExt ) ) {
420 $nt_lc = Title::newFromText( $partname . '.' . strtolower( $finalExt ) );
421 $image_lc = new Image( $nt_lc );
422 }
423
424 if( $image->exists() ) {
425 $dlink = $sk->makeKnownLinkObj( $nt );
426 $dlink2 = $sk->makeImageLinkObj( $nt, wfMsgExt( 'fileexists-thumb', 'parseinline', $dlink ), $nt->getText(), 'right', false, false, false, true );
427
428 # when $dlink2 begins with a normal href it is not a thumbnail -> do not show the link twice
429 if ( substr( $dlink2, 0, 7) == '<a href' ) $dlink2 = '';
430
431 $warning .= '<li>' . wfMsgExt( 'fileexists', 'parseline', $dlink ) . '</li>' . $dlink2;
432
433 } elseif ( isset( $image_lc) && $image_lc->exists() ) {
434 # Check if image with lowercase extension exists.
435 # It's not forbidden but in 99% it makes no sense to upload the same filename with uppercase extension
436 $dlink = $sk->makeKnownLinkObj( $nt_lc );
437 $dlink2 = $sk->makeImageLinkObj( $nt_lc, wfMsgExt( 'fileexists-thumb', 'parseinline', $dlink ), $nt_lc->getText(), 'right', false, false, false, true );
438
439 # when $dlink2 begins with a normal href it is not a thumbnail -> do not show the link twice
440 if ( substr( $dlink2, 0, 7) == '<a href' ) $dlink2 = '';
441
442 $warning .= '<li>' . wfMsgExt( 'fileexists-extension', 'parsemag' , $partname . '.' . $finalExt , $dlink ) . '</li>' . $dlink2;
443
444 } elseif ( ( substr( $partname , 3, 3 ) == 'px-' || substr( $partname , 2, 3 ) == 'px-' ) && ereg( "[0-9]{2}" , substr( $partname , 0, 2) ) ) {
445 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
446 $nt_thb = Title::newFromText( substr( $partname , strpos( $partname , '-' ) +1 ) . '.' . $finalExt );
447 $image_thb = new Image( $nt_thb );
448 if ($image_thb->exists() ) {
449 # Check if an image without leading '180px-' (or similiar) exists
450 $dlink = $sk->makeKnownLinkObj( $nt_thb);
451 $dlink2 = $sk->makeImageLinkObj( $nt_thb, wfMsgExt( 'fileexists-thumb', 'parseinline', $dlink ), $nt_thb->getText(), 'right', false, false, false, true );
452 # when $dlink2 begins with a normal href it is not a thumbnail -> do not show the link twice
453 if ( substr( $dlink2, 0, 7) == '<a href' ) $dlink2 = '';
454 $warning .= '<li>' . wfMsgExt( 'fileexists-thumbnail-yes', 'parsemag', $dlink ) . '</li>' . $dlink2;
455 } else {
456 # Image w/o '180px-' does not exists, but we do not like these filenames
457 $warning .= '<li>' . wfMsgExt( 'file-thumbnail-no', 'parseinline' , substr( $partname , 0, strpos( $partname , '-' ) +1 ) ) . '</li>';
458 }
459 }
460 if ( $image->wasDeleted() ) {
461 # If the file existed before and was deleted, warn the user of this
462 # Don't bother doing so if the image exists now, however
463 $ltitle = SpecialPage::getTitleFor( 'Log' );
464 $llink = $sk->makeKnownLinkObj( $ltitle, wfMsgHtml( 'deletionlog' ), 'type=delete&page=' . $nt->getPrefixedUrl() );
465 $warning .= wfOpenElement( 'li' ) . wfMsgWikiHtml( 'filewasdeleted', $llink ) . wfCloseElement( 'li' );
466 }
467
468 if( $warning != '' ) {
469 /**
470 * Stash the file in a temporary location; the user can choose
471 * to let it through and we'll complete the upload then.
472 */
473 return $this->uploadWarning( $warning );
474 }
475 }
476
477 /**
478 * Try actually saving the thing...
479 * It will show an error form on failure.
480 */
481 $hasBeenMunged = !empty( $this->mSessionKey ) || $this->mRemoveTempFile;
482 if( $this->saveUploadedFile( $this->mUploadSaveName,
483 $this->mUploadTempName,
484 $hasBeenMunged ) ) {
485 /**
486 * Update the upload log and create the description page
487 * if it's a new file.
488 */
489 $img = Image::newFromName( $this->mUploadSaveName );
490 $success = $img->recordUpload( $this->mUploadOldVersion,
491 $this->mUploadDescription,
492 $this->mLicense,
493 $this->mUploadCopyStatus,
494 $this->mUploadSource,
495 $this->mWatchthis );
496
497 if ( $success ) {
498 $this->showSuccess();
499 wfRunHooks( 'UploadComplete', array( &$img ) );
500 } else {
501 // Image::recordUpload() fails if the image went missing, which is
502 // unlikely, hence the lack of a specialised message
503 $wgOut->showFileNotFoundError( $this->mUploadSaveName );
504 }
505 }
506 }
507
508 /**
509 * Move the uploaded file from its temporary location to the final
510 * destination. If a previous version of the file exists, move
511 * it into the archive subdirectory.
512 *
513 * @todo If the later save fails, we may have disappeared the original file.
514 *
515 * @param string $saveName
516 * @param string $tempName full path to the temporary file
517 * @param bool $useRename if true, doesn't check that the source file
518 * is a PHP-managed upload temporary
519 */
520 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
521 global $wgOut, $wgAllowCopyUploads;
522
523 if ( !$useRename AND $wgAllowCopyUploads AND $this->mSourceType == 'web' ) $useRename = true;
524
525 $fname= "SpecialUpload::saveUploadedFile";
526
527 $dest = wfImageDir( $saveName );
528 $archive = wfImageArchiveDir( $saveName );
529 if ( !is_dir( $dest ) ) wfMkdirParents( $dest );
530 if ( !is_dir( $archive ) ) wfMkdirParents( $archive );
531
532 $this->mSavedFile = "{$dest}/{$saveName}";
533
534 if( is_file( $this->mSavedFile ) ) {
535 $this->mUploadOldVersion = gmdate( 'YmdHis' ) . "!{$saveName}";
536 wfSuppressWarnings();
537 $success = rename( $this->mSavedFile, "${archive}/{$this->mUploadOldVersion}" );
538 wfRestoreWarnings();
539
540 if( ! $success ) {
541 $wgOut->showFileRenameError( $this->mSavedFile,
542 "${archive}/{$this->mUploadOldVersion}" );
543 return false;
544 }
545 else wfDebug("$fname: moved file ".$this->mSavedFile." to ${archive}/{$this->mUploadOldVersion}\n");
546 }
547 else {
548 $this->mUploadOldVersion = '';
549 }
550
551 wfSuppressWarnings();
552 $success = $useRename
553 ? rename( $tempName, $this->mSavedFile )
554 : move_uploaded_file( $tempName, $this->mSavedFile );
555 wfRestoreWarnings();
556
557 if( ! $success ) {
558 $wgOut->showFileCopyError( $tempName, $this->mSavedFile );
559 return false;
560 } else {
561 wfDebug("$fname: wrote tempfile $tempName to ".$this->mSavedFile."\n");
562 }
563
564 chmod( $this->mSavedFile, 0644 );
565 return true;
566 }
567
568 /**
569 * Stash a file in a temporary directory for later processing
570 * after the user has confirmed it.
571 *
572 * If the user doesn't explicitly cancel or accept, these files
573 * can accumulate in the temp directory.
574 *
575 * @param string $saveName - the destination filename
576 * @param string $tempName - the source temporary file to save
577 * @return string - full path the stashed file, or false on failure
578 * @access private
579 */
580 function saveTempUploadedFile( $saveName, $tempName ) {
581 global $wgOut;
582 $archive = wfImageArchiveDir( $saveName, 'temp' );
583 if ( !is_dir ( $archive ) ) wfMkdirParents( $archive );
584 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
585
586 $success = $this->mRemoveTempFile
587 ? rename( $tempName, $stash )
588 : move_uploaded_file( $tempName, $stash );
589 if ( !$success ) {
590 $wgOut->showFileCopyError( $tempName, $stash );
591 return false;
592 }
593
594 return $stash;
595 }
596
597 /**
598 * Stash a file in a temporary directory for later processing,
599 * and save the necessary descriptive info into the session.
600 * Returns a key value which will be passed through a form
601 * to pick up the path info on a later invocation.
602 *
603 * @return int
604 * @access private
605 */
606 function stashSession() {
607 $stash = $this->saveTempUploadedFile(
608 $this->mUploadSaveName, $this->mUploadTempName );
609
610 if( !$stash ) {
611 # Couldn't save the file.
612 return false;
613 }
614
615 $key = mt_rand( 0, 0x7fffffff );
616 $_SESSION['wsUploadData'][$key] = array(
617 'mUploadTempName' => $stash,
618 'mUploadSize' => $this->mUploadSize,
619 'mOname' => $this->mOname );
620 return $key;
621 }
622
623 /**
624 * Remove a temporarily kept file stashed by saveTempUploadedFile().
625 * @access private
626 * @return success
627 */
628 function unsaveUploadedFile() {
629 global $wgOut;
630 wfSuppressWarnings();
631 $success = unlink( $this->mUploadTempName );
632 wfRestoreWarnings();
633 if ( ! $success ) {
634 $wgOut->showFileDeleteError( $this->mUploadTempName );
635 return false;
636 } else {
637 return true;
638 }
639 }
640
641 /* -------------------------------------------------------------- */
642
643 /**
644 * Show some text and linkage on successful upload.
645 * @access private
646 */
647 function showSuccess() {
648 global $wgUser, $wgOut, $wgContLang;
649
650 $sk = $wgUser->getSkin();
651 $ilink = $sk->makeMediaLink( $this->mUploadSaveName, Image::imageUrl( $this->mUploadSaveName ) );
652 $dname = $wgContLang->getNsText( NS_IMAGE ) . ':'.$this->mUploadSaveName;
653 $dlink = $sk->makeKnownLink( $dname, $dname );
654
655 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'successfulupload' ) . "</h2>\n" );
656 $text = wfMsgWikiHtml( 'fileuploaded', $ilink, $dlink );
657 $wgOut->addHTML( $text );
658 $wgOut->returnToMain( false );
659 }
660
661 /**
662 * @param string $error as HTML
663 * @access private
664 */
665 function uploadError( $error ) {
666 global $wgOut;
667 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
668 $wgOut->addHTML( "<span class='error'>{$error}</span>\n" );
669 }
670
671 /**
672 * There's something wrong with this file, not enough to reject it
673 * totally but we require manual intervention to save it for real.
674 * Stash it away, then present a form asking to confirm or cancel.
675 *
676 * @param string $warning as HTML
677 * @access private
678 */
679 function uploadWarning( $warning ) {
680 global $wgOut;
681 global $wgUseCopyrightUpload;
682
683 $this->mSessionKey = $this->stashSession();
684 if( !$this->mSessionKey ) {
685 # Couldn't save file; an error has been displayed so let's go.
686 return;
687 }
688
689 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
690 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
691
692 $save = wfMsgHtml( 'savefile' );
693 $reupload = wfMsgHtml( 'reupload' );
694 $iw = wfMsgWikiHtml( 'ignorewarning' );
695 $reup = wfMsgWikiHtml( 'reuploaddesc' );
696 $titleObj = SpecialPage::getTitleFor( 'Upload' );
697 $action = $titleObj->escapeLocalURL( 'action=submit' );
698
699 if ( $wgUseCopyrightUpload )
700 {
701 $copyright = "
702 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mUploadCopyStatus ) . "\" />
703 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mUploadSource ) . "\" />
704 ";
705 } else {
706 $copyright = "";
707 }
708
709 $wgOut->addHTML( "
710 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
711 <input type='hidden' name='wpIgnoreWarning' value='1' />
712 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey ) . "\" />
713 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mUploadDescription ) . "\" />
714 <input type='hidden' name='wpLicense' value=\"" . htmlspecialchars( $this->mLicense ) . "\" />
715 <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDestFile ) . "\" />
716 <input type='hidden' name='wpWatchthis' value=\"" . htmlspecialchars( intval( $this->mWatchthis ) ) . "\" />
717 {$copyright}
718 <table border='0'>
719 <tr>
720 <tr>
721 <td align='right'>
722 <input tabindex='2' type='submit' name='wpUpload' value=\"$save\" />
723 </td>
724 <td align='left'>$iw</td>
725 </tr>
726 <tr>
727 <td align='right'>
728 <input tabindex='2' type='submit' name='wpReUpload' value=\"{$reupload}\" />
729 </td>
730 <td align='left'>$reup</td>
731 </tr>
732 </tr>
733 </table></form>\n" );
734 }
735
736 /**
737 * Displays the main upload form, optionally with a highlighted
738 * error message up at the top.
739 *
740 * @param string $msg as HTML
741 * @access private
742 */
743 function mainUploadForm( $msg='' ) {
744 global $wgOut, $wgUser;
745 global $wgUseCopyrightUpload;
746 global $wgRequest, $wgAllowCopyUploads;
747
748 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) )
749 {
750 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
751 return false;
752 }
753
754 $cols = intval($wgUser->getOption( 'cols' ));
755 $ew = $wgUser->getOption( 'editwidth' );
756 if ( $ew ) $ew = " style=\"width:100%\"";
757 else $ew = '';
758
759 if ( '' != $msg ) {
760 $sub = wfMsgHtml( 'uploaderror' );
761 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
762 "<span class='error'>{$msg}</span>\n" );
763 }
764 $wgOut->addHTML( '<div id="uploadtext">' );
765 $wgOut->addWikiText( wfMsgNoTrans( 'uploadtext', $this->mDestFile ) );
766 $wgOut->addHTML( '</div>' );
767
768 $sourcefilename = wfMsgHtml( 'sourcefilename' );
769 $destfilename = wfMsgHtml( 'destfilename' );
770 $summary = wfMsgWikiHtml( 'fileuploadsummary' );
771
772 $licenses = new Licenses();
773 $license = wfMsgHtml( 'license' );
774 $nolicense = wfMsgHtml( 'nolicense' );
775 $licenseshtml = $licenses->getHtml();
776
777 $ulb = wfMsgHtml( 'uploadbtn' );
778
779
780 $titleObj = SpecialPage::getTitleFor( 'Upload' );
781 $action = $titleObj->escapeLocalURL();
782
783 $encDestFile = htmlspecialchars( $this->mDestFile );
784
785 $watchChecked =
786 ( $wgUser->getOption( 'watchdefault' ) ||
787 ( $wgUser->getOption( 'watchcreations' ) && $this->mDestFile == '' ) )
788 ? 'checked="checked"'
789 : '';
790
791 // Prepare form for upload or upload/copy
792 if( $wgAllowCopyUploads && $wgUser->isAllowed( 'upload_by_url' ) ) {
793 $filename_form =
794 "<input type='radio' id='wpSourceTypeFile' name='wpSourceType' value='file' onchange='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\")' checked />" .
795 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' onfocus='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\");toggle_element_check(\"wpSourceTypeFile\",\"wpSourceTypeURL\")'" .
796 ($this->mDestFile?"":"onchange='fillDestFilename(\"wpUploadFile\")' ") . "size='40' />" .
797 wfMsgHTML( 'upload_source_file' ) . "<br/>" .
798 "<input type='radio' id='wpSourceTypeURL' name='wpSourceType' value='web' onchange='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\")' />" .
799 "<input tabindex='1' type='text' name='wpUploadFileURL' id='wpUploadFileURL' onfocus='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\");toggle_element_check(\"wpSourceTypeURL\",\"wpSourceTypeFile\")'" .
800 ($this->mDestFile?"":"onchange='fillDestFilename(\"wpUploadFileURL\")' ") . "size='40' DISABLED />" .
801 wfMsgHtml( 'upload_source_url' ) ;
802 } else {
803 $filename_form =
804 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
805 ($this->mDestFile?"":"onchange='fillDestFilename(\"wpUploadFile\")' ") .
806 "size='40' />" .
807 "<input type='hidden' name='wpSourceType' value='file' />" ;
808 }
809
810 $wgOut->addHTML( "
811 <form id='upload' method='post' enctype='multipart/form-data' action=\"$action\">
812 <table border='0'>
813 <tr>
814 {$this->uploadFormTextTop}
815 <td align='right' valign='top'><label for='wpUploadFile'>{$sourcefilename}:</label></td>
816 <td align='left'>
817 {$filename_form}
818 </td>
819 </tr>
820 <tr>
821 <td align='right'><label for='wpDestFile'>{$destfilename}:</label></td>
822 <td align='left'>
823 <input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='40' value=\"$encDestFile\" />
824 </td>
825 </tr>
826 <tr>
827 <td align='right'><label for='wpUploadDescription'>{$summary}</label></td>
828 <td align='left'>
829 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6' cols='{$cols}'{$ew}>" . htmlspecialchars( $this->mUploadDescription ) . "</textarea>
830 {$this->uploadFormTextAfterSummary}
831 </td>
832 </tr>
833 <tr>" );
834
835 if ( $licenseshtml != '' ) {
836 global $wgStylePath;
837 $wgOut->addHTML( "
838 <td align='right'><label for='wpLicense'>$license:</label></td>
839 <td align='left'>
840 <script type='text/javascript' src=\"$wgStylePath/common/upload.js\"></script>
841 <select name='wpLicense' id='wpLicense' tabindex='4'
842 onchange='licenseSelectorCheck()'>
843 <option value=''>$nolicense</option>
844 $licenseshtml
845 </select>
846 </td>
847 </tr>
848 <tr>
849 ");
850 }
851
852 if ( $wgUseCopyrightUpload ) {
853 $filestatus = wfMsgHtml ( 'filestatus' );
854 $copystatus = htmlspecialchars( $this->mUploadCopyStatus );
855 $filesource = wfMsgHtml ( 'filesource' );
856 $uploadsource = htmlspecialchars( $this->mUploadSource );
857
858 $wgOut->addHTML( "
859 <td align='right' nowrap='nowrap'><label for='wpUploadCopyStatus'>$filestatus:</label></td>
860 <td><input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus' value=\"$copystatus\" size='40' /></td>
861 </tr>
862 <tr>
863 <td align='right'><label for='wpUploadCopyStatus'>$filesource:</label></td>
864 <td><input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus' value=\"$uploadsource\" size='40' /></td>
865 </tr>
866 <tr>
867 ");
868 }
869
870
871 $wgOut->addHtml( "
872 <td></td>
873 <td>
874 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
875 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthisupload' ) . "</label>
876 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' />
877 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
878 </td>
879 </tr>
880 <tr>
881 <td></td>
882 <td align='left'><input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\" /></td>
883 </tr>
884
885 <tr>
886 <td></td>
887 <td align='left'>
888 " );
889 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
890 $wgOut->addHTML( "
891 </td>
892 </tr>
893
894 </table>
895 </form>" );
896 }
897
898 /* -------------------------------------------------------------- */
899
900 /**
901 * Split a file into a base name and all dot-delimited 'extensions'
902 * on the end. Some web server configurations will fall back to
903 * earlier pseudo-'extensions' to determine type and execute
904 * scripts, so the blacklist needs to check them all.
905 *
906 * @return array
907 */
908 function splitExtensions( $filename ) {
909 $bits = explode( '.', $filename );
910 $basename = array_shift( $bits );
911 return array( $basename, $bits );
912 }
913
914 /**
915 * Perform case-insensitive match against a list of file extensions.
916 * Returns true if the extension is in the list.
917 *
918 * @param string $ext
919 * @param array $list
920 * @return bool
921 */
922 function checkFileExtension( $ext, $list ) {
923 return in_array( strtolower( $ext ), $list );
924 }
925
926 /**
927 * Perform case-insensitive match against a list of file extensions.
928 * Returns true if any of the extensions are in the list.
929 *
930 * @param array $ext
931 * @param array $list
932 * @return bool
933 */
934 function checkFileExtensionList( $ext, $list ) {
935 foreach( $ext as $e ) {
936 if( in_array( strtolower( $e ), $list ) ) {
937 return true;
938 }
939 }
940 return false;
941 }
942
943 /**
944 * Verifies that it's ok to include the uploaded file
945 *
946 * @param string $tmpfile the full path of the temporary file to verify
947 * @param string $extension The filename extension that the file is to be served with
948 * @return mixed true of the file is verified, a WikiError object otherwise.
949 */
950 function verify( $tmpfile, $extension ) {
951 #magically determine mime type
952 $magic=& MimeMagic::singleton();
953 $mime= $magic->guessMimeType($tmpfile,false);
954
955 $fname= "SpecialUpload::verify";
956
957 #check mime type, if desired
958 global $wgVerifyMimeType;
959 if ($wgVerifyMimeType) {
960
961 #check mime type against file extension
962 if( !$this->verifyExtension( $mime, $extension ) ) {
963 return new WikiErrorMsg( 'uploadcorrupt' );
964 }
965
966 #check mime type blacklist
967 global $wgMimeTypeBlacklist;
968 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
969 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
970 return new WikiErrorMsg( 'filetype-badmime', htmlspecialchars( $mime ) );
971 }
972 }
973
974 #check for htmlish code and javascript
975 if( $this->detectScript ( $tmpfile, $mime, $extension ) ) {
976 return new WikiErrorMsg( 'uploadscripted' );
977 }
978
979 /**
980 * Scan the uploaded file for viruses
981 */
982 $virus= $this->detectVirus($tmpfile);
983 if ( $virus ) {
984 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
985 }
986
987 wfDebug( "$fname: all clear; passing.\n" );
988 return true;
989 }
990
991 /**
992 * Checks if the mime type of the uploaded file matches the file extension.
993 *
994 * @param string $mime the mime type of the uploaded file
995 * @param string $extension The filename extension that the file is to be served with
996 * @return bool
997 */
998 function verifyExtension( $mime, $extension ) {
999 $fname = 'SpecialUpload::verifyExtension';
1000
1001 $magic =& MimeMagic::singleton();
1002
1003 if ( ! $mime || $mime == 'unknown' || $mime == 'unknown/unknown' )
1004 if ( ! $magic->isRecognizableExtension( $extension ) ) {
1005 wfDebug( "$fname: passing file with unknown detected mime type; unrecognized extension '$extension', can't verify\n" );
1006 return true;
1007 } else {
1008 wfDebug( "$fname: rejecting file with unknown detected mime type; recognized extension '$extension', so probably invalid file\n" );
1009 return false;
1010 }
1011
1012 $match= $magic->isMatchingExtension($extension,$mime);
1013
1014 if ($match===NULL) {
1015 wfDebug( "$fname: no file extension known for mime type $mime, passing file\n" );
1016 return true;
1017 } elseif ($match===true) {
1018 wfDebug( "$fname: mime type $mime matches extension $extension, passing file\n" );
1019
1020 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
1021 return true;
1022
1023 } else {
1024 wfDebug( "$fname: mime type $mime mismatches file extension $extension, rejecting file\n" );
1025 return false;
1026 }
1027 }
1028
1029 /** Heuristig for detecting files that *could* contain JavaScript instructions or
1030 * things that may look like HTML to a browser and are thus
1031 * potentially harmful. The present implementation will produce false positives in some situations.
1032 *
1033 * @param string $file Pathname to the temporary upload file
1034 * @param string $mime The mime type of the file
1035 * @param string $extension The extension of the file
1036 * @return bool true if the file contains something looking like embedded scripts
1037 */
1038 function detectScript($file, $mime, $extension) {
1039 global $wgAllowTitlesInSVG;
1040
1041 #ugly hack: for text files, always look at the entire file.
1042 #For binarie field, just check the first K.
1043
1044 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
1045 else {
1046 $fp = fopen( $file, 'rb' );
1047 $chunk = fread( $fp, 1024 );
1048 fclose( $fp );
1049 }
1050
1051 $chunk= strtolower( $chunk );
1052
1053 if (!$chunk) return false;
1054
1055 #decode from UTF-16 if needed (could be used for obfuscation).
1056 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
1057 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
1058 else $enc= NULL;
1059
1060 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
1061
1062 $chunk= trim($chunk);
1063
1064 #FIXME: convert from UTF-16 if necessarry!
1065
1066 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
1067
1068 #check for HTML doctype
1069 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
1070
1071 /**
1072 * Internet Explorer for Windows performs some really stupid file type
1073 * autodetection which can cause it to interpret valid image files as HTML
1074 * and potentially execute JavaScript, creating a cross-site scripting
1075 * attack vectors.
1076 *
1077 * Apple's Safari browser also performs some unsafe file type autodetection
1078 * which can cause legitimate files to be interpreted as HTML if the
1079 * web server is not correctly configured to send the right content-type
1080 * (or if you're really uploading plain text and octet streams!)
1081 *
1082 * Returns true if IE is likely to mistake the given file for HTML.
1083 * Also returns true if Safari would mistake the given file for HTML
1084 * when served with a generic content-type.
1085 */
1086
1087 $tags = array(
1088 '<body',
1089 '<head',
1090 '<html', #also in safari
1091 '<img',
1092 '<pre',
1093 '<script', #also in safari
1094 '<table'
1095 );
1096 if( ! $wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1097 $tags[] = '<title';
1098 }
1099
1100 foreach( $tags as $tag ) {
1101 if( false !== strpos( $chunk, $tag ) ) {
1102 return true;
1103 }
1104 }
1105
1106 /*
1107 * look for javascript
1108 */
1109
1110 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1111 $chunk = Sanitizer::decodeCharReferences( $chunk );
1112
1113 #look for script-types
1114 if (preg_match('!type\s*=\s*[\'"]?\s*(\w*/)?(ecma|java)!sim',$chunk)) return true;
1115
1116 #look for html-style script-urls
1117 if (preg_match('!(href|src|data)\s*=\s*[\'"]?\s*(ecma|java)script:!sim',$chunk)) return true;
1118
1119 #look for css-style script-urls
1120 if (preg_match('!url\s*\(\s*[\'"]?\s*(ecma|java)script:!sim',$chunk)) return true;
1121
1122 wfDebug("SpecialUpload::detectScript: no scripts found\n");
1123 return false;
1124 }
1125
1126 /** Generic wrapper function for a virus scanner program.
1127 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1128 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1129 *
1130 * @param string $file Pathname to the temporary upload file
1131 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1132 * or a string containing feedback from the virus scanner if a virus was found.
1133 * If textual feedback is missing but a virus was found, this function returns true.
1134 */
1135 function detectVirus($file) {
1136 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1137
1138 $fname= "SpecialUpload::detectVirus";
1139
1140 if (!$wgAntivirus) { #disabled?
1141 wfDebug("$fname: virus scanner disabled\n");
1142
1143 return NULL;
1144 }
1145
1146 if (!$wgAntivirusSetup[$wgAntivirus]) {
1147 wfDebug("$fname: unknown virus scanner: $wgAntivirus\n");
1148
1149 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" ); #LOCALIZE
1150
1151 return "unknown antivirus: $wgAntivirus";
1152 }
1153
1154 #look up scanner configuration
1155 $virus_scanner= $wgAntivirusSetup[$wgAntivirus]["command"]; #command pattern
1156 $virus_scanner_codes= $wgAntivirusSetup[$wgAntivirus]["codemap"]; #exit-code map
1157 $msg_pattern= $wgAntivirusSetup[$wgAntivirus]["messagepattern"]; #message pattern
1158
1159 $scanner= $virus_scanner; #copy, so we can resolve the pattern
1160
1161 if (strpos($scanner,"%f")===false) $scanner.= " ".wfEscapeShellArg($file); #simple pattern: append file to scan
1162 else $scanner= str_replace("%f",wfEscapeShellArg($file),$scanner); #complex pattern: replace "%f" with file to scan
1163
1164 wfDebug("$fname: running virus scan: $scanner \n");
1165
1166 #execute virus scanner
1167 $code= false;
1168
1169 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1170 # that does not seem to be worth the pain.
1171 # Ask me (Duesentrieb) about it if it's ever needed.
1172 $output = array();
1173 if (wfIsWindows()) exec("$scanner",$output,$code);
1174 else exec("$scanner 2>&1",$output,$code);
1175
1176 $exit_code= $code; #remember for user feedback
1177
1178 if ($virus_scanner_codes) { #map exit code to AV_xxx constants.
1179 if (isset($virus_scanner_codes[$code])) {
1180 $code= $virus_scanner_codes[$code]; # explicit mapping
1181 } else if (isset($virus_scanner_codes["*"])) {
1182 $code= $virus_scanner_codes["*"]; # fallback mapping
1183 }
1184 }
1185
1186 if ($code===AV_SCAN_FAILED) { #scan failed (code was mapped to false by $virus_scanner_codes)
1187 wfDebug("$fname: failed to scan $file (code $exit_code).\n");
1188
1189 if ($wgAntivirusRequired) { return "scan failed (code $exit_code)"; }
1190 else { return NULL; }
1191 }
1192 else if ($code===AV_SCAN_ABORTED) { #scan failed because filetype is unknown (probably imune)
1193 wfDebug("$fname: unsupported file type $file (code $exit_code).\n");
1194 return NULL;
1195 }
1196 else if ($code===AV_NO_VIRUS) {
1197 wfDebug("$fname: file passed virus scan.\n");
1198 return false; #no virus found
1199 }
1200 else {
1201 $output= join("\n",$output);
1202 $output= trim($output);
1203
1204 if (!$output) $output= true; #if there's no output, return true
1205 else if ($msg_pattern) {
1206 $groups= array();
1207 if (preg_match($msg_pattern,$output,$groups)) {
1208 if ($groups[1]) $output= $groups[1];
1209 }
1210 }
1211
1212 wfDebug("$fname: FOUND VIRUS! scanner feedback: $output");
1213 return $output;
1214 }
1215 }
1216
1217 /**
1218 * Check if the temporary file is MacBinary-encoded, as some uploads
1219 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
1220 * If so, the data fork will be extracted to a second temporary file,
1221 * which will then be checked for validity and either kept or discarded.
1222 *
1223 * @access private
1224 */
1225 function checkMacBinary() {
1226 $macbin = new MacBinary( $this->mUploadTempName );
1227 if( $macbin->isValid() ) {
1228 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
1229 $dataHandle = fopen( $dataFile, 'wb' );
1230
1231 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
1232 $macbin->extractData( $dataHandle );
1233
1234 $this->mUploadTempName = $dataFile;
1235 $this->mUploadSize = $macbin->dataForkLength();
1236
1237 // We'll have to manually remove the new file if it's not kept.
1238 $this->mRemoveTempFile = true;
1239 }
1240 $macbin->close();
1241 }
1242
1243 /**
1244 * If we've modified the upload file we need to manually remove it
1245 * on exit to clean up.
1246 * @access private
1247 */
1248 function cleanupTempFile() {
1249 if( $this->mRemoveTempFile && file_exists( $this->mUploadTempName ) ) {
1250 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file $this->mUploadTempName\n" );
1251 unlink( $this->mUploadTempName );
1252 }
1253 }
1254
1255 /**
1256 * Check if there's an overwrite conflict and, if so, if restrictions
1257 * forbid this user from performing the upload.
1258 *
1259 * @return mixed true on success, WikiError on failure
1260 * @access private
1261 */
1262 function checkOverwrite( $name ) {
1263 $img = Image::newFromName( $name );
1264 if( is_null( $img ) ) {
1265 // Uh... this shouldn't happen ;)
1266 // But if it does, fall through to previous behavior
1267 return false;
1268 }
1269
1270 $error = '';
1271 if( $img->exists() ) {
1272 global $wgUser, $wgOut;
1273 if( $img->isLocal() ) {
1274 if( !$wgUser->isAllowed( 'reupload' ) ) {
1275 $error = 'fileexists-forbidden';
1276 }
1277 } else {
1278 if( !$wgUser->isAllowed( 'reupload' ) ||
1279 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1280 $error = "fileexists-shared-forbidden";
1281 }
1282 }
1283 }
1284
1285 if( $error ) {
1286 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1287 return new WikiError( $wgOut->parse( $errorText ) );
1288 }
1289
1290 // Rockin', go ahead and upload
1291 return true;
1292 }
1293
1294 }
1295 ?>