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