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