Beispiel #1
0
 /**
  * xSaveAction
  *
  * @param string $ccId
  * @param string $projectId
  * @param string $name
  * @param string $description
  * @param string $billingCode
  * @param string $leadEmail
  * @param int $shared
  * @param int $accountId optional
  * @param bool $checkAccountAccessToCc optional
  * @param bool $grantAccountAccessToCc optional
  * @throws Scalr_Exception_InsufficientPermissions
  */
 public function xSaveAction($ccId, $projectId, $name, $description, $billingCode, $leadEmail, $shared, $accountId = null, $checkAccountAccessToCc = true, $grantAccountAccessToCc = false)
 {
     $validator = new Validator();
     $validator->validate($name, 'name', Validator::NOEMPTY);
     if ($projectId) {
         $project = $this->getContainer()->analytics->projects->get($projectId);
         if (!$project) {
             throw new Scalr_UI_Exception_NotFound();
         }
     } else {
         $project = new ProjectEntity();
         $project->createdById = $this->user->id;
         $project->createdByEmail = $this->user->getEmail();
         $cc = $this->getContainer()->analytics->ccs->get($ccId);
         if (!$cc) {
             $validator->addError('ccId', 'Cost center ID should be set');
         }
         $project->ccId = $ccId;
     }
     if ($shared == ProjectEntity::SHARED_WITHIN_ACCOUNT) {
         $project->shared = ProjectEntity::SHARED_WITHIN_ACCOUNT;
         $project->accountId = $accountId;
     } elseif ($shared == ProjectEntity::SHARED_WITHIN_CC) {
         $project->shared = ProjectEntity::SHARED_WITHIN_CC;
         $project->accountId = null;
     } else {
         throw new Scalr_UI_Exception_NotFound();
     }
     if (!$validator->isValid($this->response)) {
         return;
     }
     if ($project->shared == ProjectEntity::SHARED_WITHIN_ACCOUNT) {
         if (!AccountCostCenterEntity::findOne([['accountId' => $project->accountId], ['ccId' => $ccId]])) {
             if ($checkAccountAccessToCc) {
                 $this->response->data(['ccIsNotAllowedToAccount' => true]);
                 $this->response->failure();
                 return;
             } elseif ($grantAccountAccessToCc) {
                 //give account access to cc
                 $accountCcEntity = new AccountCostCenterEntity($project->accountId, $ccId);
                 $accountCcEntity->save();
             }
         }
     }
     $project->name = $name;
     $this->db->BeginTrans();
     try {
         $project->save();
         //NOTE please take into account the presence of the usage->createHostedScalrAccountCostCenter() method
         $project->saveProperty(ProjectPropertyEntity::NAME_BILLING_CODE, $billingCode);
         $project->saveProperty(ProjectPropertyEntity::NAME_DESCRIPTION, $description);
         $project->saveProperty(ProjectPropertyEntity::NAME_LEAD_EMAIL, $leadEmail);
         $this->db->CommitTrans();
     } catch (Exception $e) {
         $this->db->RollbackTrans();
         throw $e;
     }
     $this->response->data(['project' => $this->getProjectData($project)]);
     $this->response->success('Project has been successfully saved');
 }
Beispiel #2
0
 public function xSaveAction()
 {
     $this->request->defineParams(array('id' => array('type' => 'int'), 'name' => array('type' => 'string'), 'ownerEmail' => array('type' => 'string'), 'ownerPassword' => array('type' => 'string', 'rawValue' => true), 'comments' => array('type' => 'string'), 'ccs' => array('type' => 'json')));
     $account = Scalr_Account::init();
     $validator = new Validator();
     $id = (int) $this->getParam('id');
     $name = $this->getParam('name');
     $ownerEmail = $this->getParam('ownerEmail');
     $ownerPassword = $this->getParam('ownerPassword');
     $validator->validate($name, "name", Validator::NOEMPTY, [], "Name is required");
     $validator->validate($id, "id", Validator::INTEGERNUM);
     if ($id) {
         $account->loadById($id);
     } else {
         $account->status = Scalr_Account::STATUS_ACTIVE;
         if ($this->getContainer()->config->get('scalr.auth_mode') == 'scalr') {
             $validator->validate($ownerEmail, "ownerEmail", Validator::EMAIL);
             $validator->validate($ownerPassword, "ownerPassword", Validator::PASSWORD, ["admin"]);
         } elseif ($this->getContainer()->config->get('scalr.auth_mode') == 'ldap') {
             $validator->validate($ownerEmail, "ownerEmail", Validator::NOEMPTY, [], "Email is required");
         }
     }
     if (!$validator->isValid($this->response)) {
         return;
     }
     $this->db->BeginTrans();
     try {
         $account->name = $name;
         $account->comments = $this->getParam('comments');
         $account->save();
         $account->initializeAcl();
         $account->setLimits(array(Scalr_Limits::ACCOUNT_ENVIRONMENTS => $this->getParam('limitEnv'), Scalr_Limits::ACCOUNT_FARMS => $this->getParam('limitFarms'), Scalr_Limits::ACCOUNT_SERVERS => $this->getParam('limitServers'), Scalr_Limits::ACCOUNT_USERS => $this->getParam('limitUsers')));
         if (!$id) {
             $user = $account->createUser($ownerEmail, $ownerPassword, Scalr_Account_User::TYPE_ACCOUNT_OWNER);
             if ($this->getContainer()->analytics->enabled) {
                 //Default Cost Center should be assigned
                 $cc = $this->getContainer()->analytics->ccs->get($this->getContainer()->analytics->usage->autoCostCentre());
                 //Assigns account with Cost Center
                 $accountCcEntity = new AccountCostCenterEntity($account->id, $cc->ccId);
                 $accountCcEntity->save();
             }
             $account->createEnvironment("default");
         }
         if ($this->getContainer()->config->get('scalr.auth_mode') == 'ldap' && $id) {
             if ($ownerEmail != $account->getOwner()->getEmail()) {
                 $prev = $account->getOwner();
                 $prev->type = Scalr_Account_User::TYPE_TEAM_USER;
                 $prev->save();
                 $user = new Scalr_Account_User();
                 if ($user->loadByEmail($ownerEmail, $account->id)) {
                     $user->type = Scalr_Account_User::TYPE_ACCOUNT_OWNER;
                     $user->save();
                 } else {
                     $account->createUser($ownerEmail, $ownerPassword, Scalr_Account_User::TYPE_ACCOUNT_OWNER);
                 }
             }
         }
         if ($this->getContainer()->analytics->enabled) {
             if (!Scalr::isHostedScalr()) {
                 //save ccs
                 $ccs = (array) $this->getParam('ccs');
                 foreach (AccountCostCenterEntity::findByAccountId($account->id) as $accountCcsEntity) {
                     $index = array_search($accountCcsEntity->ccId, $ccs);
                     if ($index === false) {
                         $accountCcsEntity->delete();
                     } else {
                         unset($ccs[$index]);
                     }
                 }
                 foreach ($ccs as $ccId) {
                     $accountCcsEntity = new AccountCostCenterEntity($account->id, $ccId);
                     $accountCcsEntity->save();
                 }
             }
         }
     } catch (Exception $e) {
         $this->db->RollbackTrans();
         throw $e;
     }
     $this->db->CommitTrans();
     $this->response->data(array('accountId' => $account->id));
 }
Beispiel #3
0
 /**
  * xMoveProjectsAction
  *
  * @param JsonData $projects Projects that should be moved
  * @throws AnalyticsException
  * @throws Exception
  * @throws \Scalr\Exception\ModelException
  */
 public function xMoveProjectsAction(JsonData $projects = null)
 {
     $envChange = [];
     $accountChange = [];
     $projectChange = [];
     $ccEntityCache = [];
     $collisions = [];
     foreach ($projects as $project) {
         $projectEntity = ProjectEntity::findPk($project['projectId']);
         /* @var $projectEntity ProjectEntity */
         if (empty($ccEntity)) {
             $ccEntity = $projectEntity->getCostCenter();
         }
         if ($ccEntity->ccId == $project['ccId']) {
             continue;
         }
         if (empty($ccEntityCache[$project['ccId']])) {
             $newCcEntity = CostCentreEntity::findPk($project['ccId']);
             /* @var $newCcEntity CostCentreEntity */
             if (!$newCcEntity) {
                 throw new Exception(sprintf("Cost center with id %s has not been found.", $project['ccId']), 404);
             }
             $ccEntityCache[$project['ccId']] = $newCcEntity->ccId;
         }
         $farms[$projectEntity->projectId] = $projectEntity->getFarmsList();
         foreach ($farms[$projectEntity->projectId] as $farmId => $farmName) {
             $farmEntity = Farm::findPk($farmId);
             /* @var $farmEntity Farm */
             if (empty($accountChange[$farmEntity->accountId])) {
                 $accountCss = AccountCostCenterEntity::findOne([['accountId' => $farmEntity->accountId], ['ccId' => $newCcEntity->ccId]]);
                 if (!$accountCss) {
                     $accountChange[$farmEntity->accountId] = $newCcEntity->ccId;
                 }
             }
             if (empty($envChange[$farmEntity->envId])) {
                 $project['name'] = $projectEntity->name;
                 $envChange[$farmEntity->envId] = $project;
             } else {
                 if ($envChange[$farmEntity->envId]['ccId'] != $project['ccId']) {
                     if (!in_array($projectEntity->name, $collisions)) {
                         $collisions[] = $projectEntity->name;
                     }
                     if (!in_array($envChange[$farmEntity->envId]['name'], $collisions)) {
                         $collisions[] = $envChange[$farmEntity->envId]['name'];
                     }
                     continue;
                 }
             }
         }
         $projectEntity->ccId = $project['ccId'];
         $projectChange[$projectEntity->projectId] = $projectEntity;
     }
     $remainningEnvs = [];
     $projectsCount = count($projectChange);
     if ($projectsCount) {
         if (isset($ccEntity)) {
             $envList = $ccEntity->getEnvironmentsList();
             foreach ($envList as $envId => $name) {
                 if (isset($envChange[$envId])) {
                     $ccProjects = $this->getContainer()->analytics->projects->getUsedInEnvironment($envId);
                     foreach ($ccProjects as $project) {
                         /* @var $project ProjectEntity */
                         if (!isset($farms[$project->projectId])) {
                             $farms[$project->projectId] = $project->getFarmsList();
                         }
                         if (count($farms[$project->projectId]) > 0 && !isset($projectChange[$project->projectId])) {
                             if (!in_array($envId, $remainningEnvs)) {
                                 $remainningEnvs[] = $envId;
                             }
                         }
                     }
                 }
             }
         }
         $this->db->BeginTrans();
         try {
             foreach ($accountChange as $accountId => $ccId) {
                 $accountCss = new AccountCostCenterEntity($accountId, $ccId);
                 $accountCss->save();
             }
             if (empty($remainningEnvs) && empty($collisions)) {
                 foreach ($envChange as $envId => $data) {
                     $envProp = EnvironmentProperty::findOne([['envId' => $envId], ['name' => EnvironmentProperty::SETTING_CC_ID]]);
                     /* @var $envProp EnvironmentProperty */
                     $envProp->value = $data['ccId'];
                     $envProp->save();
                 }
             }
             foreach ($projectChange as $project) {
                 /* @var $project ProjectEntity */
                 $project->save();
             }
             $this->db->CommitTrans();
         } catch (Exception $e) {
             $this->db->RollbackTrans();
             throw $e;
         }
     }
     if (count($collisions) > 0) {
         $this->response->warning(sprintf("%d Project%s %s been moved however collision occurred. Projects '%s' are used in the Farms from the same Environment however they have been moved to different Cost Centers.", $projectsCount, $projectsCount > 1 ? 's' : '', $projectsCount > 1 ? 'have' : 'has', implode("', '", $collisions)));
     } else {
         if (count($remainningEnvs) > 0) {
             $this->response->warning(sprintf("%d Project%s %s been moved however some Projects don't correspond to Cost Centers assigned to Environments '%s'.", $projectsCount, $projectsCount > 1 ? 's' : '', $projectsCount > 1 ? 'have' : 'has', implode("', '", $remainningEnvs)));
         } else {
             $this->response->success(sprintf("%d Project%s %s been moved to other Cost Center.", $projectsCount, $projectsCount > 1 ? 's' : '', $projectsCount > 1 ? 'have' : 'has'));
         }
     }
 }
Beispiel #4
0
 protected function run1($stage)
 {
     $analytics = \Scalr::getContainer()->analytics;
     if (!\Scalr::isHostedScalr()) {
         $this->console->warning("Terminating as this upgrade script is only for Hosted Scalr installation.");
         return;
     }
     $this->console->out("Creates default Cost Center for an each Account");
     $rs = $this->db->Execute("SELECT id FROM `clients`");
     while ($rec = $rs->FetchRow()) {
         try {
             $account = Scalr_Account::init()->loadById($rec['id']);
         } catch (Exception $e) {
             continue;
         }
         $this->console->out("Processing %s (%d) account...", $account->name, $account->id);
         //Whether the Account already has account level Cost Center assigned to it
         $ccs = $account->getCostCenters()->filterByAccountId($account->id);
         if (count($ccs) > 0) {
             //We assume that the account has already been initialized
             continue;
         }
         try {
             //Gets account owner user to be CC Lead
             $owner = $account->getOwner();
         } catch (Exception $e) {
             continue;
         }
         //Creates default Cost Center and Project
         $cc = $analytics->usage->createHostedScalrAccountCostCenter($account, $owner);
         //Associates default CC with the account
         $accountCc = new AccountCostCenterEntity($account->id, $cc->ccId);
         $accountCc->save();
         //Gets project entity
         /* @var $project ProjectEntity */
         $project = $cc->getProjects()[0];
         foreach ($this->db->GetAll("SELECT id FROM client_environments WHERE client_id = ?", [$account->id]) as $row) {
             try {
                 $environment = Scalr_Environment::init()->loadById($row['id']);
             } catch (Exception $e) {
                 continue;
             }
             $this->console->out("- Environment: %s (%d) CC: %s", $environment->name, $environment->id, $cc->ccId);
             //Creates association
             $environment->setPlatformConfig([Scalr_Environment::SETTING_CC_ID => $cc->ccId]);
             foreach ($this->db->GetAll("SELECT id FROM farms WHERE env_id = ?", [$environment->id]) as $r) {
                 try {
                     $farm = DBFarm::LoadByID($r['id']);
                 } catch (Exception $e) {
                     continue;
                 }
                 $this->console->out("- - Farm: %s (%d) Project: %s", $farm->Name, $farm->ID, $project->projectId);
                 //Associates farm with default Project
                 $farm->SetSetting(Entity\FarmSetting::PROJECT_ID, $project->projectId);
                 unset($farm);
             }
             $this->console->out("- Updating server properties for environment %s (%d)", $environment->name, $environment->id);
             $this->db->Execute("\n                    INSERT `server_properties` (`server_id`, `name`, `value`)\n                    SELECT s.`server_id`, ?, ? FROM `servers` s WHERE s.env_id = ?\n                    ON DUPLICATE KEY UPDATE `value` = ?\n                ", [SERVER_PROPERTIES::FARM_PROJECT_ID, $project->projectId, $environment->id, $project->projectId]);
             $this->db->Execute("\n                    INSERT `server_properties` (`server_id`, `name`, `value`)\n                    SELECT s.`server_id`, ?, ? FROM `servers` s WHERE s.env_id = ?\n                    ON DUPLICATE KEY UPDATE `value` = ?\n                ", [SERVER_PROPERTIES::ENV_CC_ID, $cc->ccId, $environment->id, $cc->ccId]);
             unset($environment);
         }
         unset($ccs);
         unset($owner);
         unset($account);
     }
 }
Beispiel #5
0
 /**
  * @param string  $name
  * @param string  $org
  * @param string  $email
  * @param RawData $password
  * @param string  $agreeTerms
  * @param string  $newBilling
  * @param string  $country
  * @param string  $phone
  * @param string  $lastname
  * @param string  $firstname
  * @param string  $v
  * @param string  $numServers
  */
 public function xCreateAccountAction($name = '', $org = '', $email = '', RawData $password = null, $agreeTerms = '', $newBilling = '', $country = '', $phone = '', $lastname = '', $firstname = '', $v = '', $numServers = '', $beta = 0)
 {
     if (!\Scalr::config('scalr.billing.enabled')) {
         header("HTTP/1.0 403 Forbidden");
         exit;
     }
     $validator = new Validator();
     if ($v == 2) {
         $validator->validate($firstname, "firstname", Validator::NOEMPTY, [], "First name is required");
         $validator->validate($lastname, "lastname", Validator::NOEMPTY, [], "Last name is required");
         $name = $firstname . " " . $lastname;
     } else {
         $validator->validate($name, "name", Validator::NOEMPTY, [], "Account name is required");
     }
     if ($password == '') {
         $password = \Scalr::GenerateSecurePassword(User::PASSWORD_ADMIN_LENGTH);
     }
     $validator->validate($email, "email", Validator::EMAIL);
     $validator->validate($password, "password", Validator::PASSWORD, ['admin']);
     $validator->addErrorIf($this->db->GetOne("SELECT EXISTS(SELECT * FROM account_users WHERE email = ?)", [$email]), "email", "E-mail already exists in the database");
     $validator->validate($agreeTerms, "agreeTerms", Validator::NOEMPTY, [], "You haven't accepted terms and conditions");
     $errors = $validator->getErrors(true);
     if (empty($errors)) {
         $account = Scalr_Account::init();
         $account->name = $org ? $org : $name;
         $account->status = Scalr_Account::STATUS_ACTIVE;
         $account->save();
         $user = $account->createUser($email, $password, Scalr_Account_User::TYPE_ACCOUNT_OWNER);
         $user->fullname = $name;
         $user->save();
         if ($this->getContainer()->analytics->enabled) {
             $analytics = $this->getContainer()->analytics;
             //Default Cost Center should be assigned
             $cc = $analytics->ccs->get($analytics->usage->autoCostCentre());
             //Assigns account with Cost Center
             $accountCcEntity = new AccountCostCenterEntity($account->id, $cc->ccId);
             $accountCcEntity->save();
         }
         //Creates Environment. It will be associated with the Cost Center itself.
         $account->createEnvironment("Environment 1");
         $account->initializeAcl();
         if ($v == 2) {
             $user->setSetting('website.phone', $phone);
             $user->setSetting('website.country', $country);
             $user->setSetting('website.num_servers', $numServers);
         }
         /**
          * Limits
          */
         $url = Scalr::config('scalr.endpoint.scheme') . "://" . Scalr::config('scalr.endpoint.host');
         try {
             $billing = new Scalr_Billing();
             $billing->loadByAccount($account);
             $billing->createSubscription(Scalr_Billing::PAY_AS_YOU_GO, "", "", "", "");
         } catch (Exception $e) {
             $account->delete();
             header("Location: {$url}/order/?error={$e->getMessage()}");
             exit;
         }
         if ($_COOKIE['__utmz']) {
             $gaParser = new Scalr_Service_GoogleAnalytics_Parser();
             $clientSettings[CLIENT_SETTINGS::GA_CAMPAIGN_CONTENT] = $gaParser->campaignContent;
             $clientSettings[CLIENT_SETTINGS::GA_CAMPAIGN_MEDIUM] = $gaParser->campaignMedium;
             $clientSettings[CLIENT_SETTINGS::GA_CAMPAIGN_NAME] = $gaParser->campaignName;
             $clientSettings[CLIENT_SETTINGS::GA_CAMPAIGN_SOURCE] = $gaParser->campaignSource;
             $clientSettings[CLIENT_SETTINGS::GA_CAMPAIGN_TERM] = $gaParser->campaignTerm;
             $clientSettings[CLIENT_SETTINGS::GA_FIRST_VISIT] = $gaParser->firstVisit;
             $clientSettings[CLIENT_SETTINGS::GA_PREVIOUS_VISIT] = $gaParser->previousVisit;
             $clientSettings[CLIENT_SETTINGS::GA_TIMES_VISITED] = $gaParser->timesVisited;
         }
         if (!empty($clientSettings)) {
             foreach ($clientSettings as $k => $v) {
                 $account->setSetting($k, $v);
             }
         }
         try {
             $this->db->Execute("\n                    INSERT INTO default_records\n                    SELECT null, '{$account->id}', rtype, ttl, rpriority, rvalue, rkey\n                    FROM default_records\n                    WHERE clientid='0'\n                ");
         } catch (Exception $e) {
         }
         $clientinfo = array('fullname' => $name, 'firstname' => $firstname ? $firstname : $name, 'email' => $email, 'password' => $password);
         //Sends welcome email
         $this->getContainer()->mailer->setFrom('*****@*****.**', 'Scalr')->setHtml()->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/welcome.html.php', array('firstName' => htmlspecialchars($clientinfo['firstname']), 'password' => htmlspecialchars($clientinfo['password']), "siteUrl" => htmlspecialchars($url), "wikiUrl" => htmlspecialchars(\Scalr::config('scalr.ui.wiki_url')), "supportUrl" => htmlspecialchars(\Scalr::config('scalr.ui.support_url')), "isUrl" => preg_match('/^http(s?):\\/\\//i', \Scalr::config('scalr.ui.support_url'))), $email);
         $user->getAccount()->setSetting(Scalr_Account::SETTING_IS_TRIAL, 1);
         //AutoLogin
         $user->updateLastLogin();
         Scalr_Session::create($user->getId());
         Scalr_Session::keepSession();
         if ($beta != 1) {
             $this->response->setRedirect("{$url}/thanks.html");
         } else {
             $this->response->data(array('accountId' => $user->getAccountId()));
         }
     } else {
         if ($beta == 1) {
             header("HTTP/1.0 400 Bad request");
             print json_encode($errors);
             exit;
         } else {
             $error = array_values($errors)[0];
             $this->response->setRedirect("{$url}/order/?error={$error}");
         }
     }
 }