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