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