(bug 14496) Fix regression with parseinline on Special:Upload
[lhc/web/wiklou.git] / includes / 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 $this->mainUploadForm();
263 } else if( 'submit' == $this->mAction || $this->mUploadClicked ) {
264 $this->processUpload();
265 } else {
266 $this->mainUploadForm();
267 }
268
269 $this->cleanupTempFile();
270 }
271
272 /**
273 * Do the upload
274 * Checks are made in SpecialUpload::execute()
275 *
276 * @access private
277 */
278 function processUpload(){
279 global $wgUser, $wgOut, $wgFileExtensions;
280 $details = null;
281 $value = null;
282 $value = $this->internalProcessUpload( $details );
283
284 switch($value) {
285 case self::SUCCESS:
286 $wgOut->redirect( $this->mLocalFile->getTitle()->getFullURL() );
287 break;
288
289 case self::BEFORE_PROCESSING:
290 break;
291
292 case self::LARGE_FILE_SERVER:
293 $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
294 break;
295
296 case self::EMPTY_FILE:
297 $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
298 break;
299
300 case self::MIN_LENGHT_PARTNAME:
301 $this->mainUploadForm( wfMsgHtml( 'minlength1' ) );
302 break;
303
304 case self::ILLEGAL_FILENAME:
305 $filtered = $details['filtered'];
306 $this->uploadError( wfMsgWikiHtml( 'illegalfilename', htmlspecialchars( $filtered ) ) );
307 break;
308
309 case self::PROTECTED_PAGE:
310 $wgOut->showPermissionsErrorPage( $details['permissionserrors'] );
311 break;
312
313 case self::OVERWRITE_EXISTING_FILE:
314 $errorText = $details['overwrite'];
315 $overwrite = new WikiError( $wgOut->parse( $errorText ) );
316 $this->uploadError( $overwrite->toString() );
317 break;
318
319 case self::FILETYPE_MISSING:
320 $this->uploadError( wfMsgExt( 'filetype-missing', array ( 'parseinline' ) ) );
321 break;
322
323 case self::FILETYPE_BADTYPE:
324 $finalExt = $details['finalExt'];
325 $this->uploadError(
326 wfMsgExt( 'filetype-banned-type',
327 array( 'parseinline' ),
328 htmlspecialchars( $finalExt ),
329 implode(
330 wfMsgExt( 'comma-separator', array( 'escapenoentities' ) ),
331 $wgFileExtensions
332 )
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 # Chop off any directories in the given filename
392 if( $this->mDesiredDestName ) {
393 $basename = $this->mDesiredDestName;
394 } else {
395 $basename = $this->mSrcName;
396 }
397 $filtered = wfBaseName( $basename );
398
399 /**
400 * We'll want to blacklist against *any* 'extension', and use
401 * only the final one for the whitelist.
402 */
403 list( $partname, $ext ) = $this->splitExtensions( $filtered );
404
405 if( count( $ext ) ) {
406 $finalExt = $ext[count( $ext ) - 1];
407 } else {
408 $finalExt = '';
409 }
410
411 # If there was more than one "extension", reassemble the base
412 # filename to prevent bogus complaints about length
413 if( count( $ext ) > 1 ) {
414 for( $i = 0; $i < count( $ext ) - 1; $i++ )
415 $partname .= '.' . $ext[$i];
416 }
417
418 if( strlen( $partname ) < 1 ) {
419 return self::MIN_LENGHT_PARTNAME;
420 }
421
422 /**
423 * Filter out illegal characters, and try to make a legible name
424 * out of it. We'll strip some silently that Title would die on.
425 */
426 $filtered = preg_replace ( "/[^".Title::legalChars()."]|:/", '-', $filtered );
427 $nt = Title::makeTitleSafe( NS_IMAGE, $filtered );
428 if( is_null( $nt ) ) {
429 $resultDetails = array( 'filtered' => $filtered );
430 return self::ILLEGAL_FILENAME;
431 }
432 $this->mLocalFile = wfLocalFile( $nt );
433 $this->mDestName = $this->mLocalFile->getName();
434
435 /**
436 * If the image is protected, non-sysop users won't be able
437 * to modify it by uploading a new revision.
438 */
439 $permErrors = $nt->getUserPermissionsErrors( 'edit', $wgUser );
440 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $wgUser );
441 $permErrorsCreate = ( $nt->exists() ? array() : $nt->getUserPermissionsErrors( 'create', $wgUser ) );
442
443 if( $permErrors || $permErrorsUpload || $permErrorsCreate ) {
444 // merge all the problems into one list, avoiding duplicates
445 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
446 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
447 $resultDetails = array( 'permissionserrors' => $permErrors );
448 return self::PROTECTED_PAGE;
449 }
450
451 /**
452 * In some cases we may forbid overwriting of existing files.
453 */
454 $overwrite = $this->checkOverwrite( $this->mDestName );
455 if( $overwrite !== true ) {
456 $resultDetails = array( 'overwrite' => $overwrite );
457 return self::OVERWRITE_EXISTING_FILE;
458 }
459
460 /* Don't allow users to override the blacklist (check file extension) */
461 global $wgCheckFileExtensions, $wgStrictFileExtensions;
462 global $wgFileExtensions, $wgFileBlacklist;
463 if ($finalExt == '') {
464 return self::FILETYPE_MISSING;
465 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
466 ($wgCheckFileExtensions && $wgStrictFileExtensions &&
467 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
468 $resultDetails = array( 'finalExt' => $finalExt );
469 return self::FILETYPE_BADTYPE;
470 }
471
472 /**
473 * Look at the contents of the file; if we can recognize the
474 * type but it's corrupt or data of the wrong type, we should
475 * probably not accept it.
476 */
477 if( !$this->mStashed ) {
478 $this->mFileProps = File::getPropsFromPath( $this->mTempPath, $finalExt );
479 $this->checkMacBinary();
480 $veri = $this->verify( $this->mTempPath, $finalExt );
481
482 if( $veri !== true ) { //it's a wiki error...
483 $resultDetails = array( 'veri' => $veri );
484 return self::VERIFICATION_ERROR;
485 }
486
487 /**
488 * Provide an opportunity for extensions to add further checks
489 */
490 $error = '';
491 if( !wfRunHooks( 'UploadVerification',
492 array( $this->mDestName, $this->mTempPath, &$error ) ) ) {
493 $resultDetails = array( 'error' => $error );
494 return self::UPLOAD_VERIFICATION_ERROR;
495 }
496 }
497
498
499 /**
500 * Check for non-fatal conditions
501 */
502 if ( ! $this->mIgnoreWarning ) {
503 $warning = '';
504
505 global $wgCapitalLinks;
506 if( $wgCapitalLinks ) {
507 $filtered = ucfirst( $filtered );
508 }
509 if( $basename != $filtered ) {
510 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mDestName ) ).'</li>';
511 }
512
513 global $wgCheckFileExtensions;
514 if ( $wgCheckFileExtensions ) {
515 if ( !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
516 $warning .= '<li>' .
517 wfMsgExt( 'filetype-unwanted-type',
518 array( 'parseinline' ),
519 htmlspecialchars( $finalExt ),
520 implode(
521 wfMsgExt( 'comma-separator', array( 'escapenoentities' ) ),
522 $wgFileExtensions
523 )
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 );
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_IMAGE, $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_IMAGE, '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 ) {
751 $hash = File::sha1Base36( $tempfile );
752 $dupes = RepoGroup::singleton()->findBySha1( $hash );
753 if( $dupes ) {
754 global $wgOut;
755 $msg = "<gallery>";
756 foreach( $dupes as $file ) {
757 $title = $file->getTitle();
758 $msg .= $title->getPrefixedText() .
759 "|" . $title->getText() . "\n";
760 }
761 $msg .= "</gallery>";
762 return "<li>" .
763 wfMsgExt( "file-exists-duplicate", array( "parse" ), count( $dupes ) ) .
764 $wgOut->parse( $msg ) .
765 "</li>\n";
766 } else {
767 return '';
768 }
769 }
770
771 /**
772 * Get a list of blacklisted filename prefixes from [[MediaWiki:filename-prefix-blacklist]]
773 *
774 * @return array list of prefixes
775 */
776 public static function getFilenamePrefixBlacklist() {
777 $blacklist = array();
778 $message = wfMsgForContent( 'filename-prefix-blacklist' );
779 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) || $message == '-' ) ) {
780 $lines = explode( "\n", $message );
781 foreach( $lines as $line ) {
782 // Remove comment lines
783 $comment = substr( trim( $line ), 0, 1 );
784 if ( $comment == '#' || $comment == '' ) {
785 continue;
786 }
787 // Remove additional comments after a prefix
788 $comment = strpos( $line, '#' );
789 if ( $comment > 0 ) {
790 $line = substr( $line, 0, $comment-1 );
791 }
792 $blacklist[] = trim( $line );
793 }
794 }
795 return $blacklist;
796 }
797
798 /**
799 * Stash a file in a temporary directory for later processing
800 * after the user has confirmed it.
801 *
802 * If the user doesn't explicitly cancel or accept, these files
803 * can accumulate in the temp directory.
804 *
805 * @param string $saveName - the destination filename
806 * @param string $tempName - the source temporary file to save
807 * @return string - full path the stashed file, or false on failure
808 * @access private
809 */
810 function saveTempUploadedFile( $saveName, $tempName ) {
811 global $wgOut;
812 $repo = RepoGroup::singleton()->getLocalRepo();
813 $status = $repo->storeTemp( $saveName, $tempName );
814 if ( !$status->isGood() ) {
815 $this->showError( $status->getWikiText() );
816 return false;
817 } else {
818 return $status->value;
819 }
820 }
821
822 /**
823 * Stash a file in a temporary directory for later processing,
824 * and save the necessary descriptive info into the session.
825 * Returns a key value which will be passed through a form
826 * to pick up the path info on a later invocation.
827 *
828 * @return int
829 * @access private
830 */
831 function stashSession() {
832 $stash = $this->saveTempUploadedFile( $this->mDestName, $this->mTempPath );
833
834 if( !$stash ) {
835 # Couldn't save the file.
836 return false;
837 }
838
839 $key = mt_rand( 0, 0x7fffffff );
840 $_SESSION['wsUploadData'][$key] = array(
841 'mTempPath' => $stash,
842 'mFileSize' => $this->mFileSize,
843 'mSrcName' => $this->mSrcName,
844 'mFileProps' => $this->mFileProps,
845 'version' => self::SESSION_VERSION,
846 );
847 return $key;
848 }
849
850 /**
851 * Remove a temporarily kept file stashed by saveTempUploadedFile().
852 * @access private
853 * @return success
854 */
855 function unsaveUploadedFile() {
856 global $wgOut;
857 $repo = RepoGroup::singleton()->getLocalRepo();
858 $success = $repo->freeTemp( $this->mTempPath );
859 if ( ! $success ) {
860 $wgOut->showFileDeleteError( $this->mTempPath );
861 return false;
862 } else {
863 return true;
864 }
865 }
866
867 /* -------------------------------------------------------------- */
868
869 /**
870 * @param string $error as HTML
871 * @access private
872 */
873 function uploadError( $error ) {
874 global $wgOut;
875 $wgOut->addHTML( Xml::element( 'h2', null, wfMsg( 'uploadwarning' ) . "\n" ) );
876 $wgOut->addHTML( Xml::tags( 'span', array( 'class' => 'error' ), $error ) );
877 }
878
879 /**
880 * There's something wrong with this file, not enough to reject it
881 * totally but we require manual intervention to save it for real.
882 * Stash it away, then present a form asking to confirm or cancel.
883 *
884 * @param string $warning as HTML
885 * @access private
886 */
887 function uploadWarning( $warning ) {
888 global $wgOut;
889 global $wgUseCopyrightUpload;
890
891 $this->mSessionKey = $this->stashSession();
892 if( !$this->mSessionKey ) {
893 # Couldn't save file; an error has been displayed so let's go.
894 return;
895 }
896
897 $wgOut->addHTML( Xml::element( 'h2', null, wfMsg( 'uploadwarning' ) ) . "\n" );
898 $wgOut->addHTML( Xml::tags( 'ul', array( 'class' => 'warning' ), $warning ) . "\n" );
899
900 $titleObj = SpecialPage::getTitleFor( 'Upload' );
901
902 if ( $wgUseCopyrightUpload ) {
903 $copyright = Xml::hidden( 'wpUploadCopyStatus', $this->mCopyrightStatus ) . "\n" .
904 Xml::hidden( 'wpUploadSource', $this->mCopyrightSource ) . "\n";
905 } else {
906 $copyright = '';
907 }
908
909 $wgOut->addHTML(
910 Xml::openElement( 'form', array( 'method' => 'post', 'action' => $titleObj->getLocalURL( 'action=submit' ),
911 'enctype' => 'multipart/form-data', 'id' => 'uploadwarning' ) ) . "\n" .
912 Xml::hidden( 'wpIgnoreWarning', '1' ) . "\n" .
913 Xml::hidden( 'wpSessionKey', $this->mSessionKey ) . "\n" .
914 Xml::hidden( 'wpUploadDescription', $this->mComment ) . "\n" .
915 Xml::hidden( 'wpLicense', $this->mLicense ) . "\n" .
916 Xml::hidden( 'wpDestFile', $this->mDesiredDestName ) . "\n" .
917 Xml::hidden( 'wpWatchthis', $this->mWatchthis ) . "\n" .
918 "{$copyright}<br />" .
919 Xml::submitButton( wfMsg( 'ignorewarning' ), array ( 'name' => 'wpUpload', 'id' => 'wpUpload', 'checked' => 'checked' ) ) . ' ' .
920 Xml::submitButton( wfMsg( 'reuploaddesc' ), array ( 'name' => 'wpReUpload', 'id' => 'wpReUpload' ) ) .
921 Xml::closeElement( 'form' ) . "\n"
922 );
923 }
924
925 /**
926 * Displays the main upload form, optionally with a highlighted
927 * error message up at the top.
928 *
929 * @param string $msg as HTML
930 * @access private
931 */
932 function mainUploadForm( $msg='' ) {
933 global $wgOut, $wgUser, $wgLang, $wgMaxUploadSize;
934 global $wgUseCopyrightUpload, $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview;
935 global $wgRequest, $wgAllowCopyUploads;
936 global $wgStylePath, $wgStyleVersion;
937
938 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
939 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview;
940
941 $adc = wfBoolToStr( $useAjaxDestCheck );
942 $alp = wfBoolToStr( $useAjaxLicensePreview );
943 $autofill = wfBoolToStr( $this->mDesiredDestName == '' );
944
945 $wgOut->addScript( "<script type=\"text/javascript\">
946 wgAjaxUploadDestCheck = {$adc};
947 wgAjaxLicensePreview = {$alp};
948 wgUploadAutoFill = {$autofill};
949 </script>" );
950 $wgOut->addScriptFile( 'upload.js' );
951 $wgOut->addScriptFile( 'edit.js' ); // For <charinsert> support
952
953 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) )
954 {
955 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
956 return false;
957 }
958
959 if( $this->mDesiredDestName ) {
960 $title = Title::makeTitleSafe( NS_IMAGE, $this->mDesiredDestName );
961 // Show a subtitle link to deleted revisions (to sysops et al only)
962 if( $title instanceof Title && ( $count = $title->isDeleted() ) > 0 && $wgUser->isAllowed( 'deletedhistory' ) ) {
963 $link = wfMsgExt(
964 $wgUser->isAllowed( 'delete' ) ? 'thisisdeleted' : 'viewdeleted',
965 array( 'parse', 'replaceafter' ),
966 $wgUser->getSkin()->makeKnownLinkObj(
967 SpecialPage::getTitleFor( 'Undelete', $title->getPrefixedText() ),
968 wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $count )
969 )
970 );
971 $wgOut->addHtml( "<div id=\"contentSub2\">{$link}</div>" );
972 }
973
974 // Show the relevant lines from deletion log (for still deleted files only)
975 if( $title instanceof Title && $title->isDeleted() > 0 && !$title->exists() ) {
976 $this->showDeletionLog( $wgOut, $title->getPrefixedText() );
977 }
978 }
979
980 $cols = intval($wgUser->getOption( 'cols' ));
981
982 if( $wgUser->getOption( 'editwidth' ) ) {
983 $width = " style=\"width:100%\"";
984 } else {
985 $width = '';
986 }
987
988 if ( '' != $msg ) {
989 $sub = wfMsgHtml( 'uploaderror' );
990 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
991 "<span class='error'>{$msg}</span>\n" );
992 }
993 $wgOut->addHTML( '<div id="uploadtext">' );
994 $wgOut->addWikiMsg( 'uploadtext', $this->mDesiredDestName );
995 $wgOut->addHTML( "</div>\n" );
996
997 # Print a list of allowed file extensions, if so configured. We ignore
998 # MIME type here, it's incomprehensible to most people and too long.
999 global $wgCheckFileExtensions, $wgStrictFileExtensions,
1000 $wgFileExtensions, $wgFileBlacklist;
1001
1002 $allowedExtensions = '';
1003 if( $wgCheckFileExtensions ) {
1004 $delim = wfMsgExt( 'comma-separator', array( 'escapenoentities' ) );
1005 if( $wgStrictFileExtensions ) {
1006 # Everything not permitted is banned
1007 $extensionsList =
1008 '<div id="mw-upload-permitted">' .
1009 wfMsgWikiHtml( 'upload-permitted', implode( $wgFileExtensions, $delim ) ) .
1010 "</div>\n";
1011 } else {
1012 # We have to list both preferred and prohibited
1013 $extensionsList =
1014 '<div id="mw-upload-preferred">' .
1015 wfMsgWikiHtml( 'upload-preferred', implode( $wgFileExtensions, $delim ) ) .
1016 "</div>\n" .
1017 '<div id="mw-upload-prohibited">' .
1018 wfMsgWikiHtml( 'upload-prohibited', implode( $wgFileBlacklist, $delim ) ) .
1019 "</div>\n";
1020 }
1021 } else {
1022 # Everything is permitted.
1023 $extensionsList = '';
1024 }
1025
1026 # Get the maximum file size from php.ini as $wgMaxUploadSize works for uploads from URL via CURL only
1027 # See http://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize for possible values of upload_max_filesize
1028 $val = trim( ini_get( 'upload_max_filesize' ) );
1029 $last = strtoupper( ( substr( $val, -1 ) ) );
1030 switch( $last ) {
1031 case 'G':
1032 $val2 = substr( $val, 0, -1 ) * 1024 * 1024 * 1024;
1033 break;
1034 case 'M':
1035 $val2 = substr( $val, 0, -1 ) * 1024 * 1024;
1036 break;
1037 case 'K':
1038 $val2 = substr( $val, 0, -1 ) * 1024;
1039 break;
1040 default:
1041 $val2 = $val;
1042 }
1043 $val2 = $wgAllowCopyUploads ? min( $wgMaxUploadSize, $val2 ) : $val2;
1044 $maxUploadSize = wfMsgExt( 'upload-maxfilesize', array( 'parseinline', 'escapenoentities' ), $wgLang->formatSize( $val2 ) );
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( Xml::tags( 'div',
1233 array( 'id' => 'mw-upload-footer-message' ), $uploadfooter ) );
1234 }
1235 }
1236
1237 /* -------------------------------------------------------------- */
1238
1239 /**
1240 * See if we should check the 'watch this page' checkbox on the form
1241 * based on the user's preferences and whether we're being asked
1242 * to create a new file or update an existing one.
1243 *
1244 * In the case where 'watch edits' is off but 'watch creations' is on,
1245 * we'll leave the box unchecked.
1246 *
1247 * Note that the page target can be changed *on the form*, so our check
1248 * state can get out of sync.
1249 */
1250 function watchCheck() {
1251 global $wgUser;
1252 if( $wgUser->getOption( 'watchdefault' ) ) {
1253 // Watch all edits!
1254 return true;
1255 }
1256
1257 $local = wfLocalFile( $this->mDesiredDestName );
1258 if( $local && $local->exists() ) {
1259 // We're uploading a new version of an existing file.
1260 // No creation, so don't watch it if we're not already.
1261 return $local->getTitle()->userIsWatching();
1262 } else {
1263 // New page should get watched if that's our option.
1264 return $wgUser->getOption( 'watchcreations' );
1265 }
1266 }
1267
1268 /**
1269 * Split a file into a base name and all dot-delimited 'extensions'
1270 * on the end. Some web server configurations will fall back to
1271 * earlier pseudo-'extensions' to determine type and execute
1272 * scripts, so the blacklist needs to check them all.
1273 *
1274 * @return array
1275 */
1276 function splitExtensions( $filename ) {
1277 $bits = explode( '.', $filename );
1278 $basename = array_shift( $bits );
1279 return array( $basename, $bits );
1280 }
1281
1282 /**
1283 * Perform case-insensitive match against a list of file extensions.
1284 * Returns true if the extension is in the list.
1285 *
1286 * @param string $ext
1287 * @param array $list
1288 * @return bool
1289 */
1290 function checkFileExtension( $ext, $list ) {
1291 return in_array( strtolower( $ext ), $list );
1292 }
1293
1294 /**
1295 * Perform case-insensitive match against a list of file extensions.
1296 * Returns true if any of the extensions are in the list.
1297 *
1298 * @param array $ext
1299 * @param array $list
1300 * @return bool
1301 */
1302 function checkFileExtensionList( $ext, $list ) {
1303 foreach( $ext as $e ) {
1304 if( in_array( strtolower( $e ), $list ) ) {
1305 return true;
1306 }
1307 }
1308 return false;
1309 }
1310
1311 /**
1312 * Verifies that it's ok to include the uploaded file
1313 *
1314 * @param string $tmpfile the full path of the temporary file to verify
1315 * @param string $extension The filename extension that the file is to be served with
1316 * @return mixed true of the file is verified, a WikiError object otherwise.
1317 */
1318 function verify( $tmpfile, $extension ) {
1319 #magically determine mime type
1320 $magic = MimeMagic::singleton();
1321 $mime = $magic->guessMimeType($tmpfile,false);
1322
1323 #check mime type, if desired
1324 global $wgVerifyMimeType;
1325 if ($wgVerifyMimeType) {
1326
1327 wfDebug ( "\n\nmime: <$mime> extension: <$extension>\n\n");
1328 #check mime type against file extension
1329 if( !$this->verifyExtension( $mime, $extension ) ) {
1330 return new WikiErrorMsg( 'uploadcorrupt' );
1331 }
1332
1333 #check mime type blacklist
1334 global $wgMimeTypeBlacklist;
1335 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
1336 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
1337 return new WikiErrorMsg( 'filetype-badmime', htmlspecialchars( $mime ) );
1338 }
1339 }
1340
1341 #check for htmlish code and javascript
1342 if( $this->detectScript ( $tmpfile, $mime, $extension ) ) {
1343 return new WikiErrorMsg( 'uploadscripted' );
1344 }
1345
1346 /**
1347 * Scan the uploaded file for viruses
1348 */
1349 $virus= $this->detectVirus($tmpfile);
1350 if ( $virus ) {
1351 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
1352 }
1353
1354 wfDebug( __METHOD__.": all clear; passing.\n" );
1355 return true;
1356 }
1357
1358 /**
1359 * Checks if the mime type of the uploaded file matches the file extension.
1360 *
1361 * @param string $mime the mime type of the uploaded file
1362 * @param string $extension The filename extension that the file is to be served with
1363 * @return bool
1364 */
1365 function verifyExtension( $mime, $extension ) {
1366 $magic = MimeMagic::singleton();
1367
1368 if ( ! $mime || $mime == 'unknown' || $mime == 'unknown/unknown' )
1369 if ( ! $magic->isRecognizableExtension( $extension ) ) {
1370 wfDebug( __METHOD__.": passing file with unknown detected mime type; " .
1371 "unrecognized extension '$extension', can't verify\n" );
1372 return true;
1373 } else {
1374 wfDebug( __METHOD__.": rejecting file with unknown detected mime type; ".
1375 "recognized extension '$extension', so probably invalid file\n" );
1376 return false;
1377 }
1378
1379 $match= $magic->isMatchingExtension($extension,$mime);
1380
1381 if ($match===NULL) {
1382 wfDebug( __METHOD__.": no file extension known for mime type $mime, passing file\n" );
1383 return true;
1384 } elseif ($match===true) {
1385 wfDebug( __METHOD__.": mime type $mime matches extension $extension, passing file\n" );
1386
1387 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
1388 return true;
1389
1390 } else {
1391 wfDebug( __METHOD__.": mime type $mime mismatches file extension $extension, rejecting file\n" );
1392 return false;
1393 }
1394 }
1395
1396 /**
1397 * Heuristic for detecting files that *could* contain JavaScript instructions or
1398 * things that may look like HTML to a browser and are thus
1399 * potentially harmful. The present implementation will produce false positives in some situations.
1400 *
1401 * @param string $file Pathname to the temporary upload file
1402 * @param string $mime The mime type of the file
1403 * @param string $extension The extension of the file
1404 * @return bool true if the file contains something looking like embedded scripts
1405 */
1406 function detectScript($file, $mime, $extension) {
1407 global $wgAllowTitlesInSVG;
1408
1409 #ugly hack: for text files, always look at the entire file.
1410 #For binarie field, just check the first K.
1411
1412 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
1413 else {
1414 $fp = fopen( $file, 'rb' );
1415 $chunk = fread( $fp, 1024 );
1416 fclose( $fp );
1417 }
1418
1419 $chunk= strtolower( $chunk );
1420
1421 if (!$chunk) return false;
1422
1423 #decode from UTF-16 if needed (could be used for obfuscation).
1424 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
1425 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
1426 else $enc= NULL;
1427
1428 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
1429
1430 $chunk= trim($chunk);
1431
1432 #FIXME: convert from UTF-16 if necessarry!
1433
1434 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
1435
1436 #check for HTML doctype
1437 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
1438
1439 /**
1440 * Internet Explorer for Windows performs some really stupid file type
1441 * autodetection which can cause it to interpret valid image files as HTML
1442 * and potentially execute JavaScript, creating a cross-site scripting
1443 * attack vectors.
1444 *
1445 * Apple's Safari browser also performs some unsafe file type autodetection
1446 * which can cause legitimate files to be interpreted as HTML if the
1447 * web server is not correctly configured to send the right content-type
1448 * (or if you're really uploading plain text and octet streams!)
1449 *
1450 * Returns true if IE is likely to mistake the given file for HTML.
1451 * Also returns true if Safari would mistake the given file for HTML
1452 * when served with a generic content-type.
1453 */
1454
1455 $tags = array(
1456 '<body',
1457 '<head',
1458 '<html', #also in safari
1459 '<img',
1460 '<pre',
1461 '<script', #also in safari
1462 '<table'
1463 );
1464 if( ! $wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1465 $tags[] = '<title';
1466 }
1467
1468 foreach( $tags as $tag ) {
1469 if( false !== strpos( $chunk, $tag ) ) {
1470 return true;
1471 }
1472 }
1473
1474 /*
1475 * look for javascript
1476 */
1477
1478 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1479 $chunk = Sanitizer::decodeCharReferences( $chunk );
1480
1481 #look for script-types
1482 if (preg_match('!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim',$chunk)) return true;
1483
1484 #look for html-style script-urls
1485 if (preg_match('!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1486
1487 #look for css-style script-urls
1488 if (preg_match('!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1489
1490 wfDebug("SpecialUpload::detectScript: no scripts found\n");
1491 return false;
1492 }
1493
1494 /**
1495 * Generic wrapper function for a virus scanner program.
1496 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1497 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1498 *
1499 * @param string $file Pathname to the temporary upload file
1500 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1501 * or a string containing feedback from the virus scanner if a virus was found.
1502 * If textual feedback is missing but a virus was found, this function returns true.
1503 */
1504 function detectVirus($file) {
1505 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1506
1507 if ( !$wgAntivirus ) {
1508 wfDebug( __METHOD__.": virus scanner disabled\n");
1509 return NULL;
1510 }
1511
1512 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1513 wfDebug( __METHOD__.": unknown virus scanner: $wgAntivirus\n" );
1514 # @TODO: localise
1515 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" );
1516 return "unknown antivirus: $wgAntivirus";
1517 }
1518
1519 # look up scanner configuration
1520 $command = $wgAntivirusSetup[$wgAntivirus]["command"];
1521 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]["codemap"];
1522 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]["messagepattern"] ) ?
1523 $wgAntivirusSetup[$wgAntivirus]["messagepattern"] : null;
1524
1525 if ( strpos( $command,"%f" ) === false ) {
1526 # simple pattern: append file to scan
1527 $command .= " " . wfEscapeShellArg( $file );
1528 } else {
1529 # complex pattern: replace "%f" with file to scan
1530 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1531 }
1532
1533 wfDebug( __METHOD__.": running virus scan: $command \n" );
1534
1535 # execute virus scanner
1536 $exitCode = false;
1537
1538 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1539 # that does not seem to be worth the pain.
1540 # Ask me (Duesentrieb) about it if it's ever needed.
1541 $output = array();
1542 if ( wfIsWindows() ) {
1543 exec( "$command", $output, $exitCode );
1544 } else {
1545 exec( "$command 2>&1", $output, $exitCode );
1546 }
1547
1548 # map exit code to AV_xxx constants.
1549 $mappedCode = $exitCode;
1550 if ( $exitCodeMap ) {
1551 if ( isset( $exitCodeMap[$exitCode] ) ) {
1552 $mappedCode = $exitCodeMap[$exitCode];
1553 } elseif ( isset( $exitCodeMap["*"] ) ) {
1554 $mappedCode = $exitCodeMap["*"];
1555 }
1556 }
1557
1558 if ( $mappedCode === AV_SCAN_FAILED ) {
1559 # scan failed (code was mapped to false by $exitCodeMap)
1560 wfDebug( __METHOD__.": failed to scan $file (code $exitCode).\n" );
1561
1562 if ( $wgAntivirusRequired ) {
1563 return "scan failed (code $exitCode)";
1564 } else {
1565 return NULL;
1566 }
1567 } else if ( $mappedCode === AV_SCAN_ABORTED ) {
1568 # scan failed because filetype is unknown (probably imune)
1569 wfDebug( __METHOD__.": unsupported file type $file (code $exitCode).\n" );
1570 return NULL;
1571 } else if ( $mappedCode === AV_NO_VIRUS ) {
1572 # no virus found
1573 wfDebug( __METHOD__.": file passed virus scan.\n" );
1574 return false;
1575 } else {
1576 $output = join( "\n", $output );
1577 $output = trim( $output );
1578
1579 if ( !$output ) {
1580 $output = true; #if there's no output, return true
1581 } elseif ( $msgPattern ) {
1582 $groups = array();
1583 if ( preg_match( $msgPattern, $output, $groups ) ) {
1584 if ( $groups[1] ) {
1585 $output = $groups[1];
1586 }
1587 }
1588 }
1589
1590 wfDebug( __METHOD__.": FOUND VIRUS! scanner feedback: $output" );
1591 return $output;
1592 }
1593 }
1594
1595 /**
1596 * Check if the temporary file is MacBinary-encoded, as some uploads
1597 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
1598 * If so, the data fork will be extracted to a second temporary file,
1599 * which will then be checked for validity and either kept or discarded.
1600 *
1601 * @access private
1602 */
1603 function checkMacBinary() {
1604 $macbin = new MacBinary( $this->mTempPath );
1605 if( $macbin->isValid() ) {
1606 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
1607 $dataHandle = fopen( $dataFile, 'wb' );
1608
1609 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
1610 $macbin->extractData( $dataHandle );
1611
1612 $this->mTempPath = $dataFile;
1613 $this->mFileSize = $macbin->dataForkLength();
1614
1615 // We'll have to manually remove the new file if it's not kept.
1616 $this->mRemoveTempFile = true;
1617 }
1618 $macbin->close();
1619 }
1620
1621 /**
1622 * If we've modified the upload file we need to manually remove it
1623 * on exit to clean up.
1624 * @access private
1625 */
1626 function cleanupTempFile() {
1627 if ( $this->mRemoveTempFile && file_exists( $this->mTempPath ) ) {
1628 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file {$this->mTempPath}\n" );
1629 unlink( $this->mTempPath );
1630 }
1631 }
1632
1633 /**
1634 * Check if there's an overwrite conflict and, if so, if restrictions
1635 * forbid this user from performing the upload.
1636 *
1637 * @return mixed true on success, WikiError on failure
1638 * @access private
1639 */
1640 function checkOverwrite( $name ) {
1641 $img = wfFindFile( $name );
1642
1643 $error = '';
1644 if( $img ) {
1645 global $wgUser, $wgOut;
1646 if( $img->isLocal() ) {
1647 if( !self::userCanReUpload( $wgUser, $img->name ) ) {
1648 $error = 'fileexists-forbidden';
1649 }
1650 } else {
1651 if( !$wgUser->isAllowed( 'reupload' ) ||
1652 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1653 $error = "fileexists-shared-forbidden";
1654 }
1655 }
1656 }
1657
1658 if( $error ) {
1659 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1660 return $errorText;
1661 }
1662
1663 // Rockin', go ahead and upload
1664 return true;
1665 }
1666
1667 /**
1668 * Check if a user is the last uploader
1669 *
1670 * @param User $user
1671 * @param string $img, image name
1672 * @return bool
1673 */
1674 public static function userCanReUpload( User $user, $img ) {
1675 if( $user->isAllowed( 'reupload' ) )
1676 return true; // non-conditional
1677 if( !$user->isAllowed( 'reupload-own' ) )
1678 return false;
1679
1680 $dbr = wfGetDB( DB_SLAVE );
1681 $row = $dbr->selectRow('image',
1682 /* SELECT */ 'img_user',
1683 /* WHERE */ array( 'img_name' => $img )
1684 );
1685 if ( !$row )
1686 return false;
1687
1688 return $user->getId() == $row->img_user;
1689 }
1690
1691 /**
1692 * Display an error with a wikitext description
1693 */
1694 function showError( $description ) {
1695 global $wgOut;
1696 $wgOut->setPageTitle( wfMsg( "internalerror" ) );
1697 $wgOut->setRobotpolicy( "noindex,nofollow" );
1698 $wgOut->setArticleRelated( false );
1699 $wgOut->enableClientCache( false );
1700 $wgOut->addWikiText( $description );
1701 }
1702
1703 /**
1704 * Get the initial image page text based on a comment and optional file status information
1705 */
1706 static function getInitialPageText( $comment, $license, $copyStatus, $source ) {
1707 global $wgUseCopyrightUpload;
1708 if ( $wgUseCopyrightUpload ) {
1709 if ( $license != '' ) {
1710 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1711 }
1712 $pageText = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n" .
1713 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1714 "$licensetxt" .
1715 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1716 } else {
1717 if ( $license != '' ) {
1718 $filedesc = $comment == '' ? '' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n";
1719 $pageText = $filedesc .
1720 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1721 } else {
1722 $pageText = $comment;
1723 }
1724 }
1725 return $pageText;
1726 }
1727
1728 /**
1729 * If there are rows in the deletion log for this file, show them,
1730 * along with a nice little note for the user
1731 *
1732 * @param OutputPage $out
1733 * @param string filename
1734 */
1735 private function showDeletionLog( $out, $filename ) {
1736 global $wgUser;
1737 $loglist = new LogEventsList( $wgUser->getSkin(), $out );
1738 $pager = new LogPager( $loglist, 'delete', false, $filename );
1739 if( $pager->getNumRows() > 0 ) {
1740 $out->addHtml( '<div id="mw-upload-deleted-warn">' );
1741 $out->addWikiMsg( 'upload-wasdeleted' );
1742 $out->addHTML(
1743 $loglist->beginLogEventsList() .
1744 $pager->getBody() .
1745 $loglist->endLogEventsList()
1746 );
1747 $out->addHtml( '</div>' );
1748 }
1749 }
1750 }