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