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