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