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