function handleWork($farmId) { try { $dbFarm = DBFarm::LoadByID($farmId); $governance = new Scalr_Governance($dbFarm->EnvID); $settings = $governance->getValue(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE, 'notifications'); $curDate = new DateTime(); $td = new DateTime($dbFarm->GetSetting(DBFarm::SETTING_LEASE_TERMINATE_DATE)); if ($td > $curDate) { // only inform user $days = $td->diff($curDate)->days; $notifications = json_decode($dbFarm->GetSetting(DBFarm::SETTING_LEASE_NOTIFICATION_SEND), true); if (is_array($settings)) { foreach ($settings as $n) { if (!$notifications[$n['key']] && $n['period'] >= $days) { $mailer = Scalr::getContainer()->mailer; $tdHuman = Scalr_Util_DateTime::convertDateTime($td, $dbFarm->GetSetting(DBFarm::SETTING_TIMEZONE), 'M j, Y'); if ($n['to'] == 'owner') { $user = new Scalr_Account_User(); $user->loadById($dbFarm->createdByUserId); if (Scalr::config('scalr.auth_mode') == 'ldap') { $email = $user->getSetting(Scalr_Account_User::SETTING_LDAP_EMAIL); if (!$email) { $email = $user->getEmail(); } } else { $email = $user->getEmail(); } $mailer->addTo($email); } else { foreach (explode(',', $n['emails']) as $email) { $mailer->addTo(trim($email)); } } $mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/farm_lease_terminate.eml', array('{{terminate_date}}' => $tdHuman, '{{farm}}' => $dbFarm->Name, '{{envName}}' => $dbFarm->GetEnvironmentObject()->name, '{{envId}}' => $dbFarm->GetEnvironmentObject()->id)); $notifications[$n['key']] = 1; $dbFarm->SetSetting(DBFarm::SETTING_LEASE_NOTIFICATION_SEND, json_encode($notifications)); $this->logger->info("Notification was sent by key: " . $n['key'] . " about farm: " . $dbFarm->Name . " by lease manager"); } } } } else { // terminate farm $event = new FarmTerminatedEvent(0, 1, false, 1); Scalr::FireEvent($farmId, $event); $this->logger->info("Farm: " . $dbFarm->Name . " was terminated by lease manager"); } } catch (Exception $e) { var_dump($e->getMessage()); } }
/** * Modify sql query to limit access by only allowable farms * * @param string $query * @param array $args * @param string $prefix optional Prefix for table farms in sql query * @param string $perm optional * @return array */ public function prepareFarmSqlQuery($query, $args, $prefix = '', $perm = null) { $prefix = $prefix ? "{$prefix}." : ''; if (!$this->isAllowed(Acl::RESOURCE_FARMS, $perm)) { $q = []; if ($this->isAllowed(Acl::RESOURCE_TEAM_FARMS, $perm)) { $t = array_map(function ($t) { return $t['id']; }, $this->user->getTeams()); if (count($t)) { $q[] = "{$prefix}team_id IN(" . join(',', $t) . ")"; } } if ($this->isAllowed(Acl::RESOURCE_OWN_FARMS, $perm)) { $q[] = "{$prefix}created_by_id = ?"; $args[] = $this->user->getId(); } if (count($q)) { $query .= ' AND (' . join(' OR ', $q) . ')'; } else { $query .= ' AND false'; // no permissions } } return [$query, $args]; }
public function getAccountUsersList() { if ($this->user->canManageAcl()) { $result = $this->db->getAll('SELECT account_users.id FROM account_users WHERE account_id = ?', array($this->user->getAccountId())); foreach ($result as &$row) { $row = Scalr_Account_User::init()->loadById($row['id'])->getUserInfo(); } } else { $result = array(); $teams = $this->user->getTeams(); if (!empty($teams)) { $sql = ' SELECT u.id, u.fullname, u.email FROM account_users u INNER JOIN account_team_users tu ON u.id = tu.user_id WHERE account_id= ?'; $params[] = $this->user->getAccountId(); foreach ($teams as $team) { $r[] = 'tu.team_id = ?'; $params[] = $team['id']; } $sql .= ' AND (' . implode(' OR ', $r) . ')'; $result = $this->db->getAll($sql, $params); } } return $result; }
/** * Gets acl roles superposition for the request * * @return \Scalr\Acl\Role\AccountRoleSuperposition */ protected function getAclRoles() { if (!$this->aclRoles) { $this->aclRoles = $this->user->getAclRolesByEnvironment($this->Environment->id); } return $this->aclRoles; }
/** * @param $type * @param $headers * @param $server * @param $params * @param $files * @param $userId * @param $envId * @return Scalr_UI_Request * @throws Scalr_Exception_Core * @throws Exception */ public static function initializeInstance($type, $headers, $server, $params, $files, $userId, $envId) { if (self::$_instance) { self::$_instance = null; } $class = get_called_class(); $instance = new $class($type, $headers, $server, $params, $files); if ($userId) { try { $user = Scalr_Account_User::init(); $user->loadById($userId); } catch (Exception $e) { throw new Exception('User account is no longer available.'); } if ($user->status != Scalr_Account_User::STATUS_ACTIVE) { throw new Exception('User account has been deactivated. Please contact your account owner.'); } if ($user->getType() != Scalr_Account_User::TYPE_SCALR_ADMIN) { $environment = $user->getDefaultEnvironment($envId); $user->getPermissions()->setEnvironmentId($environment->id); } if ($user->getAccountId()) { if ($user->getAccount()->status == Scalr_Account::STATUS_INACIVE) { if ($user->getType() == Scalr_Account_User::TYPE_TEAM_USER) { throw new Exception('Scalr account has been deactivated. Please contact scalr team.'); } } else { if ($user->getAccount()->status == Scalr_Account::STATUS_SUSPENDED) { if ($user->getType() == Scalr_Account_User::TYPE_TEAM_USER) { throw new Exception('Account was suspended. Please contact your account owner to solve this situation.'); } } } } $ipWhitelist = $user->getVar(Scalr_Account_User::VAR_SECURITY_IP_WHITELIST); if ($ipWhitelist) { $ipWhitelist = unserialize($ipWhitelist); if (!Scalr_Util_Network::isIpInSubnets($instance->getRemoteAddr(), $ipWhitelist)) { throw new Exception('The IP address isn\'t authorized'); } } // check header's variables $headerUserId = !is_null($instance->getHeaderVar('UserId')) ? intval($instance->getHeaderVar('UserId')) : null; $headerEnvId = !is_null($instance->getHeaderVar('EnvId')) ? intval($instance->getHeaderVar('EnvId')) : null; if (!empty($headerUserId) && $headerUserId != $user->getId()) { throw new Scalr_Exception_Core('Session expired. Please refresh page.', 1); } if (!empty($headerEnvId) && !empty($environment) && $headerEnvId != $environment->id) { throw new Scalr_Exception_Core('Session expired. Please refresh page.', 1); } $instance->user = $user; $instance->environment = isset($environment) ? $environment : null; } $container = \Scalr::getContainer(); $container->request = $instance; $container->environment = isset($instance->environment) ? $instance->environment : null; self::$_instance = $instance; return $instance; }
/** * {@inheritdoc} * @see \Scalr\LogCollector\AuditLoggerRetrieveConfigurationInterface::getAuditLoggerConfig() */ public function getAuditLoggerConfig() { $config = new AuditLoggerConfiguration(AuditLogger::REQUEST_TYPE_API); $config->user = $this->user; $config->accountId = $this->user ? $this->user->getAccountId() : null; $config->envId = isset($this->Environment) ? $this->Environment->id : null; $config->remoteAddr = $this->getContainer()->request->getRemoteAddr(); return $config; }
protected function LogRequest($trans_id, $action, $ipaddr, $request, $response) { if ($request['debug'] == 1 || $request['Debug'] == 1 || $request['Action'] == 'DNSZoneRecordAdd') { try { $this->DB->Execute("INSERT INTO api_log SET\r\n\t\t\t\t\t\ttransaction_id\t= ?,\r\n\t\t\t\t\t\tdtadded\t\t\t= ?,\r\n\t\t\t\t\t\taction\t\t\t= ?,\r\n\t\t\t\t\t\tipaddress\t\t= ?,\r\n\t\t\t\t\t\trequest\t\t\t= ?,\r\n\t\t\t\t\t\tresponse\t\t= ?,\r\n\t\t\t\t\t\tclientid\t\t= ?,\r\n\t\t\t\t\t\tenv_id\t\t\t= ?\r\n\t\t\t\t\t", array($trans_id, time(), $action, $ipaddr, http_build_query($request), $response, $this->user->getAccountId(), $this->Environment->id)); } catch (Exception $e) { } } }
public function xRemoveAction() { $user = Scalr_Account_User::init(); $user->loadById($this->getParam('userId')); if ($user->getEmail() == 'admin') { throw new Scalr_Exception_InsufficientPermissions(); } $user->delete(); $this->response->success('User successfully removed'); }
/** * {@inheritdoc} * @see \Scalr\LogCollector\AuditLoggerRetrieveConfigurationInterface::getAuditLoggerConfig() */ public function getAuditLoggerConfig() { $config = new AuditLoggerConfiguration(AuditLogger::REQUEST_TYPE_UI); $config->user = $this->user; $config->accountId = $this->user ? $this->user->getAccountId() : null; $config->envId = isset($this->environment) ? $this->environment->id : null; $config->ruid = Scalr_Session::getInstance()->getRealUserId(); $config->remoteAddr = $this->getRemoteAddr(); return $config; }
/** * Gets an test User instance * * @return \Scalr_Account_user Returns user instance */ protected function getUser() { if (!isset($this->user)) { if (empty($this->_testUserId)) { $this->_testUserId = \Scalr::config('scalr.phpunit.userid'); } $this->user = \Scalr_Account_User::init(); $this->user->loadById($this->_testUserId); } return $this->user; }
protected function getUserInfoByAccountId($accountId) { if (!isset($this->accountsCache[$accountId])) { if ($accountId) { try { $acc = new \Scalr_Account(); $acc->loadById($accountId); $this->accountsCache[$accountId] = array('id' => $acc->getOwner()->id, 'email' => $acc->getOwner()->getEmail()); } catch (\Exception $e) { $this->console->error($e->getMessage()); return array('id' => 0, 'email' => ''); } } else { $user = new \Scalr_Account_User(); $user->loadByEmail('admin', 0); $this->accountsCache[$accountId] = array('id' => $user->id, 'email' => $user->getEmail()); } } return $this->accountsCache[$accountId]; }
public function callActionMethod($method) { if ($this->request->getRequestType() == Scalr_UI_Request::REQUEST_TYPE_API) { $apiMethodCheck = false; if (method_exists($this, 'getApiDefinitions')) { $api = $this::getApiDefinitions(); $m = str_replace('Action', '', $method); if (in_array($m, $api)) { $apiMethodCheck = true; } } if (!$apiMethodCheck) { throw new Scalr_UI_Exception_NotFound(); } } if ($this->user) { if ($this->user->getType() == Scalr_Account_User::TYPE_TEAM_USER) { if (!$this->user->isTeamUserInEnvironment($this->getEnvironmentId(), Scalr_Account_Team::PERMISSIONS_OWNER) && !$this->user->isTeamUserInEnvironment($this->getEnvironmentId(), Scalr_Account_Team::PERMISSIONS_FULL)) { if (method_exists($this, 'getPermissionDefinitions')) { // rules defined for this controller $cls = get_class($this); $clsShort = str_replace('Scalr_UI_Controller_', '', $cls); $methodShort = str_replace('Action', '', $method); $clsPermissions = $cls::getPermissionDefinitions(); $permissions = $this->user->getGroupPermissions($this->getEnvironmentId()); if (array_key_exists($clsShort, $permissions)) { // rules for user and such controller $perm = $permissions[$clsShort]; if (!in_array('FULL', $perm, true)) { // user doesn't has full privilegies if (array_key_exists($methodShort, $clsPermissions)) { // standalone rule for this method if (!in_array($clsPermissions[$methodShort], $perm)) { throw new Scalr_Exception_InsufficientPermissions(); } } else { // VIEW rule if (!in_array('VIEW', $perm)) { throw new Scalr_Exception_InsufficientPermissions(); } } } } else { throw new Scalr_Exception_InsufficientPermissions(); } } } } } $this->{$method}(); }
/** * Restricts access to controller's actions * * @return boolean Returns true if user has access. */ public function hasAccess() { if ($this->user) { // check admin, non-admin if (!$this->user->isAdmin()) { // check controller in permissions return true; } else { return false; } } else { return false; } }
public function xRequestResultAction() { $this->request->defineParams(array('requests' => array('type' => 'json'), 'decision')); if (!in_array($this->getParam('decision'), array(FarmLease::STATUS_APPROVE, FarmLease::STATUS_DECLINE))) { throw new Scalr_Exception_Core('Wrong status'); } foreach ($this->getParam('requests') as $id) { $req = $this->db->GetRow('SELECT * FROM farm_lease_requests WHERE id = ? LIMIT 1', array($id)); if ($req) { $dbFarm = DBFarm::LoadByID($req['farm_id']); $this->user->getPermissions()->validate($dbFarm); $this->db->Execute('UPDATE farm_lease_requests SET status = ?, answer_comment = ?, answer_user_id = ? WHERE id = ?', array($this->getParam('decision'), $this->getParam('comment'), $this->user->getId(), $id)); try { $mailer = Scalr::getContainer()->mailer; $user = new Scalr_Account_User(); $user->loadById($dbFarm->createdByUserId); if ($this->getContainer()->config('scalr.auth_mode') == 'ldap') { if ($user->getSetting(Scalr_Account_User::SETTING_LDAP_EMAIL)) { $mailer->addTo($user->getSetting(Scalr_Account_User::SETTING_LDAP_EMAIL)); } else { $mailer->addTo($user->getEmail()); } } else { $mailer->addTo($user->getEmail()); } } catch (Exception $e) { $mailer = null; } if ($this->getParam('decision') == FarmLease::STATUS_APPROVE) { if ($req['request_days'] > 0) { $dt = $dbFarm->GetSetting(DBFarm::SETTING_LEASE_TERMINATE_DATE); $dt = new DateTime($dt); $dt->add(new DateInterval('P' . $req['request_days'] . 'D')); $dbFarm->SetSetting(DBFarm::SETTING_LEASE_TERMINATE_DATE, $dt->format('Y-m-d H:i:s')); $dbFarm->SetSetting(DBFarm::SETTING_LEASE_NOTIFICATION_SEND, null); if ($mailer) { $mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/farm_lease_non_standard_approve.eml', array('{{farm_name}}' => $dbFarm->Name, '{{user_name}}' => $this->user->getEmail(), '{{comment}}' => $this->getParam('comment'), '{{date}}' => $dt->format('M j, Y'), '{{envName}}' => $dbFarm->GetEnvironmentObject()->name, '{{envId}}' => $dbFarm->GetEnvironmentObject()->id)); } } else { $dbFarm->SetSetting(DBFarm::SETTING_LEASE_STATUS, ''); $dbFarm->SetSetting(DBFarm::SETTING_LEASE_TERMINATE_DATE, ''); $dbFarm->SetSetting(DBFarm::SETTING_LEASE_NOTIFICATION_SEND, ''); if ($mailer) { $mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/farm_lease_non_standard_forever.eml', array('{{farm_name}}' => $dbFarm->Name, '{{user_name}}' => $this->user->getEmail(), '{{comment}}' => $this->getParam('comment'), '{{envName}}' => $dbFarm->GetEnvironmentObject()->name, '{{envId}}' => $dbFarm->GetEnvironmentObject()->id)); } } } else { $dt = new DateTime($dbFarm->GetSetting(DBFarm::SETTING_LEASE_TERMINATE_DATE)); SettingEntity::increase(SettingEntity::LEASE_DECLINED_REQUEST); if ($mailer) { $mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/farm_lease_non_standard_decline.eml', array('{{farm_name}}' => $dbFarm->Name, '{{user_name}}' => $this->user->getEmail(), '{{date}}' => $dt->format('M j, Y'), '{{comment}}' => $this->getParam('comment'), '{{envName}}' => $dbFarm->GetEnvironmentObject()->name, '{{envId}}' => $dbFarm->GetEnvironmentObject()->id)); } } } } $this->response->success(); }
/** * Performs upgrade literally for the stage ONE. * * Implementation of this method performs update steps needs to be taken * to accomplish upgrade successfully. * * If there are any error during an execution of this scenario it must * throw an exception. * * @param int $stage optional The stage number * @throws \Exception */ protected function run1($stage) { $dashboards = $this->db->Execute('SELECT user_id, env_id FROM account_user_dashboard'); foreach ($dashboards as $keys) { try { $user = new \Scalr_Account_User(); $user->loadById($keys['user_id']); $dash = $user->getDashboard($keys['env_id']); if (!(is_array($dash) && isset($dash['configuration']) && is_array($dash['configuration']) && isset($dash['flags']) && is_array($dash['flags']))) { // old configuration, remove it $this->db->Execute('DELETE FROM account_user_dashboard WHERE user_id = ? AND env_id = ?', array($keys['user_id'], $keys['env_id'])); continue; } foreach ($dash['configuration'] as &$column) { foreach ($column as &$widget) { if ($widget['name'] == 'dashboard.monitoring') { $metrics = array('CPUSNMP' => 'cpu', 'LASNMP' => 'la', 'NETSNMP' => 'net', 'ServersNum' => 'snum', 'MEMSNMP' => 'mem'); $params = array('farmId' => $widget['params']['farmid'], 'period' => $widget['params']['graph_type'], 'metrics' => $metrics[$widget['params']['watchername']], 'title' => $widget['params']['title'], 'hash' => $this->db->GetOne('SELECT hash FROM farms WHERE id = ?', array($widget['params']['farmid']))); if (stristr($widget['params']['role'], "INSTANCE_")) { $ar = explode('_', $widget['params']['role']); $params['farmRoleId'] = $ar[1]; $params['index'] = $ar[2]; } else { if ($widget['params']['role'] != 'FARM' && $widget['params']['role'] != 'role') { $params['farmRoleId'] = $widget['params']['role']; } } $widget['params'] = $params; } } } $user->setDashboard($keys['env_id'], $dash); } catch (\Exception $e) { $this->console->warning($e->getMessage()); } } }
/** * @param DBFarm $dbFarm * @param string $permissionId * @return bool */ protected function isFarmAllowed(DBFarm $dbFarm = null, $permissionId = null) { $acl = \Scalr::getContainer()->acl; if (is_null($dbFarm)) { return $acl->isUserAllowedByEnvironment($this->user, $this->Environment, \Scalr\Acl\Acl::RESOURCE_FARMS, $permissionId) || $acl->isUserAllowedByEnvironment($this->user, $this->Environment, \Scalr\Acl\Acl::RESOURCE_TEAM_FARMS, $permissionId) || $acl->isUserAllowedByEnvironment($this->user, $this->Environment, \Scalr\Acl\Acl::RESOURCE_OWN_FARMS, $permissionId); } else { if (!$dbFarm instanceof DBFarm) { throw new \InvalidArgumentException(sprintf('First argument should be instance of DBFarm or null')); } $result = $acl->isUserAllowedByEnvironment($this->user, $this->Environment, \Scalr\Acl\Acl::RESOURCE_FARMS, $permissionId); if (!$result && $dbFarm->teamId && $this->user->isInTeam($dbFarm->teamId)) { $result = $acl->isUserAllowedByEnvironment($this->user, $this->Environment, \Scalr\Acl\Acl::RESOURCE_TEAM_FARMS, $permissionId); } if (!$result && $dbFarm->createdByUserId && $this->user->id == $dbFarm->createdByUserId) { $result = $acl->isUserAllowedByEnvironment($this->user, $this->Environment, \Scalr\Acl\Acl::RESOURCE_OWN_FARMS, $permissionId); } return $result; } }
protected function run1($stage) { $this->db->Execute(' ALTER TABLE `timeline_events` ADD `account_id` int(11) NULL AFTER `user_id`, ADD `env_id` int(11) NULL AFTER `account_id`, ADD INDEX `idx_account_id` (`account_id` ASC), ADD INDEX `idx_env_id` (`env_id` ASC) '); $res = $this->db->Execute('SELECT * FROM timeline_events'); while ($item = $res->FetchRow()) { $event = new TimelineEventEntity(); $event->load($item); try { $event->accountId = \Scalr_Account_User::init()->loadById($event->userId)->getAccountId(); } catch (Exception $e) { continue; } $event->save(); } }
/** * Raises onCloudAdd notification event * * @param string $platform A platform name. * @param \Scalr_Environment $environment An environment object which cloud is created in. * @param \Scalr_Account_User $user An user who has created platform. */ public function onCloudAdd($platform, $environment, $user) { $container = \Scalr::getContainer(); $analytics = $container->analytics; //Nothing to do in case analytics is disabled if (!$analytics->enabled) { return; } if (!$environment instanceof \Scalr_Environment) { $environment = \Scalr_Environment::init()->loadById($environment); } $pm = PlatformFactory::NewPlatform($platform); //Check if there are some price for this platform and endpoint url if (($endpointUrl = $pm->hasCloudPrices($environment)) === true) { return; } //Disabled or badly configured environment if ($endpointUrl === false && !in_array($platform, [\SERVER_PLATFORMS::EC2, \SERVER_PLATFORMS::GCE])) { return; } //Send a message to financial admin if there are not any price for this cloud $baseUrl = rtrim($container->config('scalr.endpoint.scheme') . "://" . $container->config('scalr.endpoint.host'), '/'); //Disable notifications for hosted Scalr if (!\Scalr::isAllowedAnalyticsOnHostedScalrAccount($environment->clientId)) { return; } $emails = $this->getFinancialAdminEmails(); //There isn't any financial admin if (empty($emails)) { return; } $emails = array_map(function ($email) { return '<' . trim($email, '<>') . '>'; }, $emails); try { $res = $container->mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/analytics_on_cloud_add.eml.php', ['isPublicCloud' => $platform == \SERVER_PLATFORMS::EC2, 'userEmail' => $user->getEmail(), 'cloudName' => \SERVER_PLATFORMS::GetName($platform), 'linkToPricing' => $baseUrl . '/#/analytics/pricing?platform=' . urlencode($platform) . '&url=' . urlencode($endpointUrl === false ? '' : $analytics->prices->normalizeUrl($endpointUrl))], join(',', $emails)); } catch (\Exception $e) { } }
/** * Checks if specified resource is allowed for superposition of the roles. * * If access permission is allowed at least in one role it is considered to be allowed. * Current exclude filter will be applied * * @param int $resourceId The ID of the resource. * @param string $permissionId optional The ID of the permission associated with resource. * @return bool|null Returns true if access is allowed. * If resource or permission isn't overridden it returns null. * @throws Exception\RoleObjectException */ public function isAllowed($resourceId, $permissionId = null) { $allowed = false; if ($this->user) { if ($this->user->isAccountOwner() || $this->user->isScalrAdmin()) { //Scalr Admin and Account Owner is allowed for everything, without any ACL defined for them. return true; } else { if ($resourceId === Acl::RESOURCE_ENVADMINISTRATION_ENV_CLOUDS && $permissionId === null && $this->user->canManageAcl()) { //Account Admin should be able to manage all relatings between environments and teams return true; } } } $iterator = $this->getIterator(); while ($iterator->valid() && !$allowed) { //If access permission is allowed at least in one role it is considered to be allowed. $allowed = $allowed || (bool) $iterator->current()->isAllowed($resourceId, $permissionId); $iterator->next(); } return $allowed; }
public function FarmGetDetails($FarmID) { $response = parent::FarmGetDetails($FarmID); try { $DBFarm = DBFarm::LoadByID($FarmID); if ($DBFarm->EnvID != $this->Environment->id) { throw new Exception("N"); } } catch (Exception $e) { throw new Exception(sprintf("Farm #%s not found", $FarmID)); } $response->ID = $DBFarm->ID; $response->Name = $DBFarm->Name; $response->IsLocked = $DBFarm->GetSetting(DBFarm::SETTING_LOCK); if ($response->IsLocked == 1) { $response->LockComment = $DBFarm->GetSetting(DBFarm::SETTING_LOCK_COMMENT); try { $response->LockedBy = Scalr_Account_User::init()->loadById($DBFarm->GetSetting(DBFarm::SETTING_LOCK_BY))->fullname; } catch (Exception $e) { } } foreach ($response->FarmRoleSet->Item as &$item) { $dbFarmRole = DBFarmRole::LoadByID($item->ID); $item->IsScalingEnabled = $dbFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_ENABLED); $item->{"ScalingAlgorithmSet"} = new stdClass(); $item->{"ScalingAlgorithmSet"}->Item = array(); $metrics = $this->DB->GetAll("SELECT metric_id, name, dtlastpolled FROM `farm_role_scaling_metrics`\n INNER JOIN scaling_metrics ON scaling_metrics.id = farm_role_scaling_metrics.metric_id WHERE farm_roleid = ?", array($item->ID)); foreach ($metrics as $metric) { $itm = new stdClass(); $itm->MetricID = $metric['id']; $itm->MetricName = $metric['name']; $itm->DateLastPolled = $metric['dtlastpolled']; $item->{"ScalingAlgorithmSet"}->Item[] = $itm; } } return $response; }
public static function initializeInstance($type, $userId, $envId) { $instance = new Scalr_UI_Request($type); if ($userId) { try { $user = Scalr_Account_User::init(); $user->loadById($userId); } catch (Exception $e) { throw new Exception('User account is no longer available.'); } if ($user->status != Scalr_Account_User::STATUS_ACTIVE) { throw new Exception('User account has been deactivated. Please contact your account owner.'); } if ($user->getType() != Scalr_Account_User::TYPE_SCALR_ADMIN) { $environment = $user->getDefaultEnvironment($envId); $user->getPermissions()->setEnvironmentId($environment->id); } if ($user->getAccountId()) { if ($user->getAccount()->status == Scalr_Account::STATUS_INACIVE) { if ($user->getType() == Scalr_Account_User::TYPE_TEAM_USER) { throw new Exception('Scalr account has been deactivated. Please contact scalr team.'); } } else { if ($user->getAccount()->status == Scalr_Account::STATUS_SUSPENDED) { if ($user->getType() == Scalr_Account_User::TYPE_TEAM_USER) { throw new Exception('Account was suspended. Please contact your account owner to solve this situation.'); } } } } $instance->user = $user; $instance->environment = $environment; } self::$_instance = $instance; return $instance; }
/** * Checks whether the user is allowed to edit specified user * * @param \Scalr_Account_User $user The user to edit * @return boolean Returns true if the user is allowed to edit specified user */ public function canEditUser($user) { return !$this->isTeamUser() && $user->getAccountId() == $this->getAccountId() && ($this->getId() == $user->getId() || $this->isAccountOwner() || $this->isAccountSuperAdmin() && !$user->isAccountOwner() || $this->isAccountAdmin() && !$user->isAccountOwner() && !$user->isAccountSuperAdmin()); }
/** * Migrates an Image to another Cloud Location * * @param string $cloudLocation The cloud location * @param \Scalr_Account_User|\Scalr\Model\Entity\Account\User $user The user object * @return Image * @throws Exception * @throws NotEnabledPlatformException * @throws DomainException */ public function migrateEc2Location($cloudLocation, $user) { if (!$this->getEnvironment()->isPlatformEnabled(SERVER_PLATFORMS::EC2)) { throw new NotEnabledPlatformException("You can migrate image between regions only on EC2 cloud"); } if ($this->cloudLocation == $cloudLocation) { throw new DomainException('Destination region is the same as source one'); } $snap = $this->getEnvironment()->aws($this->cloudLocation)->ec2->image->describe($this->id); if ($snap->count() == 0) { throw new Exception("Image haven't been found on cloud."); } if ($snap->get(0)->toArray()['imageState'] != 'available') { throw new Exception('Image is not in "available" status on cloud and cannot be copied.'); } $this->checkImage(); // re-check properties $aws = $this->getEnvironment()->aws($cloudLocation); $newImageId = $aws->ec2->image->copy($this->cloudLocation, $this->id, $this->name, "Image was copied by Scalr from image: {$this->name}, cloudLocation: {$this->cloudLocation}, id: {$this->id}", null, $cloudLocation); $newImage = new Image(); $newImage->platform = $this->platform; $newImage->cloudLocation = $cloudLocation; $newImage->id = $newImageId; $newImage->name = $this->name; $newImage->architecture = $this->architecture; $newImage->size = $this->size; $newImage->accountId = $this->accountId; $newImage->envId = $this->envId; $newImage->osId = $this->osId; $newImage->source = Image::SOURCE_MANUAL; $newImage->type = $this->type; $newImage->agentVersion = $this->agentVersion; $newImage->createdById = $user->getId(); $newImage->createdByEmail = $user->getEmail(); $newImage->status = Image::STATUS_ACTIVE; $newImage->isScalarized = $this->isScalarized; $newImage->hasCloudInit = $this->hasCloudInit; $newImage->save(); $newImage->setSoftware($this->getSoftware()); return $newImage; }
public function xRemoveAction() { $user = Scalr_Account_User::init(); $user->loadById($this->getParam('userId')); if ($user->getAccountId() == $this->user->getAccountId()) { if ($this->user->canManageAcl() || $this->user->isTeamOwner()) { $user->delete(); $this->response->success('User has been successfully removed.'); return; } } throw new Scalr_Exception_InsufficientPermissions(); }
$envId = $env->id; $user = $account->createUser($email, $password, Scalr_Account_User::TYPE_ACCOUNT_OWNER); $user->fullname = $name; $user->save(); $clientSettings[CLIENT_SETTINGS::RSS_LOGIN] = $email; $clientSettings[CLIENT_SETTINGS::RSS_PASSWORD] = $crypto->sault(10); foreach ($clientSettings as $k => $v) { $account->setSetting($k, $v); } try { $db->Execute("INSERT INTO default_records SELECT null, '{$account->id}', type, ttl, priority, value, name FROM default_records WHERE clientid='0'"); } catch (Exception $e) { $err['db'] = $e->getMessage(); } } else { $user = Scalr_Account_User::init()->loadByEmail($email); if (!$user) { throw new Exception("User Not Found"); } $account = $user->getAccount(); $env = $user->getDefaultEnvironment(); $envId = $env->id; } try { $retval = array('success' => true, 'account' => array('id' => $account->id, 'userId' => $user->id, 'password' => $password, 'envId' => $env->id, 'api_access_key' => $user->getSetting(Scalr_Account_User::SETTING_API_ACCESS_KEY), 'api_secret_key' => $user->getSetting(Scalr_Account_User::SETTING_API_SECRET_KEY))); $updateEnv = false; if (!$_REQUEST['update']) { //CONFIGURE OPENSTACK: $pars[SERVER_PLATFORMS::ECS . "." . OpenstackPlatformModule::KEYSTONE_URL] = $_REQUEST['openstack_keystone_url']; $pars[SERVER_PLATFORMS::ECS . "." . OpenstackPlatformModule::USERNAME] = $_REQUEST['openstack_username']; $pars[SERVER_PLATFORMS::ECS . "." . OpenstackPlatformModule::PASSWORD] = $_REQUEST['openstack_password'];
public function callActionMethod($method) { if ($this->request->getRequestType() == Scalr_UI_Request::REQUEST_TYPE_API) { $apiMethodCheck = false; if (method_exists($this, 'getApiDefinitions')) { $api = $this::getApiDefinitions(); $m = str_replace('Action', '', $method); if (in_array($m, $api)) { $apiMethodCheck = true; } } if (!$apiMethodCheck) { throw new Scalr_UI_Exception_NotFound(); } } /* * Debug action section * Controller::Action => array of filter's params (accountId, userId) or true */ $debug = false; $debugMode = false; $key = get_class($this) . '::' . $method; if ($debug && array_key_exists($key, $debug)) { $value = $debug[$key]; if (is_array($value) && $this->user) { if (isset($value['accountId'])) { if (is_array($value['accountId']) && in_array($this->user->getAccountId(), $value['accountId'])) { $debugMode = true; } if (is_numeric($value['accountId']) && $value['accountId'] == $this->user->getAccountId()) { $debugMode = true; } } if (isset($value['userId'])) { if (is_array($value['userId']) && in_array($this->user->getId(), $value['userId'])) { $debugMode = true; } if (is_numeric($value['userId']) && $value['userId'] == $this->user->getId()) { $debugMode = true; } } } else { $debugMode = true; } } if ($debugMode) { $this->response->debugLog('Server', $_SERVER); $this->response->debugLog('Request', $_REQUEST); $this->response->debugLog('Session', Scalr_Session::getInstance()); } $this->{$method}(); if ($debugMode) { if ($this->response->jsResponseFlag) { $this->response->debugLog('JS Response', $this->response->jsResponse); } try { $message = ''; foreach ($this->response->serverDebugLog as $value) { $message .= $value['key'] . ":\n" . $value['value'] . "\n\n"; } $this->db->Execute('INSERT INTO ui_debug_log (ipaddress, url, report, env_id, account_id, user_id) VALUES(?, ?, ?, ?, ?, ?)', array($this->request->getClientIp(), $key, $message, $this->getEnvironment() ? $this->getEnvironmentId() : 0, $this->user ? $this->user->getAccountId() : 0, $this->user ? $this->user->getId() : 0)); } catch (Exception $e) { } } }
/** * Check if farm is locked * * @param $throwException * @return bool * @throws Exception */ public function isLocked($throwException = true) { if ($this->GetSetting(Entity\FarmSetting::LOCK)) { $message = $this->GetSetting(Entity\FarmSetting::LOCK_COMMENT); try { $userName = Scalr_Account_User::init()->loadById($this->getSetting(Entity\FarmSetting::LOCK_BY))->getEmail(); } catch (Exception $e) { $userName = $this->getSetting(Entity\FarmSetting::LOCK_BY); } if ($message) { $message = sprintf(' with comment: \'%s\'', $message); } if ($throwException) { throw new Exception(sprintf('Farm was locked by %s%s. Please unlock it first.', $userName, $message)); } else { return sprintf('Farm was locked by %s%s.', $userName, $message); } } return false; }
/** * Gets email address of the user who fires an event * * @return string */ public function getUserEmail() { return $this->user ? $this->user->getEmail() : '[scalr]'; }
/** * @param \Scalr_Account_User $user * @param int $envId * @throws \Scalr_Exception_InsufficientPermissions */ public function checkPermission(\Scalr_Account_User $user, $envId) { if ($this->accountId && $this->accountId != $user->getAccountId()) { throw new \Scalr_Exception_InsufficientPermissions(); } if ($this->envId && $this->envId != $envId) { throw new \Scalr_Exception_InsufficientPermissions(); } }
/** * Checks wheter access to ACL resource or unique permission is allowed. * * @param \Scalr_Account_User $user The user * @param \Scalr_Environment $environment The client's environment * @param int $resourceId The ID of the ACL resource or its symbolic name without "RESOURCE_" prefix. * @param string $permissionId optional The ID of the uniqure permission which is * related to specified resource. * @return bool Returns TRUE if access is allowed */ public function isUserAllowedByEnvironment(\Scalr_Account_User $user, $environment, $resourceId, $permissionId = null) { //Checks wheter environment and user are from the same account. if ($user->isScalrAdmin()) { return true; } else { if (!$environment instanceof \Scalr_Environment) { //If environment is not defined it will return false. return false; } else { if ($environment->clientId != $user->getAccountId()) { return false; } } } //Scalr-Admin and Account-Owner is allowed for everything if ($user->isAccountOwner()) { return true; } if (is_string($resourceId)) { $sName = 'Scalr\\Acl\\Acl::RESOURCE_' . strtoupper($resourceId); if (defined($sName)) { $resourceId = constant($sName); } else { throw new \InvalidArgumentException(sprintf('Cannot find ACL resource %s by specified symbolic name %s.', $sName, $resourceId)); } } return (bool) $user->getAclRolesByEnvironment($environment->id)->isAllowed($resourceId, $permissionId); }