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