Example #1
0
 /**
  * @param $platform
  * @param $cloudLocation
  * @param $cloudServerId
  * @param $roleName
  * @param bool $roleImage
  * @throws Exception
  */
 public function xInitiateImportAction($platform, $cloudLocation, $cloudServerId, $roleName, $roleImage = false)
 {
     $validator = new Scalr_Validator();
     if ($roleImage) {
         $roleName = Role::generateName('import');
     } else {
         if ($validator->validateNotEmpty($roleName) !== true) {
             throw new Exception('Role name cannot be empty');
         }
         if (strlen($roleName) < 3) {
             throw new Exception(_("Role name should be greater than 3 chars"));
         }
         if (!preg_match("/^[A-Za-z0-9-]+\$/si", $roleName)) {
             throw new Exception(_("Role name is incorrect"));
         }
         if ($this->db->GetOne("SELECT id FROM roles WHERE name=? AND (env_id = '0' OR env_id = ?) LIMIT 1", array($roleName, $this->getEnvironmentId()))) {
             throw new Exception('Selected role name is already used. Please select another one.');
         }
     }
     $cryptoKey = Scalr::GenerateRandomKey(40);
     $creInfo = new ServerCreateInfo($platform, null, 0, 0);
     $creInfo->clientId = $this->user->getAccountId();
     $creInfo->envId = $this->getEnvironmentId();
     $creInfo->farmId = 0;
     $creInfo->SetProperties(array(SERVER_PROPERTIES::SZR_IMPORTING_ROLE_NAME => $roleName, SERVER_PROPERTIES::SZR_KEY => $cryptoKey, SERVER_PROPERTIES::SZR_KEY_TYPE => SZR_KEY_TYPE::PERMANENT, SERVER_PROPERTIES::SZR_VESION => "0.14.0", SERVER_PROPERTIES::SZR_IMPORTING_VERSION => 2, SERVER_PROPERTIES::SZR_IMPORTING_STEP => 1, SERVER_PROPERTIES::LAUNCHED_BY_ID => $this->user->id, SERVER_PROPERTIES::LAUNCHED_BY_EMAIL => $this->user->getEmail()));
     $platformObj = PlatformFactory::NewPlatform($platform);
     if ($platform == SERVER_PLATFORMS::EC2) {
         $client = $this->environment->aws($cloudLocation)->ec2;
         $r = $client->instance->describe($cloudServerId);
         $instance = $r->get(0)->instancesSet->get(0);
         $creInfo->SetProperties(array(EC2_SERVER_PROPERTIES::REGION => $cloudLocation, EC2_SERVER_PROPERTIES::INSTANCE_ID => $cloudServerId, EC2_SERVER_PROPERTIES::AMIID => $instance->imageId, EC2_SERVER_PROPERTIES::AVAIL_ZONE => $instance->placement->availabilityZone));
     } else {
         if ($platform == SERVER_PLATFORMS::EUCALYPTUS) {
             $client = $this->environment->eucalyptus($cloudLocation)->ec2;
             $r = $client->instance->describe($cloudServerId);
             $instance = $r->get(0)->instancesSet->get(0);
             $creInfo->SetProperties(array(EUCA_SERVER_PROPERTIES::REGION => $cloudLocation, EUCA_SERVER_PROPERTIES::INSTANCE_ID => $cloudServerId, EUCA_SERVER_PROPERTIES::EMIID => $instance->imageId, EUCA_SERVER_PROPERTIES::AVAIL_ZONE => $instance->placement->availabilityZone));
         } else {
             if ($platform == SERVER_PLATFORMS::GCE) {
                 $gce = $platformObj->getClient($this->environment, $cloudLocation);
                 $result = $gce->instances->get($this->environment->getPlatformConfigValue(GoogleCEPlatformModule::PROJECT_ID), $cloudLocation, $cloudServerId);
                 $creInfo->SetProperties(array(GCE_SERVER_PROPERTIES::SERVER_NAME => $cloudServerId, GCE_SERVER_PROPERTIES::CLOUD_LOCATION => $cloudLocation));
             } else {
                 if (PlatformFactory::isOpenstack($platform)) {
                     $creInfo->SetProperties(array(OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION => $cloudLocation, OPENSTACK_SERVER_PROPERTIES::SERVER_ID => $cloudServerId));
                 } else {
                     if (PlatformFactory::isCloudstack($platform)) {
                         $creInfo->SetProperties(array(CLOUDSTACK_SERVER_PROPERTIES::CLOUD_LOCATION => $cloudLocation, CLOUDSTACK_SERVER_PROPERTIES::SERVER_ID => $cloudServerId));
                     }
                 }
             }
         }
     }
     $dbServer = DBServer::Create($creInfo, true);
     $ips = $platformObj->GetServerIPAddresses($dbServer);
     $dbServer->localIp = $ips['localIp'];
     $dbServer->remoteIp = $ips['remoteIp'];
     $dbServer->Save();
     $this->response->data(array('command' => $this->getSzrCmd($dbServer), 'serverId' => $dbServer->serverId));
 }
Example #2
0
 /**
  * @param int $id
  * @param $email
  * @param $type
  * @param RawData $password
  * @param $status
  * @param $fullname
  * @param $comments
  * @param RawData $currentPassword optional
  * @throws Scalr_Exception_Core
  * @throws Scalr_Exception_InsufficientPermissions
  */
 public function xSaveAction($id = 0, $email, $type, RawData $password, $status, $fullname, $comments, RawData $currentPassword = null)
 {
     $user = Scalr_Account_User::init();
     $validator = new Scalr_Validator();
     $isNewUser = empty($id);
     $isExistingPasswordChanged = false;
     if (!$isNewUser && $password != '******' && !$this->user->checkPassword($currentPassword)) {
         $this->response->data(['errors' => ['currentPassword' => 'Invalid password']]);
         $this->response->failure();
         return;
     }
     if (!$email) {
         throw new Scalr_Exception_Core('Email cannot be empty');
     }
     if ($type == Scalr_Account_User::TYPE_FIN_ADMIN && $validator->validateEmail($email, null, true) !== true) {
         throw new Scalr_Exception_Core('Email is not valid');
     }
     if (!in_array($type, [Scalr_Account_User::TYPE_SCALR_ADMIN, Scalr_Account_User::TYPE_FIN_ADMIN])) {
         throw new Scalr_Exception_Core('Type is not valid');
     }
     if (!in_array($status, [Scalr_Account_User::STATUS_ACTIVE, Scalr_Account_User::STATUS_INACTIVE])) {
         throw new Scalr_Exception_Core('Status is not valid');
     }
     if (!$isNewUser) {
         $user->loadById($id);
         if ($user->getEmail() == 'admin' && $user->getId() != $this->user->getId()) {
             throw new Scalr_Exception_InsufficientPermissions();
         }
         if ($user->getEmail() != 'admin') {
             $user->updateEmail($email);
         }
     } else {
         $user->create($email, $this->user->getAccountId());
         $user->type = $type;
     }
     if ($password != '******') {
         $user->updatePassword($password);
         if (!$isNewUser) {
             $isExistingPasswordChanged = true;
         }
     }
     if ($user->getEmail() != 'admin') {
         $user->status = $status;
         $user->type = $type;
         $user->fullname = $fullname;
         $user->comments = $comments;
     }
     $user->save();
     // Send notification E-mail
     if ($isExistingPasswordChanged) {
         $this->getContainer()->mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/password_change_admin_notification.eml', array('{{fullname}}' => $user->fullname ? $user->fullname : $user->getEmail(), '{{administratorFullName}}' => $this->user->fullname ? $this->user->fullname : $this->user->getEmail()), $user->getEmail(), $user->fullname);
     } else {
         if ($isNewUser) {
             $this->getContainer()->mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/user_new_admin_notification.eml', array('{{fullname}}' => $user->fullname ? $user->fullname : $user->getEmail(), '{{subject}}' => $user->type == Scalr_Account_User::TYPE_FIN_ADMIN ? 'Financial Admin for Scalr Cost Analytics' : 'Admin for Scalr', '{{user_type}}' => $user->type == Scalr_Account_User::TYPE_FIN_ADMIN ? 'a Financial Admin' : 'an Admin', '{{link}}' => Scalr::config('scalr.endpoint.scheme') . "://" . Scalr::config('scalr.endpoint.host')), $user->getEmail(), $user->fullname);
         }
     }
     $this->response->success('User successfully saved');
 }
Example #3
0
 public function ApacheVhostCreate($DomainName, $FarmID, $FarmRoleID, $DocumentRootDir, $EnableSSL, $SSLPrivateKey = null, $SSLCertificate = null)
 {
     $this->restrictAccess(Acl::RESOURCE_SERVICES_APACHE);
     $validator = new Scalr_Validator();
     if ($validator->validateDomain($DomainName) !== true) {
         $err[] = _("Domain name is incorrect");
     }
     $DBFarm = DBFarm::LoadByID($FarmID);
     if ($DBFarm->EnvID != $this->Environment->id) {
         throw new Exception(sprintf("Farm #%s not found", $FarmID));
     }
     $this->user->getPermissions()->validate($DBFarm);
     $DBFarmRole = DBFarmRole::LoadByID($FarmRoleID);
     if ($DBFarm->ID != $DBFarmRole->FarmID) {
         throw new Exception(sprintf("FarmRole #%s not found on Farm #%s", $FarmRoleID, $FarmID));
     }
     if (!$DocumentRootDir) {
         throw new Exception(_("DocumentRootDir required"));
     }
     $options = serialize(array("document_root" => trim($DocumentRootDir), "logs_dir" => "/var/log", "server_admin" => $this->user->getEmail()));
     $httpConfigTemplateSSL = @file_get_contents(dirname(__FILE__) . "/../../templates/services/apache/ssl.vhost.tpl");
     $httpConfigTemplate = @file_get_contents(dirname(__FILE__) . "/../../templates/services/apache/nonssl.vhost.tpl");
     $vHost = Scalr_Service_Apache_Vhost::init();
     $vHost->envId = (int) $this->Environment->id;
     $vHost->clientId = $this->user->getAccountId();
     $vHost->domainName = $DomainName;
     $vHost->isSslEnabled = $EnableSSL ? true : false;
     $vHost->farmId = $FarmID;
     $vHost->farmRoleId = $FarmRoleID;
     $vHost->httpdConf = $httpConfigTemplate;
     $vHost->templateOptions = $options;
     //SSL stuff
     if ($vHost->isSslEnabled) {
         $cert = new Scalr_Service_Ssl_Certificate();
         $cert->envId = $DBFarm->EnvID;
         $cert->name = $DomainName;
         $cert->privateKey = base64_decode($SSLPrivateKey);
         $cert->certificate = base64_decode($SSLCertificate);
         $cert->save();
         $vHost->sslCertId = $cert->id;
         $vHost->httpdConfSsl = $httpConfigTemplateSSL;
     } else {
         $vHost->sslCertId = 0;
     }
     $vHost->save();
     $servers = $DBFarm->GetServersByFilter(array('status' => array(SERVER_STATUS::INIT, SERVER_STATUS::RUNNING)));
     foreach ($servers as $DBServer) {
         if ($DBServer->GetFarmRoleObject()->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::NGINX) || $DBServer->GetFarmRoleObject()->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::APACHE)) {
             $DBServer->SendMessage(new Scalr_Messaging_Msg_VhostReconfigure());
         }
     }
     $response = $this->CreateInitialResponse();
     $response->Result = 1;
     return $response;
 }
Example #4
0
 /**
  * @param int $id
  * @param $email
  * @param $type
  * @param $password
  * @param $status
  * @param $fullname
  * @param $comments
  * @throws Scalr_Exception_Core
  * @throws Scalr_Exception_InsufficientPermissions
  */
 public function xSaveAction($id = 0, $email, $type, $password, $status, $fullname, $comments)
 {
     $user = Scalr_Account_User::init();
     $validator = new Scalr_Validator();
     if (!$email) {
         throw new Scalr_Exception_Core('Email cannot be empty');
     }
     if ($type == Scalr_Account_User::TYPE_FIN_ADMIN && $validator->validateEmail($email, null, true) !== true) {
         throw new Scalr_Exception_Core('Email is not valid');
     }
     if (!in_array($type, [Scalr_Account_User::TYPE_SCALR_ADMIN, Scalr_Account_User::TYPE_FIN_ADMIN])) {
         throw new Scalr_Exception_Core('Type is not valid');
     }
     if (!in_array($status, [Scalr_Account_User::STATUS_ACTIVE, Scalr_Account_User::STATUS_INACTIVE])) {
         throw new Scalr_Exception_Core('Status is not valid');
     }
     if ($id) {
         $user->loadById($id);
         if ($user->getEmail() == 'admin' && $user->getId() != $this->user->getId()) {
             throw new Scalr_Exception_InsufficientPermissions();
         }
         if ($user->getEmail() != 'admin') {
             $user->updateEmail($email);
         }
     } else {
         $user->create($email, $this->user->getAccountId());
         $user->type = $type;
     }
     if ($password != '******') {
         $user->updatePassword($password);
     }
     if ($user->getEmail() != 'admin') {
         $user->status = $status;
         $user->type = $type;
         $user->fullname = $fullname;
         $user->comments = $comments;
     }
     $user->save();
     $this->response->success('User successfully saved');
 }
Example #5
0
 public function xSaveAction()
 {
     $user = Scalr_Account_User::init();
     $validator = new Scalr_Validator();
     if (!$this->getParam('email')) {
         throw new Scalr_Exception_Core('Email must be provided.');
     }
     if ($validator->validateEmail($this->getParam('email'), null, true) !== true) {
         throw new Scalr_Exception_Core('Email should be correct');
     }
     if ($this->user->canManageAcl() || $this->user->isTeamOwner()) {
         $newUser = false;
         if ($this->getParam('id')) {
             $user->loadById((int) $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;
         }
         $sendResetLink = false;
         if (!$this->getParam('password')) {
             $password = CryptoTool::sault(10);
             $sendResetLink = true;
         } else {
             $password = $this->getParam('password');
         }
         if ($password != '******') {
             $user->updatePassword($password);
         }
         if (in_array($this->getParam('status'), array(Scalr_Account_User::STATUS_ACTIVE, Scalr_Account_User::STATUS_INACTIVE)) && !$user->isAccountOwner()) {
             $user->status = $this->getParam('status');
         }
         $user->fullname = $this->getParam('fullname');
         $user->comments = $this->getParam('comments');
         $user->save();
         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']);
         }
         if ($newUser) {
             if ($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);
                     // Send reset password E-mail
                     $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) {
                 }
             }
         }
         $this->response->data(array('user' => array('id' => $user->getId(), 'email' => $user->getEmail(), 'fullname' => $user->fullname)));
         $this->response->success('User successfully saved');
     } else {
         throw new Scalr_Exception_InsufficientPermissions();
     }
 }
Example #6
0
<?php

require_once __DIR__ . "/../src/prepend.inc.php";
use Scalr\Service\OpenStack\OpenStack;
use Scalr\Service\OpenStack\OpenStackConfig;
use Scalr\Service\OpenStack\Services\Network\Type\CreateSubnet;
use Scalr\Service\OpenStack\Services\Network\Type\CreateRouter;
use Scalr\Modules\Platforms\Openstack\OpenstackPlatformModule;
use Scalr\Service\OpenStack\Services\Servers\Type\ServersExtension;
$validator = new Scalr_Validator();
$crypto = new Scalr_Util_CryptoTool(MCRYPT_TRIPLEDES, MCRYPT_MODE_CFB, 24, 8);
if (!$_REQUEST['update'] && !$_REQUEST['delete']) {
    if (!$_REQUEST['name']) {
        $err['name'] = _("Account name required");
    }
    $name = $_REQUEST['name'];
    $password = $crypto->sault(10);
}
if ($validator->validateEmail($_REQUEST['email'], null, true) !== true) {
    $err['email'] = _("Invalid E-mail address");
}
$email = $_REQUEST['email'];
function getOpenStackOption($name)
{
    return SERVER_PLATFORMS::ECS . "." . constant('Scalr\\Modules\\Platforms\\Openstack\\OpenstackPlatformModule::' . $name);
}
if (count($err) == 0) {
    if ($_REQUEST['delete']) {
        $user = Scalr_Account_User::init()->loadByEmail($email);
        if (!$user) {
            throw new Exception("User Not Found");
Example #7
0
 /**
  *
  * @return Scalr_UI_Request
  */
 public function validate()
 {
     $this->paramErrors = array();
     $this->paramsIsValid = true;
     $validator = new Scalr_Validator();
     foreach ($this->definitions as $key => $value) {
         if (isset($value['validator'])) {
             $result = $validator->validate($this->getParam($key), $value['validator']);
             if ($result !== true) {
                 $this->addValidationErrors($key, $result);
             }
         }
     }
     if (count($this->paramErrors)) {
         $this->paramsIsValid = false;
     }
     return $this;
 }
Example #8
0
 public function xSaveAction()
 {
     $this->request->restrictAccess(Acl::RESOURCE_SERVICES_APACHE, Acl::PERM_SERVICES_APACHE_MANAGE);
     $validator = new Scalr_Validator();
     try {
         if ($validator->validateDomain($this->getParam('domainName')) !== true) {
             $err['domainName'] = _("Domain name is incorrect");
         }
         if (!$this->getParam('farmId')) {
             $err['farmId'] = _("Farm required");
         } else {
             $dbFarm = DBFarm::LoadByID($this->getParam('farmId'));
             $this->user->getPermissions()->validate($dbFarm);
         }
         if (!$this->getParam('farmRoleId')) {
             $err['farmRoleId'] = _("Role required");
         } else {
             $dbFarmRole = DBFarmRole::LoadByID($this->getParam('farmRoleId'));
             if ($dbFarmRole->FarmID != $dbFarm->ID) {
                 $err['farmRoleId'] = _("Role not found");
             }
         }
         if ($validator->validateEmail($this->getParam('serverAdmin'), null, true) !== true) {
             $err['serverAdmin'] = _("Server admin's email is incorrect or empty ");
         }
         if (!$this->getParam('documentRoot')) {
             $err['documentRoot'] = _("Document root required");
         }
         if (!$this->getParam('logsDir')) {
             $err['logsDir'] = _("Logs directory required");
         }
         if ($this->db->GetOne("SELECT id FROM apache_vhosts WHERE env_id=? AND `name` = ? AND id != ? AND farm_id = ? AND farm_roleid = ? LIMIT 1", array($this->getEnvironmentId(), $this->getParam('domainName'), $this->getParam('vhostId'), $this->getParam('farmId'), $this->getParam('farmRoleId')))) {
             $err['domainName'] = "'{$this->getParam('domainName')}' virtualhost already exists";
         }
     } catch (Exception $e) {
         $err[] = $e->getMessage();
     }
     if (count($err) == 0) {
         $vHost = Scalr_Service_Apache_Vhost::init();
         if ($this->getParam('vhostId')) {
             $vHost->loadById($this->getParam('vhostId'));
             $this->user->getPermissions()->validate($vHost);
         } else {
             $vHost->envId = $this->getEnvironmentId();
             $vHost->clientId = $this->user->getAccountId();
         }
         $vHost->domainName = $this->getParam('domainName');
         $isSslEnabled = $this->getParam('isSslEnabled') == 'on' ? true : false;
         if ($vHost->farmRoleId && $vHost->farmRoleId != $this->getParam('farmRoleId')) {
             $oldFarmRoleId = $vHost->farmRoleId;
         }
         $vHost->farmId = $this->getParam('farmId');
         $vHost->farmRoleId = $this->getParam('farmRoleId');
         $vHost->isSslEnabled = $isSslEnabled ? 1 : 0;
         $vHost->httpdConf = $this->getParam("nonSslTemplate", true);
         $vHost->templateOptions = serialize(array("document_root" => trim($this->getParam('documentRoot')), "logs_dir" => trim($this->getParam('logsDir')), "server_admin" => trim($this->getParam('serverAdmin')), "server_alias" => trim($this->getParam('serverAlias'))));
         //SSL stuff
         if ($isSslEnabled) {
             $cert = Entity\SslCertificate::findPk($this->getParam('sslCertId'));
             $this->user->getPermissions()->validate($cert);
             $vHost->sslCertId = $cert->id;
             $vHost->httpdConfSsl = $this->getParam("sslTemplate", true);
         } else {
             $vHost->sslCertId = 0;
             $vHost->httpdConfSsl = "";
         }
         $vHost->save();
         $servers = $dbFarm->GetServersByFilter(array('status' => array(SERVER_STATUS::INIT, SERVER_STATUS::RUNNING)));
         foreach ($servers as $dBServer) {
             if ($dBServer->GetFarmRoleObject()->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::NGINX) || $dBServer->GetFarmRoleObject()->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::APACHE) && $dBServer->farmRoleId == $vHost->farmRoleId) {
                 $dBServer->SendMessage(new Scalr_Messaging_Msg_VhostReconfigure());
             }
         }
         if ($oldFarmRoleId) {
             $oldFarmRole = DBFarmRole::LoadByID($oldFarmRoleId);
             $servers = $oldFarmRole->GetServersByFilter(array('status' => array(SERVER_STATUS::INIT, SERVER_STATUS::RUNNING)));
             foreach ($servers as $dBServer) {
                 $dBServer->SendMessage(new Scalr_Messaging_Msg_VhostReconfigure());
             }
         }
         $this->response->success(_('Virtualhost successfully saved'));
     } else {
         $this->response->failure();
         $this->response->data(array('errors' => $err));
     }
 }
 public function DNSZoneCreate($DomainName, $FarmID = null, $FarmRoleID = null)
 {
     $this->restrictAccess(Acl::RESOURCE_DNS_ZONES);
     if (!Scalr::config('scalr.dns.global.enabled')) {
         throw new Exception("DNS functionality is not enabled. Please contact your Scalr administrator.");
     }
     $DomainName = trim($DomainName);
     $Validator = new Scalr_Validator();
     if ($Validator->validateDomain($DomainName) !== true) {
         throw new Exception(_("Invalid domain name"));
     }
     $domain_chunks = explode(".", $DomainName);
     $chk_dmn = '';
     while (count($domain_chunks) > 0) {
         $chk_dmn = trim(array_pop($domain_chunks) . ".{$chk_dmn}", ".");
         if ($this->DB->GetOne("SELECT id FROM dns_zones WHERE zone_name=? AND client_id != ? LIMIT 1", array($chk_dmn, $this->user->getAccountId()))) {
             if ($chk_dmn == $DomainName) {
                 throw new Exception(sprintf(_("%s already exists on scalr nameservers"), $DomainName));
             } else {
                 throw new Exception(sprintf(_("You cannot use %s domain name because top level domain %s does not belong to you"), $DomainName, $chk_dmn));
             }
         }
     }
     if ($FarmID) {
         $DBFarm = DBFarm::LoadByID($FarmID);
         if ($DBFarm->EnvID != $this->Environment->id) {
             throw new Exception(sprintf("Farm #%s not found", $FarmID));
         }
         $this->user->getPermissions()->validate($DBFarm);
     }
     if ($FarmRoleID) {
         $DBFarmRole = DBFarmRole::LoadByID($FarmRoleID);
         if ($DBFarm->ID != $DBFarmRole->FarmID) {
             throw new Exception(sprintf("FarmRole #%s not found on Farm #%s", $FarmRoleID, $FarmID));
         }
     }
     $response = $this->CreateInitialResponse();
     $DBDNSZone = DBDNSZone::create($DomainName, 14400, 86400, str_replace('@', '.', $this->user->getEmail()));
     $DBDNSZone->farmRoleId = (int) $FarmRoleID;
     $DBDNSZone->farmId = (int) $FarmID;
     $DBDNSZone->clientId = $this->user->getAccountId();
     $DBDNSZone->envId = $this->Environment->id;
     $def_records = $this->DB->GetAll("SELECT * FROM default_records WHERE clientid=?", array($this->user->getAccountId()));
     foreach ($def_records as $record) {
         $record["name"] = str_replace(array("%hostname%", "%zonename%"), array("{$DomainName}.", "{$DomainName}."), $record["name"]);
         $record["value"] = str_replace(array("%hostname%", "%zonename%"), array("{$DomainName}.", "{$DomainName}."), $record["value"]);
         $records[] = $record;
     }
     $nameservers = Scalr::config('scalr.dns.global.nameservers');
     foreach ($nameservers as $ns) {
         $records[] = array("id" => "c" . rand(10000, 999999), "type" => "NS", "ttl" => 14400, "value" => "{$ns}.", "name" => "{$DomainName}.", "issystem" => 0);
     }
     $DBDNSZone->setRecords($records);
     $DBDNSZone->save(true);
     $response->Result = 1;
     return $response;
 }
Example #10
0
 /**
  * @param string $name
  * @param string $org
  * @param $email
  * @param $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, $password = '', $agreeTerms = '', $newBilling = '', $country = '', $phone = '', $lastname = '', $firstname = '', $v = '', $numServers = '')
 {
     if (!\Scalr::config('scalr.billing.enabled')) {
         exit;
     }
     $Validator = new Scalr_Validator();
     if ($v == 2) {
         if (!$firstname) {
             $err['firstname'] = _("First name required");
         }
         if (!$lastname) {
             $err['lastname'] = _("Last name required");
         }
         //if (!$org)
         //    $err['org'] = _("Organization required");
         $name = $firstname . " " . $lastname;
     } else {
         if (!$name) {
             $err['name'] = _("Account name required");
         }
     }
     if (!$password) {
         $password = $this->getCrypto()->sault(10);
     }
     if ($Validator->validateEmail($email, null, true) !== true) {
         $err['email'] = _("Invalid E-mail address");
     }
     if (strlen($password) < 6) {
         $err['password'] = _("Password should be longer than 6 chars");
     }
     // Check email
     $DBEmailCheck = $this->db->GetOne("SELECT COUNT(*) FROM account_users WHERE email=?", array($email));
     if ($DBEmailCheck > 0) {
         $err['email'] = _("E-mail already exists in database");
     }
     if (!$agreeTerms) {
         $err['agreeTerms'] = _("You need to agree with terms and conditions");
     }
     if (count($err) == 0) {
         $account = Scalr_Account::init();
         $account->name = $org ? $org : $name;
         $account->status = Scalr_Account::STATUS_ACTIVE;
         $account->save();
         $account->createEnvironment("Environment 1");
         $account->initializeAcl();
         $user = $account->createUser($email, $password, Scalr_Account_User::TYPE_ACCOUNT_OWNER);
         $user->fullname = $name;
         $user->save();
         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;
         }
         $clientSettings[CLIENT_SETTINGS::RSS_LOGIN] = $email;
         $clientSettings[CLIENT_SETTINGS::RSS_PASSWORD] = $this->getCrypto()->sault(10);
         foreach ($clientSettings as $k => $v) {
             $account->setSetting($k, $v);
         }
         try {
             $this->db->Execute("INSERT INTO default_records SELECT null, '{$account->id}', rtype, ttl, rpriority, rvalue, rkey FROM default_records WHERE clientid='0'");
         } 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();
         $this->response->setRedirect("{$url}/thanks.html");
     } else {
         $errors = array_values($err);
         $error = $errors[0];
         $this->response->setRedirect("{$url}/order/?error={$error}");
     }
 }
Example #11
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 #12
0
 public function xSaveAction()
 {
     $this->request->defineParams(array('domainId' => array('type' => 'int'), 'domainName', 'domainType', 'domainFarm' => array('type' => 'int'), 'domainFarmRole' => array('type' => 'int'), 'soaRefresh' => array('type' => 'int'), 'soaExpire' => array('type' => 'int'), 'soaRetry' => array('type' => 'int'), 'records' => array('type' => 'json')));
     $errors = array();
     // validate farmId, farmRoleId
     $farmId = 0;
     $farmRoleId = 0;
     if ($this->getParam('domainFarm')) {
         $DBFarm = DBFarm::LoadByID($this->getParam('domainFarm'));
         if (!$this->user->getPermissions()->check($DBFarm)) {
             $errors['domainFarm'] = _('Farm not found');
         } else {
             $farmId = $DBFarm->ID;
             if ($this->getParam('domainFarmRole')) {
                 $DBFarmRole = DBFarmRole::LoadByID($this->getParam('domainFarmRole'));
                 if ($DBFarmRole->FarmID != $DBFarm->ID) {
                     $errors['domainFarmRole'] = _('Role not found');
                 } else {
                     $farmRoleId = $DBFarmRole->ID;
                 }
             }
         }
     }
     $domainName = trim($this->getParam('domainName'), ".");
     // validate domain name
     if (!$this->getParam('domainId')) {
         if ($this->getParam('domainType') == 'own') {
             $validator = new Scalr_Validator();
             if ($validator->validateDomain($domainName) !== true) {
                 $errors['domainName'] = _("Invalid domain name");
             } else {
                 $domainChunks = explode(".", $domainName);
                 $chkDmn = '';
                 while (count($domainChunks) > 0) {
                     $chkDmn = trim(array_pop($domainChunks) . ".{$chkDmn}", ".");
                     if (in_array($chkDmn, array('scalr.net', 'scalr.com', 'scalr-dns.net', 'scalr-dns.com'))) {
                         $errors['domainName'] = sprintf(_("You cannot use %s domain name because top level domain %s does not belong to you"), $domainName, $chkDmn);
                     } else {
                         $chkDomainId = $this->db->GetOne("SELECT id FROM dns_zones WHERE zone_name=? AND client_id != ? LIMIT 1", array($chkDmn, $this->user->getAccountId()));
                         if ($chkDomainId) {
                             if ($chkDmn == $domainName) {
                                 $errors['domainName'] = sprintf(_("%s already exists on scalr nameservers"), $domainName);
                             } else {
                                 $chkDnsZone = DBDNSZone::loadById($chkDomainId);
                                 $access = false;
                                 foreach (explode(";", $chkDnsZone->allowedAccounts) as $email) {
                                     if ($email == $this->user->getEmail()) {
                                         $access = true;
                                     }
                                 }
                                 if (!$access) {
                                     $errors['domainName'] = sprintf(_("You cannot use %s domain name because top level domain %s does not belong to you"), $domainName, $chkDmn);
                                 }
                             }
                         }
                     }
                 }
             }
         } else {
             $domainName = Scalr::GenerateUID() . '.' . \Scalr::config('scalr.dns.global.default_domain_name');
         }
         // check in DB
         $rez = $this->db->GetOne("SELECT id FROM dns_zones WHERE zone_name = ? LIMIT 1", array($domainName));
         if ($rez) {
             $errors['domainName'] = 'Domain name already exist in database';
         }
     }
     $records = array();
     foreach ($this->getParam('records') as $key => $r) {
         if (($r['name'] || $r['value']) && $r['issystem'] == 0) {
             $r['name'] = str_replace(array("%hostname%", "%zonename%"), array("{$domainName}", "{$domainName}"), $r['name']);
             $r['value'] = str_replace(array("%hostname%", "%zonename%"), array("{$domainName}", "{$domainName}"), $r['value']);
             $records[$key] = $r;
         }
     }
     $recordsValidation = Scalr_Net_Dns_Zone::validateRecords($records);
     if ($recordsValidation !== true) {
         $errors = array_merge($errors, $recordsValidation);
     }
     $soaOwner = $this->getParam('soaOwner');
     if (!$soaOwner) {
         $soaOwner = $this->user->getEmail();
     }
     if (count($errors) == 0) {
         if ($this->getParam('domainId')) {
             $DBDNSZone = DBDNSZone::loadById($this->getParam('domainId'));
             $this->user->getPermissions()->validate($DBDNSZone);
             $DBDNSZone->soaRefresh = $this->getParam('soaRefresh');
             $DBDNSZone->soaExpire = $this->getParam('soaExpire');
             $DBDNSZone->soaRetry = $this->getParam('soaRetry');
             $DBDNSZone->soaOwner = str_replace('@', '.', $soaOwner);
             $this->response->success("DNS zone successfully updated. It could take up to 5 minutes to update it on NS servers.");
         } else {
             $DBDNSZone = DBDNSZone::create($domainName, $this->getParam('soaRefresh'), $this->getParam('soaExpire'), str_replace('@', '.', $soaOwner), $this->getParam('soaRetry'));
             $DBDNSZone->clientId = $this->user->getAccountId();
             $DBDNSZone->envId = $this->getEnvironmentId();
             $this->response->success("DNS zone successfully added to database. Please allow up to 5 minutes for it to be configured on your NS servers.");
         }
         if ($DBDNSZone->farmRoleId != $farmRoleId || $DBDNSZone->farmId != $farmId) {
             $DBDNSZone->farmId = 0;
             $DBDNSZone->updateSystemRecords();
         }
         $DBDNSZone->farmRoleId = $farmRoleId;
         $DBDNSZone->farmId = $farmId;
         $DBDNSZone->privateRootRecords = $this->getParam('privateRootRecords') == 'on' ? 1 : 0;
         $DBDNSZone->setRecords($records);
         $DBDNSZone->save(true);
     } else {
         $this->response->failure();
         $this->response->data(array('errors' => $errors));
     }
 }
Example #13
0
 /**
  * Return true if $domain is valid domain name
  * @var string $domain Domain name
  * @return bool
  */
 function isDomain($domain)
 {
     return $domain == "*" || $this->validator->validateDomain($domain) === true;
 }
Example #14
0
 public function xSaveAction()
 {
     $this->request->defineParams(array('teams' => array('type' => 'json'), 'action'));
     $user = Scalr_Account_User::init();
     $validator = new Scalr_Validator();
     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')) {
         $user->loadById((int) $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 ($password === '' || $newUser && !$password) {
         $password = $this->getCrypto()->sault(10);
         $sendResetLink = true;
     }
     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()) {
         $user->type = $this->getParam('isAccountAdmin') ? Scalr_Account_User::TYPE_ACCOUNT_ADMIN : 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);
             $res = $this->getContainer()->mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/welcome.eml.php', array("creatorName" => $creatorName, "clientFirstname" => $clientinfo['firstname'], "email" => $clientinfo['email'], "password" => $clientinfo['password'], "siteUrl" => "http://{$_SERVER['HTTP_HOST']}", "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) {
         }
     }
     $userTeams = array();
     $troles = $this->environment->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);
     }
     $this->response->data(array('user' => $user->getUserInfo(), 'teams' => $userTeams));
     $this->response->success('User successfully saved');
 }