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