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