Revert r23523, r23524, stabbed by Tim :-(
[lhc/web/wiklou.git] / includes / SpecialUpload.php
1 <?php
2 /**
3 *
4 * @addtogroup SpecialPage
5 */
6
7
8 /**
9 * Entry point
10 */
11 function wfSpecialUpload() {
12 global $wgRequest;
13 $form = new UploadForm( $wgRequest );
14 $form->execute();
15 }
16
17 /**
18 * implements Special:Upload
19 * @addtogroup SpecialPage
20 */
21 class UploadForm {
22 /**#@+
23 * @access private
24 */
25 var $mComment, $mLicense, $mIgnoreWarning, $mCurlError;
26 var $mDestName, $mTempPath, $mFileSize, $mFileProps;
27 var $mCopyrightStatus, $mCopyrightSource, $mReUpload, $mAction, $mUploadClicked;
28 var $mSrcName, $mSessionKey, $mStashed, $mDesiredDestName, $mRemoveTempFile, $mSourceType;
29 var $mCurlDestHandle;
30 var $mLocalFile;
31
32 # Placeholders for text injection by hooks (must be HTML)
33 # extensions should take care to _append_ to the present value
34 var $uploadFormTextTop;
35 var $uploadFormTextAfterSummary;
36
37 const SESSION_VERSION = 1;
38 /**#@-*/
39
40 /**
41 * Constructor : initialise object
42 * Get data POSTed through the form and assign them to the object
43 * @param $request Data posted.
44 */
45 function UploadForm( &$request ) {
46 global $wgAllowCopyUploads;
47 $this->mDesiredDestName = $request->getText( 'wpDestFile' );
48 $this->mIgnoreWarning = $request->getCheck( 'wpIgnoreWarning' );
49
50 if( !$request->wasPosted() ) {
51 # GET requests just give the main form; no data except wpDestfile.
52 return;
53 }
54
55 # Placeholders for text injection by hooks (empty per default)
56 $this->uploadFormTextTop = "";
57 $this->uploadFormTextAfterSummary = "";
58
59 $this->mReUpload = $request->getCheck( 'wpReUpload' );
60 $this->mUploadClicked = $request->getCheck( 'wpUpload' );
61
62 $this->mComment = $request->getText( 'wpUploadDescription' );
63 $this->mLicense = $request->getText( 'wpLicense' );
64 $this->mCopyrightStatus = $request->getText( 'wpUploadCopyStatus' );
65 $this->mCopyrightSource = $request->getText( 'wpUploadSource' );
66 $this->mWatchthis = $request->getBool( 'wpWatchthis' );
67 $this->mSourceType = $request->getText( 'wpSourceType' );
68 wfDebug( "UploadForm: watchthis is: '$this->mWatchthis'\n" );
69
70 $this->mAction = $request->getVal( 'action' );
71
72 $this->mSessionKey = $request->getInt( 'wpSessionKey' );
73 if( !empty( $this->mSessionKey ) &&
74 isset( $_SESSION['wsUploadData'][$this->mSessionKey]['version'] ) &&
75 $_SESSION['wsUploadData'][$this->mSessionKey]['version'] == self::SESSION_VERSION ) {
76 /**
77 * Confirming a temporarily stashed upload.
78 * We don't want path names to be forged, so we keep
79 * them in the session on the server and just give
80 * an opaque key to the user agent.
81 */
82 $data = $_SESSION['wsUploadData'][$this->mSessionKey];
83 $this->mTempPath = $data['mTempPath'];
84 $this->mFileSize = $data['mFileSize'];
85 $this->mSrcName = $data['mSrcName'];
86 $this->mFileProps = $data['mFileProps'];
87 $this->mCurlError = 0/*UPLOAD_ERR_OK*/;
88 $this->mStashed = true;
89 $this->mRemoveTempFile = false;
90 } else {
91 /**
92 *Check for a newly uploaded file.
93 */
94 if( $wgAllowCopyUploads && $this->mSourceType == 'web' ) {
95 $this->initializeFromUrl( $request );
96 } else {
97 $this->initializeFromUpload( $request );
98 }
99 }
100 }
101
102 /**
103 * Initialize the uploaded file from PHP data
104 * @access private
105 */
106 function initializeFromUpload( $request ) {
107 $this->mTempPath = $request->getFileTempName( 'wpUploadFile' );
108 $this->mFileSize = $request->getFileSize( 'wpUploadFile' );
109 $this->mSrcName = $request->getFileName( 'wpUploadFile' );
110 $this->mCurlError = $request->getUploadError( 'wpUploadFile' );
111 $this->mSessionKey = false;
112 $this->mStashed = false;
113 $this->mRemoveTempFile = false; // PHP will handle this
114 }
115
116 /**
117 * Copy a web file to a temporary file
118 * @access private
119 */
120 function initializeFromUrl( $request ) {
121 global $wgTmpDirectory;
122 $url = $request->getText( 'wpUploadFileURL' );
123 $local_file = tempnam( $wgTmpDirectory, 'WEBUPLOAD' );
124
125 $this->mTempPath = $local_file;
126 $this->mFileSize = 0; # Will be set by curlCopy
127 $this->mCurlError = $this->curlCopy( $url, $local_file );
128 $this->mSrcName = array_pop( explode( '/', $url ) );
129 $this->mSessionKey = false;
130 $this->mStashed = false;
131
132 // PHP won't auto-cleanup the file
133 $this->mRemoveTempFile = file_exists( $local_file );
134 }
135
136 /**
137 * Safe copy from URL
138 * Returns true if there was an error, false otherwise
139 */
140 private function curlCopy( $url, $dest ) {
141 global $wgUser, $wgOut;
142
143 if( !$wgUser->isAllowed( 'upload_by_url' ) ) {
144 $wgOut->permissionRequired( 'upload_by_url' );
145 return true;
146 }
147
148 # Maybe remove some pasting blanks :-)
149 $url = trim( $url );
150 if( stripos($url, 'http://') !== 0 && stripos($url, 'ftp://') !== 0 ) {
151 # Only HTTP or FTP URLs
152 $wgOut->errorPage( 'upload-proto-error', 'upload-proto-error-text' );
153 return true;
154 }
155
156 # Open temporary file
157 $this->mCurlDestHandle = @fopen( $this->mTempPath, "wb" );
158 if( $this->mCurlDestHandle === false ) {
159 # Could not open temporary file to write in
160 $wgOut->errorPage( 'upload-file-error', 'upload-file-error-text');
161 return true;
162 }
163
164 $ch = curl_init();
165 curl_setopt( $ch, CURLOPT_HTTP_VERSION, 1.0); # Probably not needed, but apparently can work around some bug
166 curl_setopt( $ch, CURLOPT_TIMEOUT, 10); # 10 seconds timeout
167 curl_setopt( $ch, CURLOPT_LOW_SPEED_LIMIT, 512); # 0.5KB per second minimum transfer speed
168 curl_setopt( $ch, CURLOPT_URL, $url);
169 curl_setopt( $ch, CURLOPT_WRITEFUNCTION, array( $this, 'uploadCurlCallback' ) );
170 curl_exec( $ch );
171 $error = curl_errno( $ch ) ? true : false;
172 $errornum = curl_errno( $ch );
173 // if ( $error ) print curl_error ( $ch ) ; # Debugging output
174 curl_close( $ch );
175
176 fclose( $this->mCurlDestHandle );
177 unset( $this->mCurlDestHandle );
178 if( $error ) {
179 unlink( $dest );
180 if( wfEmptyMsg( "upload-curl-error$errornum", wfMsg("upload-curl-error$errornum") ) )
181 $wgOut->errorPage( 'upload-misc-error', 'upload-misc-error-text' );
182 else
183 $wgOut->errorPage( "upload-curl-error$errornum", "upload-curl-error$errornum-text" );
184 }
185
186 return $error;
187 }
188
189 /**
190 * Callback function for CURL-based web transfer
191 * Write data to file unless we've passed the length limit;
192 * if so, abort immediately.
193 * @access private
194 */
195 function uploadCurlCallback( $ch, $data ) {
196 global $wgMaxUploadSize;
197 $length = strlen( $data );
198 $this->mFileSize += $length;
199 if( $this->mFileSize > $wgMaxUploadSize ) {
200 return 0;
201 }
202 fwrite( $this->mCurlDestHandle, $data );
203 return $length;
204 }
205
206 /**
207 * Start doing stuff
208 * @access public
209 */
210 function execute() {
211 global $wgUser, $wgOut;
212 global $wgEnableUploads;
213
214 # Check uploading enabled
215 if( !$wgEnableUploads ) {
216 $wgOut->showErrorPage( 'uploaddisabled', 'uploaddisabledtext', array( $this->mDesiredDestName ) );
217 return;
218 }
219
220 # Check permissions
221 if( !$wgUser->isAllowed( 'upload' ) ) {
222 if( !$wgUser->isLoggedIn() ) {
223 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
224 } else {
225 $wgOut->permissionRequired( 'upload' );
226 }
227 return;
228 }
229
230 # Check blocks
231 if( $wgUser->isBlocked() ) {
232 $wgOut->blockedPage();
233 return;
234 }
235
236 if( wfReadOnly() ) {
237 $wgOut->readOnlyPage();
238 return;
239 }
240
241 if( $this->mReUpload ) {
242 if( !$this->unsaveUploadedFile() ) {
243 return;
244 }
245 $this->mainUploadForm();
246 } else if( 'submit' == $this->mAction || $this->mUploadClicked ) {
247 $this->processUpload();
248 } else {
249 $this->mainUploadForm();
250 }
251
252 $this->cleanupTempFile();
253 }
254
255 /* -------------------------------------------------------------- */
256
257 /**
258 * Really do the upload
259 * Checks are made in SpecialUpload::execute()
260 * @access private
261 */
262 function processUpload() {
263 global $wgUser, $wgOut;
264
265 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) )
266 {
267 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file." );
268 return false;
269 }
270
271 /* Check for PHP error if any, requires php 4.2 or newer */
272 if( $this->mCurlError == 1/*UPLOAD_ERR_INI_SIZE*/ ) {
273 $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
274 return;
275 }
276
277 /**
278 * If there was no filename or a zero size given, give up quick.
279 */
280 if( trim( $this->mSrcName ) == '' || empty( $this->mFileSize ) ) {
281 $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
282 return;
283 }
284
285 # Chop off any directories in the given filename
286 if( $this->mDesiredDestName ) {
287 $basename = wfBaseName( $this->mDesiredDestName );
288 } else {
289 $basename = wfBaseName( $this->mSrcName );
290 }
291
292 /**
293 * We'll want to blacklist against *any* 'extension', and use
294 * only the final one for the whitelist.
295 */
296 list( $partname, $ext ) = $this->splitExtensions( $basename );
297
298 if( count( $ext ) ) {
299 $finalExt = $ext[count( $ext ) - 1];
300 } else {
301 $finalExt = '';
302 }
303
304 # If there was more than one "extension", reassemble the base
305 # filename to prevent bogus complaints about length
306 if( count( $ext ) > 1 ) {
307 for( $i = 0; $i < count( $ext ) - 1; $i++ )
308 $partname .= '.' . $ext[$i];
309 }
310
311 if( strlen( $partname ) < 1 ) {
312 $this->mainUploadForm( wfMsgHtml( 'minlength1' ) );
313 return;
314 }
315
316 /**
317 * Filter out illegal characters, and try to make a legible name
318 * out of it. We'll strip some silently that Title would die on.
319 */
320 $filtered = preg_replace ( "/[^".Title::legalChars()."]|:/", '-', $basename );
321 $nt = Title::makeTitleSafe( NS_IMAGE, $filtered );
322 if( is_null( $nt ) ) {
323 $this->uploadError( wfMsgWikiHtml( 'illegalfilename', htmlspecialchars( $filtered ) ) );
324 return;
325 }
326 $this->mLocalFile = wfLocalFile( $nt );
327 $this->mDestName = $this->mLocalFile->getName();
328
329 /**
330 * If the image is protected, non-sysop users won't be able
331 * to modify it by uploading a new revision.
332 */
333 if( !$nt->userCan( 'edit' ) ) {
334 return $this->uploadError( wfMsgWikiHtml( 'protectedpage' ) );
335 }
336
337 /**
338 * In some cases we may forbid overwriting of existing files.
339 */
340 $overwrite = $this->checkOverwrite( $this->mDestName );
341 if( WikiError::isError( $overwrite ) ) {
342 return $this->uploadError( $overwrite->toString() );
343 }
344
345 /* Don't allow users to override the blacklist (check file extension) */
346 global $wgStrictFileExtensions;
347 global $wgFileExtensions, $wgFileBlacklist;
348 if ($finalExt == '') {
349 return $this->uploadError( wfMsgExt( 'filetype-missing', array ( 'parseinline' ) ) );
350 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
351 ($wgStrictFileExtensions && !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
352 return $this->uploadError( wfMsgExt( 'filetype-badtype', array ( 'parseinline' ),
353 htmlspecialchars( $finalExt ), implode ( ', ', $wgFileExtensions ) ) );
354 }
355
356 /**
357 * Look at the contents of the file; if we can recognize the
358 * type but it's corrupt or data of the wrong type, we should
359 * probably not accept it.
360 */
361 if( !$this->mStashed ) {
362 $this->mFileProps = File::getPropsFromPath( $this->mTempPath, $finalExt );
363 $this->checkMacBinary();
364 $veri = $this->verify( $this->mTempPath, $finalExt );
365
366 if( $veri !== true ) { //it's a wiki error...
367 return $this->uploadError( $veri->toString() );
368 }
369
370 /**
371 * Provide an opportunity for extensions to add futher checks
372 */
373 $error = '';
374 if( !wfRunHooks( 'UploadVerification',
375 array( $this->mDestName, $this->mTempPath, &$error ) ) ) {
376 return $this->uploadError( $error );
377 }
378 }
379
380
381 /**
382 * Check for non-fatal conditions
383 */
384 if ( ! $this->mIgnoreWarning ) {
385 $warning = '';
386
387 global $wgCapitalLinks;
388 if( $wgCapitalLinks ) {
389 $filtered = ucfirst( $filtered );
390 }
391 if( $this->mDestName != $filtered ) {
392 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mDestName ) ).'</li>';
393 }
394
395 global $wgCheckFileExtensions;
396 if ( $wgCheckFileExtensions ) {
397 if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
398 $warning .= '<li>'.wfMsgExt( 'filetype-badtype', array ( 'parseinline' ),
399 htmlspecialchars( $finalExt ), implode ( ', ', $wgFileExtensions ) ).'</li>';
400 }
401 }
402
403 global $wgUploadSizeWarning;
404 if ( $wgUploadSizeWarning && ( $this->mFileSize > $wgUploadSizeWarning ) ) {
405 $skin = $wgUser->getSkin();
406 $wsize = $skin->formatSize( $wgUploadSizeWarning );
407 $asize = $skin->formatSize( $this->mFileSize );
408 $warning .= '<li>' . wfMsgHtml( 'large-file', $wsize, $asize ) . '</li>';
409 }
410 if ( $this->mFileSize == 0 ) {
411 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
412 }
413
414 global $wgUser;
415 $sk = $wgUser->getSkin();
416
417 // Check for uppercase extension. We allow these filenames but check if an image
418 // with lowercase extension exists already
419 if ( $finalExt != strtolower( $finalExt ) ) {
420 $nt_lc = Title::newFromText( $partname . '.' . strtolower( $finalExt ) );
421 $image_lc = wfLocalFile( $nt_lc );
422 }
423
424 if( $this->mLocalFile->exists() ) {
425 $dlink = $sk->makeKnownLinkObj( $nt );
426 if ( $this->mLocalFile->allowInlineDisplay() ) {
427 $dlink2 = $sk->makeImageLinkObj( $nt, wfMsgExt( 'fileexists-thumb', 'parseinline', $dlink ),
428 $nt->getText(), 'right', array(), false, true );
429 } elseif ( !$this->mLocalFile->allowInlineDisplay() && $this->mLocalFile->isSafeFile() ) {
430 $icon = $this->mLocalFile->iconThumb();
431 $dlink2 = '<div style="float:right" id="mw-media-icon"><a href="' . $this->mLocalFile->getURL() . '">' .
432 $icon->toHtml() . '</a><br />' . $dlink . '</div>';
433 } else {
434 $dlink2 = '';
435 }
436
437 $warning .= '<li>' . wfMsgExt( 'fileexists', 'parseline', $dlink ) . '</li>' . $dlink2;
438
439 } elseif ( isset( $image_lc) && $image_lc->exists() ) {
440 # Check if image with lowercase extension exists.
441 # It's not forbidden but in 99% it makes no sense to upload the same filename with uppercase extension
442 $dlink = $sk->makeKnownLinkObj( $nt_lc );
443 if ( $image_lc->allowInlineDisplay() ) {
444 $dlink2 = $sk->makeImageLinkObj( $nt_lc, wfMsgExt( 'fileexists-thumb', 'parseinline', $dlink ),
445 $nt_lc->getText(), 'right', array(), false, true );
446 } elseif ( !$image_lc->allowInlineDisplay() && $image_lc->isSafeFile() ) {
447 $icon = $image_lc->iconThumb();
448 $dlink2 = '<div style="float:right" id="mw-media-icon"><a href="' . $image_lc->getURL() . '">' .
449 $icon->toHtml() . '</a><br />' . $dlink . '</div>';
450 } else {
451 $dlink2 = '';
452 }
453
454 $warning .= '<li>' . wfMsgExt( 'fileexists-extension', 'parsemag' , $partname . '.'
455 . $finalExt , $dlink ) . '</li>' . $dlink2;
456
457 } elseif ( ( substr( $partname , 3, 3 ) == 'px-' || substr( $partname , 2, 3 ) == 'px-' )
458 && ereg( "[0-9]{2}" , substr( $partname , 0, 2) ) )
459 {
460 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
461 $nt_thb = Title::newFromText( substr( $partname , strpos( $partname , '-' ) +1 ) . '.' . $finalExt );
462 $image_thb = wfLocalFile( $nt_thb );
463 if ($image_thb->exists() ) {
464 # Check if an image without leading '180px-' (or similiar) exists
465 $dlink = $sk->makeKnownLinkObj( $nt_thb);
466 if ( $image_thb->allowInlineDisplay() ) {
467 $dlink2 = $sk->makeImageLinkObj( $nt_thb,
468 wfMsgExt( 'fileexists-thumb', 'parseinline', $dlink ),
469 $nt_thb->getText(), 'right', array(), false, true );
470 } elseif ( !$image_thb->allowInlineDisplay() && $image_thb->isSafeFile() ) {
471 $icon = $image_thb->iconThumb();
472 $dlink2 = '<div style="float:right" id="mw-media-icon"><a href="' .
473 $image_thb->getURL() . '">' . $icon->toHtml() . '</a><br />' .
474 $dlink . '</div>';
475 } else {
476 $dlink2 = '';
477 }
478
479 $warning .= '<li>' . wfMsgExt( 'fileexists-thumbnail-yes', 'parsemag', $dlink ) .
480 '</li>' . $dlink2;
481 } else {
482 # Image w/o '180px-' does not exists, but we do not like these filenames
483 $warning .= '<li>' . wfMsgExt( 'file-thumbnail-no', 'parseinline' ,
484 substr( $partname , 0, strpos( $partname , '-' ) +1 ) ) . '</li>';
485 }
486 }
487 if ( $this->mLocalFile->wasDeleted() ) {
488 # If the file existed before and was deleted, warn the user of this
489 # Don't bother doing so if the image exists now, however
490 $ltitle = SpecialPage::getTitleFor( 'Log' );
491 $llink = $sk->makeKnownLinkObj( $ltitle, wfMsgHtml( 'deletionlog' ),
492 'type=delete&page=' . $nt->getPrefixedUrl() );
493 $warning .= wfOpenElement( 'li' ) . wfMsgWikiHtml( 'filewasdeleted', $llink ) .
494 wfCloseElement( 'li' );
495 }
496
497 if( $warning != '' ) {
498 /**
499 * Stash the file in a temporary location; the user can choose
500 * to let it through and we'll complete the upload then.
501 */
502 return $this->uploadWarning( $warning );
503 }
504 }
505
506 /**
507 * Try actually saving the thing...
508 * It will show an error form on failure.
509 */
510 $pageText = self::getInitialPageText( $this->mComment, $this->mLicense,
511 $this->mCopyrightStatus, $this->mCopyrightSource );
512
513 $status = $this->mLocalFile->upload( $this->mTempPath, $this->mComment, $pageText,
514 File::DELETE_SOURCE, $this->mFileProps );
515 if ( WikiError::isError( $status ) ) {
516 $this->showError( $status );
517 } else {
518 if ( $this->mWatchthis ) {
519 global $wgUser;
520 $wgUser->addWatch( $this->mLocalFile->getTitle() );
521 }
522 if ( $status === '' ) {
523 // New upload, redirect to description page
524 $wgOut->redirect( $this->mLocalFile->getTitle()->getFullURL() );
525 } else {
526 // Reupload, show success page
527 $this->showSuccess();
528 }
529 wfRunHooks( 'UploadComplete', array( &$img ) );
530 }
531 }
532
533 /**
534 * Stash a file in a temporary directory for later processing
535 * after the user has confirmed it.
536 *
537 * If the user doesn't explicitly cancel or accept, these files
538 * can accumulate in the temp directory.
539 *
540 * @param string $saveName - the destination filename
541 * @param string $tempName - the source temporary file to save
542 * @return string - full path the stashed file, or false on failure
543 * @access private
544 */
545 function saveTempUploadedFile( $saveName, $tempName ) {
546 global $wgOut;
547 $repo = RepoGroup::singleton()->getLocalRepo();
548 $result = $repo->storeTemp( $saveName, $tempName );
549 if ( WikiError::isError( $result ) ) {
550 $this->showError( $result );
551 return false;
552 } else {
553 return $result;
554 }
555 }
556
557 /**
558 * Stash a file in a temporary directory for later processing,
559 * and save the necessary descriptive info into the session.
560 * Returns a key value which will be passed through a form
561 * to pick up the path info on a later invocation.
562 *
563 * @return int
564 * @access private
565 */
566 function stashSession() {
567 $stash = $this->saveTempUploadedFile( $this->mDestName, $this->mTempPath );
568
569 if( !$stash ) {
570 # Couldn't save the file.
571 return false;
572 }
573
574 $key = mt_rand( 0, 0x7fffffff );
575 $_SESSION['wsUploadData'][$key] = array(
576 'mTempPath' => $stash,
577 'mFileSize' => $this->mFileSize,
578 'mSrcName' => $this->mSrcName,
579 'mFileProps' => $this->mFileProps,
580 'version' => self::SESSION_VERSION,
581 );
582 return $key;
583 }
584
585 /**
586 * Remove a temporarily kept file stashed by saveTempUploadedFile().
587 * @access private
588 * @return success
589 */
590 function unsaveUploadedFile() {
591 global $wgOut;
592 $repo = RepoGroup::singleton()->getLocalRepo();
593 $success = $repo->freeTemp( $this->mTempPath );
594 if ( ! $success ) {
595 $wgOut->showFileDeleteError( $this->mTempPath );
596 return false;
597 } else {
598 return true;
599 }
600 }
601
602 /* -------------------------------------------------------------- */
603
604 /**
605 * Show some text and linkage on successful upload.
606 * @access private
607 */
608 function showSuccess() {
609 global $wgUser, $wgOut, $wgContLang;
610
611 $sk = $wgUser->getSkin();
612 $ilink = $sk->makeMediaLinkObj( $this->mLocalFile->getTitle() );
613 $dname = $wgContLang->getNsText( NS_IMAGE ) . ':'.$this->mDestName;
614 $dlink = $sk->makeKnownLink( $dname, $dname );
615
616 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'successfulupload' ) . "</h2>\n" );
617 $text = wfMsgWikiHtml( 'fileuploaded', $ilink, $dlink );
618 $wgOut->addHTML( $text );
619 $wgOut->returnToMain( false );
620 }
621
622 /**
623 * @param string $error as HTML
624 * @access private
625 */
626 function uploadError( $error ) {
627 global $wgOut;
628 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
629 $wgOut->addHTML( "<span class='error'>{$error}</span>\n" );
630 }
631
632 /**
633 * There's something wrong with this file, not enough to reject it
634 * totally but we require manual intervention to save it for real.
635 * Stash it away, then present a form asking to confirm or cancel.
636 *
637 * @param string $warning as HTML
638 * @access private
639 */
640 function uploadWarning( $warning ) {
641 global $wgOut;
642 global $wgUseCopyrightUpload;
643
644 $this->mSessionKey = $this->stashSession();
645 if( !$this->mSessionKey ) {
646 # Couldn't save file; an error has been displayed so let's go.
647 return;
648 }
649
650 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
651 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
652
653 $save = wfMsgHtml( 'savefile' );
654 $reupload = wfMsgHtml( 'reupload' );
655 $iw = wfMsgWikiHtml( 'ignorewarning' );
656 $reup = wfMsgWikiHtml( 'reuploaddesc' );
657 $titleObj = SpecialPage::getTitleFor( 'Upload' );
658 $action = $titleObj->escapeLocalURL( 'action=submit' );
659
660 if ( $wgUseCopyrightUpload )
661 {
662 $copyright = "
663 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mCopyrightStatus ) . "\" />
664 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mCopyrightSource ) . "\" />
665 ";
666 } else {
667 $copyright = "";
668 }
669
670 $wgOut->addHTML( "
671 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
672 <input type='hidden' name='wpIgnoreWarning' value='1' />
673 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey ) . "\" />
674 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mComment ) . "\" />
675 <input type='hidden' name='wpLicense' value=\"" . htmlspecialchars( $this->mLicense ) . "\" />
676 <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDesiredDestName ) . "\" />
677 <input type='hidden' name='wpWatchthis' value=\"" . htmlspecialchars( intval( $this->mWatchthis ) ) . "\" />
678 {$copyright}
679 <table border='0'>
680 <tr>
681 <tr>
682 <td align='right'>
683 <input tabindex='2' type='submit' name='wpUpload' value=\"$save\" />
684 </td>
685 <td align='left'>$iw</td>
686 </tr>
687 <tr>
688 <td align='right'>
689 <input tabindex='2' type='submit' name='wpReUpload' value=\"{$reupload}\" />
690 </td>
691 <td align='left'>$reup</td>
692 </tr>
693 </tr>
694 </table></form>\n" );
695 }
696
697 /**
698 * Displays the main upload form, optionally with a highlighted
699 * error message up at the top.
700 *
701 * @param string $msg as HTML
702 * @access private
703 */
704 function mainUploadForm( $msg='' ) {
705 global $wgOut, $wgUser;
706 global $wgUseCopyrightUpload;
707 global $wgRequest, $wgAllowCopyUploads;
708
709 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) )
710 {
711 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
712 return false;
713 }
714
715 $cols = intval($wgUser->getOption( 'cols' ));
716 $ew = $wgUser->getOption( 'editwidth' );
717 if ( $ew ) $ew = " style=\"width:100%\"";
718 else $ew = '';
719
720 if ( '' != $msg ) {
721 $sub = wfMsgHtml( 'uploaderror' );
722 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
723 "<span class='error'>{$msg}</span>\n" );
724 }
725 $wgOut->addHTML( '<div id="uploadtext">' );
726 $wgOut->addWikiText( wfMsgNoTrans( 'uploadtext', $this->mDesiredDestName ) );
727 $wgOut->addHTML( '</div>' );
728
729 $sourcefilename = wfMsgHtml( 'sourcefilename' );
730 $destfilename = wfMsgHtml( 'destfilename' );
731 $summary = wfMsgWikiHtml( 'fileuploadsummary' );
732
733 $licenses = new Licenses();
734 $license = wfMsgExt( 'license', array( 'parseinline' ) );
735 $nolicense = wfMsgHtml( 'nolicense' );
736 $licenseshtml = $licenses->getHtml();
737
738 $ulb = wfMsgHtml( 'uploadbtn' );
739
740
741 $titleObj = SpecialPage::getTitleFor( 'Upload' );
742 $action = $titleObj->escapeLocalURL();
743
744 $encDestName = htmlspecialchars( $this->mDesiredDestName );
745
746 $watchChecked =
747 ( $wgUser->getOption( 'watchdefault' ) ||
748 ( $wgUser->getOption( 'watchcreations' ) && $this->mDesiredDestName == '' ) )
749 ? 'checked="checked"'
750 : '';
751 $warningChecked = $this->mIgnoreWarning ? 'checked' : '';
752
753 // Prepare form for upload or upload/copy
754 if( $wgAllowCopyUploads && $wgUser->isAllowed( 'upload_by_url' ) ) {
755 $filename_form =
756 "<input type='radio' id='wpSourceTypeFile' name='wpSourceType' value='file' " .
757 "onchange='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\")' checked />" .
758 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
759 "onfocus='" .
760 "toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\");" .
761 "toggle_element_check(\"wpSourceTypeFile\",\"wpSourceTypeURL\")'" .
762 ($this->mDesiredDestName?"":"onchange='fillDestFilename(\"wpUploadFile\")' ") . "size='40' />" .
763 wfMsgHTML( 'upload_source_file' ) . "<br/>" .
764 "<input type='radio' id='wpSourceTypeURL' name='wpSourceType' value='web' " .
765 "onchange='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\")' />" .
766 "<input tabindex='1' type='text' name='wpUploadFileURL' id='wpUploadFileURL' " .
767 "onfocus='" .
768 "toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\");" .
769 "toggle_element_check(\"wpSourceTypeURL\",\"wpSourceTypeFile\")'" .
770 ($this->mDesiredDestName?"":"onchange='fillDestFilename(\"wpUploadFileURL\")' ") . "size='40' DISABLED />" .
771 wfMsgHtml( 'upload_source_url' ) ;
772 } else {
773 $filename_form =
774 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
775 ($this->mDesiredDestName?"":"onchange='fillDestFilename(\"wpUploadFile\")' ") .
776 "size='40' />" .
777 "<input type='hidden' name='wpSourceType' value='file' />" ;
778 }
779 $encComment = htmlspecialchars( $this->mComment );
780
781 $wgOut->addHTML( <<<EOT
782 <form id='upload' method='post' enctype='multipart/form-data' action="$action">
783 <table border='0'>
784 <tr>
785 {$this->uploadFormTextTop}
786 <td align='right' valign='top'><label for='wpUploadFile'>{$sourcefilename}:</label></td>
787 <td align='left'>
788 {$filename_form}
789 </td>
790 </tr>
791 <tr>
792 <td align='right'><label for='wpDestFile'>{$destfilename}:</label></td>
793 <td align='left'>
794 <input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='40' value="$encDestName" />
795 </td>
796 </tr>
797 <tr>
798 <td align='right'><label for='wpUploadDescription'>{$summary}</label></td>
799 <td align='left'>
800 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6'
801 cols='{$cols}'{$ew}>$encComment</textarea>
802 {$this->uploadFormTextAfterSummary}
803 </td>
804 </tr>
805 <tr>
806 EOT
807 );
808
809 if ( $licenseshtml != '' ) {
810 global $wgStylePath;
811 $wgOut->addHTML( "
812 <td align='right'><label for='wpLicense'>$license:</label></td>
813 <td align='left'>
814 <script type='text/javascript' src=\"$wgStylePath/common/upload.js\"></script>
815 <select name='wpLicense' id='wpLicense' tabindex='4'
816 onchange='licenseSelectorCheck()'>
817 <option value=''>$nolicense</option>
818 $licenseshtml
819 </select>
820 </td>
821 </tr>
822 <tr>
823 ");
824 }
825
826 if ( $wgUseCopyrightUpload ) {
827 $filestatus = wfMsgHtml ( 'filestatus' );
828 $copystatus = htmlspecialchars( $this->mCopyrightStatus );
829 $filesource = wfMsgHtml ( 'filesource' );
830 $uploadsource = htmlspecialchars( $this->mCopyrightSource );
831
832 $wgOut->addHTML( "
833 <td align='right' nowrap='nowrap'><label for='wpUploadCopyStatus'>$filestatus:</label></td>
834 <td><input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus'
835 value=\"$copystatus\" size='40' /></td>
836 </tr>
837 <tr>
838 <td align='right'><label for='wpUploadCopyStatus'>$filesource:</label></td>
839 <td><input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus'
840 value=\"$uploadsource\" size='40' /></td>
841 </tr>
842 <tr>
843 ");
844 }
845
846
847 $wgOut->addHtml( "
848 <td></td>
849 <td>
850 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
851 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthisupload' ) . "</label>
852 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' $warningChecked/>
853 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
854 </td>
855 </tr>
856 <tr>
857 <td></td>
858 <td align='left'><input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\" /></td>
859 </tr>
860
861 <tr>
862 <td></td>
863 <td align='left'>
864 " );
865 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
866 $wgOut->addHTML( "
867 </td>
868 </tr>
869
870 </table>
871 </form>" );
872 }
873
874 /* -------------------------------------------------------------- */
875
876 /**
877 * Split a file into a base name and all dot-delimited 'extensions'
878 * on the end. Some web server configurations will fall back to
879 * earlier pseudo-'extensions' to determine type and execute
880 * scripts, so the blacklist needs to check them all.
881 *
882 * @return array
883 */
884 function splitExtensions( $filename ) {
885 $bits = explode( '.', $filename );
886 $basename = array_shift( $bits );
887 return array( $basename, $bits );
888 }
889
890 /**
891 * Perform case-insensitive match against a list of file extensions.
892 * Returns true if the extension is in the list.
893 *
894 * @param string $ext
895 * @param array $list
896 * @return bool
897 */
898 function checkFileExtension( $ext, $list ) {
899 return in_array( strtolower( $ext ), $list );
900 }
901
902 /**
903 * Perform case-insensitive match against a list of file extensions.
904 * Returns true if any of the extensions are in the list.
905 *
906 * @param array $ext
907 * @param array $list
908 * @return bool
909 */
910 function checkFileExtensionList( $ext, $list ) {
911 foreach( $ext as $e ) {
912 if( in_array( strtolower( $e ), $list ) ) {
913 return true;
914 }
915 }
916 return false;
917 }
918
919 /**
920 * Verifies that it's ok to include the uploaded file
921 *
922 * @param string $tmpfile the full path of the temporary file to verify
923 * @param string $extension The filename extension that the file is to be served with
924 * @return mixed true of the file is verified, a WikiError object otherwise.
925 */
926 function verify( $tmpfile, $extension ) {
927 #magically determine mime type
928 $magic=& MimeMagic::singleton();
929 $mime= $magic->guessMimeType($tmpfile,false);
930
931 #check mime type, if desired
932 global $wgVerifyMimeType;
933 if ($wgVerifyMimeType) {
934
935 #check mime type against file extension
936 if( !$this->verifyExtension( $mime, $extension ) ) {
937 return new WikiErrorMsg( 'uploadcorrupt' );
938 }
939
940 #check mime type blacklist
941 global $wgMimeTypeBlacklist;
942 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
943 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
944 return new WikiErrorMsg( 'filetype-badmime', htmlspecialchars( $mime ) );
945 }
946 }
947
948 #check for htmlish code and javascript
949 if( $this->detectScript ( $tmpfile, $mime, $extension ) ) {
950 return new WikiErrorMsg( 'uploadscripted' );
951 }
952
953 /**
954 * Scan the uploaded file for viruses
955 */
956 $virus= $this->detectVirus($tmpfile);
957 if ( $virus ) {
958 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
959 }
960
961 wfDebug( __METHOD__.": all clear; passing.\n" );
962 return true;
963 }
964
965 /**
966 * Checks if the mime type of the uploaded file matches the file extension.
967 *
968 * @param string $mime the mime type of the uploaded file
969 * @param string $extension The filename extension that the file is to be served with
970 * @return bool
971 */
972 function verifyExtension( $mime, $extension ) {
973 $magic =& MimeMagic::singleton();
974
975 if ( ! $mime || $mime == 'unknown' || $mime == 'unknown/unknown' )
976 if ( ! $magic->isRecognizableExtension( $extension ) ) {
977 wfDebug( __METHOD__.": passing file with unknown detected mime type; " .
978 "unrecognized extension '$extension', can't verify\n" );
979 return true;
980 } else {
981 wfDebug( __METHOD__.": rejecting file with unknown detected mime type; ".
982 "recognized extension '$extension', so probably invalid file\n" );
983 return false;
984 }
985
986 $match= $magic->isMatchingExtension($extension,$mime);
987
988 if ($match===NULL) {
989 wfDebug( __METHOD__.": no file extension known for mime type $mime, passing file\n" );
990 return true;
991 } elseif ($match===true) {
992 wfDebug( __METHOD__.": mime type $mime matches extension $extension, passing file\n" );
993
994 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
995 return true;
996
997 } else {
998 wfDebug( __METHOD__.": mime type $mime mismatches file extension $extension, rejecting file\n" );
999 return false;
1000 }
1001 }
1002
1003 /**
1004 * Heuristic for detecting files that *could* contain JavaScript instructions or
1005 * things that may look like HTML to a browser and are thus
1006 * potentially harmful. The present implementation will produce false positives in some situations.
1007 *
1008 * @param string $file Pathname to the temporary upload file
1009 * @param string $mime The mime type of the file
1010 * @param string $extension The extension of the file
1011 * @return bool true if the file contains something looking like embedded scripts
1012 */
1013 function detectScript($file, $mime, $extension) {
1014 global $wgAllowTitlesInSVG;
1015
1016 #ugly hack: for text files, always look at the entire file.
1017 #For binarie field, just check the first K.
1018
1019 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
1020 else {
1021 $fp = fopen( $file, 'rb' );
1022 $chunk = fread( $fp, 1024 );
1023 fclose( $fp );
1024 }
1025
1026 $chunk= strtolower( $chunk );
1027
1028 if (!$chunk) return false;
1029
1030 #decode from UTF-16 if needed (could be used for obfuscation).
1031 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
1032 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
1033 else $enc= NULL;
1034
1035 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
1036
1037 $chunk= trim($chunk);
1038
1039 #FIXME: convert from UTF-16 if necessarry!
1040
1041 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
1042
1043 #check for HTML doctype
1044 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
1045
1046 /**
1047 * Internet Explorer for Windows performs some really stupid file type
1048 * autodetection which can cause it to interpret valid image files as HTML
1049 * and potentially execute JavaScript, creating a cross-site scripting
1050 * attack vectors.
1051 *
1052 * Apple's Safari browser also performs some unsafe file type autodetection
1053 * which can cause legitimate files to be interpreted as HTML if the
1054 * web server is not correctly configured to send the right content-type
1055 * (or if you're really uploading plain text and octet streams!)
1056 *
1057 * Returns true if IE is likely to mistake the given file for HTML.
1058 * Also returns true if Safari would mistake the given file for HTML
1059 * when served with a generic content-type.
1060 */
1061
1062 $tags = array(
1063 '<body',
1064 '<head',
1065 '<html', #also in safari
1066 '<img',
1067 '<pre',
1068 '<script', #also in safari
1069 '<table'
1070 );
1071 if( ! $wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1072 $tags[] = '<title';
1073 }
1074
1075 foreach( $tags as $tag ) {
1076 if( false !== strpos( $chunk, $tag ) ) {
1077 return true;
1078 }
1079 }
1080
1081 /*
1082 * look for javascript
1083 */
1084
1085 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1086 $chunk = Sanitizer::decodeCharReferences( $chunk );
1087
1088 #look for script-types
1089 if (preg_match('!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim',$chunk)) return true;
1090
1091 #look for html-style script-urls
1092 if (preg_match('!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1093
1094 #look for css-style script-urls
1095 if (preg_match('!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1096
1097 wfDebug("SpecialUpload::detectScript: no scripts found\n");
1098 return false;
1099 }
1100
1101 /**
1102 * Generic wrapper function for a virus scanner program.
1103 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1104 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1105 *
1106 * @param string $file Pathname to the temporary upload file
1107 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1108 * or a string containing feedback from the virus scanner if a virus was found.
1109 * If textual feedback is missing but a virus was found, this function returns true.
1110 */
1111 function detectVirus($file) {
1112 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1113
1114 if ( !$wgAntivirus ) {
1115 wfDebug( __METHOD__.": virus scanner disabled\n");
1116 return NULL;
1117 }
1118
1119 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1120 wfDebug( __METHOD__.": unknown virus scanner: $wgAntivirus\n" );
1121 # @TODO: localise
1122 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" );
1123 return "unknown antivirus: $wgAntivirus";
1124 }
1125
1126 # look up scanner configuration
1127 $command = $wgAntivirusSetup[$wgAntivirus]["command"];
1128 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]["codemap"];
1129 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]["messagepattern"] ) ?
1130 $wgAntivirusSetup[$wgAntivirus]["messagepattern"] : null;
1131
1132 if ( strpos( $command,"%f" ) === false ) {
1133 # simple pattern: append file to scan
1134 $command .= " " . wfEscapeShellArg( $file );
1135 } else {
1136 # complex pattern: replace "%f" with file to scan
1137 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1138 }
1139
1140 wfDebug( __METHOD__.": running virus scan: $command \n" );
1141
1142 # execute virus scanner
1143 $exitCode = false;
1144
1145 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1146 # that does not seem to be worth the pain.
1147 # Ask me (Duesentrieb) about it if it's ever needed.
1148 $output = array();
1149 if ( wfIsWindows() ) {
1150 exec( "$command", $output, $exitCode );
1151 } else {
1152 exec( "$command 2>&1", $output, $exitCode );
1153 }
1154
1155 # map exit code to AV_xxx constants.
1156 $mappedCode = $exitCode;
1157 if ( $exitCodeMap ) {
1158 if ( isset( $exitCodeMap[$exitCode] ) ) {
1159 $mappedCode = $exitCodeMap[$exitCode];
1160 } elseif ( isset( $exitCodeMap["*"] ) ) {
1161 $mappedCode = $exitCodeMap["*"];
1162 }
1163 }
1164
1165 if ( $mappedCode === AV_SCAN_FAILED ) {
1166 # scan failed (code was mapped to false by $exitCodeMap)
1167 wfDebug( __METHOD__.": failed to scan $file (code $exitCode).\n" );
1168
1169 if ( $wgAntivirusRequired ) {
1170 return "scan failed (code $exitCode)";
1171 } else {
1172 return NULL;
1173 }
1174 } else if ( $mappedCode === AV_SCAN_ABORTED ) {
1175 # scan failed because filetype is unknown (probably imune)
1176 wfDebug( __METHOD__.": unsupported file type $file (code $exitCode).\n" );
1177 return NULL;
1178 } else if ( $mappedCode === AV_NO_VIRUS ) {
1179 # no virus found
1180 wfDebug( __METHOD__.": file passed virus scan.\n" );
1181 return false;
1182 } else {
1183 $output = join( "\n", $output );
1184 $output = trim( $output );
1185
1186 if ( !$output ) {
1187 $output = true; #if there's no output, return true
1188 } elseif ( $msgPattern ) {
1189 $groups = array();
1190 if ( preg_match( $msgPattern, $output, $groups ) ) {
1191 if ( $groups[1] ) {
1192 $output = $groups[1];
1193 }
1194 }
1195 }
1196
1197 wfDebug( __METHOD__.": FOUND VIRUS! scanner feedback: $output" );
1198 return $output;
1199 }
1200 }
1201
1202 /**
1203 * Check if the temporary file is MacBinary-encoded, as some uploads
1204 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
1205 * If so, the data fork will be extracted to a second temporary file,
1206 * which will then be checked for validity and either kept or discarded.
1207 *
1208 * @access private
1209 */
1210 function checkMacBinary() {
1211 $macbin = new MacBinary( $this->mTempPath );
1212 if( $macbin->isValid() ) {
1213 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
1214 $dataHandle = fopen( $dataFile, 'wb' );
1215
1216 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
1217 $macbin->extractData( $dataHandle );
1218
1219 $this->mTempPath = $dataFile;
1220 $this->mFileSize = $macbin->dataForkLength();
1221
1222 // We'll have to manually remove the new file if it's not kept.
1223 $this->mRemoveTempFile = true;
1224 }
1225 $macbin->close();
1226 }
1227
1228 /**
1229 * If we've modified the upload file we need to manually remove it
1230 * on exit to clean up.
1231 * @access private
1232 */
1233 function cleanupTempFile() {
1234 if ( $this->mRemoveTempFile && file_exists( $this->mTempPath ) ) {
1235 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file {$this->mTempPath}\n" );
1236 unlink( $this->mTempPath );
1237 }
1238 }
1239
1240 /**
1241 * Check if there's an overwrite conflict and, if so, if restrictions
1242 * forbid this user from performing the upload.
1243 *
1244 * @return mixed true on success, WikiError on failure
1245 * @access private
1246 */
1247 function checkOverwrite( $name ) {
1248 $img = wfFindFile( $name );
1249
1250 $error = '';
1251 if( $img ) {
1252 global $wgUser, $wgOut;
1253 if( $img->isLocal() ) {
1254 if( !self::userCanReUpload( $wgUser, $img->name ) ) {
1255 $error = 'fileexists-forbidden';
1256 }
1257 } else {
1258 if( !$wgUser->isAllowed( 'reupload' ) ||
1259 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1260 $error = "fileexists-shared-forbidden";
1261 }
1262 }
1263 }
1264
1265 if( $error ) {
1266 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1267 return new WikiError( $wgOut->parse( $errorText ) );
1268 }
1269
1270 // Rockin', go ahead and upload
1271 return true;
1272 }
1273
1274 /**
1275 * Check if a user is the last uploader
1276 *
1277 * @param User $user
1278 * @param string $img, image name
1279 * @return bool
1280 */
1281 public static function userCanReUpload( User $user, $img ) {
1282 if( $user->isAllowed( 'reupload' ) )
1283 return true; // non-conditional
1284 if( !$user->isAllowed( 'reupload-own' ) )
1285 return false;
1286
1287 $dbr = wfGetDB( DB_SLAVE );
1288 $row = $dbr->selectRow('image',
1289 /* SELECT */ 'img_user',
1290 /* WHERE */ array( 'img_name' => $img )
1291 );
1292 if ( !$row )
1293 return false;
1294
1295 return $user->getID() == $row->img_user;
1296 }
1297
1298 /**
1299 * Display an error from a wikitext-formatted WikiError object
1300 */
1301 function showError( WikiError $error ) {
1302 global $wgOut;
1303 $wgOut->setPageTitle( wfMsg( "internalerror" ) );
1304 $wgOut->setRobotpolicy( "noindex,nofollow" );
1305 $wgOut->setArticleRelated( false );
1306 $wgOut->enableClientCache( false );
1307 $wgOut->addWikiText( $error->getMessage() );
1308 }
1309
1310 /**
1311 * Get the initial image page text based on a comment and optional file status information
1312 */
1313 static function getInitialPageText( $comment, $license, $copyStatus, $source ) {
1314 global $wgUseCopyrightUpload;
1315 if ( $wgUseCopyrightUpload ) {
1316 if ( $license != '' ) {
1317 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1318 }
1319 $pageText = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n" .
1320 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1321 "$licensetxt" .
1322 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1323 } else {
1324 if ( $license != '' ) {
1325 $filedesc = $comment == '' ? '' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n";
1326 $pageText = $filedesc .
1327 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1328 } else {
1329 $pageText = $comment;
1330 }
1331 }
1332 return $pageText;
1333 }
1334 }
1335