public function handleFormSubmit($data)
 {
     // unlink requests do not accept user input so repeat parent code but skip call to
     // AuthenticationRequest::loadRequestsFromSubmission
     $response = $this->performAuthenticationStep($this->authAction, $this->authRequests);
     return Status::newGood($response);
 }
 public function testBeginSecondaryAccountCreation()
 {
     $authManager = new AuthManager(new \FauxRequest(), new \HashConfig());
     $creator = $this->getMock('User');
     $userWithoutEmail = $this->getMock('User');
     $userWithoutEmail->expects($this->any())->method('getEmail')->willReturn('');
     $userWithoutEmail->expects($this->never())->method('sendConfirmationMail');
     $userWithEmailError = $this->getMock('User');
     $userWithEmailError->expects($this->any())->method('getEmail')->willReturn('*****@*****.**');
     $userWithEmailError->expects($this->any())->method('sendConfirmationMail')->willReturn(\Status::newFatal('fail'));
     $userExpectsConfirmation = $this->getMock('User');
     $userExpectsConfirmation->expects($this->any())->method('getEmail')->willReturn('*****@*****.**');
     $userExpectsConfirmation->expects($this->once())->method('sendConfirmationMail')->willReturn(\Status::newGood());
     $userNotExpectsConfirmation = $this->getMock('User');
     $userNotExpectsConfirmation->expects($this->any())->method('getEmail')->willReturn('*****@*****.**');
     $userNotExpectsConfirmation->expects($this->never())->method('sendConfirmationMail');
     $provider = new EmailNotificationSecondaryAuthenticationProvider(['sendConfirmationEmail' => false]);
     $provider->setManager($authManager);
     $provider->beginSecondaryAccountCreation($userNotExpectsConfirmation, $creator, []);
     $provider = new EmailNotificationSecondaryAuthenticationProvider(['sendConfirmationEmail' => true]);
     $provider->setManager($authManager);
     $provider->beginSecondaryAccountCreation($userWithoutEmail, $creator, []);
     $provider->beginSecondaryAccountCreation($userExpectsConfirmation, $creator, []);
     // test logging of email errors
     $logger = $this->getMockForAbstractClass(LoggerInterface::class);
     $logger->expects($this->once())->method('warning');
     $provider->setLogger($logger);
     $provider->beginSecondaryAccountCreation($userWithEmailError, $creator, []);
     // test disable flag used by other providers
     $authManager->setAuthenticationSessionData('no-email', true);
     $provider->setManager($authManager);
     $provider->beginSecondaryAccountCreation($userNotExpectsConfirmation, $creator, []);
 }
 /**
  * Various checks against the uploaded file
  * - maximum upload size
  * - maximum number of embedded files
  * - maximum size of metadata
  * - identify-errors
  * - identify-warnings
  * - check for running-identify-service
  */
 function verifyUpload($fileName)
 {
     global $wgTiffUseTiffReader, $wgTiffReaderCheckEofForJS;
     $status = Status::newGood();
     if ($wgTiffUseTiffReader) {
         $tr = new TiffReader($fileName);
         $tr->check();
         if (!$tr->isValidTiff()) {
             wfDebug(__METHOD__ . ": bad file\n");
             $status->fatal('tiff_bad_file');
         } else {
             if ($tr->checkScriptAtEnd($wgTiffReaderCheckEofForJS)) {
                 wfDebug(__METHOD__ . ": script detected\n");
                 $status->fatal('tiff_script_detected');
             }
             if (!$tr->checkSize()) {
                 wfDebug(__METHOD__ . ": size error\n");
                 $status->fatal('tiff_size_error');
             }
         }
     }
     $meta = self::getTiffImage(false, $fileName)->retrieveMetaData();
     if (!$meta) {
         wfDebug(__METHOD__ . ": unable to retreive metadata\n");
         $status->fatal('tiff_out_of_service');
     } else {
         $error = false;
         $ok = self::verifyMetaData($meta, $error);
         if (!$ok) {
             call_user_func_array(array($status, 'fatal'), $error);
         }
     }
     return $status;
 }
 /**
  * @dataProvider provideValues
  * @covers Status::newGood
  */
 public function testNewGood($value = null)
 {
     $status = Status::newGood($value);
     $this->assertTrue($status->isGood());
     $this->assertTrue($status->isOK());
     $this->assertEquals($value, $status->getValue());
 }
 public function testExecute_email()
 {
     $config = new HashConfig(['PasswordResetRoutes' => ['username' => true, 'email' => true], 'EnableEmail' => true]);
     $authManager = $this->getMockBuilder(AuthManager::class)->disableOriginalConstructor()->getMock();
     $authManager->expects($this->any())->method('allowsAuthenticationDataChange')->willReturn(Status::newGood());
     $authManager->expects($this->exactly(2))->method('changeAuthenticationData');
     $request = new FauxRequest();
     $request->setIP('1.2.3.4');
     $performingUser = $this->getMock(User::class);
     $performingUser->expects($this->any())->method('getRequest')->willReturn($request);
     $performingUser->expects($this->any())->method('isAllowed')->willReturn(true);
     $targetUser1 = $this->getMock(User::class);
     $targetUser2 = $this->getMock(User::class);
     $targetUser1->expects($this->any())->method('getName')->willReturn('User1');
     $targetUser2->expects($this->any())->method('getName')->willReturn('User2');
     $targetUser1->expects($this->any())->method('getId')->willReturn(1);
     $targetUser2->expects($this->any())->method('getId')->willReturn(2);
     $targetUser1->expects($this->any())->method('getEmail')->willReturn('*****@*****.**');
     $targetUser2->expects($this->any())->method('getEmail')->willReturn('*****@*****.**');
     $passwordReset = $this->getMockBuilder(PasswordReset::class)->setMethods(['getUsersByEmail'])->setConstructorArgs([$config, $authManager])->getMock();
     $passwordReset->expects($this->any())->method('getUsersByEmail')->with('*****@*****.**')->willReturn([$targetUser1, $targetUser2]);
     $status = $passwordReset->isAllowed($performingUser);
     $this->assertTrue($status->isGood());
     $status = $passwordReset->execute($performingUser, null, '*****@*****.**');
     $this->assertTrue($status->isGood());
 }
Example #6
0
 /**
  * @covers ApiErrorFormatter_BackCompat
  */
 public function testErrorFormatterBC()
 {
     $mainpagePlain = wfMessage('mainpage')->useDatabase(false)->plain();
     $parensPlain = wfMessage('parentheses', 'foobar')->useDatabase(false)->plain();
     $result = new ApiResult(8388608);
     $formatter = new ApiErrorFormatter_BackCompat($result);
     $formatter->addWarning('string', 'mainpage');
     $formatter->addError('err', 'mainpage');
     $this->assertSame(array('error' => array('code' => 'mainpage', 'info' => $mainpagePlain), 'warnings' => array('string' => array('warnings' => $mainpagePlain, ApiResult::META_CONTENT => 'warnings')), ApiResult::META_TYPE => 'assoc'), $result->getResultData(), 'Simple test');
     $result->reset();
     $formatter->addWarning('foo', 'mainpage');
     $formatter->addWarning('foo', 'mainpage');
     $formatter->addWarning('foo', array('parentheses', 'foobar'));
     $msg1 = wfMessage('mainpage');
     $formatter->addWarning('message', $msg1);
     $msg2 = new ApiMessage('mainpage', 'overriddenCode', array('overriddenData' => true));
     $formatter->addWarning('messageWithData', $msg2);
     $formatter->addError('errWithData', $msg2);
     $this->assertSame(array('error' => array('code' => 'overriddenCode', 'info' => $mainpagePlain, 'overriddenData' => true), 'warnings' => array('messageWithData' => array('warnings' => $mainpagePlain, ApiResult::META_CONTENT => 'warnings'), 'message' => array('warnings' => $mainpagePlain, ApiResult::META_CONTENT => 'warnings'), 'foo' => array('warnings' => "{$mainpagePlain}\n{$parensPlain}", ApiResult::META_CONTENT => 'warnings')), ApiResult::META_TYPE => 'assoc'), $result->getResultData(), 'Complex test');
     $result->reset();
     $status = Status::newGood();
     $status->warning('mainpage');
     $status->warning('parentheses', 'foobar');
     $status->warning($msg1);
     $status->warning($msg2);
     $status->error('mainpage');
     $status->error('parentheses', 'foobar');
     $formatter->addMessagesFromStatus('status', $status);
     $this->assertSame(array('error' => array('code' => 'parentheses', 'info' => $parensPlain), 'warnings' => array('status' => array('warnings' => "{$mainpagePlain}\n{$parensPlain}", ApiResult::META_CONTENT => 'warnings')), ApiResult::META_TYPE => 'assoc'), $result->getResultData(), 'Status test');
     $I = ApiResult::META_INDEXED_TAG_NAME;
     $this->assertSame(array(array('type' => 'error', 'message' => 'mainpage', 'params' => array($I => 'param')), array('type' => 'error', 'message' => 'parentheses', 'params' => array('foobar', $I => 'param')), $I => 'error'), $formatter->arrayFromStatus($status, 'error'), 'arrayFromStatus test for error');
     $this->assertSame(array(array('type' => 'warning', 'message' => 'mainpage', 'params' => array($I => 'param')), array('type' => 'warning', 'message' => 'parentheses', 'params' => array('foobar', $I => 'param')), array('message' => 'mainpage', 'params' => array($I => 'param'), 'type' => 'warning'), array('message' => 'mainpage', 'params' => array($I => 'param'), 'type' => 'warning'), $I => 'warning'), $formatter->arrayFromStatus($status, 'warning'), 'arrayFromStatus test for warning');
 }
 /**
  * @param string|MWRestrictions $value The value the field was submitted with
  * @param array $alldata The data collected from the form
  *
  * @return bool|string True on success, or String error to display, or
  *   false to fail validation without displaying an error.
  */
 public function validate($value, $alldata)
 {
     if ($this->isHidden($alldata)) {
         return true;
     }
     if (isset($this->mParams['required']) && $this->mParams['required'] !== false && $value instanceof MWRestrictions && !$value->toArray()['IPAddresses']) {
         return $this->msg('htmlform-required')->parse();
     }
     if (is_string($value)) {
         // MWRestrictions::newFromArray failed; one of the IP ranges must be invalid
         $status = Status::newGood();
         foreach (explode(PHP_EOL, $value) as $range) {
             if (!\IP::isIPAddress($range)) {
                 $status->fatal('restrictionsfield-badip', $range);
             }
         }
         if ($status->isOK()) {
             $status->fatal('unknown-error');
         }
         return $status->getMessage()->parse();
     }
     if (isset($this->mValidationCallback)) {
         return call_user_func($this->mValidationCallback, $value, $alldata, $this->mParent);
     }
     return true;
 }
Example #8
0
 protected function doDeleteInternal(array $params)
 {
     $this->debug(serialize($params));
     $src = $params['src'];
     unset($this->mocked[$src]);
     return Status::newGood();
 }
 public function run()
 {
     $scope = RequestContext::importScopedSession($this->params['session']);
     $context = RequestContext::getMain();
     try {
         $user = $context->getUser();
         if (!$user->isLoggedIn()) {
             $this->setLastError("Could not load the author user from session.");
             return false;
         }
         if (count($_SESSION) === 0) {
             // Empty session probably indicates that we didn't associate
             // with the session correctly. Note that being able to load
             // the user does not necessarily mean the session was loaded.
             // Most likely cause by suhosin.session.encrypt = On.
             $this->setLastError("Error associating with user session. " . "Try setting suhosin.session.encrypt = Off");
             return false;
         }
         UploadBase::setSessionStatus($this->params['filekey'], array('result' => 'Poll', 'stage' => 'publish', 'status' => Status::newGood()));
         $upload = new UploadFromStash($user);
         // @todo initialize() causes a GET, ideally we could frontload the antivirus
         // checks and anything else to the stash stage (which includes concatenation and
         // the local file is thus already there). That way, instead of GET+PUT, there could
         // just be a COPY operation from the stash to the public zone.
         $upload->initialize($this->params['filekey'], $this->params['filename']);
         // Check if the local file checks out (this is generally a no-op)
         $verification = $upload->verifyUpload();
         if ($verification['status'] !== UploadBase::OK) {
             $status = Status::newFatal('verification-error');
             $status->value = array('verification' => $verification);
             UploadBase::setSessionStatus($this->params['filekey'], array('result' => 'Failure', 'stage' => 'publish', 'status' => $status));
             $this->setLastError("Could not verify upload.");
             return false;
         }
         // Upload the stashed file to a permanent location
         $status = $upload->performUpload($this->params['comment'], $this->params['text'], $this->params['watch'], $user);
         if (!$status->isGood()) {
             UploadBase::setSessionStatus($this->params['filekey'], array('result' => 'Failure', 'stage' => 'publish', 'status' => $status));
             $this->setLastError($status->getWikiText());
             return false;
         }
         // Build the image info array while we have the local reference handy
         $apiMain = new ApiMain();
         // dummy object (XXX)
         $imageInfo = $upload->getImageInfo($apiMain->getResult());
         // Cleanup any temporary local file
         $upload->cleanupTempFile();
         // Cache the info so the user doesn't have to wait forever to get the final info
         UploadBase::setSessionStatus($this->params['filekey'], array('result' => 'Success', 'stage' => 'publish', 'filename' => $upload->getLocalFile()->getName(), 'imageinfo' => $imageInfo, 'status' => Status::newGood()));
     } catch (MWException $e) {
         UploadBase::setSessionStatus($this->params['filekey'], array('result' => 'Failure', 'stage' => 'publish', 'status' => Status::newFatal('api-error-publishfailed')));
         $this->setLastError(get_class($e) . ": " . $e->getText());
         // To prevent potential database referential integrity issues.
         // See bug 32551.
         MWExceptionHandler::rollbackMasterChangesAndLog($e);
         return false;
     }
     return true;
 }
 /**
  *
  */
 public function testOkAndErrors()
 {
     $status = Status::newGood('foo');
     $this->assertTrue($status->ok);
     $status = Status::newFatal('foo', 1, 2);
     $this->assertFalse($status->ok);
     $this->assertArrayEquals(array(array('type' => 'error', 'message' => 'foo', 'params' => array(1, 2))), $status->errors);
 }
 /**
  * @dataProvider trackDataProvider
  * @param $amgId
  * @param $trackResult
  * @param $responseCode
  */
 public function testTrack($amgId, $trackResult, $responseCode)
 {
     $controller = new LyricFindController();
     $controller->setRequest(new WikiaRequest(['amgid' => $amgId]));
     $controller->setResponse(new WikiaResponse('json'));
     $this->mockClassWithMethods('LyricFindTrackingService', ['track' => $trackResult ? Status::newGood() : Status::newFatal('foo')]);
     $controller->track();
     $this->assertEquals($responseCode, $controller->getResponse()->getCode(), 'HTTP response code should match the expected value');
 }
Example #12
0
 public function fetchFile()
 {
     if (!Http::isValidURI($this->mUrl)) {
         return Status::newFatal('http-invalid-url');
     }
     if (!$this->mAsync) {
         return $this->reallyFetchFile();
     }
     return Status::newGood();
 }
 public function run()
 {
     $scope = RequestContext::importScopedSession($this->params['session']);
     $this->addTeardownCallback(function () use(&$scope) {
         ScopedCallback::consume($scope);
         // T126450
     });
     $context = RequestContext::getMain();
     $user = $context->getUser();
     try {
         if (!$user->isLoggedIn()) {
             $this->setLastError("Could not load the author user from session.");
             return false;
         }
         UploadBase::setSessionStatus($user, $this->params['filekey'], ['result' => 'Poll', 'stage' => 'publish', 'status' => Status::newGood()]);
         $upload = new UploadFromStash($user);
         // @todo initialize() causes a GET, ideally we could frontload the antivirus
         // checks and anything else to the stash stage (which includes concatenation and
         // the local file is thus already there). That way, instead of GET+PUT, there could
         // just be a COPY operation from the stash to the public zone.
         $upload->initialize($this->params['filekey'], $this->params['filename']);
         // Check if the local file checks out (this is generally a no-op)
         $verification = $upload->verifyUpload();
         if ($verification['status'] !== UploadBase::OK) {
             $status = Status::newFatal('verification-error');
             $status->value = ['verification' => $verification];
             UploadBase::setSessionStatus($user, $this->params['filekey'], ['result' => 'Failure', 'stage' => 'publish', 'status' => $status]);
             $this->setLastError("Could not verify upload.");
             return false;
         }
         // Upload the stashed file to a permanent location
         $status = $upload->performUpload($this->params['comment'], $this->params['text'], $this->params['watch'], $user, isset($this->params['tags']) ? $this->params['tags'] : []);
         if (!$status->isGood()) {
             UploadBase::setSessionStatus($user, $this->params['filekey'], ['result' => 'Failure', 'stage' => 'publish', 'status' => $status]);
             $this->setLastError($status->getWikiText(false, false, 'en'));
             return false;
         }
         // Build the image info array while we have the local reference handy
         $apiMain = new ApiMain();
         // dummy object (XXX)
         $imageInfo = $upload->getImageInfo($apiMain->getResult());
         // Cleanup any temporary local file
         $upload->cleanupTempFile();
         // Cache the info so the user doesn't have to wait forever to get the final info
         UploadBase::setSessionStatus($user, $this->params['filekey'], ['result' => 'Success', 'stage' => 'publish', 'filename' => $upload->getLocalFile()->getName(), 'imageinfo' => $imageInfo, 'status' => Status::newGood()]);
     } catch (Exception $e) {
         UploadBase::setSessionStatus($user, $this->params['filekey'], ['result' => 'Failure', 'stage' => 'publish', 'status' => Status::newFatal('api-error-publishfailed')]);
         $this->setLastError(get_class($e) . ": " . $e->getMessage());
         // To prevent potential database referential integrity issues.
         // See bug 32551.
         MWExceptionHandler::rollbackMasterChangesAndLog($e);
         return false;
     }
     return true;
 }
 /**
  * @param $username
  * @return Status
  */
 function fetchUser($username)
 {
     $knownwiki = $this->getRequest()->getVal('wpKnownWiki');
     $user = CentralAuthGroupMembershipProxy::newFromName($username);
     if (!$user) {
         return Status::newFatal('nosuchusershort', $username);
     } elseif (!$this->getRequest()->getCheck('saveusergroups') && !$user->attachedOn($knownwiki)) {
         return Status::newFatal('centralauth-globalgroupmembership-badknownwiki', $username, $knownwiki);
     }
     return Status::newGood($user);
 }
Example #15
0
 /**
  * Do the real fetching stuff
  */
 function fetchFile()
 {
     if (!self::isValidUrl($this->mUrl)) {
         return Status::newFatal('upload-proto-error');
     }
     $res = $this->curlCopy();
     if ($res !== true) {
         return Status::newFatal($res);
     }
     return Status::newGood();
 }
 /**
  * Check if a passwords meets the effective password policy for a User.
  * @param User $user who's policy we are checking
  * @param string $password the password to check
  * @return Status error to indicate the password didn't meet the policy, or fatal to
  *	indicate the user shouldn't be allowed to login.
  */
 public function checkUserPassword(User $user, $password)
 {
     $effectivePolicy = $this->getPoliciesForUser($user);
     $status = Status::newGood();
     foreach ($effectivePolicy as $policy => $value) {
         if (!isset($this->policyCheckFunctions[$policy])) {
             throw new DomainException('Invalid password policy config');
         }
         $status->merge(call_user_func($this->policyCheckFunctions[$policy], $value, $user, $password));
     }
     return $status;
 }
 /**
  * Entry points for MediaWiki hook 'EditFilterMerged' (MW 1.20 and earlier)
  *
  * @param $editor EditPage instance (object)
  * @param $text string Content of the edit box
  * @param &$error string Error message to return
  * @param $summary string Edit summary for page
  * @return bool
  */
 public static function onEditFilterMerged($editor, $text, &$error, $summary)
 {
     $context = $editor->mArticle->getContext();
     $status = Status::newGood();
     $minoredit = $editor->minoredit;
     // poor man's PST, see bug 20310
     $text = str_replace("\r\n", "\n", $text);
     $continue = self::filterEdit($context, null, $text, $status, $summary, $minoredit);
     if (!$status->isOK()) {
         $error = $status->getWikiText();
     }
     return $continue;
 }
 public function execute($par)
 {
     $this->useTransactionalTimeLimit();
     $this->checkPermissions();
     $this->checkReadOnly();
     $this->setHeaders();
     $this->outputHeader();
     $this->addHelpLink('Help:Merge history');
     $opts = new FormOptions();
     $opts->add('target', '');
     $opts->add('dest', '');
     $opts->add('target', '');
     $opts->add('mergepoint', '');
     $opts->add('reason', '');
     $opts->add('merge', false);
     $opts->fetchValuesFromRequest($this->getRequest());
     $target = $opts->getValue('target');
     $dest = $opts->getValue('dest');
     $targetObj = Title::newFromText($target);
     $destObj = Title::newFromText($dest);
     $status = Status::newGood();
     $this->mOpts = $opts;
     $this->mTargetObj = $targetObj;
     $this->mDestObj = $destObj;
     if ($opts->getValue('merge') && $targetObj && $destObj && $opts->getValue('mergepoint') !== '') {
         $this->merge();
         return;
     }
     if ($target === '' && $dest === '') {
         $this->showMergeForm();
         return;
     }
     if (!$targetObj instanceof Title) {
         $status->merge(Status::newFatal('mergehistory-invalid-source'));
     } elseif (!$targetObj->exists()) {
         $status->merge(Status::newFatal('mergehistory-no-source', wfEscapeWikiText($targetObj->getPrefixedText())));
     }
     if (!$destObj instanceof Title) {
         $status->merge(Status::newFatal('mergehistory-invalid-destination'));
     } elseif (!$destObj->exists()) {
         $status->merge(Status::newFatal('mergehistory-no-destination', wfEscapeWikiText($destObj->getPrefixedText())));
     }
     if ($targetObj && $destObj && $targetObj->equals($destObj)) {
         $status->merge(Status::newFatal('mergehistory-same-destination'));
     }
     $this->mStatus = $status;
     $this->showMergeForm();
     if ($status->isOK()) {
         $this->showHistory();
     }
 }
Example #19
0
	/**
	 * Open a /dev/urandom file handle
	 * Returns a Status object
	 */
	function open() {
		if ( $this->urandom ) {
			return Status::newGood();
		}

		if ( wfIsWindows() ) {
			return Status::newFatal( 'securepoll-urandom-not-supported' );
		}
		$this->urandom = fopen( '/dev/urandom', 'rb' );
		if ( !$this->urandom ) {
			return Status::newFatal( 'securepoll-dump-no-urandom' );
		}
		return Status::newGood();
	}
 public function run()
 {
     $scope = RequestContext::importScopedSession($this->params['session']);
     $context = RequestContext::getMain();
     try {
         $user = $context->getUser();
         if (!$user->isLoggedIn()) {
             $this->setLastError("Could not load the author user from session.");
             return false;
         }
         if (count($_SESSION) === 0) {
             // Empty session probably indicates that we didn't associate
             // with the session correctly. Note that being able to load
             // the user does not necessarily mean the session was loaded.
             // Most likely cause by suhosin.session.encrypt = On.
             $this->setLastError("Error associating with user session. " . "Try setting suhosin.session.encrypt = Off");
             return false;
         }
         UploadBase::setSessionStatus($this->params['filekey'], array('result' => 'Poll', 'stage' => 'assembling', 'status' => Status::newGood()));
         $upload = new UploadFromChunks($user);
         $upload->continueChunks($this->params['filename'], $this->params['filekey'], $context->getRequest());
         // Combine all of the chunks into a local file and upload that to a new stash file
         $status = $upload->concatenateChunks();
         if (!$status->isGood()) {
             UploadBase::setSessionStatus($this->params['filekey'], array('result' => 'Failure', 'stage' => 'assembling', 'status' => $status));
             $this->setLastError($status->getWikiText());
             return false;
         }
         // We have a new filekey for the fully concatenated file
         $newFileKey = $upload->getLocalFile()->getFileKey();
         // Remove the old stash file row and first chunk file
         $upload->stash->removeFileNoAuth($this->params['filekey']);
         // Build the image info array while we have the local reference handy
         $apiMain = new ApiMain();
         // dummy object (XXX)
         $imageInfo = $upload->getImageInfo($apiMain->getResult());
         // Cleanup any temporary local file
         $upload->cleanupTempFile();
         // Cache the info so the user doesn't have to wait forever to get the final info
         UploadBase::setSessionStatus($this->params['filekey'], array('result' => 'Success', 'stage' => 'assembling', 'filekey' => $newFileKey, 'imageinfo' => $imageInfo, 'status' => Status::newGood()));
     } catch (MWException $e) {
         UploadBase::setSessionStatus($this->params['filekey'], array('result' => 'Failure', 'stage' => 'assembling', 'status' => Status::newFatal('api-error-stashfailed')));
         $this->setLastError(get_class($e) . ": " . $e->getText());
         // To be extra robust.
         MWExceptionHandler::rollbackMasterChangesAndLog($e);
         return false;
     }
     return true;
 }
 public function onSubmit(array $data)
 {
     global $wgReadOnlyFile;
     if (!$data['Confirm']) {
         return Status::newFatal('locknoconfirm');
     }
     wfSuppressWarnings();
     $res = unlink($wgReadOnlyFile);
     wfRestoreWarnings();
     if ($res) {
         return Status::newGood();
     } else {
         return Status::newFatal('filedeleteerror', $wgReadOnlyFile);
     }
 }
Example #22
0
 public function onSubmit(array $data)
 {
     if (!$data['Confirm']) {
         return Status::newFatal('locknoconfirm');
     }
     $readOnlyFile = $this->getConfig()->get('ReadOnlyFile');
     MediaWiki\suppressWarnings();
     $res = unlink($readOnlyFile);
     MediaWiki\restoreWarnings();
     if ($res) {
         return Status::newGood();
     } else {
         return Status::newFatal('filedeleteerror', $readOnlyFile);
     }
 }
 public function run()
 {
     $scope = RequestContext::importScopedSession($this->params['session']);
     $this->addTeardownCallback(function () use(&$scope) {
         ScopedCallback::consume($scope);
         // T126450
     });
     $context = RequestContext::getMain();
     $user = $context->getUser();
     try {
         if (!$user->isLoggedIn()) {
             $this->setLastError("Could not load the author user from session.");
             return false;
         }
         UploadBase::setSessionStatus($user, $this->params['filekey'], ['result' => 'Poll', 'stage' => 'assembling', 'status' => Status::newGood()]);
         $upload = new UploadFromChunks($user);
         $upload->continueChunks($this->params['filename'], $this->params['filekey'], new WebRequestUpload($context->getRequest(), 'null'));
         // Combine all of the chunks into a local file and upload that to a new stash file
         $status = $upload->concatenateChunks();
         if (!$status->isGood()) {
             UploadBase::setSessionStatus($user, $this->params['filekey'], ['result' => 'Failure', 'stage' => 'assembling', 'status' => $status]);
             $this->setLastError($status->getWikiText(false, false, 'en'));
             return false;
         }
         // We can only get warnings like 'duplicate' after concatenating the chunks
         $status = Status::newGood();
         $status->value = ['warnings' => $upload->checkWarnings()];
         // We have a new filekey for the fully concatenated file
         $newFileKey = $upload->getStashFile()->getFileKey();
         // Remove the old stash file row and first chunk file
         $upload->stash->removeFileNoAuth($this->params['filekey']);
         // Build the image info array while we have the local reference handy
         $apiMain = new ApiMain();
         // dummy object (XXX)
         $imageInfo = $upload->getImageInfo($apiMain->getResult());
         // Cleanup any temporary local file
         $upload->cleanupTempFile();
         // Cache the info so the user doesn't have to wait forever to get the final info
         UploadBase::setSessionStatus($user, $this->params['filekey'], ['result' => 'Success', 'stage' => 'assembling', 'filekey' => $newFileKey, 'imageinfo' => $imageInfo, 'status' => $status]);
     } catch (Exception $e) {
         UploadBase::setSessionStatus($user, $this->params['filekey'], ['result' => 'Failure', 'stage' => 'assembling', 'status' => Status::newFatal('api-error-stashfailed')]);
         $this->setLastError(get_class($e) . ": " . $e->getMessage());
         // To be extra robust.
         MWExceptionHandler::rollbackMasterChangesAndLog($e);
         return false;
     }
     return true;
 }
 /**
  * @param string $username
  * @return Status
  */
 function fetchUser($username)
 {
     if ($username[0] == '#') {
         $id = intval(substr($username, 1));
         $user = CentralAuthGroupMembershipProxy::newFromId($id);
         if (!$user) {
             return Status::newFatal('noname', $id);
         }
     } else {
         $user = CentralAuthGroupMembershipProxy::newFromName($username);
         if (!$user) {
             return Status::newFatal('nosuchusershort', $username);
         }
     }
     return Status::newGood($user);
 }
/**
 * Remove variable from WikiFactory (delete from city_variables_pool table)
 * @param array $varData
 * @return Status
 */
function removeFromVariablesPool($varData)
{
    $log = WikiaLogger::instance();
    $dbw = WikiFactory::db(DB_MASTER);
    $dbw->begin();
    try {
        $dbw->delete("city_variables_pool", array("cv_id" => $varData['cv_id']), __METHOD__);
        $log->info("Remove variable from city_variables_pool table.", $varData);
        $dbw->commit();
        $status = Status::newGood();
    } catch (DBQueryError $e) {
        $log->error("Database error: Cannot remove variable from city_variables_pool table.", $varData);
        $dbw->rollback();
        $status = Status::newFatal("Database error: Cannot remove variable from city_variables_pool table (" . $e->getMessage() . ").");
    }
    return $status;
}
 /**
  * Parses coordinates
  * See https://en.wikipedia.org/wiki/Template:Coord for sample inputs
  * 
  * @param Array $parts: Array of coordinate components
  * @param String $globe: Globe name
  * @returns Status: Status object, in case of success its value is a Coord object.
  */
 public static function parseCoordinates($parts, $globe)
 {
     global $wgContLang, $wgGlobes;
     $count = count($parts);
     if (!is_array($parts) || $count < 2 || $count > 8 || $count % 2) {
         return Status::newFatal('geodata-bad-input');
     }
     list($latArr, $lonArr) = array_chunk($parts, $count / 2);
     $coordInfo = self::getCoordInfo();
     $lat = self::parseOneCoord($latArr, $coordInfo['lat']);
     if ($lat === false) {
         return Status::newFatal('geodata-bad-latitude');
     }
     $lonInfo = isset($wgGlobes[$globe]) ? $wgGlobes[$globe] : array('min' => -360, 'mid' => 0, 'max' => 360, 'abbr' => array('E' => 1, 'W' => -1), 'wrap' => true);
     $lon = self::parseOneCoord($lonArr, $lonInfo);
     if ($lon === false) {
         return Status::newFatal('geodata-bad-longitude');
     }
     return Status::newGood(new Coord($lat, $lon));
 }
 /**
  * This task is run when a video is uploaded but the provider does not have a
  * thumbnail for us to use. This gets triggered the first time a thumbnail
  * cannot be found, and is queued up again at longer intervals until we either
  * get a thumbnail from the provider, or exhaust all of our attempts.
  * @param $title
  * @param $delayIndex
  * @param $provider
  * @param $videoId
  * @return FileRepoStatus
  */
 public function retryThumbUpload($title, $delayIndex, $provider, $videoId)
 {
     global $IP, $wgCityId;
     /** @var Title $title */
     $file = WikiaFileHelper::getVideoFileFromTitle($title);
     if (empty($file)) {
         $msg = "File not found on wiki";
         if ($title instanceof Title) {
             $title = $title->getText();
         }
         $this->log("error", $delayIndex, $title, $provider, ["errorMsg" => $msg]);
         return Status::newFatal($msg);
     }
     $delayIndex++;
     $this->log("start", $delayIndex, $title->getText(), $provider);
     // IVA requires extra steps to update their thumbnail, use the script we have for that
     if ($provider == self::IVA) {
         $cmd = sprintf("SERVER_ID={$wgCityId} php {$IP}/maintenance/wikia/VideoHandlers/updateOoyalaThumbnail.php --videoId={$videoId} --delayIndex={$delayIndex}");
         $response = wfShellExec($cmd, $exitStatus);
         if ($exitStatus == 0) {
             $msg = "Video thumbnail uploaded successfully";
             $status = Status::newGood($msg);
         } else {
             $msg = "Error uploading video thumbnail: {$response}";
             $status = Status::newFatal($msg);
         }
     } else {
         $helper = new VideoHandlerHelper();
         $status = $helper->resetVideoThumb($file, null, $delayIndex);
     }
     if ($status->isGood()) {
         // A good status doesn't necessarily mean we updated the actual thumbnail. A good status is returned for
         // successfully uploading the default thumb as well. Actually check the img sha to see if the thumb changed
         if ($file->getSha1() != self::DEFAULT_THUMB_SHA) {
             $this->log("success", $delayIndex, $title->getText(), $provider, ['thumbnail' => $file->getThumbUrl()]);
         }
     } else {
         $this->log("error", $delayIndex, $title->getText(), $provider, ['errorMsg' => $status->getMessage()]);
     }
     return $status;
 }
Example #28
0
 public function onSubmit(array $data)
 {
     global $wgContLang;
     if (!$data['Confirm']) {
         return Status::newFatal('locknoconfirm');
     }
     MediaWiki\suppressWarnings();
     $fp = fopen($this->getConfig()->get('ReadOnlyFile'), 'w');
     MediaWiki\restoreWarnings();
     if (false === $fp) {
         # This used to show a file not found error, but the likeliest reason for fopen()
         # to fail at this point is insufficient permission to write to the file...good old
         # is_writable() is plain wrong in some cases, it seems...
         return Status::newFatal('lockfilenotwritable');
     }
     fwrite($fp, $data['Reason']);
     $timestamp = wfTimestampNow();
     fwrite($fp, "\n<p>" . $this->msg('lockedbyandtime', $this->getUser()->getName(), $wgContLang->date($timestamp, false, false), $wgContLang->time($timestamp, false, false))->inContentLanguage()->text() . "</p>\n");
     fclose($fp);
     return Status::newGood();
 }
 /**
  * Update metadata in the wiki
  * @param $video
  * @return bool
  */
 protected function addGenreToPageCategories($video)
 {
     $name = $video['img_name'];
     $this->outputMessage("Title: {$name}");
     $title = Title::newFromText($name, NS_FILE);
     if ($title instanceof Title && $title->exists()) {
         $article = Article::newFromID($title->getArticleID());
         $content = $article->getContent();
         // set default value
         $status = Status::newGood();
         // add category
         $metadata = $this->extractMetadata($video);
         if (empty($metadata['genres'])) {
             $this->incSkipped();
             $this->outputMessage("File remained indifferent. no category changes.");
             return false;
         }
         $categories = explode(', ', $metadata['genres']);
         $content = $this->addCategories($content, $categories);
         $msg = 'Added: ' . implode(', ', $categories);
         if (!$this->isDryRun()) {
             $botUser = User::newFromName('WikiaBot');
             $status = $article->doEdit($content, 'Changing categories', EDIT_UPDATE | EDIT_SUPPRESS_RC | EDIT_FORCE_BOT, false, $botUser);
         }
         if ($status instanceof Status) {
             if ($status->isOK()) {
                 $this->outputMessage("...DONE (" . $msg . ")");
             } else {
                 ++$this->failedWiki;
                 echo "...FAILED (" . $status->getMessage() . ").\n";
                 return false;
             }
         }
         $this->outputMessage("\tUpdated (Wiki): {$name}");
     } else {
         $this->outputError("(Title '{$name}' not found).", "...FAILED ");
         return false;
     }
     return true;
 }
 public function run()
 {
     $scope = RequestContext::importScopedSession($this->params['session']);
     $context = RequestContext::getMain();
     try {
         $user = $context->getUser();
         if (!$user->isLoggedIn()) {
             $this->setLastError("Could not load the author user from session.");
             return false;
         }
         UploadBase::setSessionStatus($this->params['filekey'], array('result' => 'Poll', 'stage' => 'assembling', 'status' => Status::newGood()));
         $upload = new UploadFromChunks($user);
         $upload->continueChunks($this->params['filename'], $this->params['filekey'], $context->getRequest());
         // Combine all of the chunks into a local file and upload that to a new stash file
         $status = $upload->concatenateChunks();
         if (!$status->isGood()) {
             UploadBase::setSessionStatus($this->params['filekey'], array('result' => 'Failure', 'stage' => 'assembling', 'status' => $status));
             $this->setLastError($status->getWikiText());
             return false;
         }
         // We have a new filekey for the fully concatenated file
         $newFileKey = $upload->getLocalFile()->getFileKey();
         // Remove the old stash file row and first chunk file
         $upload->stash->removeFileNoAuth($this->params['filekey']);
         // Build the image info array while we have the local reference handy
         $apiMain = new ApiMain();
         // dummy object (XXX)
         $imageInfo = $upload->getImageInfo($apiMain->getResult());
         // Cleanup any temporary local file
         $upload->cleanupTempFile();
         // Cache the info so the user doesn't have to wait forever to get the final info
         UploadBase::setSessionStatus($this->params['filekey'], array('result' => 'Success', 'stage' => 'assembling', 'filekey' => $newFileKey, 'imageinfo' => $imageInfo, 'status' => Status::newGood()));
     } catch (MWException $e) {
         UploadBase::setSessionStatus($this->params['filekey'], array('result' => 'Failure', 'stage' => 'assembling', 'status' => Status::newFatal('api-error-stashfailed')));
         $this->setLastError(get_class($e) . ": " . $e->getText());
         return false;
     }
     return true;
 }