function __construct($zohoCrm)
 {
     $this->zohoCrm = $zohoCrm;
     $this->db = Core::GetDBInstance();
     $this->zohoMappings = new Scalr_Integration_ZohoCrm_CustomFields();
     $this->logger = Logger::getLogger(__CLASS__);
 }
 /**
  * Constructor
  *
  * @param unknown_type $queue_name
  */
 public function __construct($queue_name)
 {
     $this->QueueName = $queue_name;
     $this->DB = Core::GetDBInstance(null, true);
     $this->ReflectionTask = new ReflectionClass("Task");
     $this->LastTaskID = 0;
 }
        public function OnStartForking()
        {            
            Log::Log("Starting 'CleanZombyUsers' cronjob...", E_USER_NOTICE);
            
            $db = Core::GetDBInstance();
            
            $this->ThreadArgs = array();
    
			foreach((array)$db->GetAll("SELECT * FROM users") as $user)
			{ 
				$domains = $db->GetOne("SELECT COUNT(*) FROM domains WHERE status='".DOMAIN_STATUS::DELEGATED."' AND userid='{$user['id']}'");
				$invoices = $db->GetOne("SELECT COUNT(*) FROM invoices WHERE (status='1' OR (status = '0' 
										AND TO_DAYS(NOW())-TO_DAYS(dtcreated)<15)) AND userid='{$user['id']}'
									   ");
				
				if ($domains == 0 && $invoices == 0)
				{
					Log::Log("Found inactive user: {$user['login']} (id = {$user['id']})", E_USER_NOTICE);
					
					$db->Execute("DELETE FROM users WHERE id='{$user['id']}'");	
					$db->Execute("DELETE FROM invoices WHERE userid='{$user['id']}'");
					$db->Execute("DELETE FROM domains WHERE userid='{$user['id']}'");
					$db->Execute("DELETE FROM contacts WHERE userid='{$user['id']}'");
				}
			}
        }
 public static function OnCompleteChangeContactRequest($Contact, $op_type, $approved, $request_ok, $error = null)
 {
     $DB = Core::GetDBInstance();
     $userinfo = $DB->GetRow("SELECT * FROM users WHERE id=?", array($Contact->UserID));
     $args = array("client" => $userinfo, "Contact" => $Contact, "approved" => $approved, "request_ok" => $request_ok, "error" => $error);
     mailer_send("contact_change_request_complete.eml", $args, $userinfo["email"], $userinfo["name"]);
 }
 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);
         }
     }
 }
 public static function doJob($job)
 {
     $db = Core::GetDBInstance(null, true);
     $messageSerializer = new Scalr_Messaging_XmlSerializer();
     $message = $db->GetRow("SELECT server_id, message, id, handle_attempts FROM messages WHERE id=?", array($job->workload()));
     try {
         if ($message['handle_attempts'] >= 3) {
             $db->Execute("UPDATE messages SET status=? WHERE id=?", array(MESSAGE_STATUS::FAILED, $message['id']));
         } else {
             try {
                 $DBServer = DBServer::LoadByID($message['server_id']);
             } catch (Exception $e) {
                 $db->Execute("UPDATE messages SET status=? WHERE id=?", array(MESSAGE_STATUS::FAILED, $message['id']));
                 return;
             }
             if ($DBServer->status == SERVER_STATUS::RUNNING || $DBServer->status == SERVER_STATUS::INIT || $DBServer->status == SERVER_STATUS::IMPORTING || $DBServer->status == SERVER_STATUS::TEMPORARY || $DBServer->status == SERVER_STATUS::PENDING_TERMINATE) {
                 // Only 0.2-68 or greater version support this feature.
                 if ($DBServer->IsSupported("0.2-68")) {
                     $msg = $messageSerializer->unserialize($message['message']);
                     $DBServer->SendMessage($msg);
                 } else {
                     $db->Execute("UPDATE messages SET status=? WHERE id=?", array(MESSAGE_STATUS::UNSUPPORTED, $message['id']));
                 }
             } elseif (in_array($DBServer->status, array(SERVER_STATUS::TERMINATED, SERVER_STATUS::PENDING_TERMINATE))) {
                 $db->Execute("UPDATE messages SET status=? WHERE id=?", array(MESSAGE_STATUS::FAILED, $message['id']));
             }
         }
     } catch (Exception $e) {
         //var_dump($e->getMessage());
     }
 }
        public function StartThread($module_info)
        {   
        	// Reopen database connection in child process
        	$db = Core::GetDBInstance(null, true);
        	
        	// Attach mail notifications on registy events
			Registry::AttachClassObserver(new EmailToRegistrantObserver());
        	Registry::AttachClassObserver(new OperationHistory());
        	Registry::AttachClassObserver(new ManagedDNSRegistryObserver());
			
        	$RegFactory = RegistryModuleFactory::GetInstance();        	
        	$Registry = $RegFactory->GetRegistryByName($module_info["name"], false);
        	$Extensions = $Registry->GetManifest()->GetExtensionList();
        	
            foreach ($Extensions as $ext)
            {
            	try
            	{
            		$r = false;
            		$r = $RegFactory->GetRegistryByExtension($ext, true, true);
            	}
            	catch(Exception $e)
            	{
            		$r = false;
            	}
            	
            	if ($r && $r->GetModuleName() == $Registry->GetModuleName())
            	{
	            	Log::Log(sprintf("Processing %s extension with module %s", $ext, $r->GetModuleName()), E_USER_NOTICE);
    	        	$r->DispatchPendingOperations();
            	}
            }
        }
Beispiel #8
0
 public static function getIdByUrlAndAuth($url, $authInfo)
 {
     $crypto = new Scalr_Util_CryptoTool(MCRYPT_TRIPLEDES, MCRYPT_MODE_CFB, 24, 8);
     $cryptoKey = @file_get_contents(dirname(__FILE__) . "/../../etc/.cryptokey");
     $eAuthInfo = $crypto->encrypt(serialize($authInfo), $cryptoKey);
     return Core::GetDBInstance()->GetOne("SELECT id FROM dm_sources WHERE `url`=? AND auth_info=?", array($url, $eAuthInfo));
 }
 public function __call($method, $args)
 {
     // If observer enabled
     if (!$this->Config || $this->Config->GetFieldByName("IsEnabled")->Value == 0) {
         return;
     }
     $url = $this->Config->GetFieldByName("{$method}NotifyURL");
     if (!$url || $url->Value == '') {
         return;
     }
     $DB = Core::GetDBInstance();
     // Event message
     $message = urlencode($DB->GetOne("SELECT message FROM events WHERE event_id = ?", array($args[0]->GetEventID())));
     $ch = @curl_init();
     // set URL and other appropriate options
     @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
     @curl_setopt($ch, CURLOPT_URL, $url->Value);
     @curl_setopt($ch, CURLOPT_HEADER, false);
     @curl_setopt($ch, CURLOPT_POST, true);
     @curl_setopt($ch, CURLOPT_POSTFIELDS, "event={$method}&message={$message}");
     // grab URL and pass it to the browser
     @curl_exec($ch);
     $error = curl_error();
     if ($error) {
         Logger::getLogger(__CLASS__)->error($error);
     }
     // close cURL resource, and free up system resources
     @curl_close($ch);
 }
 function startChild()
 {
     // Reopen DB connection in child
     $this->db = Core::GetDBInstance(null, true);
     // Reconfigure observers;
     Scalr::ReconfigureObservers();
 }
 public function OnStartForking()
 {
     $db = Core::GetDBInstance();
     // Clear old instances log
     $oldlogtime = mktime(date("H"), date("i"), date("s"), date("m"), date("d") - 10, date("Y"));
     $db->Execute("DELETE FROM logentries WHERE `time` < {$oldlogtime}");
     sleep(60);
     $oldlogtime = date("Y-m-d", mktime(date("H"), date("i"), date("s"), date("m"), date("d") - 20, date("Y")));
     $db->Execute("DELETE FROM scripting_log WHERE `dtadded` < {$oldlogtime}");
     sleep(60);
     $oldlogtime = date("Y-m-d", mktime(date("H"), date("i"), date("s"), date("m") - 6, date("d"), date("Y")));
     $db->Execute("DELETE FROM events WHERE `dtadded` < {$oldlogtime}");
     sleep(60);
     $oldlogtime = date("Y-m-d", mktime(date("H"), date("i"), date("s"), date("m"), date("d") - 30, date("Y")));
     $db->Execute("DELETE FROM messages WHERE type='out' AND status='1' AND `dtlasthandleattempt` < {$oldlogtime}");
     sleep(60);
     //Clear old scripting events
     $year = date("Y");
     $month = date("m", mktime(date("H"), date("i"), date("s"), date("m") - 1, date("d"), date("Y")));
     $db->Execute("DELETE FROM  `farm_role_scripts` WHERE ismenuitem='0' AND event_name LIKE  'CustomEvent-{$year}{$month}%'");
     $db->Execute("DELETE FROM  `farm_role_scripts` WHERE ismenuitem='0' AND event_name LIKE  'APIEvent-{$year}{$month}%'");
     // Rotate syslog
     if ($db->GetOne("SELECT COUNT(*) FROM syslog") > 1000000) {
         $dtstamp = date("dmY");
         $db->Execute("CREATE TABLE syslog_{$dtstamp} (id INT NOT NULL AUTO_INCREMENT,\n                              PRIMARY KEY (id))\n                              ENGINE=MyISAM SELECT dtadded, message, severity, transactionid FROM syslog;");
         $db->Execute("TRUNCATE TABLE syslog");
         $db->Execute("OPTIMIZE TABLE syslog");
         $db->Execute("TRUNCATE TABLE syslog_metadata");
         $db->Execute("OPTIMIZE TABLE syslog_metadata");
         $this->Logger->debug("Log rotated. New table 'syslog_{$dtstamp}' created.");
     }
 }
 public function __call($method, $args)
 {
     // If observer enabled
     if (!$this->Config || $this->Config->GetFieldByName("IsEnabled")->Value == 0) {
         return;
     }
     $enabled = $this->Config->GetFieldByName("{$method}Notify");
     if (!$enabled || $enabled->Value == 0) {
         return;
     }
     $DB = Core::GetDBInstance();
     // Event name
     $name = substr($method, 2);
     // Event message
     $message = $DB->GetOne("SELECT message FROM events WHERE event_id = ?", array($args[0]->GetEventID()));
     $farm_name = $DB->GetOne("SELECT name FROM farms WHERE id=?", array($args[0]->GetFarmID()));
     // Set subject
     if (!$farm_name) {
         $this->Mailer->Subject = "{$name} event notification (FarmID: {$args[0]->GetFarmID()})";
     } else {
         $this->Mailer->Subject = "{$name} event notification (FarmID: {$args[0]->GetFarmID()} FarmName: {$farm_name})";
     }
     // Set body
     $this->Mailer->Body = $message;
     // Send mail
     $res = $this->Mailer->Send();
     if (!$res) {
         Logger::getLogger(__CLASS__)->info("Mail sent to '{$this->Config->GetFieldByName("EventMailTo")->Value}'. Result: {$res}");
     }
 }
 /**
  * Setup db connection.
  * Based on defined options, this method connects to db defined in {@link $dsn}
  * and creates a {@link $table} table if {@link $createTable} is true.
  * @return boolean true if all ok.
  */
 function activateOptions()
 {
     $this->db = Core::GetDBInstance();
     //null, true);
     $this->layout = LoggerReflectionUtils::createObject('LoggerPatternLayoutScalr');
     $this->layout->setConversionPattern($this->getSql());
     $this->canAppend = true;
 }
Beispiel #14
0
 /**
  * SQL Paging
  *
  * @param string $sql SQL Query without LIMIT x,x
  * @param integer $page Current page
  * @param integer $pagesize Page size
  */
 function __construct($sql = null, $page = null, $pagesize = null)
 {
     parent::__construct($page, 0, $pagesize);
     $this->DB = Core::GetDBInstance();
     if ($sql) {
         $this->SetSQLQuery($sql);
     }
 }
 /**
  * @return DBEBSVolume
  * @param string $volumeId
  */
 public static function loadByVolumeId($volumeId)
 {
     $db = Core::GetDBInstance();
     $ebs_info = $db->GetRow("SELECT id FROM ec2_ebs WHERE volume_id = ?", array($volumeId));
     if (!$ebs_info) {
         throw new Exception(sprintf(_("EBS volume ID#%s not found in database"), $volumeId));
     }
     return self::loadById($ebs_info['id']);
 }
 public function __construct(DBServer $DBServer)
 {
     parent::__construct();
     $this->DBServer = $DBServer;
     $r_server = Core::GetDBInstance()->GetRow("SELECT server_id FROM servers WHERE replace_server_id=?", array($DBServer->serverId));
     if ($r_server) {
         $this->replacementDBServer = DBServer::LoadByID($r_server['server_id']);
     }
 }
Beispiel #17
0
 /**
  * Load Client Object by E-mail
  * @param string $email
  * @return Client $Client
  */
 public static function LoadByEmail($email)
 {
     $db = Core::GetDBInstance();
     $clientid = $db->GetOne("SELECT id FROM clients WHERE email=?", array($email));
     if (!$clientid) {
         throw new Exception(sprintf(_("Client with email=%s not found in database"), $email));
     }
     return self::Load($clientid);
 }
 public function OnStartForking()
 {
     $db = Core::GetDBInstance(null, true);
     // selects rows where the snapshot's time has come to create new snapshot.
     $resultset = $db->Execute("SELECT * FROM autosnap_settings \r\n\t\t\t\t\t\tWHERE (UNIX_TIMESTAMP(DATE_ADD(dtlastsnapshot, INTERVAL period HOUR)) < UNIX_TIMESTAMP(NOW())\r\n\t\t\t\t\t\tOR dtlastsnapshot IS NULL)\r\n\t\t\t\t\t\tAND objectid \t!= '0' \r\n\t\t\t\t\t\tAND object_type = ?", array(AUTOSNAPSHOT_TYPE::RDSSnap));
     while ($snapshotsSettings = $resultset->FetchRow()) {
         try {
             $environment = Scalr_Model::init(Scalr_Model::ENVIRONMENT)->loadById($snapshotsSettings['env_id']);
             $AmazonRDSClient = Scalr_Service_Cloud_Aws::newRds($environment->getPlatformConfigValue(Modules_Platforms_Ec2::ACCESS_KEY), $environment->getPlatformConfigValue(Modules_Platforms_Ec2::SECRET_KEY), $snapshotsSettings['region']);
             // Check instance. If instance wasn't found then delete current recrod from settings table
             try {
                 $AmazonRDSClient->DescribeDBInstances($snapshotsSettings['objectid']);
             } catch (Exception $e) {
                 if (stristr($e->getMessage(), "not found") || stristr($e->getMessage(), "not a valid") || stristr($e->getMessage(), "security token included in the request is invalid")) {
                     $db->Execute("DELETE FROM autosnap_settings WHERE id = ?", array($snapshotsSettings['id']));
                 }
                 $this->Logger->error(sprintf(_("RDS instance %s was not found. Auto-snapshot settings for this \r\n\t\t\t\t\t\t\t\tinstance will be deleted. %s."), $snapshotsSettings['objectid'], $e->getMessage()));
                 throw $e;
             }
             // snapshot random unique name
             $snapshotId = "scalr-auto-" . dechex(microtime(true) * 10000) . rand(0, 9);
             try {
                 // Create new snapshot
                 $AmazonRDSClient->CreateDBSnapshot($snapshotId, $snapshotsSettings['objectid']);
                 // update last snapshot creation date in settings
                 $db->Execute("UPDATE autosnap_settings SET last_snapshotid=?, dtlastsnapshot=NOW() WHERE id=?", array($snapshotId, $snapshotsSettings['id']));
                 // create new snapshot record in DB
                 $db->Execute("INSERT INTO rds_snaps_info SET \r\n\t\t\t\t\t\t\tsnapid\t\t= ?,\r\n\t\t\t\t\t\t\tcomment\t\t= ?,\r\n\t\t\t\t\t\t\tdtcreated\t= NOW(),\r\n\t\t\t\t\t\t\tregion\t\t= ?,\r\n\t\t\t\t\t\t\tautosnapshotid = ?", array($snapshotId, _("Auto snapshot"), $snapshotsSettings['region'], $snapshotsSettings['id']));
             } catch (Exception $e) {
                 $this->Logger->warn(sprintf(_("Cannot create RDS snapshot: %s."), $e->getMessage()));
             }
             // Remove old snapshots
             if ($snapshotsSettings['rotate'] != 0) {
                 $oldSnapshots = $db->GetAll("SELECT * FROM rds_snaps_info WHERE autosnapshotid = ? ORDER BY id ASC", array($snapshotsSettings['id']));
                 if (count($oldSnapshots) > $snapshotsSettings['rotate']) {
                     while (count($oldSnapshots) > $snapshotsSettings['rotate']) {
                         // takes the oldest snapshot ...
                         $deletingSnapshot = array_shift($oldSnapshots);
                         try {
                             // and deletes it from amazon and from DB
                             $AmazonRDSClient->DeleteDBSnapshot($deletingSnapshot['snapid']);
                             $db->Execute("DELETE FROM rds_snaps_info WHERE id = ?", array($deletingSnapshot['id']));
                         } catch (Exception $e) {
                             if (stristr($e->getMessage(), "not found") || stristr($e->getMessage(), "not a valid")) {
                                 $db->Execute("DELETE FROM rds_snaps_info WHERE id = ?", array($deletingSnapshot['id']));
                             }
                             $this->Logger->error(sprintf(_("DBsnapshot %s for RDS instance %s was not found \r\n\t\t\t\t\t\t\t\t\t\t\t\tand cannot be deleted . %s."), $deletingSnapshot['snapid'], $snapshotsSettings['objectid'], $e->getMessage()));
                         }
                     }
                 }
             }
         } catch (Exception $e) {
             $this->Logger->warn(sprintf(_("Cannot create snapshot for RDS Instance %s. %s"), $snapshotsSettings['objectid'], $e->getMessage()));
         }
     }
 }
 /**
  * Constructor
  *
  * @param string $search
  */
 function __construct($search = false)
 {
     parent::__construct();
     $this->DB = Core::GetDBInstance();
     $this->SearchString = $search;
     $this->XML = new DOMDocument();
     $this->XML->loadXML("<?xml version=\"1.0\" encoding=\"UTF-8\"?><menu></menu>");
     $this->XML->formatOutput = true;
     $this->XPath = new DOMXPath($this->XML);
 }
Beispiel #20
0
 public function onFarmSave(DBFarm $dbFarm, DBFarmRole $dbFarmRole)
 {
     try {
         $account = Scalr_Account::init()->loadById($dbFarm->ClientID);
         if (!$account->isFeatureEnabled(Scalr_Limits::FEATURE_CHEF)) {
             $dbFarmRole->ClearSettings("chef.");
             return false;
         }
         $db = Core::GetDBInstance();
         $runListId = $dbFarmRole->GetSetting(self::ROLE_CHEF_RUNLIST_ID);
         $attributes = $dbFarmRole->GetSetting(self::ROLE_CHEF_ATTRIBUTES);
         $checksum = $dbFarmRole->GetSetting(self::ROLE_CHEF_CHECKSUM);
         $chefRoleName = $dbFarmRole->GetSetting(self::ROLE_CHEF_ROLE_NAME);
         $chefServerId = $dbFarmRole->GetSetting(self::ROLE_CHEF_SERVER_ID);
         // Need to remove chef role if chef was disabled for current farmrole
         if (!$runListId && $chefRoleName) {
             $this->removeChefRole($chefServerId, $chefRoleName);
             $dbFarmRole->ClearSettings("chef.");
             return true;
         }
         if ($runListId) {
             $runListInfo = $this->db->GetRow("SELECT chef_server_id, runlist FROM services_chef_runlists WHERE id=?", array($runListId));
             $newChefServerId = $runListInfo['chef_server_id'];
             if ($newChefServerId != $chefServerId && $chefServerId) {
                 // Remove role from old server
                 $this->removeChefRole($chefServerId, $chefRoleName);
                 $createNew = true;
             }
             if (!$chefServerId) {
                 $createNew = true;
             }
             $chefServerInfo = $this->db->GetRow("SELECT * FROM services_chef_servers WHERE id=?", array($runListInfo['chef_server_id']));
             $chefServerInfo['auth_key'] = $this->getCrypto()->decrypt($chefServerInfo['auth_key'], $this->cryptoKey);
             $chefClient = Scalr_Service_Chef_Client::getChef($chefServerInfo['url'], $chefServerInfo['username'], trim($chefServerInfo['auth_key']));
             $roleName = "scalr-{$dbFarmRole->ID}";
             $setSettings = false;
             if ($createNew) {
                 $chefClient->createRole($roleName, $roleName, json_decode($runListInfo['runlist']), json_decode($attributes), $runListInfo['chef_environment']);
                 $setSettings = true;
             } else {
                 if ($dbFarmRole->GetSetting(self::ROLE_CHEF_CHECKSUM) != md5("{$runListInfo['runlist']}.{$attributes}")) {
                     $chefClient->updateRole($roleName, $roleName, json_decode($runListInfo['runlist']), json_decode($attributes), $runListInfo['chef_environment']);
                     $setSettings = true;
                 }
             }
             if ($setSettings) {
                 $dbFarmRole->SetSetting(self::ROLE_CHEF_ROLE_NAME, $roleName);
                 $dbFarmRole->SetSetting(self::ROLE_CHEF_SERVER_ID, $runListInfo['chef_server_id']);
                 $dbFarmRole->SetSetting(self::ROLE_CHEF_CHECKSUM, md5("{$runListInfo['runlist']}.{$attributes}"));
             }
         }
     } catch (Exception $e) {
         throw new Exception("Chef settings error: {$e->getMessage()} ({$e->getTraceAsString()})");
     }
 }
 function startChild()
 {
     // Reopen DB connection in child
     $this->db = Core::GetDBInstance(null, true);
     // Reconfigure observers;
     Scalr::ReconfigureObservers();
     $this->snmpWatcher = new SNMPWatcher();
     foreach (array_keys($this->watchers) as $watcher_name) {
         $this->snmpWatcher->SetOIDs($watcher_name);
     }
 }
Beispiel #22
0
 /**
  * Constructor
  * @param $DBFarmRole
  * @return void
  */
 function __construct(DBFarmRole $DBFarmRole)
 {
     $this->db = Core::GetDBInstance();
     $this->dbFarmRole = $DBFarmRole;
     $this->logger = Logger::getLogger(__CLASS__);
     $role_metrics = $this->db->Execute("SELECT id, metric_id FROM farm_role_scaling_metrics WHERE farm_roleid = ?", array($this->dbFarmRole->ID));
     $this->farmRoleMetrics = array();
     while ($role_metric = $role_metrics->FetchRow()) {
         $this->farmRoleMetrics[$role_metric['metric_id']] = Scalr_Model::init(Scalr_Model::SCALING_FARM_ROLE_METRIC)->loadById($role_metric['id']);
     }
 }
 public function OnPaid(Invoice $Invoice, AbstractPaymentModule $payment_module = null)
 {
     $db = Core::GetDBInstance();
     if (CONFIG::$PREPAID_MODE && $Invoice->Purpose != INVOICE_PURPOSE::BALANCE_DEPOSIT) {
         // In prepaid mode skip emails about invoices
         return;
     }
     $userinfo = $db->GetRow("SELECT * FROM users WHERE id=?", array($Invoice->UserID));
     $args = array("login" => $userinfo["login"], "Invoice" => $Invoice, "client" => $userinfo);
     mailer_send("invoice_paid.eml", $args, $userinfo["email"], $userinfo["name"]);
 }
        public function OnStartForking()
        {            
            Log::Log("Starting 'LogRotate' cronjob...", E_USER_NOTICE);
            
            $db = Core::GetDBInstance();
            
            $this->ThreadArgs = array();
    
			if (CONFIG::$ROTATE_LOG_EVERY > 0)
				$db->Execute("DELETE FROM syslog WHERE TO_DAYS(NOW())-TO_DAYS(dtadded) > ?", array(CONFIG::$ROTATE_LOG_EVERY));
        }
 public function OnStartForking()
 {
     $db = Core::GetDBInstance();
     $roles = $db->GetAll("SELECT * FROM roles_queue WHERE `action` = 'remove'");
     foreach ($roles as $role) {
         try {
             $dbRole = DBRole::loadById($role['role_id']);
             $dbRole->remove(true);
         } catch (Exception $e) {
             print $e->getMessage() . "\n";
         }
     }
 }
Beispiel #26
0
 function __construct($api_version)
 {
     $class_name = "EppDrs_Api_Service{$api_version}";
     $class_file = dirname(__FILE__) . "/class.Service{$api_version}.php";
     if (!class_exists($class_name) && file_exists($class_file)) {
         require_once $class_file;
     }
     if (!class_exists($class_name)) {
         throw new Exception("Cannot load service implementation class for API version {$api_version}");
     }
     $this->ServiceImpl = new $class_name();
     $this->Db = Core::GetDBInstance();
 }
Beispiel #27
0
 public function __construct()
 {
     $this->Db = Core::GetDBInstance();
     $args = func_get_args();
     if (count($args) == 1 && is_numeric($args[0])) {
         $this->constructLoad($args[0]);
     } else {
         if (count($args) == 3) {
             $this->constructCreate($args[0], $args[1], $args[2]);
         } else {
             throw new Exception("Constructor is not applicable by such arguments");
         }
     }
 }
 /**
  * 
  * @param integer $id
  * @return DBDNSZone
  */
 public static function loadById($id)
 {
     $db = Core::GetDBInstance();
     $zoneinfo = $db->GetRow("SELECT * FROM dns_zones WHERE id=?", array($id));
     if (!$zoneinfo) {
         throw new Exception(sprintf(_("DNS zone ID#%s not found in database"), $id));
     }
     $DBDNSZone = new DBDNSZone($id);
     foreach (self::$FieldPropertyMap as $k => $v) {
         if (isset($zoneinfo[$k])) {
             $DBDNSZone->{$v} = $zoneinfo[$k];
         }
     }
     return $DBDNSZone;
 }
        public function OnStartForking()
        {            
            $DbBalance = DBBalance::GetInstance();
            $db = Core::GetDBInstance();
            			
			// Get packages. Order by their commercial value.
            $sql = "SELECT SUM(discount)/COUNT(packageid) AS cv, packageid AS id, min_domains, min_balance  
				FROM discounts d 
				INNER JOIN packages p ON p.id = d.packageid
				WHERE p.min_domains IS NOT NULL OR p.min_balance IS NOT NULL
				GROUP BY packageid ORDER BY cv";
            $packages = (array)$db->GetAll($sql);
            foreach ($packages as &$pkg)
            {
            	$pkg["min_balance"] = (float)$pkg["min_balance"];
            	$pkg["min_domains"] = (int)$pkg["min_domains"];
            } 
            
            if ($packages)
            {
				foreach((array)$db->GetAll("SELECT id FROM users WHERE package_fixed != 1") as $user)
				{ 
					$Balance = $DbBalance->LoadClientBalance($user["id"]);
					$num_domains = (int)$db->GetOne("
						SELECT COUNT(*) 
						FROM domains 
						WHERE userid = ? AND status NOT IN (
							'".DOMAIN_STATUS::EXPIRED."', 
							'".DOMAIN_STATUS::TRANSFER_FAILED."', 
							'".DOMAIN_STATUS::REJECTED."', 
							'".DOMAIN_STATUS::REGISTRATION_FAILED."',
							'".DOMAIN_STATUS::APPLICATION_RECALLED."')
					", array($user["id"]));
					
					$newpackageid = 0;
					foreach ($packages as $package)
					{
						if (($package["min_domains"] && $num_domains > $package["min_domains"])
							|| ($package["min_balance"] && $Balance->Total > $package["min_balance"]))
						{
							$newpackageid = $package["id"];
						}
					}
					
					$db->Execute("UPDATE users SET packageid=? WHERE id=?", array($newpackageid, $user["id"]));
				}
            }
        }
Beispiel #30
0
 public function getLocations()
 {
     try {
         $envId = Scalr_UI_Request::getInstance()->getEnvironment()->id;
     } catch (Exception $e) {
         return array();
     }
     //Eucalyptus locations defined by client. Admin cannot get them
     $db = Core::GetDBInstance();
     $locations = $db->GetAll("SELECT DISTINCT(`group`) as `name` FROM client_environment_properties WHERE `name` = ? AND env_id = ?", array(self::API_URL, $envId));
     $retval = array();
     foreach ($locations as $location) {
         $retval[$location['name']] = "Openstack / {$location['name']}";
     }
     return $retval;
 }