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