Fix regression in even sizing of diff columns; forgot to restore a couple bits I...
[mediawiki.git] / includes / SpecialUpload.php
blobaf7597f6452c4afcc17f95946b4baea377d147a1
1 <?php
2 /**
4 * @addtogroup SpecialPage
5 */
8 /**
9 * Entry point
11 function wfSpecialUpload() {
12 global $wgRequest;
13 $form = new UploadForm( $wgRequest );
14 $form->execute();
17 /**
18 * implements Special:Upload
19 * @addtogroup SpecialPage
21 class UploadForm {
22 /**#@+
23 * @access private
25 var $mUploadFile, $mUploadDescription, $mLicense ,$mIgnoreWarning, $mUploadError;
26 var $mUploadSaveName, $mUploadTempName, $mUploadSize, $mUploadOldVersion;
27 var $mUploadCopyStatus, $mUploadSource, $mReUpload, $mAction, $mUpload;
28 var $mOname, $mSessionKey, $mStashed, $mDestFile, $mRemoveTempFile, $mSourceType;
29 var $mUploadTempFileSize = 0;
31 # Placeholders for text injection by hooks (must be HTML)
32 # extensions should take care to _append_ to the present value
33 var $uploadFormTextTop;
34 var $uploadFormTextAfterSummary;
36 /**#@-*/
38 /**
39 * Constructor : initialise object
40 * Get data POSTed through the form and assign them to the object
41 * @param $request Data posted.
43 function UploadForm( &$request ) {
44 global $wgAllowCopyUploads;
45 $this->mDestFile = $request->getText( 'wpDestFile' );
47 if( !$request->wasPosted() ) {
48 # GET requests just give the main form; no data except wpDestfile.
49 return;
52 # Placeholders for text injection by hooks (empty per default)
53 $this->uploadFormTextTop = "";
54 $this->uploadFormTextAfterSummary = "";
56 $this->mIgnoreWarning = $request->getCheck( 'wpIgnoreWarning' );
57 $this->mReUpload = $request->getCheck( 'wpReUpload' );
58 $this->mUpload = $request->getCheck( 'wpUpload' );
60 $this->mUploadDescription = $request->getText( 'wpUploadDescription' );
61 $this->mLicense = $request->getText( 'wpLicense' );
62 $this->mUploadCopyStatus = $request->getText( 'wpUploadCopyStatus' );
63 $this->mUploadSource = $request->getText( 'wpUploadSource' );
64 $this->mWatchthis = $request->getBool( 'wpWatchthis' );
65 $this->mSourceType = $request->getText( 'wpSourceType' );
66 wfDebug( "UploadForm: watchthis is: '$this->mWatchthis'\n" );
68 $this->mAction = $request->getVal( 'action' );
70 $this->mSessionKey = $request->getInt( 'wpSessionKey' );
71 if( !empty( $this->mSessionKey ) &&
72 isset( $_SESSION['wsUploadData'][$this->mSessionKey] ) ) {
73 /**
74 * Confirming a temporarily stashed upload.
75 * We don't want path names to be forged, so we keep
76 * them in the session on the server and just give
77 * an opaque key to the user agent.
79 $data = $_SESSION['wsUploadData'][$this->mSessionKey];
80 $this->mUploadTempName = $data['mUploadTempName'];
81 $this->mUploadSize = $data['mUploadSize'];
82 $this->mOname = $data['mOname'];
83 $this->mUploadError = 0/*UPLOAD_ERR_OK*/;
84 $this->mStashed = true;
85 $this->mRemoveTempFile = false;
86 } else {
87 /**
88 *Check for a newly uploaded file.
90 if( $wgAllowCopyUploads && $this->mSourceType == 'web' ) {
91 $this->initializeFromUrl( $request );
92 } else {
93 $this->initializeFromUpload( $request );
98 /**
99 * Initialize the uploaded file from PHP data
100 * @access private
102 function initializeFromUpload( $request ) {
103 $this->mUploadTempName = $request->getFileTempName( 'wpUploadFile' );
104 $this->mUploadSize = $request->getFileSize( 'wpUploadFile' );
105 $this->mOname = $request->getFileName( 'wpUploadFile' );
106 $this->mUploadError = $request->getUploadError( 'wpUploadFile' );
107 $this->mSessionKey = false;
108 $this->mStashed = false;
109 $this->mRemoveTempFile = false; // PHP will handle this
113 * Copy a web file to a temporary file
114 * @access private
116 function initializeFromUrl( $request ) {
117 global $wgTmpDirectory;
118 $url = $request->getText( 'wpUploadFileURL' );
119 $local_file = tempnam( $wgTmpDirectory, 'WEBUPLOAD' );
121 $this->mUploadTempName = $local_file;
122 $this->mUploadError = $this->curlCopy( $url, $local_file );
123 $this->mUploadSize = $this->mUploadTempFileSize;
124 $this->mOname = array_pop( explode( '/', $url ) );
125 $this->mSessionKey = false;
126 $this->mStashed = false;
128 // PHP won't auto-cleanup the file
129 $this->mRemoveTempFile = file_exists( $local_file );
133 * Safe copy from URL
134 * Returns true if there was an error, false otherwise
136 private function curlCopy( $url, $dest ) {
137 global $wgUser, $wgOut;
139 if( !$wgUser->isAllowed( 'upload_by_url' ) ) {
140 $wgOut->permissionRequired( 'upload_by_url' );
141 return true;
144 # Maybe remove some pasting blanks :-)
145 $url = trim( $url );
146 if( stripos($url, 'http://') !== 0 && stripos($url, 'ftp://') !== 0 ) {
147 # Only HTTP or FTP URLs
148 $wgOut->errorPage( 'upload-proto-error', 'upload-proto-error-text' );
149 return true;
152 # Open temporary file
153 $this->mUploadTempFile = @fopen( $this->mUploadTempName, "wb" );
154 if( $this->mUploadTempFile === false ) {
155 # Could not open temporary file to write in
156 $wgOut->errorPage( 'upload-file-error', 'upload-file-error-text');
157 return true;
160 $ch = curl_init();
161 curl_setopt( $ch, CURLOPT_HTTP_VERSION, 1.0); # Probably not needed, but apparently can work around some bug
162 curl_setopt( $ch, CURLOPT_TIMEOUT, 10); # 10 seconds timeout
163 curl_setopt( $ch, CURLOPT_LOW_SPEED_LIMIT, 512); # 0.5KB per second minimum transfer speed
164 curl_setopt( $ch, CURLOPT_URL, $url);
165 curl_setopt( $ch, CURLOPT_WRITEFUNCTION, array( $this, 'uploadCurlCallback' ) );
166 curl_exec( $ch );
167 $error = curl_errno( $ch ) ? true : false;
168 $errornum = curl_errno( $ch );
169 // if ( $error ) print curl_error ( $ch ) ; # Debugging output
170 curl_close( $ch );
172 fclose( $this->mUploadTempFile );
173 unset( $this->mUploadTempFile );
174 if( $error ) {
175 unlink( $dest );
176 if( wfEmptyMsg( "upload-curl-error$errornum", wfMsg("upload-curl-error$errornum") ) )
177 $wgOut->errorPage( 'upload-misc-error', 'upload-misc-error-text' );
178 else
179 $wgOut->errorPage( "upload-curl-error$errornum", "upload-curl-error$errornum-text" );
182 return $error;
186 * Callback function for CURL-based web transfer
187 * Write data to file unless we've passed the length limit;
188 * if so, abort immediately.
189 * @access private
191 function uploadCurlCallback( $ch, $data ) {
192 global $wgMaxUploadSize;
193 $length = strlen( $data );
194 $this->mUploadTempFileSize += $length;
195 if( $this->mUploadTempFileSize > $wgMaxUploadSize ) {
196 return 0;
198 fwrite( $this->mUploadTempFile, $data );
199 return $length;
203 * Start doing stuff
204 * @access public
206 function execute() {
207 global $wgUser, $wgOut;
208 global $wgEnableUploads, $wgUploadDirectory;
210 # Check uploading enabled
211 if( !$wgEnableUploads ) {
212 $wgOut->showErrorPage( 'uploaddisabled', 'uploaddisabledtext' );
213 return;
216 # Check permissions
217 if( !$wgUser->isAllowed( 'upload' ) ) {
218 if( !$wgUser->isLoggedIn() ) {
219 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
220 } else {
221 $wgOut->permissionRequired( 'upload' );
223 return;
226 # Check blocks
227 if( $wgUser->isBlocked() ) {
228 $wgOut->blockedPage();
229 return;
232 if( wfReadOnly() ) {
233 $wgOut->readOnlyPage();
234 return;
237 /** Check if the image directory is writeable, this is a common mistake */
238 if( !is_writeable( $wgUploadDirectory ) ) {
239 $wgOut->addWikiText( wfMsg( 'upload_directory_read_only', $wgUploadDirectory ) );
240 return;
243 if( $this->mReUpload ) {
244 if( !$this->unsaveUploadedFile() ) {
245 return;
247 $this->mainUploadForm();
248 } else if( 'submit' == $this->mAction || $this->mUpload ) {
249 $this->processUpload();
250 } else {
251 $this->mainUploadForm();
254 $this->cleanupTempFile();
257 /* -------------------------------------------------------------- */
260 * Really do the upload
261 * Checks are made in SpecialUpload::execute()
262 * @access private
264 function processUpload() {
265 global $wgUser, $wgOut;
267 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) )
269 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file." );
270 return false;
273 /* Check for PHP error if any, requires php 4.2 or newer */
274 if( $this->mUploadError == 1/*UPLOAD_ERR_INI_SIZE*/ ) {
275 $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
276 return;
280 * If there was no filename or a zero size given, give up quick.
282 if( trim( $this->mOname ) == '' || empty( $this->mUploadSize ) ) {
283 $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
284 return;
287 # Chop off any directories in the given filename
288 if( $this->mDestFile ) {
289 $basename = wfBaseName( $this->mDestFile );
290 } else {
291 $basename = wfBaseName( $this->mOname );
295 * We'll want to blacklist against *any* 'extension', and use
296 * only the final one for the whitelist.
298 list( $partname, $ext ) = $this->splitExtensions( $basename );
300 if( count( $ext ) ) {
301 $finalExt = $ext[count( $ext ) - 1];
302 } else {
303 $finalExt = '';
306 # If there was more than one "extension", reassemble the base
307 # filename to prevent bogus complaints about length
308 if( count( $ext ) > 1 ) {
309 for( $i = 0; $i < count( $ext ) - 1; $i++ )
310 $partname .= '.' . $ext[$i];
313 if( strlen( $partname ) < 3 ) {
314 $this->mainUploadForm( wfMsgHtml( 'minlength' ) );
315 return;
319 * Filter out illegal characters, and try to make a legible name
320 * out of it. We'll strip some silently that Title would die on.
322 $filtered = preg_replace ( "/[^".Title::legalChars()."]|:/", '-', $basename );
323 $nt = Title::newFromText( $filtered );
324 if( is_null( $nt ) ) {
325 $this->uploadError( wfMsgWikiHtml( 'illegalfilename', htmlspecialchars( $filtered ) ) );
326 return;
328 $nt =& Title::makeTitle( NS_IMAGE, $nt->getDBkey() );
329 $this->mUploadSaveName = $nt->getDBkey();
332 * If the image is protected, non-sysop users won't be able
333 * to modify it by uploading a new revision.
335 if( !$nt->userCan( 'edit' ) ) {
336 return $this->uploadError( wfMsgWikiHtml( 'protectedpage' ) );
340 * In some cases we may forbid overwriting of existing files.
342 $overwrite = $this->checkOverwrite( $this->mUploadSaveName );
343 if( WikiError::isError( $overwrite ) ) {
344 return $this->uploadError( $overwrite->toString() );
347 /* Don't allow users to override the blacklist (check file extension) */
348 global $wgStrictFileExtensions;
349 global $wgFileExtensions, $wgFileBlacklist;
350 if ($finalExt == '') {
351 return $this->uploadError( wfMsgExt( 'filetype-missing', array ( 'parseinline' ) ) );
352 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
353 ($wgStrictFileExtensions &&
354 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
355 return $this->uploadError( wfMsgExt( 'filetype-badtype', array ( 'parseinline' ), htmlspecialchars( $finalExt ), implode ( ', ', $wgFileExtensions ) ) );
359 * Look at the contents of the file; if we can recognize the
360 * type but it's corrupt or data of the wrong type, we should
361 * probably not accept it.
363 if( !$this->mStashed ) {
364 $this->checkMacBinary();
365 $veri = $this->verify( $this->mUploadTempName, $finalExt );
367 if( $veri !== true ) { //it's a wiki error...
368 return $this->uploadError( $veri->toString() );
373 * Provide an opportunity for extensions to add futher checks
375 $error = '';
376 if( !wfRunHooks( 'UploadVerification',
377 array( $this->mUploadSaveName, $this->mUploadTempName, &$error ) ) ) {
378 return $this->uploadError( $error );
382 * Check for non-fatal conditions
384 if ( ! $this->mIgnoreWarning ) {
385 $warning = '';
387 global $wgCapitalLinks;
388 if( $wgCapitalLinks ) {
389 $filtered = ucfirst( $filtered );
391 if( $this->mUploadSaveName != $filtered ) {
392 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mUploadSaveName ) ).'</li>';
395 global $wgCheckFileExtensions;
396 if ( $wgCheckFileExtensions ) {
397 if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
398 $warning .= '<li>'.wfMsgExt( 'filetype-badtype', array ( 'parseinline' ), htmlspecialchars( $finalExt ), implode ( ', ', $wgFileExtensions ) ).'</li>';
402 global $wgUploadSizeWarning;
403 if ( $wgUploadSizeWarning && ( $this->mUploadSize > $wgUploadSizeWarning ) ) {
404 $skin = $wgUser->getSkin();
405 $wsize = $skin->formatSize( $wgUploadSizeWarning );
406 $asize = $skin->formatSize( $this->mUploadSize );
407 $warning .= '<li>' . wfMsgHtml( 'large-file', $wsize, $asize ) . '</li>';
409 if ( $this->mUploadSize == 0 ) {
410 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
413 global $wgUser;
414 $sk = $wgUser->getSkin();
415 $image = new Image( $nt );
417 // Check for uppercase extension. We allow these filenames but check if an image
418 // with lowercase extension exists already
419 if ( $finalExt != strtolower( $finalExt ) ) {
420 $nt_lc = Title::newFromText( $partname . '.' . strtolower( $finalExt ) );
421 $image_lc = new Image( $nt_lc );
424 if( $image->exists() ) {
425 $dlink = $sk->makeKnownLinkObj( $nt );
426 if ( $image->allowInlineDisplay() ) {
427 $dlink2 = $sk->makeImageLinkObj( $nt, wfMsgExt( 'fileexists-thumb', 'parseinline', $dlink ), $nt->getText(), 'right', array(), false, true );
428 } elseif ( !$image->allowInlineDisplay() && $image->isSafeFile() ) {
429 $icon = $image->iconThumb();
430 $dlink2 = '<div style="float:right" id="mw-media-icon"><a href="' . $image->getURL() . '">' . $icon->toHtml() . '</a><br />' . $dlink . '</div>';
431 } else {
432 $dlink2 = '';
435 $warning .= '<li>' . wfMsgExt( 'fileexists', 'parseline', $dlink ) . '</li>' . $dlink2;
437 } elseif ( isset( $image_lc) && $image_lc->exists() ) {
438 # Check if image with lowercase extension exists.
439 # It's not forbidden but in 99% it makes no sense to upload the same filename with uppercase extension
440 $dlink = $sk->makeKnownLinkObj( $nt_lc );
441 if ( $image_lc->allowInlineDisplay() ) {
442 $dlink2 = $sk->makeImageLinkObj( $nt_lc, wfMsgExt( 'fileexists-thumb', 'parseinline', $dlink ), $nt_lc->getText(), 'right', array(), false, true );
443 } elseif ( !$image_lc->allowInlineDisplay() && $image_lc->isSafeFile() ) {
444 $icon = $image_lc->iconThumb();
445 $dlink2 = '<div style="float:right" id="mw-media-icon"><a href="' . $image_lc->getURL() . '">' . $icon->toHtml() . '</a><br />' . $dlink . '</div>';
446 } else {
447 $dlink2 = '';
450 $warning .= '<li>' . wfMsgExt( 'fileexists-extension', 'parsemag' , $partname . '.' . $finalExt , $dlink ) . '</li>' . $dlink2;
452 } elseif ( ( substr( $partname , 3, 3 ) == 'px-' || substr( $partname , 2, 3 ) == 'px-' ) && ereg( "[0-9]{2}" , substr( $partname , 0, 2) ) ) {
453 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
454 $nt_thb = Title::newFromText( substr( $partname , strpos( $partname , '-' ) +1 ) . '.' . $finalExt );
455 $image_thb = new Image( $nt_thb );
456 if ($image_thb->exists() ) {
457 # Check if an image without leading '180px-' (or similiar) exists
458 $dlink = $sk->makeKnownLinkObj( $nt_thb);
459 if ( $image_thb->allowInlineDisplay() ) {
460 $dlink2 = $sk->makeImageLinkObj( $nt_thb, wfMsgExt( 'fileexists-thumb', 'parseinline', $dlink ), $nt_thb->getText(), 'right', array(), false, true );
461 } elseif ( !$image_thb->allowInlineDisplay() && $image_thb->isSafeFile() ) {
462 $icon = $image_thb->iconThumb();
463 $dlink2 = '<div style="float:right" id="mw-media-icon"><a href="' . $image_thb->getURL() . '">' . $icon->toHtml() . '</a><br />' . $dlink . '</div>';
464 } else {
465 $dlink2 = '';
468 $warning .= '<li>' . wfMsgExt( 'fileexists-thumbnail-yes', 'parsemag', $dlink ) . '</li>' . $dlink2;
469 } else {
470 # Image w/o '180px-' does not exists, but we do not like these filenames
471 $warning .= '<li>' . wfMsgExt( 'file-thumbnail-no', 'parseinline' , substr( $partname , 0, strpos( $partname , '-' ) +1 ) ) . '</li>';
474 if ( $image->wasDeleted() ) {
475 # If the file existed before and was deleted, warn the user of this
476 # Don't bother doing so if the image exists now, however
477 $ltitle = SpecialPage::getTitleFor( 'Log' );
478 $llink = $sk->makeKnownLinkObj( $ltitle, wfMsgHtml( 'deletionlog' ), 'type=delete&page=' . $nt->getPrefixedUrl() );
479 $warning .= wfOpenElement( 'li' ) . wfMsgWikiHtml( 'filewasdeleted', $llink ) . wfCloseElement( 'li' );
482 if( $warning != '' ) {
484 * Stash the file in a temporary location; the user can choose
485 * to let it through and we'll complete the upload then.
487 return $this->uploadWarning( $warning );
492 * Try actually saving the thing...
493 * It will show an error form on failure.
495 $hasBeenMunged = !empty( $this->mSessionKey ) || $this->mRemoveTempFile;
496 if( $this->saveUploadedFile( $this->mUploadSaveName,
497 $this->mUploadTempName,
498 $hasBeenMunged ) ) {
500 * Update the upload log and create the description page
501 * if it's a new file.
503 $img = Image::newFromName( $this->mUploadSaveName );
504 $success = $img->recordUpload( $this->mUploadOldVersion,
505 $this->mUploadDescription,
506 $this->mLicense,
507 $this->mUploadCopyStatus,
508 $this->mUploadSource,
509 $this->mWatchthis );
511 if ( $success ) {
512 $this->showSuccess();
513 wfRunHooks( 'UploadComplete', array( &$img ) );
514 } else {
515 // Image::recordUpload() fails if the image went missing, which is
516 // unlikely, hence the lack of a specialised message
517 $wgOut->showFileNotFoundError( $this->mUploadSaveName );
523 * Move the uploaded file from its temporary location to the final
524 * destination. If a previous version of the file exists, move
525 * it into the archive subdirectory.
527 * @todo If the later save fails, we may have disappeared the original file.
529 * @param string $saveName
530 * @param string $tempName full path to the temporary file
531 * @param bool $useRename if true, doesn't check that the source file
532 * is a PHP-managed upload temporary
534 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
535 global $wgOut, $wgAllowCopyUploads;
537 if ( !$useRename AND $wgAllowCopyUploads AND $this->mSourceType == 'web' ) $useRename = true;
539 $fname= "SpecialUpload::saveUploadedFile";
541 $dest = wfImageDir( $saveName );
542 $archive = wfImageArchiveDir( $saveName );
543 if ( !is_dir( $dest ) ) wfMkdirParents( $dest );
544 if ( !is_dir( $archive ) ) wfMkdirParents( $archive );
546 $this->mSavedFile = "{$dest}/{$saveName}";
548 if( is_file( $this->mSavedFile ) ) {
549 $this->mUploadOldVersion = gmdate( 'YmdHis' ) . "!{$saveName}";
550 wfSuppressWarnings();
551 $success = rename( $this->mSavedFile, "${archive}/{$this->mUploadOldVersion}" );
552 wfRestoreWarnings();
554 if( ! $success ) {
555 $wgOut->showFileRenameError( $this->mSavedFile,
556 "${archive}/{$this->mUploadOldVersion}" );
557 return false;
559 else wfDebug("$fname: moved file ".$this->mSavedFile." to ${archive}/{$this->mUploadOldVersion}\n");
561 else {
562 $this->mUploadOldVersion = '';
565 wfSuppressWarnings();
566 $success = $useRename
567 ? rename( $tempName, $this->mSavedFile )
568 : move_uploaded_file( $tempName, $this->mSavedFile );
569 wfRestoreWarnings();
571 if( ! $success ) {
572 $wgOut->showFileCopyError( $tempName, $this->mSavedFile );
573 return false;
574 } else {
575 wfDebug("$fname: wrote tempfile $tempName to ".$this->mSavedFile."\n");
578 chmod( $this->mSavedFile, 0644 );
579 return true;
583 * Stash a file in a temporary directory for later processing
584 * after the user has confirmed it.
586 * If the user doesn't explicitly cancel or accept, these files
587 * can accumulate in the temp directory.
589 * @param string $saveName - the destination filename
590 * @param string $tempName - the source temporary file to save
591 * @return string - full path the stashed file, or false on failure
592 * @access private
594 function saveTempUploadedFile( $saveName, $tempName ) {
595 global $wgOut;
596 $archive = wfImageArchiveDir( $saveName, 'temp' );
597 if ( !is_dir ( $archive ) ) wfMkdirParents( $archive );
598 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
600 $success = $this->mRemoveTempFile
601 ? rename( $tempName, $stash )
602 : move_uploaded_file( $tempName, $stash );
603 if ( !$success ) {
604 $wgOut->showFileCopyError( $tempName, $stash );
605 return false;
608 return $stash;
612 * Stash a file in a temporary directory for later processing,
613 * and save the necessary descriptive info into the session.
614 * Returns a key value which will be passed through a form
615 * to pick up the path info on a later invocation.
617 * @return int
618 * @access private
620 function stashSession() {
621 $stash = $this->saveTempUploadedFile(
622 $this->mUploadSaveName, $this->mUploadTempName );
624 if( !$stash ) {
625 # Couldn't save the file.
626 return false;
629 $key = mt_rand( 0, 0x7fffffff );
630 $_SESSION['wsUploadData'][$key] = array(
631 'mUploadTempName' => $stash,
632 'mUploadSize' => $this->mUploadSize,
633 'mOname' => $this->mOname );
634 return $key;
638 * Remove a temporarily kept file stashed by saveTempUploadedFile().
639 * @access private
640 * @return success
642 function unsaveUploadedFile() {
643 global $wgOut;
644 wfSuppressWarnings();
645 $success = unlink( $this->mUploadTempName );
646 wfRestoreWarnings();
647 if ( ! $success ) {
648 $wgOut->showFileDeleteError( $this->mUploadTempName );
649 return false;
650 } else {
651 return true;
655 /* -------------------------------------------------------------- */
658 * Show some text and linkage on successful upload.
659 * @access private
661 function showSuccess() {
662 global $wgUser, $wgOut, $wgContLang;
664 $sk = $wgUser->getSkin();
665 $ilink = $sk->makeMediaLink( $this->mUploadSaveName, Image::imageUrl( $this->mUploadSaveName ) );
666 $dname = $wgContLang->getNsText( NS_IMAGE ) . ':'.$this->mUploadSaveName;
667 $dlink = $sk->makeKnownLink( $dname, $dname );
669 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'successfulupload' ) . "</h2>\n" );
670 $text = wfMsgWikiHtml( 'fileuploaded', $ilink, $dlink );
671 $wgOut->addHTML( $text );
672 $wgOut->returnToMain( false );
676 * @param string $error as HTML
677 * @access private
679 function uploadError( $error ) {
680 global $wgOut;
681 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
682 $wgOut->addHTML( "<span class='error'>{$error}</span>\n" );
686 * There's something wrong with this file, not enough to reject it
687 * totally but we require manual intervention to save it for real.
688 * Stash it away, then present a form asking to confirm or cancel.
690 * @param string $warning as HTML
691 * @access private
693 function uploadWarning( $warning ) {
694 global $wgOut;
695 global $wgUseCopyrightUpload;
697 $this->mSessionKey = $this->stashSession();
698 if( !$this->mSessionKey ) {
699 # Couldn't save file; an error has been displayed so let's go.
700 return;
703 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
704 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
706 $save = wfMsgHtml( 'savefile' );
707 $reupload = wfMsgHtml( 'reupload' );
708 $iw = wfMsgWikiHtml( 'ignorewarning' );
709 $reup = wfMsgWikiHtml( 'reuploaddesc' );
710 $titleObj = SpecialPage::getTitleFor( 'Upload' );
711 $action = $titleObj->escapeLocalURL( 'action=submit' );
713 if ( $wgUseCopyrightUpload )
715 $copyright = "
716 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mUploadCopyStatus ) . "\" />
717 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mUploadSource ) . "\" />
719 } else {
720 $copyright = "";
723 $wgOut->addHTML( "
724 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
725 <input type='hidden' name='wpIgnoreWarning' value='1' />
726 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey ) . "\" />
727 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mUploadDescription ) . "\" />
728 <input type='hidden' name='wpLicense' value=\"" . htmlspecialchars( $this->mLicense ) . "\" />
729 <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDestFile ) . "\" />
730 <input type='hidden' name='wpWatchthis' value=\"" . htmlspecialchars( intval( $this->mWatchthis ) ) . "\" />
731 {$copyright}
732 <table border='0'>
733 <tr>
734 <tr>
735 <td align='right'>
736 <input tabindex='2' type='submit' name='wpUpload' value=\"$save\" />
737 </td>
738 <td align='left'>$iw</td>
739 </tr>
740 <tr>
741 <td align='right'>
742 <input tabindex='2' type='submit' name='wpReUpload' value=\"{$reupload}\" />
743 </td>
744 <td align='left'>$reup</td>
745 </tr>
746 </tr>
747 </table></form>\n" );
751 * Displays the main upload form, optionally with a highlighted
752 * error message up at the top.
754 * @param string $msg as HTML
755 * @access private
757 function mainUploadForm( $msg='' ) {
758 global $wgOut, $wgUser;
759 global $wgUseCopyrightUpload;
760 global $wgRequest, $wgAllowCopyUploads;
762 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) )
764 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
765 return false;
768 $cols = intval($wgUser->getOption( 'cols' ));
769 $ew = $wgUser->getOption( 'editwidth' );
770 if ( $ew ) $ew = " style=\"width:100%\"";
771 else $ew = '';
773 if ( '' != $msg ) {
774 $sub = wfMsgHtml( 'uploaderror' );
775 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
776 "<span class='error'>{$msg}</span>\n" );
778 $wgOut->addHTML( '<div id="uploadtext">' );
779 $wgOut->addWikiText( wfMsgNoTrans( 'uploadtext', $this->mDestFile ) );
780 $wgOut->addHTML( '</div>' );
782 $sourcefilename = wfMsgHtml( 'sourcefilename' );
783 $destfilename = wfMsgHtml( 'destfilename' );
784 $summary = wfMsgWikiHtml( 'fileuploadsummary' );
786 $licenses = new Licenses();
787 $license = wfMsgHtml( 'license' );
788 $nolicense = wfMsgHtml( 'nolicense' );
789 $licenseshtml = $licenses->getHtml();
791 $ulb = wfMsgHtml( 'uploadbtn' );
794 $titleObj = SpecialPage::getTitleFor( 'Upload' );
795 $action = $titleObj->escapeLocalURL();
797 $encDestFile = htmlspecialchars( $this->mDestFile );
799 $watchChecked =
800 ( $wgUser->getOption( 'watchdefault' ) ||
801 ( $wgUser->getOption( 'watchcreations' ) && $this->mDestFile == '' ) )
802 ? 'checked="checked"'
803 : '';
805 // Prepare form for upload or upload/copy
806 if( $wgAllowCopyUploads && $wgUser->isAllowed( 'upload_by_url' ) ) {
807 $filename_form =
808 "<input type='radio' id='wpSourceTypeFile' name='wpSourceType' value='file' onchange='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\")' checked />" .
809 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' onfocus='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\");toggle_element_check(\"wpSourceTypeFile\",\"wpSourceTypeURL\")'" .
810 ($this->mDestFile?"":"onchange='fillDestFilename(\"wpUploadFile\")' ") . "size='40' />" .
811 wfMsgHTML( 'upload_source_file' ) . "<br/>" .
812 "<input type='radio' id='wpSourceTypeURL' name='wpSourceType' value='web' onchange='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\")' />" .
813 "<input tabindex='1' type='text' name='wpUploadFileURL' id='wpUploadFileURL' onfocus='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\");toggle_element_check(\"wpSourceTypeURL\",\"wpSourceTypeFile\")'" .
814 ($this->mDestFile?"":"onchange='fillDestFilename(\"wpUploadFileURL\")' ") . "size='40' DISABLED />" .
815 wfMsgHtml( 'upload_source_url' ) ;
816 } else {
817 $filename_form =
818 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
819 ($this->mDestFile?"":"onchange='fillDestFilename(\"wpUploadFile\")' ") .
820 "size='40' />" .
821 "<input type='hidden' name='wpSourceType' value='file' />" ;
824 $wgOut->addHTML( "
825 <form id='upload' method='post' enctype='multipart/form-data' action=\"$action\">
826 <table border='0'>
827 <tr>
828 {$this->uploadFormTextTop}
829 <td align='right' valign='top'><label for='wpUploadFile'>{$sourcefilename}:</label></td>
830 <td align='left'>
831 {$filename_form}
832 </td>
833 </tr>
834 <tr>
835 <td align='right'><label for='wpDestFile'>{$destfilename}:</label></td>
836 <td align='left'>
837 <input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='40' value=\"$encDestFile\" />
838 </td>
839 </tr>
840 <tr>
841 <td align='right'><label for='wpUploadDescription'>{$summary}</label></td>
842 <td align='left'>
843 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6' cols='{$cols}'{$ew}>" . htmlspecialchars( $this->mUploadDescription ) . "</textarea>
844 {$this->uploadFormTextAfterSummary}
845 </td>
846 </tr>
847 <tr>" );
849 if ( $licenseshtml != '' ) {
850 global $wgStylePath;
851 $wgOut->addHTML( "
852 <td align='right'><label for='wpLicense'>$license:</label></td>
853 <td align='left'>
854 <script type='text/javascript' src=\"$wgStylePath/common/upload.js\"></script>
855 <select name='wpLicense' id='wpLicense' tabindex='4'
856 onchange='licenseSelectorCheck()'>
857 <option value=''>$nolicense</option>
858 $licenseshtml
859 </select>
860 </td>
861 </tr>
862 <tr>
866 if ( $wgUseCopyrightUpload ) {
867 $filestatus = wfMsgHtml ( 'filestatus' );
868 $copystatus = htmlspecialchars( $this->mUploadCopyStatus );
869 $filesource = wfMsgHtml ( 'filesource' );
870 $uploadsource = htmlspecialchars( $this->mUploadSource );
872 $wgOut->addHTML( "
873 <td align='right' nowrap='nowrap'><label for='wpUploadCopyStatus'>$filestatus:</label></td>
874 <td><input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus' value=\"$copystatus\" size='40' /></td>
875 </tr>
876 <tr>
877 <td align='right'><label for='wpUploadCopyStatus'>$filesource:</label></td>
878 <td><input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus' value=\"$uploadsource\" size='40' /></td>
879 </tr>
880 <tr>
885 $wgOut->addHtml( "
886 <td></td>
887 <td>
888 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
889 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthisupload' ) . "</label>
890 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' />
891 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
892 </td>
893 </tr>
894 <tr>
895 <td></td>
896 <td align='left'><input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\" /></td>
897 </tr>
899 <tr>
900 <td></td>
901 <td align='left'>
902 " );
903 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
904 $wgOut->addHTML( "
905 </td>
906 </tr>
908 </table>
909 </form>" );
912 /* -------------------------------------------------------------- */
915 * Split a file into a base name and all dot-delimited 'extensions'
916 * on the end. Some web server configurations will fall back to
917 * earlier pseudo-'extensions' to determine type and execute
918 * scripts, so the blacklist needs to check them all.
920 * @return array
922 function splitExtensions( $filename ) {
923 $bits = explode( '.', $filename );
924 $basename = array_shift( $bits );
925 return array( $basename, $bits );
929 * Perform case-insensitive match against a list of file extensions.
930 * Returns true if the extension is in the list.
932 * @param string $ext
933 * @param array $list
934 * @return bool
936 function checkFileExtension( $ext, $list ) {
937 return in_array( strtolower( $ext ), $list );
941 * Perform case-insensitive match against a list of file extensions.
942 * Returns true if any of the extensions are in the list.
944 * @param array $ext
945 * @param array $list
946 * @return bool
948 function checkFileExtensionList( $ext, $list ) {
949 foreach( $ext as $e ) {
950 if( in_array( strtolower( $e ), $list ) ) {
951 return true;
954 return false;
958 * Verifies that it's ok to include the uploaded file
960 * @param string $tmpfile the full path of the temporary file to verify
961 * @param string $extension The filename extension that the file is to be served with
962 * @return mixed true of the file is verified, a WikiError object otherwise.
964 function verify( $tmpfile, $extension ) {
965 #magically determine mime type
966 $magic=& MimeMagic::singleton();
967 $mime= $magic->guessMimeType($tmpfile,false);
969 $fname= "SpecialUpload::verify";
971 #check mime type, if desired
972 global $wgVerifyMimeType;
973 if ($wgVerifyMimeType) {
975 #check mime type against file extension
976 if( !$this->verifyExtension( $mime, $extension ) ) {
977 return new WikiErrorMsg( 'uploadcorrupt' );
980 #check mime type blacklist
981 global $wgMimeTypeBlacklist;
982 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
983 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
984 return new WikiErrorMsg( 'filetype-badmime', htmlspecialchars( $mime ) );
988 #check for htmlish code and javascript
989 if( $this->detectScript ( $tmpfile, $mime, $extension ) ) {
990 return new WikiErrorMsg( 'uploadscripted' );
994 * Scan the uploaded file for viruses
996 $virus= $this->detectVirus($tmpfile);
997 if ( $virus ) {
998 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
1001 wfDebug( "$fname: all clear; passing.\n" );
1002 return true;
1006 * Checks if the mime type of the uploaded file matches the file extension.
1008 * @param string $mime the mime type of the uploaded file
1009 * @param string $extension The filename extension that the file is to be served with
1010 * @return bool
1012 function verifyExtension( $mime, $extension ) {
1013 $fname = 'SpecialUpload::verifyExtension';
1015 $magic =& MimeMagic::singleton();
1017 if ( ! $mime || $mime == 'unknown' || $mime == 'unknown/unknown' )
1018 if ( ! $magic->isRecognizableExtension( $extension ) ) {
1019 wfDebug( "$fname: passing file with unknown detected mime type; unrecognized extension '$extension', can't verify\n" );
1020 return true;
1021 } else {
1022 wfDebug( "$fname: rejecting file with unknown detected mime type; recognized extension '$extension', so probably invalid file\n" );
1023 return false;
1026 $match= $magic->isMatchingExtension($extension,$mime);
1028 if ($match===NULL) {
1029 wfDebug( "$fname: no file extension known for mime type $mime, passing file\n" );
1030 return true;
1031 } elseif ($match===true) {
1032 wfDebug( "$fname: mime type $mime matches extension $extension, passing file\n" );
1034 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
1035 return true;
1037 } else {
1038 wfDebug( "$fname: mime type $mime mismatches file extension $extension, rejecting file\n" );
1039 return false;
1043 /** Heuristig for detecting files that *could* contain JavaScript instructions or
1044 * things that may look like HTML to a browser and are thus
1045 * potentially harmful. The present implementation will produce false positives in some situations.
1047 * @param string $file Pathname to the temporary upload file
1048 * @param string $mime The mime type of the file
1049 * @param string $extension The extension of the file
1050 * @return bool true if the file contains something looking like embedded scripts
1052 function detectScript($file, $mime, $extension) {
1053 global $wgAllowTitlesInSVG;
1055 #ugly hack: for text files, always look at the entire file.
1056 #For binarie field, just check the first K.
1058 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
1059 else {
1060 $fp = fopen( $file, 'rb' );
1061 $chunk = fread( $fp, 1024 );
1062 fclose( $fp );
1065 $chunk= strtolower( $chunk );
1067 if (!$chunk) return false;
1069 #decode from UTF-16 if needed (could be used for obfuscation).
1070 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
1071 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
1072 else $enc= NULL;
1074 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
1076 $chunk= trim($chunk);
1078 #FIXME: convert from UTF-16 if necessarry!
1080 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
1082 #check for HTML doctype
1083 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
1086 * Internet Explorer for Windows performs some really stupid file type
1087 * autodetection which can cause it to interpret valid image files as HTML
1088 * and potentially execute JavaScript, creating a cross-site scripting
1089 * attack vectors.
1091 * Apple's Safari browser also performs some unsafe file type autodetection
1092 * which can cause legitimate files to be interpreted as HTML if the
1093 * web server is not correctly configured to send the right content-type
1094 * (or if you're really uploading plain text and octet streams!)
1096 * Returns true if IE is likely to mistake the given file for HTML.
1097 * Also returns true if Safari would mistake the given file for HTML
1098 * when served with a generic content-type.
1101 $tags = array(
1102 '<body',
1103 '<head',
1104 '<html', #also in safari
1105 '<img',
1106 '<pre',
1107 '<script', #also in safari
1108 '<table'
1110 if( ! $wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1111 $tags[] = '<title';
1114 foreach( $tags as $tag ) {
1115 if( false !== strpos( $chunk, $tag ) ) {
1116 return true;
1121 * look for javascript
1124 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1125 $chunk = Sanitizer::decodeCharReferences( $chunk );
1127 #look for script-types
1128 if (preg_match('!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim',$chunk)) return true;
1130 #look for html-style script-urls
1131 if (preg_match('!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1133 #look for css-style script-urls
1134 if (preg_match('!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1136 wfDebug("SpecialUpload::detectScript: no scripts found\n");
1137 return false;
1140 /** Generic wrapper function for a virus scanner program.
1141 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1142 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1144 * @param string $file Pathname to the temporary upload file
1145 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1146 * or a string containing feedback from the virus scanner if a virus was found.
1147 * If textual feedback is missing but a virus was found, this function returns true.
1149 function detectVirus($file) {
1150 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1152 $fname= "SpecialUpload::detectVirus";
1154 if (!$wgAntivirus) { #disabled?
1155 wfDebug("$fname: virus scanner disabled\n");
1157 return NULL;
1160 if (!$wgAntivirusSetup[$wgAntivirus]) {
1161 wfDebug("$fname: unknown virus scanner: $wgAntivirus\n");
1163 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" ); #LOCALIZE
1165 return "unknown antivirus: $wgAntivirus";
1168 #look up scanner configuration
1169 $virus_scanner= $wgAntivirusSetup[$wgAntivirus]["command"]; #command pattern
1170 $virus_scanner_codes= $wgAntivirusSetup[$wgAntivirus]["codemap"]; #exit-code map
1171 $msg_pattern= $wgAntivirusSetup[$wgAntivirus]["messagepattern"]; #message pattern
1173 $scanner= $virus_scanner; #copy, so we can resolve the pattern
1175 if (strpos($scanner,"%f")===false) $scanner.= " ".wfEscapeShellArg($file); #simple pattern: append file to scan
1176 else $scanner= str_replace("%f",wfEscapeShellArg($file),$scanner); #complex pattern: replace "%f" with file to scan
1178 wfDebug("$fname: running virus scan: $scanner \n");
1180 #execute virus scanner
1181 $code= false;
1183 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1184 # that does not seem to be worth the pain.
1185 # Ask me (Duesentrieb) about it if it's ever needed.
1186 $output = array();
1187 if (wfIsWindows()) exec("$scanner",$output,$code);
1188 else exec("$scanner 2>&1",$output,$code);
1190 $exit_code= $code; #remember for user feedback
1192 if ($virus_scanner_codes) { #map exit code to AV_xxx constants.
1193 if (isset($virus_scanner_codes[$code])) {
1194 $code= $virus_scanner_codes[$code]; # explicit mapping
1195 } else if (isset($virus_scanner_codes["*"])) {
1196 $code= $virus_scanner_codes["*"]; # fallback mapping
1200 if ($code===AV_SCAN_FAILED) { #scan failed (code was mapped to false by $virus_scanner_codes)
1201 wfDebug("$fname: failed to scan $file (code $exit_code).\n");
1203 if ($wgAntivirusRequired) { return "scan failed (code $exit_code)"; }
1204 else { return NULL; }
1206 else if ($code===AV_SCAN_ABORTED) { #scan failed because filetype is unknown (probably imune)
1207 wfDebug("$fname: unsupported file type $file (code $exit_code).\n");
1208 return NULL;
1210 else if ($code===AV_NO_VIRUS) {
1211 wfDebug("$fname: file passed virus scan.\n");
1212 return false; #no virus found
1214 else {
1215 $output= join("\n",$output);
1216 $output= trim($output);
1218 if (!$output) $output= true; #if there's no output, return true
1219 else if ($msg_pattern) {
1220 $groups= array();
1221 if (preg_match($msg_pattern,$output,$groups)) {
1222 if ($groups[1]) $output= $groups[1];
1226 wfDebug("$fname: FOUND VIRUS! scanner feedback: $output");
1227 return $output;
1232 * Check if the temporary file is MacBinary-encoded, as some uploads
1233 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
1234 * If so, the data fork will be extracted to a second temporary file,
1235 * which will then be checked for validity and either kept or discarded.
1237 * @access private
1239 function checkMacBinary() {
1240 $macbin = new MacBinary( $this->mUploadTempName );
1241 if( $macbin->isValid() ) {
1242 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
1243 $dataHandle = fopen( $dataFile, 'wb' );
1245 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
1246 $macbin->extractData( $dataHandle );
1248 $this->mUploadTempName = $dataFile;
1249 $this->mUploadSize = $macbin->dataForkLength();
1251 // We'll have to manually remove the new file if it's not kept.
1252 $this->mRemoveTempFile = true;
1254 $macbin->close();
1258 * If we've modified the upload file we need to manually remove it
1259 * on exit to clean up.
1260 * @access private
1262 function cleanupTempFile() {
1263 if( $this->mRemoveTempFile && file_exists( $this->mUploadTempName ) ) {
1264 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file $this->mUploadTempName\n" );
1265 unlink( $this->mUploadTempName );
1270 * Check if there's an overwrite conflict and, if so, if restrictions
1271 * forbid this user from performing the upload.
1273 * @return mixed true on success, WikiError on failure
1274 * @access private
1276 function checkOverwrite( $name ) {
1277 $img = Image::newFromName( $name );
1278 if( is_null( $img ) ) {
1279 // Uh... this shouldn't happen ;)
1280 // But if it does, fall through to previous behavior
1281 return false;
1284 $error = '';
1285 if( $img->exists() ) {
1286 global $wgUser, $wgOut;
1287 if( $img->isLocal() ) {
1288 if( !$this->userCanReUpload( $wgUser, $img->name ) ) {
1289 $error = 'fileexists-forbidden';
1291 } else {
1292 if( !$wgUser->isAllowed( 'reupload' ) ||
1293 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1294 $error = "fileexists-shared-forbidden";
1299 if( $error ) {
1300 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1301 return new WikiError( $wgOut->parse( $errorText ) );
1304 // Rockin', go ahead and upload
1305 return true;
1309 * Check if a user is the last uploader
1311 * @param User $user
1312 * @param string $img, image name
1313 * @return bool
1314 * @access private
1316 function userCanReUpload( $user, $img ) {
1317 if( $user->isAllowed('reupload' ) )
1318 return true; // non-conditional
1319 if( !$user->isAllowed('reupload-own') )
1320 return false;
1322 $dbr = wfGetDB( DB_SLAVE );
1323 $row = $dbr->selectRow(
1324 /* FROM */ 'image',
1325 /* SELECT */ 'img_user',
1326 /* WHERE */ array( 'img_name' => $img )
1328 if ( !$row )
1329 return false;
1331 return $user->getID() == $row->img_user;