public function checkWarnings()
 {
     $warnings = parent::checkWarnings();
     unset($warnings['exists']);
     unset($warnings['duplicate']);
     unset($warnings['duplicate-archive']);
     unset($warnings['badfilename']);
     return $warnings;
 }
 public function verifyUpload()
 {
     global $wgVerifyMimeType;
     //Avoid extension->mime mismatch since
     //we're forcing wathever image format to be saved as a PNG
     $origVerifyMimeTypeValue = $wgVerifyMimeType;
     $wgVerifyMimeType = false;
     parent::verifyUpload();
     $wgVerifyMimeType = $origVerifyMimeTypeValue;
 }
 public function checkWarnings()
 {
     $warnings = parent::checkWarnings();
     //for wordmark we allow overwriting and don't care of
     //filname mismatch for FakeLocalFile (see UploadBase::checkWarnings)
     unset($warnings['exists']);
     unset($warnings['duplicate']);
     unset($warnings['duplicate-archive']);
     unset($warnings['badfilename']);
     return $warnings;
 }
 function upload()
 {
     $details = null;
     $this->content = 'error';
     $up = new UploadFromFile();
     $up->initializeFromRequest($this->wg->request);
     $permErrors = $up->verifyPermissions($this->wg->user);
     if ($permErrors !== true) {
         $this->status = self::UPLOAD_PERMISSION_ERROR;
         $this->statusMessage = $this->uploadMessage($this->status, null);
     } else {
         if (empty($this->wg->EnableUploads)) {
             // BugId:6122
             $this->statusMessage = wfMsg('uploaddisabled');
         } else {
             $details = $up->verifyUpload();
             $this->status = is_array($details) ? $details['status'] : UploadBase::UPLOAD_VERIFICATION_ERROR;
             $this->statusMessage = '';
             if ($this->status > 0) {
                 $this->statusMessage = $this->uploadMessage($this->status, $details);
             } else {
                 $titleText = $this->request->getVal('title');
                 $sectionNumber = $this->request->getVal('section', 0);
                 $this->status = $up->performUpload('', '', '', $this->wg->user);
                 $mainArticle = new Article(Title::newFromText($titleText));
                 if ($sectionNumber == 0) {
                     $mainArticle->updateArticle($this->getWikiText($up->getTitle()->getText(), self::LEFT) . $mainArticle->getRawText(), '', false, false);
                 } else {
                     $firstSectionText = $mainArticle->getSection($mainArticle->getRawText(), $sectionNumber);
                     $matches = array();
                     if (preg_match('/={2,3}[^=]+={2,3}/', $firstSectionText, $matches)) {
                         $firstSectionText = trim(str_replace($matches[0], '', $firstSectionText));
                         $newSectionText = $mainArticle->replaceSection($sectionNumber, $matches[0] . "\n" . $this->getWikiText($up->getTitle()->getText(), self::LEFT) . $firstSectionText);
                         $mainArticle->updateArticle($newSectionText, '', false, false);
                     }
                 }
                 $this->content = $this->renderImage($up->getTitle()->getText(), self::LEFT);
             }
         }
     }
 }
Ejemplo n.º 5
0
 /**
  * Append the final chunk and ready file for parent::performUpload()
  * @return FileRepoStatus
  */
 public function concatenateChunks()
 {
     $chunkIndex = $this->getChunkIndex();
     wfDebug(__METHOD__ . " concatenate {$this->mChunkIndex} chunks:" . $this->getOffset() . ' inx:' . $chunkIndex . "\n");
     // Concatenate all the chunks to mVirtualTempPath
     $fileList = array();
     // The first chunk is stored at the mVirtualTempPath path so we start on "chunk 1"
     for ($i = 0; $i <= $chunkIndex; $i++) {
         $fileList[] = $this->getVirtualChunkLocation($i);
     }
     // Get the file extension from the last chunk
     $ext = FileBackend::extensionFromPath($this->mVirtualTempPath);
     // Get a 0-byte temp file to perform the concatenation at
     $tmpFile = TempFSFile::factory('chunkedupload_', $ext);
     $tmpPath = false;
     // fail in concatenate()
     if ($tmpFile) {
         // keep alive with $this
         $tmpPath = $tmpFile->bind($this)->getPath();
     }
     // Concatenate the chunks at the temp file
     $tStart = microtime(true);
     $status = $this->repo->concatenate($fileList, $tmpPath, FileRepo::DELETE_SOURCE);
     $tAmount = microtime(true) - $tStart;
     if (!$status->isOk()) {
         return $status;
     }
     wfDebugLog('fileconcatenate', "Combined {$i} chunks in {$tAmount} seconds.");
     // File system path
     $this->mTempPath = $tmpPath;
     // Since this was set for the last chunk previously
     $this->mFileSize = filesize($this->mTempPath);
     $ret = $this->verifyUpload();
     if ($ret['status'] !== UploadBase::OK) {
         wfDebugLog('fileconcatenate', "Verification failed for chunked upload");
         $status->fatal($this->getVerificationErrorCode($ret['status']));
         return $status;
     }
     // Update the mTempPath and mLocalFile
     // (for FileUpload or normal Stash to take over)
     $tStart = microtime(true);
     $this->mLocalFile = parent::stashFile($this->user);
     $tAmount = microtime(true) - $tStart;
     $this->mLocalFile->setLocalReference($tmpFile);
     // reuse (e.g. for getImageInfo())
     wfDebugLog('fileconcatenate', "Stashed combined file ({$i} chunks) in {$tAmount} seconds.");
     return $status;
 }
Ejemplo n.º 6
0
 /**
  * Append the generic comment.
  *
  * @param $comment string The comment describing the change in the changelog
  * @param $pageText string The text of the page. This string is modified
  *   with a link back to the original article referred to by the
  *    ADD_RESOURCE_REFERER_FIELD variable.
  */
 function performUpload($comment, $pageText, $watch, $user)
 {
     $pageText .= getResourceComment();
     return parent::performUpload($comment, $pageText, $watch, $user);
 }
Ejemplo n.º 7
0
 /**
  * Perform the upload, then remove the temp copy afterward
  * @param $comment string
  * @param $pageText string
  * @param $watch bool
  * @param $user User
  * @return Status
  */
 public function performUpload($comment, $pageText, $watch, $user)
 {
     $rv = parent::performUpload($comment, $pageText, $watch, $user);
     return $rv;
 }
Ejemplo n.º 8
0
 /**
  * Append the final chunk and ready file for parent::performUpload()
  * @return FileRepoStatus
  */
 public function concatenateChunks()
 {
     $chunkIndex = $this->getChunkIndex();
     wfDebug(__METHOD__ . " concatenate {$this->mChunkIndex} chunks:" . $this->getOffset() . ' inx:' . $chunkIndex . "\n");
     // Concatenate all the chunks to mVirtualTempPath
     $fileList = [];
     // The first chunk is stored at the mVirtualTempPath path so we start on "chunk 1"
     for ($i = 0; $i <= $chunkIndex; $i++) {
         $fileList[] = $this->getVirtualChunkLocation($i);
     }
     // Get the file extension from the last chunk
     $ext = FileBackend::extensionFromPath($this->mVirtualTempPath);
     // Get a 0-byte temp file to perform the concatenation at
     $tmpFile = TempFSFile::factory('chunkedupload_', $ext, wfTempDir());
     $tmpPath = false;
     // fail in concatenate()
     if ($tmpFile) {
         // keep alive with $this
         $tmpPath = $tmpFile->bind($this)->getPath();
     }
     // Concatenate the chunks at the temp file
     $tStart = microtime(true);
     $status = $this->repo->concatenate($fileList, $tmpPath, FileRepo::DELETE_SOURCE);
     $tAmount = microtime(true) - $tStart;
     if (!$status->isOK()) {
         return $status;
     }
     wfDebugLog('fileconcatenate', "Combined {$i} chunks in {$tAmount} seconds.");
     // File system path of the actual full temp file
     $this->setTempFile($tmpPath);
     $ret = $this->verifyUpload();
     if ($ret['status'] !== UploadBase::OK) {
         wfDebugLog('fileconcatenate', "Verification failed for chunked upload");
         $status->fatal($this->getVerificationErrorCode($ret['status']));
         return $status;
     }
     // Update the mTempPath and mStashFile
     // (for FileUpload or normal Stash to take over)
     $tStart = microtime(true);
     // This is a re-implementation of UploadBase::tryStashFile(), we can't call it because we
     // override doStashFile() with completely different functionality in this class...
     $error = $this->runUploadStashFileHook($this->user);
     if ($error) {
         call_user_func_array([$status, 'fatal'], $error);
         return $status;
     }
     try {
         $this->mStashFile = parent::doStashFile($this->user);
     } catch (UploadStashException $e) {
         $status->fatal('uploadstash-exception', get_class($e), $e->getMessage());
         return $status;
     }
     $tAmount = microtime(true) - $tStart;
     $this->mStashFile->setLocalReference($tmpFile);
     // reuse (e.g. for getImageInfo())
     wfDebugLog('fileconcatenate', "Stashed combined file ({$i} chunks) in {$tAmount} seconds.");
     return $status;
 }
 /**
  * Perform image name check
  */
 public function checkImageName($imageName, $uploadFieldName)
 {
     global $wgRequest, $wgUser;
     $upload = new UploadFromFile();
     $upload->initializeFromRequest($wgRequest);
     $permErrors = $upload->verifyPermissions($wgUser);
     if ($permErrors !== true) {
         return self::USER_PERMISSION_ERROR;
     }
     $ret = $upload->verifyUpload();
     // this hook is used by WikiaTitleBlackList extension
     if (!wfRunHooks('WikiaMiniUpload:BeforeProcessing', array($imageName))) {
         $this->log(__METHOD__, 'Hook "WikiaMiniUpload:BeforeProcessing" broke processing the file');
         wfProfileOut(__METHOD__);
         return UploadBase::VERIFICATION_ERROR;
     }
     if (is_array($ret)) {
         return $ret['status'];
     } else {
         return $ret;
     }
 }
Ejemplo n.º 10
0
 /**
  * @static
  * @return AjaxResponse
  * @throws MWException
  */
 public static function uploadImage()
 {
     global $wgRequest, $wgUser, $wgFileExtensions, $wgLang;
     if ($wgRequest->wasPosted()) {
         $ret = array();
         $upload = new UploadFromFile();
         $upload->initializeFromRequest($wgRequest);
         $permErrors = $upload->verifyPermissions($wgUser);
         if ($permErrors !== true) {
             $ret['error'] = true;
             $ret['message'] = wfMsg('badaccess');
         } else {
             $details = $upload->verifyUpload();
             if ($details['status'] != UploadBase::OK) {
                 $ret['error'] = true;
                 switch ($details['status']) {
                     /** Statuses that only require name changing **/
                     case UploadBase::MIN_LENGTH_PARTNAME:
                         $ret['message'] = wfMsgHtml('minlength1');
                         break;
                     case UploadBase::ILLEGAL_FILENAME:
                         $ret['message'] = wfMsgExt('illegalfilename', 'parseinline', $details['filtered']);
                         break;
                     case UploadBase::OVERWRITE_EXISTING_FILE:
                         $ret['message'] = wfMsgExt($details['overwrite'], 'parseinline');
                         break;
                     case UploadBase::FILETYPE_MISSING:
                         $ret['message'] = wfMsgExt('filetype-missing', 'parseinline');
                         break;
                     case UploadBase::EMPTY_FILE:
                         $ret['message'] = wfMsgHtml('emptyfile');
                         break;
                     case UploadBase::FILETYPE_BADTYPE:
                         $finalExt = $details['finalExt'];
                         $ret['message'] = wfMsgExt('filetype-banned-type', array('parseinline'), htmlspecialchars($finalExt), implode(wfMsgExt('comma-separator', array('escapenoentities')), $wgFileExtensions), $wgLang->formatNum(count($wgFileExtensions)));
                         break;
                     case UploadBase::VERIFICATION_ERROR:
                         unset($details['status']);
                         $code = array_shift($details['details']);
                         $ret['message'] = wfMsgExt($code, 'parseinline', $details['details']);
                         break;
                     case UploadBase::HOOK_ABORTED:
                         if (is_array($details['error'])) {
                             # allow hooks to return error details in an array
                             $args = $details['error'];
                             $error = array_shift($args);
                         } else {
                             $error = $details['error'];
                             $args = null;
                         }
                         $ret['message'] = wfMsgExt($error, 'parseinline', $args);
                         break;
                     default:
                         throw new MWException(__METHOD__ . ": Unknown value `{$details['status']}`");
                 }
             } else {
                 $warnings = $upload->checkWarnings();
                 if ($warnings) {
                     if (!empty($warnings['exists']) || !empty($warnings['duplicate']) || !empty($warnings['duplicate-archive'])) {
                         $ret['conflict'] = true;
                         $ret['message'] = wfMsg('toplists-error-image-already-exists');
                     } else {
                         $ret['error'] = true;
                         $ret['message'] = '';
                         foreach ($warnings as $warning => $args) {
                             if ($args === true) {
                                 $args = array();
                             } elseif (!is_array($args)) {
                                 $args = array($args);
                             }
                             $ret['message'] .= wfMsgExt($warning, 'parseinline', $args) . "/n";
                         }
                     }
                 } else {
                     $status = $upload->performUpload('/* comment */', '/* page text */', false, $wgUser);
                     if (!$status->isGood()) {
                         $ret['error'] = true;
                         $ret['message'] = wfMsg('toplists-upload-error-unknown');
                     } else {
                         $ret['success'] = true;
                         $file = $upload->getLocalFile();
                         if (!empty($file)) {
                             $thumb = $file->transform(array('width' => 120), 0);
                             $pictureName = $upload->getTitle()->getText();
                             $pictureUrl = $thumb->getUrl();
                         }
                         $ret['name'] = $pictureName;
                         $ret['url'] = $pictureUrl;
                     }
                 }
             }
         }
         $response = new AjaxResponse('<script type="text/javascript">window.document.responseContent = ' . json_encode($ret) . ';</script>');
         $response->setContentType('text/html; charset=utf-8');
         return $response;
     }
 }
 protected function uploadImage()
 {
     global $wgImageMagickConvertCommand, $wgServer;
     $request = $this->getRequest();
     $result = array();
     $fromPage = $request->getVal('viapage');
     // sanity check on the page to link to
     $title = Title::newFromText($fromPage, NS_MAIN);
     if (!$title->exists()) {
         $result['error'] = "Error: No article {$fromPage} found to link image.";
         return $result;
     }
     // try to get a unique file name by appending a suffix and the current time to the save name here
     $dateTime = new DateTime();
     $webUpload = $request->getUpload('wpUploadImage');
     $info = new SplFileInfo($webUpload->getName());
     $ext = $info->getExtension();
     $info = new SplFileInfo($request->getVal("name"));
     for ($i = 0; $i < 100; $i++) {
         $saveName = "User Completed Image {$fromPage} {$dateTime->format('Y.m.d H.i.s')}.{$i}.{$ext}";
         $title = Title::newFromText($saveName, NS_IMAGE);
         if (!$title->getArticleID()) {
             break;
         }
     }
     // if the title still exists, show an error
     if ($title->getArticleID()) {
         $result['error'] = 'file with this name already exists';
         return $result;
     }
     $upload = new UploadFromFile();
     $upload->initialize($saveName, $webUpload);
     $verification = $upload->verifyUpload();
     if ($verification['status'] !== UploadBase::OK) {
         $result['error'] = "verification error: " . $verification['status'];
         return $result;
     }
     $warnings = $upload->checkWarnings();
     if ($warnings) {
         $result['warnings'] = $warnings;
         // todo this should be toggled on off for testings perhaps
         // since it might get kind of annoying
         if ($warnings['duplicate']) {
             $result['debug'][] = $warnings['duplicate-archive'];
             $result['error'] = "this file was already uploaded";
             return $result;
         }
     }
     $comment = '{{Self}}';
     $status = $upload->performUpload($comment, '', true, $this->getUser());
     if (!$status->isGood()) {
         $error = $status->getErrorsArray();
         $result['error'] = 'perform upload error: ' . $error;
         return $result;
     }
     $upload->cleanupTempFile();
     // todo - do this part after the single file upload
     // Image orientation is a bit wonky on some mobile devices; use ImageMagick's auto-orient to try fixing it.
     //$tempFilePath = $temp_file->getPath();
     //$cmd = $wgImageMagickConvertCommand . ' ' . $tempFilePath . ' -auto-orient ' . $tempFilePath;
     //exec($cmd);
     $file = $upload->getLocalFile();
     $thumb = $file->getThumbnail(200, -1, true, true);
     if (!$thumb) {
         $result['error'] = 'file thumbnail does not exist';
         $file->delete('');
         return $result;
     }
     $fileTitle = $file->getTitle();
     $result['titleText'] = $fileTitle->getText();
     $result['titleDBkey'] = substr($fileTitle->getDBkey(), 21);
     // Only keep important info
     $result['titlePreText'] = '/' . $fileTitle->getPrefixedText();
     $result['titleArtID'] = $fileTitle->getArticleID();
     $result['timestamp'] = wfTimestamp(TS_MW);
     $result['fromPage'] = $request->getVal('viapage');
     $result['thumbURL'] = $thumb->getUrl();
     $result['fileURL'] = $wgServer . $file->getUrl();
     $this->addToDB($result);
     return $result;
 }
Ejemplo n.º 12
0
 /**
  * Perform image check
  *
  * @return array|int
  */
 function checkImage()
 {
     global $wgRequest, $wgUser;
     $mSrcName = stripslashes($wgRequest->getFileName('wpUploadFile'));
     $upload = new UploadFromFile();
     $upload->initializeFromRequest($wgRequest);
     $permErrors = $upload->verifyPermissions($wgUser);
     if ($permErrors !== true) {
         return self::USER_PERMISSION_ERROR;
     }
     $ret = $upload->verifyUpload();
     if (!wfRunHooks('WikiaMiniUpload:BeforeProcessing', array($mSrcName))) {
         wfDebug("Hook 'WikiaMiniUpload:BeforeProcessing' broke processing the file.");
         return UploadBase::VERIFICATION_ERROR;
     }
     if (is_array($ret)) {
         return $ret['status'];
     } else {
         return $ret;
     }
 }
Ejemplo n.º 13
0
 /**
  * Handle the mediawiki file upload process
  * @return boolean status of file "upload"
  */
 public function run()
 {
     global $wgOut;
     $mUpload = new UploadFromFile();
     wfDebug("QrCodeDebug::" . $this->_dstFileName . " " . $this->_tmpName . "\n");
     // $mUpload->initialize( $this->_dstFileName, $this->_tmpName, null );	// pre 1.17
     $mUpload->initializePathInfo($this->_dstFileName, $this->_tmpName, null);
     // we don't know the filesize, how could we?
     wfDebug("QrCodeDebug:: Intialization finished\n");
     $pageText = 'QrCode ' . $this->_dstFileName . ', generated on ' . date("r") . ' by the QrCode Extension for page [[' . $this->title->getFullText() . ']].';
     wfDebug('QrCodeJob::run: Uploading qrcode, c: ' . $this->_uploadComment . ' t: ' . $pageText . "\n");
     $status = $mUpload->performUpload($this->_uploadComment, $pageText, false, $this->_getBot());
     if ($status->isGood()) {
         return true;
     } else {
         $wgOut->addWikiText($status->getWikiText());
         return false;
     }
 }
Ejemplo n.º 14
0
 public function getUploadFileErrorMessage(UploadFromFile $uploader, $verified)
 {
     $errorReadable = $uploader->getVerificationErrorCode($verified['status']);
     return wfMessage($errorReadable)->parse();
 }
	/**
	 * This method hacks the normal nirvana dispatcher chain because of AIM and application/json mimetype incompatibility
	 * Talk to Hyun or Inez
	 */
	public function executeUpload($params) {
		wfProfileIn(__METHOD__);
		global $wgRequest, $wgUser;

		if(!$wgUser->isLoggedIn()) {
			echo 'Not logged in';
			exit();
		}

		$this->watchthis = $wgRequest->getBool('wpWatchthis') && $wgUser->isLoggedIn();
		$this->license = $wgRequest->getText('wpLicense');
		$this->copyrightstatus = $wgRequest->getText('wpUploadCopyStatus');
		$this->copyrightsource = $wgRequest->getText('wpUploadSource');
		$this->ignorewarning = $wgRequest->getCheck('wpIgnoreWarning');
		$this->overwritefile = $wgRequest->getCheck('wpDestFileWarningAck');
		$this->defaultcaption = $wgRequest->getText('wpUploadDescription');
		$details = null;
		$up = new UploadFromFile();
		$up->initializeFromRequest($wgRequest);
		$permErrors = $up->verifyPermissions($wgUser);

		if ( $permErrors !== true ) {
			$this->status = self::UPLOAD_PERMISSION_ERROR;
			$this->statusMessage = $this->uploadMessage( $this->status, null );
		} else if (empty($this->wg->EnableUploads)) {
			// BugId:6122
			$this->statusMessage = wfMsg('uploaddisabled');
		} else {
			$details = $up->verifyUpload();

			$this->status = (is_array($details) ? $details['status'] : UploadBase::UPLOAD_VERIFICATION_ERROR);
			$this->statusMessage = '';

			if ($this->status > 0) {
				$this->statusMessage = $this->uploadMessage($this->status, $details);
			} else {
				$warnings = array();
				if(!$this->ignorewarning) {
					$warnings = $up->checkWarnings();

					// BugId:3325 - add handling for "Overwrite File" checkbox
					if ($this->overwritefile && !empty($warnings['exists'])) {
						unset($warnings['exists']);
					}

					if(!empty($warnings)) {
						$this->status = self::UPLOAD_WARNING;
						$this->statusMessage .= $this->uploadWarning($warnings);
					}
				}
				if(empty($warnings)) {
					$pageText = SpecialUpload::getInitialPageText( $this->defaultcaption, $this->license,
						$this->copyrightstatus, $this->copyrightsource );
					$status = $up->performUpload( $this->defaultcaption, $pageText, $this->watchthis, $wgUser );
					if ($status->isGood()) {
						$aPageProps = array ( 'default_caption' => $this->defaultcaption );
						Wikia::setProps( $up->getTitle()->getArticleID(), $aPageProps );
					} else {
						$this->statusMessage .= "something is wrong with upload";
					}
				}
			}
		}

		echo json_encode($this->getResponse()->getData());
		header('content-type: text/plain; charset=utf-8');

		wfProfileOut(__METHOD__);

		exit();	//end hack
	}
Ejemplo n.º 16
0
<?php

error_reporting(E_ALL);
ini_set("display_errors", 1);
#echo getcwd()."\n";
chdir("../../");
require_once 'includes/WebStart.php';
if (isset($_GET['user'])) {
    $wgUser = User::newFromName($_GET['user']);
}
#echo $wgUser->getToken();
#echo $wgUser->getName();
#apiupload.php
#functions in UploadBase.php
$mUpload = new UploadFromFile();
global $sCreateIndexFilepath;
$sCreateIndexFilepath = false;
$ignorewarnings = true;
$text = "";
$comment = "MsUpload";
$watch = false;
$error = false;
if (isset($_FILES['Filedata']['name'])) {
    $filename = $_FILES['Filedata']['name'];
    $anz = 1;
    #  if (array_key_exists('name_hidden', $_POST)) {
    foreach ($_POST['name_hidden'] as $nam) {
        $change = explode("|", $nam);
        if ($change[0] == $filename) {
            #namen stimmen überein
            $ids = $anz;