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