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