(bug 548) A spot of refactoring, for legibility and better handling of 'warning'...
[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 /**
14 * Entry point
15 */
16 function wfSpecialUpload() {
17 global $wgRequest;
18 $form = new UploadForm( $wgRequest );
19 $form->execute();
20 }
21
22 /**
23 *
24 * @package MediaWiki
25 * @subpackage SpecialPage
26 */
27 class UploadForm {
28 /**#@+
29 * @access private
30 */
31 var $mUploadAffirm, $mUploadFile, $mUploadDescription, $mIgnoreWarning;
32 var $mUploadSaveName, $mUploadTempName, $mUploadSize, $mUploadOldVersion;
33 var $mUploadCopyStatus, $mUploadSource, $mReUpload, $mAction, $mUpload;
34 var $mOname, $mSessionKey;
35 /**#@- */
36
37 /**
38 * Constructor : initialise object
39 * Get data POSTed through the form and assign them to the object
40 * @param $request Data posted.
41 */
42 function UploadForm( &$request ) {
43 if( !$request->wasPosted() ) {
44 # GET requests just give the main form; no data.
45 return;
46 }
47
48 $this->mUploadAffirm = $request->getCheck( 'wpUploadAffirm' );
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->mUploadCopyStatus = $request->getText( 'wpUploadCopyStatus' );
55 $this->mUploadSource = $request->getText( 'wpUploadSource');
56
57 $this->mAction = $request->getVal( 'action' );
58
59 $this->mSessionKey = $request->getInt( 'wpSessionKey' );
60 if( !empty( $this->mSessionKey ) &&
61 isset( $_SESSION['wsUploadData'][$this->mSessionKey] ) ) {
62 /**
63 * Confirming a temporarily stashed upload.
64 * We don't want path names to be forged, so we keep
65 * them in the session on the server and just give
66 * an opaque key to the user agent.
67 */
68 $data = $_SESSION['wsUploadData'][$this->mSessionKey];
69 $this->mUploadTempName = $data['mUploadTempName'];
70 $this->mUploadSize = $data['mUploadSize'];
71 $this->mOname = $data['mOname'];
72 } else {
73 /**
74 *Check for a newly uploaded file.
75 */
76 $this->mUploadTempName = $request->getFileTempName( 'wpUploadFile' );
77 $this->mUploadSize = $request->getFileSize( 'wpUploadFile' );
78 $this->mOname = $request->getFileName( 'wpUploadFile' );
79 $this->mSessionKey = false;
80 }
81 }
82
83 /**
84 * Start doing stuff
85 * @access public
86 */
87 function execute() {
88 global $wgUser, $wgOut;
89 global $wgDisableUploads;
90
91 /** Show an error message if file upload is disabled */
92 if( $wgDisableUploads ) {
93 $wgOut->addWikiText( wfMsg( 'uploaddisabled' ) );
94 return;
95 }
96
97 /** Various rights checks */
98 if( ( $wgUser->getID() == 0 )
99 OR $wgUser->isBlocked() ) {
100 $wgOut->errorpage( 'uploadnologin', 'uploadnologintext' );
101 return;
102 }
103 if( wfReadOnly() ) {
104 $wgOut->readOnlyPage();
105 return;
106 }
107
108 if( $this->mReUpload ) {
109 $this->unsaveUploadedFile();
110 $this->mainUploadForm();
111 } else if ( 'submit' == $this->mAction || $this->mUpload ) {
112 $this->processUpload();
113 } else {
114 $this->mainUploadForm();
115 }
116 }
117
118 /* -------------------------------------------------------------- */
119
120 /**
121 * Really do the upload
122 * Checks are made in SpecialUpload::execute()
123 * @access private
124 */
125 function processUpload() {
126 global $wgUser, $wgOut, $wgLang, $wgContLang;
127 global $wgUploadDirectory;
128 global $wgUseCopyrightUpload, $wgCheckCopyrightUpload;
129
130 /**
131 * When using detailed copyright, if user filled field, assume he
132 * confirmed the upload
133 */
134 if ( $wgUseCopyrightUpload ) {
135 $this->mUploadAffirm = true;
136 if( $wgCheckCopyrightUpload &&
137 ( trim( $this->mUploadCopyStatus ) == '' ||
138 trim( $this->mUploadSource ) == '' ) ) {
139 $this->mUploadAffirm = false;
140 }
141 }
142
143 /** User need to confirm his upload */
144 if( !$this->mUploadAffirm ) {
145 $this->mainUploadForm( WfMsg( 'noaffirmation' ) );
146 return;
147 }
148
149 if ( $this->mOname == '' && !isset($this->mUploadSaveName) ) {
150 // no filename given!
151 return $this->uploadError('<li>'.wfMsg( 'emptyfile' ).'</li>');
152 }
153
154 # Chop off any directories in the given filename
155 $basename = basename( $this->mOname );
156
157 if( preg_match( '/^(.*)\.([^.]*)$/', $basename, $matches ) ) {
158 $partname = $matches[1];
159 $ext = $matches[2];
160 } else {
161 $partname = $basename;
162 $ext = '';
163 }
164
165 if ( strlen( $partname ) < 3 ) {
166 $this->mainUploadForm( wfMsg( 'minlength' ) );
167 return;
168 }
169
170 /**
171 * Filter out illegal characters, and try to make a legible name
172 * out of it. We'll strip some silently that Title would die on.
173 */
174 $filtered = preg_replace ( "/[^".Title::legalChars()."]/", '-', $basename );
175 $nt = Title::newFromText( $filtered );
176 if( is_null( $nt ) ) {
177 return $this->uploadError( wfMsg( 'illegalfilename', htmlspecialchars( $filtered ) ) );
178 }
179 $nt->setNamespace( NS_IMAGE );
180 $this->mUploadSaveName = $nt->getDBkey();
181
182 /**
183 * If the image is protected, non-sysop users won't be able
184 * to modify it by uploading a new revision.
185 */
186 if( !$nt->userCanEdit() ) {
187 return $this->uploadError( wfMsg( 'protectedpage' ) );
188 }
189
190 /* Don't allow users to override the blacklist */
191 global $wgStrictFileExtensions;
192 global $wgFileExtensions, $wgFileBlacklist;
193 if( $this->checkFileExtension( $ext, $wgFileBlacklist ) ||
194 ($wgStrictFileExtensions && !$this->checkFileExtension( $ext, $wgFileExtensions ) ) ) {
195 return $this->uploadError( wfMsg( 'badfiletype', htmlspecialchars( $ext ) ) );
196 }
197
198 /**
199 * Look at the contents of the file; if we can recognize the
200 * type but it's corrupt or data of the wrong type, we should
201 * probably not accept it.
202 */
203 if( !$this->verify( $this->mUploadTempName, $ext ) ) {
204 return $this->uploadError( wfMsg( 'uploadcorrupt' ) );
205 }
206
207 /**
208 * Check for non-fatal conditions
209 */
210 if ( ! $this->mIgnoreWarning ) {
211 $warning = '';
212 if( $this->mUploadSaveName != ucfirst( $filtered ) ) {
213 $warning .= '<li>'.wfMsg( 'badfilename', htmlspecialchars( $this->mUploadSaveName ) ).'</li>';
214 }
215
216 global $wgCheckFileExtensions;
217 if ( $wgCheckFileExtensions ) {
218 if ( ! $this->checkFileExtension( $ext, $wgFileExtensions ) ) {
219 $warning .= '<li>'.wfMsg( 'badfiletype', htmlspecialchars( $ext ) ).'</li>';
220 }
221 }
222
223 global $wgUploadSizeWarning;
224 if ( $wgUploadSizeWarning && ( $this->mUploadSize > $wgUploadSizeWarning ) ) {
225 $warning .= '<li>'.wfMsg( 'largefile' ).'</li>';
226 }
227 if ( $this->mUploadSize == 0 ) {
228 $warning .= '<li>'.wfMsg( 'emptyfile' ).'</li>';
229 }
230
231 if( $nt->getArticleID() ) {
232 global $wgUser;
233 $sk = $wgUser->getSkin();
234 $dlink = $sk->makeKnownLinkObj( $nt );
235 $warning .= '<li>'.wfMsg( 'fileexists', $dlink ).'</li>';
236 }
237
238 if( $warning != '' ) {
239 /**
240 * Stash the file in a temporary location; the user can choose
241 * to let it through and we'll complete the upload then.
242 */
243 return $this->uploadWarning($warning);
244 }
245 }
246
247 /**
248 * Try actually saving the thing...
249 * It will show an error form on failure.
250 */
251 if( $this->saveUploadedFile( $this->mUploadSaveName,
252 $this->mUploadTempName,
253 !empty( $this->mSessionKey ) ) ) {
254 /**
255 * Update the upload log and create the description page
256 * if it's a new file.
257 */
258 wfRecordUpload( $this->mUploadSaveName,
259 $this->mUploadOldVersion,
260 $this->mUploadSize,
261 $this->mUploadDescription,
262 $this->mUploadCopyStatus,
263 $this->mUploadSource );
264 $this->showSuccess();
265 }
266 }
267
268 /**
269 * Move the uploaded file from its temporary location to the final
270 * destination. If a previous version of the file exists, move
271 * it into the archive subdirectory.
272 *
273 * @todo If the later save fails, we may have disappeared the original file.
274 *
275 * @param string $saveName
276 * @param string $tempName full path to the temporary file
277 * @param bool $useRename if true, doesn't check that the source file
278 * is a PHP-managed upload temporary
279 */
280 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
281 global $wgUploadDirectory, $wgOut;
282
283 $dest = wfImageDir( $saveName );
284 $archive = wfImageArchiveDir( $saveName );
285 $this->mSavedFile = "{$dest}/{$saveName}";
286
287 if( is_file( $this->mSavedFile ) ) {
288 $this->mUploadOldVersion = gmdate( 'YmdHis' ) . "!{$saveName}";
289
290 if( !rename( $this->mSavedFile, "${archive}/{$this->mUploadOldVersion}" ) ) {
291 $wgOut->fileRenameError( $this->mSavedFile,
292 "${archive}/{$this->mUploadOldVersion}" );
293 return false;
294 }
295 } else {
296 $this->mUploadOldVersion = '';
297 }
298
299 if( $useRename ) {
300 if( !rename( $tempName, $this->mSavedFile ) ) {
301 $wgOut->fileCopyError( $tempName, $this->mSavedFile );
302 return false;
303 }
304 } else {
305 if( !move_uploaded_file( $tempName, $this->mSavedFile ) ) {
306 $wgOut->fileCopyError( $tempName, $this->mSavedFile );
307 return false;
308 }
309 }
310 chmod( $this->mSavedFile, 0644 );
311 return true;
312 }
313
314 /**
315 * Stash a file in a temporary directory for later processing
316 * after the user has confirmed it.
317 *
318 * If the user doesn't explicitly cancel or accept, these files
319 * can accumulate in the temp directory.
320 *
321 * @param string $saveName - the destination filename
322 * @param string $tempName - the source temporary file to save
323 * @return string - full path the stashed file, or false on failure
324 * @access private
325 */
326 function saveTempUploadedFile( $saveName, $tempName ) {
327 global $wgOut;
328
329 $archive = wfImageArchiveDir( $saveName, 'temp' );
330 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
331
332 if ( !move_uploaded_file( $tempName, $stash ) ) {
333 $wgOut->fileCopyError( $tempName, $stash );
334 return false;
335 }
336
337 return $stash;
338 }
339
340 /**
341 * Stash a file in a temporary directory for later processing,
342 * and save the necessary descriptive info into the session.
343 * Returns a key value which will be passed through a form
344 * to pick up the path info on a later invocation.
345 *
346 * @return int
347 * @access private
348 */
349 function stashSession() {
350 $stash = $this->saveTempUploadedFile(
351 $this->mUploadSaveName, $this->mUploadTempName );
352
353 if( !$stash ) {
354 # Couldn't save the file.
355 return false;
356 }
357
358 $key = mt_rand( 0, 0x7fffffff );
359 $_SESSION['wsUploadData'][$key] = array(
360 'mUploadTempName' => $stash,
361 'mUploadSize' => $this->mUploadSize,
362 'mOname' => $this->mOname );
363 return $key;
364 }
365
366 /**
367 * Remove a temporarily kept file stashed by saveTempUploadedFile().
368 * @access private
369 */
370 function unsaveUploadedFile() {
371 if ( ! @unlink( $this->mUploadTempName ) ) {
372 $wgOut->fileDeleteError( $this->mUploadTempName );
373 }
374 }
375
376 /* -------------------------------------------------------------- */
377
378 /**
379 * Show some text and linkage on successful upload.
380 * @access private
381 */
382 function showSuccess() {
383 global $wgUser, $wgOut, $wgContLang;
384
385 $sk = $wgUser->getSkin();
386 $ilink = $sk->makeMediaLink( $this->mUploadSaveName, Image::wfImageUrl( $this->mUploadSaveName ) );
387 $dname = $wgContLang->getNsText( Namespace::getImage() ) . ':'.$this->mUploadSaveName;
388 $dlink = $sk->makeKnownLink( $dname, $dname );
389
390 $wgOut->addHTML( '<h2>' . wfMsg( 'successfulupload' ) . "</h2>\n" );
391 $text = wfMsg( 'fileuploaded', $ilink, $dlink );
392 $wgOut->addHTML( '<p>'.$text."\n" );
393 $wgOut->returnToMain( false );
394 }
395
396 /**
397 * @param string $error as HTML
398 * @access private
399 */
400 function uploadError( $error ) {
401 global $wgOut;
402 $sub = wfMsg( 'uploadwarning' );
403 $wgOut->addHTML( "<h2>{$sub}</h2>\n" );
404 $wgOut->addHTML( "<h4 style='error'>{$error}</h4>\n" );
405 }
406
407 /**
408 * There's something wrong with this file, not enough to reject it
409 * totally but we require manual intervention to save it for real.
410 * Stash it away, then present a form asking to confirm or cancel.
411 *
412 * @param string $warning as HTML
413 * @access private
414 */
415 function uploadWarning( $warning ) {
416 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
417 global $wgUseCopyrightUpload;
418
419 $this->mSessionKey = $this->stashSession();
420 if( !$this->mSessionKey ) {
421 # Couldn't save file; an error has been displayed so let's go.
422 return;
423 }
424
425 $sub = wfMsg( 'uploadwarning' );
426 $wgOut->addHTML( "<h2>{$sub}</h2>\n" );
427 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br/>\n" );
428
429 $save = wfMsg( 'savefile' );
430 $reupload = wfMsg( 'reupload' );
431 $iw = wfMsg( 'ignorewarning' );
432 $reup = wfMsg( 'reuploaddesc' );
433 $titleObj = Title::makeTitle( NS_SPECIAL, 'Upload' );
434 $action = $titleObj->escapeLocalURL( 'action=submit' );
435
436 if ( $wgUseCopyrightUpload )
437 {
438 $copyright = "
439 <input type='hidden' name=\"wpUploadCopyStatus\" value=\"" . htmlspecialchars( $this->mUploadCopyStatus ) . "\" />
440 <input type='hidden' name=\"wpUploadSource\" value=\"" . htmlspecialchars( $this->mUploadSource ) . "\" />
441 ";
442 } else {
443 $copyright = "";
444 }
445
446 $wgOut->addHTML( "
447 <form id=\"uploadwarning\" method=\"post\" enctype=\"multipart/form-data\"
448 action=\"{$action}\">
449 <input type=hidden name=\"wpUploadAffirm\" value=\"1\" />
450 <input type=hidden name=\"wpIgnoreWarning\" value=\"1\" />
451 <input type=hidden name=\"wpSessionKey\" value=\"" . htmlspecialchars( $this->mSessionKey ) . "\" />
452 {$copyright}
453 <table border='0'><tr>
454 <tr><td align='right'>
455 <input tabindex='2' type='submit' name=\"wpUpload\" value=\"{$save}\" />
456 </td><td align='left'>{$iw}</td></tr>
457 <tr><td align='right'>
458 <input tabindex='2' type='submit' name=\"wpReUpload\" value=\"{$reupload}\" />
459 </td><td align='left'>{$reup}</td></tr></table></form>\n" );
460 }
461
462 /**
463 * Displays the main upload form, optionally with a highlighted
464 * error message up at the top.
465 *
466 * @param string $msg as HTML
467 * @access private
468 */
469 function mainUploadForm( $msg='' ) {
470 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
471 global $wgUseCopyrightUpload;
472
473 if ( '' != $msg ) {
474 $sub = wfMsg( 'uploaderror' );
475 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
476 "<h4 style='error'>{$msg}</h4>\n" );
477 } else {
478 $sub = wfMsg( 'uploadfile' );
479 $wgOut->addHTML( "<h2>{$sub}</h2>\n" );
480 }
481 $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
482 $sk = $wgUser->getSkin();
483
484 $fn = wfMsg( 'filename' );
485 $fd = wfMsg( 'filedesc' );
486 $ulb = wfMsg( 'uploadbtn' );
487
488 $clink = $sk->makeKnownLink( wfMsgForContent( 'copyrightpage' ),
489 wfMsg( 'copyrightpagename' ) );
490 $ca = wfMsg( 'affirmation', $clink );
491 $iw = wfMsg( 'ignorewarning' );
492
493 $titleObj = Title::makeTitle( NS_SPECIAL, 'Upload' );
494 $action = $titleObj->escapeLocalURL();
495
496 $source = "
497 <td align='right'>
498 <input tabindex='3' type='checkbox' name=\"wpUploadAffirm\" value=\"1\" id=\"wpUploadAffirm\" />
499 </td><td align='left'><label for=\"wpUploadAffirm\">{$ca}</label></td>
500 " ;
501 if ( $wgUseCopyrightUpload )
502 {
503 $source = "
504 <td align='right' nowrap='nowrap'>" . wfMsg ( 'filestatus' ) . ":</td>
505 <td><input tabindex='3' type='text' name=\"wpUploadCopyStatus\" value=\"" .
506 htmlspecialchars($this->mUploadCopyStatus). "\" size='40' /></td>
507 </tr><tr>
508 <td align='right'>". wfMsg ( 'filesource' ) . ":</td>
509 <td><input tabindex='4' type='text' name=\"wpUploadSource\" value=\"" .
510 htmlspecialchars($this->mUploadSource). "\" size='40' /></td>
511 " ;
512 }
513
514 $wgOut->addHTML( "
515 <form id=\"upload\" method=\"post\" enctype=\"multipart/form-data\"
516 action=\"{$action}\">
517 <table border='0'><tr>
518 <td align='right'>{$fn}:</td><td align='left'>
519 <input tabindex='1' type='file' name=\"wpUploadFile\" size='40' />
520 </td></tr><tr>
521 <td align='right'>{$fd}:</td><td align='left'>
522 <input tabindex='2' type='text' name=\"wpUploadDescription\" value=\""
523 . htmlspecialchars( $this->mUploadDescription ) . "\" size='40' />
524 </td></tr><tr>
525 {$source}
526 </tr>
527 <tr><td></td><td align='left'>
528 <input tabindex='5' type='submit' name=\"wpUpload\" value=\"{$ulb}\" />
529 </td></tr></table></form>\n" );
530 }
531
532 /* -------------------------------------------------------------- */
533
534 /**
535 * Perform case-insensitive match against a list of file extensions.
536 * Returns true if the extension is in the list.
537 *
538 * @param string $ext
539 * @param array $list
540 * @return bool
541 */
542 function checkFileExtension( $ext, $list ) {
543 return in_array( strtolower( $ext ), $list );
544 }
545
546 /**
547 * Returns false if the file is of a known type but can't be recognized,
548 * indicating a corrupt file.
549 * Returns true otherwise; unknown file types are not checked if given
550 * with an unrecognized extension.
551 *
552 * @param string $tmpfile Pathname to the temporary upload file
553 * @param string $extension The filename extension that the file is to be served with
554 * @return bool
555 */
556 function verify( $tmpfile, $extension ) {
557 if( $this->triggersIEbug( $tmpfile ) ) {
558 return false;
559 }
560
561 $fname = 'SpecialUpload::verify';
562 $mergeExtensions = array(
563 'jpg' => 'jpeg',
564 'tif' => 'tiff' );
565 $extensionTypes = array(
566 # See http://www.php.net/getimagesize
567 1 => 'gif',
568 2 => 'jpeg',
569 3 => 'png',
570 4 => 'swf',
571 5 => 'psd',
572 6 => 'bmp',
573 7 => 'tiff',
574 8 => 'tiff',
575 9 => 'jpc',
576 10 => 'jp2',
577 11 => 'jpx',
578 12 => 'jb2',
579 13 => 'swc',
580 14 => 'iff',
581 15 => 'wbmp',
582 16 => 'xbm' );
583
584 $extension = strtolower( $extension );
585 if( isset( $mergeExtensions[$extension] ) ) {
586 $extension = $mergeExtensions[$extension];
587 }
588 wfDebug( "$fname: Testing file '$tmpfile' with given extension '$extension'\n" );
589
590 if( !in_array( $extension, $extensionTypes ) ) {
591 # Not a recognized image type. We don't know how to verify these.
592 # They're allowed by policy or they wouldn't get this far, so we'll
593 # let them slide for now.
594 wfDebug( "$fname: Unknown extension; passing.\n" );
595 return true;
596 }
597
598 $data = @getimagesize( $tmpfile );
599 if( false === $data ) {
600 # Didn't recognize the image type.
601 # Either the image is corrupt or someone's slipping us some
602 # bogus data such as HTML+JavaScript trying to take advantage
603 # of an Internet Explorer security flaw.
604 wfDebug( "$fname: getimagesize() doesn't recognize the file; rejecting.\n" );
605 return false;
606 }
607
608 $imageType = $data[2];
609 if( !isset( $extensionTypes[$imageType] ) ) {
610 # Now we're kind of confused. Perhaps new image types added
611 # to PHP's support that we don't know about.
612 # We'll let these slide for now.
613 wfDebug( "$fname: getimagesize() knows the file, but we don't recognize the type; passing.\n" );
614 return true;
615 }
616
617 $ext = strtolower( $extension );
618 if( $extension != $extensionTypes[$imageType] ) {
619 # The given filename extension doesn't match the
620 # file type. Probably just a mistake, but it's a stupid
621 # one and we shouldn't let it pass. KILL THEM!
622 wfDebug( "$fname: file extension does not match recognized type; rejecting.\n" );
623 return false;
624 }
625
626 wfDebug( "$fname: all clear; passing.\n" );
627 return true;
628 }
629
630 /**
631 * Internet Explorer for Windows performs some really stupid file type
632 * autodetection which can cause it to interpret valid image files as HTML
633 * and potentially execute JavaScript, creating a cross-site scripting
634 * attack vectors.
635 *
636 * Returns true if IE is likely to mistake the given file for HTML.
637 *
638 * @param string $filename
639 * @return bool
640 */
641 function triggersIEbug( $filename ) {
642 $file = fopen( $filename, 'rb' );
643 $chunk = strtolower( fread( $file, 200 ) );
644 fclose( $file );
645
646 $tags = array( '<html', '<head', '<body', '<script' );
647 foreach( $tags as $tag ) {
648 if( false !== strpos( $chunk, $tag ) ) {
649 return true;
650 }
651 }
652 return false;
653 }
654 }
655 ?>