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