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