Revert r34619, r34622 and do it right. :)
[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 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::newFromText( $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>' . wfMsgExt( 'fileexists-extension', 'parsemag', $file->getName(), $dlink ) . '</li>' . $dlink2;
639
640 } elseif ( ( substr( $partname , 3, 3 ) == 'px-' || substr( $partname , 2, 3 ) == 'px-' )
641 && ereg( "[0-9]{2}" , substr( $partname , 0, 2) ) )
642 {
643 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
644 $nt_thb = Title::newFromText( substr( $partname , strpos( $partname , '-' ) +1 ) . '.' . $rawExtension );
645 $file_thb = wfLocalFile( $nt_thb );
646 if ($file_thb->exists() ) {
647 # Check if an image without leading '180px-' (or similiar) exists
648 $dlink = $sk->makeKnownLinkObj( $nt_thb);
649 if ( $file_thb->allowInlineDisplay() ) {
650 $dlink2 = $sk->makeImageLinkObj( $nt_thb,
651 wfMsgExt( 'fileexists-thumb', 'parseinline' ),
652 $nt_thb->getText(), $align, array(), false, true );
653 } elseif ( !$file_thb->allowInlineDisplay() && $file_thb->isSafeFile() ) {
654 $icon = $file_thb->iconThumb();
655 $dlink2 = '<div style="float:' . $align . '" id="mw-media-icon">' .
656 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' .
657 $dlink . '</div>';
658 } else {
659 $dlink2 = '';
660 }
661
662 $warning .= '<li>' . wfMsgExt( 'fileexists-thumbnail-yes', 'parsemag', $dlink ) .
663 '</li>' . $dlink2;
664 } else {
665 # Image w/o '180px-' does not exists, but we do not like these filenames
666 $warning .= '<li>' . wfMsgExt( 'file-thumbnail-no', 'parseinline' ,
667 substr( $partname , 0, strpos( $partname , '-' ) +1 ) ) . '</li>';
668 }
669 }
670
671 $filenamePrefixBlacklist = self::getFilenamePrefixBlacklist();
672 # Do the match
673 foreach( $filenamePrefixBlacklist as $prefix ) {
674 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
675 $warning .= '<li>' . wfMsgExt( 'filename-bad-prefix', 'parseinline', $prefix ) . '</li>';
676 break;
677 }
678 }
679
680 if ( $file->wasDeleted() && !$file->exists() ) {
681 # If the file existed before and was deleted, warn the user of this
682 # Don't bother doing so if the file exists now, however
683 $ltitle = SpecialPage::getTitleFor( 'Log' );
684 $llink = $sk->makeKnownLinkObj( $ltitle, wfMsgHtml( 'deletionlog' ),
685 'type=delete&page=' . $file->getTitle()->getPrefixedUrl() );
686 $warning .= '<li>' . wfMsgWikiHtml( 'filewasdeleted', $llink ) . '</li>';
687 }
688 return $warning;
689 }
690
691 /**
692 * Get a list of warnings
693 *
694 * @param string local filename, e.g. 'file exists', 'non-descriptive filename'
695 * @return array list of warning messages
696 */
697 static function ajaxGetExistsWarning( $filename ) {
698 $file = wfFindFile( $filename );
699 if( !$file ) {
700 // Force local file so we have an object to do further checks against
701 // if there isn't an exact match...
702 $file = wfLocalFile( $filename );
703 }
704 $s = '&nbsp;';
705 if ( $file ) {
706 $warning = self::getExistsWarning( $file );
707 if ( $warning !== '' ) {
708 $s = "<ul>$warning</ul>";
709 }
710 }
711 return $s;
712 }
713
714 /**
715 * Render a preview of a given license for the AJAX preview on upload
716 *
717 * @param string $license
718 * @return string
719 */
720 public static function ajaxGetLicensePreview( $license ) {
721 global $wgParser, $wgUser;
722 $text = '{{' . $license . '}}';
723 $title = Title::makeTitle( NS_IMAGE, 'Sample.jpg' );
724 $options = ParserOptions::newFromUser( $wgUser );
725
726 // Expand subst: first, then live templates...
727 $text = $wgParser->preSaveTransform( $text, $title, $wgUser, $options );
728 $output = $wgParser->parse( $text, $title, $options );
729
730 return $output->getText();
731 }
732
733 /**
734 * Get a list of blacklisted filename prefixes from [[MediaWiki:filename-prefix-blacklist]]
735 *
736 * @return array list of prefixes
737 */
738 public static function getFilenamePrefixBlacklist() {
739 $blacklist = array();
740 $message = wfMsgForContent( 'filename-prefix-blacklist' );
741 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) || $message == '-' ) ) {
742 $lines = explode( "\n", $message );
743 foreach( $lines as $line ) {
744 // Remove comment lines
745 $comment = substr( trim( $line ), 0, 1 );
746 if ( $comment == '#' || $comment == '' ) {
747 continue;
748 }
749 // Remove additional comments after a prefix
750 $comment = strpos( $line, '#' );
751 if ( $comment > 0 ) {
752 $line = substr( $line, 0, $comment-1 );
753 }
754 $blacklist[] = trim( $line );
755 }
756 }
757 return $blacklist;
758 }
759
760 /**
761 * Stash a file in a temporary directory for later processing
762 * after the user has confirmed it.
763 *
764 * If the user doesn't explicitly cancel or accept, these files
765 * can accumulate in the temp directory.
766 *
767 * @param string $saveName - the destination filename
768 * @param string $tempName - the source temporary file to save
769 * @return string - full path the stashed file, or false on failure
770 * @access private
771 */
772 function saveTempUploadedFile( $saveName, $tempName ) {
773 global $wgOut;
774 $repo = RepoGroup::singleton()->getLocalRepo();
775 $status = $repo->storeTemp( $saveName, $tempName );
776 if ( !$status->isGood() ) {
777 $this->showError( $status->getWikiText() );
778 return false;
779 } else {
780 return $status->value;
781 }
782 }
783
784 /**
785 * Stash a file in a temporary directory for later processing,
786 * and save the necessary descriptive info into the session.
787 * Returns a key value which will be passed through a form
788 * to pick up the path info on a later invocation.
789 *
790 * @return int
791 * @access private
792 */
793 function stashSession() {
794 $stash = $this->saveTempUploadedFile( $this->mDestName, $this->mTempPath );
795
796 if( !$stash ) {
797 # Couldn't save the file.
798 return false;
799 }
800
801 $key = mt_rand( 0, 0x7fffffff );
802 $_SESSION['wsUploadData'][$key] = array(
803 'mTempPath' => $stash,
804 'mFileSize' => $this->mFileSize,
805 'mSrcName' => $this->mSrcName,
806 'mFileProps' => $this->mFileProps,
807 'version' => self::SESSION_VERSION,
808 );
809 return $key;
810 }
811
812 /**
813 * Remove a temporarily kept file stashed by saveTempUploadedFile().
814 * @access private
815 * @return success
816 */
817 function unsaveUploadedFile() {
818 global $wgOut;
819 $repo = RepoGroup::singleton()->getLocalRepo();
820 $success = $repo->freeTemp( $this->mTempPath );
821 if ( ! $success ) {
822 $wgOut->showFileDeleteError( $this->mTempPath );
823 return false;
824 } else {
825 return true;
826 }
827 }
828
829 /* -------------------------------------------------------------- */
830
831 /**
832 * @param string $error as HTML
833 * @access private
834 */
835 function uploadError( $error ) {
836 global $wgOut;
837 $wgOut->addHTML( Xml::element( 'h2', null, wfMsg( 'uploadwarning' ) . "\n" ) );
838 $wgOut->addHTML( Xml::tags( 'span', array( 'class' => 'error' ), $error ) );
839 }
840
841 /**
842 * There's something wrong with this file, not enough to reject it
843 * totally but we require manual intervention to save it for real.
844 * Stash it away, then present a form asking to confirm or cancel.
845 *
846 * @param string $warning as HTML
847 * @access private
848 */
849 function uploadWarning( $warning ) {
850 global $wgOut;
851 global $wgUseCopyrightUpload;
852
853 $this->mSessionKey = $this->stashSession();
854 if( !$this->mSessionKey ) {
855 # Couldn't save file; an error has been displayed so let's go.
856 return;
857 }
858
859 $wgOut->addHTML( Xml::element( 'h2', null, wfMsg( 'uploadwarning' ) ) . "\n" );
860 $wgOut->addHTML( Xml::tags( 'ul', array( 'class' => 'warning' ), $warning ) . "\n" );
861
862 $titleObj = SpecialPage::getTitleFor( 'Upload' );
863
864 if ( $wgUseCopyrightUpload ) {
865 $copyright = Xml::hidden( 'wpUploadCopyStatus', $this->mCopyrightStatus ) . "\n" .
866 Xml::hidden( 'wpUploadSource', $this->mCopyrightSource ) . "\n";
867 } else {
868 $copyright = '';
869 }
870
871 $wgOut->addHTML(
872 Xml::openElement( 'form', array( 'method' => 'post', 'action' => $titleObj->getLocalURL( 'action=submit' ),
873 'enctype' => 'multipart/form-data', 'id' => 'uploadwarning' ) ) . "\n" .
874 Xml::hidden( 'wpIgnoreWarning', '1' ) . "\n" .
875 Xml::hidden( 'wpSessionKey', $this->mSessionKey ) . "\n" .
876 Xml::hidden( 'wpUploadDescription', $this->mComment ) . "\n" .
877 Xml::hidden( 'wpLicense', $this->mLicense ) . "\n" .
878 Xml::hidden( 'wpDestFile', $this->mDesiredDestName ) . "\n" .
879 Xml::hidden( 'wpWatchthis', $this->mWatchthis ) . "\n" .
880 "{$copyright}<br />" .
881 Xml::submitButton( wfMsg( 'ignorewarning' ), array ( 'name' => 'wpUpload', 'id' => 'wpUpload', 'checked' => 'checked' ) ) . ' ' .
882 Xml::submitButton( wfMsg( 'reuploaddesc' ), array ( 'name' => 'wpReUpload', 'id' => 'wpReUpload' ) ) .
883 Xml::closeElement( 'form' ) . "\n"
884 );
885 }
886
887 /**
888 * Displays the main upload form, optionally with a highlighted
889 * error message up at the top.
890 *
891 * @param string $msg as HTML
892 * @access private
893 */
894 function mainUploadForm( $msg='' ) {
895 global $wgOut, $wgUser, $wgLang, $wgMaxUploadSize;
896 global $wgUseCopyrightUpload, $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview;
897 global $wgRequest, $wgAllowCopyUploads;
898 global $wgStylePath, $wgStyleVersion;
899
900 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
901 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview;
902
903 $adc = wfBoolToStr( $useAjaxDestCheck );
904 $alp = wfBoolToStr( $useAjaxLicensePreview );
905 $autofill = wfBoolToStr( $this->mDesiredDestName == '' );
906
907 $wgOut->addScript( "<script type=\"text/javascript\">
908 wgAjaxUploadDestCheck = {$adc};
909 wgAjaxLicensePreview = {$alp};
910 wgUploadAutoFill = {$autofill};
911 </script>
912 <script type=\"text/javascript\" src=\"{$wgStylePath}/common/upload.js?{$wgStyleVersion}\"></script>
913 " );
914
915 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) )
916 {
917 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
918 return false;
919 }
920
921 if( $this->mDesiredDestName ) {
922 $title = Title::makeTitleSafe( NS_IMAGE, $this->mDesiredDestName );
923 // Show a subtitle link to deleted revisions (to sysops et al only)
924 if( $title instanceof Title && ( $count = $title->isDeleted() ) > 0 && $wgUser->isAllowed( 'deletedhistory' ) ) {
925 $link = wfMsgExt(
926 $wgUser->isAllowed( 'delete' ) ? 'thisisdeleted' : 'viewdeleted',
927 array( 'parse', 'replaceafter' ),
928 $wgUser->getSkin()->makeKnownLinkObj(
929 SpecialPage::getTitleFor( 'Undelete', $title->getPrefixedText() ),
930 wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $count )
931 )
932 );
933 $wgOut->addHtml( "<div id=\"contentSub2\">{$link}</div>" );
934 }
935
936 // Show the relevant lines from deletion log (for still deleted files only)
937 if( $title instanceof Title && $title->isDeleted() > 0 && !$title->exists() ) {
938 $this->showDeletionLog( $wgOut, $title->getPrefixedText() );
939 }
940 }
941
942 $cols = intval($wgUser->getOption( 'cols' ));
943
944 if( $wgUser->getOption( 'editwidth' ) ) {
945 $width = " style=\"width:100%\"";
946 } else {
947 $width = '';
948 }
949
950 if ( '' != $msg ) {
951 $sub = wfMsgHtml( 'uploaderror' );
952 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
953 "<span class='error'>{$msg}</span>\n" );
954 }
955 $wgOut->addHTML( '<div id="uploadtext">' );
956 $wgOut->addWikiMsg( 'uploadtext', $this->mDesiredDestName );
957 $wgOut->addHTML( "</div>\n" );
958
959 # Print a list of allowed file extensions, if so configured. We ignore
960 # MIME type here, it's incomprehensible to most people and too long.
961 global $wgCheckFileExtensions, $wgStrictFileExtensions,
962 $wgFileExtensions, $wgFileBlacklist;
963
964 $allowedExtensions = '';
965 if( $wgCheckFileExtensions ) {
966 $delim = wfMsgExt( 'comma-separator', array( 'escapenoentities' ) );
967 if( $wgStrictFileExtensions ) {
968 # Everything not permitted is banned
969 $extensionsList =
970 '<div id="mw-upload-permitted">' .
971 wfMsgWikiHtml( 'upload-permitted', implode( $wgFileExtensions, $delim ) ) .
972 "</div>\n";
973 } else {
974 # We have to list both preferred and prohibited
975 $extensionsList =
976 '<div id="mw-upload-preferred">' .
977 wfMsgWikiHtml( 'upload-preferred', implode( $wgFileExtensions, $delim ) ) .
978 "</div>\n" .
979 '<div id="mw-upload-prohibited">' .
980 wfMsgWikiHtml( 'upload-prohibited', implode( $wgFileBlacklist, $delim ) ) .
981 "</div>\n";
982 }
983 } else {
984 # Everything is permitted.
985 $extensionsList = '';
986 }
987
988 # Get the maximum file size from php.ini as $wgMaxUploadSize works for uploads from URL via CURL only
989 # See http://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize for possible values of upload_max_filesize
990 $val = trim( ini_get( 'upload_max_filesize' ) );
991 $last = strtoupper( ( substr( $val, -1 ) ) );
992 switch( $last ) {
993 case 'G':
994 $val2 = substr( $val, 0, -1 ) * 1024 * 1024 * 1024;
995 break;
996 case 'M':
997 $val2 = substr( $val, 0, -1 ) * 1024 * 1024;
998 break;
999 case 'K':
1000 $val2 = substr( $val, 0, -1 ) * 1024;
1001 break;
1002 default:
1003 $val2 = $val;
1004 }
1005 $val2 = $wgAllowCopyUploads ? min( $wgMaxUploadSize, $val2 ) : $val2;
1006 $maxUploadSize = wfMsgExt( 'upload-maxfilesize', array( 'parseinline', 'escapenoentities' ), $wgLang->formatSize( $val2 ) );
1007
1008 $sourcefilename = wfMsgExt( 'sourcefilename', 'escapenoentities' );
1009 $destfilename = wfMsgExt( 'destfilename', 'escapenoentities' );
1010 $summary = wfMsgExt( 'fileuploadsummary', 'parseinline' );
1011
1012 $licenses = new Licenses();
1013 $license = wfMsgExt( 'license', array( 'parseinline' ) );
1014 $nolicense = wfMsgHtml( 'nolicense' );
1015 $licenseshtml = $licenses->getHtml();
1016
1017 $ulb = wfMsgHtml( 'uploadbtn' );
1018
1019
1020 $titleObj = SpecialPage::getTitleFor( 'Upload' );
1021
1022 $encDestName = htmlspecialchars( $this->mDesiredDestName );
1023
1024 $watchChecked = $this->watchCheck()
1025 ? 'checked="checked"'
1026 : '';
1027 $warningChecked = $this->mIgnoreWarning ? 'checked' : '';
1028
1029 // Prepare form for upload or upload/copy
1030 if( $wgAllowCopyUploads && $wgUser->isAllowed( 'upload_by_url' ) ) {
1031 $filename_form =
1032 "<input type='radio' id='wpSourceTypeFile' name='wpSourceType' value='file' " .
1033 "onchange='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\")' checked='checked' />" .
1034 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
1035 "onfocus='" .
1036 "toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\");" .
1037 "toggle_element_check(\"wpSourceTypeFile\",\"wpSourceTypeURL\")' " .
1038 "onchange='fillDestFilename(\"wpUploadFile\")' size='60' />" .
1039 wfMsgHTML( 'upload_source_file' ) . "<br/>" .
1040 "<input type='radio' id='wpSourceTypeURL' name='wpSourceType' value='web' " .
1041 "onchange='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\")' />" .
1042 "<input tabindex='1' type='text' name='wpUploadFileURL' id='wpUploadFileURL' " .
1043 "onfocus='" .
1044 "toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\");" .
1045 "toggle_element_check(\"wpSourceTypeURL\",\"wpSourceTypeFile\")' " .
1046 "onchange='fillDestFilename(\"wpUploadFileURL\")' size='60' disabled='disabled' />" .
1047 wfMsgHtml( 'upload_source_url' ) ;
1048 } else {
1049 $filename_form =
1050 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
1051 ($this->mDesiredDestName?"":"onchange='fillDestFilename(\"wpUploadFile\")' ") .
1052 "size='60' />" .
1053 "<input type='hidden' name='wpSourceType' value='file' />" ;
1054 }
1055 if ( $useAjaxDestCheck ) {
1056 $warningRow = "<tr><td colspan='2' id='wpDestFile-warning'>&nbsp;</td></tr>";
1057 $destOnkeyup = 'onkeyup="wgUploadWarningObj.keypress();"';
1058 } else {
1059 $warningRow = '';
1060 $destOnkeyup = '';
1061 }
1062
1063 $encComment = htmlspecialchars( $this->mComment );
1064
1065 $wgOut->addHTML(
1066 Xml::openElement( 'form', array( 'method' => 'post', 'action' => $titleObj->getLocalURL(),
1067 'enctype' => 'multipart/form-data', 'id' => 'mw-upload-form' ) ) .
1068 Xml::openElement( 'fieldset' ) .
1069 Xml::element( 'legend', null, wfMsg( 'upload' ) ) .
1070 Xml::openElement( 'table', array( 'border' => '0', 'id' => 'mw-upload-table' ) ) .
1071 "<tr>
1072 {$this->uploadFormTextTop}
1073 <td class='mw-label'>
1074 <label for='wpUploadFile'>{$sourcefilename}</label>
1075 </td>
1076 <td class='mw-input'>
1077 {$filename_form}
1078 </td>
1079 </tr>
1080 <tr>
1081 <td></td>
1082 <td>
1083 {$maxUploadSize}
1084 {$extensionsList}
1085 </td>
1086 </tr>
1087 <tr>
1088 <td class='mw-label'>
1089 <label for='wpDestFile'>{$destfilename}</label>
1090 </td>
1091 <td class='mw-input'>
1092 <input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='60'
1093 value=\"{$encDestName}\" onchange='toggleFilenameFiller()' $destOnkeyup />
1094 </td>
1095 </tr>
1096 <tr>
1097 <td class='mw-label'>
1098 <label for='wpUploadDescription'>{$summary}</label>
1099 </td>
1100 <td class='mw-input'>
1101 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6'
1102 cols='{$cols}'{$width}>$encComment</textarea>
1103 {$this->uploadFormTextAfterSummary}
1104 </td>
1105 </tr>
1106 <tr>"
1107 );
1108
1109 if ( $licenseshtml != '' ) {
1110 global $wgStylePath;
1111 $wgOut->addHTML( "
1112 <td class='mw-label'>
1113 <label for='wpLicense'>$license</label>
1114 </td>
1115 <td class='mw-input'>
1116 <select name='wpLicense' id='wpLicense' tabindex='4'
1117 onchange='licenseSelectorCheck()'>
1118 <option value=''>$nolicense</option>
1119 $licenseshtml
1120 </select>
1121 </td>
1122 </tr>
1123 <tr>"
1124 );
1125 if( $useAjaxLicensePreview ) {
1126 $wgOut->addHtml( "
1127 <td></td>
1128 <td id=\"mw-license-preview\"></td>
1129 </tr>
1130 <tr>"
1131 );
1132 }
1133 }
1134
1135 if ( $wgUseCopyrightUpload ) {
1136 $filestatus = wfMsgExt( 'filestatus', 'escapenoentities' );
1137 $copystatus = htmlspecialchars( $this->mCopyrightStatus );
1138 $filesource = wfMsgExt( 'filesource', 'escapenoentities' );
1139 $uploadsource = htmlspecialchars( $this->mCopyrightSource );
1140
1141 $wgOut->addHTML( "
1142 <td class='mw-label' style='white-space: nowrap;'>
1143 <label for='wpUploadCopyStatus'>$filestatus</label></td>
1144 <td class='mw-input'>
1145 <input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus'
1146 value=\"$copystatus\" size='60' />
1147 </td>
1148 </tr>
1149 <tr>
1150 <td class='mw-label'>
1151 <label for='wpUploadCopyStatus'>$filesource</label>
1152 </td>
1153 <td class='mw-input'>
1154 <input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus'
1155 value=\"$uploadsource\" size='60' />
1156 </td>
1157 </tr>
1158 <tr>"
1159 );
1160 }
1161
1162 $wgOut->addHtml( "
1163 <td></td>
1164 <td>
1165 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
1166 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthisupload' ) . "</label>
1167 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' $warningChecked/>
1168 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
1169 </td>
1170 </tr>
1171 $warningRow
1172 <tr>
1173 <td></td>
1174 <td class='mw-input'>
1175 <input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\"" . $wgUser->getSkin()->tooltipAndAccesskey( 'upload' ) . " />
1176 </td>
1177 </tr>
1178 <tr>
1179 <td></td>
1180 <td class='mw-input'>"
1181 );
1182 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1183 $wgOut->addHTML( "
1184 </td>
1185 </tr>" .
1186 Xml::closeElement( 'table' ) .
1187 Xml::hidden( 'wpDestFileWarningAck', '', array( 'id' => 'wpDestFileWarningAck' ) ) .
1188 Xml::closeElement( 'fieldset' ) .
1189 Xml::closeElement( 'form' )
1190 );
1191 $uploadfooter = wfMsgNoTrans( 'uploadfooter' );
1192 if( $uploadfooter != '-' && !wfEmptyMsg( 'uploadfooter', $uploadfooter ) ){
1193 $wgOut->addWikiText( Xml::tags( 'div',
1194 array( 'id' => 'mw-upload-footer-message' ), $uploadfooter ) );
1195 }
1196 }
1197
1198 /* -------------------------------------------------------------- */
1199
1200 /**
1201 * See if we should check the 'watch this page' checkbox on the form
1202 * based on the user's preferences and whether we're being asked
1203 * to create a new file or update an existing one.
1204 *
1205 * In the case where 'watch edits' is off but 'watch creations' is on,
1206 * we'll leave the box unchecked.
1207 *
1208 * Note that the page target can be changed *on the form*, so our check
1209 * state can get out of sync.
1210 */
1211 function watchCheck() {
1212 global $wgUser;
1213 if( $wgUser->getOption( 'watchdefault' ) ) {
1214 // Watch all edits!
1215 return true;
1216 }
1217
1218 $local = wfLocalFile( $this->mDesiredDestName );
1219 if( $local && $local->exists() ) {
1220 // We're uploading a new version of an existing file.
1221 // No creation, so don't watch it if we're not already.
1222 return $local->getTitle()->userIsWatching();
1223 } else {
1224 // New page should get watched if that's our option.
1225 return $wgUser->getOption( 'watchcreations' );
1226 }
1227 }
1228
1229 /**
1230 * Split a file into a base name and all dot-delimited 'extensions'
1231 * on the end. Some web server configurations will fall back to
1232 * earlier pseudo-'extensions' to determine type and execute
1233 * scripts, so the blacklist needs to check them all.
1234 *
1235 * @return array
1236 */
1237 function splitExtensions( $filename ) {
1238 $bits = explode( '.', $filename );
1239 $basename = array_shift( $bits );
1240 return array( $basename, $bits );
1241 }
1242
1243 /**
1244 * Perform case-insensitive match against a list of file extensions.
1245 * Returns true if the extension is in the list.
1246 *
1247 * @param string $ext
1248 * @param array $list
1249 * @return bool
1250 */
1251 function checkFileExtension( $ext, $list ) {
1252 return in_array( strtolower( $ext ), $list );
1253 }
1254
1255 /**
1256 * Perform case-insensitive match against a list of file extensions.
1257 * Returns true if any of the extensions are in the list.
1258 *
1259 * @param array $ext
1260 * @param array $list
1261 * @return bool
1262 */
1263 function checkFileExtensionList( $ext, $list ) {
1264 foreach( $ext as $e ) {
1265 if( in_array( strtolower( $e ), $list ) ) {
1266 return true;
1267 }
1268 }
1269 return false;
1270 }
1271
1272 /**
1273 * Verifies that it's ok to include the uploaded file
1274 *
1275 * @param string $tmpfile the full path of the temporary file to verify
1276 * @param string $extension The filename extension that the file is to be served with
1277 * @return mixed true of the file is verified, a WikiError object otherwise.
1278 */
1279 function verify( $tmpfile, $extension ) {
1280 #magically determine mime type
1281 $magic = MimeMagic::singleton();
1282 $mime = $magic->guessMimeType($tmpfile,false);
1283
1284 #check mime type, if desired
1285 global $wgVerifyMimeType;
1286 if ($wgVerifyMimeType) {
1287
1288 wfDebug ( "\n\nmime: <$mime> extension: <$extension>\n\n");
1289 #check mime type against file extension
1290 if( !$this->verifyExtension( $mime, $extension ) ) {
1291 return new WikiErrorMsg( 'uploadcorrupt' );
1292 }
1293
1294 #check mime type blacklist
1295 global $wgMimeTypeBlacklist;
1296 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
1297 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
1298 return new WikiErrorMsg( 'filetype-badmime', htmlspecialchars( $mime ) );
1299 }
1300 }
1301
1302 #check for htmlish code and javascript
1303 if( $this->detectScript ( $tmpfile, $mime, $extension ) ) {
1304 return new WikiErrorMsg( 'uploadscripted' );
1305 }
1306
1307 /**
1308 * Scan the uploaded file for viruses
1309 */
1310 $virus= $this->detectVirus($tmpfile);
1311 if ( $virus ) {
1312 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
1313 }
1314
1315 wfDebug( __METHOD__.": all clear; passing.\n" );
1316 return true;
1317 }
1318
1319 /**
1320 * Checks if the mime type of the uploaded file matches the file extension.
1321 *
1322 * @param string $mime the mime type of the uploaded file
1323 * @param string $extension The filename extension that the file is to be served with
1324 * @return bool
1325 */
1326 function verifyExtension( $mime, $extension ) {
1327 $magic = MimeMagic::singleton();
1328
1329 if ( ! $mime || $mime == 'unknown' || $mime == 'unknown/unknown' )
1330 if ( ! $magic->isRecognizableExtension( $extension ) ) {
1331 wfDebug( __METHOD__.": passing file with unknown detected mime type; " .
1332 "unrecognized extension '$extension', can't verify\n" );
1333 return true;
1334 } else {
1335 wfDebug( __METHOD__.": rejecting file with unknown detected mime type; ".
1336 "recognized extension '$extension', so probably invalid file\n" );
1337 return false;
1338 }
1339
1340 $match= $magic->isMatchingExtension($extension,$mime);
1341
1342 if ($match===NULL) {
1343 wfDebug( __METHOD__.": no file extension known for mime type $mime, passing file\n" );
1344 return true;
1345 } elseif ($match===true) {
1346 wfDebug( __METHOD__.": mime type $mime matches extension $extension, passing file\n" );
1347
1348 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
1349 return true;
1350
1351 } else {
1352 wfDebug( __METHOD__.": mime type $mime mismatches file extension $extension, rejecting file\n" );
1353 return false;
1354 }
1355 }
1356
1357 /**
1358 * Heuristic for detecting files that *could* contain JavaScript instructions or
1359 * things that may look like HTML to a browser and are thus
1360 * potentially harmful. The present implementation will produce false positives in some situations.
1361 *
1362 * @param string $file Pathname to the temporary upload file
1363 * @param string $mime The mime type of the file
1364 * @param string $extension The extension of the file
1365 * @return bool true if the file contains something looking like embedded scripts
1366 */
1367 function detectScript($file, $mime, $extension) {
1368 global $wgAllowTitlesInSVG;
1369
1370 #ugly hack: for text files, always look at the entire file.
1371 #For binarie field, just check the first K.
1372
1373 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
1374 else {
1375 $fp = fopen( $file, 'rb' );
1376 $chunk = fread( $fp, 1024 );
1377 fclose( $fp );
1378 }
1379
1380 $chunk= strtolower( $chunk );
1381
1382 if (!$chunk) return false;
1383
1384 #decode from UTF-16 if needed (could be used for obfuscation).
1385 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
1386 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
1387 else $enc= NULL;
1388
1389 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
1390
1391 $chunk= trim($chunk);
1392
1393 #FIXME: convert from UTF-16 if necessarry!
1394
1395 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
1396
1397 #check for HTML doctype
1398 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
1399
1400 /**
1401 * Internet Explorer for Windows performs some really stupid file type
1402 * autodetection which can cause it to interpret valid image files as HTML
1403 * and potentially execute JavaScript, creating a cross-site scripting
1404 * attack vectors.
1405 *
1406 * Apple's Safari browser also performs some unsafe file type autodetection
1407 * which can cause legitimate files to be interpreted as HTML if the
1408 * web server is not correctly configured to send the right content-type
1409 * (or if you're really uploading plain text and octet streams!)
1410 *
1411 * Returns true if IE is likely to mistake the given file for HTML.
1412 * Also returns true if Safari would mistake the given file for HTML
1413 * when served with a generic content-type.
1414 */
1415
1416 $tags = array(
1417 '<body',
1418 '<head',
1419 '<html', #also in safari
1420 '<img',
1421 '<pre',
1422 '<script', #also in safari
1423 '<table'
1424 );
1425 if( ! $wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1426 $tags[] = '<title';
1427 }
1428
1429 foreach( $tags as $tag ) {
1430 if( false !== strpos( $chunk, $tag ) ) {
1431 return true;
1432 }
1433 }
1434
1435 /*
1436 * look for javascript
1437 */
1438
1439 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1440 $chunk = Sanitizer::decodeCharReferences( $chunk );
1441
1442 #look for script-types
1443 if (preg_match('!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim',$chunk)) return true;
1444
1445 #look for html-style script-urls
1446 if (preg_match('!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1447
1448 #look for css-style script-urls
1449 if (preg_match('!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1450
1451 wfDebug("SpecialUpload::detectScript: no scripts found\n");
1452 return false;
1453 }
1454
1455 /**
1456 * Generic wrapper function for a virus scanner program.
1457 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1458 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1459 *
1460 * @param string $file Pathname to the temporary upload file
1461 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1462 * or a string containing feedback from the virus scanner if a virus was found.
1463 * If textual feedback is missing but a virus was found, this function returns true.
1464 */
1465 function detectVirus($file) {
1466 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1467
1468 if ( !$wgAntivirus ) {
1469 wfDebug( __METHOD__.": virus scanner disabled\n");
1470 return NULL;
1471 }
1472
1473 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1474 wfDebug( __METHOD__.": unknown virus scanner: $wgAntivirus\n" );
1475 # @TODO: localise
1476 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" );
1477 return "unknown antivirus: $wgAntivirus";
1478 }
1479
1480 # look up scanner configuration
1481 $command = $wgAntivirusSetup[$wgAntivirus]["command"];
1482 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]["codemap"];
1483 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]["messagepattern"] ) ?
1484 $wgAntivirusSetup[$wgAntivirus]["messagepattern"] : null;
1485
1486 if ( strpos( $command,"%f" ) === false ) {
1487 # simple pattern: append file to scan
1488 $command .= " " . wfEscapeShellArg( $file );
1489 } else {
1490 # complex pattern: replace "%f" with file to scan
1491 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1492 }
1493
1494 wfDebug( __METHOD__.": running virus scan: $command \n" );
1495
1496 # execute virus scanner
1497 $exitCode = false;
1498
1499 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1500 # that does not seem to be worth the pain.
1501 # Ask me (Duesentrieb) about it if it's ever needed.
1502 $output = array();
1503 if ( wfIsWindows() ) {
1504 exec( "$command", $output, $exitCode );
1505 } else {
1506 exec( "$command 2>&1", $output, $exitCode );
1507 }
1508
1509 # map exit code to AV_xxx constants.
1510 $mappedCode = $exitCode;
1511 if ( $exitCodeMap ) {
1512 if ( isset( $exitCodeMap[$exitCode] ) ) {
1513 $mappedCode = $exitCodeMap[$exitCode];
1514 } elseif ( isset( $exitCodeMap["*"] ) ) {
1515 $mappedCode = $exitCodeMap["*"];
1516 }
1517 }
1518
1519 if ( $mappedCode === AV_SCAN_FAILED ) {
1520 # scan failed (code was mapped to false by $exitCodeMap)
1521 wfDebug( __METHOD__.": failed to scan $file (code $exitCode).\n" );
1522
1523 if ( $wgAntivirusRequired ) {
1524 return "scan failed (code $exitCode)";
1525 } else {
1526 return NULL;
1527 }
1528 } else if ( $mappedCode === AV_SCAN_ABORTED ) {
1529 # scan failed because filetype is unknown (probably imune)
1530 wfDebug( __METHOD__.": unsupported file type $file (code $exitCode).\n" );
1531 return NULL;
1532 } else if ( $mappedCode === AV_NO_VIRUS ) {
1533 # no virus found
1534 wfDebug( __METHOD__.": file passed virus scan.\n" );
1535 return false;
1536 } else {
1537 $output = join( "\n", $output );
1538 $output = trim( $output );
1539
1540 if ( !$output ) {
1541 $output = true; #if there's no output, return true
1542 } elseif ( $msgPattern ) {
1543 $groups = array();
1544 if ( preg_match( $msgPattern, $output, $groups ) ) {
1545 if ( $groups[1] ) {
1546 $output = $groups[1];
1547 }
1548 }
1549 }
1550
1551 wfDebug( __METHOD__.": FOUND VIRUS! scanner feedback: $output" );
1552 return $output;
1553 }
1554 }
1555
1556 /**
1557 * Check if the temporary file is MacBinary-encoded, as some uploads
1558 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
1559 * If so, the data fork will be extracted to a second temporary file,
1560 * which will then be checked for validity and either kept or discarded.
1561 *
1562 * @access private
1563 */
1564 function checkMacBinary() {
1565 $macbin = new MacBinary( $this->mTempPath );
1566 if( $macbin->isValid() ) {
1567 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
1568 $dataHandle = fopen( $dataFile, 'wb' );
1569
1570 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
1571 $macbin->extractData( $dataHandle );
1572
1573 $this->mTempPath = $dataFile;
1574 $this->mFileSize = $macbin->dataForkLength();
1575
1576 // We'll have to manually remove the new file if it's not kept.
1577 $this->mRemoveTempFile = true;
1578 }
1579 $macbin->close();
1580 }
1581
1582 /**
1583 * If we've modified the upload file we need to manually remove it
1584 * on exit to clean up.
1585 * @access private
1586 */
1587 function cleanupTempFile() {
1588 if ( $this->mRemoveTempFile && file_exists( $this->mTempPath ) ) {
1589 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file {$this->mTempPath}\n" );
1590 unlink( $this->mTempPath );
1591 }
1592 }
1593
1594 /**
1595 * Check if there's an overwrite conflict and, if so, if restrictions
1596 * forbid this user from performing the upload.
1597 *
1598 * @return mixed true on success, WikiError on failure
1599 * @access private
1600 */
1601 function checkOverwrite( $name ) {
1602 $img = wfFindFile( $name );
1603
1604 $error = '';
1605 if( $img ) {
1606 global $wgUser, $wgOut;
1607 if( $img->isLocal() ) {
1608 if( !self::userCanReUpload( $wgUser, $img->name ) ) {
1609 $error = 'fileexists-forbidden';
1610 }
1611 } else {
1612 if( !$wgUser->isAllowed( 'reupload' ) ||
1613 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1614 $error = "fileexists-shared-forbidden";
1615 }
1616 }
1617 }
1618
1619 if( $error ) {
1620 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1621 return $errorText;
1622 }
1623
1624 // Rockin', go ahead and upload
1625 return true;
1626 }
1627
1628 /**
1629 * Check if a user is the last uploader
1630 *
1631 * @param User $user
1632 * @param string $img, image name
1633 * @return bool
1634 */
1635 public static function userCanReUpload( User $user, $img ) {
1636 if( $user->isAllowed( 'reupload' ) )
1637 return true; // non-conditional
1638 if( !$user->isAllowed( 'reupload-own' ) )
1639 return false;
1640
1641 $dbr = wfGetDB( DB_SLAVE );
1642 $row = $dbr->selectRow('image',
1643 /* SELECT */ 'img_user',
1644 /* WHERE */ array( 'img_name' => $img )
1645 );
1646 if ( !$row )
1647 return false;
1648
1649 return $user->getID() == $row->img_user;
1650 }
1651
1652 /**
1653 * Display an error with a wikitext description
1654 */
1655 function showError( $description ) {
1656 global $wgOut;
1657 $wgOut->setPageTitle( wfMsg( "internalerror" ) );
1658 $wgOut->setRobotpolicy( "noindex,nofollow" );
1659 $wgOut->setArticleRelated( false );
1660 $wgOut->enableClientCache( false );
1661 $wgOut->addWikiText( $description );
1662 }
1663
1664 /**
1665 * Get the initial image page text based on a comment and optional file status information
1666 */
1667 static function getInitialPageText( $comment, $license, $copyStatus, $source ) {
1668 global $wgUseCopyrightUpload;
1669 if ( $wgUseCopyrightUpload ) {
1670 if ( $license != '' ) {
1671 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1672 }
1673 $pageText = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n" .
1674 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1675 "$licensetxt" .
1676 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1677 } else {
1678 if ( $license != '' ) {
1679 $filedesc = $comment == '' ? '' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n";
1680 $pageText = $filedesc .
1681 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1682 } else {
1683 $pageText = $comment;
1684 }
1685 }
1686 return $pageText;
1687 }
1688
1689 /**
1690 * If there are rows in the deletion log for this file, show them,
1691 * along with a nice little note for the user
1692 *
1693 * @param OutputPage $out
1694 * @param string filename
1695 */
1696 private function showDeletionLog( $out, $filename ) {
1697 global $wgUser;
1698 $loglist = new LogEventsList( $wgUser->getSkin(), $out );
1699 $pager = new LogPager( $loglist, 'delete', false, $filename );
1700 if( $pager->getNumRows() > 0 ) {
1701 $out->addHtml( '<div id="mw-upload-deleted-warn">' );
1702 $out->addWikiMsg( 'upload-wasdeleted' );
1703 $out->addHTML(
1704 $loglist->beginLogEventsList() .
1705 $pager->getBody() .
1706 $loglist->endLogEventsList()
1707 );
1708 $out->addHtml( '</div>' );
1709 }
1710 }
1711 }