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