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