getInstance() public static method

public static getInstance ( boolean $isAutomaticRequest = false ) : Scalr_Session
$isAutomaticRequest boolean
return Scalr_Session
Example #1
0
 /**
  * @param bool $enabled
  * @throws Scalr_UI_Exception_NotFound
  */
 public function xSaveDebugAction($enabled = false)
 {
     Scalr_Session::getInstance()->setDebugMode(['enabled' => $enabled]);
     if ($enabled) {
         $this->response->data(['js' => $this->response->getModuleName('ui-debug.js')]);
     }
     $this->response->success('Debug parameters have applied');
 }
Example #2
0
 /**
  * If session is not virtual, - sets UserSetting::NAME_UI_ANNOUNCEMENT_TIME
  *
  * @param int $tm  Unix timestamp
  */
 public function xSetTmAction($tm)
 {
     if (Scalr_Session::getInstance()->isVirtual()) {
         $data = ['tmUpdated' => false];
     } else {
         $this->getUser()->saveSetting(UserSetting::NAME_UI_ANNOUNCEMENT_TIME, $tm);
         $data = ['tmUpdated' => true];
     }
     $data['tm'] = $this->getUser()->getSetting(UserSetting::NAME_UI_ANNOUNCEMENT_TIME);
     $this->response->data($data);
 }
Example #3
0
 public function xSaveDebugAction()
 {
     Scalr_Session::getInstance()->setDebugMode(array('sql' => $this->getParam('sql')));
     $js = array();
     if ($this->getParam('sql')) {
         $js[] = $this->response->getModuleName('ui-debug.js');
     }
     if (count($js)) {
         $this->response->data(array('js' => $js));
     }
     $this->response->success('Debug parameters have applied');
 }
Example #4
0
 public function xRemoveAction()
 {
     if (!$this->user->isAccountOwner() && !$this->user->isAccountSuperAdmin()) {
         throw new Scalr_Exception_InsufficientPermissions();
     }
     $env = Scalr_Environment::init()->loadById($this->getParam('envId'));
     $this->user->getPermissions()->validate($env);
     $env->delete();
     if ($env->id == $this->getEnvironmentId()) {
         Scalr_Session::getInstance()->setEnvironmentId(null);
         // reset
     }
     $this->response->success("Environment successfully removed");
     $this->response->data(array('env' => array('id' => $env->id), 'flagReload' => $env->id == $this->getEnvironmentId() ? true : false));
 }
Example #5
0
 public function getContext()
 {
     $data = array();
     if ($this->user) {
         $data['user'] = array('userId' => $this->user->getId(), 'clientId' => $this->user->getAccountId(), 'userName' => $this->user->getEmail(), 'gravatarHash' => $this->user->getGravatarHash(), 'envId' => $this->getEnvironment() ? $this->getEnvironmentId() : 0, 'envName' => $this->getEnvironment() ? $this->getEnvironment()->name : '', 'envVars' => $this->getEnvironment() ? $this->getEnvironment()->getPlatformConfigValue(Scalr_Environment::SETTING_UI_VARS) : '', 'type' => $this->user->getType());
         if (!$this->user->isScalrAdmin()) {
             $data['farms'] = $this->db->getAll('SELECT id, name FROM farms WHERE env_id = ? ORDER BY name', array($this->getEnvironmentId()));
             if ($this->user->getAccountId() != 0) {
                 $data['flags'] = $this->user->getAccount()->getFeaturesList();
                 $data['user']['userIsTrial'] = $this->user->getAccount()->getSetting(Scalr_Account::SETTING_IS_TRIAL) == '1' ? true : false;
             } else {
                 $data['flags'] = array();
             }
             $data['flags']['billingExists'] = \Scalr::config('scalr.billing.enabled');
             $data['flags']['featureUsersPermissions'] = $this->user->getAccount()->isFeatureEnabled(Scalr_Limits::FEATURE_USERS_PERMISSIONS);
             $data['flags']['wikiUrl'] = \Scalr::config('scalr.ui.wiki_url');
             $data['flags']['supportUrl'] = \Scalr::config('scalr.ui.support_url');
             $data['acl'] = $this->request->getAclRoles()->getAllowedArray(true);
             if ($this->user->isAccountOwner()) {
                 if (!$this->user->getAccount()->getSetting(Scalr_Account::SETTING_DATE_ENV_CONFIGURED)) {
                     if (count($this->environment->getEnabledPlatforms()) == 0) {
                         $data['flags']['needEnvConfig'] = Scalr_Environment::init()->loadDefault($this->user->getAccountId())->id;
                     }
                 }
             }
             $data['environments'] = $this->user->getEnvironments();
             if ($this->getEnvironment() && $this->user->isTeamOwner()) {
                 $data['user']['isTeamOwner'] = true;
             }
         }
         $data['platforms'] = array();
         $allowedClouds = (array) \Scalr::config('scalr.allowed_clouds');
         foreach (SERVER_PLATFORMS::getList() as $platform => $platformName) {
             if (!in_array($platform, $allowedClouds) || $platform == SERVER_PLATFORMS::UCLOUD && !$this->request->getHeaderVar('Interface-Beta')) {
                 continue;
             }
             $data['platforms'][$platform] = array('enabled' => $this->user->isScalrAdmin() ? false : !!$this->environment->isPlatformEnabled($platform), 'name' => $platformName);
         }
     }
     $data['flags']['authMode'] = $this->getContainer()->config->get('scalr.auth_mode');
     $data['flags']['specialToken'] = Scalr_Session::getInstance()->getToken();
     return $data;
 }
Example #6
0
 public function xChangeEnvironmentAction()
 {
     $env = Scalr_Environment::init()->loadById($this->getParam('envId'));
     foreach ($this->user->getEnvironments() as $e) {
         if ($env->id == $e['id']) {
             Scalr_Session::getInstance()->setEnvironmentId($e['id']);
             $this->response->success();
             return;
         }
     }
     throw new Scalr_Exception_InsufficientPermissions();
 }
Example #7
0
$container->set('dsn.getter', function ($cont, array $arguments = null) {
    $my = $cont->config->get($arguments[0]);
    $dsn = sprintf("%s://%s:%s@%s/%s", isset($my['driver']) ? $my['driver'] : 'mysqli', $my['user'], rawurlencode($my['pass']), (isset($my['host']) ? $my['host'] : 'localhost') . (isset($my['port']) ? ':' . $my['port'] : ''), $my['name']);
    return $dsn;
});
$container->setShared('adodb', function ($cont) {
    return new \Scalr\Db\ConnectionPool($cont->{'dsn.getter'}('scalr.connections.mysql'));
});
$container->setShared('dnsdb', function ($cont) {
    return new \Scalr\Db\ConnectionPool($cont->{'dsn.getter'}('scalr.dns.mysql'));
});
$container->setShared('cadb', function ($cont) {
    return new \Scalr\Db\ConnectionPool($cont->{'dsn.getter'}('scalr.analytics.connections.analytics'));
});
$container->session = function ($cont) {
    return Scalr_Session::getInstance();
};
$container->user = function ($cont) {
    return $cont->initialized('request') && $cont->request->getUser() instanceof Scalr_Account_User ? $cont->request->getUser() : null;
};
$container->awsAccessKeyId = function ($cont) {
    return $cont->environment->getPlatformConfigValue(Ec2PlatformModule::ACCESS_KEY);
};
$container->awsSecretAccessKey = function ($cont) {
    return $cont->environment->getPlatformConfigValue(Ec2PlatformModule::SECRET_KEY);
};
$container->awsAccountNumber = function ($cont) {
    return $cont->environment->getPlatformConfigValue(Ec2PlatformModule::ACCOUNT_ID);
};
$container->awsCertificate = function ($cont) {
    return $cont->environment->getPlatformConfigValue(Ec2PlatformModule::CERTIFICATE);
Example #8
0
 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());
     }
     $reflection = new ReflectionMethod($this, $method);
     if ($reflection->getNumberOfParameters()) {
         $params = array();
         $comment = $reflection->getDocComment();
         $matches = array();
         $types = array();
         if (preg_match_all('/^\\s+\\*\\s+@param\\s+(.*)\\s+\\$([A-Za-z0-9_]+)*.*$/m', $comment, $matches)) {
             for ($i = 0; $i < count($matches[0]); $i++) {
                 $matches[1][$i] = strtolower(trim($matches[1][$i]));
                 if (in_array($matches[1][$i], array('bool', 'boolean', 'int', 'integer', 'float', 'string', 'array'))) {
                     $types[trim($matches[2][$i])] = $matches[1][$i];
                 }
             }
         }
         // TODO: else: make some warning to log, otherwise we don't know when type-casting is not working
         foreach ($reflection->getParameters() as $parameter) {
             $className = $parameter->getClass() ? $parameter->getClass()->name : NULL;
             $value = $this->request->getRequestParam($parameter->name);
             $hasValue = $this->request->hasParam($parameter->name);
             if ($className) {
                 if (is_subclass_of($className, 'Scalr\\UI\\Request\\ObjectInitializingInterface')) {
                     /* @var ObjectInitializingInterface $className */
                     $params[] = $className::initFromRequest($className == 'Scalr\\UI\\Request\\FileUploadData' ? $this->request->getFileName($parameter->name) : $value);
                 } else {
                     throw new Scalr\Exception\Http\BadRequestException(sprintf('%s is invalid class in argument', $className));
                 }
             } else {
                 $type = $types[$parameter->name] ? $types[$parameter->name] : 'string';
                 if ($hasValue) {
                     if (in_array($type, ['bool', 'boolean'])) {
                         if (is_numeric($value)) {
                             $value = !empty($value);
                         } else {
                             if (is_string($value)) {
                                 $value = $value !== '' && strtolower($value) !== 'false';
                             } else {
                                 $value = (bool) $value;
                             }
                         }
                     } else {
                         if ($type == 'array') {
                             // do not strip value
                             settype($value, $type);
                         } else {
                             $value = $this->request->stripValue($value);
                             settype($value, $type);
                         }
                     }
                 } else {
                     if ($parameter->isDefaultValueAvailable()) {
                         $value = $parameter->getDefaultValue();
                     } else {
                         throw new Exception(sprintf('Missing required argument: %s', $parameter->name));
                     }
                 }
                 $params[] = $value;
             }
         }
         call_user_func_array(array($this, $method), $params);
     } else {
         $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) {
         }
     }
 }
Example #9
0
 /**
  * @param int $userId
  * @param int $envId
  * @param JsonData $uiStorage
  * @param JsonData $updateDashboard
  */
 public function xPerpetuumMobileAction($userId, $envId, JsonData $uiStorage, JsonData $updateDashboard)
 {
     $result = array();
     if ($this->user) {
         if ($updateDashboard) {
             $result['updateDashboard'] = Scalr_UI_Controller::loadController('dashboard')->checkLifeCycle($updateDashboard);
         }
         if (!Scalr_Session::getInstance()->isVirtual() && $uiStorage) {
             $this->user->setSetting(Scalr_Account_User::SETTING_UI_STORAGE_TIME, $uiStorage['time']);
             $this->user->setVar(Scalr_Account_User::VAR_UI_STORAGE, $uiStorage['dump']);
         }
     }
     $equal = $this->user && $this->user->getId() == $userId && ($this->getEnvironment() ? $this->getEnvironmentId() : 0) == $envId;
     $result['equal'] = $equal;
     $result['isAuthenticated'] = $this->user ? true : false;
     $this->response->data($result);
 }
Example #10
0
 /**
  * @param int $envId
  * @throws Scalr_Exception_InsufficientPermissions
  */
 public function xChangeEnvironmentAction($envId)
 {
     if ($this->user->isAdmin()) {
         throw new Scalr_Exception_InsufficientPermissions();
     }
     $env = Scalr_Environment::init()->loadById($envId);
     foreach ($this->user->getEnvironments() as $e) {
         if ($env->id == $e['id']) {
             Scalr_Session::getInstance()->setEnvironmentId($e['id']);
             if (!Scalr_Session::getInstance()->isVirtual()) {
                 $this->user->setSetting(Scalr_Account_User::SETTING_UI_ENVIRONMENT, $e['id']);
             }
             $this->response->success();
             return;
         }
     }
     throw new Scalr_Exception_InsufficientPermissions();
 }
Example #11
0
 /**
  * @param   bool    $enabled
  * @throws  Scalr_Exception_InsufficientPermissions
  */
 public function xSaveDebugAction($enabled = false)
 {
     $session = Scalr_Session::getInstance();
     if ($session->isVirtual() || $this->user->isScalrAdmin()) {
         Scalr_Session::getInstance()->setDebugMode($enabled);
         if ($enabled) {
             $this->response->data(['js' => $this->response->getModuleName('ui-debug.js')]);
         }
         $this->response->success();
     } else {
         throw new Scalr_Exception_InsufficientPermissions();
     }
 }
Example #12
0
 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) {
         }
     }
 }
Example #13
0
 /**
  * @param RawData $password
  * @param RawData $cpassword
  * @param $securityIpWhitelist
  * @param RawData $currentPassword optional
  */
 public function xSecuritySaveAction(RawData $password, RawData $cpassword, $securityIpWhitelist, RawData $currentPassword = null)
 {
     $validator = new Validator();
     if ($password != '******') {
         $validator->addErrorIf(!$this->user->checkPassword($currentPassword), ['currentPassword'], 'Invalid password');
     }
     $validator->validate($password, 'password', Validator::NOEMPTY);
     $validator->validate($cpassword, 'cpassword', Validator::NOEMPTY);
     $validator->addErrorIf($password && $cpassword && $password != $cpassword, ['password', 'cpassword'], 'Two passwords are not equal');
     $subnets = array();
     $securityIpWhitelist = trim($securityIpWhitelist);
     if ($securityIpWhitelist) {
         $whitelist = explode(',', $securityIpWhitelist);
         foreach ($whitelist as $mask) {
             $sub = Scalr_Util_Network::convertMaskToSubnet($mask);
             if ($sub) {
                 $subnets[] = $sub;
             } else {
                 $validator->addError('securityIpWhitelist', sprintf('Not valid mask: %s', $mask));
             }
         }
     }
     if (count($subnets) && !Scalr_Util_Network::isIpInSubnets($this->request->getRemoteAddr(), $subnets)) {
         $validator->addError('securityIpWhitelist', 'New IP access whitelist doesn\'t correspond your current IP address');
     }
     if ($validator->isValid($this->response)) {
         $updateSession = false;
         if ($password != '******') {
             $this->user->updatePassword($password);
             $updateSession = true;
             // Send notification E-mail
             $this->getContainer()->mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/password_change_notification.eml', array('{{fullname}}' => $this->user->fullname ? $this->user->fullname : $this->user->getEmail()), $this->user->getEmail(), $this->user->fullname);
         }
         $this->user->setVar(Scalr_Account_User::VAR_SECURITY_IP_WHITELIST, count($subnets) ? serialize($subnets) : '');
         $this->user->save();
         if ($updateSession) {
             Scalr_Session::create($this->user->getId());
             $this->response->data(['specialToken' => Scalr_Session::getInstance()->getToken()]);
         }
         $this->response->success('Security settings successfully updated');
     }
 }
Example #14
0
File: di.php Project: mheydt/scalr
            return $cloudCredentials ?: false;
        });
    }
    if (empty($cloudCredentials = $cont->get($contCloudCredId))) {
        $cloudCredentials = new Entity\CloudCredentials();
        $cloudCredentials->accountId = empty($cont->environment) || $cont->environment->id != $envId ? \Scalr_Environment::init()->loadById($envId)->getAccountId() : $cont->environment;
        $cloudCredentials->envId = $envId;
        $cloudCredentials->cloud = $cloud;
    }
    return $cloudCredentials;
});
$container->setShared('saml.config', function ($cont) {
    $settings = $cont->config->get('scalr.connections.saml');
    // Adjust saml service provider settings based on the scalr base url
    $baseUrl = $cont->config('scalr.endpoint.scheme') . "://" . rtrim($cont->config('scalr.endpoint.host'), '/');
    $settings['sp']['entityId'] = $baseUrl . '/public/saml?metadata';
    $settings['sp']['assertionConsumerService']['url'] = $baseUrl . '/public/saml?acs';
    $settings['sp']['singleLogoutService']['url'] = $baseUrl . '/public/saml?sls';
    return $settings;
});
$container->set('saml', function ($cont) {
    return new OneLogin_Saml2_Auth($cont->{'saml.config'});
});
$container->setShared('auditlogger.metadata', function ($cont) {
    $uiReq = $cont->initialized('request');
    return (object) ['user' => $uiReq ? $cont->request->getUser() : null, 'envId' => $uiReq && $cont->request->getEnvironment() ? $cont->request->getEnvironment()->id : null, 'remoteAddr' => $uiReq ? $cont->request->getRemoteAddr() : null, 'ruid' => $uiReq && $cont->request instanceof Scalr_UI_Request ? Scalr_Session::getInstance()->getRealUserId() : null, 'requestType' => null, 'systemTask' => null];
});
$container->setShared('auditlogger', function ($cont) {
    $m = $cont->get('auditlogger.metadata');
    return new AuditLogger($m->user, $m->envId, $m->remoteAddr, $m->ruid, $m->requestType, $m->systemTask);
});
Example #15
0
             $registerImageType->architecture = $imageInfo->architecture;
             if ($imageInfo->kernelId) {
                 $registerImageType->kernelId = $imageInfo->kernelId;
             }
             if ($imageInfo->ramdiskId) {
                 $registerImageType->ramdiskId = $imageInfo->ramdiskId;
             }
             $registerImageType->rootDeviceName = $imageInfo->rootDeviceName;
             print "Registering new AMI...";
             $newImageId = $aws->ec2->image->register($registerImageType);
             print "<span style='color:green;'>OK</span>. New AMI id: {$res->imageId}<br>";
             print "Updating Scalr database AMI...";
             $roleId = $db->GetOne("SELECT role_id FROM role_images WHERE image_id = ? LIMIT 1", array($imageId));
             if ($roleId) {
                 $dbRole = DBRole::loadById($roleId);
                 if ($dbRole->clientId = Scalr_Session::getInstance()->getClientId()) {
                     $db->Execute("UPDATE role_images SET image_id=? WHERE image_id=?", array($newImageId, $imageId));
                 }
             }
             print "<span style='color:green;'>OK</span>. AMI successfully repaired.";
         } else {
             print "<span style='color:red;'>Cannot find recovered snapshot.</span><br>";
             exit;
         }
     } else {
         print "<span style='color:red;'>Snapshot is okay. No need to replace it.</span><br>";
         exit;
     }
 } else {
     print "<span style='color:red;'>ERROR: SnapshotID not found</span><br>";
     exit;
Example #16
0
 /**
  * {@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;
 }
Example #17
0
 public function xSaveAction()
 {
     $this->request->defineParams(array('teams' => array('type' => 'json'), 'action', 'password' => array('type' => 'string', 'rawValue' => true), 'currentPassword' => array('type' => 'string', 'rawValue' => true)));
     $user = Scalr_Account_User::init();
     $validator = new Scalr_Validator();
     if ($this->getParam('id')) {
         $user->loadById((int) $this->getParam('id'));
     } else {
         if ($this->getContainer()->config->get('scalr.auth_mode') == 'ldap') {
             throw new Exception("Adding new users is not supported with LDAP user management");
         }
     }
     if ($this->getContainer()->config->get('scalr.auth_mode') != 'ldap') {
         if (!$this->getParam('email')) {
             throw new Scalr_Exception_Core('Email cannot be null');
         }
         if ($validator->validateEmail($this->getParam('email'), null, true) !== true) {
             throw new Scalr_Exception_Core('Email should be correct');
         }
         if ($this->getParam('id')) {
             if (!$this->user->canEditUser($user)) {
                 throw new Scalr_Exception_InsufficientPermissions();
             }
             $user->updateEmail($this->getParam('email'));
         } else {
             $this->user->getAccount()->validateLimit(Scalr_Limits::ACCOUNT_USERS, 1);
             $user->create($this->getParam('email'), $this->user->getAccountId());
             $user->type = Scalr_Account_User::TYPE_TEAM_USER;
             $newUser = true;
         }
         $password = $this->getParam('password');
         if (!$newUser && $password) {
             $existingPasswordChanged = true;
         } else {
             if (!$password && ($this->request->hasParam('password') || $newUser)) {
                 $password = $this->getCrypto()->sault(10);
                 $sendResetLink = true;
             }
         }
         if (($existingPasswordChanged || !$newUser && $sendResetLink) && !$this->user->checkPassword($this->getParam('currentPassword'))) {
             $this->response->data(['errors' => ['currentPassword' => 'Invalid password']]);
             $this->response->failure();
             return;
         }
         if ($password) {
             $user->updatePassword($password);
         }
     }
     if ($user->getId() != $this->user->getId() && in_array($this->getParam('status'), array(Scalr_Account_User::STATUS_ACTIVE, Scalr_Account_User::STATUS_INACTIVE))) {
         $user->status = $this->getParam('status');
     }
     if (!$user->isAccountOwner()) {
         if ($this->getParam('isAccountAdmin')) {
             if ($this->user->isAccountOwner() && $this->getParam('isAccountSuperAdmin')) {
                 $user->type = Scalr_Account_User::TYPE_ACCOUNT_SUPER_ADMIN;
             } else {
                 if ($user->type != Scalr_Account_User::TYPE_ACCOUNT_SUPER_ADMIN) {
                     $user->type = Scalr_Account_User::TYPE_ACCOUNT_ADMIN;
                 }
             }
         } else {
             $user->type = Scalr_Account_User::TYPE_TEAM_USER;
         }
     }
     $user->fullname = $this->getParam('fullname');
     $user->comments = $this->getParam('comments');
     $user->save();
     $user->setAclRoles($this->getParam('teams'));
     if ($this->getParam('enableApi')) {
         $keys = Scalr::GenerateAPIKeys();
         $user->setSetting(Scalr_Account_User::SETTING_API_ENABLED, true);
         $user->setSetting(Scalr_Account_User::SETTING_API_ACCESS_KEY, $keys['id']);
         $user->setSetting(Scalr_Account_User::SETTING_API_SECRET_KEY, $keys['key']);
     }
     $creatorName = $this->user->fullname;
     if (empty($creatorName)) {
         $creatorName = $this->user->isAccountOwner() ? 'Account owner' : ($this->user->isAccountAdmin() ? 'Account admin' : 'Team user');
     }
     if ($newUser) {
         try {
             $clientinfo = array('fullname' => $user->fullname, 'firstname' => $user->fullname, 'email' => $user->getEmail(), 'password' => $password);
             $url = Scalr::config('scalr.endpoint.scheme') . "://" . Scalr::config('scalr.endpoint.host');
             $res = $this->getContainer()->mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/referral.eml.php', array("creatorName" => $creatorName, "clientFirstname" => $clientinfo['firstname'], "email" => $clientinfo['email'], "password" => $clientinfo['password'], "siteUrl" => $url, "wikiUrl" => \Scalr::config('scalr.ui.wiki_url'), "supportUrl" => \Scalr::config('scalr.ui.support_url'), "isUrl" => preg_match('/^http(s?):\\/\\//i', \Scalr::config('scalr.ui.support_url'))), $user->getEmail());
         } catch (Exception $e) {
         }
     } elseif ($sendResetLink) {
         try {
             $hash = $this->getCrypto()->sault(10);
             $user->setSetting(Scalr_Account::SETTING_OWNER_PWD_RESET_HASH, $hash);
             $clientinfo = array('email' => $user->getEmail(), 'fullname' => $user->fullname);
             $res = $this->getContainer()->mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/user_account_confirm.eml', array("{{fullname}}" => $clientinfo['fullname'], "{{pwd_link}}" => "https://{$_SERVER['HTTP_HOST']}/#/guest/updatePassword/?hash={$hash}"), $clientinfo['email'], $clientinfo['fullname']);
         } catch (Exception $e) {
         }
     } else {
         if ($existingPasswordChanged) {
             // Send notification E-mail
             $this->getContainer()->mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/password_change_notification.eml', array('{{fullname}}' => $user->fullname ? $user->fullname : $user->getEmail()), $user->getEmail(), $user->fullname);
         }
     }
     $userTeams = array();
     $troles = $this->getContainer()->acl->getUserRoleIdsByTeam($user->id, array_map(create_function('$v', 'return $v["id"];'), $user->getTeams()), $user->getAccountId());
     foreach ($troles as $teamId => $roles) {
         $userTeams[$teamId] = array('roles' => $roles);
     }
     $data = ['user' => $user->getUserInfo(), 'teams' => $userTeams];
     if ($existingPasswordChanged && $user->getId() == $this->user->getId()) {
         Scalr_Session::create($this->user->getId());
         $data['specialToken'] = Scalr_Session::getInstance()->getToken();
     }
     $this->response->data($data);
     $this->response->success('User successfully saved');
 }
Example #18
0
//NOTE: Apache mod_rewrite sets REDIRECT_URL instead of REQUEST_URI environment variable, we need to get final overridden URI
$path = trim(str_replace("?{$_SERVER['QUERY_STRING']}", "", isset($_SERVER['REDIRECT_URL']) ? $_SERVER['REDIRECT_URL'] : $_SERVER['REQUEST_URI']), '/');
$logMysqlExcepton = function ($e) {
    \Scalr::logException($e);
    Scalr_UI_Response::getInstance()->data(array('errorDB' => true));
    Scalr_UI_Response::getInstance()->debugException($e);
    Scalr_UI_Response::getInstance()->failure($e instanceof \Scalr\Exception\MysqlConnectionException ? 'Database connection issue' : 'Database error');
    Scalr_UI_Response::getInstance()->sendResponse();
};
try {
    $startTime = microtime(true);
    require __DIR__ . '/src/prepend.inc.php';
    $prependTime = microtime(true);
    // public controller for link like /public/*; don't check CSRF
    $publicController = !strncmp('public', $path, strlen('public'));
    $session = Scalr_Session::getInstance();
    $time1 = microtime(true);
    try {
        $request = Scalr_UI_Request::initializeInstance(Scalr_UI_Request::REQUEST_TYPE_UI, getallheaders(), $_SERVER, $_REQUEST, $_FILES, $session->getUserId(), null);
    } catch (Exception $e) {
        if ($path == 'guest/logout') {
            // hack
            Scalr_Session::destroy();
            Scalr_UI_Response::getInstance()->setRedirect('/');
            Scalr_UI_Response::getInstance()->sendResponse();
            exit;
        }
        $message = $e->getMessage();
        if ($e->getCode() != 1) {
            $message = htmlspecialchars($message) . ' <a href="/guest/logout">Click here to login as another user</a>';
            Scalr_UI_Response::getInstance()->debugException($e);
Example #19
0
File: ui.php Project: scalr/scalr
$path = trim(str_replace("?{$_SERVER['QUERY_STRING']}", "", isset($_SERVER['REDIRECT_URL']) ? $_SERVER['REDIRECT_URL'] : $_SERVER['REQUEST_URI']), '/');
$logMysqlExcepton = function ($e) {
    \Scalr::logException($e);
    Scalr_UI_Response::getInstance()->data(array('errorDB' => true));
    Scalr_UI_Response::getInstance()->debugException($e);
    Scalr_UI_Response::getInstance()->failure($e instanceof \Scalr\Exception\MysqlConnectionException ? 'Database connection issue' : 'Database error');
    Scalr_UI_Response::getInstance()->sendResponse();
};
try {
    $startTime = microtime(true);
    require __DIR__ . '/src/prepend.inc.php';
    $prependTime = microtime(true);
    // public controller for link like /public/*; don't check CSRF
    $publicController = !strncmp('public', $path, strlen('public'));
    $headers = Scalr::getAllHeaders();
    $session = Scalr_Session::getInstance(isset($headers['Scalr-Autoload-Request']));
    $time1 = microtime(true);
    try {
        $request = Scalr_UI_Request::initializeInstance(Scalr_UI_Request::REQUEST_TYPE_UI, $headers, $_SERVER, $_REQUEST, $_FILES, $session->getUserId(), null);
    } catch (Exception $e) {
        if ($path == 'guest/logout') {
            // hack
            Scalr_Session::destroy();
            Scalr_UI_Response::getInstance()->setRedirect('/');
            Scalr_UI_Response::getInstance()->sendResponse();
            exit;
        }
        $message = $e->getMessage();
        if ($e->getCode() != 1) {
            $message = htmlspecialchars($message) . ' <a href="/guest/logout">Click here to login as another user</a>';
            Scalr_UI_Response::getInstance()->debugException($e);