No direct script access allowed'); /** * @framework iResponse Framework * @version 1.0 * @author Amine Idrissi * @date 2018 * @name AmazonAccounts.php */ # core use Aws\Credentials\Credentials; use Exception; use GuzzleHttp\Exception\ClientException; use IR\Core\Application as Application; # mvc use IR\Mvc\Controller as Controller; # models use IR\App\Models\Admin\AwsAccount as AwsAccount; use IR\App\Models\Admin\AwsAccountProcess as AwsAccountProcess; # http use IR\Http\Request as Request; # helpers use IR\App\Helpers\Authentication as Authentication; use IR\App\Helpers\Page as Page; use IR\App\Helpers\DataTable as DataTable; use IR\App\Helpers\Permissions as Permissions; use IR\App\Models\Admin\MtaServer; use IR\App\Models\Admin\ServerApis as ServerApis; use IR\App\Models\Admin\ServerProvider as ServerProvider; # exceptions use IR\Framework\Exceptions\Types\PageException as PageException; use IR\Framework\Utils\Types\Strings; use IR\App\Api\Api as Api; // use IR\App\Api\Openstack; use IR\App\Api\System; use IR\App\Models\Admin\AwsProcess; use IR\App\SSH\SSH; use IR\App\SSH\SSHKeyAuthentication; use IR\App\SSH\SSHPasswordAuthentication; use OpenStack\Common\Error\BadResponseError; use phpseclib\Crypt\RSA; use OpenStack\OpenStack; # AWS use Aws\Ec2\Ec2Client; use Aws\Result; use IR\Framework\Exceptions\Types\SystemException; class Accountapi extends Controller { /** * @app * @readwrite */ protected $app; /** * @app * @readwrite */ protected $authenticatedUser; /** * @name init * @description initializing proccess before the action method executed * @once * @protected */ public function init() { # set the current application to a local variable $this->app = Application::getCurrent(); # connect to the database $this->app->database('system')->connect(); # check for authentication if (!Authentication::isUserAuthenticated()) { Page::redirect($this->app->http->request->getBaseURL() . RDS . 'auth' . RDS . 'login.' . DEFAULT_EXTENSION); } # check users roles Authentication::checkUserRoles(); # get the authenticated user $this->authenticatedUser = Authentication::getAuthenticatedUser(); } /** * @name index * @description the index action * @before init * @after closeConnections,checkForMessage */ public function index() { # check for permissions $access = Permissions::checkForAuthorization($this->authenticatedUser, __CLASS__, __FUNCTION__); if ($access == false) { throw new PageException('Access Denied !', 403); } Page::redirect($this->app->http->request->getBaseURL() . RDS . 'isps' . RDS . 'lists.html'); } /** * @name lists * @description the lists action * @before init * @after closeConnections,checkForMessage */ public function lists() { # check for permissions $access = Permissions::checkForAuthorization($this->authenticatedUser, __CLASS__, __FUNCTION__); if ($access == false) { throw new PageException('Access Denied !', 403); } # set the menu item to active $this->masterView->set('menu_admin_isps', true); $this->masterView->set('menu_admin_isps_lists', true); # get the data from the database $list = ServerApis::all(ServerApis::FETCH_ARRAY, array(), array('id', 'account_name', 'api_provider'), 'id', 'ASC'); # get all the columns names $columns = array('id', 'account_name', 'api_provider'); # set the list into the template data system $this->pageView->set('list', $list); # set the columns list into the template data system $this->pageView->set('columns', $columns); } /** * @name add * @description the add action * @before init * @after closeConnections,checkForMessage */ public function add() { # check for permissions $access = Permissions::checkForAuthorization($this->authenticatedUser, __CLASS__, __FUNCTION__); if ($access == false) { throw new PageException('Access Denied !', 403); } # set the menu item to active $this->masterView->set('menu_admin_api', true); $this->masterView->set('menu_admin_api_add', true); # get status list // $status = Status::all(true, array(), array('id', 'name'), 'id', 'ASC'); $providers = ServerProvider::all(ServerProvider::FETCH_ARRAY, array(), array('id', 'name'), 'id', 'ASC'); # set the list into the template data system // $this->pageView->set('status', $status); $this->pageView->set('providers', $providers); } private function getEc2Client($accountId, $region) { $account = ServerApis::first(ServerApis::FETCH_ARRAY, array('id = ?', $accountId)); $credentials = new Credentials($account['api_key'], $account['access_key']); $ec2Client = new Ec2Client([ 'region' => $region, 'version' => '2016-11-15', 'credentials' => $credentials ]); return $ec2Client; } /** * @name amazonaws * @description manage amazon aws instances * @before init * @after closeConnections,checkForMessage */ public function amazonaws() { # check for permissions $access = Permissions::checkForAuthorization($this->authenticatedUser, __CLASS__, __FUNCTION__); if ($access == false) { throw new PageException('Access Denied !', 403); } # check if the request is not AJAX request then return to index if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) { # prevent layout to be displayed // $this->setShowMasterView(false); // $this->setShowPageView(false); # retreive $data = $this->app->http->request->retrieve(Request::ALL, Request::POST); if (count($data)) { // // \ma\mfw\output\PrintWriter::printValue($data); # add user data $data['user'] = []; $data['user']['id'] = $this->authenticatedUser->getId(); $accountId = $data['accountId']; $region = $data['region']; $system = $data['os']; $account = ServerApis::first(ServerApis::FETCH_ARRAY, array('id = ?', $accountId)); $data['accessKey'] = $account['access_key']; $data['secretKey'] = $account['secret_key']; # Manage the Operation System // $centos = array( // "us-east-1" => "ami-3830342f", // "us-east-2" => "ami-03237966", // "us-west-1" => "ami-09f6d94c", // "us-west-2" => "ami-39e5ae09", // "eu-central-1" => "ami-86d4e59b", // "ca-central-1" => "ami-bbb408df", // "eu-west-1" => "ami-442d9933", // "eu-west-2" => "ami-dcbaafb8", // "eu-west-3" => "ami-011aad7c", // "sa-east-1" => "ami-3d14bd20", // ); // $amazon = array( // "us-east-1" => "ami-0b69ea66ff7391e80", // "us-east-2" => "ami-00c03f7f7f2ec15c3", // "us-west-1" => "ami-0245d318c6788de52", // "us-west-2" => "ami-04b762b4289fba92b", // "eu-central-1" => "ami-00aa4671cbf840d82", // "ca-central-1" => "ami-085edf38cedbea498", // "eu-west-1" => "ami-0ce71448843cb18a1", // "eu-west-2" => "ami-00a1270ce1e007c27", // "eu-west-3" => "ami-03b4b78aae82b30f1", // "sa-east-1" => "ami-0a1f49a762473adbd", // ); // if ($system == "centos" && $centos[$region] == "") { // die(json_encode(array("started" => false, "message" => "The operation system not found on Centos ! please choose the custom ID"))); // } else if ($system == "amazon" && $amazon[$region] == "") { // die(json_encode(array("started" => false, "message" => "The operation system not found on AMAZON ! please choose the custom ID"))); // } else { // $data['os'] = ($system == "centos") ? $centos[$region] : $amazon[$region]; // } if (empty($data['os'])) { die(json_encode(array("started" => false, "message" => "Select Select OS"))); } if (empty($data['type'])) { die(json_encode(array("started" => false, "message" => "Select Instance type"))); } # log file path // $logFile = INSTALLATIONS_LOGS_PATH . 'aws_' . $accountId . '.log'; // # process path // $processFile = INSTALLATIONS_LOGS_PATH . 'aws_' . $accountId . '.process'; # empty the log file // System::executeCommand("> " . $logFile); // System::executeCommand("echo 'Started' > " . $processFile); // $data['logpath'] = $logFile; // $data['processpath'] = $processFile; // # write the form into a file // $fileDirectory = TRASH_PATH . DS . 'aws'; // $fileName = 'amazon_' . Strings::generateRandomText(20, true, true, true, false) . '.aws'; # convert the form data into json to store it into a file so that the mailing script will read it // $jsonVersionOfDrop = json_encode($data, JSON_UNESCAPED_UNICODE); // $this->_generateSSHKey('amazon'); $ec2Client = $this->getEc2Client($accountId, $region); $keyPairName = $region . 'aws-amazon-server-key-' . $accountId; $this->_amazonKey($keyPairName, $ec2Client); $securityGroupName = ''; $result = $this->_createAmazonSecurityGroup($ec2Client, $region); if ($result['status']) { $securityGroupName = $result['securityGroupName']; $maxCount = empty($data['count']) ? 1 : intval($data['count']); $VolumeSize = empty($data['volumeSize']) ? 20 : intval($data['volumeSize']); $VolumeType = empty($data['VolumeType']) ? 'standard' : $data['VolumeType']; $result = $this->_launchInstance($ec2Client, $data['os'], $data['type'], $keyPairName, $securityGroupName, $maxCount, $VolumeSize, $VolumeType); } // print_r($output); // exit; // new Aws // $result = $ec2Client->createKeyPair(array( // 'KeyName' => $keyPairName // )); // if ($jsonVersionOfDrop != '' && file_put_contents($fileDirectory . DS . $fileName, $jsonVersionOfDrop)) { // # execute the job that takes care of sent proccess // chdir(JOBS_PATH . DS . 'aws-java-sample'); // $pid = exec("nohup java -Dfile.encoding=UTF8 -jar aws-manager.jar create_proccess " . $fileDirectory . DS . $fileName . ' > ' . $logFile . ' 2> ' . $logFile . ' &'); // die(json_encode(array("started" => true))); // } else { // die(json_encode(array("type" => "error", "message" => "Error occured while trying to create the drop file !"))); // } } // Gettign the new values from DB and display them ... // $list = $this->app->database('system')->execute("SELECT * FROM admin.aws WHERE accountid = '$accountId' AND region = '$region';", true); // $resalutTable = array(); // foreach ($list as $row) { // $resalutTable[] = array('id' => $row['id'], 'label' => $row['awsid'], 'ipv4' => $row['ip'], 'status' => $row['status_id']); // } die(json_encode($result)); } else { # set the menu item to active $this->masterView->set('menu_admin_api', true); $this->masterView->set('menu_admin_api_add', true); // Manage APIs $accounts = ServerApis::all(ServerApis::FETCH_ARRAY, array('api_provider = ?', 'Amazon'), array('id', 'account_name'), 'id', 'ASC'); # set the list into the template data system $this->pageView->set('accounts', $accounts); } } /** * @name proccess * @description the proccess action * @before init * @after closeConnections,checkForMessage */ public function proccess() { # check for permissions $access = Permissions::checkForAuthorization($this->authenticatedUser, __CLASS__, __FUNCTION__); if ($access == false) { throw new PageException('Access Denied !', 403); } if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) { // $this->setShowMasterView(false); // $this->setShowPageView(false); # retreive $data = $this->app->http->request->retrieve(Request::ALL, Request::POST); $log = ''; $status = 0; $logFile = TRASH_PATH . DS . 'logs' . DS . 'installations' . DS . 'aws_' . $data['accountId'] . '.log'; $statusFile = TRASH_PATH . DS . 'logs' . DS . 'installations' . DS . 'aws_' . $data['accountId'] . '.process'; if (file_exists($logFile)) { $content = file_get_contents($logFile); $log = str_replace(PHP_EOL, '
', $content); } if (file_exists($statusFile)) { $content = file_get_contents($statusFile); $status = trim(trim($content, PHP_EOL)); } die(json_encode(array("status" => $status, "log" => $log))); } } /** * @name getawsinstances * @description manage amazon aws instances * @before init * @after closeConnections,checkForMessage */ public function getawsinstances() { # check for permissions $access = Permissions::checkForAuthorization($this->authenticatedUser, __CLASS__, __FUNCTION__); if ($access == false) { throw new PageException('Access Denied !', 403); } # check if the request is not AJAX request then return to index if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) { # prevent layout to be displayed // $this->setShowMasterView(false); // $this->setShowPageView(false); # retreive $data = $this->app->http->request->retrieve(Request::ALL, Request::POST); if (count($data)) { new Result; # add user data $data['user'] = []; $data['user']['id'] = $this->authenticatedUser->getId(); $region = $data['region']; $accountId = $data['accountId']; $ec2Client = $this->getEc2Client($accountId, $region); $result = $ec2Client->describeInstances([ 'MaxResults' => 500, // 'Filters' => [ // [ // 'Name' => 'instance-state-code', // 'Value' => [0, 16] // ] // ] ]); // print_r($result->toArray()); $expr = 'Reservations[*].Instances[*].{id: InstanceId, InstanceId: InstanceId, ImageId:ImageId, InstanceType:InstanceType, ipv4: PublicIpAddress, PublicDnsName: PublicDnsName, KeyName: KeyName, State: State.Name}'; // print_r($result); // exit; // $result = ($result->search('Reservations[0].Instances')); // print_r($result); $_result = ($result->search($expr)); $result = []; if ($_result) { foreach ($_result as $row) { foreach ($row as $r) { if ($r['State'] != 'terminated') $result[] = $r; } } } // print_r($result); // exit; // // ::factory(array( // // 'credentials' => [ // // 'key' => $account['access_key'], // // 'secret' => $account['secret_key'], // // ], // // 'region' => $region, // (e.g., us-east-1), // // 'version' => '2016-11-15' // // )); // // $result = $ec2Client->describeInstances(); // echo '
';
                // print_r($result);
                // exit;
                // $region = $data['region'];

                // $list = $this->app->database('system')->execute("SELECT * FROM admin.aws WHERE accountid = '$accountId' AND region = '$region';");
                // $resalutTable = array();

                // foreach ($list as $row) {
                //     $resalutTable[] = array('id' => $row['id'], 'label' => $row['awsid'], 'ipv4' => $row['ip'], 'status' => $row['status_id']);
                // }

                die(json_encode(array("resaults" => $result, 'result' => $result)));
            }
        } else {
            # set the menu item to active 
            $this->masterView->set('menu_admin_api', true);
            $this->masterView->set('menu_admin_api_add', true);

            // Manage APIs 
            $accounts = ServerApis::all(ServerApis::FETCH_ARRAY, array('api_provider = ?', 'Amazon'), array('id', 'account_name'), 'id', 'ASC');

            # set the list into the template data system 
            $this->pageView->set('accounts', $accounts);
        }
    }

    private function _getImages()
    {
        $file = BASE_PATH . DS . 'storage' . DS . 'aws-os.csv';
        $lines = explode("\n", file_get_contents($file));
        $headers = str_getcsv(array_shift($lines));
        $data = array();
        foreach ($lines as $line) {

            $row = array();

            foreach (str_getcsv($line) as $key => $field)
                $row[$headers[$key]] = $field;

            $row = array_filter($row);

            $data[] = $row;
        }
        return $data;
    }

    /**
     * @name getawsinstances
     * @description manage amazon aws instances
     * @before init
     * @after closeConnections,checkForMessage
     */
    public function getawsimages()
    {
        # check for permissions
        $access = Permissions::checkForAuthorization($this->authenticatedUser, __CLASS__, __FUNCTION__);

        if ($access == false) {
            throw new PageException('Access Denied !', 403);
        }
        # check if the request is not AJAX request then return to index 
        if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) {
            # retreive
            $data = $this->app->http->request->retrieve(Request::ALL, Request::POST);

            if (count($data)) {
                // new Result;
                # add user data 
                $data['user'] = [];
                $data['user']['id'] = $this->authenticatedUser->getId();
                $region = $data['region'];
                // $accountId = $data['accountId'];
                $result = [];
                $data = $this->_getImages();
                $dd = [];
                foreach ($data as $d) {
                    // if (!in_array($d['CentOS-Version'], $dd)) {
                    //     $dd[] = $d['CentOS-Version'];
                    $result[$d['Region']][] = ['version' => $d['CentOS-Version'], 'amiId' => $d['Ami-ID']];
                    // }
                }
                // $ec2Client = $this->getEc2Client($accountId, $region);
                // $result = $ec2Client->DescribeImages();
                // $expr = 'Reservations[*].Instances[*].{id: InstanceId,
                //     InstanceId: InstanceId,
                //     ImageId:ImageId,
                //     InstanceType:InstanceType,
                //     ipv4: PublicIpAddress,
                //     PublicDnsName: PublicDnsName,
                //     KeyName: KeyName,
                //     State: State.Name}';
                // var_dump($result);
                // exit;
                // $result = ($result->search('Reservations[0].Instances'));
                // print_r($result);
                // $_result = ($result->search($expr));
                // $result = [];
                // if ($_result) {
                //     foreach ($_result as $row) {
                //         $result[] = $row[0];
                //     }
                // }
                $res = $result[$region];
                $_res = [];
                foreach ($res as $i => $r) {
                    if (!in_array($r['version'], $_res)) {
                        $_res[] = $r['version'];
                    } else {
                        unset($res[$i]);
                    }
                }
                // array_unique($res);
                die(json_encode(array("resaults" => $res, 'result' => $res)));
            }
        } else {
            # set the menu item to active 
            $this->masterView->set('menu_admin_api', true);
            $this->masterView->set('menu_admin_api_add', true);

            // Manage APIs 
            $accounts = ServerApis::all(ServerApis::FETCH_ARRAY, array('api_provider = ?', 'Amazon'), array('id', 'account_name'), 'id', 'ASC');

            # set the list into the template data system 
            $this->pageView->set('accounts', $accounts);
        }
    }

    /**
     * @name cloud
     * @description manage start stop actions
     * @before init
     * @after closeConnections,checkForMessage
     */
    public function cloud()
    {
        # check if the request is not AJAX request then return to index 
        if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) {
            # prevent layout to be displayed
            // $this->setShowMasterView(false);
            // $this->setShowPageView(false);

            # retreive
            $data = $this->app->http->request->retrieve(Request::ALL, Request::POST);

            if (count($data)) {

                # add user data 
                $data['user'] = [];
                $data['user']['id'] = $this->authenticatedUser->getId();

                $accountId = $data['accountId'];
                $region = $data['region'];

                if ($data['keepAlive'] == "" || $data['keepDown'] == "") {
                    die(json_encode(array("started" => false, "message" => "Please insert start and stop delai ")));
                }

                # insert proccess
                $proccess = new AwsProcess();
                $proccess->setAws_ids($data['aws']);
                $proccess->setStart($data['keepAlive']);
                $proccess->setStop($data['keepDown']);
                $proccess->setStatus("STOPING");

                $data['cloud'] = $proccess->save();

                $aws = json_decode($data['aws']);
                $data['accountIds'] = implode(";", $aws);

                # log file path 
                $logFile = TRASH_PATH  . DS . 'logs' . DS . 'installations' . DS . 'aws_' . $accountId . '.log';
                # process  path 
                $processFile = TRASH_PATH  . DS . 'logs' . DS . 'installations' . DS . 'aws_' . $accountId . '.process';

                # empty the log file 
                System::executeCommand("> " . $logFile);
                System::executeCommand("echo 'Started' > " . $processFile);

                $data['logpath'] = $logFile;
                $data['processpath'] = $processFile;

                # write the form into a file
                $fileDirectory = TRASH_PATH . DS . 'aws';
                $fileName = 'amazon_' . Strings::generateRandomText(20, true, true, true, false) . '.aws';

                # convert the form data into json to store it into a file so that the mailing script will read it 
                $jsonVersionOfDrop = json_encode($data, JSON_UNESCAPED_UNICODE);

                if ($jsonVersionOfDrop != '' && file_put_contents($fileDirectory . DS . $fileName, $jsonVersionOfDrop)) {
                    # execute the job that takes care of sent proccess
                    chdir(JOBS_PATH . DS . 'aws-java-sample');
                    $pid = exec("nohup java -Dfile.encoding=UTF8 -jar aws-manager.jar cloud " . $fileDirectory . DS . $fileName . ' > ' . $logFile . ' 2> ' . $logFile . ' &');
                    die(json_encode(array("started" => true)));
                } else {
                    die(json_encode(array("type" => "error", "message" => "Error occured while trying to create the drop file !")));
                }

                //$id = $this->app->database('system')->"INSERT INTO admin.aws_proccesses (aws_ids,start,stop,status) VALUES ('qqq' , 5 , 5, 'starting')" , false ,null, true , 1);
                // \ma\mfw\output\PrintWriter::printValue($id);
            }
        }
    }

    /**
     * @name removeAWS
     * @description Remove AWS Intance
     * @before init
     * @after closeConnections,checkForMessage
     */
    public function removeAWS()
    {
        # check if the request is not AJAX request then return to index 
        if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) {
            # prevent layout to be displayed
            // $this->setShowMasterView(false);
            // $this->setShowPageView(false);

            # retreive
            $data = $this->app->http->request->retrieve(Request::ALL, Request::POST);

            if (count($data)) {

                # add user data 
                $data['user'] = [];
                $data['user']['id'] = $this->authenticatedUser->getId();
                # add user data 
                $data['api-link'] = $this->app->http->request->getBaseURL() . RDS . 'api';

                $instanceIds = json_decode($data['instance'], true);
                // $aws = json_decode($data['aws']);
                $ips = $data['ips'];
                $accountId = $data['accountId'];
                // $accountId = $data['accountId'];
                // $account = ServerApis::first(ServerApis::FETCH_ARRAY, array('id = ?', $accountId));

                // $data['accessKey'] = $account['access_key'];
                // $data['secretKey'] = $account['secret_key'];
                // $data['accountIds'] = implode(";", $aws);
                $data['region'] = $data['region'];
                if ($instanceIds) {
                    $ec2Client = $this->getEc2Client($accountId, $data['region']);
                    $result = $ec2Client->TerminateInstances(array(
                        'InstanceIds' => $instanceIds,
                    ));
                }
                // $data['region'] = $data['region'];

                # log file path 
                // $logFile = TRASH_PATH  . DS . 'logs' . DS . 'installations' . DS . 'aws_' . $accountId . '.log';
                // # process  path 
                // $processFile = TRASH_PATH  . DS . 'logs' . DS . 'installations' . DS . 'aws_' . $accountId . '.process';

                // # empty the log file 
                // System::executeCommand("> " . $logFile);
                // System::executeCommand("echo 'Started' > " . $processFile);

                // $data['logpath'] = $logFile;
                // $data['processpath'] = $processFile;

                // # write the form into a file
                // $fileDirectory = TRASH_PATH . DS . 'aws';
                // $fileName = 'amazon_' . Strings::generateRandomText(20, true, true, true, false) . '.aws';

                // # convert the form data into json to store it into a file so that the mailing script will read it 
                // $jsonVersionOfDrop = json_encode($data, JSON_UNESCAPED_UNICODE);

                // if ($jsonVersionOfDrop != '' && file_put_contents($fileDirectory . DS . $fileName, $jsonVersionOfDrop)) {
                //     $awsString = implode(";", $aws);
                //     chdir(JOBS_PATH . DS . 'aws-java-sample');
                //     $pid = exec("nohup java -Dfile.encoding=UTF8 -jar aws-manager.jar remove_proccess " . $fileDirectory . DS . $fileName . ' > ' . $logFile . ' 2> ' . $logFile . ' &');
                // } else {
                //     die(json_encode(array("type" => "error", "message" => "Error occured while trying to create the drop file !")));
                // }

                foreach ($ips as $ip) {
                    $serverAccount = MtaServer::first(MtaServer::FETCH_ARRAY, array('main_ip = ?', trim($ip)), array('id', 'name', 'main_ip', 'ssh_username', 'ssh_password', 'ssh_port'));

                    if ($serverAccount != null && count($serverAccount)) {
                        $serverID = $serverAccount['id'];
                        $server = new MtaServer(array("id" => $serverID));
                        $res = $this->app->database('system')->query()->from('admin.mta_servers')->where('id = ?', $serverID)->delete();

                        # update domains 
                        // $this->app->database('system')->execute("UPDATE admin.domains SET ip_id = 0 , domain_status = 'Available' WHERE ip_id IN (SELECT id FROM admin.ips WHERE server_id = $serverID)");
                        // $this->app->database('system')->execute("DELETE FROM admin.ips WHERE server_id = $serverID");
                        $this->app->database('system')->execute("DELETE FROM admin.servers_vmtas WHERE mta_server_id = $serverID");
                    }

                    $this->app->database('system')->execute("DELETE FROM admin.aws WHERE ip = '$ip';");
                }

                die(json_encode(array("started" => true)));
            }
        }
    }

    /**
     * @name rebootAWS
     * @description Reboot AWS Intance
     * @before init
     * @after closeConnections,checkForMessage
     */
    public function rebootAWS()
    {
        # check if the request is not AJAX request then return to index 
        if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) {
            # prevent layout to be displayed
            // $this->setShowMasterView(false);
            // $this->setShowPageView(false);

            # retreive
            $data = $this->app->http->request->retrieve(Request::ALL, Request::POST);

            if (count($data)) {

                # add user data 
                $data['user'] = [];
                $data['user']['id'] = $this->authenticatedUser->getId();
                # add user data 
                $data['api-link'] = $this->app->http->request->getBaseURL() . RDS . 'api';

                $instanceIds = json_decode($data['instance'], true);
                // $aws = json_decode($data['aws']);
                $ips = $data['ips'];
                $accountId = $data['accountId'];
                // $accountId = $data['accountId'];
                // $account = ServerApis::first(ServerApis::FETCH_ARRAY, array('id = ?', $accountId));

                // $data['accessKey'] = $account['access_key'];
                // $data['secretKey'] = $account['secret_key'];
                // $data['accountIds'] = implode(";", $aws);
                $result = [];
                $data['region'] = $data['region'];
                if ($instanceIds) {
                    $ec2Client = $this->getEc2Client($accountId, $data['region']);
                    $result = $ec2Client->RebootInstances(array(
                        'InstanceIds' => $instanceIds,
                    ));
                    $result = $result->toArray();
                }

                die(json_encode(array("started" => true, 'result' => $result)));
            }
        }
    }



    /**
     * @name UpdateServerAWS
     * @description update servers ips
     * @before init
     * @after closeConnections,checkForMessage
     */
    public function UpdateServerAWS()
    {
        # check if the request is not AJAX request then return to index 
        if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) {
            # prevent layout to be displayed
            // $this->setShowMasterView(false);
            // $this->setShowPageView(false);

            # retreive
            $data = $this->app->http->request->retrieve(Request::ALL, Request::POST);

            if (count($data)) {

                # add user data 
                $data['user'] = [];
                $data['user']['id'] = $this->authenticatedUser->getId();
                # add user data 
                $data['api-link'] = $this->app->http->request->getBaseURL() . RDS . 'api';

                $instances = json_decode($data['instance']);
                $aws = json_decode($data['aws']);
                $ips = $data['ips'];
                $accountId = $data['accountId'];
                $accountId = $data['accountId'];
                $account = ServerApis::first(ServerApis::FETCH_ARRAY, array('id = ?', $accountId));
                //// \ma\mfw\output\PrintWriter::printValue($data);

                $data['accessKey'] = $account['access_key'];
                $data['secretKey'] = $account['secret_key'];
                $data['accountIds'] = implode(";", $aws);
                $data['region'] = $data['region'];
                $updated = 0;

                foreach ($aws as $ip) {
                    $_server = MtaServer::first(MtaServer::FETCH_ARRAY, array('main_ip = ?', $ip), array('id', 'name', 'main_ip', 'ssh_username', 'ssh_password', 'ssh_port'));
                    $serverAWS = $this->app->database('system')->execute("SELECT * FROM admin.aws WHERE awsid ='" . $ip . "';", true);
                    $mainIP = trim($serverAWS[0]['ip']);
                    $id = trim($serverAWS[0]['serverid']);
                    $server = new MtaServer(array("id" => $id));
                    $server->setMainIp($mainIP);
                    if ($_server != null  && count($_server)) {
                        $result = $server->update();
                    } else {
                        $result = $server->insert();
                    }
                }
                if ($updated > 0) {
                    die(json_encode(array("resaults" => 1)));
                } else {
                    die(json_encode(array("resaults" =>  0)));
                }


                die(json_encode(array("resaults" => 'Done')));
            }
        }
    }

    /**
     * @name get
     * @description gets a $_SERVER value in a secure way 
     * @access static
     * @param string $key
     * @return mixed
     */

    public static function getGlobalServer($key)
    {
        if (array_key_exists($key, $_SERVER)) {
            if (!filter_var($_SERVER[$key], FILTER_SANITIZE_STRING)) {
                return NULL;
            }
            return $_SERVER[$key];
        } else {
            return NULL;
        }
    }

    /**
     * @name stopAWS
     * @description stop AWS Intance
     * @before init
     * @after closeConnections,checkForMessage
     */
    public function stopAWS()
    {
        # check if the request is not AJAX request then return to index 
        if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) {
            # prevent layout to be displayed
            // $this->setShowMasterView(false);
            // $this->setShowPageView(false);

            # retreive
            $data = $this->app->http->request->retrieve(Request::ALL, Request::POST);

            if (count($data)) {

                # add user data 
                $data['user'] = [];
                $data['user']['id'] = $this->authenticatedUser->getId();
                # add user data 
                $data['api-link'] = $this->app->http->request->getBaseURL() . RDS . 'api';

                $instanceIds = json_decode($data['instance'], true);
                if ($instanceIds) {
                    // $aws = json_decode($data['aws']);
                    // $ips = $data['ips'];
                    // $instanceIds = $data['accountId'];
                    $accountId = $data['accountId'];
                    // $account = ServerApis::first(ServerApis::FETCH_ARRAY, array('id = ?', $accountId));

                    // $data['accessKey'] = $account['access_key'];
                    // $data['secretKey'] = $account['secret_key'];
                    // $data['accountIds'] = implode(";", $aws);
                    $data['region'] = $data['region'];
                    // print_r($data);
                    // print_r($instanceIds);
                    // exit;
                    $ec2Client = $this->getEc2Client($accountId, $data['region']);
                    $result = $ec2Client->stopInstances(array(
                        'InstanceIds' => $instanceIds,
                    ));
                } else {
                    die(json_encode(array("type" => "error", "message" => "Please select instances")));
                }
                # log file path 
                // $logFile = TRASH_PATH  . DS . 'logs' . DS . 'installations' . DS . 'aws_' . $accountId . '.log';
                // # process  path 
                // $processFile = TRASH_PATH  . DS . 'logs' . DS . 'installations' . DS . 'aws_' . $accountId . '.process';

                // # empty the log file 
                // System::executeCommand("> " . $logFile);
                // System::executeCommand("echo 'Started' > " . $processFile);

                // $data['logpath'] = $logFile;
                // $data['processpath'] = $processFile;

                // # write the form into a file
                // $fileDirectory = TRASH_PATH . DS . 'aws';
                // $fileName = 'amazon_' . Strings::generateRandomText(20, true, true, true, false) . '.aws';

                // # convert the form data into json to store it into a file so that the mailing script will read it 
                // $jsonVersionOfDrop = json_encode($data, JSON_UNESCAPED_UNICODE);

                // if ($jsonVersionOfDrop != '' && file_put_contents($fileDirectory . DS . $fileName, $jsonVersionOfDrop)) {
                //     $awsString = implode(";", $aws);
                //     chdir(JOBS_PATH . DS . 'aws-java-sample');
                //     $pid = exec("nohup java -Dfile.encoding=UTF8 -jar aws-manager.jar stop_proccess " . $fileDirectory . DS . $fileName . ' > ' . $logFile . ' 2> ' . $logFile . ' &');
                // } else {
                //     die(json_encode(array("type" => "error", "message" => "Error occured while trying to create the drop file !")));
                // }

                die(json_encode(array("started" => true)));
            }
        }
    }

    /**
     * @name stopAWS
     * @description stop AWS Intance
     * @before init
     * @after closeConnections,checkForMessage
     */
    public function startAWS()
    {
        # check if the request is not AJAX request then return to index 
        if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) {
            # prevent layout to be displayed
            // $this->setShowMasterView(false);
            // $this->setShowPageView(false);

            # retreive
            $data = $this->app->http->request->retrieve(Request::ALL, Request::POST);

            if (count($data)) {

                # add user data 
                $data['user'] = [];
                $data['user']['id'] = $this->authenticatedUser->getId();
                # add user data 
                $data['api-link'] = $this->app->http->request->getBaseURL() . RDS . 'api';

                $instanceIds = json_decode($data['instance'], true);
                if ($instanceIds) {


                    // $aws = json_decode($data['aws']);
                    // $ips = $data['ips'];
                    // $accountId = $data['accountId'];
                    $accountId = $data['accountId'];
                    // $account = ServerApis::first(ServerApis::FETCH_ARRAY, array('id = ?', $accountId));

                    // $data['accessKey'] = $account['access_key'];
                    // $data['secretKey'] = $account['secret_key'];
                    // $data['accountIds'] = implode(";", $aws);
                    // $data['region'] = $data['region'];
                    $data['region'] = $data['region'];
                    $ec2Client = $this->getEc2Client($accountId, $data['region']);
                    $result = $ec2Client->startInstances(array(
                        'InstanceIds' => $instanceIds,
                    ));
                } else {
                    die(json_encode(array("type" => "error", "message" => "Please select instances")));
                }
                # log file path 
                // $logFile = TRASH_PATH  . DS . 'logs' . DS . 'installations' . DS . 'aws_' . $accountId . '.log';
                // # process  path 
                // $processFile = TRASH_PATH  . DS . 'logs' . DS . 'installations' . DS . 'aws_' . $accountId . '.process';

                // # empty the log file 
                // System::executeCommand("> " . $logFile);
                // System::executeCommand("echo 'Started' > " . $processFile);

                // $data['logpath'] = $logFile;
                // $data['processpath'] = $processFile;

                // # write the form into a file
                // $fileDirectory = TRASH_PATH . DS . 'aws';
                // $fileName = 'amazon_' . Strings::generateRandomText(20, true, true, true, false) . '.aws';

                // # convert the form data into json to store it into a file so that the mailing script will read it 
                // $jsonVersionOfDrop = json_encode($data, JSON_UNESCAPED_UNICODE);

                // if ($jsonVersionOfDrop != '' && file_put_contents($fileDirectory . DS . $fileName, $jsonVersionOfDrop)) {
                //     $awsString = implode(";", $aws);
                //     chdir(JOBS_PATH . DS . 'aws-java-sample');
                //     $pid = exec("nohup java -Dfile.encoding=UTF8 -jar aws-manager.jar start_proccess " . $fileDirectory . DS . $fileName . ' > ' . $logFile . ' 2> ' . $logFile . ' &');
                // } else {
                //     die(json_encode(array("type" => "error", "message" => "Error occured while trying to create the drop file !")));
                // }

                die(json_encode(array("started" => true)));
            }
        }
    }

    /**
     * @name addServersAws
     * @description Add Aws Insatnces into DB
     * @before init
     * @after closeConnections,checkForMessage
     */
    public function addServersAws()
    {
        # check if the request is not AJAX request then return to index 
        if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) {

            # prevent layout to be displayed
            // $this->setShowMasterView(false);
            // $this->setShowPageView(false);

            # retreive
            $data = $this->app->http->request->retrieve(Request::ALL, Request::POST);

            if (count($data)) {
                # add user data 
                $data['user'] = [];
                $data['user']['id'] = $this->authenticatedUser->getId();
                $instancesName = $data['serversNames'];
                $index = 0;

                $ipsSelected = json_decode($data['ips']);
                $instances = json_decode($data['instance'], true);
                $servers = json_decode($data['servers'], true);
                $keyPath = "/home/.keys/";
                $shellFileRoot = BASH_SCRIPT_PATH . DS . 'aws' . DS . "addServerRoot.sh";
                $shellFileEc2 = BASH_SCRIPT_PATH . DS . 'aws' . DS . "addServerEc.sh";
                $shellFileEc2Ubuntu = BASH_SCRIPT_PATH . DS . 'aws' . DS . "ubuntuRoot.sh";

                foreach ($servers as $server) {
                    if (in_array($server['InstanceId'], $instances)) {
                        // $instance = $this->app->database('system')->execute("SELECT * FROM admin.aws WHERE ip = '$ip';", true);
                        $id = $server['id'];
                        $ip = $server['ipv4'];
                        $accoountId = $data['accountId'];
                        $instanceIp = $server['ipv4'];
                        $password  = $data['password'];
                        // $password = $data['password'];
                        $image = $server['ImageId'];
                        $region = $data['region'];
                        // $dns = $instance[0]['dns'];
                        if (!defined('HETZNER_SSH_KEY_PATH')) {
                            define('HETZNER_SSH_KEY_PATH', '/home/keys/');
                        }
                        $insatceKey = HETZNER_SSH_KEY_PATH . $server['KeyName'] . ".pem";
                        // $ipDash = str_replace('.', "-", $instanceIp);

                        $account = $accont = ServerApis::first(ServerApis::FETCH_ARRAY, array('id = ?', $accoountId));
                        $cmd = "";
                        $_data = $this->_getImages();
                        $osUser = 'root';
                        // print_r($server['ImageId']);
                        // exit;
                        foreach ($_data as $row) {
                            if ($row['Ami-ID'] == $server['ImageId']) {
                                switch ($row['CentOS-Version']) {
                                    case 'CentOS Linux 7':
                                    case 'CentOS Linux 6':
                                        $osUser = 'centos';
                                        break;
                                    case 'Ubuntu 18.04 LTS':
                                        $osUser = 'ubuntu';
                                        break;
                                }
                            }
                        }
                        // if ($dns == "" || $dns == null) {
                        // $instageinfo = "root@ec2-" . $ipDash . "." . $region . ".compute.amazonaws.com";
                        $instageinfo = $osUser . "@" . $server['ipv4'];

                        if ($osUser == 'ubuntu') {
                            // $instageinfo = "ec2-user@" . $server['ipv4'];
                            // $cmd = "sh " . $shellFileEc2 . " " . $insatceKey . " " . $instageinfo . " " . $password;
                            $cmd = "sh " . $shellFileEc2Ubuntu . ' "' . $insatceKey . '" "' . $instageinfo . '" "' . $password . '"';
                        } else {
                            // $cmd = "sh " . $shellFileRoot . " " . $insatceKey . " " . $instageinfo . " " . $password;
                            $cmd = "sh " . $shellFileRoot . ' "' . $insatceKey . '" "' . $instageinfo . '" "' . $password . '"';
                        }
                        // } else {
                        //     $instageinfo = "root@" . $dns;
                        //     if (strlen($image) == 21) {
                        //         $instageinfo = "ec2-user@" . $dns;
                        //         // $cmd = "sh " . $shellFileEc2 . " " . $insatceKey . " " . $instageinfo . " " . $password;
                        //         $cmd = "sh " . $shellFileEc2 . ' "' . $insatceKey . '" "' . $instageinfo . '" "' . $password . '"';
                        //     } else {
                        //         // $cmd = "sh " . $shellFileRoot . " " . $insatceKey . " " . $instageinfo . " " . $password;
                        //         $cmd = "sh " . $shellFileRoot . ' "' . $insatceKey . '" "' . $instageinfo . '" "' . $password . '"';
                        //     }
                        // }
                        // // \ma\mfw\output\PrintWriter::printValue($cmd);
                        exec($cmd, $output);
                        // echo $cmd;
                        // var_dump($cmd);
                        // var_dump($output);
                        // die("done");
                        $rand = Strings::generateRandomText(3, true, false, true, false);
                        $index = $index + 1;
                        $serverName = $instancesName . "_" . $index;
                        $instancesServerName = ($instancesName != "") ? $serverName : $region . "_" . $accont['account_name'] . "_" . $rand;

                        # insert case
                        $_server = MtaServer::first(MtaServer::FETCH_ARRAY, array('main_ip = ?', $ip), array('id', 'name', 'main_ip', 'ssh_username', 'ssh_password', 'ssh_port'));
                        # insert case
                        if ($_server != null  && count($_server)) {
                            $server = new MtaServer(array('id' => $_server['id']));
                        } else {
                            $server = new MtaServer();
                        }
                        $server->setStatus('Activated');
                        $server->setProviderId($account['provider_id']);

                        $server->setName("AWS_" . $instancesServerName);
                        $server->setHostName("");
                        $server->setMainIp($ip);
                        $server->setSshUsername("root");
                        $server->setSshPassword($password);

                        $server->setSshPort(22);
                        $server->setOldSshPort(22);
                        $server->setSshLoginType('user-pass');
                        $server->setExpirationDate(date("Y-m-d"));
                        $server->setCreatedBy(intval($this->app->utils->arrays->get($data['user'], 'id', 1)));
                        $server->setCreatedDate(date("Y-m-d"));
                        $server->setLastUpdatedBy(intval($this->app->utils->arrays->get($data['user'], 'id', 1)));
                        $server->setLastUpdatedDate(date("Y-m-d"));


                        if ($_server != null  && count($_server)) {
                            $result = $server->update();
                        } else {
                            $result = $server->insert();
                        }

                        // Update AWS Status 
                        // $this->app->database('system')->execute("UPDATE admin.aws SET status_id = 2,serverId = " . $result . " WHERE id = " . $id);

                        if ($result > -1) {
                            $message = "Record stored succesfully !";
                            $messageFlag = 'success';
                        }
                    }
                }
                die(json_encode(array("resaults" => 'Done', 'cmd' => $cmd)));
                // // \ma\mfw\output\PrintWriter::printValue("ddd");
            }
        }
    }

    /**
     * @name addServersPassAws
     * @description Add Aws Insatnces into DB
     * @before init
     * @after closeConnections,checkForMessage
     */
    public function addServersPassAws()
    {
        # check if the request is not AJAX request then return to index 
        if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) {

            # prevent layout to be displayed
            // $this->setShowMasterView(false);
            // $this->setShowPageView(false);

            # retreive
            $data = $this->app->http->request->retrieve(Request::ALL, Request::POST);

            if (count($data)) {
                # add user data 
                $data['user'] = [];
                $data['user']['id'] = $this->authenticatedUser->getId();
                $instancesName = $data['serversNames'];
                $index = 0;

                $ipsSelected = json_decode($data['ips']);
                $instances = json_decode($data['instance'], true);
                $servers = json_decode($data['servers'], true);
                $keyPath = "/home/.keys/";
                $shellFileRoot = BASH_SCRIPT_PATH . DS . 'aws' . DS . "addServerRoot.sh";
                $shellFileEc2 = BASH_SCRIPT_PATH . DS . 'aws' . DS . "addServerEc.sh";
                $shellFileEc2Ubuntu = BASH_SCRIPT_PATH . DS . 'aws' . DS . "ubuntuRoot.sh";

                foreach ($servers as $server) {
                    if (in_array($server['InstanceId'], $instances)) {
                        // $instance = $this->app->database('system')->execute("SELECT * FROM admin.aws WHERE ip = '$ip';", true);
                        $id = $server['id'];
                        $ip = $server['ipv4'];
                        $accoountId = $data['accountId'];
                        $instanceIp = $server['ipv4'];
                        $password  = $data['password'];
                        // $password = $data['password'];
                        $image = $server['ImageId'];
                        $region = $data['region'];
                        // $dns = $instance[0]['dns'];
                        if (!defined('HETZNER_SSH_KEY_PATH')) {
                            define('HETZNER_SSH_KEY_PATH', '/home/keys/');
                        }
                        $insatceKey = HETZNER_SSH_KEY_PATH . $server['KeyName'] . ".pem";
                        // $ipDash = str_replace('.', "-", $instanceIp);

                        $account = $accont = ServerApis::first(ServerApis::FETCH_ARRAY, array('id = ?', $accoountId));
                        $cmd = "";
                        $_data = $this->_getImages();
                        $osUser = 'root';
                        // print_r($server['ImageId']);
                        // exit;
                        foreach ($_data as $row) {
                            if ($row['Ami-ID'] == $server['ImageId']) {
                                switch ($row['CentOS-Version']) {
                                    case 'CentOS Linux 7':
                                    case 'CentOS Linux 6':
                                        $osUser = 'centos';
                                        break;
                                    case 'Ubuntu 18.04 LTS':
                                        $osUser = 'ubuntu';
                                        break;
                                }
                            }
                        }
                        // if ($dns == "" || $dns == null) {
                        // $instageinfo = "root@ec2-" . $ipDash . "." . $region . ".compute.amazonaws.com";
                        $instageinfo = $osUser . "@" . $server['ipv4'];

                        if ($osUser == 'ubuntu') {
                            // $instageinfo = "ec2-user@" . $server['ipv4'];
                            // $cmd = "sh " . $shellFileEc2 . " " . $insatceKey . " " . $instageinfo . " " . $password;
                            $cmd = "sh " . $shellFileEc2Ubuntu . ' "' . $insatceKey . '" "' . $instageinfo . '" "' . $password . '"';
                        } else {
                            // $cmd = "sh " . $shellFileRoot . " " . $insatceKey . " " . $instageinfo . " " . $password;
                            $cmd = "sh " . $shellFileRoot . ' "' . $insatceKey . '" "' . $instageinfo . '" "' . $password . '"';
                        }
                        // } else {
                        //     $instageinfo = "root@" . $dns;
                        //     if (strlen($image) == 21) {
                        //         $instageinfo = "ec2-user@" . $dns;
                        //         // $cmd = "sh " . $shellFileEc2 . " " . $insatceKey . " " . $instageinfo . " " . $password;
                        //         $cmd = "sh " . $shellFileEc2 . ' "' . $insatceKey . '" "' . $instageinfo . '" "' . $password . '"';
                        //     } else {
                        //         // $cmd = "sh " . $shellFileRoot . " " . $insatceKey . " " . $instageinfo . " " . $password;
                        //         $cmd = "sh " . $shellFileRoot . ' "' . $insatceKey . '" "' . $instageinfo . '" "' . $password . '"';
                        //     }
                        // }
                        // // \ma\mfw\output\PrintWriter::printValue($cmd);
                        exec($cmd, $output);
                        // echo $cmd;
                        // var_dump($cmd);
                        // var_dump($output);
                        // die("done");
                        // $rand = Strings::generateRandomText(3, true, false, true, false);
                        // $index = $index + 1;
                        // $serverName = $instancesName . "_" . $index;
                        // $instancesServerName = ($instancesName != "") ? $serverName : $region . "_" . $accont['account_name'] . "_" . $rand;

                        # insert case
                        // $_server = MtaServer::first(MtaServer::FETCH_ARRAY, array('main_ip = ?', $ip), array('id', 'name', 'main_ip', 'ssh_username', 'ssh_password', 'ssh_port'));
                        // # insert case
                        // if ($_server != null  && count($_server)) {
                        //     $server = new MtaServer(array('id' => $_server['id']));
                        // } else {
                        //     $server = new MtaServer();
                        // }
                        // $server->setStatus('Activated');
                        // $server->setProviderId($account['provider_id']);

                        // $server->setName("AWS_" . $instancesServerName);
                        // $server->setHostName("");
                        // $server->setMainIp($ip);
                        // $server->setSshUsername("root");
                        // $server->setSshPassword($password);

                        // $server->setSshPort(22);
                        // $server->setOldSshPort(22);
                        // $server->setSshLoginType('user-pass');
                        // $server->setExpirationDate(date("Y-m-d"));
                        // $server->setCreatedBy(intval($this->app->utils->arrays->get($data['user'], 'id', 1)));
                        // $server->setCreatedDate(date("Y-m-d"));
                        // $server->setLastUpdatedBy(intval($this->app->utils->arrays->get($data['user'], 'id', 1)));
                        // $server->setLastUpdatedDate(date("Y-m-d"));


                        // if ($_server != null  && count($_server)) {
                        //     $result = $server->update();
                        // } else {
                        //     $result = $server->insert();
                        // }

                        // Update AWS Status 
                        // $this->app->database('system')->execute("UPDATE admin.aws SET status_id = 2,serverId = " . $result . " WHERE id = " . $id);

                        // if ($result > -1) {
                            $message = "Record stored succesfully !";
                            $messageFlag = 'success';
                        // }
                    }
                }
                die(json_encode(array("resaults" => 'Done', 'cmd' => $cmd)));
                // // \ma\mfw\output\PrintWriter::printValue("ddd");
            }
        }
    }

    /**
     * @name amazon
     * @description manage amazon instances
     * @before init
     * @after closeConnections,checkForMessage
     */
    public function amazon()
    {
        # set the menu item to active 
        $this->masterView->set('menu_admin_api', true);
        $this->masterView->set('menu_admin_api_add', true);

        $servers = MtaServer::all(MtaServer::FETCH_ARRAY, array('status = ?', array('Activated')), array('id', 'name', 'provider_id'), 'id', 'desc');
        # set the data to the template
        $this->pageView->set('servers', $servers);
    }

    /**
     * @name stop ec2
     * @description stop ec2
     * @before init
     * @after closeConnections,checkForMessage
     */
    public function configureAmazonSTOP()
    {
        # check if the request is not AJAX request then return to index 
        if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) {
            # prevent layout to be displayed
            // $this->setShowMasterView(false);
            // $this->setShowPageView(false);

            # retreive
            $data = $this->app->http->request->retrieve(Request::ALL, Request::POST);


            if (count($data)) {
                $mainServer = $data['serverID'][0];
                $instancesIds = explode(PHP_EOL, $data['ids']);
                $region = $data['region'];

                $server = MtaServer::first(MtaServer::FETCH_ARRAY, array('id = ?', $mainServer), array('id', 'name', 'main_ip', 'ssh_username', 'ssh_password', 'ssh_port'));

                $sshAuthenticator = new SSHPasswordAuthentication($server['ssh_username'], $server['ssh_password']);
                $sshConnector = new SSH($server['main_ip'], $sshAuthenticator, $server['ssh_port']);

                if ($sshConnector->isConnected()) {
                    foreach ($instancesIds as $instances) {
                        // \ma\mfw\output\PrintWriter::printValue("Start Stoping the server " . $instances, false);
                        $stopResalut =  $sshConnector->cmd("aws ec2 stop-instances --instance-ids $instances", true);
                        // \ma\mfw\output\PrintWriter::printValue($stopResalut, false);
                    }

                    // \ma\mfw\output\PrintWriter::printValue("Done ...");
                } else {
                    // \ma\mfw\output\PrintWriter::printValue("Can not connect to the server : " . $server['name']);
                }
            }
        }
    }


    /**
     * @name start ec2
     * @description start ec2
     * @before init
     * @after closeConnections,checkForMessage
     */
    public function configureAmazonSTART()
    {
        # check if the request is not AJAX request then return to index 
        if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) {
            # prevent layout to be displayed
            // $this->setShowMasterView(false);
            // $this->setShowPageView(false);

            # retreive
            $data = $this->app->http->request->retrieve(Request::ALL, Request::POST);


            if (count($data)) {
                $mainServer = $data['serverID'][0];
                $instancesIds = explode(PHP_EOL, $data['ids']);

                $server = MtaServer::first(MtaServer::FETCH_ARRAY, array('id = ?', $mainServer), array('id', 'name', 'main_ip', 'ssh_username', 'ssh_password', 'ssh_port'));

                $sshAuthenticator = new SSHPasswordAuthentication($server['ssh_username'], $server['ssh_password']);
                $sshConnector = new SSH($server['main_ip'], $sshAuthenticator, $server['ssh_port']);

                if ($sshConnector->isConnected()) {
                    foreach ($instancesIds as $instances) {
                        // // \ma\mfw\output\PrintWriter::printValue("Start Stoping the server " . $instances, false);
                        $stopResalut =  $sshConnector->cmd("aws ec2 start-instances --instance-ids $instances", true);
                        // // \ma\mfw\output\PrintWriter::printValue($stopResalut, false);
                    }

                    // // \ma\mfw\output\PrintWriter::printValue("Done ...");
                } else {
                    // // \ma\mfw\output\PrintWriter::printValue("Can not connect to the server : " . $server['name']);
                }
            }
        }
    }

    /**
     * @name manage
     * @description manage api accounts
     * @before init
     * @after closeConnections,checkForMessage
     */
    public function manage()
    {
        # check for permissions
        $access = Permissions::checkForAuthorization($this->authenticatedUser, __CLASS__, __FUNCTION__);
        if ($access == false) {
            throw new PageException('Access Denied !', 403);
        }
        # set the menu item to active 
        $this->masterView->set('menu_admin_api', true);
        $this->masterView->set('menu_admin_api_add', true);

        // Manage APIs 
        $accounts = ServerApis::all(ServerApis::FETCH_ARRAY, array('api_provider = ?', 'Linode'), array('id', 'account_name'), 'id', 'ASC');

        // get default API to use 

        $api = Api::getAPIClass(array("api_type" => "linode", "api_url" => "https://api.linode.com/v4"));
        // echo '
';print_r($api);
        // exit;
        // echo '
';
        // var_dump($api->getRegions());
        // exit;

        // *********** GET REGIONS *********** //
        $regionsJson = json_decode($api->getRegions());
        $regions = array();
        if ($regionsJson->results > 0) {
            $resaultRegion = $regionsJson->data;
            foreach ($resaultRegion as $region) {
                $regions[] = $region->id;
            }
        }

        // *********** GET IMAGES *********** //
        $imagesJson = json_decode($api->getImages());
        $images = array();
        if ($imagesJson->results > 0) {
            $ResaultImages = $imagesJson->data;
            foreach ($ResaultImages as $image) {
                $images[] = $image->id;
            }
        }

        // *********** GET TYPES *********** //

        $typesJson = json_decode($api->getTypes());

        $types = array();
        if ($typesJson->results > 0) {
            $ResaultTypes = $typesJson->data;
            foreach ($ResaultTypes as $type) {
                $types[] = array('id' => $type->id, 'label' => $type->label);
            }
        }


        # set the list into the template data system 
        $this->pageView->set('accounts', $accounts);
        $this->pageView->set('regions', $regions);
        $this->pageView->set('images', $images);
        $this->pageView->set('types', $types);
    }

    /**
     * @name getServers
     * @description get Servers by API
     * @before init
     * @after closeConnections,checkForMessage
     */
    public function getServers()
    {
        # check if the request is not AJAX request then return to index 
        if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) {
            # prevent layout to be displayed
            // $this->setShowMasterView(false);
            // $this->setShowPageView(false);

            # retreive
            $data = $this->app->http->request->retrieve(Request::ALL, Request::POST);

            if (count($data)) {

                # add user data 
                $data['user'] = [];
                $data['user']['id'] = $this->authenticatedUser->getId();
                # add user data 
                $data['api-link'] = $this->app->http->request->getBaseURL() . RDS . 'api';


                # get the main values
                $user = $data['user'];
                $accountId = $data['accountId'];
                $region = $data['region'];
                $os = $data['os'];
                $type = $data['type'];
                $authType = $data['authType'];
                $rootPassword = $data['rootPassword'];
                $count = $data['count'];

                $app = Application::getCurrent()->getSetting('init');

                $public_key = trim(file_get_contents($app->public_key));

                $account = ServerApis::first(ServerApis::FETCH_ARRAY, array('id = ?', $accountId));

                $linode = array(
                    "api_type" => $account['api_provider'],
                    "api_url" => $account['api_url'],
                    "api_key" => $account['api_key']
                );

                $api = Api::getAPIClass($linode);

                $resalutTable = array();

                for ($index1 = 0; $index1 < $count; $index1++) {
                    $rand = Strings::generateRandomText(3, true, false, true, false);
                    $res = json_decode($api->CreateServer($type, $region, $os, $rootPassword, "LND-" . $rand, $public_key));
                    $resalutTable[] = array('id' => $res->id, 'label' => $res->label, 'ipv4' => $res->ipv4[0], 'status' => $res->status);
                }

                die(json_encode(array("resaults" => $resalutTable)));
            }
        }
    }

    /**
     * @name configureRdns
     * @description configure ip rdns
     * @before init
     * @after closeConnections,checkForMessage
     */
    public function configureRdns()
    {
        # check if the request is not AJAX request then return to index 
        if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) {
            # prevent layout to be displayed
            // $this->setShowMasterView(false);
            // $this->setShowPageView(false);

            # retreive
            $data = $this->app->http->request->retrieve(Request::ALL, Request::POST);


            if (count($data)) {

                # add user data 
                $data['user'] = [];
                $data['user']['id'] = $this->authenticatedUser->getId();
                # add user data 
                $data['api-link'] = $this->app->http->request->getBaseURL() . RDS . 'api';

                $accountId = $data['accountId'];
                $instances = json_decode($data['ips']);
                $domains = $data['domains'];

                $account = ServerApis::first(ServerApis::FETCH_ARRAY, array('id = ?', $accountId));

                $linode = array(
                    "api_type" => $account['api_provider'],
                    "api_url" => $account['api_url'],
                    "api_key" => $account['api_key']
                );

                $api = Api::getAPIClass($linode);

                foreach ($instances as $instance) {
                    $res = json_decode($api->configureRdsn($instance, $domains));
                }

                die(json_encode(array("resaults" => $res)));
            }
        }
    }


    /**
     * @name listServers
     * @description get all Servers by API
     * @before init
     * @after closeConnections,checkForMessage
     */
    public function listServers()
    {
        # check if the request is not AJAX request then return to index 
        if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) {
            # prevent layout to be displayed
            // $this->setShowMasterView(false);
            // $this->setShowPageView(false);

            # retreive
            $data = $this->app->http->request->retrieve(Request::ALL, Request::POST);


            if (count($data)) {

                # add user data 
                $data['user'] = [];
                $data['user']['id'] = $this->authenticatedUser->getId();
                # add user data 
                $data['api-link'] = $this->app->http->request->getBaseURL() . RDS . 'api';


                # get the main values
                $user = $data['user'];
                $accountId = $data['accountId'];

                $app = Application::getCurrent()->getSetting('init');

                $account = ServerApis::first(ServerApis::FETCH_ARRAY, array('id = ?', $accountId));

                $linode = array(
                    "api_type" => $account['api_provider'],
                    "api_url" => $account['api_url'],
                    "api_key" => $account['api_key']
                );

                $api = Api::getAPIClass($linode);
                $resalutTable = array();
                $res = json_decode($api->getAllServers());
                if ($res->results > 0) {
                    $data = $res->data;

                    foreach ($data as $server) {
                        $resalutTable[] = array('id' => $server->id, 'label' => $server->label, 'ipv4' => $server->ipv4[0], 'status' => $server->status);
                    }
                }

                die(json_encode(array("resaults" => $resalutTable)));
            }
        }
    }

    /**
     * @name removeInstances
     * @description get all Servers by API
     * @before init
     * @after closeConnections,checkForMessage
     */
    public function removeInstances()
    {
        # check if the request is not AJAX request then return to index 
        if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) {
            # prevent layout to be displayed
            // $this->setShowMasterView(false);
            // $this->setShowPageView(false);

            # retreive
            $data = $this->app->http->request->retrieve(Request::ALL, Request::POST);

            if (count($data)) {

                # add user data 
                $data['user'] = [];
                $data['user']['id'] = $this->authenticatedUser->getId();
                # add user data 
                $data['api-link'] = $this->app->http->request->getBaseURL() . RDS . 'api';

                $instances = json_decode($data['instance']);
                $ips = json_decode($data['ips']);
                $accountId = $data['accountId'];

                $account = ServerApis::first(ServerApis::FETCH_ARRAY, array('id = ?', $accountId));

                $linode = array(
                    "api_type" => $account['api_provider'],
                    "api_url" => $account['api_url'],
                    "api_key" => $account['api_key']
                );

                $api = Api::getAPIClass($linode);

                foreach ($instances as $instance) {
                    $res = json_decode($api->removeInstance($instance));
                }

                // remove them from DB now ...

                foreach ($ips as $ip) {
                    $serverAccount = MtaServer::first(MtaServer::FETCH_ARRAY, array('main_ip = ?', $ip), array('id', 'name', 'main_ip', 'ssh_username', 'ssh_password', 'ssh_port'));
                    if ($serverAccount != null && count($serverAccount)) {
                        $serverID = $serverAccount['id'];
                        $server = new MtaServer(array("id" => $serverID));
                        $res = $this->app->database('system')->query()->from('admin.mta_servers')->where('id = ?', $serverID)->delete();

                        # update domains 
                        // $this->app->database('system')->execute("UPDATE admin.domains SET ip_id = 0 , domain_status = 'Available' WHERE ip_id IN (SELECT id FROM admin.ips WHERE server_id = $serverID)");
                        // $this->app->database('system')->execute("DELETE FROM admin.ips WHERE server_id = $serverID");
                        $this->app->database('system')->execute("DELETE FROM admin.servers_vmtas WHERE mta_server_id = $serverID");
                    }
                }


                die(json_encode(array("resaults" => 'Done')));
            }
        }
    }


    /**
     * @name testIps
     * @description get all Servers by API
     * @before init
     * @after closeConnections,checkForMessage
     */
    public function testIps()
    {
        # check if the request is not AJAX request then return to index 
        if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) {
            # prevent layout to be displayed
            // $this->setShowMasterView(false);
            // $this->setShowPageView(false);

            # retreive
            $data = $this->app->http->request->retrieve(Request::ALL, Request::POST);

            if (count($data)) {

                # add user data 
                $data['user'] = [];
                $data['user']['id'] = $this->authenticatedUser->getId();
                # add user data 
                $data['api-link'] = $this->app->http->request->getBaseURL() . RDS . 'api';

                $ips = json_decode($data['ips']);
                $emails =  explode(";", $data['emails']);

                $app = Application::getCurrent()->getSetting('init');
                $public_key = $app->public_key;
                $private_key = $app->private_key;

                $cmd = '';
                foreach ($ips as $ip) {
                    $sshAuthenticator = new SSHKeyAuthentication('root', $public_key, $private_key);
                    $sshConnector = new SSH($ip, $sshAuthenticator, 22);

                    if ($sshConnector->isConnected()) {
                        $sshConnector->cmd('yum -y update');
                        $sshConnector->cmd('yum install -y mailx');
                        $sshConnector->cmd('yum install -y sendmail');
                        $sshConnector->cmd("echo 'Blue mail tester body' | mail -v -r 'quantomia IP Tester : " . $ip . " ' -s 'quantomia Tester for IP : " . $ip . "' " . $emails[0]);
                        $cmd = "echo 'Blue mail tester body' | mail -v -r 'quantomia IP Tester : " . $ip . " ' -s 'quantomia Tester for IP : " . $ip . "' " . $emails[0];
                        //$sshConnector->cmd("sudo mailx -r \"quantomia IP Tester \" -s \"IP - ".$ip." \" ".$emails[0]." <<<$'\n quantomia Body Content for Server ip -> ".$ip." \n'");
                    } else {
                        // \ma\mfw\output\PrintWriter::printValue("can not connect to -> " . $ip);
                    }

                    // // \ma\mfw\output\PrintWriter::printValue("dddd");
                }

                die(json_encode(array("resaults" => 'Done', 'cmd' => $cmd)));
            }
        }
    }


    /**
     * @name addServers
     * @description add servers to DB
     * @before init
     * @after closeConnections,checkForMessage
     */
    public function addServers()
    {
        # check if the request is not AJAX request then return to index 
        if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) {
            # prevent layout to be displayed
            // $this->setShowMasterView(false);
            // $this->setShowPageView(false);

            # retreive
            $data = $this->app->http->request->retrieve(Request::ALL, Request::POST);

            if (count($data)) {

                # add user data 
                $data['user'] = [];
                $data['user']['id'] = $this->authenticatedUser->getId();
                # add user data 
                $data['api-link'] = $this->app->http->request->getBaseURL() . RDS . 'api';

                $ips = json_decode($data['ips']);
                $accountId = $data['accountId'];


                $account = ServerApis::first(ServerApis::FETCH_ARRAY, array('id = ?', $accountId));

                $app = Application::getCurrent()->getSetting('init');
                $public_key = $app->public_key;
                $private_key = $app->private_key;


                foreach ($ips as $ip) {
                    $rand = Strings::generateRandomText(3, true, false, true, false);
                    # insert case
                    $_server = MtaServer::first(MtaServer::FETCH_ARRAY, array('main_ip = ?', $ip), array('id', 'name', 'main_ip', 'ssh_username', 'ssh_password', 'ssh_port'));
                    # insert case
                    if ($_server != null  && count($_server)) {
                        $server = new MtaServer(array('id' => $_server['id']));
                    } else {
                        $server = new MtaServer();
                    }
                    $server->setStatus('Activated');
                    $server->setProviderId($account['provider_id']);

                    $server->setName("LINOD_" . $account['account_name'] . "_" . $rand);
                    $server->setHostName("");
                    $server->setMainIp($ip);
                    $server->setSshUsername("root");
                    $server->setSshPassword($data['password']);
                    $server->setServerAuth('1');
                    $server->setSshPort(22);
                    $server->setOldSshPort(22);
                    $server->setSshLoginType('user-pass');
                    $server->setExpirationDate(date("Y-m-d"));
                    $server->setCreatedBy(intval($this->app->utils->arrays->get($data['user'], 'id', 1)));
                    $server->setCreatedDate(date("Y-m-d"));
                    $server->setLastUpdatedBy(intval($this->app->utils->arrays->get($data['user'], 'id', 1)));
                    $server->setLastUpdatedDate(date("Y-m-d"));


                    if ($_server != null  && count($_server)) {
                        $result = $server->update();
                    } else {
                        $result = $server->insert();
                    }

                    if ($result > -1) {
                        $message = "Record stored succesfully !";
                        $messageFlag = 'success';
                    }
                }

                # stores the message in the session 
                Page::registerMessage($messageFlag, $message);
                // Session::set('proccess_message_flag', $messageFlag);
                // Session::set('proccess_message', $message);

                die(json_encode(array("resaults" => 'Done')));
            }
        }
    }

    /**
     * @name add
     * @description the add action
     * @before init
     * @after closeConnections,checkForMessage
     */
    public function edit()
    {
        # set the menu item to active 
        $this->masterView->set('menu_admin_isps', true);
        $this->masterView->set('menu_admin_isps_add', true);

        $arguments = func_get_args();
        $id = isset($arguments) && count($arguments) ? $arguments[0] : null;

        if (isset($id) && is_numeric($id)) {
            # retrieve the server by id
            $ServerApis = ServerApis::first(ServerApis::FETCH_ARRAY, array('id = ?', $id));
            // $status = Status::all(true);
            $providers = ServerProvider::all(ServerProvider::FETCH_ARRAY, array(), array('id', 'name'), 'id', 'ASC');

            # set the data to the template
            $this->pageView->set('ServerApis', $ServerApis);
            // $this->pageView->set('status', $status);
            $this->pageView->set('providers', $providers);
        }
    }

    /**
     * @name save
     * @description the save action
     * @before init
     * @after closeConnections,checkForMessage
     */
    public function save()
    {
        # get the connected user
        $user = $this->authenticatedUser;
        $data = $this->app->http->request->retrieve(Request::ALL, Request::POST);
        # retrieves the data from post
        // echo '
';
        // print_r($this->app->http->request);
        // exit;
        $id = $this->app->utils->arrays->get($data, 'api-account-id');
        $accountStatus = $this->app->utils->arrays->get($data, 'status-id');
        $AccountName = $this->app->utils->arrays->get($data, 'account-name');
        $Username = $this->app->utils->arrays->get($data, 'api-user-name');
        $Password = $this->app->utils->arrays->get($data, 'api-user-pass');
        $ApiUrl = $this->app->utils->arrays->get($data, 'api-url');
        $ApiKey = $this->app->utils->arrays->get($data, 'api-key');
        $SSHkey = $this->app->utils->arrays->get($data, 'ssh-key');
        $Provider = $this->app->utils->arrays->get($data, 'provider');
        $AccessKey = $this->app->utils->arrays->get($data, 'access-key');
        $SecretKey = $this->app->utils->arrays->get($data, 'secret-key');
        $ProxyIp = $this->app->utils->arrays->get($data, 'proxy-ip');
        $ProxyPort = $this->app->utils->arrays->get($data, 'proxy-port');
        $ProxyUsername = $this->app->utils->arrays->get($data, 'proxy-username');
        $ProxyPassword = $this->app->utils->arrays->get($data, 'proxy-password');
        $ServerProviderId = $this->app->utils->arrays->get($data, 'server-provider-id');
        // var_dump($id);
        // exit;
        if (isset($AccountName)) {
            $message = "Something went wrong !";
            $messageFlag = 'error';
            if ($id != NULL && is_numeric($id)) {
                # update case
                $id = intval($id);
                $Appiaccount = new ServerApis(array("id" => $id));
                $Appiaccount->setStatusId(intval($accountStatus));
                $Appiaccount->setProviderId(intval($ServerProviderId));
                $Appiaccount->setAccount_name($AccountName);
                $Appiaccount->setUsername($Username);
                $Appiaccount->setPassword($Password);
                $Appiaccount->setApi_url($ApiUrl);
                $Appiaccount->setApi_key($ApiKey);
                $Appiaccount->setSsh_key($SSHkey);
                $Appiaccount->setAccess_key($AccessKey);
                $Appiaccount->setSecret_key($SecretKey);
                $Appiaccount->setProxy_ip($ProxyIp);
                $Appiaccount->setProxy_port($ProxyPort);
                $Appiaccount->setProxy_username($ProxyUsername);
                $Appiaccount->setProxy_password($ProxyPassword);
                $Appiaccount->setApiProvider($Provider);
                $Appiaccount->setCreatedBy($user->getId());
                $Appiaccount->setCreatedAt(date("Y-m-d"));
                $Appiaccount->setLastUpdatedBy($user->getId());
                $Appiaccount->setLastUpdatedAt(date("Y-m-d"));
                $result = $Appiaccount->update();

                if ($result > -1) {
                    $message = "Record updated succesfully !";
                    $messageFlag = 'success';
                }
            } else {
                # insert case

                $Appiaccount = new ServerApis();
                $Appiaccount->setStatusId(intval($accountStatus));
                $Appiaccount->setProviderId(intval($ServerProviderId));
                $Appiaccount->setAccountName($AccountName);
                $Appiaccount->setUsername($Username);
                $Appiaccount->setPassword($Password);
                $Appiaccount->setApiUrl($ApiUrl);
                $Appiaccount->setApiKey($ApiKey);
                $Appiaccount->setSshKey($SSHkey);
                $Appiaccount->setAccessKey($AccessKey);
                $Appiaccount->setSecretKey($SecretKey);
                $Appiaccount->setProxy_ip($ProxyIp);
                $Appiaccount->setProxy_port($ProxyPort);
                $Appiaccount->setProxy_username($ProxyUsername);
                $Appiaccount->setProxy_password($ProxyPassword);
                $Appiaccount->setApiProvider($Provider);
                $Appiaccount->setCreatedBy($user->getId());
                $Appiaccount->setCreatedAt(date("Y-m-d"));
                $Appiaccount->setLastUpdatedBy($user->getId());
                $Appiaccount->setLastUpdatedAt(date("Y-m-d"));
                $result = $Appiaccount->insert();

                if ($result > -1) {

                    $message = "Record stored succesfully !";
                    $messageFlag = 'success';
                }
            }
            // echo '
';print_r($Appiaccount);
            // exit;
            # stores the message in the session 
            Page::registerMessage($messageFlag, $message);
            // Session::set('proccess_message_flag', $messageFlag);
            // Session::set('proccess_message', $message);
        }
        // var_dump($messageFlag);
        // var_dump($message);
        # redirect to show list 
        Page::redirect($this->app->http->request->getBaseURL() . RDS . 'accountapi' . RDS . 'lists.html');
    }

    /**
     * @name delete
     * @description the delete action
     * @before init
     * @after closeConnections,checkForMessage
     */
    public function delete()
    {
        $arguments = func_get_args();
        $id = isset($arguments) && count($arguments) > 0 ? $arguments[0] : null;

        $message = "Something went wrong !";
        $messageFlag = 'error';

        if (isset($id) && is_numeric($id)) {
            # delete the server
            $serverApi = new ServerApis(array("id" => $id));
            $serverApi->delete();
            $message = "Record deleted successfully !";
            $messageFlag = 'success';
        }

        # stores the message in the session 
        Page::registerMessage($messageFlag, $message);
        // Session::set('proccess_message_flag', $messageFlag);
        // Session::set('proccess_message', $message);

        # redirect to show list 
        Page::redirect($this->app->http->request->getBaseURL() . RDS . 'accountapi' . RDS . 'lists.html');
    }

    /* HETZNER AREA  */

    /**
     * @name hetzner
     * @description manage dg api accounts hetzner
     * @before init
     * @after closeConnections,checkForMessage
     */
    public function hetzner()
    {
        # check for permissions
        $access = Permissions::checkForAuthorization($this->authenticatedUser, __CLASS__, __FUNCTION__);
        if ($access == false) {
            throw new PageException('Access Denied !', 403);
        }
        # set the menu item to active 
        $this->masterView->set('menu_admin_api', true);
        $this->masterView->set('menu_admin_api_add', true);
        // $output = [];
        // $command = 'sh /var/NewQAF/storage/bash_scripts/hetzner/hello.sh';
        // exec($command,$output);
        // print_r($output);
        // echo 123;exit;
        // gfbHrRdwqOeAuASbMRMXhmiUHMnpUK6wA8r18cQpnBiQ9vz6XhXo6qa2J0laQ4Li
        //
        //   curl -H "Authorization: Bearer gfbHrRdwqOeAuASbMRMXhmiUHMnpUK6wA8r18cQpnBiQ9vz6XhXo6qa2J0laQ4Li" 'https://api.hetzner.cloud/v1/locations'
        //   curl -H "Authorization: Bearer gfbHrRdwqOeAuASbMRMXhmiUHMnpUK6wA8r18cQpnBiQ9vz6XhXo6qa2J0laQ4Li" 'https://api.hetzner.cloud/v1/images'
        //            curl -H "Authorization: Bearer gfbHrRdwqOeAuASbMRMXhmiUHMnpUK6wA8r18cQpnBiQ9vz6XhXo6qa2J0laQ4Li" 'https://api.hetzner.cloud/v1/server_types'            
        // Manage APIs 
        // echo 123;
        // exit;
        $accounts = ServerApis::all(ServerApis::FETCH_ARRAY, array('api_provider = ?', 'Hetzner'), array('id', 'account_name'), 'id', 'ASC');
        // $app = Application::getCurrent()->getSetting('init');
        // $this->_generateSSHKey();
        # set the list into the template data system 
        // PagesHelper::checkForMessageToPage($this);
        $this->pageView->set('accounts', $accounts);
    }

    /**
     * @name getServersht
     * @description get Servers by API DigitalOceon
     * @before init
     * @after closeConnections,checkForMessage
     */
    public function getServersht()
    {
        # check if the request is not AJAX request then return to index 
        if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) {
            # prevent layout to be displayed
            // $this->setShowMasterView(false);
            // $this->setShowPageView(false);

            # retreive
            $data = $this->app->http->request->retrieve(Request::ALL, Request::POST);

            if (count($data)) {

                # add user data 
                $data['user'] = [];
                $data['user']['id'] = $this->authenticatedUser->getId();
                # add user data 
                $data['api-link'] = $this->app->http->request->getBaseURL() . RDS . 'api';


                # get the main values
                $user = $data['user'];
                $accountId = $data['accountId'];
                $region = $data['region'];
                $os = $data['os'];
                $type = $data['type'];
                $authType = $data['authType'];
                $rootPassword = $data['rootPassword'];
                $count = $data['count'];
                $names = "";

                $app = Application::getCurrent()->getSetting('init');



                $account = ServerApis::first(ServerApis::FETCH_ARRAY, array('id = ?', $accountId));

                $hitzner = array(
                    "api_type" => $account['api_provider'],
                    "api_url" => $account['api_url'],
                    "api_key" => $account['api_key'],
                    "proxy" => [
                        'ip' => $account['proxy_ip'],
                        'port' => $account['proxy_port'],
                        'username' => $account['proxy_username'],
                        'password' => $account['proxy_password']
                    ]
                );

                $api = Api::getAPIClass($hitzner);

                $valid = true;
                $ssh_key_name = '';
                $resalutTable = array();
                # Create hetzner ssh key or find old one.
                $ssh_keys = json_decode($api->getAllSshkeys());
                if (!$ssh_keys->ssh_keys) { # No Key create first ssh key
                    $rand = Strings::generateRandomText(5, true, false, true, false);
                    $ssh_key_name = 'HTZ-key-' . $rand;
                    $public_key = $this->_generateSSHKey();
                    $res = json_decode($api->CreateSshkeys($ssh_key_name, $public_key));
                    if ($res->error) {
                        $valid = false;
                        $resalutTable[] = array('label' => $res->error->message, 'ipv4' => $res->error->code, 'res' => $res, 'status' => false);
                    }
                } else { # check if already present
                    $public_key = $this->_generateSSHKey();
                    foreach ($ssh_keys->ssh_keys as $ssh_key) {
                        if ($ssh_key->public_key == $public_key) {
                            $ssh_key_name = $ssh_key->name;
                        }
                    }
                    if (empty($ssh_key_name)) {
                        $rand = Strings::generateRandomText(5, true, false, true, false);
                        $ssh_key_name = 'HTZ-key-' . $rand;
                        $res = json_decode($api->CreateSshkeys($ssh_key_name, $public_key));
                        if ($res->error) {
                            $valid = false;
                            $resalutTable[] = array('label' => $res->error->message, 'ipv4' => $res->error->code, 'res' => $res, 'status' => false);
                        }
                    }
                }
                # End hetzner ssh key or find old one.
                if ($valid) {
                    for ($index1 = 0; $index1 < $count; $index1++) {
                        $names = "";
                        $rand = Strings::generateRandomText(3, true, false, true, false);
                        $name = "HTZ-" . $rand;
                        $res = json_decode($api->CreateServer($name, $type, $region, $os, $ssh_key_name));
                        if (!$res->error && count($res)) {
                            $server = $res->server;
                            $ipnet = $server->public_net;
                            $ipv4 = $ipnet->ipv4;
                            $resalutTable[] = array('id' => $server->id, 'label' => $server->name, 'ipv4' => $ipv4->ip, 'status' => $server->status, 'htz_key' => $ssh_key_name);
                        } else if ($res && $res->error) {
                            $resalutTable[] = array('label' => $res->error->message, 'ipv4' => $res->error->code, 'res' => $res, 'ssh_key_name' => $ssh_key_name, 'status' => false);
                        }
                    }
                }


                die(json_encode(array("resaults" => $resalutTable)));
            }
        }
    }

    private function _amazonKey($key_name = 'amazon', $ec2Client)
    {
        if (!defined('HETZNER_SSH_KEY_PATH')) {
            define('HETZNER_SSH_KEY_PATH', '/home/keys/');
        }
        if (!file_exists(HETZNER_SSH_KEY_PATH))
            mkdir(HETZNER_SSH_KEY_PATH, 777);
        if (!file_exists(HETZNER_SSH_KEY_PATH)) {
            // Session::set('proccess_message_flag', 'error');
            // Session::set('proccess_message', 'DIRECTORY NOT PRESENT ' . HETZNER_SSH_KEY_PATH);
            Page::registerMessage('error', 'DIRECTORY NOT PRESENT ' . HETZNER_SSH_KEY_PATH);
            // Page::registerMessage($messageFlag, $message);
        }
        if (file_exists(HETZNER_SSH_KEY_PATH . $key_name . '.pem')) {
            return file_get_contents(HETZNER_SSH_KEY_PATH . $key_name . '.pem');
        }

        $result = $ec2Client->createKeyPair(array(
            'KeyName' => $key_name
        ))->toArray();
        // print_r($result);
        $save_location = HETZNER_SSH_KEY_PATH . $key_name . '.pem';
        file_put_contents($save_location, $result['KeyMaterial']);
        exec('chmod 400 ' . $save_location);
        // exit;
    }

    private function _launchInstance($ec2Client, $ImageId, $InstanceType, $keyPairName, $securityGroupName, $maxCount = 1,$VolumeSize = 20, $VolumeType = 'standard')
    {
        $blockMappings = [];
        for ($i = 0; $i < $maxCount; $i++) {
            $rand = Strings::generateRandomText(15, true, false, false, false);
            $blockMappings[] = array(
                'DeviceName' => '/dev/sda1',
                'Ebs' => array(                     // EBS Volume Info
                    // 'SnapshotId' => 'snap-' . $rand,
                    'VolumeSize' => $VolumeSize,
                    'VolumeType' => $VolumeType,
                )
            );
        }
        try {
            $result = $ec2Client->runInstances(array(
                'ImageId'        => $ImageId,
                'MinCount'       => 1,
                'MaxCount'       => $maxCount,
                'InstanceType'   => $InstanceType,
                'KeyName'        => $keyPairName,
                'SecurityGroups' => array($securityGroupName),
                'BlockDeviceMappings' => $blockMappings
            ));
            // var_dump($result);
            // exit;
            // // $ec2Client->waitUntilInstanceRunning(array(
            // //     'InstanceIds' => $instanceIds,
            // // ));
            // // Describe the now-running instance to get the public URL
            // $result = $ec2Client->describeInstances(array(
            //     'InstanceIds' => $instanceIds,
            // ));
            // $ips =  current($result->getPath('Reservations/*/Instances/*/PublicDnsName'));
            return ['started' => true, 'result' => $result->toArray()];
        } catch (SystemException $e) {
            // print_r($e->getMessage());
            die(json_encode(['started' => false, 'message' => $e->getMessage()]));
        } catch (Exception $e) {
            die(json_encode(['started' => false, 'message' => $e->getMessage()]));
        }
    }

    private function _createAmazonSecurityGroup($ec2Client, $region)
    {
        // Create the security group
        try {
            $result = $ec2Client->describeSecurityGroups();
            $groupNames = [];
            foreach ($result as $rows) {
                foreach ($rows as $row) {
                    if (isset($row['GroupId']))
                        $groupNames[$row['GroupId']] = $row['GroupName'];
                }
            }
            $securityGroupName = $region . '-app-all-security';
            if (!in_array($securityGroupName, $groupNames)) {
                $result = $ec2Client->createSecurityGroup(array(
                    'GroupName'   => $securityGroupName,
                    'Description' => 'Basic web server security'
                ));
                $securityGroupId = $result->get('GroupId');
                $ec2Client->authorizeSecurityGroupIngress(array(
                    'GroupName'     => $securityGroupName,
                    'IpPermissions' => array(
                        array(
                            'IpProtocol' => 'tcp',
                            'FromPort'   => 0,
                            'ToPort'     => 65535,
                            'IpRanges'   => array(
                                array('CidrIp' => '0.0.0.0/0')
                            ),
                        )
//                        array(
//                            'IpProtocol' => 'tcp',
//                            'FromPort'   => 22,
//                            'ToPort'     => 22,
//                            'IpRanges'   => array(
//                                array('CidrIp' => '0.0.0.0/0')
//                            ),
//                        )
                    )
                ));
            }
            return ['status' => true, 'securityGroupName' => $securityGroupName];
            // Get the security group ID (optional)
        } catch (SystemException $e) {
            die(json_encode(['started' => false, 'message' => $e->getMessage()]));
        } catch (Exception $e) {
            die(json_encode(['started' => false, 'message' => $e->getMessage()]));
        }


        // return $securityGroupName;
    }

    private function _generateSSHKey($key_name = 'hetzner')
    {
        if (!defined('HETZNER_SSH_KEY_PATH')) {
            define('HETZNER_SSH_KEY_PATH', '/home/keys/');
        }
        if (!file_exists(HETZNER_SSH_KEY_PATH))
            mkdir(HETZNER_SSH_KEY_PATH, 777);
        if (!file_exists(HETZNER_SSH_KEY_PATH)) {
            // Session::set('proccess_message_flag', 'error');
            // Session::set('proccess_message', 'DIRECTORY NOT PRESENT ' . HETZNER_SSH_KEY_PATH);
            Page::registerMessage('error', 'DIRECTORY NOT PRESENT ' . HETZNER_SSH_KEY_PATH);
            // Page::registerMessage($messageFlag, $message);
        }
        if (file_exists(HETZNER_SSH_KEY_PATH . $key_name . '.pub')) {
            return file_get_contents(HETZNER_SSH_KEY_PATH . $key_name . '.pub');
        }
        $rsa = new RSA();
        $rsa->setPrivateKeyFormat(RSA::PUBLIC_FORMAT_OPENSSH);
        $rsa->setPublicKeyFormat(RSA::PUBLIC_FORMAT_OPENSSH);
        $rsa->setComment($key_name . '-server-key');
        $keys = $rsa->createKey(4096);
        if ($keys) {
            if (!file_put_contents(HETZNER_SSH_KEY_PATH . $key_name . '.pub', $keys['publickey'])) {
                // Session::set('proccess_message_flag', 'error');
                // Session::set('proccess_message', 'PERMISSION DENIED TO WRITE FILE ON ' . HETZNER_SSH_KEY_PATH);
                Page::registerMessage('error', 'PERMISSION DENIED TO WRITE FILE ON ' . HETZNER_SSH_KEY_PATH);
            }
            file_put_contents(HETZNER_SSH_KEY_PATH . $key_name . '.ppk', $keys['privatekey']);
            exec('chmod 400 ' . HETZNER_SSH_KEY_PATH . $key_name . '.ppk');
        }
        return $keys['publickey'];
    }

    /**
     * @name listHtServers Hitzner
     * @description get all Servers by API
     * @before init
     * @after closeConnections,checkForMessage
     */
    public function listHtServers()
    {
        # check if the request is not AJAX request then return to index 
        if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) {
            # prevent layout to be displayed
            // $this->setShowMasterView(false);
            // $this->setShowPageView(false);

            # retreive
            $data = $this->app->http->request->retrieve(Request::ALL, Request::POST);

            if (count($data)) {

                # add user data 
                $data['user'] = [];
                $data['user']['id'] = $this->authenticatedUser->getId();
                # add user data 
                $data['api-link'] = $this->app->http->request->getBaseURL() . RDS . 'api';

                # get the main values
                $user = $data['user'];
                $accountId = $data['accountId'];

                $app = Application::getCurrent()->getSetting('init');
                
                $account = ServerApis::first(ServerApis::FETCH_ARRAY, array('id = ?', $accountId));

                $ht = array(
                    "api_type" => $account['api_provider'],
                    "api_url" => $account['api_url'],
                    "api_key" => $account['api_key']
                );

                $api = Api::getAPIClass($ht);
                // var_dump($account);
                // exit;
                $resalutTable = array();
                $res = json_decode($api->getAllServers());
                // echo 123;exit;
                $servers = $res->servers;

                if (count($servers)) {
                    foreach ($servers as $server) {
                        $net = $server->public_net;
                        $ipv4 = $net->ipv4;
                        $resalutTable[] = array('id' => $server->id, 'label' => $server->name, 'ipv4' => $ipv4->ip, 'status' => $server->status);
                    }
                }

                die(json_encode(array("resaults" => $resalutTable)));
            }
        }
    }

    /**
     * @name addHtServers Hitzner
     * @description Store Servers on DB
     * @before init
     * @after closeConnections,checkForMessage
     */
    public function addHtServers()
    {
        # check if the request is not AJAX request then return to index 
        if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) {
            # prevent layout to be displayed
            // $this->setShowMasterView(false);
            // $this->setShowPageView(false);

            # retreive
            $data = $this->app->http->request->retrieve(Request::ALL, Request::POST);

            if (count($data)) {
                # add user data 
                $data['user'] = [];
                $data['user']['id'] = $this->authenticatedUser->getId();
                # add user data 
                $data['api-link'] = $this->app->http->request->getBaseURL() . RDS . 'api';

                $ips = json_decode($data['ips']);
                $accountId = $data['accountId'];

                if (empty($data['password'])) {
                    die(json_encode(array("resaults" => 'Done', 'message' => 'Password not provided')));
                }
                $account = ServerApis::first(ServerApis::FETCH_ARRAY, array('id = ?', trim($accountId)));
                $shellFileRoot = BASH_SCRIPT_PATH . DS . 'hetzner' . DS . "createRootPsw.sh";
                if (!file_exists($shellFileRoot)) {
                    die(json_encode(array("resaults" => 'Done', 'message' => 'Script not found', 'path' => $shellFileRoot)));
                }
                $message = $messageFlag = '';
                $insatceKey  = "/home/keys/hetzner.ppk";
                $output = [];
                foreach ($ips as $ip) {
                    $instageinfo = "root@{$ip}";
                    $password = $data['password'];
                    $cmd = "sh " . $shellFileRoot . ' "' . $insatceKey . '" "' . $instageinfo . '" "' . $password . '"';

                    exec($cmd, $output);
                    $rand = Strings::generateRandomText(3, true, false, true, false);
                    $_server = MtaServer::first(MtaServer::FETCH_ARRAY, array('main_ip = ?', $ip), array('id', 'name', 'main_ip', 'ssh_username', 'ssh_password', 'ssh_port'));
                    # insert case
                    if ($_server != null  && count($_server)) {
                        $server = new MtaServer(array('id' => $_server['id']));
                    } else {
                        $server = new MtaServer();
                    }
                    $server->setStatus('Activated');
                    $server->setProviderId($account['provider_id']);

                    $server->setName("HT_" . $account['account_name'] . "_" . $rand);
                    $server->setHostName("");
                    $server->setMainIp($ip);
                    $server->setSshUsername("root");
                    $server->setSshPassword($password);

                    $server->setSshPort(22);
                    $server->setOldSshPort(22);
                    $server->setSshLoginType('user-pass');
                    $server->setExpirationDate(date("Y-m-d"));
                    $server->setCreatedBy(intval($this->app->utils->arrays->get($data['user'], 'id', 1)));
                    $server->setCreatedDate(date("Y-m-d"));
                    $server->setLastUpdatedBy(intval($this->app->utils->arrays->get($data['user'], 'id', 1)));
                    $server->setLastUpdatedDate(date("Y-m-d"));


                    if ($_server != null  && count($_server)) {
                        $result = $server->update();
                    } else {
                        $result = $server->insert();
                    }

                    if ($result > -1) {
                        $message = "Record stored succesfully !";
                        $messageFlag = 'success';
                    }
                }

                # stores the message in the session 
                // Session::set('proccess_message_flag', $messageFlag);
                // Session::set('proccess_message', $message);
                Page::registerMessage($messageFlag, $message);

                die(json_encode(array("resaults" => 'Done', 'message' => $message, 'cmd' => $cmd, 'output' => $output)));
            }
        }
    }

    /**
     * @name removeInstances
     * @description get all Servers by API
     * @before init
     * @after closeConnections,checkForMessage
     */
    public function removeHtServers()
    {
        # check if the request is not AJAX request then return to index 
        if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) {
            # prevent layout to be displayed
            // $this->setShowMasterView(false);
            // $this->setShowPageView(false);

            # retreive
            $data = $this->app->http->request->retrieve(Request::ALL, Request::POST);

            if (count($data)) {

                # add user data 
                $data['user'] = [];
                $data['user']['id'] = $this->authenticatedUser->getId();
                # add user data 
                $data['api-link'] = $this->app->http->request->getBaseURL() . RDS . 'api';

                $instances = json_decode($data['instance']);
                $ips = json_decode($data['ips']);
                $accountId = $data['accountId'];

                $account = ServerApis::first(ServerApis::FETCH_ARRAY, array('id = ?', $accountId));

                $dg = array(
                    "api_type" => $account['api_provider'],
                    "api_url" => $account['api_url'],
                    "api_key" => $account['api_key']
                );

                $api = Api::getAPIClass($dg);


                foreach ($instances as $instance) {
                    $res = json_decode($api->removeDroplet($instance));
                }

                // remove them from DB now ...

                foreach ($ips as $ip) {
                    $serverAccount = MtaServer::first(MtaServer::FETCH_ARRAY, array('main_ip = ?', $ip), array('id', 'name', 'main_ip', 'ssh_username', 'ssh_password', 'ssh_port'));

                    if ($serverAccount != null && count($serverAccount)) {
                        $serverID = $serverAccount['id'];
                        $server = new MtaServer(array("id" => $serverID));
                        
                        $this->app->database('system')->execute("UPDATE admin.mta_servers SET status = 'Deleted' WHERE id = $serverID");

                        //$res = $this->app->database('system')->query()->from('admin.mta_servers')->where('id = ?', $serverID)->delete();

                        # update domains 
                        // $this->app->database('system')->execute("UPDATE admin.domains SET ip_id = 0 , domain_status = 'Available' WHERE ip_id IN (SELECT id FROM admin.ips WHERE server_id = $serverID)");
                        // $this->app->database('system')->execute("DELETE FROM admin.ips WHERE server_id = $serverID");
                        $this->app->database('system')->execute("UPDATE admin.servers_vmtas SET status = 'Deleted' WHERE mta_server_id = $serverID");
                        //$this->app->database('system')->execute("DELETE FROM admin.servers_vmtas WHERE mta_server_id = $serverID");
                    }
                }


                die(json_encode(array("resaults" => 'Done')));
            }
        }
    }
    /**
     * @name removeInstances
     * @description get all Servers by API
     * @before init
     * @after closeConnections,checkForMessage
     */
    public function ChangePtr()
    {
        # check if the request is not AJAX request then return to index 
        if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) {
            # prevent layout to be displayed
            // $this->setShowMasterView(false);
            // $this->setShowPageView(false);

            # retreive
            $data = $this->app->http->request->retrieve(Request::ALL, Request::POST);

			//print_r($data);die;
            if (count($data)) {

                # add user data 
                $data['user'] = [];
                $data['user']['id'] = $this->authenticatedUser->getId();
                # add user data 
                $data['api-link'] = $this->app->http->request->getBaseURL() . RDS . 'api';

                $accountId = $data['accountId'];
				$PTR_DOMAIN = explode(PHP_EOL, $data['PTR']);    
				//print_r(array_filter($PTR_DOMAIN));die;
                $instances = json_decode($data['data'],true);
				//print_r($instances);die;
                $account = ServerApis::first(ServerApis::FETCH_ARRAY, array('id = ?', $accountId));

                $dg = array(
                    "api_type" => $account['api_provider'],
                    "api_url" => $account['api_url'],
                    "api_key" => $account['api_key']
                );

                $api = Api::getAPIClass($dg);
			
				if(count($PTR_DOMAIN) > 0 ){
					$i = 0;
					foreach ($instances as $instance) {
						$res[] = json_decode($api->ChangeDnsPtr($instance['instanceId'],$instance['instanceIp'],$PTR_DOMAIN[$i]));
						$i++;
						if($i > count($PTR_DOMAIN) ) $i=0;
					}
				}
				die(json_encode(array("resaults" => $res)));				
			}			
		}
	}
    /* Openstaack AREA */

    private function _getOpenStack($account, $region)
    {
        $openstack = new Openstack([
            'authUrl' => $account['api_url'],
            'user'    => [
                'id'       => $account['api_key'],
                'password' => $account['password']
            ]
        ]);
        return $openstack->computeV2(['region' => $region]);
    }

    /**
     * @name addOSServers Openstack
     * @description Store Servers on DB
     * @before init
     * @after closeConnections,checkForMessage
     */
    public function addOSServers()
    {
        # check if the request is not AJAX request then return to index 
        if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) {
            # prevent layout to be displayed
            // $this->setShowMasterView(false);
            // $this->setShowPageView(false);

            # retreive
            $data = $this->app->http->request->retrieve(Request::ALL, Request::POST);

            if (count($data)) {
                # add user data 
                $data['user'] = [];
                $data['user']['id'] = $this->authenticatedUser->getId();
                # add user data 
                $data['api-link'] = $this->app->http->request->getBaseURL() . RDS . 'api';

                $ips = json_decode($data['ips']);
                $accountId = $data['accountId'];

                if (empty($data['password'])) {
                    die(json_encode(array("resaults" => 'Done', 'message' => 'Password not provided')));
                }
                $account = ServerApis::first(ServerApis::FETCH_ARRAY, array('id = ?', trim($accountId)));
                $shellFileRoot = BASH_SCRIPT_PATH . DS . 'openstack' . DS . "createRootPsw.sh";
                if (!file_exists($shellFileRoot)) {
                    die(json_encode(array("resaults" => 'Done', 'message' => 'Script not found')));
                }
                $insatceKey  = "/home/keys/openstack.ppk";
                foreach ($ips as $ip) {
                    $instageinfo = "root@{$ip}";
                    $password = $data['password'];
                    $cmd = "sh " . $shellFileRoot . ' "' . $insatceKey . '" "' . $instageinfo . '" "' . $password . '"';
                    exec($cmd);
                    // exit;
                    $rand = Strings::generateRandomText(3, true, false, true, false);
                    $_server = MtaServer::first(MtaServer::FETCH_ARRAY, array('main_ip = ?', $ip), array('id', 'name', 'main_ip', 'ssh_username', 'ssh_password', 'ssh_port'));
                    # insert case
                    if ($_server != null  && count($_server)) {
                        $server = new MtaServer(array('id' => $_server['id']));
                    } else {
                        $server = new MtaServer();
                    }
                    $server->setStatus('Activated');
                    $server->setProviderId($account['provider_id']);

                    $server->setName("OS_" . $account['account_name'] . "_" . $rand);
                    $server->setHostName("");
                    $server->setMainIp($ip);
                    $server->setSshUsername("root");
                    $server->setSshPassword($password);

                    $server->setSshPort(22);
                    $server->setOldSshPort(22);
                    $server->setSshLoginType('user-pass');
                    $server->setExpirationDate(date("Y-m-d"));
                    $server->setCreatedBy(intval($this->app->utils->arrays->get($data['user'], 'id', 1)));
                    $server->setCreatedDate(date("Y-m-d"));
                    $server->setLastUpdatedBy(intval($this->app->utils->arrays->get($data['user'], 'id', 1)));
                    $server->setLastUpdatedDate(date("Y-m-d"));


                    if ($_server != null  && count($_server)) {
                        $result = $server->update();
                    } else {
                        $result = $server->insert();
                    }

                    if ($result > -1) {
                        $message = "Record stored succesfully !";
                        $messageFlag = 'success';
                    }
                }

                # stores the message in the session 
                // Session::set('proccess_message_flag', $messageFlag);
                // Session::set('proccess_message', $message);
                Page::registerMessage($messageFlag, $message);

                die(json_encode(array("resaults" => 'Done', 'message' => $message)));
            }
        }
    }

    /**
     * @name openstack
     * @description manage openstack api accounts
     * @before init
     * @after closeConnections,checkForMessage
     */
    public function openstack()
    {
        # check for permissions
        $access = Permissions::checkForAuthorization($this->authenticatedUser, __CLASS__, __FUNCTION__);
        if ($access == false) {
            throw new PageException('Access Denied !', 403);
        }
        # set the menu item to active 
        $this->masterView->set('menu_admin_api', true);
        $this->masterView->set('menu_admin_api_add', true);

        // benaissa key : 16491ba4c96747cab04c7eb5f1e6eea986132fab01846af0fbd7ef91ce3b3d7a

        // Manage APIs 
        // $accounts = ServerApis::all(ServerApis::FETCH_ARRAY, array(), array('id', 'account_name'), 'id', 'ASC');
        $accounts = ServerApis::all(ServerApis::FETCH_ARRAY, array('api_provider = ?', 'OpenStack'), array('id', 'account_name'), 'id', 'ASC');
        // $account = $accounts[count($accounts) - 1];
        $flavors = json_decode('[{"name":"6GB SLXC","id":"021aa4df-58c3-4c18-bb67-f09abe528f5e"},{"name":"4GB PLXC","id":"0534697b-3962-4500-960b-5d62b8182e35"},{"name":"2GB MKVM","id":"090be7f6-6199-431d-a2e5-f51d1d37a14b"},{"name":"256MB PLXC","id":"0a6fab35-b785-41b8-8988-3ceb870ae092"},{"name":"512MB PLXC","id":"2d41f893-8a63-4b7d-9bf5-1591f1c9051e"},{"name":"2GB PKVM","id":"2eac003e-f062-4c25-84e2-0ac9a0e0f1e2"},{"name":"1GB MKVM","id":"31834514-409d-4d19-8467-46ee1c1d462c"},{"name":"4GB SKVM","id":"33920162-e6bd-4d48-9daa-2509beb913cb"},{"name":"8GB VDS","id":"3fad6c2f-d322-4d21-b592-da93264108d8"},{"name":"1GB SLXC","id":"421a3f6b-55ad-482e-b44d-4aa83fc944de"},{"name":"16GB SLXC","id":"48b3f618-ae7f-4c20-8908-6e4edb1aca2f"},{"name":"6GB PKVM","id":"56842625-9b95-4e7d-993f-a20127bcbb46"},{"name":"3GB PLXC","id":"5d145ece-1897-4961-988c-16edd18645aa"},{"name":"2GB SLXC","id":"5e73b3df-9165-4508-9c06-175f8fdb63c2"},{"name":"512MB MKVM","id":"67b9fae9-7165-4080-805a-cc4ec5359070"},{"name":"8GB MKVM","id":"6a47ede4-a19d-4366-8aa4-4b52f22beec6"},{"name":"512MB SKVM","id":"74a2534b-6d21-4076-b1e4-f657ce91a454"},{"name":"4GB SLXC","id":"75944c94-9037-434b-a11d-fc23234f562a"},{"name":"12GB MKVM","id":"7690d446-2e49-47da-9fe4-e239be73cf8a"},{"name":"3GB SKVM","id":"79114029-54ac-426d-97f4-7bab06295760"},{"name":"4GB MKVM","id":"7edd29c0-31f2-4deb-9b38-306f05750a06"},{"name":"2GB SKVM","id":"9c6425e1-d36e-4b9a-bdb2-4e64f811280a"},{"name":"16GB PKVM","id":"9d0abf25-86a7-4a7a-b471-1297e39c0a52"},{"name":"8GB PKVM","id":"9e8078be-a832-47e2-8477-dcff6d4494cd"},{"name":"1GB PLXC","id":"9f42a3a3-5adb-4774-89ba-34d9d251266e"},{"name":"16GB VDS","id":"ac63dd7f-f2d2-4ca9-a2ff-1540cdaea372"},{"name":"1GB SKVM","id":"aeb78066-fcae-4271-8cfa-a1bca7ef3b1f"},{"name":"8GB SKVM","id":"cdc95197-4328-443c-bff6-f3cabc0de6bc"},{"name":"32GB VDS","id":"d091a00b-f470-47c6-b86f-2b47bcf06655"},{"name":"8GB SLXC","id":"de21e1e0-8a5f-4022-b0ec-a23fbb975aea"},{"name":"3GB MKVM","id":"e3825d4f-54e6-4634-8869-704a421ed17e"},{"name":"2GB PLXC","id":"e545dcb1-66ef-4f6c-95d3-bc34c508750a"},{"name":"4GB PKVM","id":"fe104881-b309-4556-b32b-7f46d2bbccfd"}]', true);
        // $images = json_decode('[{"name":"Debian 9 Cloud","id":"4f18abc7-af1c-42bf-b229-c0b92185b95e"},{"name":"GParted","id":"5cb65503-ef8e-46f7-bcbf-b61e6c3eb805"},{"name":"Debian 10 Netinstall","id":"186fe8cf-697b-4e24-a433-159124f16153"},{"name":"CentOS 8 Netinstall","id":"32e38863-2117-4cb2-a822-4e2ff96144a8"},{"name":"Debian 10 Cloud","id":"090838b5-ac40-4a45-962f-be3175e52dd3"},{"name":"CloudLinux 7.6","id":"9c3e2b8b-792a-45fa-972e-f65c749fdddd"},{"name":"openSUSE Leap 15.1 Cloud","id":"6ef3a6ea-c3af-4da1-aafb-18cb481fe870"},{"name":"Fedora 30 Cloud","id":"d22f13fe-1257-4d9c-b4d4-bef3a00f70ed"},{"name":"Ubuntu 19.04 Server Cloud","id":"c22e99b9-cf24-4503-8513-b62cc1eb1203"},{"name":"Ubuntu 18.04 Server Cloud","id":"b70776a4-1b16-45d6-9e90-ff0815a7f565"},{"name":"CentOS 7 Cloud","id":"33b1083a-f9de-43c1-9be2-32400e8893c2"},{"name":"Fedora 30 Netinstall","id":"7586d3c6-33af-45ef-a9bf-9eb0d7937e5e"},{"name":"Ubuntu 18.04 Desktop AMD64","id":"53a02544-3e60-492d-b2eb-f31f8726c317"},{"name":"Ubuntu 18.04 Server AMD64","id":"02411e01-c3f6-43c9-9d87-c6317323d52c"},{"name":"CentOS 7 Netinstall","id":"0c66024b-ef18-48ee-8e06-bf2382bc3d52"},{"name":"openSUSE Leap 15.1 Netinstall","id":"538c73c1-db53-455a-aaee-2161b36de7f1"}]', true);
        // $this->_createSecurityGroup($account);
        $images = json_decode('[{"name":"CentOS 7 Cloud","id":"33b1083a-f9de-43c1-9be2-32400e8893c2"}]', true);
        // try {
        //     $compute = $openstack->computeV2(['region' => 'NYC']);
        //     $images = $compute->listImages(['status' => 'ACTIVE']);
        //     $images_list = [];
        //     foreach ($images as $server) {
        //         $images_list[] = ['name' => $server->name, 'id' => $server->id];
        //         // echo '
';
        //         // print_r($server);
        //         // echo '
'; // } // echo '
';
        //     echo json_encode($images_list);
        //     echo '
'; // } catch (ClientException $e) { // echo $e->getMessage(); // } // echo '
'; // try { // $compute = $this->_getOpenStack($account, "NYC"); // $serverId = "6b947325-8ad7-43b0-94e9-e12c327a7a8a"; // $server = $compute->getServer([ // 'id' => $serverId // ]); // $server->addSecurityGroup(['name' => 'os-ssh-firewall']); // } catch (ClientException $e) { // echo $e->getMessage(); // } // exit; // exit; $this->_generateSSHKey('openstack'); # set the list into the template data system $this->pageView->set('accounts', $accounts); $this->pageView->set('flavors', $flavors); $this->pageView->set('images', $images); } /** * @name getOSFlavours Openstack * @description get Flavor and images by API * @before init * @after closeConnections,checkForMessage */ public function getOSFlavours() { # check if the request is not AJAX request then return to index if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) { # prevent layout to be displayed // $this->setShowMasterView(false); // $this->setShowPageView(false); # retreive $data = $this->app->http->request->retrieve(Request::ALL, Request::POST); if (count($data)) { $accountId = $data['accountId']; $account = ServerApis::first(ServerApis::FETCH_ARRAY, array('id = ?', $accountId)); try { $compute = $this->_getOpenStack($account, $data['region']); $flavors = $compute->listFlavors(); $images = $compute->listImages(); $images_list = $flavor_list = []; foreach ($flavors as $flavor) { $flavor_list[] = ['name' => $flavor->name, 'id' => $flavor->id]; } foreach ($images as $image) { if (strpos($image->name, 'CentOS 7 Cloud') !== false) { $images_list[] = ['name' => $image->name, 'id' => $image->id]; } } die(json_encode(['flavors' => $flavor_list, 'images' => $images_list])); } catch (Exception $e) { $resalutTable['message'] = $e->getMessage(); } die(json_encode(array("resaults" => $resalutTable))); } } } /** * @name openstackSSH Openstack * @description Enabele SSH by API * @before init * @after closeConnections,checkForMessage */ public function openstackSSH() { # check if the request is not AJAX request then return to index if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) { # prevent layout to be displayed // $this->setShowMasterView(false); // $this->setShowPageView(false); # retreive $data = $this->app->http->request->retrieve(Request::ALL, Request::POST); if (count($data)) { $accountId = $data['accountId']; $region = $data['region']; $results = []; $account = ServerApis::first(ServerApis::FETCH_ARRAY, array('id = ?', $accountId)); $ids = json_decode($data['ips']); foreach ($ids as $id) { try { $compute = $this->_getOpenStack($account, $data['region']); $server = $compute->getServer([ 'id' => $id, ]); $securityGroupName = $this->_createSecurityGroup($account, $region); $server->addSecurityGroup(['name' => $securityGroupName]); } catch (Exception $e) { $results[] = $e->getMessage(); } } die(json_encode(array("resaults" => $results))); } } } /** * @name openstackPassword Openstack * @description Change password by API * @before init * @after closeConnections,checkForMessage */ public function openstackPassword() { # check if the request is not AJAX request then return to index if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) { # prevent layout to be displayed // $this->setShowMasterView(false); // $this->setShowPageView(false); # retreive $data = $this->app->http->request->retrieve(Request::ALL, Request::POST); if (count($data)) { $accountId = $data['accountId']; $rootPassword = $data['password']; $account = ServerApis::first(ServerApis::FETCH_ARRAY, array('id = ?', $accountId)); $ids = json_decode($data['ids']); foreach ($ids as $id) { try { $compute = $this->_getOpenStack($account, $data['region']); $server = $compute->getServer([ 'id' => $id, ]); $server->changePassword($rootPassword); } catch (Exception $e) { } } die(json_encode(array("resaults" => []))); } } } /** * @name listOpenstackServers Openstack * @description get all Servers by API * @before init * @after closeConnections,checkForMessage */ public function listOpenstackServers() { # check if the request is not AJAX request then return to index if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) { # prevent layout to be displayed // $this->setShowMasterView(false); // $this->setShowPageView(false); # retreive $data = $this->app->http->request->retrieve(Request::ALL, Request::POST); if (count($data)) { # add user data $data['user'] = []; $data['user']['id'] = $this->authenticatedUser->getId(); # add user data $data['api-link'] = $this->app->http->request->getBaseURL() . RDS . 'api'; # get the main values $accountId = $data['accountId']; $account = ServerApis::first(ServerApis::FETCH_ARRAY, array('id = ?', $accountId)); $resalutTable = []; try { $compute = $this->_getOpenStack($account, $data['region']); $servers = $compute->listServers(true); foreach ($servers as $server) { $ipv4 = ''; foreach ($server->addresses['Public'] as $address) { if ($address['version'] == 4) { $ipv4 = $address['addr']; } } $resalutTable[] = array('id' => $server->id, 'label' => $server->name, 'ipv4' => $ipv4, 'status' => $server->status, 'server' => $server); } } catch (ClientException $e) { $resalutTable['error'] = $e->getMessage(); } die(json_encode(array("resaults" => $resalutTable))); } } } // private function _saveKey($keypair, $key_name = '') // { // if (!defined('HETZNER_SSH_KEY_PATH')) { // define('HETZNER_SSH_KEY_PATH', '/home/keys/'); // } // if (!file_exists(HETZNER_SSH_KEY_PATH)) // mkdir(HETZNER_SSH_KEY_PATH, 777); // if (!file_exists(HETZNER_SSH_KEY_PATH)) { // Session::set('proccess_message_flag', 'error'); // Session::set('proccess_message', 'DIRECTORY NOT PRESENT ' . HETZNER_SSH_KEY_PATH); // } // if ($keypair) { // if (file_put_contents(HETZNER_SSH_KEY_PATH . $key_name . '.pub', $keypair->publicKey)) { // Session::set('proccess_message_flag', 'error'); // Session::set('proccess_message', 'PERMISSION DENIED TO WRITE FILE ON ' . HETZNER_SSH_KEY_PATH); // } // file_put_contents(HETZNER_SSH_KEY_PATH . $key_name . '.ppk', $keypair->privateKey); // exec('chmod 400 ' . HETZNER_SSH_KEY_PATH . $key_name . '.ppk'); // } // // return $keys['publickey']; // } /** * @name openstackDelete Openstack * @description Delete by API * @before init * @after closeConnections,checkForMessage */ public function openstackDelete() { # check if the request is not AJAX request then return to index if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) { # prevent layout to be displayed // $this->setShowMasterView(false); // $this->setShowPageView(false); # retreive $data = $this->app->http->request->retrieve(Request::ALL, Request::POST); if (count($data)) { $accountId = $data['accountId']; $account = ServerApis::first(ServerApis::FETCH_ARRAY, array('id = ?', $accountId)); $ids = json_decode($data['ids']); $ips = json_decode($data['ips']); $resalutTable = []; foreach ($ids as $ind => $id) { try { $compute = $this->_getOpenStack($account, $data['region']); $server = $compute->getServer([ 'id' => $id, ]); $server->delete(); $ip = $ips[$ind]; $serverAccount = MtaServer::first(MtaServer::FETCH_ARRAY, array('main_ip = ?', $ip), array('id', 'name', 'main_ip', 'ssh_username', 'ssh_password', 'ssh_port')); if ($serverAccount != null && count($serverAccount)) { $serverID = $serverAccount['id']; $server = new MtaServer(array("id" => $serverID)); $res = $this->app->database('system')->query()->from('admin.mta_servers')->where('id = ?', $serverID)->delete(); # update domains // $this->app->database('system')->execute("UPDATE admin.domains SET ip_id = 0 , domain_status = 'Available' WHERE ip_id IN (SELECT id FROM admin.ips WHERE server_id = $serverID)"); // $this->app->database('system')->execute("DELETE FROM admin.ips WHERE server_id = $serverID"); $this->app->database('system')->execute("DELETE FROM admin.servers_vmtas WHERE mta_server_id = $serverID"); } // $this->app->database('system')->query()->from('admin.mta_servers')->where('id = ?',$serverID)->delete(); } catch (Exception $e) { $resalutTable[] = ['error' => $e->getMessage()]; } } $status = $resalutTable ? false : true; die(json_encode(array("resaults" => implode(',', $resalutTable), 'status' => $status))); } } } private function _createSecurityGroup($account, $region) { $openstack = new OpenStack([ 'authUrl' => $account['api_url'], 'user' => [ 'id' => $account['api_key'], 'password' => $account['password'] ] ]); $securityGroupName = 'os-ssh-firewall'; $networking = $openstack->networkingV2ExtSecGroups(['region' => $region]); $secGroups = $networking->listSecurityGroups(); $secGroupId = null; foreach ($secGroups as $secGroup) { if ($secGroup->name == $securityGroupName) { $secGroupId = $secGroup->id; } // echo '
';
            // print_r($secGroup);
            // echo '
'; } // var_dump($secGroupId); // exit; if (is_null($secGroupId)) { $secGroup = $networking->createSecurityGroup([ 'name' => $securityGroupName, 'description' => 'security group for ' . $securityGroupName, ]); $secGroupId = $secGroup->id; $rule = $networking->createSecurityGroupRule([ "direction" => "ingress", "ethertype" => "IPv4", // "portRangeMin" => "1", // "portRangeMax" => "65535", "protocol" => "tcp", // "cidr" => "0.0.0.0//24", // "remoteGroupId" => $secGroupId, "securityGroupId" => $secGroupId, ]); // print_r($rule); // exit; } return $securityGroupName; } /** * @name generateOpenstack * @description add server by API Openstack * @before init * @after closeConnections,checkForMessage */ public function generateOpenstack() { # check if the request is not AJAX request then return to index if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) { # prevent layout to be displayed // $this->setShowMasterView(false); // $this->setShowPageView(false); # retreive $data = $this->app->http->request->retrieve(Request::ALL, Request::POST); if (count($data)) { # add user data $data['user'] = []; $data['user']['id'] = $this->authenticatedUser->getId(); # add user data $data['api-link'] = $this->app->http->request->getBaseURL() . RDS . 'api'; # get the main values // $user = $data['user']; $accountId = $data['accountId']; $region = $data['region']; $os = $data['os']; $type = $data['type']; // $authType = $data['authType']; $rootPassword = $data['rootPassword']; $count = $data['count']; $account = ServerApis::first(ServerApis::FETCH_ARRAY, array('id = ?', $accountId)); $valid = true; $resalutTable = array(); $compute = $this->_getOpenStack($account, $data['region']); $keypairs = $compute->listKeypairs(); $ssh_key_pairs = []; foreach ($keypairs as $keypair) { $ssh_key_pairs[] = $keypair; } $ssh_key_name = ''; # Create openstack ssh key or find old one. if (!$ssh_key_pairs) { $public_key = $this->_generateSSHKey('openstack'); # No Key create first ssh key $rand = Strings::generateRandomText(5, true, false, true, false); $ssh_key_name = 'openstack_default_' . $rand; $data = [ 'name' => $ssh_key_name, 'publicKey' => $public_key ]; $keypair = $compute->createKeypair($data); if (!$keypair->name) { $valid = false; $resalutTable[] = array('label' => 'KeY not created', 'ipv4' => 'KeY not created', 'res' => $keypair, 'status' => false); } } else { # check if already present $public_key = $this->_generateSSHKey('openstack'); foreach ($ssh_key_pairs as $keypair) { if ($keypair->publicKey == $public_key) { $ssh_key_id = $ssh_key_name = $keypair->name; } } if (empty($ssh_key_id)) { $rand = Strings::generateRandomText(5, true, false, true, false); $ssh_key_name = 'openstack_default_' . $rand; $data = [ 'name' => $ssh_key_name, 'publicKey' => $public_key ]; $keypair = $compute->createKeypair($data); // $this->_saveKey($keypair, $ssh_key_name); if (!$keypair->name) { $valid = false; $resalutTable[] = array('label' => 'KeY not created', 'ipv4' => 'KeY not created', 'res' => $keypair, 'status' => false); } } } // print_r($ssh_key_id); // exit; if ($valid) { $resalutTable = []; for ($index1 = 0; $index1 < $count; $index1++) { $rand = Strings::generateRandomText(7, true, false, false, false); $name = "OPS-" . $rand; try { $securityGroupName = $this->_createSecurityGroup($account, $region); $options = [ // Required 'name' => $name, 'imageId' => $os, 'flavorId' => $type, 'keyName' => $ssh_key_name, 'adminPass' => $rootPassword, 'SecurityGroup' => ['name' => $securityGroupName] ]; $server = $compute->createServer($options); // sleep(5); // $server = $compute->getServer([ // 'id' => $server->id, // ]); // $server->addSecurityGroup(['name' => $securityGroupName]); $resalutTable[] = array('id' => $server->id, 'label' => $server->name, 'ipv4' => $server->accessIPv4, 'res' => $server, 'options' => $options); } catch (ClientException $e) { $resalutTable[] = array('label' => $e->getMessage(), 'ipv4' => $e->getCode(), 'status' => false); } catch (BadResponseError $e) { $resalutTable[] = array('label' => $e->getMessage(), 'ipv4' => $e->getCode(), 'status' => false); } } } die(json_encode(array("resaults" => $resalutTable))); } } } /* DG AREA */ /** * @name db * @description manage dg api accounts * @before init * @after closeConnections,checkForMessage */ public function dg() { # check for permissions $access = Permissions::checkForAuthorization($this->authenticatedUser, __CLASS__, __FUNCTION__); if ($access == false) { throw new PageException('Access Denied !', 403); } # set the menu item to active $this->masterView->set('menu_admin_api', true); $this->masterView->set('menu_admin_api_add', true); // benaissa key : 16491ba4c96747cab04c7eb5f1e6eea986132fab01846af0fbd7ef91ce3b3d7a // Manage APIs $accounts = ServerApis::all(ServerApis::FETCH_ARRAY, array('api_provider = ?', 'Digital'), array('id', 'account_name'), 'id', 'ASC'); # set the list into the template data system $this->pageView->set('accounts', $accounts); } /** * @name getServersdg * @description get Servers by API DigitalOceon * @before init * @after closeConnections,checkForMessage */ public function getServersdg() { # check if the request is not AJAX request then return to index if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) { # prevent layout to be displayed // $this->setShowMasterView(false); // $this->setShowPageView(false); # retreive $data = $this->app->http->request->retrieve(Request::ALL, Request::POST); if (count($data)) { # add user data $data['user'] = []; $data['user']['id'] = $this->authenticatedUser->getId(); # add user data $data['api-link'] = $this->app->http->request->getBaseURL() . RDS . 'api'; # get the main values $user = $data['user']; $accountId = $data['accountId']; $region = $data['region']; $os = $data['os']; $type = $data['type']; $authType = $data['authType']; $rootPassword = $data['rootPassword']; $count = $data['count']; $names = ""; $app = Application::getCurrent()->getSetting('init'); $account = ServerApis::first(ServerApis::FETCH_ARRAY, array('id = ?', $accountId)); $digital = array( "api_type" => $account['api_provider'], "api_url" => $account['api_url'], "api_key" => $account['api_key'] ); $api = Api::getAPIClass($digital); $ssh_key_id = ''; $valid = true; $resalutTable = array(); # Create hetzner ssh key or find old one. $ssh_keys = json_decode($api->getAllSshkeys()); // var_dump($ssh_keys); if (!$ssh_keys->ssh_keys) { # No Key create first ssh key $rand = Strings::generateRandomText(5, true, false, true, false); $ssh_key_name = 'LND-key-' . $rand; $public_key = $this->_generateSSHKey(); $res = json_decode($api->CreateSshkeys($ssh_key_name, $public_key)); // var_dump($res); if ($res->error) { $valid = false; $resalutTable[] = array('label' => $res->error->message, 'ipv4' => $res->error->code, 'res' => $res, 'status' => false); } else { $ssh_key_id = $res->ssh_key->id; # add id for ssh key } } else { # check if already present $public_key = $this->_generateSSHKey(); foreach ($ssh_keys->ssh_keys as $ssh_key) { if ($ssh_key->public_key == $public_key) { $ssh_key_id = $ssh_key->id; } } if (empty($ssh_key_id)) { $rand = Strings::generateRandomText(5, true, false, true, false); $ssh_key_name = 'HTZ-key-' . $rand; $res = json_decode($api->CreateSshkeys($ssh_key_name, $public_key)); if ($res->error) { $valid = false; $resalutTable[] = array('label' => $res->error->message, 'ipv4' => $res->error->code, 'res' => $res, 'status' => false); } else { $ssh_key_id = $res->ssh_key->id; # add id for ssh key } } } if ($valid) { for ($index1 = 0; $index1 < $count; $index1++) { $rand = Strings::generateRandomText(3, true, false, true, false); $names[] = "digital-ocean-" . $rand; } $public_key = $this->_generateSSHKey(); $res = json_decode($api->CreateServer($names, $type, $region, $os, $ssh_key_id)); //// \ma\mfw\output\PrintWriter::printValue($res); $droplets = $res->droplets; if (!count($droplets)) { $resalutTable[] = array('id' => $res->id, 'label' => $res->message, 'ipv4' => '0.0.0.0', 'status' => false); } foreach ($droplets as $droplet) { $resalutTable[] = array('id' => $droplet->id, 'label' => $droplet->name, 'ipv4' => '0.0.0.0', 'status' => $droplet->status); } } die(json_encode(array("resaults" => $resalutTable))); } } } /** * @name removeInstances * @description get all Servers by API * @before init * @after closeConnections,checkForMessage */ public function removeDroplets() { # check if the request is not AJAX request then return to index if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) { # prevent layout to be displayed // $this->setShowMasterView(false); // $this->setShowPageView(false); # retreive $data = $this->app->http->request->retrieve(Request::ALL, Request::POST); if (count($data)) { # add user data $data['user'] = []; $data['user']['id'] = $this->authenticatedUser->getId(); # add user data $data['api-link'] = $this->app->http->request->getBaseURL() . RDS . 'api'; $instances = json_decode($data['instance']); $ips = json_decode($data['ips']); $accountId = $data['accountId']; $account = ServerApis::first(ServerApis::FETCH_ARRAY, array('id = ?', $accountId)); $dg = array( "api_type" => $account['api_provider'], "api_url" => $account['api_url'], "api_key" => $account['api_key'] ); $api = Api::getAPIClass($dg); foreach ($instances as $instance) { $res = json_decode($api->removeDroplet($instance)); } // remove them from DB now ... foreach ($ips as $ip) { $serverAccount = MtaServer::first(MtaServer::FETCH_ARRAY, array('main_ip = ?', $ip), array('id', 'name', 'main_ip', 'ssh_username', 'ssh_password', 'ssh_port')); if ($serverAccount != null && count($serverAccount)) { $serverID = $serverAccount['id']; $server = new MtaServer(array("id" => $serverID)); $res = $this->app->database('system')->query()->from('admin.mta_servers')->where('id = ?', $serverID)->delete(); # update domains // $this->app->database('system')->execute("UPDATE admin.domains SET ip_id = 0 , domain_status = 'Available' WHERE ip_id IN (SELECT id FROM admin.ips WHERE server_id = $serverID)"); // $this->app->database('system')->execute("DELETE FROM admin.ips WHERE server_id = $serverID"); $this->app->database('system')->execute("DELETE FROM admin.servers_vmtas WHERE mta_server_id = $serverID"); } } die(json_encode(array("resaults" => 'Done'))); } } } /** * @name listServers Digitaloceon * @description get all Servers by API * @before init * @after closeConnections,checkForMessage */ public function listDgServers() { # check if the request is not AJAX request then return to index if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) { # prevent layout to be displayed // $this->setShowMasterView(false); // $this->setShowPageView(false); # retreive $data = $this->app->http->request->retrieve(Request::ALL, Request::POST); if (count($data)) { # add user data $data['user'] = []; $data['user']['id'] = $this->authenticatedUser->getId(); # add user data $data['api-link'] = $this->app->http->request->getBaseURL() . RDS . 'api'; # get the main values $user = $data['user']; $accountId = $data['accountId']; $app = Application::getCurrent()->getSetting('init'); $account = ServerApis::first(ServerApis::FETCH_ARRAY, array('id = ?', $accountId)); $dg = array( "api_type" => $account['api_provider'], "api_url" => $account['api_url'], "api_key" => $account['api_key'] ); $api = Api::getAPIClass($dg); // var_dump($dg); $resalutTable = array(); $res = json_decode($api->getAllServers()); $droplets = $res->droplets; if (count($droplets)) { foreach ($droplets as $droplet) { $ip = $droplet->networks; $v4 = $ip->v4; $ipv4 = $v4[0]->ip_address; $resalutTable[] = array('id' => $droplet->id, 'label' => $droplet->name, 'ipv4' => $ipv4, 'status' => $droplet->status); } } die(json_encode(array("resaults" => $resalutTable))); } } } /** * @name addServers Digital * @description add servers to DB * @before init * @after closeConnections,checkForMessage */ public function addDgServers() { # check if the request is not AJAX request then return to index if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) { # prevent layout to be displayed // $this->setShowMasterView(false); // $this->setShowPageView(false); # retreive $data = $this->app->http->request->retrieve(Request::ALL, Request::POST); if (count($data)) { # add user data $data['user'] = []; $data['user']['id'] = $this->authenticatedUser->getId(); # add user data $data['api-link'] = $this->app->http->request->getBaseURL() . RDS . 'api'; $ips = json_decode($data['ips']); $accountId = $data['accountId']; $account = ServerApis::first(ServerApis::FETCH_ARRAY, array('id = ?', $accountId)); $app = Application::getCurrent()->getSetting('init'); $public_key = $app->public_key; $private_key = $app->private_key; $shellFileRoot = BASH_SCRIPT_PATH . DS . 'digitalocean' . DS . "createRootPsDO.sh"; if (!file_exists($shellFileRoot)) { die(json_encode(array("resaults" => 'Done', 'message' => 'Script not found'))); } $insatceKey = "/home/keys/hetzner.ppk"; foreach ($ips as $ip) { $instageinfo = "root@{$ip}"; $password = $data['password']; $cmd = "sh " . $shellFileRoot . ' "' . $insatceKey . '" "' . $instageinfo . '" "' . $password . '"'; exec($cmd); $rand = Strings::generateRandomText(3, true, false, true, false); # insert case $_server = MtaServer::first(MtaServer::FETCH_ARRAY, array('main_ip = ?', $ip), array('id', 'name', 'main_ip', 'ssh_username', 'ssh_password', 'ssh_port')); # insert case if ($_server != null && count($_server)) { $server = new MtaServer(array('id' => $_server['id'])); } else { $server = new MtaServer(); } $server->setStatus('Activated'); $server->setProviderId($account['provider_id']); $server->setName("DG_" . $account['account_name'] . "_" . $rand); $server->setHostName(""); $server->setMainIp($ip); $server->setSshUsername("root"); $server->setSshPassword($password); $server->setServerAuth('1'); $server->setSshPort(22); $server->setOldSshPort(22); $server->setSshLoginType('user-pass'); $server->setExpirationDate(date("Y-m-d")); $server->setCreatedBy(intval($this->app->utils->arrays->get($data['user'], 'id', 1))); $server->setCreatedDate(date("Y-m-d")); $server->setLastUpdatedBy(intval($this->app->utils->arrays->get($data['user'], 'id', 1))); $server->setLastUpdatedDate(date("Y-m-d")); if ($_server != null && count($_server)) { $result = $server->update(); } else { $result = $server->insert(); } if ($result > -1) { $message = "Record stored succesfully !"; $messageFlag = 'success'; } } # stores the message in the session // Session::set('proccess_message_flag', $messageFlag); // Session::set('proccess_message', $message); Page::registerMessage($messageFlag, $message); die(json_encode(array("resaults" => 'Done', 'cmd' => $cmd))); } } } /** * @name testIps * @description get all Servers by API * @before init * @after closeConnections,checkForMessage */ public function testDgIps() { # check if the request is not AJAX request then return to index if (!empty(self::getGlobalServer('HTTP_X_REQUESTED_WITH')) && strtolower(self::getGlobalServer('HTTP_X_REQUESTED_WITH'))) { # prevent layout to be displayed // $this->setShowMasterView(false); // $this->setShowPageView(false); # retreive $data = $this->app->http->request->retrieve(Request::ALL, Request::POST); if (count($data)) { # add user data $data['user'] = []; $data['user']['id'] = $this->authenticatedUser->getId(); # add user data $data['api-link'] = $this->app->http->request->getBaseURL() . RDS . 'api'; $ips = json_decode($data['ips']); $emails = $data['emails']; $app = Application::getCurrent()->getSetting('init'); $public_key = $app->public_key; $private_key = $app->private_key; foreach ($ips as $ip) { $sshAuthenticator = new SSHKeyAuthentication('root', $public_key, $private_key); $sshConnector = new SSH($ip, $sshAuthenticator, 22); if ($sshConnector->isConnected()) { $sshConnector->cmd('yum -y update &'); $sshConnector->cmd('yum install -y mailx &'); $sshConnector->cmd('yum install -y sendmail &'); // // \ma\mfw\output\PrintWriter::printValue('echo "Blue mail tester body" | mail -v -r "quantomia IP Tester : ' . $ip . ' " -s "quantomia Tester for IP : ' . $ip . '" ' . $emails); $sshConnector->cmd("echo 'Blue mail tester body' | mail -v -r 'quantomia IP Tester : " . $ip . " ' -s 'quantomia Tester for IP : " . $ip . "' " . $emails); } else { die(json_encode(array("resaults" => 'Can not connect to the server ' . $ip))); } } die(json_encode(array("resaults" => 'Done Test has been sent to ' . $emails[0]))); } } } /** * @name closeConnections * @description close all connections * @once * @protected */ public function closeConnections() { # connect to the database $this->app->database('system')->disconnect(); $this->app->database('clients')->disconnect(); } /** * @name checkForMessage * @description checks for session messages * @once * @protected */ public function checkForMessage() { # check for message Page::checkForMessage($this); } }