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