/** * Gets default search criteria * * @return array Returns array of the search criteria * * @throws ApiNotImplementedErrorException */ public function getDefaultCriteria() { switch ($this->getScope()) { case ScopeInterface::SCOPE_ENVIRONMENT: return [['$and' => [['ccId' => $this->getEnvironmentCostCenterId()]]]]; case ScopeInterface::SCOPE_ACCOUNT: $cc = new CostCentreEntity(); $accs = new AccountCostCenterEntity(); return [AbstractEntity::STMT_FROM => "{$cc->table()} LEFT JOIN {$accs->table()} AS `accs` ON {$accs->columnCcId('accs')} = {$cc->columnCcId()}", AbstractEntity::STMT_WHERE => "{$accs->columnAccountId('accs')} = " . $accs->qstr('accountId', $this->getUser()->accountId)]; case ScopeInterface::SCOPE_SCALR: throw new ApiNotImplementedErrorException(); } }
public function getContent($params = array()) { $this->request->restrictAccess(Acl::RESOURCE_OWN_FARMS, Acl::PERM_FARMS_CREATE); $projects = []; if ($this->getContainer()->analytics->enabled && $this->getEnvironment()->getPlatformConfigValue(Scalr_Environment::SETTING_CC_ID)) { $costCenter = $this->getContainer()->analytics->ccs->get($this->getEnvironment()->getPlatformConfigValue(Scalr_Environment::SETTING_CC_ID)); $currentYear = (new \DateTime('now', new \DateTimeZone('UTC')))->format('Y'); $quarters = new Quarters(SettingEntity::getQuarters()); $currentQuarter = $quarters->getQuarterForDate(new \DateTime('now', new \DateTimeZone('UTC'))); if ($costCenter instanceof CostCentreEntity) { $projectsIterator = new SharedProjectsFilterIterator($costCenter->getProjects(), $costCenter->ccId, $this->user, $this->getEnvironment()); foreach ($projectsIterator as $item) { $quarterBudget = QuarterlyBudgetEntity::findOne([['year' => $currentYear], ['subjectType' => QuarterlyBudgetEntity::SUBJECT_TYPE_PROJECT], ['subjectId' => $item->projectId], ['quarter' => $currentQuarter]]); $projects[] = array('projectId' => $item->projectId, 'name' => $item->name, 'budgetRemain' => !is_null($quarterBudget) && $quarterBudget->budget > 0 ? max(0, round($quarterBudget->budget - $quarterBudget->cumulativespend)) : null); } //$costCentreName = $costCenter->name; $isLocked = $costCenter->getProperty(CostCentrePropertyEntity::NAME_LOCKED); $accountCcs = AccountCostCenterEntity::findOne([['accountId' => $this->environment->clientId], ['ccId' => $costCenter->ccId]]); if ($isLocked || !$accountCcs instanceof AccountCostCenterEntity) { $costCentreLocked = 1; } else { $costCentreLocked = 0; } } else { $costCentreName = ''; $costCentreLocked = 0; } } return ['costCenterLocked' => $costCentreLocked, 'projects' => $projects]; }
public function viewAction() { $ccs = false; $unassignedCcs = false; if ($this->getContainer()->analytics->enabled) { $ccs = []; foreach (AccountCostCenterEntity::findByAccountId($this->user->getAccountId()) as $accountCc) { /* @var $accountCs \Scalr\Stats\CostAnalytics\Entity\AccountCostCenterEntity */ $ccEntity = CostCentreEntity::findPk($accountCc->ccId); /* @var $ccEntity \Scalr\Stats\CostAnalytics\Entity\CostCentreEntity */ if ($ccEntity->archived) { continue; } $ccs[$accountCc->ccId] = get_object_vars($ccEntity); } $unassignedCcs = []; foreach ($this->user->getEnvironments() as $row) { $env = Scalr_Environment::init()->loadById($row['id']); $ccEntity = CostCentreEntity::findPk($env->getPlatformConfigValue(Scalr_Environment::SETTING_CC_ID)); /* @var $ccEntity \Scalr\Stats\CostAnalytics\Entity\CostCentreEntity */ if ($ccEntity && !isset($ccs[$ccEntity->ccId])) { $unassignedCcs[$row['id']] = ['ccId' => $ccEntity->ccId, 'name' => $ccEntity->name]; } } } $this->response->page('ui/account2/environments/view.js', array('ccs' => array_values($ccs), 'unassignedCcs' => $unassignedCcs), array('ui/account2/dataconfig.js'), array('ui/account2/environments/view.css'), array('account.environments', 'account.teams')); }
/** * Edit project action * * @param string $projectId * @throws Scalr_UI_Exception_NotFound */ public function editAction($projectId = null) { $scope = $this->request->getScope(); $this->request->restrictAccess(Acl::RESOURCE_ADMINISTRATION_ANALYTICS, Acl::PERM_ADMINISTRATION_ANALYTICS_MANAGE_PROJECTS); if (!empty($projectId)) { $project = $this->getContainer()->analytics->projects->get($projectId); if ($project->shared != ProjectEntity::SHARED_WITHIN_ACCOUNT || $project->accountId != $this->user->getAccountId()) { throw new Scalr_Exception_InsufficientPermissions(); } $cc = $project->getCostCenter(); $projectData = $this->getProjectData($project, true); //Check whether it can be removed try { $projectData['removable'] = $project->checkRemoval(); } catch (AnalyticsException $e) { $projectData['removable'] = false; $projectData['warning'] = $e->getMessage(); } } else { if ($scope == 'environment') { $cc = $this->getContainer()->analytics->ccs->get($this->getEnvironment()->getPlatformConfigValue(\Scalr_Environment::SETTING_CC_ID)); } $projectData = []; } $ccs = []; if ($scope == 'environment') { $accountCcs = AccountCostCenterEntity::findOne([['accountId' => $this->user->getAccountId()], ['ccId' => $cc->ccId]]); if ($accountCcs instanceof AccountCostCenterEntity) { $ccs[$cc->ccId] = ['ccId' => $cc->ccId, 'name' => $cc->name, 'billingCode' => $cc->getProperty(CostCentrePropertyEntity::NAME_BILLING_CODE)]; } } elseif ($scope == 'account') { foreach ($this->user->getEnvironments() as $row) { $env = \Scalr_Environment::init()->loadById($row['id']); $ccEntity = CostCentreEntity::findPk($env->getPlatformConfigValue(\Scalr_Environment::SETTING_CC_ID)); /* @var $ccEntity \Scalr\Stats\CostAnalytics\Entity\CostCentreEntity */ if ($ccEntity) { $accountCcs = AccountCostCenterEntity::findOne([['accountId' => $env->clientId], ['ccId' => $ccEntity->ccId]]); if ($accountCcs instanceof AccountCostCenterEntity) { $ccs[$ccEntity->ccId] = ['ccId' => $ccEntity->ccId, 'name' => $ccEntity->name, 'billingCode' => $ccEntity->getProperty(CostCentrePropertyEntity::NAME_BILLING_CODE)]; } } } } $this->response->page('ui/admin/analytics/projects/edit.js', array('project' => $projectData, 'ccs' => $ccs, 'scope' => 'account')); }
/** * Also Removes Cost Centers properties generated for test * * {@inheritdoc} * @see Scalr\Tests\Functional\Api\ApiTestCase::tearDownAfterClass() */ public static function tearDownAfterClass() { ksort(static::$testData, SORT_REGULAR); foreach (static::$testData as $priority => $data) { foreach ($data as $class => $ids) { if ($class === 'Scalr\\Stats\\CostAnalytics\\Entity\\CostCentreEntity') { $ids = array_unique($ids, SORT_REGULAR); foreach ($ids as $entry) { /* @var $cc CostCentreEntity */ $cc = $class::findPk(...$entry); if (!empty($cc)) { try { CostCentrePropertyEntity::deleteByCcId($cc->ccId); AccountCostCenterEntity::deleteByCcId($cc->ccId); $cc->delete(); } catch (\Exception $e) { \Scalr::logException($e); } } } unset(static::$testData[$priority][$class]); } } } parent::tearDownAfterClass(); }
/** * {@inheritdoc} * @see AccessPermissionsInterface::hasAccessPermissions() */ public function hasAccessPermissions($user, $environment = null, $modify = null) { if ($user->isFinAdmin() || $user->isScalrAdmin()) { return true; } else { if ($modify) { return false; } } if ($environment) { return $this->ccId == Scalr_Environment::init()->loadById($environment->id)->getPlatformConfigValue(Scalr_Environment::SETTING_CC_ID); } else { return (bool) AccountCostCenterEntity::findPk($user->accountId, $this->ccId); } }
/** * 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'); }
public function create($name, $clientId) { $this->id = 0; $this->name = $name; $this->clientId = $clientId; $this->status = self::STATUS_ACTIVE; $this->save(); if (\Scalr::getContainer()->analytics->enabled) { //Default Cost Center for the new Environment is the first Cost Center //from the list of the Account Cost Centers $accountCcEntity = AccountCostCenterEntity::findOne([['accountId' => $clientId]]); if ($accountCcEntity instanceof AccountCostCenterEntity) { //Associates environment with the Cost Center $this->setPlatformConfig([Scalr_Environment::SETTING_CC_ID => $accountCcEntity->ccId]); //Fire event \Scalr::getContainer()->analytics->events->fireAssignCostCenterEvent($this, $accountCcEntity->ccId); } } return $this; }
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)); }
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); } }
/** * Gets the list of the Cost Centers which correspond to Account * * @return \Scalr\Model\Collections\ArrayCollection Returns collection of the entities */ public function getCostCenters() { $ccs = new ArrayCollection(); foreach (AccountCostCenterEntity::findByAccountId($this->id) as $accountCc) { $cc = CostCentreEntity::findPk($accountCc->ccId); if (!$cc instanceof CostCentreEntity) { continue; } $ccs->append($cc); } return $ccs; }
/** * 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')); } } }
private function getFarmCostData($farmId) { $result = []; $costCenter = $this->getContainer()->analytics->ccs->get($this->getEnvironment()->getPlatformConfigValue(Scalr_Environment::SETTING_CC_ID)); $currentYear = (new \DateTime('now', new \DateTimeZone('UTC')))->format('Y'); $quarters = new Quarters(SettingEntity::getQuarters()); $currentQuarter = $quarters->getQuarterForDate(new \DateTime('now', new \DateTimeZone('UTC'))); $projects = []; if ($farmId) { $farm = DBFarm::LoadByID($farmId); $currentProjectId = $farm->GetSetting(Entity\FarmSetting::PROJECT_ID); $currentProject = ProjectEntity::findPk($currentProjectId); /* @var $currentProject ProjectEntity */ if (!empty($currentProject)) { $quarterBudget = QuarterlyBudgetEntity::findOne([['year' => $currentYear], ['subjectType' => QuarterlyBudgetEntity::SUBJECT_TYPE_PROJECT], ['subjectId' => $currentProject->projectId], ['quarter' => $currentQuarter]]); $projects[] = ['projectId' => $currentProject->projectId, 'name' => "{$currentProject->name} / {$currentProject->getCostCenter()->name}", 'budgetRemain' => !is_null($quarterBudget) && $quarterBudget->budget > 0 ? max(0, round($quarterBudget->budget - $quarterBudget->cumulativespend)) : null]; } $result['projectId'] = $farm->GetSetting(Entity\FarmSetting::PROJECT_ID); $result['farmCostMetering'] = $result['projectId'] ? $this->getContainer()->analytics->usage->getFarmCostMetering($this->user->getAccountId(), $farmId) : null; } if ($costCenter instanceof CostCentreEntity) { $projectsIterator = new SharedProjectsFilterIterator($costCenter->getProjects(), $costCenter->ccId, $this->user, $this->getEnvironment()); foreach ($projectsIterator as $item) { /* @var $item Scalr\Stats\CostAnalytics\Entity\ProjectEntity */ if (!empty($currentProjectId) && $item->projectId == $currentProjectId) { continue; } $quarterBudget = QuarterlyBudgetEntity::findOne([['year' => $currentYear], ['subjectType' => QuarterlyBudgetEntity::SUBJECT_TYPE_PROJECT], ['subjectId' => $item->projectId], ['quarter' => $currentQuarter]]); $projects[] = array('projectId' => $item->projectId, 'name' => "{$item->name} / {$costCenter->name}", 'budgetRemain' => !is_null($quarterBudget) && $quarterBudget->budget > 0 ? max(0, round($quarterBudget->budget - $quarterBudget->cumulativespend)) : null); } $costCentreName = $costCenter->name; $isLocked = $costCenter->getProperty(CostCentrePropertyEntity::NAME_LOCKED); $accountCcs = AccountCostCenterEntity::findOne([['accountId' => $this->environment->clientId], ['ccId' => $costCenter->ccId]]); if ($isLocked || !$accountCcs instanceof AccountCostCenterEntity) { $costCentreLocked = 1; } else { $costCentreLocked = 0; } } else { $costCentreName = ''; $costCentreLocked = 0; } $supportedClouds = $this->getContainer()->analytics->prices->getSupportedClouds(); $result['analytics'] = array('costCenterName' => $costCentreName, 'costCenterLocked' => $costCentreLocked, 'projects' => $projects, 'unsupportedClouds' => array_values(array_diff($this->environment->getEnabledPlatforms(), $supportedClouds))); return $result; }
/** * @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}"); } } }