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, $mDestFile;
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 $this->mDestFile
= $request->getText( 'wpDestFile' );
45 if( !$request->wasPosted() ) {
46 # GET requests just give the main form; no data except wpDestfile.
50 $this->mUploadAffirm
= $request->getCheck( 'wpUploadAffirm' );
51 $this->mIgnoreWarning
= $request->getCheck( 'wpIgnoreWarning');
52 $this->mReUpload
= $request->getCheck( 'wpReUpload' );
53 $this->mUpload
= $request->getCheck( 'wpUpload' );
55 $this->mUploadDescription
= $request->getText( 'wpUploadDescription' );
56 $this->mUploadCopyStatus
= $request->getText( 'wpUploadCopyStatus' );
57 $this->mUploadSource
= $request->getText( 'wpUploadSource');
59 $this->mAction
= $request->getVal( 'action' );
61 $this->mSessionKey
= $request->getInt( 'wpSessionKey' );
62 if( !empty( $this->mSessionKey
) &&
63 isset( $_SESSION['wsUploadData'][$this->mSessionKey
] ) ) {
65 * Confirming a temporarily stashed upload.
66 * We don't want path names to be forged, so we keep
67 * them in the session on the server and just give
68 * an opaque key to the user agent.
70 $data = $_SESSION['wsUploadData'][$this->mSessionKey
];
71 $this->mUploadTempName
= $data['mUploadTempName'];
72 $this->mUploadSize
= $data['mUploadSize'];
73 $this->mOname
= $data['mOname'];
74 $this->mStashed
= true;
77 *Check for a newly uploaded file.
79 $this->mUploadTempName
= $request->getFileTempName( 'wpUploadFile' );
80 $this->mUploadSize
= $request->getFileSize( 'wpUploadFile' );
81 $this->mOname
= $request->getFileName( 'wpUploadFile' );
82 $this->mSessionKey
= false;
83 $this->mStashed
= false;
92 global $wgUser, $wgOut;
93 global $wgEnableUploads, $wgUploadDirectory;
95 /** Show an error message if file upload is disabled */
96 if( ! $wgEnableUploads ) {
97 $wgOut->addWikiText( wfMsg( 'uploaddisabled' ) );
101 /** Various rights checks */
102 if( ( $wgUser->isAnon() )
103 OR $wgUser->isBlocked() ) {
104 $wgOut->errorpage( 'uploadnologin', 'uploadnologintext' );
108 $wgOut->readOnlyPage();
112 /** Check if the image directory is writeable, this is a common mistake */
113 if ( !is_writeable( $wgUploadDirectory ) ) {
114 $wgOut->addWikiText( wfMsg( 'upload_directory_read_only', $wgUploadDirectory ) );
118 if( $this->mReUpload
) {
119 $this->unsaveUploadedFile();
120 $this->mainUploadForm();
121 } else if ( 'submit' == $this->mAction ||
$this->mUpload
) {
122 $this->processUpload();
124 $this->mainUploadForm();
128 /* -------------------------------------------------------------- */
131 * Really do the upload
132 * Checks are made in SpecialUpload::execute()
135 function processUpload() {
136 global $wgUser, $wgOut, $wgLang, $wgContLang;
137 global $wgUploadDirectory;
138 global $wgUseCopyrightUpload, $wgCheckCopyrightUpload;
141 * If there was no filename or a zero size given, give up quick.
143 if( trim( $this->mOname
) == '' ||
empty( $this->mUploadSize
) ) {
144 return $this->mainUploadForm('<li>'.wfMsg( 'emptyfile' ).'</li>');
148 * When using detailed copyright, if user filled field, assume he
149 * confirmed the upload
151 if ( $wgUseCopyrightUpload ) {
152 $this->mUploadAffirm
= true;
153 if( $wgCheckCopyrightUpload &&
154 ( trim( $this->mUploadCopyStatus
) == '' ||
155 trim( $this->mUploadSource
) == '' ) ) {
156 $this->mUploadAffirm
= false;
160 /** User need to confirm his upload */
161 if( !$this->mUploadAffirm
) {
162 $this->mainUploadForm( wfMsg( 'noaffirmation' ) );
166 # Chop off any directories in the given filename
167 if ( $this->mDestFile
) {
168 $basename = basename( $this->mDestFile
);
170 $basename = basename( $this->mOname
);
174 * We'll want to blacklist against *any* 'extension', and use
175 * only the final one for the whitelist.
177 list( $partname, $ext ) = $this->splitExtensions( $basename );
178 if( count( $ext ) ) {
179 $finalExt = $ext[count( $ext ) - 1];
183 $fullExt = implode( '.', $ext );
185 if ( strlen( $partname ) < 3 ) {
186 $this->mainUploadForm( wfMsg( 'minlength' ) );
191 * Filter out illegal characters, and try to make a legible name
192 * out of it. We'll strip some silently that Title would die on.
194 $filtered = preg_replace ( "/[^".Title
::legalChars()."]|:/", '-', $basename );
195 $nt = Title
::newFromText( $filtered );
196 if( is_null( $nt ) ) {
197 return $this->uploadError( wfMsg( 'illegalfilename', htmlspecialchars( $filtered ) ) );
199 $nt =& Title
::makeTitle( NS_IMAGE
, $nt->getDBkey() );
200 $this->mUploadSaveName
= $nt->getDBkey();
203 * If the image is protected, non-sysop users won't be able
204 * to modify it by uploading a new revision.
206 if( !$nt->userCanEdit() ) {
207 return $this->uploadError( wfMsg( 'protectedpage' ) );
210 /* Don't allow users to override the blacklist */
211 global $wgStrictFileExtensions;
212 global $wgFileExtensions, $wgFileBlacklist;
213 if( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
214 ($wgStrictFileExtensions &&
215 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
216 return $this->uploadError( wfMsg( 'badfiletype', htmlspecialchars( $fullExt ) ) );
220 * Look at the contents of the file; if we can recognize the
221 * type but it's corrupt or data of the wrong type, we should
222 * probably not accept it.
224 if( !$this->mStashed
&& !$this->verify( $this->mUploadTempName
, $finalExt ) ) {
225 return $this->uploadError( wfMsg( 'uploadcorrupt' ) );
229 * Check for non-fatal conditions
231 if ( ! $this->mIgnoreWarning
) {
233 if( $this->mUploadSaveName
!= ucfirst( $filtered ) ) {
234 $warning .= '<li>'.wfMsg( 'badfilename', htmlspecialchars( $this->mUploadSaveName
) ).'</li>';
237 global $wgCheckFileExtensions;
238 if ( $wgCheckFileExtensions ) {
239 if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
240 $warning .= '<li>'.wfMsg( 'badfiletype', htmlspecialchars( $fullExt ) ).'</li>';
244 global $wgUploadSizeWarning;
245 if ( $wgUploadSizeWarning && ( $this->mUploadSize
> $wgUploadSizeWarning ) ) {
246 # TODO: Format $wgUploadSizeWarning to something that looks better than the raw byte
247 # value, perhaps add GB,MB and KB suffixes?
248 $warning .= '<li>'.wfMsg( 'largefile', $wgUploadSizeWarning, $this->mUploadSize
).'</li>';
250 if ( $this->mUploadSize
== 0 ) {
251 $warning .= '<li>'.wfMsg( 'emptyfile' ).'</li>';
254 if( $nt->getArticleID() ) {
256 $sk = $wgUser->getSkin();
257 $dlink = $sk->makeKnownLinkObj( $nt );
258 $warning .= '<li>'.wfMsg( 'fileexists', $dlink ).'</li>';
261 if( $warning != '' ) {
263 * Stash the file in a temporary location; the user can choose
264 * to let it through and we'll complete the upload then.
266 return $this->uploadWarning($warning);
271 * Try actually saving the thing...
272 * It will show an error form on failure.
274 if( $this->saveUploadedFile( $this->mUploadSaveName
,
275 $this->mUploadTempName
,
276 !empty( $this->mSessionKey
) ) ) {
278 * Update the upload log and create the description page
279 * if it's a new file.
281 $img = Image
::newFromName( $this->mUploadSaveName
);
282 $success = $img->recordUpload( $this->mUploadOldVersion
,
283 $this->mUploadDescription
,
284 $this->mUploadCopyStatus
,
285 $this->mUploadSource
);
288 $this->showSuccess();
290 // Image::recordUpload() fails if the image went missing, which is
291 // unlikely, hence the lack of a specialised message
292 $wgOut->fileNotFoundError( $this->mUploadSaveName
);
298 * Move the uploaded file from its temporary location to the final
299 * destination. If a previous version of the file exists, move
300 * it into the archive subdirectory.
302 * @todo If the later save fails, we may have disappeared the original file.
304 * @param string $saveName
305 * @param string $tempName full path to the temporary file
306 * @param bool $useRename if true, doesn't check that the source file
307 * is a PHP-managed upload temporary
309 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
310 global $wgUploadDirectory, $wgOut;
312 $dest = wfImageDir( $saveName );
313 $archive = wfImageArchiveDir( $saveName );
314 $this->mSavedFile
= "{$dest}/{$saveName}";
316 if( is_file( $this->mSavedFile
) ) {
317 $this->mUploadOldVersion
= gmdate( 'YmdHis' ) . "!{$saveName}";
318 wfSuppressWarnings();
319 $success = rename( $this->mSavedFile
, "${archive}/{$this->mUploadOldVersion}" );
323 $wgOut->fileRenameError( $this->mSavedFile
,
324 "${archive}/{$this->mUploadOldVersion}" );
328 $this->mUploadOldVersion
= '';
332 wfSuppressWarnings();
333 $success = rename( $tempName, $this->mSavedFile
);
337 $wgOut->fileCopyError( $tempName, $this->mSavedFile
);
341 wfSuppressWarnings();
342 $success = move_uploaded_file( $tempName, $this->mSavedFile
);
346 $wgOut->fileCopyError( $tempName, $this->mSavedFile
);
350 chmod( $this->mSavedFile
, 0644 );
355 * Stash a file in a temporary directory for later processing
356 * after the user has confirmed it.
358 * If the user doesn't explicitly cancel or accept, these files
359 * can accumulate in the temp directory.
361 * @param string $saveName - the destination filename
362 * @param string $tempName - the source temporary file to save
363 * @return string - full path the stashed file, or false on failure
366 function saveTempUploadedFile( $saveName, $tempName ) {
368 $archive = wfImageArchiveDir( $saveName, 'temp' );
369 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
371 if ( !move_uploaded_file( $tempName, $stash ) ) {
372 $wgOut->fileCopyError( $tempName, $stash );
380 * Stash a file in a temporary directory for later processing,
381 * and save the necessary descriptive info into the session.
382 * Returns a key value which will be passed through a form
383 * to pick up the path info on a later invocation.
388 function stashSession() {
389 $stash = $this->saveTempUploadedFile(
390 $this->mUploadSaveName
, $this->mUploadTempName
);
393 # Couldn't save the file.
397 $key = mt_rand( 0, 0x7fffffff );
398 $_SESSION['wsUploadData'][$key] = array(
399 'mUploadTempName' => $stash,
400 'mUploadSize' => $this->mUploadSize
,
401 'mOname' => $this->mOname
);
406 * Remove a temporarily kept file stashed by saveTempUploadedFile().
409 function unsaveUploadedFile() {
410 wfSuppressWarnings();
411 $success = unlink( $this->mUploadTempName
);
414 $wgOut->fileDeleteError( $this->mUploadTempName
);
418 /* -------------------------------------------------------------- */
421 * Show some text and linkage on successful upload.
424 function showSuccess() {
425 global $wgUser, $wgOut, $wgContLang;
427 $sk = $wgUser->getSkin();
428 $ilink = $sk->makeMediaLink( $this->mUploadSaveName
, Image
::imageUrl( $this->mUploadSaveName
) );
429 $dname = $wgContLang->getNsText( NS_IMAGE
) . ':'.$this->mUploadSaveName
;
430 $dlink = $sk->makeKnownLink( $dname, $dname );
432 $wgOut->addHTML( '<h2>' . wfMsg( 'successfulupload' ) . "</h2>\n" );
433 $text = wfMsg( 'fileuploaded', $ilink, $dlink );
434 $wgOut->addHTML( '<p>'.$text."\n" );
435 $wgOut->returnToMain( false );
439 * @param string $error as HTML
442 function uploadError( $error ) {
444 $sub = wfMsg( 'uploadwarning' );
445 $wgOut->addHTML( "<h2>{$sub}</h2>\n" );
446 $wgOut->addHTML( "<h4 class='error'>{$error}</h4>\n" );
450 * There's something wrong with this file, not enough to reject it
451 * totally but we require manual intervention to save it for real.
452 * Stash it away, then present a form asking to confirm or cancel.
454 * @param string $warning as HTML
457 function uploadWarning( $warning ) {
458 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
459 global $wgUseCopyrightUpload;
461 $this->mSessionKey
= $this->stashSession();
462 if( !$this->mSessionKey
) {
463 # Couldn't save file; an error has been displayed so let's go.
467 $sub = wfMsg( 'uploadwarning' );
468 $wgOut->addHTML( "<h2>{$sub}</h2>\n" );
469 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
471 $save = wfMsg( 'savefile' );
472 $reupload = wfMsg( 'reupload' );
473 $iw = wfMsg( 'ignorewarning' );
474 $reup = wfMsg( 'reuploaddesc' );
475 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Upload' );
476 $action = $titleObj->escapeLocalURL( 'action=submit' );
478 if ( $wgUseCopyrightUpload )
481 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mUploadCopyStatus
) . "\" />
482 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mUploadSource
) . "\" />
489 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
490 <input type='hidden' name='wpUploadAffirm' value='1' />
491 <input type='hidden' name='wpIgnoreWarning' value='1' />
492 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey
) . "\" />
493 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mUploadDescription
) . "\" />
494 <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDestFile
) . "\" />
500 <input tabindex='2' type='submit' name='wpUpload' value='$save' />
502 <td align='left'>$iw</td>
506 <input tabindex='2' type='submit' name='wpReUpload' value='{$reupload}' />
508 <td align='left'>$reup</td>
511 </table></form>\n" );
515 * Displays the main upload form, optionally with a highlighted
516 * error message up at the top.
518 * @param string $msg as HTML
521 function mainUploadForm( $msg='' ) {
522 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
523 global $wgUseCopyrightUpload;
525 $cols = intval($wgUser->getOption( 'cols' ));
526 $ew = $wgUser->getOption( 'editwidth' );
527 if ( $ew ) $ew = " style=\"width:100%\"";
531 $sub = wfMsg( 'uploaderror' );
532 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
533 "<h4 class='error'>{$msg}</h4>\n" );
535 $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
536 $sk = $wgUser->getSkin();
539 $sourcefilename = wfMsg( 'sourcefilename' );
540 $destfilename = wfMsg( 'destfilename' );
542 $fd = wfMsg( 'filedesc' );
543 $ulb = wfMsg( 'uploadbtn' );
545 $clink = $sk->makeKnownLink( wfMsgForContent( 'copyrightpage' ),
546 wfMsg( 'copyrightpagename' ) );
547 $ca = wfMsg( 'affirmation', $clink );
548 $iw = wfMsg( 'ignorewarning' );
550 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Upload' );
551 $action = $titleObj->escapeLocalURL();
553 $encDestFile = htmlspecialchars( $this->mDestFile
);
557 <input tabindex='3' type='checkbox' name='wpUploadAffirm' value='1' id='wpUploadAffirm' />
558 </td><td align='left'><label for='wpUploadAffirm'>{$ca}</label></td>
560 if ( $wgUseCopyrightUpload )
563 <td align='right' nowrap='nowrap'>" . wfMsg ( 'filestatus' ) . ":</td>
564 <td><input tabindex='3' type='text' name=\"wpUploadCopyStatus\" value=\"" .
565 htmlspecialchars($this->mUploadCopyStatus
). "\" size='40' /></td>
567 <td align='right'>". wfMsg ( 'filesource' ) . ":</td>
568 <td><input tabindex='4' type='text' name='wpUploadSource' value=\"" .
569 htmlspecialchars($this->mUploadSource
). "\" size='40' /></td>
574 <form id='upload' method='post' enctype='multipart/form-data' action=\"$action\">
575 <table border='0'><tr>
577 <td align='right'>{$sourcefilename}:</td><td align='left'>
578 <input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' onchange='fillDestFilename()' size='40' />
581 <td align='right'>{$destfilename}:</td><td align='left'>
582 <input tabindex='1' type='text' name='wpDestFile' id='wpDestFile' size='40' value=\"$encDestFile\" />
585 <td align='right'>{$fd}:</td><td align='left'>
586 <textarea tabindex='2' name='wpUploadDescription' rows='6' cols='{$cols}'{$ew}>"
587 . htmlspecialchars( $this->mUploadDescription
) .
592 <tr><td></td><td align='left'>
593 <input tabindex='5' type='submit' name='wpUpload' value=\"{$ulb}\" />
594 </td></tr></table></form>\n" );
597 /* -------------------------------------------------------------- */
600 * Split a file into a base name and all dot-delimited 'extensions'
601 * on the end. Some web server configurations will fall back to
602 * earlier pseudo-'extensions' to determine type and execute
603 * scripts, so the blacklist needs to check them all.
607 function splitExtensions( $filename ) {
608 $bits = explode( '.', $filename );
609 $basename = array_shift( $bits );
610 return array( $basename, $bits );
614 * Perform case-insensitive match against a list of file extensions.
615 * Returns true if the extension is in the list.
621 function checkFileExtension( $ext, $list ) {
622 return in_array( strtolower( $ext ), $list );
626 * Perform case-insensitive match against a list of file extensions.
627 * Returns true if any of the extensions are in the list.
633 function checkFileExtensionList( $ext, $list ) {
634 foreach( $ext as $e ) {
635 if( in_array( strtolower( $e ), $list ) ) {
643 * Returns false if the file is of a known type but can't be recognized,
644 * indicating a corrupt file.
645 * Returns true otherwise; unknown file types are not checked if given
646 * with an unrecognized extension.
648 * @param string $tmpfile Pathname to the temporary upload file
649 * @param string $extension The filename extension that the file is to be served with
652 function verify( $tmpfile, $extension ) {
653 if( $this->triggersIEbug( $tmpfile ) ||
654 $this->triggersSafariBug( $tmpfile ) ) {
658 $fname = 'SpecialUpload::verify';
659 $mergeExtensions = array(
662 $extensionTypes = array(
663 # See http://www.php.net/getimagesize
681 $extension = strtolower( $extension );
682 if( isset( $mergeExtensions[$extension] ) ) {
683 $extension = $mergeExtensions[$extension];
685 wfDebug( "$fname: Testing file '$tmpfile' with given extension '$extension'\n" );
687 if( !in_array( $extension, $extensionTypes ) ) {
688 # Not a recognized image type. We don't know how to verify these.
689 # They're allowed by policy or they wouldn't get this far, so we'll
690 # let them slide for now.
691 wfDebug( "$fname: Unknown extension; passing.\n" );
695 wfSuppressWarnings();
696 $data = getimagesize( $tmpfile );
698 if( false === $data ) {
699 # Didn't recognize the image type.
700 # Either the image is corrupt or someone's slipping us some
701 # bogus data such as HTML+JavaScript trying to take advantage
702 # of an Internet Explorer security flaw.
703 wfDebug( "$fname: getimagesize() doesn't recognize the file; rejecting.\n" );
707 $imageType = $data[2];
708 if( !isset( $extensionTypes[$imageType] ) ) {
709 # Now we're kind of confused. Perhaps new image types added
710 # to PHP's support that we don't know about.
711 # We'll let these slide for now.
712 wfDebug( "$fname: getimagesize() knows the file, but we don't recognize the type; passing.\n" );
716 $ext = strtolower( $extension );
717 if( $extension != $extensionTypes[$imageType] ) {
718 # The given filename extension doesn't match the
719 # file type. Probably just a mistake, but it's a stupid
720 # one and we shouldn't let it pass. KILL THEM!
721 wfDebug( "$fname: file extension does not match recognized type; rejecting.\n" );
725 wfDebug( "$fname: all clear; passing.\n" );
730 * Internet Explorer for Windows performs some really stupid file type
731 * autodetection which can cause it to interpret valid image files as HTML
732 * and potentially execute JavaScript, creating a cross-site scripting
735 * Returns true if IE is likely to mistake the given file for HTML.
737 * @param string $filename
740 function triggersIEbug( $filename ) {
741 $file = fopen( $filename, 'rb' );
742 $chunk = strtolower( fread( $file, 256 ) );
754 foreach( $tags as $tag ) {
755 if( false !== strpos( $chunk, $tag ) ) {
763 * Apple's Safari browser performs some unsafe file type autodetection
764 * which can cause legitimate files to be interpreted as HTML if the
765 * web server is not correctly configured to send the right content-type
766 * (or if you're really uploading plain text and octet streams!)
768 * Returns true if Safari would mistake the given file for HTML
769 * when served with a generic content-type.
771 * @param string $filename
774 function triggersSafariBug( $filename ) {
775 $file = fopen( $filename, 'rb' );
776 $chunk = strtolower( fread( $file, 1024 ) );
783 foreach( $tags as $tag ) {
784 if( false !== strpos( $chunk, $tag ) ) {