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