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