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 * When using detailed copyright, if user filled field, assume he
132 * confirmed the upload
134 if ( $wgUseCopyrightUpload ) {
135 $this->mUploadAffirm
= true;
136 if( $wgCheckCopyrightUpload &&
137 ( trim( $this->mUploadCopyStatus
) == '' ||
138 trim( $this->mUploadSource
) == '' ) ) {
139 $this->mUploadAffirm
= false;
143 /** User need to confirm his upload */
144 if( !$this->mUploadAffirm
) {
145 $this->mainUploadForm( WfMsg( 'noaffirmation' ) );
149 if ( $this->mOname
== '' && !isset($this->mUploadSaveName
) ) {
150 // no filename given!
151 return $this->uploadError('<li>'.wfMsg( 'emptyfile' ).'</li>');
154 # Chop off any directories in the given filename
155 $basename = basename( $this->mOname
);
157 if( preg_match( '/^(.*)\.([^.]*)$/', $basename, $matches ) ) {
158 $partname = $matches[1];
161 $partname = $basename;
165 if ( strlen( $partname ) < 3 ) {
166 $this->mainUploadForm( wfMsg( 'minlength' ) );
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.
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 ) ) );
179 $nt->setNamespace( NS_IMAGE
);
180 $this->mUploadSaveName
= $nt->getDBkey();
183 * If the image is protected, non-sysop users won't be able
184 * to modify it by uploading a new revision.
186 if( !$nt->userCanEdit() ) {
187 return $this->uploadError( wfMsg( 'protectedpage' ) );
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 ) ) );
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.
203 if( !$this->verify( $this->mUploadTempName
, $ext ) ) {
204 return $this->uploadError( wfMsg( 'uploadcorrupt' ) );
208 * Check for non-fatal conditions
210 if ( ! $this->mIgnoreWarning
) {
212 if( $this->mUploadSaveName
!= ucfirst( $filtered ) ) {
213 $warning .= '<li>'.wfMsg( 'badfilename', htmlspecialchars( $this->mUploadSaveName
) ).'</li>';
216 global $wgCheckFileExtensions;
217 if ( $wgCheckFileExtensions ) {
218 if ( ! $this->checkFileExtension( $ext, $wgFileExtensions ) ) {
219 $warning .= '<li>'.wfMsg( 'badfiletype', htmlspecialchars( $ext ) ).'</li>';
223 global $wgUploadSizeWarning;
224 if ( $wgUploadSizeWarning && ( $this->mUploadSize
> $wgUploadSizeWarning ) ) {
225 $warning .= '<li>'.wfMsg( 'largefile' ).'</li>';
227 if ( $this->mUploadSize
== 0 ) {
228 $warning .= '<li>'.wfMsg( 'emptyfile' ).'</li>';
231 if( $nt->getArticleID() ) {
233 $sk = $wgUser->getSkin();
234 $dlink = $sk->makeKnownLinkObj( $nt );
235 $warning .= '<li>'.wfMsg( 'fileexists', $dlink ).'</li>';
238 if( $warning != '' ) {
240 * Stash the file in a temporary location; the user can choose
241 * to let it through and we'll complete the upload then.
243 return $this->uploadWarning($warning);
248 * Try actually saving the thing...
249 * It will show an error form on failure.
251 if( $this->saveUploadedFile( $this->mUploadSaveName
,
252 $this->mUploadTempName
,
253 !empty( $this->mSessionKey
) ) ) {
255 * Update the upload log and create the description page
256 * if it's a new file.
258 wfRecordUpload( $this->mUploadSaveName
,
259 $this->mUploadOldVersion
,
261 $this->mUploadDescription
,
262 $this->mUploadCopyStatus
,
263 $this->mUploadSource
);
264 $this->showSuccess();
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.
273 * @todo If the later save fails, we may have disappeared the original file.
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
280 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
281 global $wgUploadDirectory, $wgOut;
283 $dest = wfImageDir( $saveName );
284 $archive = wfImageArchiveDir( $saveName );
285 $this->mSavedFile
= "{$dest}/{$saveName}";
287 if( is_file( $this->mSavedFile
) ) {
288 $this->mUploadOldVersion
= gmdate( 'YmdHis' ) . "!{$saveName}";
290 if( !rename( $this->mSavedFile
, "${archive}/{$this->mUploadOldVersion}" ) ) {
291 $wgOut->fileRenameError( $this->mSavedFile
,
292 "${archive}/{$this->mUploadOldVersion}" );
296 $this->mUploadOldVersion
= '';
300 if( !rename( $tempName, $this->mSavedFile
) ) {
301 $wgOut->fileCopyError( $tempName, $this->mSavedFile
);
305 if( !move_uploaded_file( $tempName, $this->mSavedFile
) ) {
306 $wgOut->fileCopyError( $tempName, $this->mSavedFile
);
310 chmod( $this->mSavedFile
, 0644 );
315 * Stash a file in a temporary directory for later processing
316 * after the user has confirmed it.
318 * If the user doesn't explicitly cancel or accept, these files
319 * can accumulate in the temp directory.
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
326 function saveTempUploadedFile( $saveName, $tempName ) {
329 $archive = wfImageArchiveDir( $saveName, 'temp' );
330 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
332 if ( !move_uploaded_file( $tempName, $stash ) ) {
333 $wgOut->fileCopyError( $tempName, $stash );
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.
349 function stashSession() {
350 $stash = $this->saveTempUploadedFile(
351 $this->mUploadSaveName
, $this->mUploadTempName
);
354 # Couldn't save the file.
358 $key = mt_rand( 0, 0x7fffffff );
359 $_SESSION['wsUploadData'][$key] = array(
360 'mUploadTempName' => $stash,
361 'mUploadSize' => $this->mUploadSize
,
362 'mOname' => $this->mOname
);
367 * Remove a temporarily kept file stashed by saveTempUploadedFile().
370 function unsaveUploadedFile() {
371 if ( ! @unlink
( $this->mUploadTempName
) ) {
372 $wgOut->fileDeleteError( $this->mUploadTempName
);
376 /* -------------------------------------------------------------- */
379 * Show some text and linkage on successful upload.
382 function showSuccess() {
383 global $wgUser, $wgOut, $wgContLang;
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 );
390 $wgOut->addHTML( '<h2>' . wfMsg( 'successfulupload' ) . "</h2>\n" );
391 $text = wfMsg( 'fileuploaded', $ilink, $dlink );
392 $wgOut->addHTML( '<p>'.$text."\n" );
393 $wgOut->returnToMain( false );
397 * @param string $error as HTML
400 function uploadError( $error ) {
402 $sub = wfMsg( 'uploadwarning' );
403 $wgOut->addHTML( "<h2>{$sub}</h2>\n" );
404 $wgOut->addHTML( "<h4 style='error'>{$error}</h4>\n" );
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.
412 * @param string $warning as HTML
415 function uploadWarning( $warning ) {
416 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
417 global $wgUseCopyrightUpload;
419 $this->mSessionKey
= $this->stashSession();
420 if( !$this->mSessionKey
) {
421 # Couldn't save file; an error has been displayed so let's go.
425 $sub = wfMsg( 'uploadwarning' );
426 $wgOut->addHTML( "<h2>{$sub}</h2>\n" );
427 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br/>\n" );
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' );
436 if ( $wgUseCopyrightUpload )
439 <input type='hidden' name=\"wpUploadCopyStatus\" value=\"" . htmlspecialchars( $this->mUploadCopyStatus
) . "\" />
440 <input type='hidden' name=\"wpUploadSource\" value=\"" . htmlspecialchars( $this->mUploadSource
) . "\" />
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
) . "\" />
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" );
463 * Displays the main upload form, optionally with a highlighted
464 * error message up at the top.
466 * @param string $msg as HTML
469 function mainUploadForm( $msg='' ) {
470 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
471 global $wgUseCopyrightUpload;
474 $sub = wfMsg( 'uploaderror' );
475 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
476 "<h4 style='error'>{$msg}</h4>\n" );
478 $sub = wfMsg( 'uploadfile' );
479 $wgOut->addHTML( "<h2>{$sub}</h2>\n" );
481 $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
482 $sk = $wgUser->getSkin();
484 $fn = wfMsg( 'filename' );
485 $fd = wfMsg( 'filedesc' );
486 $ulb = wfMsg( 'uploadbtn' );
488 $clink = $sk->makeKnownLink( wfMsgForContent( 'copyrightpage' ),
489 wfMsg( 'copyrightpagename' ) );
490 $ca = wfMsg( 'affirmation', $clink );
491 $iw = wfMsg( 'ignorewarning' );
493 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Upload' );
494 $action = $titleObj->escapeLocalURL();
498 <input tabindex='3' type='checkbox' name=\"wpUploadAffirm\" value=\"1\" id=\"wpUploadAffirm\" />
499 </td><td align='left'><label for=\"wpUploadAffirm\">{$ca}</label></td>
501 if ( $wgUseCopyrightUpload )
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>
508 <td align='right'>". wfMsg ( 'filesource' ) . ":</td>
509 <td><input tabindex='4' type='text' name=\"wpUploadSource\" value=\"" .
510 htmlspecialchars($this->mUploadSource
). "\" size='40' /></td>
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' />
521 <td align='right'>{$fd}:</td><td align='left'>
522 <input tabindex='2' type='text' name=\"wpUploadDescription\" value=\""
523 . htmlspecialchars( $this->mUploadDescription
) . "\" size='40' />
527 <tr><td></td><td align='left'>
528 <input tabindex='5' type='submit' name=\"wpUpload\" value=\"{$ulb}\" />
529 </td></tr></table></form>\n" );
532 /* -------------------------------------------------------------- */
535 * Perform case-insensitive match against a list of file extensions.
536 * Returns true if the extension is in the list.
542 function checkFileExtension( $ext, $list ) {
543 return in_array( strtolower( $ext ), $list );
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.
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
556 function verify( $tmpfile, $extension ) {
557 if( $this->triggersIEbug( $tmpfile ) ) {
561 $fname = 'SpecialUpload::verify';
562 $mergeExtensions = array(
565 $extensionTypes = array(
566 # See http://www.php.net/getimagesize
584 $extension = strtolower( $extension );
585 if( isset( $mergeExtensions[$extension] ) ) {
586 $extension = $mergeExtensions[$extension];
588 wfDebug( "$fname: Testing file '$tmpfile' with given extension '$extension'\n" );
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" );
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" );
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" );
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" );
626 wfDebug( "$fname: all clear; passing.\n" );
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
636 * Returns true if IE is likely to mistake the given file for HTML.
638 * @param string $filename
641 function triggersIEbug( $filename ) {
642 $file = fopen( $filename, 'rb' );
643 $chunk = strtolower( fread( $file, 200 ) );
646 $tags = array( '<html', '<head', '<body', '<script' );
647 foreach( $tags as $tag ) {
648 if( false !== strpos( $chunk, $tag ) ) {