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