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