public function OnStartForking() { // Initialization $Db = Core::GetDBInstance(); $DbDomain = DBDomain::GetInstance(); $Whois = JWhois::GetInstance(); // Grep TLDs $data = $Db->GetAll("SELECT TLD FROM tlds WHERE modulename = 'Verisign' AND isactive = 1"); foreach ($data as $row) { $tlds[] = "'{$row['TLD']}'"; } $tlds = join(',', $tlds); // Grep domains $domain_data = $Db->GetAll("\r\n\t\t\t\tSELECT name, TLD FROM domains \r\n\t\t\t\tWHERE\r\n\t\t\t\t-- TLD in matching list\r\n\t\t\t\tTLD IN ({$tlds})\r\n\t\t\t\t-- Today is anniversary of registration\r\n\t\t\t\tAND ((MONTH(NOW()) = MONTH(start_date) AND DAY(NOW()) = DAY(start_date))\r\n\t\t\t\t-- Today is 28/02 and domain was registered 29/02 at leap year \r\n\t\t\t\tOR (MONTH(NOW()) = 2 AND DAY(NOW()) = 28 AND MONTH(start_date) = 2 AND DAY(start_date) = 29))\r\n\t\t\t"); foreach ($domain_data as $row) { try { $Domain = $DbDomain->LoadByName($row['name'], $row['TLD']); $Client = Client::Load($Domain->UserID); // Send notice $emlvars = array('whois' => $Whois->Whois($Domain->GetHostName()), 'Client' => $Client); mailer_send("wdrp_notice.eml", $emlvars, $Client->Email, $Client->Name); } catch (Exception $e) { Log::Log(sprintf("Failed to sent notice about %s. %s", "{$row['name']}.{$row['TLD']}", $e->getMessage()), E_ERROR); } } }
function __construct() { parent::__construct(); $this->eppdrs = new EppDrs_Api_Client_Service(array("url" => "http://localhost/api/20111014", "key" => CONFIG::$API_KEY, "keyId" => CONFIG::$API_KEY_ID)); $client = Client::Load(42); $this->eppdrs2 = new EppDrs_Api_Client_Service(array("url" => "http://localhost/api/20111014", "key" => $client->GetSettingValue(ClientSettings::API_KEY), "keyId" => $client->GetSettingValue(ClientSettings::API_KEY_ID))); }
public function defaultAction() { if ($this->user->getType() == Scalr_Account_User::TYPE_SCALR_ADMIN) { $this->response->page('ui/dashboard/admin.js'); } else { if ($this->user->getType() == Scalr_Account_User::TYPE_FIN_ADMIN) { self::loadController('Dashboard', 'Scalr_UI_Controller_Admin_Analytics')->defaultAction(); } else { $loadJs = array('ui/dashboard/columns.js'); $scope = $this->request->getScope(); $cloudynEnabled = \Scalr::config('scalr.cloudyn.master_email') ? true : false; $billingEnabled = \Scalr::config('scalr.billing.enabled') ? true : false; $panel = $this->user->getDashboard($this->getEnvironmentId(true)); if (empty($panel['configuration'])) { // default configurations $client = Client::Load($this->user->getAccountId()); if ($client->GetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED)) { // old customer if ($scope == 'account') { $panel['configuration'] = array(array(array('name' => 'dashboard.announcement', 'params' => array('newsCount' => 5))), array(array('name' => 'dashboard.environments'))); if ($this->user->getType() == Scalr_Account_User::TYPE_ACCOUNT_OWNER && $billingEnabled) { array_unshift($panel['configuration'], array(array('name' => 'dashboard.billing'))); } } else { $panel['configuration'] = array(array(array('name' => 'dashboard.status'), array('name' => 'dashboard.addfarm')), array(array('name' => 'dashboard.announcement', 'params' => array('newsCount' => 5))), array(array('name' => 'dashboard.lasterrors', 'params' => array('errorCount' => 10)))); } } else { if ($scope == 'account') { // new customer $panel['configuration'] = array(array(array('name' => 'dashboard.newuser')), array(array('name' => 'dashboard.announcement', 'params' => array('newsCount' => 5)))); if ($this->user->getType() == Scalr_Account_User::TYPE_ACCOUNT_OWNER && $billingEnabled) { array_unshift($panel['configuration'][1], array('name' => 'dashboard.billing')); } } else { // new customer $panel['configuration'] = array(array(array('name' => 'dashboard.addfarm')), array(array('name' => 'dashboard.newuser')), array(array('name' => 'dashboard.announcement', 'params' => array('newsCount' => 5)))); } } $this->user->setDashboard($this->getEnvironmentId(true), $panel); $panel = $this->user->getDashboard($this->getEnvironmentId(true)); } // section for adding required widgets if ($scope == 'environment') { if ($cloudynEnabled && !in_array('cloudynInstalled', $panel['flags']) && !in_array('dashboard.cloudyn', $panel['widgets']) && !!$this->environment->isPlatformEnabled(SERVER_PLATFORMS::EC2)) { if (!isset($panel['configuration'][0])) { $panel['configuration'][0] = array(); } array_unshift($panel['configuration'][0], array('name' => 'dashboard.cloudyn')); $panel['flags'][] = 'cloudynInstalled'; $this->user->setDashboard($this->getEnvironmentId(), $panel); $panel = $this->user->getDashboard($this->getEnvironmentId()); } } $panel = $this->fillDash($panel); $conf = $this->getContainer()->config->get('scalr.load_statistics.connections.plotter'); $monitoringUrl = "{$conf['scheme']}://{$conf['host']}:{$conf['port']}"; $this->response->page('ui/dashboard/view.js', array('panel' => $panel, 'flags' => array('cloudynEnabled' => $cloudynEnabled, 'billingEnabled' => $billingEnabled), 'params' => array('monitoringUrl' => $monitoringUrl)), $loadJs, array('ui/dashboard/view.css', 'ui/analytics/analytics.css')); } } }
function run() { $mediator = Scalr_Integration_ZohoCrm_Mediator::getDefaultMediator(); if (!$mediator) { throw new Scalr_Integration_Exception("No default mediator configured"); } switch ($this->operation) { case self::OP_CREATE_CLIENT: $client = Client::Load($this->params["clientId"]); $mediator->addClient($client); break; case self::OP_UPDATE_CLIENT: $client = Client::Load($this->params["clientId"]); $mediator->updateClient($client, $this->params["skipRelations"]); break; case self::OP_DELETE_CLIENT: $mediator->deleteClient($this->params["deletedClient"]); break; case self::OP_ADD_PAYMENT: $client = Client::Load($this->params["clientId"]); $mediator->addPayment($client, $this->params["invoiceId"]); break; default: throw new Scalr_Integration_Exception("No handler for operation '{$this->operation}'"); } }
/** * Renew domain * @param $params = array( * name string * period int * userId int User ID (In admin mode) * noBilling bool Disable billing for domain opeartion (In admin mode) * ) * @return object */ function RenewDomain($params = null) { // Check params if ($this->access_mode == self::ACCESS_MODE_ADMIN) { if (!$params["userId"]) { throw new Exception(sprintf("'%s' parameter is required", "userId")); } } else { // Reset user disabled params $params["noBilling"] = false; } $user_id = $this->user_id ? $this->user_id : $params["userId"]; if (!$params["name"]) { throw new Exception(sprintf("'%s' parameter is required", "name")); } $period = (int) $params["period"] ? (int) $params["period"] : 1; list($name, $tld) = explode(".", $params["name"], 2); $registry = $this->registry_factory->GetRegistryByExtension($tld); $domain = DBDomain::GetInstance()->LoadByName($name, $tld); $domain->Period = $period; if (!$params["noBilling"]) { // Check that enougth money $client = Client::Load($user_id); $balance = DBBalance::GetInstance()->LoadClientBalance($user_id); $invoice = new Invoice(INVOICE_PURPOSE::DOMAIN_RENEW, $domain, $domain->UserID); $invoice->Description = sprintf(_("%s domain name renewal for %s year(s)"), $domain->GetHostName(), $period); $this->CheckEnoughtMoney($client, $balance, $invoice); $invoice->ItemID = $domain->ID; $this->MakePayment($client, $balance, $invoice); } $registry->RenewDomain($domain, array('period' => $domain->Period)); return new stdClass(); }
/** * Return new instance of AmazonRDS object * * @return AmazonRDS */ private function GetAmazonRDSClientObject($region) { // Get ClientID from database; $clientid = $this->DB->GetOne("SELECT clientid FROM farms WHERE id=?", array($this->FarmID)); // Get Client Object $Client = Client::Load($clientid); $RDSClient = AmazonRDS::GetInstance($Client->AWSAccessKeyID, $Client->AWSAccessKey); $RDSClient->SetRegion($region); return $RDSClient; }
public function defaultAction() { if ($this->user->getType() == Scalr_Account_User::TYPE_SCALR_ADMIN) { $this->response->page('ui/dashboard/admin.js'); } else { $loadJs = array('ui/dashboard/columns.js'); $cloudynEnabled = \Scalr::config('scalr.cloudyn.master_email') ? true : false; $billingEnabled = \Scalr::config('scalr.billing.enabled') ? true : false; $panel = $this->user->getDashboard($this->getEnvironmentId()); if (empty($panel['configuration'])) { // default configurations $client = Client::Load($this->user->getAccountId()); if ($client->GetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED)) { // old customer $panel['configuration'] = array(array(array('name' => 'dashboard.status')), array(array('name' => 'dashboard.announcement', 'params' => array('newsCount' => 5)), array('name' => 'dashboard.usagelaststat', 'params' => array('farmCount' => 5))), array(array('name' => 'dashboard.lasterrors', 'params' => array('errorCount' => 10)))); if ($this->user->getType() == Scalr_Account_User::TYPE_ACCOUNT_OWNER && $billingEnabled) { array_unshift($panel['configuration'][0], array('name' => 'dashboard.billing')); } } else { // new customer $panel['configuration'] = array(array(array('name' => 'dashboard.tutorapp')), array(array('name' => 'dashboard.tutordns')), array(array('name' => 'dashboard.tutorfarm'), array('name' => 'dashboard.announcement', 'params' => array('newsCount' => 5)))); if ($this->user->getType() == Scalr_Account_User::TYPE_ACCOUNT_OWNER && $billingEnabled) { $panel['configuration'][1][] = array('name' => 'dashboard.billing'); } } $this->user->setDashboard($this->getEnvironmentId(), $panel); $panel = $this->user->getDashboard($this->getEnvironmentId()); } // section for adding required widgets if ($cloudynEnabled && !in_array('cloudynInstalled', $panel['flags']) && !in_array('dashboard.cloudyn', $panel['widgets']) && !!$this->environment->isPlatformEnabled(SERVER_PLATFORMS::EC2)) { if (!isset($panel['configuration'][0])) { $panel['configuration'][0] = array(); } array_unshift($panel['configuration'][0], array('name' => 'dashboard.cloudyn')); $panel['flags'][] = 'cloudynInstalled'; $this->user->setDashboard($this->getEnvironmentId(), $panel); $panel = $this->user->getDashboard($this->getEnvironmentId()); } $panel = $this->fillDash($panel); $this->response->page('ui/dashboard/view.js', array('panel' => $panel, 'flags' => array('cloudynEnabled' => $cloudynEnabled, 'billingEnabled' => $billingEnabled)), $loadJs, array('ui/dashboard/view.css')); } }
public function OnIssued(Invoice $Invoice) { if ($Invoice->Purpose != INVOICE_PURPOSE::BALANCE_DEPOSIT) { Log::Log("BalanceInvoiceObserver::OnIssued(InvoiceID={$Invoice->ID})", E_USER_NOTICE); try { $Client = Client::Load($_SESSION["userid"] ? $_SESSION["userid"] : $Invoice->UserID); if ($Client->GetSettingValue(ClientSettings::AUTO_PAY_FROM_BALANCE)) { if ($Client->GetSettingValue(ClientSettings::AUTO_PAY_NO_RENEW) && $Invoice->Purpose == INVOICE_PURPOSE::DOMAIN_RENEW) { return; } $Balance = DBBalance::GetInstance()->LoadClientBalance($Client->ID); $Operation = $Balance->CreateOperation(BalanceOperationType::Withdraw, $Invoice->GetTotal()); $Operation->InvoiceID = $Invoice->ID; $Balance->ApplyOperation($Operation); $Invoice->MarkAsPaid(null); } } catch (Exception $e) { Log::Log("BalanceInvoiceObserver::OnIssued() thrown exception: {$e->getMessage()}", E_USER_ERROR); } Log::Log("BalanceInvoiceObserver::OnIssued Successfully completed.", E_USER_NOTICE); } }
} $Domain = $Registry->NewDomainInstance(); $Domain->Name = $domain_name; $Domain->UserID = $_SESSION['userid']; try { $res = $Registry->DomainCanBeRegistered($Domain)->Result; } catch (Exception $e) { throw new ApplicationException(sprintf(_("Cannot check availability of %s. %s"))); } if ($res == true) { throw new ApplicationException(sprintf(_("Domain %s not registered"), $Domain->GetHostName())); } // Save expiration date $Domain->CreateDate = strtotime($expiredate); // See if we have to issue invoice for this client if (Client::Load($_SESSION['userid'])->GetSettingValue('bill_for_domain_preorder') != 1) { $Domain->Status = DOMAIN_STATUS::AWAITING_PREREGISTRATION; DBDomain::GetInstance()->Save($Domain); } else { $Domain->Status = DOMAIN_STATUS::AWAITING_PAYMENT; $Domain = DBDomain::GetInstance()->Save($Domain); $Invoice = new Invoice(INVOICE_PURPOSE::PREREGISTRATION_DROPCATCHING, $Domain->ID, $_SESSION['userid']); $Invoice->Description = sprintf(_("Domain name %s pre-registration"), $Domain->GetHostName()); $invoices[] = $Invoice->Save()->ID; } if (count($err) == 0) { if (count($invoices) != 0) { $okmsg = _("Please pay the generated invoices below to add domains to pre-registration queue"); CoreUtils::Redirect("checkout.php?string_invoices=" . implode(",", $invoices)); } else { $okmsg = _("Domain successfully added to pre-registration queue");
/* Query */ $statement = $database->prepare("SELECT COUNT(*) FROM tickets"); $statement->execute(); $totalNumRows = $statement->fetch(PDO::FETCH_NUM); $statement = $database->prepare("SELECT SQL_CALC_FOUND_ROWS " . implode(",", $aColumns) . " FROM tickets " . $sWhere . " " . $sOrder . " " . $sLimit); $statement->execute(); $statement2 = $database->prepare("SELECT FOUND_ROWS()"); $statement2->execute(); $filteredNumRows = $statement2->fetch(PDO::FETCH_NUM); $rows = $statement->fetchAll(PDO::FETCH_ASSOC); $rowCount = count($rows); for ($i = 0; $i < $rowCount; $i++) { $row = $rows[$i]; $color = ""; if ($q == -1) { $color = " danger"; $rows[$i] = array($row["id"], Client::Load($row["cid"])->GetUsername(), DisplayDatetime($row["creation_date"]), DisplayLimited($row["description"])); } else { $sid = $row["sid"]; $status = $row["status"]; if ($sid == $me->GetID()) { $color = " " . ($status == STATUS_OPENED ? "danger" : "success"); } $rows[$i] = array($row["id"], $status == STATUS_OPENED ? "Opened" : "Closed", Client::Load($row["cid"])->GetUsername(), DisplayDatetime($row["creation_date"]), DisplayLimited($row["description"]), implode(", ", json_decode($row["tags"], true)), Staff::Load($sid)->GetUsername(), DisplayDatetime($row["closed_date"])); } $rows[$i]["DT_RowClass"] = "linkrow" . $color; } $output = array("sEcho" => intval($_GET['sEcho']), "iTotalRecords" => $totalNumRows[0], "iTotalDisplayRecords" => $filteredNumRows[0], "aaData" => $rows); echo json_encode($output);
} $phoneNumber = "+" . $phoneNumber; if ($phoneNumber === $_REQUEST['From']) { $correct = $staff; break; } } } if ($correct === null) { exit; } $lastTicket = Ticket::GetByStaffIDOrderSingle($staff->GetID(), "last_modified_date", "DESC"); if (!$lastTicket->IsValid()) { exit; } $client = Client::Load($lastTicket->GetClientID()); if (!$client->IsValid()) { exit; } $body = "Client Information\nID: " . $client->GetUsername() . "\nName: " . $client->GetName() . "\nCommunity: " . Building::GetCommunity($client->GetBuilding()) . "\nBuilding: " . $client->GetBuilding() . "\nRoom: " . $client->GetLocation(); $remaining = 255 - strlen($body); if ($remaining > 50) { $body .= "\nDescription: "; $remaining = 255 - strlen($body); $body .= DisplayLimited($lastTicket->GetDescription()); } header("content-type: text/xml"); echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; ?> <Response> <Sms><?php
} } // Post actions if ($_POST) { if ($post_action == "del") { // Delete users $i = 0; foreach ((array)$post_id as $k=>$v) { $i++; try { $Client = Client::Load($v); $Client->Delete(); } catch(Exception $e) { $err[] = $e; } Application::FireEvent('ClientDeleted', $Client); } if (!$err) { $okmsg = "{$i} users deleted"; CoreUtils::Redirect("users_view.php"); }
public function defaultAction() { $userType = $this->user->getType(); if ($userType == Scalr_Account_User::TYPE_FIN_ADMIN) { self::loadController('Dashboard', 'Scalr_UI_Controller_Admin_Analytics')->defaultAction(); } else { $js = ['ui/dashboard/columns.js']; $css = ['ui/dashboard/view.css']; $envId = $this->getEnvironmentId(true); $panel = $this->user->getDashboard($envId); $scope = $this->request->getScope(); $isNewCustomer = false; //flags, parameters, additional stylesheets, etc if ($scope === 'scalr') { $flags = []; $params = []; } else { $client = Client::Load($this->user->getAccountId()); $isNewCustomer = !$client->GetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED); $cloudynEnabled = \Scalr::config('scalr.cloudyn.master_email') ? true : false; $billingEnabled = \Scalr::config('scalr.billing.enabled') ? true : false; $plotter = $this->getContainer()->config->get('scalr.load_statistics.connections.plotter'); $monitoringUrl = $plotter['scheme'] . '://' . $plotter['host'] . ':' . $plotter['port']; $css[] = 'ui/analytics/analytics.css'; $flags = ['cloudynEnabled' => $cloudynEnabled, 'billingEnabled' => $billingEnabled]; $params = ['monitoringUrl' => $monitoringUrl]; } if (empty($panel['configuration'])) { if ($scope === 'scalr') { $panel['configuration'] = [[['name' => 'dashboard.scalrhealth']], [['name' => 'dashboard.gettingstarted']]]; } elseif ($isNewCustomer) { if ($scope === 'account') { $panel['configuration'] = [[['name' => 'dashboard.newuser']], [['name' => 'dashboard.announcement', 'params' => ['newsCount' => 8]]]]; if ($userType == Scalr_Account_User::TYPE_ACCOUNT_OWNER && $billingEnabled) { array_unshift($panel['configuration'][1], ['name' => 'dashboard.billing']); } } else { $panel['configuration'] = [[['name' => 'dashboard.addfarm']], [['name' => 'dashboard.newuser']], [['name' => 'dashboard.announcement', 'params' => ['newsCount' => 8]]]]; } } else { if ($scope === 'account') { $panel['configuration'] = [[['name' => 'dashboard.announcement', 'params' => ['newsCount' => 8]]], [['name' => 'dashboard.environments']]]; if ($userType == Scalr_Account_User::TYPE_ACCOUNT_OWNER && $billingEnabled) { array_unshift($panel['configuration'], [['name' => 'dashboard.billing']]); } } else { $panel['configuration'] = [[['name' => 'dashboard.status'], ['name' => 'dashboard.addfarm']], [['name' => 'dashboard.announcement', 'params' => ['newsCount' => 8]]], [['name' => 'dashboard.lasterrors', 'params' => ['errorCount' => 10]]]]; } } $this->user->setDashboard($envId, $panel); $panel = $this->user->getDashboard($envId); } //required widgets $panelChanged = false; if ($scope === 'scalr') { if (!in_array('dashboard.scalrhealth', $panel['widgets'])) { if (!isset($panel['configuration'][0])) { $panel['configuration'][0] = []; } array_unshift($panel['configuration'][0], ['name' => 'dashboard.scalrhealth']); $panelChanged = true; } } elseif ($scope === 'environment') { if ($cloudynEnabled && !in_array('cloudynInstalled', $panel['flags']) && !in_array('dashboard.cloudyn', $panel['widgets']) && !!$this->environment->isPlatformEnabled(SERVER_PLATFORMS::EC2)) { if (!isset($panel['configuration'][0])) { $panel['configuration'][0] = []; } array_unshift($panel['configuration'][0], ['name' => 'dashboard.cloudyn']); $panel['flags'][] = 'cloudynInstalled'; $panelChanged = true; } } if ($panelChanged) { $this->user->setDashboard($envId, $panel); $panel = $this->user->getDashboard($envId); } $panel = $this->fillDash($panel); $this->response->page('ui/dashboard/view.js', ['panel' => $panel, 'flags' => $flags, 'params' => $params], $js, $css); } }
<? require_once('src/prepend.inc.php'); $display["TLDs"] = $TLDs; $Client = Client::Load($_SESSION["userid"]); // Complete domain registration (postpaid) if ($req_action == "complete") { Log::Log("domain_reg.php?action=complete", E_USER_NOTICE); // Get domain info try { $Domain = DBDomain::GetInstance()->Load($req_id); } catch(Exception $e) { Log::Log("Cannot get domain object (id={$req_id}), error: {$e->getMessage()}", E_USER_WARNING); $errmsg = $e->getMessage(); } Log::Log("DomainName = {$Domain->GetHostName()}", E_USER_NOTICE); if (!$errmsg && $Domain->UserID != $_SESSION['userid']) { Log::Log("UserID != Domain->UserID", E_USER_WARNING); $errmsg = _("You don't have permissions to manage this domain"); } // Check domain status if (!$errmsg && ($Domain->Status != DOMAIN_STATUS::PENDING || $Domain->IncompleteOrderOperation != INCOMPLETE_OPERATION::DOMAIN_CREATE))
/** * * @return Client */ public function GetClient() { if (!$this->client) { $this->client = Client::Load($this->clientId); } return $this->client; }
public function xBuildAction() { $this->request->defineParams(array('farmId' => array('type' => 'int'), 'roles' => array('type' => 'json'), 'rolesToRemove' => array('type' => 'json'), 'farm' => array('type' => 'json'), 'launch' => array('type' => 'bool'))); if (!$this->isFarmConfigurationValid($this->getParam('farmId'), $this->getParam('farm'), (array) $this->getParam('roles'))) { if ($this->errors['error_count'] != 0) { $this->response->failure(); $this->response->data(array('errors' => $this->errors)); return; } } $farm = $this->getParam('farm'); $client = Client::Load($this->user->getAccountId()); if ($this->getParam('farmId')) { $dbFarm = DBFarm::LoadByID($this->getParam('farmId')); $this->user->getPermissions()->validate($dbFarm); $this->request->checkPermissions($dbFarm->__getNewFarmObject(), Acl::PERM_FARMS_UPDATE); $dbFarm->isLocked(); if ($this->getParam('changed') && $dbFarm->changedTime && $this->getParam('changed') != $dbFarm->changedTime) { $userName = '******'; $changed = explode(' ', $this->getParam('changed')); $changedTime = intval($changed[1]); try { $user = new Scalr_Account_User(); $user->loadById($dbFarm->changedByUserId); $userName = $user->getEmail(); } catch (Exception $e) { } $this->response->failure(); $this->response->data(array('changedFailure' => sprintf('%s changed this farm at %s', $userName, Scalr_Util_DateTime::convertTz($changedTime)))); return; } else { if ($this->getParam('changed')) { $this->checkFarmConfigurationIntegrity($this->getParam('farmId'), $this->getParam('farm'), (array) $this->getParam('roles'), (array) $this->getParam('rolesToRemove')); } } $dbFarm->changedByUserId = $this->user->getId(); $dbFarm->changedTime = microtime(); if ($this->getContainer()->analytics->enabled) { $projectId = $farm['projectId']; if (empty($projectId)) { $ccId = $dbFarm->GetEnvironmentObject()->getPlatformConfigValue(Scalr_Environment::SETTING_CC_ID); if (!empty($ccId)) { //Assigns Project automatically only if it is the one withing the Cost Center $projects = ProjectEntity::findByCcId($ccId); if (count($projects) == 1) { $projectId = $projects->getArrayCopy()[0]->projectId; } } } if (!empty($projectId) && $dbFarm->GetSetting(Entity\FarmSetting::PROJECT_ID) != $projectId) { $this->request->checkPermissions($dbFarm->__getNewFarmObject(), Acl::PERM_FARMS_PROJECTS); } } $bNew = false; } else { $this->request->restrictAccess(Acl::RESOURCE_OWN_FARMS, Acl::PERM_FARMS_CREATE); $this->user->getAccount()->validateLimit(Scalr_Limits::ACCOUNT_FARMS, 1); $dbFarm = new DBFarm(); $dbFarm->ClientID = $this->user->getAccountId(); $dbFarm->EnvID = $this->getEnvironmentId(); $dbFarm->Status = FARM_STATUS::TERMINATED; $dbFarm->ownerId = $this->user->getId(); $dbFarm->changedByUserId = $this->user->getId(); $dbFarm->changedTime = microtime(); $bNew = true; } if ($this->getParam('farm')) { $dbFarm->Name = $this->request->stripValue($farm['name']); $dbFarm->RolesLaunchOrder = $farm['rolesLaunchOrder']; $dbFarm->Comments = $this->request->stripValue($farm['description']); } if (empty($dbFarm->Name)) { throw new Exception(_("Farm name required")); } $setFarmTeams = false; if ($bNew) { $setFarmTeams = true; } else { if ($dbFarm->ownerId == $this->user->getId() || $this->request->hasPermissions($dbFarm->__getNewFarmObject(), Acl::PERM_FARMS_CHANGE_OWNERSHIP)) { if (is_numeric($farm['owner']) && $farm['owner'] != $dbFarm->ownerId) { $dbFarm->ownerId = $farm['owner']; $f = Entity\Farm::findPk($dbFarm->ID); Entity\FarmSetting::addOwnerHistory($f, User::findPk($farm['owner']), User::findPk($this->user->getId())); $f->save(); } $setFarmTeams = true; } } $dbFarm->save(); if ($setFarmTeams && is_array($farm['teamOwner'])) { /* @var $f Entity\Farm */ $f = Entity\Farm::findPk($dbFarm->ID); $f->setTeams(empty($farm['teamOwner']) ? [] : Entity\Account\Team::find([['name' => ['$in' => $farm['teamOwner']]], ['accountId' => $this->getUser()->accountId]])); $f->save(); } if ($bNew) { $dbFarm->SetSetting(Entity\FarmSetting::CREATED_BY_ID, $this->user->getId()); $dbFarm->SetSetting(Entity\FarmSetting::CREATED_BY_EMAIL, $this->user->getEmail()); } $governance = new Scalr_Governance($this->getEnvironmentId()); if (!$this->getParam('farmId') && $governance->isEnabled(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE)) { $dbFarm->SetSetting(Entity\FarmSetting::LEASE_STATUS, 'Active'); // for created farm } if (isset($farm['variables'])) { $variables = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), ScopeInterface::SCOPE_FARM); $variables->setValues(is_array($farm['variables']) ? $farm['variables'] : [], 0, $dbFarm->ID, 0, '', false, true); } if (!$farm['timezone']) { $farm['timezone'] = date_default_timezone_get(); } $dbFarm->SetSetting(Entity\FarmSetting::TIMEZONE, $farm['timezone']); $dbFarm->SetSetting(Entity\FarmSetting::EC2_VPC_ID, isset($farm["vpc_id"]) ? $farm['vpc_id'] : null); $dbFarm->SetSetting(Entity\FarmSetting::EC2_VPC_REGION, isset($farm["vpc_id"]) ? $farm['vpc_region'] : null); $dbFarm->SetSetting(Entity\FarmSetting::SZR_UPD_REPOSITORY, $farm[Entity\FarmSetting::SZR_UPD_REPOSITORY]); $dbFarm->SetSetting(Entity\FarmSetting::SZR_UPD_SCHEDULE, $farm[Entity\FarmSetting::SZR_UPD_SCHEDULE]); if (!$dbFarm->GetSetting(Entity\FarmSetting::CRYPTO_KEY)) { $dbFarm->SetSetting(Entity\FarmSetting::CRYPTO_KEY, Scalr::GenerateRandomKey(40)); } if ($this->getContainer()->analytics->enabled) { //Cost analytics project must be set for the Farm object $dbFarm->setProject(!empty($farm['projectId']) ? $farm['projectId'] : null); } $virtualFarmRoles = array(); $roles = $this->getParam('roles'); if (!empty($roles)) { foreach ($roles as $role) { if (strpos($role['farm_role_id'], "virtual_") !== false) { $dbRole = DBRole::loadById($role['role_id']); $dbFarmRole = $dbFarm->AddRole($dbRole, $role['platform'], $role['cloud_location'], (int) $role['launch_index'], $role['alias']); $virtualFarmRoles[$role['farm_role_id']] = $dbFarmRole->ID; } } } $usedPlatforms = array(); $farmRoleVariables = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), ScopeInterface::SCOPE_FARMROLE); if (!empty($roles)) { foreach ($roles as $role) { if ($role['farm_role_id']) { if (isset($virtualFarmRoles[$role['farm_role_id']])) { $role['farm_role_id'] = $virtualFarmRoles[$role['farm_role_id']]; } $update = true; $dbFarmRole = DBFarmRole::LoadByID($role['farm_role_id']); $dbRole = DBRole::loadById($dbFarmRole->RoleID); $role['role_id'] = $dbFarmRole->RoleID; if ($dbFarmRole->Platform == SERVER_PLATFORMS::GCE) { $dbFarmRole->CloudLocation = $role['cloud_location']; } } else { /** TODO: Remove because will be handled with virtual_ **/ $update = false; $dbRole = DBRole::loadById($role['role_id']); $dbFarmRole = $dbFarm->AddRole($dbRole, $role['platform'], $role['cloud_location'], (int) $role['launch_index']); } if ($dbRole->hasBehavior(ROLE_BEHAVIORS::RABBITMQ)) { $role['settings'][Entity\FarmRoleSetting::SCALING_MAX_INSTANCES] = $role['settings'][Entity\FarmRoleSetting::SCALING_MIN_INSTANCES]; } if ($update) { $dbFarmRole->LaunchIndex = (int) $role['launch_index']; $dbFarmRole->Alias = $role['alias']; $dbFarmRole->Save(); } $usedPlatforms[$role['platform']] = 1; $oldRoleSettings = $dbFarmRole->GetAllSettings(); // Update virtual farm_role_id with actual value $scripts = (array) $role['scripting']; if (!empty($virtualFarmRoles)) { array_walk_recursive($scripts, function (&$v, $k) use($virtualFarmRoles) { if (is_string($v)) { $v = str_replace(array_keys($virtualFarmRoles), array_values($virtualFarmRoles), $v); } }); array_walk_recursive($role['settings'], function (&$v, $k) use($virtualFarmRoles) { if (is_string($v)) { $v = str_replace(array_keys($virtualFarmRoles), array_values($virtualFarmRoles), $v); } }); } $dbFarmRole->ClearSettings("chef."); if (!empty($role['scaling_settings']) && is_array($role['scaling_settings'])) { foreach ($role['scaling_settings'] as $k => $v) { $dbFarmRole->SetSetting($k, $v, Entity\FarmRoleSetting::TYPE_CFG); } } foreach ($role['settings'] as $k => $v) { $dbFarmRole->SetSetting($k, $v, Entity\FarmRoleSetting::TYPE_CFG); } /****** Scaling settings ******/ $scalingManager = new Scalr_Scaling_Manager($dbFarmRole); $scalingManager->setFarmRoleMetrics(is_array($role['scaling']) ? $role['scaling'] : array()); //TODO: optimize this code... $this->db->Execute("DELETE FROM farm_role_scaling_times WHERE farm_roleid=?", array($dbFarmRole->ID)); // 5 = Time based scaling -> move to constants if (!empty($role['scaling'][Entity\ScalingMetric::METRIC_DATE_AND_TIME_ID])) { foreach ($role['scaling'][Entity\ScalingMetric::METRIC_DATE_AND_TIME_ID] as $scal_period) { $chunks = explode(":", $scal_period['id']); $this->db->Execute("INSERT INTO farm_role_scaling_times SET\n farm_roleid\t\t= ?,\n start_time\t\t= ?,\n end_time\t\t= ?,\n days_of_week\t= ?,\n instances_count\t= ?\n ", array($dbFarmRole->ID, $chunks[0], $chunks[1], $chunks[2], $chunks[3])); } } /*****************/ /* Add script options to databse */ $dbFarmRole->SetScripts($scripts, (array) $role['scripting_params']); /* End of scripting section */ /* Add storage configuration */ if (isset($role['storages']['configs'])) { $dbFarmRole->getStorage()->setConfigs($role['storages']['configs'], false); } $farmRoleVariables->setValues(is_array($role['variables']) ? $role['variables'] : [], $dbFarmRole->GetRoleID(), $dbFarm->ID, $dbFarmRole->ID, '', false, true); foreach (Scalr_Role_Behavior::getListForFarmRole($dbFarmRole) as $behavior) { $behavior->onFarmSave($dbFarm, $dbFarmRole); } /** * Platform specified updates */ if ($dbFarmRole->Platform == SERVER_PLATFORMS::EC2) { \Scalr\Modules\Platforms\Ec2\Helpers\EbsHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); \Scalr\Modules\Platforms\Ec2\Helpers\EipHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); if ($role['settings']['aws.elb.remove']) { $this->request->restrictAccess(Acl::RESOURCE_AWS_ELB, Acl::PERM_AWS_ELB_MANAGE); } \Scalr\Modules\Platforms\Ec2\Helpers\ElbHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); } if (in_array($dbFarmRole->Platform, array(SERVER_PLATFORMS::IDCF, SERVER_PLATFORMS::CLOUDSTACK))) { Scalr\Modules\Platforms\Cloudstack\Helpers\CloudstackHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); } } } $rolesToRemove = $this->getParam('rolesToRemove'); if (!empty($rolesToRemove)) { $currentFarmRoles = Entity\FarmRole::find([['farmId' => $dbFarm->ID], ['id' => ['$in' => $rolesToRemove]]]); /* @var $farmRole Entity\FarmRole */ foreach ($currentFarmRoles as $farmRole) { $farmRole->delete(); } } $dbFarm->save(); if (!$client->GetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED)) { $client->SetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED, time()); } if ($this->request->hasPermissions($dbFarm->__getNewFarmObject(), Acl::PERM_FARMS_LAUNCH_TERMINATE) && $this->getParam('launch')) { $this->user->getPermissions()->validate($dbFarm); $dbFarm->isLocked(); Scalr::FireEvent($dbFarm->ID, new FarmLaunchedEvent(true, $this->user->id)); $this->response->success('Farm successfully saved and launched'); } else { $this->response->success('Farm successfully saved'); } $this->response->data(array('farmId' => $dbFarm->ID, 'isNewFarm' => $bNew)); }
</div> <div class="panel-body nopadding"> <table class="table table-bordered table-striped table-hover"> <thead> <tr> <th>#</th> <th>Client</th> <th>Opened Date</th> <th>Closed Date</th> </tr> </thead> <tbody class="searchable rowlink" data-link="row"> <?php $tickets = Ticket::GetByStaffIDWithStatusOrderLimit($me->GetID(), STATUS_CLOSED, "closed_date", "DESC", 20); foreach ($tickets as $ticket) { $client = Client::Load($ticket->GetClientID()); echo "<tr class='linkrow success' href='index.php?p=ticket&id=" . $ticket->GetID() . "'>"; echo "<td>" . $ticket->GetID() . "</td>"; echo "<td>" . $client->GetUsername() . "</td>"; echo "<td>" . DisplayDatetime($ticket->GetCreationDate()) . "</td>"; echo "<td>" . DisplayDatetime($ticket->GetClosedDate()) . "</td>"; echo "</tr>"; } ?> </tbody> </table> </div> </div> </div> </div>
require_once 'src/prepend.inc.php'; if ($_POST) { if (!$post_userid) { $err[] = sprintf(_("%s is required"), "Client"); } if (!$post_description) { $err[] = sprintf(_("%s is required"), "Description"); } $post_amount = floatval(str_replace(",", ".", $post_amount)); if (!$post_amount) { $err[] = sprintf(_("%s is required"), "Amount"); } if (!$err) { try { $Client = Client::Load($post_userid); $Balance = DBBalance::GetInstance()->LoadClientBalance($Client->ID); $Operation = $Balance->CreateOperation($post_type, $post_amount); $Operation->Description = $post_description; $Balance->ApplyOperation($Operation); } catch (Exception $e) { $err[] = $e->getMessage(); } } if (!$err) { $okmsg = "Balance operation apply successfully"; CoreUtils::Redirect("balance_operation.php"); } } $display["attr"] = array_merge($_GET, $_POST); $display["users"] = $db->GetAll("SELECT * FROM users ORDER BY login");
protected function ShowNS() { if ($_SESSION["userid"]) { // Set client default ns $Client = Client::Load($_SESSION["userid"]); if ($Client->GetSettingValue(ClientSettings::NS1)) { $this->display["ns1"] = $Client->GetSettingValue(ClientSettings::NS1); $this->display["ns2"] = $Client->GetSettingValue(ClientSettings::NS2); } } // Set app default ns if (!$this->display["ns1"]) { $this->display["ns1"] = CONFIG::$NS1; $this->display["ns2"] = CONFIG::$NS2; } $this->display["enable_managed_dns"] = ENABLE_EXTENSION::$MANAGED_DNS; }
/** * Request domain name ingoing transfer * * @param $params = array( * name string Domain name * authCode string Domain auth code * registrant string * admin string * billing string * tech string * extraFields array(key => value) @see GetTldInfo * userId int User ID (In admin mode) * noBilling bool Disable billing for domain opeartion (In admin mode) * ) * @return object */ function TransferDomain($params = null) { // Check params if ($this->access_mode == self::ACCESS_MODE_ADMIN) { if (!$params["userId"]) { throw new Exception(sprintf("'%s' parameter is required", "userId")); } } else { $params["noBilling"] = false; } $user_id = $this->user_id ? $this->user_id : $params["userId"]; if (!$params["name"]) { throw new Exception(sprintf("'%s' parameter is required", "name")); } list($name, $tld) = explode(".", $params["name"], 2); $registry = $this->registry_factory->GetRegistryByExtension($tld); $db_domain = DBDomain::GetInstance(); $already_exists = $this->db->GetOne("SELECT * FROM domains WHERE \n\t\t\t\t\tname = ? AND TLD = ? AND userid = ? AND incomplete_operation = ?", array($name, $tld, $user_id, INCOMPLETE_OPERATION::DOMAIN_TRANSFER)); if ($already_exists) { $domain = $db_domain->LoadByName($name, $tld); } else { $domain = $registry->NewDomainInstance(); $domain->Name = $name; $domain->UserID = $user_id; $domain->Period = 1; $domain->IncompleteOrderOperation = INCOMPLETE_OPERATION::DOMAIN_TRANSFER; if (!$params["noBilling"]) { $domain->Status = DOMAIN_STATUS::AWAITING_PAYMENT; // Check that enougth money $client = Client::Load($user_id); $balance = DBBalance::GetInstance()->LoadClientBalance($user_id); $invoice = new Invoice(INVOICE_PURPOSE::DOMAIN_TRANSFER, $domain, $domain->UserID); $invoice->Description = sprintf(_("%s domain name transfer"), $domain->GetHostName()); $this->CheckEnoughtMoney($client, $balance, $invoice); } else { $domain->Status = DOMAIN_STATUS::PENDING; } } // Check that domain is available for transfer $registry = $this->registry_factory->GetRegistryByExtension($domain->Extension); if (!$registry->DomainCanBeTransferred($domain)) { throw new Exception("This domain name cannot be transferred"); } if (!$domain->ID) { // Save domain after all checks $db_domain->Save($domain); if (!$params["noBilling"]) { $invoice->ItemID = $domain->ID; $this->MakePayment($client, $balance, $invoice); $domain->Status = DOMAIN_STATUS::PENDING; $db_domain->Save($domain); } } // Run transfer action $extra_fields = $params["extraFields"]; $extra_fields["pw"] = $params["authCode"]; $db_contact = DBContact::GetInstance(); foreach (CONTACT_TYPE::GetKeys() as $ctype) { if ($params[$ctype] || $extra_fields[$ctype]) { $clid = $params[$ctype] ? $params[$ctype] : $extra_fields[$ctype]; $c = $db_contact->LoadByCLID($clid); $domain->SetContact($c, $ctype); $extra_fields[$ctype] = $clid; } } if ($params["ns"] && !$extra_fields["ns1"]) { $extra_fields["ns1"] = $params["ns"][0]; $extra_fields["ns2"] = $params["ns"][1]; } $registry->TransferRequest($domain, $extra_fields); // Remove incomplete order operation $domain->IncompleteOrderOperation = null; $db_domain->Save($domain); $ret = new stdClass(); return $ret; }
public static function farmUpdateRoleSettings(DBFarmRole $DBFarmRole, $oldSettings, $newSettings) { try { $DBFarm = $DBFarmRole->GetFarmObject(); $Client = Client::Load($DBFarm->ClientID); $AmazonELB = Scalr_Service_Cloud_Aws::newElb($DBFarmRole->CloudLocation, $DBFarm->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Ec2::ACCESS_KEY), $DBFarm->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Ec2::SECRET_KEY)); // Load balancer settings if ($newSettings[DBFarmRole::SETTING_BALANCING_USE_ELB] == 1) { // Listeners $DBFarmRole->ClearSettings("lb.role.listener"); $ELBListenersList = new ELBListenersList(); $li = 0; foreach ($newSettings as $sk => $sv) { if (stristr($sk, "lb.role.listener")) { $li++; $listener_chunks = explode("#", $sv); $ELBListenersList->AddListener($listener_chunks[0], $listener_chunks[1], $listener_chunks[2], $listener_chunks[3]); $DBFarmRole->SetSetting("lb.role.listener.{$li}", $sv); } } $avail_zones = array(); $avail_zones_setting_hash = ""; foreach ($newSettings as $skey => $sval) { if (preg_match("/^lb.avail_zone.(.*)?\$/", $skey, $macthes)) { if ($macthes[1] != 'hash' && $macthes[1] != '.hash') { if ($sval == 1) { array_push($avail_zones, $macthes[1]); } $avail_zones_setting_hash .= "[{$macthes[1]}:{$sval}]"; } } } if (!$DBFarmRole->GetSetting(DBFarmRole::SETTING_BALANCING_HOSTNAME)) { $elb_name = sprintf("scalr-%s-%s", $DBFarm->Hash, rand(100, 999)); //CREATE NEW ELB $elb_dns_name = $AmazonELB->CreateLoadBalancer($elb_name, $avail_zones, $ELBListenersList); if ($elb_dns_name) { $DBFarmRole->SetSetting(DBFarmRole::SETTING_BALANCING_HOSTNAME, $elb_dns_name); $DBFarmRole->SetSetting(DBFarmRole::SETTING_BALANCING_NAME, $elb_name); $DBFarmRole->SetSetting(DBFarmRole::SETTING_BALANCING_AZ_HASH, $avail_zones_setting_hash); $register_servers = true; } } if ($DBFarmRole->GetSetting(DBFarmRole::SETTING_BALANCING_NAME)) { $ELBHealthCheckType = new ELBHealthCheckType($newSettings[DBFarmRole::SETTING_BALANCING_HC_TARGET], $newSettings[DBFarmRole::SETTING_BALANCING_HC_HTH], $newSettings[DBFarmRole::SETTING_BALANCING_HC_INTERVAL], $newSettings[DBFarmRole::SETTING_BALANCING_HC_TIMEOUT], $newSettings[DBFarmRole::SETTING_BALANCING_HC_UTH]); $hash = md5(serialize($ELBHealthCheckType)); if ($elb_name || $hash != $DBFarmRole->GetSetting(DBFarmRole::SETTING_BALANCING_HC_HASH)) { //UPDATE CURRENT ELB $AmazonELB->ConfigureHealthCheck($DBFarmRole->GetSetting(DBFarmRole::SETTING_BALANCING_NAME), $ELBHealthCheckType); $DBFarmRole->SetSetting(DBFarmRole::SETTING_BALANCING_HC_HASH, $hash); } // Configure AVAIL zones for the LB if (!$elb_name && $avail_zones_setting_hash != $DBFarmRole->GetSetting(DBFarmRole::SETTING_BALANCING_AZ_HASH)) { $info = $AmazonELB->DescribeLoadBalancers(array($DBFarmRole->GetSetting(DBFarmRole::SETTING_BALANCING_NAME))); $elb = $info->DescribeLoadBalancersResult->LoadBalancerDescriptions->member; $c = (array) $elb->AvailabilityZones; if (!is_array($c['member'])) { $c_zones = array($c['member']); } else { $c_zones = $c['member']; } $add_avail_zones = array(); $rem_avail_zones = array(); foreach ($newSettings as $skey => $sval) { if (preg_match("/^lb.avail_zone.(.*)?\$/", $skey, $m)) { if ($sval == 1 && !in_array($m[1], $c_zones)) { array_push($add_avail_zones, $m[1]); } if ($sval == 0 && in_array($m[1], $c_zones)) { array_push($rem_avail_zones, $m[1]); } } } if (count($add_avail_zones) > 0) { $AmazonELB->EnableAvailabilityZonesForLoadBalancer($DBFarmRole->GetSetting(DBFarmRole::SETTING_BALANCING_NAME), $add_avail_zones); } if (count($rem_avail_zones) > 0) { $AmazonELB->DisableAvailabilityZonesForLoadBalancer($DBFarmRole->GetSetting(DBFarmRole::SETTING_BALANCING_NAME), $rem_avail_zones); } $DBFarmRole->SetSetting(DBFarmRole::SETTING_BALANCING_AZ_HASH, $avail_zones_setting_hash); } } if ($register_servers) { $servers = $DBFarmRole->GetServersByFilter(array('status' => SERVER_STATUS::RUNNING)); $instances = array(); foreach ($servers as $DBServer) { $instances[] = $DBServer->GetProperty(EC2_SERVER_PROPERTIES::INSTANCE_ID); } if (count($instances) > 0) { $AmazonELB->RegisterInstancesWithLoadBalancer($DBFarmRole->GetSetting(DBFarmRole::SETTING_BALANCING_NAME), $instances); } } } else { if ($oldSettings[DBFarmRole::SETTING_BALANCING_HOSTNAME]) { try { $AmazonELB->DeleteLoadBalancer($DBFarmRole->GetSetting(DBFarmRole::SETTING_BALANCING_NAME)); } catch (Exception $e) { } $DBFarmRole->SetSetting(DBFarmRole::SETTING_BALANCING_NAME, ""); $DBFarmRole->SetSetting(DBFarmRole::SETTING_BALANCING_HOSTNAME, ""); $DBFarmRole->SetSetting(DBFarmRole::SETTING_BALANCING_USE_ELB, "0"); $DBFarmRole->SetSetting(DBFarmRole::SETTING_BALANCING_HC_HASH, ""); $DBFarmRole->ClearSettings("lb.avail_zone"); $DBFarmRole->ClearSettings("lb.healthcheck"); $DBFarmRole->ClearSettings("lb.role.listener"); } } } catch (Exception $e) { throw new Exception("Error with ELB on Role '{$DBFarmRole->GetRoleObject()->name}': {$e->getMessage()}"); } }
public function xBuildAction() { $this->request->defineParams(array('farmId' => array('type' => 'int'), 'roles' => array('type' => 'json'), 'farm' => array('type' => 'json'), 'roleUpdate' => array('type' => 'int'))); $this->request->restrictAccess(Acl::RESOURCE_FARMS, Acl::PERM_FARMS_MANAGE); if (!$this->isFarmConfigurationValid($this->getParam('farmId'), $this->getParam('farm'), (array) $this->getParam('roles'))) { if ($this->errors['error_count'] != 0) { $this->response->failure(); $this->response->data(array('errors' => $this->errors)); return; } } $farm = $this->getParam('farm'); $client = Client::Load($this->user->getAccountId()); if ($this->getParam('farmId')) { $dbFarm = DBFarm::LoadByID($this->getParam('farmId')); $this->user->getPermissions()->validate($dbFarm); $dbFarm->isLocked(); if ($this->getParam('changed') && $dbFarm->changedTime && $this->getParam('changed') != $dbFarm->changedTime) { $userName = '******'; $changed = explode(' ', $this->getParam('changed')); $changedTime = intval($changed[1]); try { $user = new Scalr_Account_User(); $user->loadById($dbFarm->changedByUserId); $userName = $user->getEmail(); } catch (Exception $e) { } $this->response->failure(); $this->response->data(array('changedFailure' => sprintf('%s changed this farm at %s', $userName, Scalr_Util_DateTime::convertTz($changedTime)))); return; } $dbFarm->changedByUserId = $this->user->getId(); $dbFarm->changedTime = microtime(); } else { $this->user->getAccount()->validateLimit(Scalr_Limits::ACCOUNT_FARMS, 1); $dbFarm = new DBFarm(); $dbFarm->Status = FARM_STATUS::TERMINATED; $dbFarm->createdByUserId = $this->user->getId(); $dbFarm->createdByUserEmail = $this->user->getEmail(); $dbFarm->changedByUserId = $this->user->getId(); $dbFarm->changedTime = microtime(); } if ($this->getParam('farm')) { $dbFarm->Name = strip_tags($farm['name']); $dbFarm->RolesLaunchOrder = $farm['rolesLaunchOrder']; $dbFarm->Comments = trim(strip_tags($farm['description'])); } if (empty($dbFarm->Name)) { throw new Exception(_("Farm name required")); } $dbFarm->save(); $governance = new Scalr_Governance($this->getEnvironmentId()); if ($governance->isEnabled(Scalr_Governance::GENERAL_LEASE)) { $dbFarm->SetSetting(DBFarm::SETTING_LEASE_STATUS, 'Active'); } if (isset($farm['variables'])) { $variables = new Scalr_Scripting_GlobalVariables($this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_FARM); $variables->setValues($farm['variables'], 0, $dbFarm->ID, 0, '', false); } if (!$farm['timezone']) { $farm['timezone'] = date_default_timezone_get(); } $dbFarm->SetSetting(DBFarm::SETTING_TIMEZONE, $farm['timezone']); $dbFarm->SetSetting(DBFarm::SETTING_EC2_VPC_ID, $farm['vpc_id']); $dbFarm->SetSetting(DBFarm::SETTING_EC2_VPC_REGION, $farm['vpc_region']); if (!$dbFarm->GetSetting(DBFarm::SETTING_CRYPTO_KEY)) { $dbFarm->SetSetting(DBFarm::SETTING_CRYPTO_KEY, Scalr::GenerateRandomKey(40)); } $virtualFarmRoles = array(); $roles = $this->getParam('roles'); if (!empty($roles)) { foreach ($roles as $role) { if (strpos($role['farm_role_id'], "virtual_") !== false) { $dbRole = DBRole::loadById($role['role_id']); $dbFarmRole = $dbFarm->AddRole($dbRole, $role['platform'], $role['cloud_location'], (int) $role['launch_index'], $role['alias']); $virtualFarmRoles[$role['farm_role_id']] = $dbFarmRole->ID; } } } $usedPlatforms = array(); $dbFarmRolesList = array(); $newFarmRolesList = array(); $farmRoleVariables = new Scalr_Scripting_GlobalVariables($this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_FARMROLE); if (!empty($roles)) { foreach ($roles as $role) { if ($role['farm_role_id']) { if ($virtualFarmRoles[$role['farm_role_id']]) { $role['farm_role_id'] = $virtualFarmRoles[$role['farm_role_id']]; } $update = true; $dbFarmRole = DBFarmRole::LoadByID($role['farm_role_id']); $dbRole = DBRole::loadById($dbFarmRole->RoleID); $role['role_id'] = $dbFarmRole->RoleID; if ($dbFarmRole->Platform == SERVER_PLATFORMS::GCE) { $dbFarmRole->CloudLocation = $role['cloud_location']; } } else { $update = false; $dbRole = DBRole::loadById($role['role_id']); $dbFarmRole = $dbFarm->AddRole($dbRole, $role['platform'], $role['cloud_location'], (int) $role['launch_index']); } if ($dbRole->hasBehavior(ROLE_BEHAVIORS::RABBITMQ)) { $role['settings'][DBFarmRole::SETTING_SCALING_MAX_INSTANCES] = $role['settings'][DBFarmRole::SETTING_SCALING_MIN_INSTANCES]; } if ($dbFarmRole->NewRoleID) { continue; } if ($update) { $dbFarmRole->LaunchIndex = (int) $role['launch_index']; $dbFarmRole->Alias = $role['alias']; $dbFarmRole->Save(); } $usedPlatforms[$role['platform']] = 1; $oldRoleSettings = $dbFarmRole->GetAllSettings(); // Update virtual farm_role_id with actual value $scripts = (array) $role['scripting']; if (count($virtualFarmRoles) > 0) { array_walk_recursive($scripts, function (&$v, $k) use($virtualFarmRoles) { if (is_string($v)) { $v = str_replace(array_keys($virtualFarmRoles), array_values($virtualFarmRoles), $v); } }); array_walk_recursive($role['settings'], function (&$v, $k) use($virtualFarmRoles) { if (is_string($v)) { $v = str_replace(array_keys($virtualFarmRoles), array_values($virtualFarmRoles), $v); } }); } //Audit log start //!TODO Enable Audit log for Farm Builder // $auditLog = $this->getEnvironment()->auditLog; // $docRoleSettingsBefore = new FarmRoleSettingsDocument($oldRoleSettings); // $docRoleSettingsBefore['farmroleid'] = $dbFarmRole->ID; // $docRoleSettings = new FarmRoleSettingsDocument(array_merge((array)$role['scaling_settings'], (array)$role['settings'])); // $docRoleSettings['farmroleid'] = $dbFarmRole->ID; $dbFarmRole->ClearSettings("chef."); if (!empty($role['scaling_settings']) && is_array($role['scaling_settings'])) { foreach ($role['scaling_settings'] as $k => $v) { $dbFarmRole->SetSetting($k, $v, DBFarmRole::TYPE_CFG); } } foreach ($role['settings'] as $k => $v) { $dbFarmRole->SetSetting($k, $v, DBFarmRole::TYPE_CFG); } // $auditLog->log('Farm has been saved', array(AuditLogTags::TAG_UPDATE), $docRoleSettings, $docRoleSettingsBefore); // unset($docRoleSettings); // unset($docRoleSettingsBefore); //Audit log finish /****** Scaling settings ******/ $scalingManager = new Scalr_Scaling_Manager($dbFarmRole); $scalingManager->setFarmRoleMetrics(is_array($role['scaling']) ? $role['scaling'] : array()); //TODO: optimize this code... $this->db->Execute("DELETE FROM farm_role_scaling_times WHERE farm_roleid=?", array($dbFarmRole->ID)); // 5 = Time based scaling -> move to constants if ($role['scaling'][5]) { foreach ($role['scaling'][5] as $scal_period) { $chunks = explode(":", $scal_period['id']); $this->db->Execute("INSERT INTO farm_role_scaling_times SET\n farm_roleid\t\t= ?,\n start_time\t\t= ?,\n end_time\t\t= ?,\n days_of_week\t= ?,\n instances_count\t= ?\n ", array($dbFarmRole->ID, $chunks[0], $chunks[1], $chunks[2], $chunks[3])); } } /*****************/ /* Update role params */ $dbFarmRole->SetParameters((array) $role['params']); /* End of role params management */ /* Add script options to databse */ $dbFarmRole->SetScripts($scripts, (array) $role['scripting_params']); /* End of scripting section */ /* Add services configuration */ $dbFarmRole->SetServiceConfigPresets((array) $role['config_presets']); /* End of scripting section */ /* Add storage configuration */ //try { $dbFarmRole->getStorage()->setConfigs((array) $role['storages']['configs']); //} catch (FarmRoleStorageException $e) { // $errors[] = array('farm_role_id' => 1, 'tab' => 'storage', 'error' => $e->getMessage()); //} $farmRoleVariables->setValues($role['variables'], $dbFarmRole->GetRoleID(), $dbFarm->ID, $dbFarmRole->ID, '', false); Scalr_Helpers_Dns::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); foreach (Scalr_Role_Behavior::getListForFarmRole($dbFarmRole) as $behavior) { $behavior->onFarmSave($dbFarm, $dbFarmRole); } /** * Platfrom specified updates */ if ($dbFarmRole->Platform == SERVER_PLATFORMS::EC2) { Modules_Platforms_Ec2_Helpers_Ebs::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); Modules_Platforms_Ec2_Helpers_Eip::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); Modules_Platforms_Ec2_Helpers_Elb::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); } if (in_array($dbFarmRole->Platform, array(SERVER_PLATFORMS::IDCF, SERVER_PLATFORMS::CLOUDSTACK))) { Modules_Platforms_Cloudstack_Helpers_Cloudstack::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); } $dbFarmRolesList[] = $dbFarmRole; $newFarmRolesList[] = $dbFarmRole->ID; } } if (!$this->getParam('roleUpdate')) { foreach ($dbFarm->GetFarmRoles() as $dbFarmRole) { if (!$dbFarmRole->NewRoleID && !in_array($dbFarmRole->ID, $newFarmRolesList)) { $dbFarmRole->Delete(); } } } if ($usedPlatforms[SERVER_PLATFORMS::CLOUDSTACK]) { Modules_Platforms_Cloudstack_Helpers_Cloudstack::farmSave($dbFarm, $dbFarmRolesList); } if ($usedPlatforms[SERVER_PLATFORMS::EC2]) { Modules_Platforms_Ec2_Helpers_Ec2::farmSave($dbFarm, $dbFarmRolesList); } if ($usedPlatforms[SERVER_PLATFORMS::EUCALYPTUS]) { Modules_Platforms_Eucalyptus_Helpers_Eucalyptus::farmSave($dbFarm, $dbFarmRolesList); } $dbFarm->save(); if (!$client->GetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED)) { $client->SetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED, time()); } $this->response->success('Farm successfully saved'); $this->response->data(array('farmId' => $dbFarm->ID)); }
$node_Settings->setAttribute("title", _("Settings")); $node_Settings->setAttribute("type", "settings"); $LangRoot->appendChild($node_Settings); $node = $DOMLang->createElement("node"); $node->setAttribute("title", _("Select interface language")); $node_Settings->appendChild($node); foreach ($display["languages"] as $k => $lng) { $item = $DOMLang->createElement("item"); $item->setAttribute("href", "index.php?lang={$lng["name"]}"); $off = $lng["name"] == LOCALE ? "" : "-off"; $item->nodeValue = "<img src='/images/menu-radio{$off}.gif'> " . $lng["language"]; $node->appendChild($item); } $XMLNav->AddNode($LangRoot, $XMLNav->XML->documentElement); } if (ENABLE_EXTENSION::$PREREGISTRATION && Client::Load($_SESSION['userid'])->GetSettingValue("domain_preorder")) { // // Add languages to menu $DOMLang = new DOMDocument(); $DOMLang->loadXML("<?xml version=\"1.0\" encoding=\"UTF-8\"?><menu></menu>"); $LangRoot = $DOMLang->documentElement; // Settings Node $node_Settings = $DOMLang->createElement("node"); $node_Settings->setAttribute("title", _("My domains")); $node_Settings->setAttribute("type", "domains"); $LangRoot->appendChild($node_Settings); $sep = $DOMLang->createElement("separator"); $node_Settings->appendChild($sep); $node = $DOMLang->createElement("item"); $node->setAttribute("href", "preregister_domain.php"); $node->nodeValue = _("Preregister domain");
public function xBuildAction() { $this->request->defineParams(array('farmId' => array('type' => 'int'), 'roles' => array('type' => 'json'), 'farm' => array('type' => 'json'), 'roleUpdate' => array('type' => 'int'))); $Validator = new Validator(); $cloudFoundryStack = array(); $nginxFound = 0; foreach ($this->getParam('roles') as $role) { $dbRole = DBRole::loadById($role['role_id']); if (!$dbRole->getImageId($role['platform'], $role['cloud_location'])) { throw new Exception(sprintf(_("Role '%s' is not available in %s on %s"), $dbRole->name, $role['platform'], $role['cloud_location'])); } // Validate deployments $appId = $role[Scalr_Role_Behavior::ROLE_DM_APPLICATION_ID]; if ($appId) { $application = Scalr_Dm_Application::init()->loadById($appId); $this->user->getPermissions()->validate($application); if (!$role[Scalr_Role_Behavior::ROLE_DM_REMOTE_PATH]) { throw new Exception(sprintf("Remote path reuired for deployment on role '%s'", $dbRole->name)); } } //-- CloudFoundryStuff if ($dbRole->hasBehavior(ROLE_BEHAVIORS::CF_CLOUD_CONTROLLER)) { $cloudFoundryStack[ROLE_BEHAVIORS::CF_CLOUD_CONTROLLER] = true; } if ($dbRole->hasBehavior(ROLE_BEHAVIORS::CF_DEA)) { $cloudFoundryStack[ROLE_BEHAVIORS::CF_DEA] = true; } if ($dbRole->hasBehavior(ROLE_BEHAVIORS::CF_HEALTH_MANAGER)) { $cloudFoundryStack[ROLE_BEHAVIORS::CF_HEALTH_MANAGER] = true; } if ($dbRole->hasBehavior(ROLE_BEHAVIORS::CF_ROUTER)) { $cloudFoundryStack[ROLE_BEHAVIORS::CF_ROUTER] = true; } if ($dbRole->hasBehavior(ROLE_BEHAVIORS::CF_SERVICE)) { $cloudFoundryStack[ROLE_BEHAVIORS::CF_SERVICE] = true; } if ($dbRole->hasBehavior(ROLE_BEHAVIORS::NGINX)) { $nginxFound++; } //-- End CloudFoundry stuff if ($dbRole->hasBehavior(ROLE_BEHAVIORS::RABBITMQ)) { $role['settings'][DBFarmRole::SETTING_SCALING_MAX_INSTANCES] = $role['settings'][DBFarmRole::SETTING_SCALING_MIN_INSTANCES]; $role['settings'][Scalr_Role_Behavior_RabbitMQ::ROLE_NODES_RATIO] = (int) $role['settings'][Scalr_Role_Behavior_RabbitMQ::ROLE_NODES_RATIO]; if ($role['settings'][Scalr_Role_Behavior_RabbitMQ::ROLE_NODES_RATIO] < 1 || $role['settings'][Scalr_Role_Behavior_RabbitMQ::ROLE_NODES_RATIO] > 100) { throw new Exception(sprintf("Nodes ratio for RabbitMq role '%s' should be between 1 and 100", $dbRole->name)); } } if ($dbRole->hasBehavior(ROLE_BEHAVIORS::MONGODB)) { if ($role['settings'][Scalr_Role_Behavior_MongoDB::ROLE_DATA_STORAGE_ENGINE] == 'ebs') { if ($role['settings'][Scalr_Role_Behavior_MongoDB::ROLE_DATA_STORAGE_EBS_SIZE] < 10 || $role['settings'][Scalr_Role_Behavior_MongoDB::ROLE_DATA_STORAGE_EBS_SIZE] > 1000) { throw new Exception(sprintf("EBS size for mongoDB role should be between 10 and 1000 GB", $dbRole->name)); } } } /* Validate scaling */ $minCount = (int) $role['settings'][DBFarmRole::SETTING_SCALING_MIN_INSTANCES]; if (!$minCount && $minCount != 0) { $minCount = 1; } if ($minCount < 0 || $minCount > 400) { throw new Exception(sprintf(_("Min instances for '%s' must be a number between 1 and 400"), $dbRole->name)); } $maxCount = (int) $role['settings'][DBFarmRole::SETTING_SCALING_MAX_INSTANCES]; if (!$maxCount) { $maxCount = 1; } if ($maxCount < 1 || $maxCount > 400) { throw new Exception(sprintf(_("Max instances for '%s' must be a number between 1 and 400"), $dbRole->name)); } if ($maxCount < $minCount) { throw new Exception(sprintf(_("Max instances should be greater or equal than Min instances for role '%s'"), $dbRole->name)); } if (isset($role['settings'][DBFarmRole::SETTING_SCALING_POLLING_INTERVAL]) && $role['settings'][DBFarmRole::SETTING_SCALING_POLLING_INTERVAL] > 0) { $polling_interval = (int) $role['settings'][DBFarmRole::SETTING_SCALING_POLLING_INTERVAL]; } else { $polling_interval = 2; } if ($polling_interval < 1 || $polling_interval > 50) { throw new Exception(sprintf(_("Polling interval for role '%s' must be a number between 1 and 50"), $dbRole->name)); } /** Validate platform specified settings **/ switch ($role['platform']) { case SERVER_PLATFORMS::EC2: Modules_Platforms_Ec2_Helpers_Ebs::farmValidateRoleSettings($role['settings'], $dbRole->name); Modules_Platforms_Ec2_Helpers_Eip::farmValidateRoleSettings($role['settings'], $dbRole->name); Modules_Platforms_Ec2_Helpers_Elb::farmValidateRoleSettings($role['settings'], $dbRole->name); if ($dbRole->hasBehavior(ROLE_BEHAVIORS::MYSQL)) { if ($role['settings'][DBFarmRole::SETTING_MYSQL_DATA_STORAGE_ENGINE] == MYSQL_STORAGE_ENGINE::EBS) { if ($dbRole->generation != 2) { if ($role['settings'][DBFarmRole::SETTING_AWS_AVAIL_ZONE] == "" || $role['settings'][DBFarmRole::SETTING_AWS_AVAIL_ZONE] == "x-scalr-diff" || stristr($role['settings'][DBFarmRole::SETTING_AWS_AVAIL_ZONE], 'x-scalr-custom')) { throw new Exception(sprintf(_("Requirement for EBS MySQL data storage is specific 'Placement' parameter for role '%s'"), $dbRole->name)); } } } } if ($dbRole->getDbMsrBehavior()) { if ($role['settings'][Scalr_Db_Msr::DATA_STORAGE_ENGINE] == MYSQL_STORAGE_ENGINE::EPH) { if (!$role['settings'][Scalr_Db_Msr::DATA_STORAGE_EPH_DISK]) { throw new Exception(sprintf(_("Ephemeral disk settings is required for role '%s'"), $dbRole->name)); } } } if ($role['settings'][DBFarmRole::SETTING_AWS_AVAIL_ZONE] == 'x-scalr-custom=') { throw new Exception(sprintf(_("Availability zone for role \"%s\" should be selected"), $dbRole->name)); } break; case SERVER_PLATFORMS::RDS: Modules_Platforms_Rds_Helpers_Rds::farmValidateRoleSettings($role['settings'], $dbRole->name); break; case SERVER_PLATFORMS::EUCALYPTUS: Modules_Platforms_Eucalyptus_Helpers_Eucalyptus::farmValidateRoleSettings($role['settings'], $dbRole->name); break; case SERVER_PLATFORMS::CLOUDSTACK: Modules_Platforms_Cloudstack_Helpers_Cloudstack::farmValidateRoleSettings($role['settings'], $dbRole->name); break; case SERVER_PLATFORMS::RACKSPACE: Modules_Platforms_Rackspace_Helpers_Rackspace::farmValidateRoleSettings($role['settings'], $dbRole->name); break; } Scalr_Helpers_Dns::farmValidateRoleSettings($role['settings'], $dbRole->name); } //Validate ClouFoundry stuff if (!empty($cloudFoundryStack)) { if (!$cloudFoundryStack[ROLE_BEHAVIORS::CF_CLOUD_CONTROLLER]) { throw new Exception("CF CloudContoller role required for CloudFoundry stack. Please add All-in-one CF or separate CCHM role to farm"); } if (!$cloudFoundryStack[ROLE_BEHAVIORS::CF_HEALTH_MANAGER]) { throw new Exception("CF HealthManager role required for CloudFoundry stack. Please add All-in-one CF or separate CCHM role to farm"); } if (!$cloudFoundryStack[ROLE_BEHAVIORS::CF_ROUTER]) { throw new Exception("CF Router role required for CloudFoundry stack. Please add All-in-one CF or separate CF Router role to farm"); } if (!$cloudFoundryStack[ROLE_BEHAVIORS::CF_DEA]) { throw new Exception("CF DEA role required for CloudFoundry stack. Please add All-in-one CF or separate CF DEA role to farm"); } if (!$nginxFound) { throw new Exception("Nginx load balancer role required for CloudFoundry stack. Please add it to the farm"); } if ($cloudFoundryStack[ROLE_BEHAVIORS::CF_CLOUD_CONTROLLER] > 1) { throw new Exception("CloudFoundry stack can work only with ONE CF CloudController role. Please leave only one CloudController role in farm"); } if ($cloudFoundryStack[ROLE_BEHAVIORS::CF_HEALTH_MANAGER] > 1) { throw new Exception("CloudFoundry stack can work only with ONE CF HealthManager role. Please leave only one HealthManager role in farm"); } if ($nginxFound > 1) { throw new Exception("CloudFoundry stack can work only with ONE nginx role. Please leave only one nginx role in farm"); } } $client = Client::Load($this->user->getAccountId()); if ($this->getParam('farmId')) { $dbFarm = DBFarm::LoadByID($this->getParam('farmId')); $this->user->getPermissions()->validate($dbFarm); } else { $this->user->getAccount()->validateLimit(Scalr_Limits::ACCOUNT_FARMS, 1); $dbFarm = new DBFarm(); $dbFarm->Status = FARM_STATUS::TERMINATED; } if ($this->getParam('farm')) { $farm = $this->getParam('farm'); $dbFarm->Name = strip_tags($farm['name']); $dbFarm->RolesLaunchOrder = $farm['roles_launch_order']; $dbFarm->Comments = trim(strip_tags($farm['description'])); } if (!$Validator->IsNotEmpty($dbFarm->Name)) { throw new Exception(_("Farm name required")); } $dbFarm->save(); if (!$dbFarm->GetSetting(DBFarm::SETTING_CRYPTO_KEY)) { $dbFarm->SetSetting(DBFarm::SETTING_CRYPTO_KEY, Scalr::GenerateRandomKey(40)); } $usedPlatforms = array(); $dbFarmRolesList = array(); $newFarmRolesList = array(); foreach ($this->getParam('roles') as $role) { if ($role['farm_role_id']) { $update = true; $dbFarmRole = DBFarmRole::LoadByID($role['farm_role_id']); $dbRole = DBRole::loadById($dbFarmRole->RoleID); $role['role_id'] = $dbFarmRole->RoleID; } else { $update = false; $dbRole = DBRole::loadById($role['role_id']); $dbFarmRole = $dbFarm->AddRole($dbRole, $role['platform'], $role['cloud_location'], (int) $role['launch_index']); } if ($dbRole->hasBehavior(ROLE_BEHAVIORS::RABBITMQ)) { $role['settings'][DBFarmRole::SETTING_SCALING_MAX_INSTANCES] = $role['settings'][DBFarmRole::SETTING_SCALING_MIN_INSTANCES]; } if ($dbFarmRole->NewRoleID) { continue; } if ($update) { $dbFarmRole->LaunchIndex = (int) $role['launch_index']; $dbFarmRole->Save(); } $usedPlatforms[$role['platform']] = 1; $oldRoleSettings = $dbFarmRole->GetAllSettings(); foreach ($role['scaling_settings'] as $k => $v) { $dbFarmRole->SetSetting($k, $v); } foreach ($role['settings'] as $k => $v) { $dbFarmRole->SetSetting($k, $v); } /****** Scaling settings ******/ $scalingManager = new Scalr_Scaling_Manager($dbFarmRole); $scalingManager->setFarmRoleMetrics($role['scaling']); //TODO: optimize this code... $this->db->Execute("DELETE FROM farm_role_scaling_times WHERE farm_roleid=?", array($dbFarmRole->ID)); // 5 = Time based scaling -> move to constants if ($role['scaling'][5]) { foreach ($role['scaling'][5] as $scal_period) { $chunks = explode(":", $scal_period['id']); $this->db->Execute("INSERT INTO farm_role_scaling_times SET\n\t\t\t\t\t\tfarm_roleid\t\t= ?,\n\t\t\t\t\t\tstart_time\t\t= ?,\n\t\t\t\t\t\tend_time\t\t= ?,\n\t\t\t\t\t\tdays_of_week\t= ?,\n\t\t\t\t\t\tinstances_count\t= ?\n\t\t\t\t\t", array($dbFarmRole->ID, $chunks[0], $chunks[1], $chunks[2], $chunks[3])); } } /*****************/ /* Update role params */ $dbFarmRole->SetParameters($role['params']); /* End of role params management */ /* Add script options to databse */ $dbFarmRole->SetScripts($role['scripting']); /* End of scripting section */ /* Add services configuration */ $dbFarmRole->SetServiceConfigPresets($role['config_presets']); /* End of scripting section */ Scalr_Helpers_Dns::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); foreach (Scalr_Role_Behavior::getListForFarmRole($dbFarmRole) as $behavior) { $behavior->onFarmSave($dbFarm, $dbFarmRole); } /** * Platfrom specified updates */ if ($dbFarmRole->Platform == SERVER_PLATFORMS::EC2) { Modules_Platforms_Ec2_Helpers_Ebs::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); Modules_Platforms_Ec2_Helpers_Eip::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); Modules_Platforms_Ec2_Helpers_Elb::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); } $dbFarmRolesList[] = $dbFarmRole; $newFarmRolesList[] = $dbFarmRole->ID; } if (!$this->getParam('roleUpdate')) { foreach ($dbFarm->GetFarmRoles() as $dbFarmRole) { if (!$dbFarmRole->NewRoleID && !in_array($dbFarmRole->ID, $newFarmRolesList)) { $dbFarmRole->Delete(); } } } if ($usedPlatforms[SERVER_PLATFORMS::CLOUDSTACK]) { Modules_Platforms_Cloudstack_Helpers_Cloudstack::farmSave($dbFarm, $dbFarmRolesList); } if ($usedPlatforms[SERVER_PLATFORMS::EC2]) { Modules_Platforms_Ec2_Helpers_Ec2::farmSave($dbFarm, $dbFarmRolesList); } if ($usedPlatforms[SERVER_PLATFORMS::EUCALYPTUS]) { Modules_Platforms_Eucalyptus_Helpers_Eucalyptus::farmSave($dbFarm, $dbFarmRolesList); } $dbFarm->save(); if (!$client->GetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED)) { $client->SetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED, time()); } $this->response->success('Farm successfully saved'); $this->response->data(array('farmId' => $dbFarm->ID)); }
Registry::AttachClassObserver(new OperationHistory()); Registry::AttachClassObserver(new ManagedDNSRegistryObserver()); Core::load("Data/JSON/JSON.php"); Core::load("UI/Paging/Paging"); Core::load("UI/Paging/SQLPaging"); Core::load("XMLNavigation", dirname(__FILE__)); Log::Log(sprintf("Client requested: %s", $_SERVER['REQUEST_URI']), E_USER_NOTICE); define("NOW", "client/".str_replace("..","", substr(basename($_SERVER['PHP_SELF']),0, -4))); // Auth try { $Client = Client::Load($_SESSION['userid']); } catch(Exception $e) { } $newhash = $Crypto->Hash("{$Client->Login}:{$Client->Password}:{$_SESSION['sault']}"); $valid = ($newhash == $_SESSION["hash"]); //var_dump($valid); //var_dump($_SESSION); if (!$valid && !stristr($_SERVER['PHP_SELF'], "login.php")) {
function Report(Task $Task) { $Job = $Task->JobObject; // Generate CSV report $report_fname = tempnam(sys_get_temp_dir(), ""); $fp = fopen($report_fname, "w+"); // Put headers fputcsv($fp, array("status", "domain", "period", "registrant", "admin", "tech", "billing", "ns1", "ns2", "extra", "error")); // For each tld take domains and generate report foreach ($Job->tlds as $tld) { // Get all domains in task of $tld $targets = $this->GetTargetsForTld($Task->GetAllTargets(), $tld); foreach ($targets as $Target) { // Format extra data if ($Job->extra[$tld]) { $extra = array(); foreach ($Job->extra[$tld] as $k => $v) { $extra[] = "{$k}: {$v}"; } $extra = join("\n", $extra); } else { $extra = ""; } // Make status if ($Target->status == TargetStatus::OK) { if ($Target->action_result == RegisterDomainAction_Result::INVOICE_GENERATED) { $status = "invoice issued"; } else { if ($Target->action_result == RegisterDomainAction_Result::PENDING) { $status = "pending"; } else { $status = "ok"; } } } else { $status = "fail"; } // Add row to report $row = array($status, $Target->target, $Job->periods[$tld], $Job->contact_list[$tld]["registrant"], $Job->contact_list[$tld]["admin"], $Job->contact_list[$tld]["tech"], $Job->contact_list[$tld]["billing"], $Job->ns_list[0], $Job->ns_list[1], $extra, $Target->fail_reason); fputcsv($fp, $row, ',', '"'); } } fclose($fp); $Mailer = Core::GetPHPSmartyMailerInstance(); // Attach report file $Mailer->ClearAttachments(); $Mailer->AddAttachment($report_fname, "report.csv"); // Send email $Client = Client::Load($Task->userid); mailer_send("bulk_registration.eml", array("Client" => $Client), $Client->Email, $Client->Name); // Clear attachments for future send $Mailer->ClearAttachments(); unlink($report_fname); }
public function OnStartForking() { global $TLDs, $modules_config; Log::Log("Starting 'Renew' cronjob...", E_USER_NOTICE); $db = Core::GetDBInstance(); $RegFactory = RegistryModuleFactory::GetInstance(); $DbDomain = DBDomain::GetInstance(); $this->ThreadArgs = array(); // For each client send notice about expiring domains $sql = "SELECT id FROM users"; foreach ($db->GetAll($sql) as $client_data) { try { $Client = Client::Load($client_data["id"]); $sql = " SELECT d.id, d.name, d.TLD, d.end_date, IF(dd.`key` IS NOT NULL, FROM_UNIXTIME(dd.`value`), DATE_SUB(end_date, INTERVAL 1 DAY)) AS last_renew_date FROM domains d LEFT JOIN domains_data dd ON (dd.domainid = d.id AND dd.`key` = 'RenewalDate') WHERE d.status = '".DOMAIN_STATUS::DELEGATED."' AND d.userid = ? AND (TO_DAYS(end_date) - TO_DAYS(NOW()) BETWEEN 0 AND ?) AND renew_disabled != 1 ORDER BY d.end_date ASC"; $start_days = $Client->GetSettingValue(ClientSettings::EXPIRE_NOTIFY_START_DAYS); $domains_data = $db->GetAll($sql, array($Client->ID, $start_days ? $start_days : 60)); // Send email to client if ($domains_data) { $eml_args = array( "client_name" => $Client->Name, "domains" => array() ); foreach ($domains_data as $domain_data) { $eml_args["domains"][] = array( "name" => "{$domain_data["name"]}.{$domain_data["TLD"]}", "expire_date" => date("Y-m-d", strtotime($domain_data["end_date"])), "last_renew_date" => date("Y-m-d", strtotime($domain_data["last_renew_date"])) ); } mailer_send("bulk_renew_notice.eml", $eml_args, $Client->Email, $Client->Name); } foreach ($domains_data as $domain_data) { $Domain = $DbDomain->Load($domain_data['id']); // Find more then 60 days invoice // Legacy from old notification system. // FIXME: Need to create a better solution to finding unpaid invoices for upgoing renew $dtNearest = date("Y-m-d", $Domain->ExpireDate - 60*24*60*60); $invoiceid = $db->GetOne("SELECT id FROM invoices WHERE userid=? AND itemid=? AND purpose=? AND dtcreated >= ?", array($Domain->UserID, $Domain->ID, INVOICE_PURPOSE::DOMAIN_RENEW, $dtNearest) ); // Generate invoice if (!$invoiceid && !$Domain->RenewDisabled) { $Registry = $RegFactory->GetRegistryByExtension($Domain->Extension); $config = $Registry->GetManifest()->GetSectionConfig(); $period = (int)$config->domain->renewal->min_period; $Domain->Period = $period; $DbDomain->Save($Domain); try { $Invoice = new Invoice(INVOICE_PURPOSE::DOMAIN_RENEW, $Domain->ID, $Domain->UserID); $Invoice->Description = sprintf(_("%s domain name renewal for %s years"), $Domain->GetHostName(), $period); $Invoice->Cancellable = 1; $Invoice->Save(); if ($Invoice->Status == INVOICE_STATUS::PENDING) { $diff_days = ceil(($Domain->ExpireDate - time())/(60*60*24)); Application::FireEvent('DomainAboutToExpire', $Domain, $diff_days); } } catch(Exception $e) { Log::Log("Cannot create renew invoice. Caught: {$e->getMessage()}", E_USER_ERROR); } } } } catch (Exception $e) { Log::Log("Caught: {$e->getMessage()}", E_USER_ERROR); } } /* $supported_extensions = $RegFactory->GetExtensionList(); // For all supported TLDs foreach ($supported_extensions as $ext) { $Registry = $RegFactory->GetRegistryByExtension($ext); $config = $Registry->GetManifest()->GetSectionConfig(); $days = $config->domain->renewal->notifications->period; $biggest_period = (int)$days[0]; // For each notification foreach($days as $expireDays) { $expireDays = (int)$expireDays; $domains = $db->GetAll(" SELECT dom.* FROM domains AS dom LEFT JOIN domains_data AS ext ON dom.id = ext.domainid AND ext.`key` = 'RenewalDate' WHERE dom.TLD = ? AND dom.status = ? AND TO_DAYS(IF ( ext.`key` IS NOT NULL AND TO_DAYS(FROM_UNIXTIME(ext.`value`)) < TO_DAYS(dom.end_date), FROM_UNIXTIME(ext.`value`), dom.end_date )) - TO_DAYS(NOW()) = ? ", array( $ext, DOMAIN_STATUS::DELEGATED, $expireDays )); // For each domain foreach($domains as $domain_info) { try { $Domain = DBDomain::GetInstance()->Load($domain_info['id']); $dtNearest = date("Y-m-d", strtotime($domain_info["end_date"]) - $biggest_period*24*60*60); $invoiceid = $db->GetOne("SELECT id FROM invoices WHERE userid=? AND itemid=? AND purpose=? AND status=? AND dtcreated >= ?", array($Domain->UserID, $Domain->ID, INVOICE_PURPOSE::DOMAIN_RENEW, INVOICE_STATUS::PENDING, $dtNearest) ); // Generate invoice if (!$invoiceid && !$Domain->RenewDisabled) { $period = (int)$config->domain->renewal->min_period; $Domain->Period = $period; DBDomain::GetInstance()->Save($Domain); try { $Invoice = new Invoice(INVOICE_PURPOSE::DOMAIN_RENEW, $Domain->ID, $Domain->UserID); $Invoice->Description = sprintf(_("%s domain name renewal for %s years"), $Domain->GetHostName(), $period); $Invoice->Cancellable = 1; $Invoice->Save(); if ($Invoice->Status == INVOICE_STATUS::PENDING) { $userinfo = $db->GetRow("SELECT * FROM users WHERE id=?", array($Domain->UserID)); //print "send notification and invoice about {$Domain->GetHostName()} to {$userinfo['email']}\n"; $args = array( "domain_name" => $Domain->Name, "extension" => $Domain->Extension, "invoice" => $Invoice, "expDays" => $expireDays, "client" => $userinfo, "renewal_date" => $Domain->RenewalDate ); mailer_send("renew_notice.eml", $args, $userinfo["email"], $userinfo["name"]); Application::FireEvent('DomainAboutToExpire', $Domain, $expireDays); } } catch(Exception $e) { $errmsg = $e->getMessage(); } } else { $userinfo = $db->GetRow("SELECT * FROM users WHERE id=?", array($Domain->UserID)); //print "send notification about {$Domain->GetHostName()} to {$userinfo['email']}\n"; $args = array( "domain_name" => $Domain->Name, "extension" => $Domain->Extension, "expDays" => $expireDays, 'client' => $userinfo, "renewal_date" => $Domain->RenewalDate ); mailer_send("renew_notice.eml", $args, $userinfo["email"], $userinfo["name"]); } } catch (Exception $e) { Log::Log("First domains loop. Caught: ".$e->getMessage(), E_USER_ERROR); } } } } */ // For auto-renew registries the day before expiration date // send to unpaid domains delete command and mark them as expired Log::Log("Going to process expiring tomorrow domains in 'auto-renew' registries", E_USER_NOTICE); $days_before = 1; $del_date = strtotime("+$days_before day"); $delete_report = array(); $domains = $db->GetAll("SELECT dom.id, dom.name, dom.TLD FROM domains AS dom LEFT JOIN domains_data AS ext ON dom.id = ext.domainid AND ext.`key` = 'RenewalDate' LEFT JOIN invoices AS i ON (dom.id = i.itemid AND i.purpose = 'Domain_Renew') WHERE dom.status = ? AND TO_DAYS(IF ( ext.`key` IS NOT NULL AND TO_DAYS(FROM_UNIXTIME(ext.`value`)) < TO_DAYS(dom.end_date), FROM_UNIXTIME(ext.`value`), dom.end_date )) - TO_DAYS(NOW()) = ? AND ((i.status = ? AND TO_DAYS(NOW()) - TO_DAYS(i.dtcreated) <= 60) OR i.status IS NULL)", array(DOMAIN_STATUS::DELEGATED, $days_before, INVOICE_STATUS::PENDING)); foreach ($domains as $domain_info) { try { $Domain = $DbDomain->Load($domain_info["id"]); $Registry = $RegFactory->GetRegistryByExtension($domain_info["TLD"]); $RegistryOptions = $Registry->GetManifest()->GetRegistryOptions(); $auto_renewal = (int)$RegistryOptions->ability->auto_renewal; $scheduled_delete = (int)$RegistryOptions->ability->scheduled_delete; if ($auto_renewal) { if (CONFIG::$AUTO_DELETE) { try { // For 'auto-renew + scheduled delete' send scheduled delete if ($scheduled_delete) { Log::Log(sprintf("Send scheduled delete to domain '%s' at '%s'", $Domain->GetHostName(), date("Y-m-d", $del_date)), E_USER_NOTICE); $Registry->DeleteDomain($Domain, $del_date); } // For 'auto-renew' only send direct delete else { Log::Log(sprintf("Send direct delete to domain '%s'", $Domain->GetHostName()), E_USER_NOTICE); $Registry->DeleteDomain($Domain); } $this->MarkAsExpired($Domain); } catch (Exception $e) { Log::Log(sprintf("Cannot delete expiring domain '%s'. %s", $Domain->GetHostName(), $e->getMessage()), E_USER_ERROR); } } else { Log::Log(sprintf("Domain %s need to be deleted. Send it to admin court", $Domain->GetHostName()), E_USER_NOTICE); // Send to the administrator court $db->Execute("UPDATE domains SET delete_status = ? WHERE id = ?", array(DOMAIN_DELETE_STATUS::AWAIT, $Domain->ID)); $userinfo = $db->GetRow("SELECT * FROM users WHERE id = ?", array($Domain->UserID)); $delete_report[] = array ( "domain" => $Domain->GetHostName(), "user" => "{$userinfo["name"]}({$userinfo["email"]})" ); } } } catch (Exception $e) { Log::Log(sprintf("Cannot load expiring domain '%s'. %s", "{$domain_info["name"]}.{$domain_info["TLD"]}", $e->getMessage()), E_USER_ERROR); } } // Notify admin about expiring domains need to be deleted if ($delete_report) { $args = array( "date" => date("Y-m-d", $del_date), "report" => $delete_report, "confirm_url" => CONFIG::$SITE_URL . "/admin/domains_await_delete_confirmation.php" ); mailer_send("root_domains_await_delete.eml", $args, CONFIG::$EMAIL_ADMIN, CONFIG::$EMAIL_ADMINNAME); } // For all registries mark domain as expired at expiration date Log::Log("Going to process expiring today domains", E_USER_NOTICE); $domains = $db->GetAll("SELECT id, name, TLD FROM domains WHERE TO_DAYS(end_date) = TO_DAYS(NOW()) AND status = ? AND delete_status != ?", array(DOMAIN_STATUS::DELEGATED, DOMAIN_DELETE_STATUS::AWAIT)); foreach ($domains as $domain_info) { try { $Domain = $DbDomain->Load($domain_info["id"]); $this->MarkAsExpired($Domain); } catch (Exception $e) { Log::Log(sprintf("Cannot load expired domain '%s'. %s", "{$domain_info["name"]}.{$domain_info["TLD"]}", $e->getMessage()), E_USER_ERROR); } } // Cleanup database from expired and transferred domains (more then 60 days) Log::Log("Going to cleanup database from transferred and expired domains (more then 60 days)", E_USER_NOTICE); $domains = $db->GetAll(" SELECT * FROM domains WHERE (status=? OR status=?) AND ((TO_DAYS(NOW()-TO_DAYS(end_date)) >= 60) OR (TO_DAYS(NOW()-TO_DAYS(dtTransfer)) >= 60))", array(DOMAIN_STATUS::TRANSFERRED, DOMAIN_STATUS::EXPIRED)); foreach ($domains as $domain_info) { try { Log::Log("Delete {$domain_info["name"]}.{$domain_info["TLD"]} from database. " . "(start_date={$domain_info["start_date"]}, end_date={$domain_info["end_date"]}, status={$domain_info["status"]})", E_USER_NOTICE); $Domain = $DbDomain->Load($domain_info['id']); $DbDomain->Delete($Domain); } catch (Exception $ignore) { Log::Log("Catch ignored exception. {$ignore->getMessage()}", E_USER_NOTICE); } } // Notify customers about low balance Log::Log("Going to notify customers about their low balance", E_USER_NOTICE); $user_ids = $db->GetAll("SELECT userid FROM user_settings WHERE `key` = '".ClientSettings::LOW_BALANCE_NOTIFY."' AND `value` = '1'"); foreach ($user_ids as $id) { try { $id = $id["userid"]; $Client = Client::Load($id); $amount = (float)$db->GetOne("SELECT `total` FROM balance WHERE clientid = ?", array($id)); $min_amount = (float)$Client->GetSettingValue(ClientSettings::LOW_BALANCE_VALUE); if ($amount < $min_amount) { mailer_send("low_balance_notice.eml", array( "client" => array("name" => $Client->Name), "amount" => number_format($min_amount, 2), "currency" => CONFIG::$CURRENCYISO ), $Client->Email, $Client->Name); } } catch (Exception $e) { Log::Log("Cannot notify customer about his low balance. Error: {$e->getMessage()}", E_USER_ERROR); } } }
public function xBuildAction() { $this->request->defineParams(array('farmId' => array('type' => 'int'), 'roles' => array('type' => 'json'), 'farm' => array('type' => 'json'), 'roleUpdate' => array('type' => 'int'), 'launch' => array('type' => 'bool'))); if (!$this->isFarmConfigurationValid($this->getParam('farmId'), $this->getParam('farm'), (array) $this->getParam('roles'))) { if ($this->errors['error_count'] != 0) { $this->response->failure(); $this->response->data(array('errors' => $this->errors)); return; } } $farm = $this->getParam('farm'); $client = Client::Load($this->user->getAccountId()); if ($this->getParam('farmId')) { $dbFarm = DBFarm::LoadByID($this->getParam('farmId')); $this->user->getPermissions()->validate($dbFarm); $this->request->restrictFarmAccess($dbFarm, Acl::PERM_FARMS_MANAGE); $dbFarm->isLocked(); if ($this->getParam('changed') && $dbFarm->changedTime && $this->getParam('changed') != $dbFarm->changedTime) { $userName = '******'; $changed = explode(' ', $this->getParam('changed')); $changedTime = intval($changed[1]); try { $user = new Scalr_Account_User(); $user->loadById($dbFarm->changedByUserId); $userName = $user->getEmail(); } catch (Exception $e) { } $this->response->failure(); $this->response->data(array('changedFailure' => sprintf('%s changed this farm at %s', $userName, Scalr_Util_DateTime::convertTz($changedTime)))); return; } $dbFarm->changedByUserId = $this->user->getId(); $dbFarm->changedTime = microtime(); $bNew = false; } else { $this->request->restrictFarmAccess(null, Acl::PERM_FARMS_MANAGE); $this->user->getAccount()->validateLimit(Scalr_Limits::ACCOUNT_FARMS, 1); $dbFarm = new DBFarm(); $dbFarm->ClientID = $this->user->getAccountId(); $dbFarm->EnvID = $this->getEnvironmentId(); $dbFarm->Status = FARM_STATUS::TERMINATED; $dbFarm->createdByUserId = $this->user->getId(); $dbFarm->createdByUserEmail = $this->user->getEmail(); $dbFarm->changedByUserId = $this->user->getId(); $dbFarm->changedTime = microtime(); $bNew = true; } if ($this->getParam('farm')) { $dbFarm->Name = $this->request->stripValue($farm['name']); $dbFarm->RolesLaunchOrder = $farm['rolesLaunchOrder']; $dbFarm->Comments = $this->request->stripValue($farm['description']); } if (empty($dbFarm->Name)) { throw new Exception(_("Farm name required")); } if ($bNew) { $dbFarm->teamId = is_numeric($farm['teamOwner']) && $farm['teamOwner'] > 0 ? $farm['teamOwner'] : NULL; } else { if ($dbFarm->createdByUserId == $this->user->getId() || $this->user->isAccountOwner() || $this->request->isFarmAllowed($dbFarm, Acl::PERM_FARMS_CHANGE_OWNERSHIP)) { if (is_numeric($farm['owner']) && $farm['owner'] != $dbFarm->createdByUserId) { $user = (new Scalr_Account_User())->loadById($farm['owner']); $dbFarm->createdByUserId = $user->getId(); $dbFarm->createdByUserEmail = $user->getEmail(); // TODO: move to subclass \Farm\Setting\OwnerHistory $history = unserialize($dbFarm->GetSetting(DBFarm::SETTING_OWNER_HISTORY)); if (!is_array($history)) { $history = []; } $history[] = ['newId' => $user->getId(), 'newEmail' => $user->getEmail(), 'changedById' => $this->user->getId(), 'changedByEmail' => $this->user->getEmail(), 'dt' => date('Y-m-d H:i:s')]; $dbFarm->SetSetting(DBFarm::SETTING_OWNER_HISTORY, serialize($history)); } $dbFarm->teamId = is_numeric($farm['teamOwner']) && $farm['teamOwner'] > 0 ? $farm['teamOwner'] : NULL; } } $dbFarm->save(); $governance = new Scalr_Governance($this->getEnvironmentId()); if (!$this->getParam('farmId') && $governance->isEnabled(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE)) { $dbFarm->SetSetting(DBFarm::SETTING_LEASE_STATUS, 'Active'); // for created farm } if (isset($farm['variables'])) { $variables = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_FARM); $variables->setValues(is_array($farm['variables']) ? $farm['variables'] : [], 0, $dbFarm->ID, 0, '', false, true); } if (!$farm['timezone']) { $farm['timezone'] = date_default_timezone_get(); } $dbFarm->SetSetting(DBFarm::SETTING_TIMEZONE, $farm['timezone']); $dbFarm->SetSetting(DBFarm::SETTING_EC2_VPC_ID, $farm['vpc_id']); $dbFarm->SetSetting(DBFarm::SETTING_EC2_VPC_REGION, $farm['vpc_region']); $dbFarm->SetSetting(DBFarm::SETTING_SZR_UPD_REPOSITORY, $farm[DBFarm::SETTING_SZR_UPD_REPOSITORY]); $dbFarm->SetSetting(DBFarm::SETTING_SZR_UPD_SCHEDULE, $farm[DBFarm::SETTING_SZR_UPD_SCHEDULE]); if (!$dbFarm->GetSetting(DBFarm::SETTING_CRYPTO_KEY)) { $dbFarm->SetSetting(DBFarm::SETTING_CRYPTO_KEY, Scalr::GenerateRandomKey(40)); } if ($this->getContainer()->analytics->enabled) { //Cost analytics project must be set for the Farm object $dbFarm->setProject(!empty($farm['projectId']) ? $farm['projectId'] : null); } $virtualFarmRoles = array(); $roles = $this->getParam('roles'); if (!empty($roles)) { foreach ($roles as $role) { if (strpos($role['farm_role_id'], "virtual_") !== false) { $dbRole = DBRole::loadById($role['role_id']); $dbFarmRole = $dbFarm->AddRole($dbRole, $role['platform'], $role['cloud_location'], (int) $role['launch_index'], $role['alias']); $virtualFarmRoles[$role['farm_role_id']] = $dbFarmRole->ID; } } } $usedPlatforms = array(); $dbFarmRolesList = array(); $newFarmRolesList = array(); $farmRoleVariables = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_FARMROLE); if (!empty($roles)) { foreach ($roles as $role) { if ($role['farm_role_id']) { if ($virtualFarmRoles[$role['farm_role_id']]) { $role['farm_role_id'] = $virtualFarmRoles[$role['farm_role_id']]; } $update = true; $dbFarmRole = DBFarmRole::LoadByID($role['farm_role_id']); $dbRole = DBRole::loadById($dbFarmRole->RoleID); $role['role_id'] = $dbFarmRole->RoleID; if ($dbFarmRole->Platform == SERVER_PLATFORMS::GCE) { $dbFarmRole->CloudLocation = $role['cloud_location']; } } else { $update = false; $dbRole = DBRole::loadById($role['role_id']); $dbFarmRole = $dbFarm->AddRole($dbRole, $role['platform'], $role['cloud_location'], (int) $role['launch_index']); } if ($dbRole->hasBehavior(ROLE_BEHAVIORS::RABBITMQ)) { $role['settings'][DBFarmRole::SETTING_SCALING_MAX_INSTANCES] = $role['settings'][DBFarmRole::SETTING_SCALING_MIN_INSTANCES]; } if ($dbFarmRole->NewRoleID) { continue; } if ($update) { $dbFarmRole->LaunchIndex = (int) $role['launch_index']; $dbFarmRole->Alias = $role['alias']; $dbFarmRole->Save(); } $usedPlatforms[$role['platform']] = 1; $oldRoleSettings = $dbFarmRole->GetAllSettings(); // Update virtual farm_role_id with actual value $scripts = (array) $role['scripting']; if (count($virtualFarmRoles) > 0) { array_walk_recursive($scripts, function (&$v, $k) use($virtualFarmRoles) { if (is_string($v)) { $v = str_replace(array_keys($virtualFarmRoles), array_values($virtualFarmRoles), $v); } }); array_walk_recursive($role['settings'], function (&$v, $k) use($virtualFarmRoles) { if (is_string($v)) { $v = str_replace(array_keys($virtualFarmRoles), array_values($virtualFarmRoles), $v); } }); } $dbFarmRole->ClearSettings("chef."); if (!empty($role['scaling_settings']) && is_array($role['scaling_settings'])) { foreach ($role['scaling_settings'] as $k => $v) { $dbFarmRole->SetSetting($k, $v, DBFarmRole::TYPE_CFG); } } foreach ($role['settings'] as $k => $v) { $dbFarmRole->SetSetting($k, $v, DBFarmRole::TYPE_CFG); } /****** Scaling settings ******/ $scalingManager = new Scalr_Scaling_Manager($dbFarmRole); $scalingManager->setFarmRoleMetrics(is_array($role['scaling']) ? $role['scaling'] : array()); //TODO: optimize this code... $this->db->Execute("DELETE FROM farm_role_scaling_times WHERE farm_roleid=?", array($dbFarmRole->ID)); // 5 = Time based scaling -> move to constants if ($role['scaling'][5]) { foreach ($role['scaling'][5] as $scal_period) { $chunks = explode(":", $scal_period['id']); $this->db->Execute("INSERT INTO farm_role_scaling_times SET\n farm_roleid\t\t= ?,\n start_time\t\t= ?,\n end_time\t\t= ?,\n days_of_week\t= ?,\n instances_count\t= ?\n ", array($dbFarmRole->ID, $chunks[0], $chunks[1], $chunks[2], $chunks[3])); } } /*****************/ /* Update role params */ $dbFarmRole->SetParameters((array) $role['params']); /* End of role params management */ /* Add script options to databse */ $dbFarmRole->SetScripts($scripts, (array) $role['scripting_params']); /* End of scripting section */ /* Add services configuration */ $dbFarmRole->SetServiceConfigPresets((array) $role['config_presets']); /* End of scripting section */ /* Add storage configuration */ if (isset($role['storages'])) { if (isset($role['storages']['configs'])) { $dbFarmRole->getStorage()->setConfigs($role['storages']['configs']); } } $farmRoleVariables->setValues(is_array($role['variables']) ? $role['variables'] : [], $dbFarmRole->GetRoleID(), $dbFarm->ID, $dbFarmRole->ID, '', false, true); foreach (Scalr_Role_Behavior::getListForFarmRole($dbFarmRole) as $behavior) { $behavior->onFarmSave($dbFarm, $dbFarmRole); } /** * Platform specified updates */ if ($dbFarmRole->Platform == SERVER_PLATFORMS::EC2) { \Scalr\Modules\Platforms\Ec2\Helpers\EbsHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); \Scalr\Modules\Platforms\Ec2\Helpers\EipHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); \Scalr\Modules\Platforms\Ec2\Helpers\ElbHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); } if (in_array($dbFarmRole->Platform, array(SERVER_PLATFORMS::IDCF, SERVER_PLATFORMS::CLOUDSTACK))) { Scalr\Modules\Platforms\Cloudstack\Helpers\CloudstackHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); } $dbFarmRolesList[] = $dbFarmRole; $newFarmRolesList[] = $dbFarmRole->ID; } } if (!$this->getParam('roleUpdate')) { foreach ($dbFarm->GetFarmRoles() as $dbFarmRole) { if (!$dbFarmRole->NewRoleID && !in_array($dbFarmRole->ID, $newFarmRolesList)) { $dbFarmRole->Delete(); } } } $dbFarm->save(); if (!$client->GetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED)) { $client->SetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED, time()); } if ($this->request->isFarmAllowed($dbFarm, Acl::PERM_FARMS_LAUNCH_TERMINATE) && $this->getParam('launch')) { $this->user->getPermissions()->validate($dbFarm); $dbFarm->isLocked(); Scalr::FireEvent($dbFarm->ID, new FarmLaunchedEvent(true, $this->user->id)); $this->response->success('Farm successfully saved and launched'); } else { $this->response->success('Farm successfully saved'); } $this->response->data(array('farmId' => $dbFarm->ID, 'isNewFarm' => $bNew)); }
public function widgetAccountInfoAction() { require_once APPPATH . "/src/externals/chargify-client/class.ChargifyConnector.php"; require_once APPPATH . "/src/externals/chargify-client/class.ChargifyCreditCard.php"; require_once APPPATH . "/src/externals/chargify-client/class.ChargifyCustomer.php"; require_once APPPATH . "/src/externals/chargify-client/class.ChargifyProduct.php"; require_once APPPATH . "/src/externals/chargify-client/class.ChargifySubscription.php"; $js_module = array(); $clientId = $this->user->getAccountId(); if ($clientId == 0) { array_push($js_module, array('xtype' => 'displayfield', 'fieldLabel' => 'Logged in as', 'value' => 'SCALR ADMIN')); } else { $client = Client::Load($clientId); array_push($js_module, array('xtype' => 'displayfield', 'fieldLabel' => 'Logged in as', 'value' => $client->Email)); // PayPal users: users without Chargify Client ID property if (!$client->GetSettingValue(CLIENT_SETTINGS::BILLING_CGF_CID)) { // Billing type array_push($js_module, array('xtype' => 'displayfield', 'fieldLabel' => 'Billing type', 'value' => 'PayPal (Legacy)')); $sid = $this->db->GetOne("SELECT subscriptionid FROM subscriptions WHERE clientid=? AND status='Active'", array($clientId)); if ($sid) { array_push($js_module, array('xtype' => 'displayfield', 'fieldLabel' => 'Subscription ID', 'value' => $sid)); } $t = strtotime($client->DueDate); if ($t) { array_push($js_module, array('xtype' => 'displayfield', 'fieldLabel' => 'Due date', 'value' => date("M j Y", $t))); } if ($this->db->GetOne("SELECT amount FROM payments WHERE clientid = ?", array($clientId)) == 50) { $package = 'Beta-legacy'; } else { $package = 'Production'; } if ($client->GetSettingValue(CLIENT_SETTINGS::BILLING_PACKAGE) == '3') { $package = 'Mission Critical'; } array_push($js_module, array('xtype' => 'displayfield', 'fieldLabel' => 'Plan', 'value' => $package)); } else { if (!$client->GetSettingValue(CLIENT_SETTINGS::BILLING_CGF_SID)) { array_push($js_module, array('xtype' => 'displayfield', 'fieldLabel' => 'Plan', 'value' => 'Development')); } else { $c = new ChargifyConnector(); try { $subs = $c->getCustomerSubscription($client->GetSettingValue(CLIENT_SETTINGS::BILLING_CGF_SID)); $color = ucfirst($subs->getState()) != 'Active' ? 'red' : 'green'; array_push($js_module, array('xtype' => 'displayfield', 'fieldLabel' => 'Status', 'value' => "<span style='color:{$color}'>" . ucfirst($subs->getState()) . "</span>")); array_push($js_module, array('xtype' => 'displayfield', 'fieldLabel' => 'Billing type', 'value' => ucfirst($subs->getCreditCard()->getCardType()) . " (" . $subs->getCreditCard()->getMaskedCardNumber() . ")")); array_push($js_module, array('xtype' => 'displayfield', 'fieldLabel' => 'Plan', 'value' => ucfirst($subs->getProduct()->getHandle()))); array_push($js_module, array('xtype' => 'displayfield', 'fieldLabel' => 'Due date', 'value' => date("M j Y", strtotime($subs->next_assessment_at)))); array_push($js_module, array('xtype' => 'displayfield', 'fieldLabel' => 'Balance', 'value' => "\$" . number_format($subs->getBalanceInCents() / 100, 2))); } catch (Exception $e) { array_push($js_module, array('xtype' => 'displayfield', 'hideLabel' => true, 'value' => "<span style='color:red;'>Billing information is not available at the moment</span>")); } } } } $this->response->data(array('module' => $js_module)); }
$okmsg = "User edited"; CoreUtils::Redirect("users_view.php"); } } else $err[] = "Username with same login already exists in database! Please select another and try again."; } } if (!$_POST) $display["attr"] = $db->GetRow("SELECT * FROM users WHERE id = ?", array($get_id)); else $display["attr"] = $_POST; $display["id"] = $req_id; $display["Client"] = Client::Load($req_id); $display["attr"]["vat"] = (int)$display["attr"]["vat"] > -1 ? $display["attr"]["vat"] : ''; $display["title"] = "Client » Edit"; $display["packages"] = $db->GetAll("SELECT * FROM packages"); $display["countries"] = $db->GetAll("SELECT * FROM countries"); $display['phone_widget'] = Phone::GetInstance()->GetWidget(); $list = $db->GetAll("SELECT * FROM client_fields"); foreach((array)$list as $v) { $display["additional_fields"][$v["title"]] = $v; if ($display["additional_fields"][$v["title"]]["type"] == "SELECT") { $values = unserialize($v["elements"]); foreach($values[0] as $kk=>$vv) $display["additional_fields"][$v["title"]]["values"][$vv] = $values[1][$kk];