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