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