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