5 * @subpackage SpecialPage
11 require_once( 'Image.php' );
16 function wfSpecialUpload() {
18 $form = new UploadForm( $wgRequest );
25 * @subpackage SpecialPage
31 var $mUploadAffirm, $mUploadFile, $mUploadDescription, $mIgnoreWarning;
32 var $mUploadSaveName, $mUploadTempName, $mUploadSize, $mUploadOldVersion;
33 var $mUploadCopyStatus, $mUploadSource, $mReUpload, $mAction, $mUpload;
34 var $mOname, $mSessionKey, $mStashed;
38 * Constructor : initialise object
39 * Get data POSTed through the form and assign them to the object
40 * @param $request Data posted.
42 function UploadForm( &$request ) {
43 if( !$request->wasPosted() ) {
44 # GET requests just give the main form; no data.
48 $this->mUploadAffirm
= $request->getCheck( 'wpUploadAffirm' );
49 $this->mIgnoreWarning
= $request->getCheck( 'wpIgnoreWarning');
50 $this->mReUpload
= $request->getCheck( 'wpReUpload' );
51 $this->mUpload
= $request->getCheck( 'wpUpload' );
53 $this->mUploadDescription
= $request->getText( 'wpUploadDescription' );
54 $this->mUploadCopyStatus
= $request->getText( 'wpUploadCopyStatus' );
55 $this->mUploadSource
= $request->getText( 'wpUploadSource');
57 $this->mAction
= $request->getVal( 'action' );
59 $this->mSessionKey
= $request->getInt( 'wpSessionKey' );
60 if( !empty( $this->mSessionKey
) &&
61 isset( $_SESSION['wsUploadData'][$this->mSessionKey
] ) ) {
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.
68 $data = $_SESSION['wsUploadData'][$this->mSessionKey
];
69 $this->mUploadTempName
= $data['mUploadTempName'];
70 $this->mUploadSize
= $data['mUploadSize'];
71 $this->mOname
= $data['mOname'];
72 $this->mStashed
= true;
75 *Check for a newly uploaded file.
77 $this->mUploadTempName
= $request->getFileTempName( 'wpUploadFile' );
78 $this->mUploadSize
= $request->getFileSize( 'wpUploadFile' );
79 $this->mOname
= $request->getFileName( 'wpUploadFile' );
80 $this->mSessionKey
= false;
81 $this->mStashed
= false;
90 global $wgUser, $wgOut;
91 global $wgDisableUploads;
93 /** Show an error message if file upload is disabled */
94 if( $wgDisableUploads ) {
95 $wgOut->addWikiText( wfMsg( 'uploaddisabled' ) );
99 /** Various rights checks */
100 if( ( $wgUser->isAnon() )
101 OR $wgUser->isBlocked() ) {
102 $wgOut->errorpage( 'uploadnologin', 'uploadnologintext' );
106 $wgOut->readOnlyPage();
110 if( $this->mReUpload
) {
111 $this->unsaveUploadedFile();
112 $this->mainUploadForm();
113 } else if ( 'submit' == $this->mAction ||
$this->mUpload
) {
114 $this->processUpload();
116 $this->mainUploadForm();
120 /* -------------------------------------------------------------- */
123 * Really do the upload
124 * Checks are made in SpecialUpload::execute()
127 function processUpload() {
128 global $wgUser, $wgOut, $wgLang, $wgContLang;
129 global $wgUploadDirectory;
130 global $wgUseCopyrightUpload, $wgCheckCopyrightUpload;
133 * If there was no filename or a zero size given, give up quick.
135 if( ( trim( $this->mOname
) == '' ) ||
empty( $this->mUploadSize
) ) {
136 return $this->mainUploadForm('<li>'.wfMsg( 'emptyfile' ).'</li>');
140 * When using detailed copyright, if user filled field, assume he
141 * confirmed the upload
143 if ( $wgUseCopyrightUpload ) {
144 $this->mUploadAffirm
= true;
145 if( $wgCheckCopyrightUpload &&
146 ( trim( $this->mUploadCopyStatus
) == '' ||
147 trim( $this->mUploadSource
) == '' ) ) {
148 $this->mUploadAffirm
= false;
152 /** User need to confirm his upload */
153 if( !$this->mUploadAffirm
) {
154 $this->mainUploadForm( wfMsg( 'noaffirmation' ) );
158 # Chop off any directories in the given filename
159 $basename = basename( $this->mOname
);
162 * We'll want to blacklist against *any* 'extension', and use
163 * only the final one for the whitelist.
165 list( $partname, $ext ) = $this->splitExtensions( $basename );
166 if( count( $ext ) ) {
167 $finalExt = $ext[count( $ext ) - 1];
171 $fullExt = implode( '.', $ext );
173 if ( strlen( $partname ) < 3 ) {
174 $this->mainUploadForm( wfMsg( 'minlength' ) );
179 * Filter out illegal characters, and try to make a legible name
180 * out of it. We'll strip some silently that Title would die on.
182 $filtered = preg_replace ( "/[^".Title
::legalChars()."]|:/", '-', $basename );
183 $nt = Title
::newFromText( $filtered );
184 if( is_null( $nt ) ) {
185 return $this->uploadError( wfMsg( 'illegalfilename', htmlspecialchars( $filtered ) ) );
187 $nt =& Title
::makeTitle( NS_IMAGE
, $nt->getDBkey() );
188 $this->mUploadSaveName
= $nt->getDBkey();
191 * If the image is protected, non-sysop users won't be able
192 * to modify it by uploading a new revision.
194 if( !$nt->userCanEdit() ) {
195 return $this->uploadError( wfMsg( 'protectedpage' ) );
198 /* Don't allow users to override the blacklist */
199 global $wgStrictFileExtensions;
200 global $wgFileExtensions, $wgFileBlacklist;
201 if( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
202 ($wgStrictFileExtensions &&
203 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
204 return $this->uploadError( wfMsg( 'badfiletype', htmlspecialchars( $fullExt ) ) );
208 * Look at the contents of the file; if we can recognize the
209 * type but it's corrupt or data of the wrong type, we should
210 * probably not accept it.
212 if( !$this->mStashed
&& !$this->verify( $this->mUploadTempName
, $finalExt ) ) {
213 return $this->uploadError( wfMsg( 'uploadcorrupt' ) );
217 * Check for non-fatal conditions
219 if ( ! $this->mIgnoreWarning
) {
221 if( $this->mUploadSaveName
!= ucfirst( $filtered ) ) {
222 $warning .= '<li>'.wfMsg( 'badfilename', htmlspecialchars( $this->mUploadSaveName
) ).'</li>';
225 global $wgCheckFileExtensions;
226 if ( $wgCheckFileExtensions ) {
227 if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
228 $warning .= '<li>'.wfMsg( 'badfiletype', htmlspecialchars( $fullExt ) ).'</li>';
232 global $wgUploadSizeWarning;
233 if ( $wgUploadSizeWarning && ( $this->mUploadSize
> $wgUploadSizeWarning ) ) {
234 $warning .= '<li>'.wfMsg( 'largefile' ).'</li>';
236 if ( $this->mUploadSize
== 0 ) {
237 $warning .= '<li>'.wfMsg( 'emptyfile' ).'</li>';
240 if( $nt->getArticleID() ) {
242 $sk = $wgUser->getSkin();
243 $dlink = $sk->makeKnownLinkObj( $nt );
244 $warning .= '<li>'.wfMsg( 'fileexists', $dlink ).'</li>';
247 if( $warning != '' ) {
249 * Stash the file in a temporary location; the user can choose
250 * to let it through and we'll complete the upload then.
252 return $this->uploadWarning($warning);
257 * Try actually saving the thing...
258 * It will show an error form on failure.
260 if( $this->saveUploadedFile( $this->mUploadSaveName
,
261 $this->mUploadTempName
,
262 !empty( $this->mSessionKey
) ) ) {
264 * Update the upload log and create the description page
265 * if it's a new file.
267 wfRecordUpload( $this->mUploadSaveName
,
268 $this->mUploadOldVersion
,
270 $this->mUploadDescription
,
271 $this->mUploadCopyStatus
,
272 $this->mUploadSource
);
274 /* refresh image metadata cache */
275 new Image( $this->mUploadSaveName
, true );
277 $this->showSuccess();
282 * Move the uploaded file from its temporary location to the final
283 * destination. If a previous version of the file exists, move
284 * it into the archive subdirectory.
286 * @todo If the later save fails, we may have disappeared the original file.
288 * @param string $saveName
289 * @param string $tempName full path to the temporary file
290 * @param bool $useRename if true, doesn't check that the source file
291 * is a PHP-managed upload temporary
293 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
294 global $wgUploadDirectory, $wgOut;
296 $dest = wfImageDir( $saveName );
297 $archive = wfImageArchiveDir( $saveName );
298 $this->mSavedFile
= "{$dest}/{$saveName}";
300 if( is_file( $this->mSavedFile
) ) {
301 $this->mUploadOldVersion
= gmdate( 'YmdHis' ) . "!{$saveName}";
303 if( @!rename( $this->mSavedFile
, "${archive}/{$this->mUploadOldVersion}" ) ) {
304 $wgOut->fileRenameError( $this->mSavedFile
,
305 "${archive}/{$this->mUploadOldVersion}" );
309 $this->mUploadOldVersion
= '';
313 if( @!rename( $tempName, $this->mSavedFile
) ) {
314 $wgOut->fileCopyError( $tempName, $this->mSavedFile
);
318 if( @!move_uploaded_file( $tempName, $this->mSavedFile
) ) {
319 $wgOut->fileCopyError( $tempName, $this->mSavedFile
);
323 chmod( $this->mSavedFile
, 0644 );
328 * Stash a file in a temporary directory for later processing
329 * after the user has confirmed it.
331 * If the user doesn't explicitly cancel or accept, these files
332 * can accumulate in the temp directory.
334 * @param string $saveName - the destination filename
335 * @param string $tempName - the source temporary file to save
336 * @return string - full path the stashed file, or false on failure
339 function saveTempUploadedFile( $saveName, $tempName ) {
341 $archive = wfImageArchiveDir( $saveName, 'temp' );
342 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
344 if ( !move_uploaded_file( $tempName, $stash ) ) {
345 $wgOut->fileCopyError( $tempName, $stash );
353 * Stash a file in a temporary directory for later processing,
354 * and save the necessary descriptive info into the session.
355 * Returns a key value which will be passed through a form
356 * to pick up the path info on a later invocation.
361 function stashSession() {
362 $stash = $this->saveTempUploadedFile(
363 $this->mUploadSaveName
, $this->mUploadTempName
);
366 # Couldn't save the file.
370 $key = mt_rand( 0, 0x7fffffff );
371 $_SESSION['wsUploadData'][$key] = array(
372 'mUploadTempName' => $stash,
373 'mUploadSize' => $this->mUploadSize
,
374 'mOname' => $this->mOname
);
379 * Remove a temporarily kept file stashed by saveTempUploadedFile().
382 function unsaveUploadedFile() {
383 if ( ! @unlink
( $this->mUploadTempName
) ) {
384 $wgOut->fileDeleteError( $this->mUploadTempName
);
388 /* -------------------------------------------------------------- */
391 * Show some text and linkage on successful upload.
394 function showSuccess() {
395 global $wgUser, $wgOut, $wgContLang;
397 $sk = $wgUser->getSkin();
398 $ilink = $sk->makeMediaLink( $this->mUploadSaveName
, Image
::wfImageUrl( $this->mUploadSaveName
) );
399 $dname = $wgContLang->getNsText( NS_IMAGE
) . ':'.$this->mUploadSaveName
;
400 $dlink = $sk->makeKnownLink( $dname, $dname );
402 $wgOut->addHTML( '<h2>' . wfMsg( 'successfulupload' ) . "</h2>\n" );
403 $text = wfMsg( 'fileuploaded', $ilink, $dlink );
404 $wgOut->addHTML( '<p>'.$text."\n" );
405 $wgOut->returnToMain( false );
409 * @param string $error as HTML
412 function uploadError( $error ) {
414 $sub = wfMsg( 'uploadwarning' );
415 $wgOut->addHTML( "<h2>{$sub}</h2>\n" );
416 $wgOut->addHTML( "<h4 class='error'>{$error}</h4>\n" );
420 * There's something wrong with this file, not enough to reject it
421 * totally but we require manual intervention to save it for real.
422 * Stash it away, then present a form asking to confirm or cancel.
424 * @param string $warning as HTML
427 function uploadWarning( $warning ) {
428 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
429 global $wgUseCopyrightUpload;
431 $this->mSessionKey
= $this->stashSession();
432 if( !$this->mSessionKey
) {
433 # Couldn't save file; an error has been displayed so let's go.
437 $sub = wfMsg( 'uploadwarning' );
438 $wgOut->addHTML( "<h2>{$sub}</h2>\n" );
439 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
441 $save = wfMsg( 'savefile' );
442 $reupload = wfMsg( 'reupload' );
443 $iw = wfMsg( 'ignorewarning' );
444 $reup = wfMsg( 'reuploaddesc' );
445 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Upload' );
446 $action = $titleObj->escapeLocalURL( 'action=submit' );
448 if ( $wgUseCopyrightUpload )
451 <input type='hidden' name=\"wpUploadCopyStatus\" value=\"" . htmlspecialchars( $this->mUploadCopyStatus
) . "\" />
452 <input type='hidden' name=\"wpUploadSource\" value=\"" . htmlspecialchars( $this->mUploadSource
) . "\" />
459 <form id=\"uploadwarning\" method=\"post\" enctype=\"multipart/form-data\"
460 action=\"{$action}\">
461 <input type=hidden name=\"wpUploadAffirm\" value=\"1\" />
462 <input type=hidden name=\"wpIgnoreWarning\" value=\"1\" />
463 <input type=hidden name=\"wpSessionKey\" value=\"" . htmlspecialchars( $this->mSessionKey
) . "\" />
464 <input type=hidden name=\"wpUploadDescription\" value=\"" . htmlspecialchars( $this->mUploadDescription
) . "\" />
466 <table border='0'><tr>
467 <tr><td align='right'>
468 <input tabindex='2' type='submit' name=\"wpUpload\" value=\"{$save}\" />
469 </td><td align='left'>{$iw}</td></tr>
470 <tr><td align='right'>
471 <input tabindex='2' type='submit' name=\"wpReUpload\" value=\"{$reupload}\" />
472 </td><td align='left'>{$reup}</td></tr></table></form>\n" );
476 * Displays the main upload form, optionally with a highlighted
477 * error message up at the top.
479 * @param string $msg as HTML
482 function mainUploadForm( $msg='' ) {
483 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
484 global $wgUseCopyrightUpload;
487 $sub = wfMsg( 'uploaderror' );
488 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
489 "<h4 class='error'>{$msg}</h4>\n" );
491 $sub = wfMsg( 'uploadfile' );
492 $wgOut->addHTML( "<h2>{$sub}</h2>\n" );
494 $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
495 $sk = $wgUser->getSkin();
497 $fn = wfMsg( 'filename' );
498 $fd = wfMsg( 'filedesc' );
499 $ulb = wfMsg( 'uploadbtn' );
501 $clink = $sk->makeKnownLink( wfMsgForContent( 'copyrightpage' ),
502 wfMsg( 'copyrightpagename' ) );
503 $ca = wfMsg( 'affirmation', $clink );
504 $iw = wfMsg( 'ignorewarning' );
506 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Upload' );
507 $action = $titleObj->escapeLocalURL();
511 <input tabindex='3' type='checkbox' name=\"wpUploadAffirm\" value=\"1\" id=\"wpUploadAffirm\" />
512 </td><td align='left'><label for=\"wpUploadAffirm\">{$ca}</label></td>
514 if ( $wgUseCopyrightUpload )
517 <td align='right' nowrap='nowrap'>" . wfMsg ( 'filestatus' ) . ":</td>
518 <td><input tabindex='3' type='text' name=\"wpUploadCopyStatus\" value=\"" .
519 htmlspecialchars($this->mUploadCopyStatus
). "\" size='40' /></td>
521 <td align='right'>". wfMsg ( 'filesource' ) . ":</td>
522 <td><input tabindex='4' type='text' name=\"wpUploadSource\" value=\"" .
523 htmlspecialchars($this->mUploadSource
). "\" size='40' /></td>
528 <form id=\"upload\" method=\"post\" enctype=\"multipart/form-data\"
529 action=\"{$action}\">
530 <table border='0'><tr>
531 <td align='right'>{$fn}:</td><td align='left'>
532 <input tabindex='1' type='file' name=\"wpUploadFile\" size='40' />
534 <td align='right'>{$fd}:</td><td align='left'>
535 <input tabindex='2' type='text' name=\"wpUploadDescription\" value=\""
536 . htmlspecialchars( $this->mUploadDescription
) . "\" size='40' />
540 <tr><td></td><td align='left'>
541 <input tabindex='5' type='submit' name=\"wpUpload\" value=\"{$ulb}\" />
542 </td></tr></table></form>\n" );
545 /* -------------------------------------------------------------- */
548 * Split a file into a base name and all dot-delimited 'extensions'
549 * on the end. Some web server configurations will fall back to
550 * earlier pseudo-'extensions' to determine type and execute
551 * scripts, so the blacklist needs to check them all.
555 function splitExtensions( $filename ) {
556 $bits = explode( '.', $filename );
557 $basename = array_shift( $bits );
558 return array( $basename, $bits );
562 * Perform case-insensitive match against a list of file extensions.
563 * Returns true if the extension is in the list.
569 function checkFileExtension( $ext, $list ) {
570 return in_array( strtolower( $ext ), $list );
574 * Perform case-insensitive match against a list of file extensions.
575 * Returns true if any of the extensions are in the list.
581 function checkFileExtensionList( $ext, $list ) {
582 foreach( $ext as $e ) {
583 if( in_array( strtolower( $e ), $list ) ) {
591 * Returns false if the file is of a known type but can't be recognized,
592 * indicating a corrupt file.
593 * Returns true otherwise; unknown file types are not checked if given
594 * with an unrecognized extension.
596 * @param string $tmpfile Pathname to the temporary upload file
597 * @param string $extension The filename extension that the file is to be served with
600 function verify( $tmpfile, $extension ) {
601 if( $this->triggersIEbug( $tmpfile ) ||
602 $this->triggersSafariBug( $tmpfile ) ) {
606 $fname = 'SpecialUpload::verify';
607 $mergeExtensions = array(
610 $extensionTypes = array(
611 # See http://www.php.net/getimagesize
629 $extension = strtolower( $extension );
630 if( isset( $mergeExtensions[$extension] ) ) {
631 $extension = $mergeExtensions[$extension];
633 wfDebug( "$fname: Testing file '$tmpfile' with given extension '$extension'\n" );
635 if( !in_array( $extension, $extensionTypes ) ) {
636 # Not a recognized image type. We don't know how to verify these.
637 # They're allowed by policy or they wouldn't get this far, so we'll
638 # let them slide for now.
639 wfDebug( "$fname: Unknown extension; passing.\n" );
643 $data = @getimagesize
( $tmpfile );
644 if( false === $data ) {
645 # Didn't recognize the image type.
646 # Either the image is corrupt or someone's slipping us some
647 # bogus data such as HTML+JavaScript trying to take advantage
648 # of an Internet Explorer security flaw.
649 wfDebug( "$fname: getimagesize() doesn't recognize the file; rejecting.\n" );
653 $imageType = $data[2];
654 if( !isset( $extensionTypes[$imageType] ) ) {
655 # Now we're kind of confused. Perhaps new image types added
656 # to PHP's support that we don't know about.
657 # We'll let these slide for now.
658 wfDebug( "$fname: getimagesize() knows the file, but we don't recognize the type; passing.\n" );
662 $ext = strtolower( $extension );
663 if( $extension != $extensionTypes[$imageType] ) {
664 # The given filename extension doesn't match the
665 # file type. Probably just a mistake, but it's a stupid
666 # one and we shouldn't let it pass. KILL THEM!
667 wfDebug( "$fname: file extension does not match recognized type; rejecting.\n" );
671 wfDebug( "$fname: all clear; passing.\n" );
676 * Internet Explorer for Windows performs some really stupid file type
677 * autodetection which can cause it to interpret valid image files as HTML
678 * and potentially execute JavaScript, creating a cross-site scripting
681 * Returns true if IE is likely to mistake the given file for HTML.
683 * @param string $filename
686 function triggersIEbug( $filename ) {
687 $file = fopen( $filename, 'rb' );
688 $chunk = strtolower( fread( $file, 256 ) );
700 foreach( $tags as $tag ) {
701 if( false !== strpos( $chunk, $tag ) ) {
709 * Apple's Safari browser performs some unsafe file type autodetection
710 * which can cause legitimate files to be interpreted as HTML if the
711 * web server is not correctly configured to send the right content-type
712 * (or if you're really uploading plain text and octet streams!)
714 * Returns true if Safari would mistake the given file for HTML
715 * when served with a generic content-type.
717 * @param string $filename
720 function triggersSafariBug( $filename ) {
721 $file = fopen( $filename, 'rb' );
722 $chunk = strtolower( fread( $file, 1024 ) );
729 foreach( $tags as $tag ) {
730 if( false !== strpos( $chunk, $tag ) ) {