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;
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'];
74 *Check for a newly uploaded file.
76 $this->mUploadTempName
= $request->getFileTempName( 'wpUploadFile' );
77 $this->mUploadSize
= $request->getFileSize( 'wpUploadFile' );
78 $this->mOname
= $request->getFileName( 'wpUploadFile' );
79 $this->mSessionKey
= false;
88 global $wgUser, $wgOut;
89 global $wgDisableUploads;
91 /** Show an error message if file upload is disabled */
92 if( $wgDisableUploads ) {
93 $wgOut->addWikiText( wfMsg( 'uploaddisabled' ) );
97 /** Various rights checks */
98 if( ( $wgUser->getID() == 0 )
99 OR $wgUser->isBlocked() ) {
100 $wgOut->errorpage( 'uploadnologin', 'uploadnologintext' );
104 $wgOut->readOnlyPage();
108 if( $this->mReUpload
) {
109 $this->unsaveUploadedFile();
110 $this->mainUploadForm();
111 } else if ( 'submit' == $this->mAction ||
$this->mUpload
) {
112 $this->processUpload();
114 $this->mainUploadForm();
118 /* -------------------------------------------------------------- */
121 * Really do the upload
122 * Checks are made in SpecialUpload::execute()
125 function processUpload() {
126 global $wgUser, $wgOut, $wgLang, $wgContLang;
127 global $wgUploadDirectory;
128 global $wgUseCopyrightUpload, $wgCheckCopyrightUpload;
131 * If there was no filename or a zero size given, give up quick.
133 if( ( trim( $this->mOname
) == '' ) ||
empty( $this->mUploadSize
) ) {
134 return $this->mainUploadForm('<li>'.wfMsg( 'emptyfile' ).'</li>');
138 * When using detailed copyright, if user filled field, assume he
139 * confirmed the upload
141 if ( $wgUseCopyrightUpload ) {
142 $this->mUploadAffirm
= true;
143 if( $wgCheckCopyrightUpload &&
144 ( trim( $this->mUploadCopyStatus
) == '' ||
145 trim( $this->mUploadSource
) == '' ) ) {
146 $this->mUploadAffirm
= false;
150 /** User need to confirm his upload */
151 if( !$this->mUploadAffirm
) {
152 $this->mainUploadForm( wfMsg( 'noaffirmation' ) );
156 # Chop off any directories in the given filename
157 $basename = basename( $this->mOname
);
159 if( preg_match( '/^(.*)\.([^.]*)$/', $basename, $matches ) ) {
160 $partname = $matches[1];
163 $partname = $basename;
167 if ( strlen( $partname ) < 3 ) {
168 $this->mainUploadForm( wfMsg( 'minlength' ) );
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.
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 ) ) );
181 $nt->setNamespace( NS_IMAGE
);
182 $this->mUploadSaveName
= $nt->getDBkey();
185 * If the image is protected, non-sysop users won't be able
186 * to modify it by uploading a new revision.
188 if( !$nt->userCanEdit() ) {
189 return $this->uploadError( wfMsg( 'protectedpage' ) );
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 ) ) );
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.
205 if( !$this->verify( $this->mUploadTempName
, $ext ) ) {
206 return $this->uploadError( wfMsg( 'uploadcorrupt' ) );
210 * Check for non-fatal conditions
212 if ( ! $this->mIgnoreWarning
) {
214 if( $this->mUploadSaveName
!= ucfirst( $filtered ) ) {
215 $warning .= '<li>'.wfMsg( 'badfilename', htmlspecialchars( $this->mUploadSaveName
) ).'</li>';
218 global $wgCheckFileExtensions;
219 if ( $wgCheckFileExtensions ) {
220 if ( ! $this->checkFileExtension( $ext, $wgFileExtensions ) ) {
221 $warning .= '<li>'.wfMsg( 'badfiletype', htmlspecialchars( $ext ) ).'</li>';
225 global $wgUploadSizeWarning;
226 if ( $wgUploadSizeWarning && ( $this->mUploadSize
> $wgUploadSizeWarning ) ) {
227 $warning .= '<li>'.wfMsg( 'largefile' ).'</li>';
229 if ( $this->mUploadSize
== 0 ) {
230 $warning .= '<li>'.wfMsg( 'emptyfile' ).'</li>';
233 if( $nt->getArticleID() ) {
235 $sk = $wgUser->getSkin();
236 $dlink = $sk->makeKnownLinkObj( $nt );
237 $warning .= '<li>'.wfMsg( 'fileexists', $dlink ).'</li>';
240 if( $warning != '' ) {
242 * Stash the file in a temporary location; the user can choose
243 * to let it through and we'll complete the upload then.
245 return $this->uploadWarning($warning);
250 * Try actually saving the thing...
251 * It will show an error form on failure.
253 if( $this->saveUploadedFile( $this->mUploadSaveName
,
254 $this->mUploadTempName
,
255 !empty( $this->mSessionKey
) ) ) {
257 * Update the upload log and create the description page
258 * if it's a new file.
260 wfRecordUpload( $this->mUploadSaveName
,
261 $this->mUploadOldVersion
,
263 $this->mUploadDescription
,
264 $this->mUploadCopyStatus
,
265 $this->mUploadSource
);
266 $this->showSuccess();
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.
275 * @todo If the later save fails, we may have disappeared the original file.
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
282 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
283 global $wgUploadDirectory, $wgOut;
285 $dest = wfImageDir( $saveName );
286 $archive = wfImageArchiveDir( $saveName );
287 $this->mSavedFile
= "{$dest}/{$saveName}";
289 if( is_file( $this->mSavedFile
) ) {
290 $this->mUploadOldVersion
= gmdate( 'YmdHis' ) . "!{$saveName}";
292 if( !rename( $this->mSavedFile
, "${archive}/{$this->mUploadOldVersion}" ) ) {
293 $wgOut->fileRenameError( $this->mSavedFile
,
294 "${archive}/{$this->mUploadOldVersion}" );
298 $this->mUploadOldVersion
= '';
302 if( !rename( $tempName, $this->mSavedFile
) ) {
303 $wgOut->fileCopyError( $tempName, $this->mSavedFile
);
307 if( !move_uploaded_file( $tempName, $this->mSavedFile
) ) {
308 $wgOut->fileCopyError( $tempName, $this->mSavedFile
);
312 chmod( $this->mSavedFile
, 0644 );
317 * Stash a file in a temporary directory for later processing
318 * after the user has confirmed it.
320 * If the user doesn't explicitly cancel or accept, these files
321 * can accumulate in the temp directory.
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
328 function saveTempUploadedFile( $saveName, $tempName ) {
331 $archive = wfImageArchiveDir( $saveName, 'temp' );
332 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
334 if ( !move_uploaded_file( $tempName, $stash ) ) {
335 $wgOut->fileCopyError( $tempName, $stash );
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.
351 function stashSession() {
352 $stash = $this->saveTempUploadedFile(
353 $this->mUploadSaveName
, $this->mUploadTempName
);
356 # Couldn't save the file.
360 $key = mt_rand( 0, 0x7fffffff );
361 $_SESSION['wsUploadData'][$key] = array(
362 'mUploadTempName' => $stash,
363 'mUploadSize' => $this->mUploadSize
,
364 'mOname' => $this->mOname
);
369 * Remove a temporarily kept file stashed by saveTempUploadedFile().
372 function unsaveUploadedFile() {
373 if ( ! @unlink
( $this->mUploadTempName
) ) {
374 $wgOut->fileDeleteError( $this->mUploadTempName
);
378 /* -------------------------------------------------------------- */
381 * Show some text and linkage on successful upload.
384 function showSuccess() {
385 global $wgUser, $wgOut, $wgContLang;
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 );
392 $wgOut->addHTML( '<h2>' . wfMsg( 'successfulupload' ) . "</h2>\n" );
393 $text = wfMsg( 'fileuploaded', $ilink, $dlink );
394 $wgOut->addHTML( '<p>'.$text."\n" );
395 $wgOut->returnToMain( false );
399 * @param string $error as HTML
402 function uploadError( $error ) {
404 $sub = wfMsg( 'uploadwarning' );
405 $wgOut->addHTML( "<h2>{$sub}</h2>\n" );
406 $wgOut->addHTML( "<h4 class='error'>{$error}</h4>\n" );
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.
414 * @param string $warning as HTML
417 function uploadWarning( $warning ) {
418 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
419 global $wgUseCopyrightUpload;
421 $this->mSessionKey
= $this->stashSession();
422 if( !$this->mSessionKey
) {
423 # Couldn't save file; an error has been displayed so let's go.
427 $sub = wfMsg( 'uploadwarning' );
428 $wgOut->addHTML( "<h2>{$sub}</h2>\n" );
429 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br/>\n" );
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' );
438 if ( $wgUseCopyrightUpload )
441 <input type='hidden' name=\"wpUploadCopyStatus\" value=\"" . htmlspecialchars( $this->mUploadCopyStatus
) . "\" />
442 <input type='hidden' name=\"wpUploadSource\" value=\"" . htmlspecialchars( $this->mUploadSource
) . "\" />
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
) . "\" />
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" );
466 * Displays the main upload form, optionally with a highlighted
467 * error message up at the top.
469 * @param string $msg as HTML
472 function mainUploadForm( $msg='' ) {
473 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
474 global $wgUseCopyrightUpload;
477 $sub = wfMsg( 'uploaderror' );
478 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
479 "<h4 class='error'>{$msg}</h4>\n" );
481 $sub = wfMsg( 'uploadfile' );
482 $wgOut->addHTML( "<h2>{$sub}</h2>\n" );
484 $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
485 $sk = $wgUser->getSkin();
487 $fn = wfMsg( 'filename' );
488 $fd = wfMsg( 'filedesc' );
489 $ulb = wfMsg( 'uploadbtn' );
491 $clink = $sk->makeKnownLink( wfMsgForContent( 'copyrightpage' ),
492 wfMsg( 'copyrightpagename' ) );
493 $ca = wfMsg( 'affirmation', $clink );
494 $iw = wfMsg( 'ignorewarning' );
496 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Upload' );
497 $action = $titleObj->escapeLocalURL();
501 <input tabindex='3' type='checkbox' name=\"wpUploadAffirm\" value=\"1\" id=\"wpUploadAffirm\" />
502 </td><td align='left'><label for=\"wpUploadAffirm\">{$ca}</label></td>
504 if ( $wgUseCopyrightUpload )
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>
511 <td align='right'>". wfMsg ( 'filesource' ) . ":</td>
512 <td><input tabindex='4' type='text' name=\"wpUploadSource\" value=\"" .
513 htmlspecialchars($this->mUploadSource
). "\" size='40' /></td>
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' />
524 <td align='right'>{$fd}:</td><td align='left'>
525 <input tabindex='2' type='text' name=\"wpUploadDescription\" value=\""
526 . htmlspecialchars( $this->mUploadDescription
) . "\" size='40' />
530 <tr><td></td><td align='left'>
531 <input tabindex='5' type='submit' name=\"wpUpload\" value=\"{$ulb}\" />
532 </td></tr></table></form>\n" );
535 /* -------------------------------------------------------------- */
538 * Perform case-insensitive match against a list of file extensions.
539 * Returns true if the extension is in the list.
545 function checkFileExtension( $ext, $list ) {
546 return in_array( strtolower( $ext ), $list );
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.
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
559 function verify( $tmpfile, $extension ) {
560 if( $this->triggersIEbug( $tmpfile ) ) {
564 $fname = 'SpecialUpload::verify';
565 $mergeExtensions = array(
568 $extensionTypes = array(
569 # See http://www.php.net/getimagesize
587 $extension = strtolower( $extension );
588 if( isset( $mergeExtensions[$extension] ) ) {
589 $extension = $mergeExtensions[$extension];
591 wfDebug( "$fname: Testing file '$tmpfile' with given extension '$extension'\n" );
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" );
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" );
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" );
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" );
629 wfDebug( "$fname: all clear; passing.\n" );
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
639 * Returns true if IE is likely to mistake the given file for HTML.
641 * @param string $filename
644 function triggersIEbug( $filename ) {
645 $file = fopen( $filename, 'rb' );
646 $chunk = strtolower( fread( $file, 200 ) );
649 $tags = array( '<html', '<head', '<body', '<script' );
650 foreach( $tags as $tag ) {
651 if( false !== strpos( $chunk, $tag ) ) {