/** * Perform validation on the user submitted data * and check that we can perform the rename * @param array $data * * @return Status */ function validate(array $data) { if (!class_exists('RenameuserSQL')) { return Status::newFatal('centralauth-rename-notinstalled'); } $oldUser = User::newFromName($data['oldname']); if (!$oldUser) { return Status::newFatal('centralauth-rename-doesnotexist'); } if ($oldUser->getName() === $this->getUser()->getName()) { return Status::newFatal('centralauth-rename-cannotself'); } $newUser = User::newFromName($data['newname']); if (!$newUser) { return Status::newFatal('centralauth-rename-badusername'); } if (!$this->overrideAntiSpoof && class_exists('CentralAuthSpoofUser')) { $spoofUser = new CentralAuthSpoofUser($newUser->getName()); $conflicts = $this->processAntiSpoofConflicts($oldUser->getName(), $spoofUser->getConflicts()); if ($conflicts) { return Status::newFatal('centralauth-rename-antispoofconflicts2', $this->getLanguage()->commaList($conflicts)); } } $validator = new GlobalRenameUserValidator(); $status = $validator->validate($oldUser, $newUser); return $status; }
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, []); }
public function execute($subPage) { $this->setHeaders(); $this->outputHeader(); $this->loadAuth($subPage); if (!$subPage) { $this->showSubpageList(); return; } if (!$this->authRequests) { // messages used: changecredentials-invalidsubpage, removecredentials-invalidsubpage $this->showSubpageList($this->msg(static::$messagePrefix . '-invalidsubpage', $subPage)); return; } $status = $this->trySubmit(); if ($status === false || !$status->isOK()) { $this->displayForm($status); return; } $response = $status->getValue(); switch ($response->status) { case AuthenticationResponse::PASS: $this->success(); break; case AuthenticationResponse::FAIL: $this->displayForm(Status::newFatal($response->message)); break; default: throw new LogicException('invalid AuthenticationResponse'); } }
public function onSubmit(array $data, \HTMLForm $form = null) { // Get uploaded file $upload =& $_FILES['wpjsonimport']; // Check to make sure there is a file uploaded if ($upload === null || !$upload['name']) { return \Status::newFatal('importnofile'); } // Messages borrowed from Special:Import if (!empty($upload['error'])) { switch ($upload['error']) { case 1: case 2: return \Status::newFatal('importuploaderrorsize'); case 3: return \Status::newFatal('importuploaderrorpartial'); case 4: return \Status::newFatal('importuploaderrortemp'); default: return \Status::newFatal('importnofile'); } } // Read file $fname = $upload['tmp_name']; if (!is_uploaded_file($fname)) { return \Status::newFatal('importnofile'); } $data = \FormatJSON::parse(file_get_contents($fname)); // If there is an error during JSON parsing, abort if (!$data->isOK()) { return $data; } $this->doImport($data->getValue()); }
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); }
/** * @covers Status::newFatal */ public function testNewFatalWithString() { $message = 'foo'; $status = Status::newFatal($message); $this->assertFalse($status->isGood()); $this->assertFalse($status->isOK()); $this->assertEquals($message, $status->getMessage()->getKey()); }
/** * Main entry point. */ public function execute() { $vars = Installer::getExistingLocalSettings(); if ($vars) { $this->showStatusMessage(Status::newFatal("config-localsettings-cli-upgrade")); } $this->performInstallation(array($this, 'startStage'), array($this, 'endStage')); }
/** * @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'); }
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); }
/** * 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(); }
/** * 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(); }
/** * @return Status */ public function submit() { $r = $this->parent->request; $type = $r->getVal('DBType'); if (!$type) { return Status::newFatal('config-invalid-db-type'); } $this->setVar('wgDBtype', $type); $installer = $this->parent->getDBInstaller($type); if (!$installer) { return Status::newFatal('config-invalid-db-type'); } return $installer->submitConnectForm(); }
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; }
protected function getPasswordResetData($username, $row) { $now = wfTimestamp(); $expiration = wfTimestampOrNull(TS_UNIX, $row->user_password_expires); if ($expiration === null || $expiration >= $now) { return null; } $grace = $this->config->get('PasswordExpireGrace'); if ($expiration + $grace < $now) { $data = ['hard' => true, 'msg' => \Status::newFatal('resetpass-expired')->getMessage()]; } else { $data = ['hard' => false, 'msg' => \Status::newFatal('resetpass-expired-soft')->getMessage()]; } return (object) $data; }
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); } }
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; }
/** * @dataProvider provideIsAllowed */ public function testIsAllowed($passwordResetRoutes, $enableEmail, $allowsAuthenticationDataChange, $canEditPrivate, $canSeePassword, $userIsBlocked, $isAllowed, $isAllowedToDisplayPassword) { $config = new HashConfig(['PasswordResetRoutes' => $passwordResetRoutes, 'EnableEmail' => $enableEmail]); $authManager = $this->getMockBuilder(AuthManager::class)->disableOriginalConstructor()->getMock(); $authManager->expects($this->any())->method('allowsAuthenticationDataChange')->willReturn($allowsAuthenticationDataChange ? Status::newGood() : Status::newFatal('foo')); $user = $this->getMock(User::class); $user->expects($this->any())->method('getName')->willReturn('Foo'); $user->expects($this->any())->method('isBlocked')->willReturn($userIsBlocked); $user->expects($this->any())->method('isAllowed')->will($this->returnCallback(function ($perm) use($canEditPrivate, $canSeePassword) { if ($perm === 'editmyprivateinfo') { return $canEditPrivate; } elseif ($perm === 'passwordreset') { return $canSeePassword; } else { $this->fail('Unexpected permission check'); } })); $passwordReset = new PasswordReset($config, $authManager); $this->assertSame($isAllowed, $passwordReset->isAllowed($user)->isGood()); $this->assertSame($isAllowedToDisplayPassword, $passwordReset->isAllowed($user, true)->isGood()); }
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(); }
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; }
public function onSubmit(array $data) { global $wgCityId; $res = true; if (!$data['Confirm']) { return Status::newFatal('locknoconfirm'); } wfSuppressWarnings(); if (!WikiFactory::setVarByName('wgReadOnly', $wgCityId, '')) { wfDebug(__METHOD__ . ": cannot set wgReadOnly for Wikia: {$wgCityId} \n"); $res = false; } if (!WikiFactory::clearCache($wgCityId)) { wfDebug(__METHOD__ . ": cannot clear cache for Wikia: {$wgCityId} \n"); $res = false; } wfRestoreWarnings(); if ($res) { return Status::newGood(); } else { return Status::newFatal('unlockdb-wikifactory-error'); } }
/** * Add a record. This is the callback function for SecurePoll_Store::callbackValidVotes(). * On error, the Status object returned here will be passed through back to * the caller of callbackValidVotes(). * * @param $store SecurePoll_Store * @param $record string Encrypted, packed record. * @return Status */ function addRecord( $store, $record ) { # Decrypt and unpack if ( $this->crypt ) { $status = $this->crypt->decrypt( $record ); if ( !$status->isOK() ) { return $status; } $record = $status->value; } $record = rtrim( $record ); $scores = $this->ballot->unpackRecord( $record ); # Add the record to the underlying question-specific tallier objects foreach ( $this->election->getQuestions() as $question ) { $qid = $question->getId(); if ( !isset( $scores[$qid] ) ) { return Status::newFatal( 'securepoll-tally-error' ); } if ( !$this->talliers[$qid]->addVote( $scores[$qid] ) ) { return Status::newFatal( 'securepoll-tally-error' ); } } return Status::newGood(); }
/** * Handle the form submission if everything validated properly * * @param $formData * @param $form PreferencesForm * @param $entryPoint string * @return bool|Status|string */ static function tryFormSubmit( $formData, $form, $entryPoint = 'internal' ) { global $wgHiddenPrefs, $wgAuth; $user = $form->getModifiedUser(); $result = true; if ( !$user->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) { return Status::newFatal( 'mypreferencesprotected' ); } // Filter input foreach ( array_keys( $formData ) as $name ) { if ( isset( self::$saveFilters[$name] ) ) { $formData[$name] = call_user_func( self::$saveFilters[$name], $formData[$name], $formData ); } } // Fortunately, the realname field is MUCH simpler // (not really "private", but still shouldn't be edited without permission) if ( !in_array( 'realname', $wgHiddenPrefs ) && $user->isAllowed( 'editmyprivateinfo' ) ) { $realName = $formData['realname']; $user->setRealName( $realName ); } if ( $user->isAllowed( 'editmyoptions' ) ) { foreach ( self::$saveBlacklist as $b ) { unset( $formData[$b] ); } # If users have saved a value for a preference which has subsequently been disabled # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference # is subsequently re-enabled # TODO: maintenance script to actually delete these foreach ( $wgHiddenPrefs as $pref ) { # If the user has not set a non-default value here, the default will be returned # and subsequently discarded $formData[$pref] = $user->getOption( $pref, null, true ); } // Keep old preferences from interfering due to back-compat code, etc. $user->resetOptions( 'unused', $form->getContext() ); foreach ( $formData as $key => $value ) { $user->setOption( $key, $value ); } $user->saveSettings(); } $wgAuth->updateExternalDB( $user ); return $result; }
/** * Use appropriate dispatch* method to obtain a redirection URL, * and either: redirect, set a 404 error code and error message, * or do nothing (if $mValue wasn't set) allowing the form to be * displayed. * * @return bool True if a redirect was successfully handled. */ function dispatch() { // the various namespaces supported by Special:Redirect switch ($this->mType) { case 'user': $url = $this->dispatchUser(); break; case 'file': $url = $this->dispatchFile(); break; case 'revision': $url = $this->dispatchRevision(); break; case 'page': $url = $this->dispatchPage(); break; case 'logid': $url = $this->dispatchLog(); break; default: $url = null; break; } if ($url) { $this->getOutput()->redirect($url); return true; } if (!is_null($this->mValue)) { $this->getOutput()->setStatusCode(404); // Message: redirect-not-exists $msg = $this->getMessagePrefix() . '-not-exists'; return Status::newFatal($msg); } return false; }