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