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