소스 검색

cleanup & comment

andre 7 달 전
부모
커밋
267bb21cbc
6개의 변경된 파일10개의 추가작업 그리고 754개의 파일을 삭제
  1. 10 91
      TestClient.php
  2. 0 100
      controllers/BackupController.php
  3. 0 181
      controllers/DeployDevController.php
  4. 0 198
      controllers/ProdController.php
  5. 0 168
      controllers/ZipController.php
  6. 0 16
      index.php

+ 10 - 91
TestClient.php

@@ -15,7 +15,7 @@ class ApiClient {
     }
 
     /**
-     * Initially deploy the development site for the customer
+     * Initially deploy the webserver environment for the customer
      *
      * @param $userName :        The username under which the domain is deployed
      * @param $domain :          The Domain to migrate
@@ -28,8 +28,8 @@ class ApiClient {
      * Attention: The given parameters username, adminName and adminPassword must be
      *            stored locally for the Single Sign on from whcms plugin
      */
-    public function deployDev($userName, $domain, $adminName, $adminPassword): array {
-        $url = "$this->apiUrl/deploydev/$userName/$domain";
+    public function init($userName, $domain, $adminName, $adminPassword): array {
+        $url = "$this->apiUrl/init/$userName/$domain";
         $data = [
             'admin_name' => $adminName,
             'admin_password' => $adminPassword
@@ -39,31 +39,7 @@ class ApiClient {
 
 
     /**
-     * Migrate dev site to prod site
-     *
-     * @param $userName:        The username under which the domain is deployed
-     * @param $domain:          The Domain to migrate
-     * @param $adminName:       The Super-Admin User of the CRM System (usually the e-mail of the customer
-     * @param $adminPassword:   A self randomly generated password
-     *
-     * @return                  a json with ['status' => $httpCode,'response' => ['success' => 'Text']];
-     *                          or a json with ['status' => $httpCode,'response' => ['error' => 'Error-Description']];
-     *
-     * Attention: The given parameters adminName and adminPassword must be stored locally for the
-     *            Single Sign on from whcms plugin
-     */
-    public function migrateprod($userName, $domain, $adminName, $adminPassword): array {
-        $url = "$this->apiUrl/migrateprod/$userName/$domain";
-        $data = [
-            'admin_name' => $adminName,
-            'admin_password' => $adminPassword
-        ];
-        return $this->sendRequest('POST', $url, $data);
-    }
-
-
-    /**
-     * Disables the prod webpage
+     * Disables the webpage
      *
      * @param username:        The username under which the domain is deployed
      * @param domain:          The Domain to migrate
@@ -71,13 +47,13 @@ class ApiClient {
      * @return                  a json with ['status' => $httpCode,'response' => ['success' => 'Text']];
      *                          or a json with ['status' => $httpCode,'response' => ['error' => 'Error-Description']];
      */
-    public function disableprod($domain, $userName): array {
-        $url = "$this->apiUrl/disableprod/$userName/$domain";
+    public function disable($domain, $userName): array {
+        $url = "$this->apiUrl/disable/$userName/$domain";
         return $this->sendRequest('GET', $url);
     }
 
     /**
-     * Enables the prod webpage
+     * Enables the webpage
      *
      * @param username:        The username under which the domain is deployed
      * @param domain:          The Domain to migrate
@@ -85,28 +61,13 @@ class ApiClient {
      * @return                  a json with ['status' => $httpCode,'response' => ['isenabled' => 'YES']];
      *                          or a json with ['status' => $httpCode,'response' => ['isenabled' => 'NO']];
      */
-    public function enableprod($domain, $userName): array {
+    public function enable($domain, $userName): array {
         $url = "$this->apiUrl/enableprod/$userName/$domain";
         return $this->sendRequest('GET', $url);
     }
 
-
-    /**
-     * Disables the prod webpage
-     *
-     * @param username:        The username under which the domain is deployed
-     * @param domain:          The Domain to migrate
-     *
-     * @return                  a json with ['status' => $httpCode,'response' => ['success' => 'Text']];
-     *                          or a json with ['status' => $httpCode,'response' => ['error' => 'Error-Description']];
-     */
-    public function isprodenabled($domain, $userName): array {
-        $url = "$this->apiUrl/isprodenabled/$userName/$domain";
-        return $this->sendRequest('GET', $url);
-    }
-
     /**
-     * Disables the prod webpage
+     * Returns certifikate informations
      *
      * @param username:        The username under which the domain is deployed
      * @param domain:          The Domain to migrate
@@ -118,48 +79,6 @@ class ApiClient {
         return $this->sendRequest('GET', $url);
     }
 
-    /**
-     * Lists the Prod Backups for the prod webpage
-     *
-     * @param username:        The username under which the domain is deployed
-     * @param domain:          The Domain to migrate
-     *
-     * @return                  a json with ['status' => $httpCode,'response' => [
-     *                                          'backups' =>
-     * [
-     *                                              ['backup_date' => 'ISO Backup Datum',
-     *                                              'swiss_date' => 'Datum im Schweizer Format',
-     *                                              'size_mb' => 'Grösse in Megabyte',
-     *                                              'filename' => 'Dateiname des tar.gz's'
-     *                                          ]
-     *                                      ];
-     *
-     */
-    public function listbackups($domain, $userName): array  {
-        $url = "$this->apiUrl/listbackups/$userName/$domain";
-        return $this->sendRequest('GET', $url);
-    }
-
-
-    /**
-     * Restores a Backup with the given ISO Date
-     *
-     * @param username:        The username under which the domain is deployed
-     * @param domain:          The Domain to migrate
-     * @param backupDate:      The ISO-Date of the backup (backup_date from listBackups) to restore
-     *
-     * @return                  a json with ['status' => $httpCode,'response' => ['success' => 'Text']];
-     *                          or a json with ['status' => $httpCode,'response' => ['error' => 'Error-Description']];
-     */
-    public function restorebackup($domain, $userName, $backupDate): array {
-        $url = "$this->apiUrl/restorebackup/$userName/$domain";
-        $data = [
-            'backup_date' => $backupDate
-        ];
-        return $this->sendRequest('POST', $url, $data);
-    }
-
-
     /**
      * Terminates a Website permanently
      *
@@ -173,7 +92,7 @@ class ApiClient {
         return $this->sendRequest('GET', $url);
     }
 
-
+    // helpers
     private function sendRequest($method, $url, $data = []): array     {
         $ch = curl_init();
 

+ 0 - 100
controllers/BackupController.php

@@ -1,100 +0,0 @@
-<?php
-namespace application\controllers;
-
-class BackupController {
-
-    // BackupFile: YYYY-MM-DD-prod_domain.tar.gz
-    // DBBackupFile: YYYY-MM-DD-prod_domain.sql
-
-    public static function listBackups($data):void {
-        $username = $data['username'] ?? '';
-        $domain = $data['domain'] ?? '';
-
-        if (empty($username) || empty($domain)) {
-            error_log("listBackups: ERROR: No username or domain provided");
-            http_response_code(400);
-            echo json_encode(['error' => 'Missing required parameters: username or domainname']);
-            return;
-        }
-
-        $backupDir = "/home/$username/backups";
-        error_log(" Starting function listbackups for " . $username . " and " . $domain . " : BackupDir " . $backupDir);
-        if (!is_dir($backupDir)) {
-            error_log(" ERROR: Backup Dir does not exist");
-            http_response_code(404);
-            echo json_encode(['error' => 'Backup directory not found']);
-            return;
-        }
-
-        $files = array_diff(scandir($backupDir), ['.', '..']);
-        $backupList = [];
-
-        foreach ($files as $file) {
-            if (preg_match('/^(\d{4}-\d{2}-\d{2})-' . preg_quote($domain, '/') . '\.tar\.gz$/', $file, $matches)) {
-		        $originalDate = $matches[1];
-                $swissDate = DateTime::createFromFormat('Y-m-d', $originalDate)->format('d.m.Y');
-                $sizeMB = round(filesize("$backupDir/$file") / (1024 * 1024), 2);
-                $backupList[] = [
-                    'backup_date' => $originalDate,
-                    'swiss_date' => $swissDate,
-                    'size_mb' => $sizeMB,
-                    'filename' => $file
-                ];
-            }
-        }
-        echo json_encode(['backups' => $backupList]);
-    }
-
-    // BackupFile: YYYY-MM-DD-prod_domain.tar.gz
-    // DBBackupFile: YYYY-MM-DD-prod_domain.sql
-    public static function restoreBackup($data):void {
-        $username = $data['username'] ?? '';
-        $domain = $data['domain'] ?? '';
-        if (empty($username) || empty($data['backup_date']) || empty($domain)) {
-            error_log("restoreBackup: ERROR: No username, domain provided or backup_date provided");
-            http_response_code(400);
-            echo json_encode(['error' => 'Missing required parameters']);
-            return;
-        }
-        error_log(" Starting function restoreBackup for " . $username . " and " . $domain . " : Backup-Date " . $data['backup_date']);
-
-        $backupDir = "/home/$username/backups";
-        $webrootDir = "/home/$username/prod.$domain";
-        $backupFile = $data['backup_date'] ?? '';
-	    $backupFile = $backupFile . "-" . $domain . ".tar.gz";
-        $dbBackupFile = $backupDir ." /" . $data['backup_date'] . "-prod_" . str_replace(['-', '.'], ["_", "_"], $domain);
-        $prodDatabaseName = $username . "_prod_";
-        $prodDatabaseName = $prodDatabaseName  . str_replace(['-', '.'], ["_", "_"], $domain);
-
-        if (!file_exists($backupFile)) {
-            error_log("restoreBackup: ERROR: Backup file $backupFile does not exist");
-            http_response_code(404);
-            echo json_encode(['error' => 'Web Backup file not found']);
-            return;
-        }
-
-        if (!file_exists($dbBackupFile)) {
-            error_log("restoreBackup: ERROR: Database backup file $dbBackupFile does not exist");
-            http_response_code(404);
-            echo json_encode(['error' => 'Database Backup file not found']);
-            return;
-        }
-
-        exec("sudo /usr/bin/tar -xzf $backupFile -C $webrootDir", $output, $returnCode);
-        if ($returnCode !== 0) {
-                error_log("restoreBackup: ERROR: Failed to restore webroot, details' =>" . implode("\n", $output));
-                http_response_code(500);
-                echo json_encode(['error' => 'Failed to restore webroot', 'details' => implode("\n", $output)]);
-                return;
-        }
-
-        exec("sudo /usr/bin/mysql $prodDatabaseName < $dbBackupFile", $output, $returnCode);
-        if ($returnCode !== 0) {
-            error_log("restoreBackup: ERROR: Failed to restore database, details' =>" . implode("\n", $output));
-            http_response_code(500);
-            echo json_encode(['error' => 'Failed to restore database', 'details' => implode("\n", $output)]);
-            return;
-        }
-        echo json_encode(['success' => 'Backup restored successfully']);
-    }
-}

+ 0 - 181
controllers/DeployDevController.php

@@ -1,181 +0,0 @@
-<?php 
-namespace application\controllers;
-
-class DeployDevController {
-    public static function deploy($data): void {
-        $username =  $data['username'];
-        $domain =    $data['domain'];
-        $adminName = $data['admin_name'] ?? '';
-        $adminPassword = $data['admin_password'];
-        $webDir = "/home/$username/dev.$domain";
-        $configTemplate = '/etc/apache2/site-config.in';
-        $configFile = "/etc/apache2/sites-enabled/dev.$domain.conf";
-
-        if (empty($username) || empty($domain) || empty($adminName) || empty($adminPassword)) {
-            error_log("deploy: ERROR: No username, domain, admin_name or admin_password provided");
-            http_response_code(400);
-            error_log("deploy: ERROR: UserName 1 " .    $username);
-            error_log("deploy: ERROR: Domain   1 " .    $domain);
-            error_log("deploy: ERROR: UserName 2 " .    $data['username'] );
-            error_log("deploy: ERROR: Domain   2 " .    $data['domain']   );
-            error_log("deploy: ERROR: AdminName  " .    $adminName);
-            error_log("deploy: ERROR: AdminPasswd" . $adminPassword);
-
-            error_log(print_r($data,true));
-            echo json_encode(['error' => 'Missing required parameters']);
-            return;
-        }
-
-        error_log(" Starting function deploy for " . $username . " and " . $domain . "  DebugMode: " . $GLOBALS['debug']);
-
-        if ($GLOBALS['debug'] == true) { error_log("Creating Webdir ($webDir) for : " . $username); }
-        exec("sudo /usr/bin/mkdir -p $webDir 2>&1", $mkdirOutput, $mkdirReturnCode);
-            if ($mkdirReturnCode !== 0) {
-                error_log("deploy: ERROR: Create Webdir for  $username failed, details => ". implode("\n", $mkdirOutput));
-                http_response_code(500);
-                echo json_encode(['error' => 'Failed to create web dir', 'details' => implode("\n", $mkdirOutput)]);
-                return;
-            }
-
-        if ($GLOBALS['debug'] == true) { error_log("Creating logdir for : " . $username); }
-        if (is_dir("/home/$username/logs") != true) {
-             exec("sudo /usr/bin/mkdir -p /home/$username/logs  2>&1", $mkdirOutput, $mkdirReturnCode);
-                if ($mkdirReturnCode !== 0) {
-                    error_log("deploy: ERROR: Failed to create log directory for  $username failed, details => " . implode("\n", $mkdirOutput));
-                    http_response_code(500);
-                    echo json_encode(['error' => 'Failed to create logs dir', 'details' => implode("\n", $mkdirOutput)]);
-                    return;
-                }
-        }
-        if ($GLOBALS['debug'] == true) { error_log("Creating backup dir for : " . $username); }
-        if (is_dir("/home/$username/backups") != true) {
-           exec("sudo /usr/bin/mkdir -p /home/$username/backups  2>&1", $mkdirOutput, $mkdirReturnCode);
-           if ($mkdirReturnCode !== 0) {
-               error_log("deploy: ERROR: mkdir /home/$username/backups failed, details => " . implode("\n", $mkdirOutput));
-               http_response_code(500);
-               echo json_encode(['error' => 'Failed to create backups dir', 'details' => implode("\n", $mkdirOutput)]);
-               return;
-           }
-        }
-
-        if ($GLOBALS['debug'] == true) { error_log("Chown homedir: " . $username); }
-        exec("sudo /usr/bin/chown $username:$username /home/$username -R 2>&1", $chownOutput, $chownReturnCode);
-        if ($chownReturnCode !== 0) {
-            error_log("deploy: ERROR: chown on /home/$username failed, details => " . implode("\n", $chownOutput));
-            http_response_code(500);
-            echo json_encode(['error' => 'Failed to chown homedir', 'details' => implode("\n", $chownOutput)]);
-            return;
-        }
-
-        if ($GLOBALS['debug'] == true) { error_log("Reading Apache Config Template /etc/apache2/site-config.in"); }
-        $configContent = file_get_contents($configTemplate);
-
-        if ($GLOBALS['debug'] == true) { error_log("Replace config settings in Apache Config Template"); }
-        $configContent = str_replace(['DOCUMENTROOT', 'SERVERNAME','USERNAME', 'DOMAINNAME', 'SERVERALIAS'], [$webDir, "dev.$domain",$username,"dev.$domain", "" ], $configContent);
-
-        if ($GLOBALS['debug'] == true) { error_log("Running Certbot for Domain " . $domain); }
-        exec("sudo /usr/bin/certbot certonly --webroot -w /etc/apache2/letsencrypt -d dev.$domain --non-interactive --agree-tos --email admin@$domain 2>&1", $output, $returnCode);
-        if ($returnCode !== 0) {
-            error_log("deploy: ERROR: certbot failed to create certificate  on dev.$domain, details => " . implode("\n", $output));
-            http_response_code(500);
-            echo json_encode(['error' => 'Certbot failed', 'details' => implode("\n", $output)]);
-            return;
-        }
-        if ($GLOBALS['debug'] == true) { error_log("Replace sslsettings in in Apache Config Template"); }
-        $configContent = str_replace('DOMAINNAME', $domain, $configContent);
-
-        if ($GLOBALS['debug'] == true) { error_log("Writing apache config file to " . $configFile); }
-        if (file_put_contents($configFile, $configContent) != true) {
-            error_log("deploy: ERROR: while writing apache config");
-            echo json_encode(['error' => 'Failed to write Apache config', 'details' => []]);
-        }
-
-        exec('sudo /usr/bin/systemctl reload apache2  2>&1', $apacheOutput, $apacheReturnCode);
-        if ($GLOBALS['debug'] == true) { error_log("Restarting Apache"); }
-        if ($apacheReturnCode !== 0) {
-            error_log("deploy: ERROR: Apache Reload error, details => " . implode("\n", $apacheOutput));
-            http_response_code(500);
-            echo json_encode(['error' => 'Failed to reload Apache', 'details' => implode("\n", $apacheOutput)]);
-            return;
-        }
-
-        echo json_encode(['success' => 'Development site deployed successfully','details' => '']);
-    }
-
-    public static function revert($data): void {
-        $username = $data['username'] ?? '';
-        $domain = $data['domain'] ?? '';
-        $adminName = $data['admin_name'] ?? '';
-        $adminPassword = $data['admin_password'] ?? '';
-        $webDir = "/home/$username/dev.$domain";
-	    $databaseName = $username . "_dev_";
-	    $databaseName = $databaseName  . str_replace(['-', '.'], ["_", "_"], $domain);
-
-
-	exec("sudo /usr/bin/rm -rf $webDir 2>&1", $rmOutput, $rmReturnCode);
-        if ($rmReturnCode !== 0) {
-            error_log("revert: error on rm $webDir -r, details => " . implode("\n", $rmOutput));
-            http_response_code(500);
-            echo json_encode(['error' => 'Failed to remove webdir dir', 'details' => implode("\n", $rmOutput)]);
-            return;
-        }
-
-	exec("sudo /usr/bin/mkdir $webDir  2>&1", $mkdirOutput, $mkdirReturnCode);
-        error_log("revert: error on mkdir $webDir, details => " . implode("\n", $mkdirOutput));
-        if ($mkdirReturnCode !== 0) {
-            http_response_code(500);
-            echo json_encode(['error' => 'Failed to create web dir', 'details' => implode("\n", $mkdirOutput)]);
-            return;
-        }
-
-	exec("sudo /usr/bin/chown $username:$username $webDir  2>&1", $chownOutput, $chownReturnCode);
-        if ($chownReturnCode !== 0) {
-            error_log("revert: chown error on $webDir, details => " . implode("\n", $chownOutput));
-            http_response_code(500);
-            echo json_encode(['error' => 'Failed to chown web dir', 'details' => implode("\n", $chownOutput)]);
-            return;
-        }
-        echo json_encode(['success' => 'Development site deployed successfully']);
-    }
-
-    public static function undeploy($data): void {
-        $username = $data['username'] ?? '';
-        $domain = $data['domain'] ?? '';
-        if (empty($username)) {
-            error_log("terminate: ERROR: No username provided");
-            http_response_code(400);
-            error_log(print_r($data,true));
-            echo json_encode(['error' => 'Missing username']);
-            return;
-        }
-        if( strpos(file_get_contents("/etc/passwd"),$username) == false) {
-            error_log("terminate: ERROR: User $username does not exist");
-            http_response_code(400);
-            error_log(print_r($data,true));
-            echo json_encode(['error' => 'Unknown user']);
-            return;
-        }
-        if(!empty($domain)) {
-            $configFile = "/etc/apache2/sites-enabled/dev.$domain.conf";
-            if ($GLOBALS['debug'] == true) { error_log("Remove config of user : " . $username); }
-            exec("sudo /usr/bin/rm -f $configFile 2>&1", $userOutput, $userReturnCode);
-            exec("sudo /usr/bin/certbot delete --cert-name dev.$domain --non-interactive 2>&1", $output, $returnCode);
-            if ($returnCode !== 0) {
-                error_log("deploy: ERROR: certbot failed to delete certificate on dev.$domain, details => " . implode("\n", $output));
-                http_response_code(500);
-                echo json_encode(['error' => 'Certbot failed', 'details' => implode("\n", $output)]);
-                return;
-            }
-            exec('sudo /usr/bin/systemctl reload apache2  2>&1', $apacheOutput, $apacheReturnCode);
-            if ($GLOBALS['debug'] == true) { error_log("Restarting Apache"); }
-            if ($apacheReturnCode !== 0) {
-                error_log("deploy: ERROR: Apache Reload error, details => " . implode("\n", $apacheOutput));
-                http_response_code(500);
-                echo json_encode(['error' => 'Failed to reload Apache', 'details' => implode("\n", $apacheOutput)]);
-                return;
-            }   
-        }
-        echo json_encode(['success' => 'Undeploy site dev.' . $domain . ' successfully']);
-    }
-
-}

+ 0 - 198
controllers/ProdController.php

@@ -1,198 +0,0 @@
-<?php
-namespace application\controllers;
-
-class ProdController {
-    public static function disable($data): void {
-        $domain = $data['domain'] ?? '';
-
-        if (empty($domain)) {
-            http_response_code(400);
-            echo json_encode(['error' => 'Missing required parameter: domainname']);
-            return;
-        }
-
-        $enabledConfig = "/etc/apache2/sites-enabled/prod.$domain.conf";
-        $availableConfig = "/etc/apache2/sites-available/prod.$domain.conf";
-
-        if (!file_exists($enabledConfig)) {
-            http_response_code(404);
-            echo json_encode(['error' => 'Configuration file not found']);
-            return;
-        }
-
-        if (!rename($enabledConfig, $availableConfig)) {
-            http_response_code(500);
-            echo json_encode(['error' => 'Failed to move configuration file']);
-            return;
-        }
-
-        exec('systemctl reload apache2', $output, $returnCode);
-        if ($returnCode !== 0) {
-            http_response_code(500);
-            echo json_encode(['error' => 'Failed to reload Apache', 'details' => implode("\n", $output)]);
-            return;
-        }
-
-        echo json_encode(['success' => 'Production site disabled successfully']);
-    }
-    
-    
-    public static function enable($data): void  {
-        $domain = $data['domain'] ?? '';
-
-        if (empty($domain)) {
-            http_response_code(400);
-            echo json_encode(['error' => 'Missing required parameter: domainname']);
-            return;
-        }
-
-        $availableConfig = "/etc/apache2/sites-available/prod.$domain.conf";
-        $enabledConfig = "/etc/apache2/sites-enabled/prod.$domain.conf";
-
-        if (!file_exists($availableConfig)) {
-            http_response_code(404);
-            echo json_encode(['error' => 'Configuration file not found']);
-            return;
-        }
-
-        if (!rename($availableConfig, $enabledConfig)) {
-            http_response_code(500);
-            echo json_encode(['error' => 'Failed to move configuration file']);
-            return;
-        }
-
-        exec('systemctl reload apache2', $output, $returnCode);
-        if ($returnCode !== 0) {
-            http_response_code(500);
-            echo json_encode(['error' => 'Failed to reload Apache', 'details' => implode("\n", $output)]);
-            return;
-        }
-
-        echo json_encode(['success' => 'Production site enabled successfully']);
-    }
-
-    public static function isenabled($data): void {
-        $domain = $data['domain'] ?? '';
-
-        if (file_exists("/etc/apache2/sites-enabled/prod.$domain.conf")) {
-            echo json_encode(['isenabled' => 'YES']);
-        } else {
-            echo json_encode(['isenabled' => 'NO']);
-        }
-    }
-
-    public static function migrateFromDev($data): void {
-        $username = $data['username'] ?? '';
-        $domain = $data['domain'] ?? '';
-        $adminName = $data['admin_name'] ?? '';
-        $adminPassword = $data['admin_password'] ?? '';
-        if (empty($username) || empty($domain) || empty($adminName) || empty($adminPassword)) {
-            http_response_code(400);
-            echo json_encode(['error' => 'Missing required parameters']);
-            return;
-        }
-	    $webDir = "/home/$username/prod.$domain";
-        $configFile = "/etc/apache2/sites-enabled/prod.$domain.conf";
-	    $configTemplate = '/etc/apache2/site-config.in';
-        $devDatabaseName = $username . "_dev_";
-        $devDatabaseName = $devDatabaseName  . str_replace(['-', '.'], ["_", "_"], $domain);
-
-        $prodDatabaseName = $username . "_prod_";
-        $prodDatabaseName = $prodDatabaseName  . str_replace(['-', '.'], ["_", "_"], $domain);
-
-        exec("sudo /usr/bin/mkdir $webDir", $mkdirOutput, $mkdirReturnCode);
-        if ($mkdirReturnCode !== 0) {
-            http_response_code(500);
-            echo json_encode(['error' => 'Failed to create web dir', 'details' => implode("\n", $mkdirOutput)]);
-            return;
-        }
-
-        exec("sudo /usr/bin/chown $username:$username $webDir", $chownOutput, $chownReturnCode);
-        if ($chownReturnCode !== 0) {
-            http_response_code(500);
-            echo json_encode(['error' => 'Failed to chown web dir', 'details' => implode("\n", $chownOutput)]);
-            return;
-        }
-
-	    $configContent = file_get_contents($configTemplate);
-        $configContent = str_replace(['DOCUMENTROOT', 'SERVERNAME','USERNAME','DOMAINNAME', 'SERVERALIAS'], [$webDir, "prod.$domain","prod.$domain", "www.$domain" ], $configContent);
-        file_put_contents($configFile, $configContent);
-
-        exec("sudo /usr/bin/certbot certonly --webroot -w /etc/apache/letsencrypt -d www.$domain -d $domain --non-interactive --agree-tos --email admin@$domain", $output, $returnCode);
-        if ($returnCode !== 0) {
-            http_response_code(500);
-            echo json_encode(['error' => 'Certbot failed', 'details' => implode("\n", $output)]);
-            return;
-        }
-
-        exec('sudo /usr/bin/systemctl reload apache2', $apacheOutput, $apacheReturnCode);
-        if ($apacheReturnCode !== 0) {
-            http_response_code(500);
-            echo json_encode(['error' => 'Failed to reload Apache', 'details' => implode("\n", $apacheOutput)]);
-            return;
-        }
-
-        // Deployment from dev to prod
-        exec("sudo /usr/bin/cp -r /home/$username/dev.$domain/* $webDir",$cpOutput,$cpReturnCode);
-        if ($cpReturnCode !== 0) {
-            http_response_code(500);
-            echo json_encode(['error' => 'Failed to copy dev installation into prod directory', 'details' => implode("\n", $cpOutput)]);
-            return;
-        }
-
-        //TODO Replace Settings in Prod Environment
-
-        if ($GLOBALS['debug'] == true) { error_log("Chown WebDir $webDir"); }
-        exec("sudo /usr/bin/chown $username:$username $webDir -R  2>&1", $chownOutput, $chownReturnCode);
-            if ($chownReturnCode !== 0) {
-                error_log("deploy: chown error on $webDir, details => " . implode("\n", $chownOutput));
-                http_response_code(500);
-                echo json_encode(['error' => 'Failed to chown web dir', 'details' => implode("\n", $chownOutput)]);
-                return;
-            }
-
-	    echo json_encode(['success' => 'Production site successfully from dev']);
-
-    }
-
-    public static function undeploy($data): void {
-        $username = $data['username'] ?? '';
-        $domain = $data['domain'] ?? '';
-        if (empty($username)) {
-            error_log("terminate: ERROR: No username provided");
-            http_response_code(400);
-            error_log(print_r($data,true));
-            echo json_encode(['error' => 'Missing username']);
-            return;
-        }
-        if( strpos(file_get_contents("/etc/passwd"),$username) == false) {
-            error_log("terminate: ERROR: User $username does not exist");
-            http_response_code(400);
-            error_log(print_r($data,true));
-            echo json_encode(['error' => 'Unknown user']);
-            return;
-        }
-        if(!empty($domain)) {
-            $configFile = "/etc/apache2/sites-enabled/prod.$domain.conf";
-            if ($GLOBALS['debug'] == true) { error_log("Remove config of user : " . $username); }
-            exec("sudo /usr/bin/rm -f $configFile 2>&1", $userOutput, $userReturnCode);
-            exec("sudo /usr/bin/certbot delete --cert-name prod.$domain --non-interactive 2>&1", $output, $returnCode);
-            if ($returnCode !== 0) {
-                error_log("deploy: ERROR: certbot failed to delete certificate on prod.$domain, details => " . implode("\n", $output));
-                http_response_code(500);
-                echo json_encode(['error' => 'Certbot failed', 'details' => implode("\n", $output)]);
-                return;
-            }
-            exec('sudo /usr/bin/systemctl reload apache2  2>&1', $apacheOutput, $apacheReturnCode);
-            if ($GLOBALS['debug'] == true) { error_log("Restarting Apache"); }
-            if ($apacheReturnCode !== 0) {
-                error_log("deploy: ERROR: Apache Reload error, details => " . implode("\n", $apacheOutput));
-                http_response_code(500);
-                echo json_encode(['error' => 'Failed to reload Apache', 'details' => implode("\n", $apacheOutput)]);
-                return;
-            }   
-        }
-        echo json_encode(['success' => 'Undeploy site prod.' . $domain . ' successfully']);
-    }
-
-}

+ 0 - 168
controllers/ZipController.php

@@ -1,168 +0,0 @@
-<?php
-namespace application\controllers;
-
-class ZipController {
-	
-	/** @var ZipFile */
-	private $zipFile = null;
-	private $zipBuffer = "";
-	private $destination = null;
-	
-	public function extractZip($data) {
-		$this->destination = '/home/' . $data['username'] . '/' . $data['domain'];
-		$url = $data['zip'];
-		@set_time_limit(3600);
-		$ch = curl_init();
-		curl_setopt($ch, CURLOPT_URL, $url);
-		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
-		curl_setopt($ch, CURLOPT_TIMEOUT, 3600);
-		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
-		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
-		//curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
-		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
-		//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
-		curl_setopt($ch, CURLOPT_WRITEFUNCTION, array($this, 'readZip'));
-		$r = curl_exec($ch);
-		$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
-		$error = curl_error($ch);
-		if ($status != 200) {
-			throw new ErrorException("Zip download error (code: $status)".($error ? ": $error" : ''));
-		}
-		curl_close($ch);
-		if ($this->zipFile) { $this->zipFile->close(); }
-	}
-	
-	protected function readZip($ch, $data) {
-		if (is_file($this->destination.'/index.html')) {
-			rename($this->destination.'/index.html', $this->destination.'/index_backup.html');
-		}
-		$size = function_exists('mb_strlen') ? mb_strlen($data, '8bit') : strlen($data);
-		$this->zipBuffer .= $data;
-		//self::debugLog("Receive: ".$data);
-		$continue = true;
-		while ($continue) {
-			$continue = false;
-			$size_0 = function_exists('mb_strlen') ? mb_strlen($this->zipBuffer, '8bit') : strlen($this->zipBuffer);
-			if ($this->zipFile && $size_0 >= $this->zipFile->compressedSize) {
-				$continue = true;
-				$this->zipFile->writeUncompressed(substr($this->zipBuffer, 0, $this->zipFile->compressedSize));
-				$this->zipBuffer = substr($this->zipBuffer, $this->zipFile->compressedSize);
-				$this->zipFile->close();
-				$this->zipFile = null;
-			} else if (!$this->zipFile && ($fp = strpos($this->zipBuffer, ZipFile::ZIP_FILE_HEAD)) !== false) {
-				$continue = true;
-				$this->zipBuffer = substr($this->zipBuffer, $fp);
-				$hsize = 26 + strlen(ZipFile::ZIP_FILE_HEAD);
-				if (strlen($this->zipBuffer) <= $hsize) { break; } // need more data
-				$name_size_raw = unpack('v', substr($this->zipBuffer, strlen(ZipFile::ZIP_FILE_HEAD) + 22, 2));
-				$name_size = intval(reset($name_size_raw));
-				$extra_size_raw = unpack('v', substr($this->zipBuffer, strlen(ZipFile::ZIP_FILE_HEAD) + 24, 2));
-				$extra_size = intval(reset($extra_size_raw));
-				$hsize += $name_size + $extra_size;
-				if (strlen($this->zipBuffer) < $hsize) { break; } // need more data
-				// parse file header
-				if ($this->zipFile) { $this->zipFile->close(); }
-				$this->zipFile = ZipFile::parse(substr($this->zipBuffer, 0, $hsize), $this->destination);
-				//self::debugLog('File: '.$this->zipFile->baseDir.'/'.$this->zipFile->name);
-				$this->zipFile->open();
-				$this->zipBuffer = substr($this->zipBuffer, $hsize);
-			}
-		}
-		return $size;
-	}
-	
-}
-
-class ZipFile {
-	
-	const ZIP_FILE_HEAD = "\x50\x4b\x03\x04";
-	
-	public $version;
-	public $flags;
-	public $compression;
-	public $modDateTime;
-	public $crc32;
-	public $crc32Raw;
-	public $compressedSize;
-	public $size;
-	public $sizeRaw;
-	public $name;
-	public $extra;
-	public $baseDir;
-	private $handle;
-	
-	public function __construct($baseDir = null) {
-		$this->baseDir = rtrim($baseDir, '/');
-		$this->modDateTime = date('Y-m-d H:i:s');
-		$this->compressedSize = 0;
-		$this->size = 0;
-		$this->name = 'new file';
-	}
-	
-	public function open() {
-		$dir = dirname($this->baseDir.'/'.$this->name);
-		if (!is_dir($dir)) { mkdir($dir, 0755, true); }
-		if (!empty($this->name)) {
-			$this->handle = fopen($this->baseDir.'/'.$this->name, 'w');
-		} else {
-			throw new ErrorException("File name is empty");
-		}
-	}
-	
-	public function close() {
-		if ($this->handle !== false) {
-			fclose($this->handle);
-			chmod($this->baseDir.'/'.$this->name, 0644);
-		}
-	}
-	
-	public function write($data) {
-		if ($this->handle !== false) {
-			fwrite($this->handle, $data);
-		} else {
-			throw new ErrorException("File is not open");
-		}
-	}
-	
-	public function writeUncompressed($data) {
-		$data_u = gzinflate($data);
-		$this->write($data_u);
-	}
-
-
-	/**
-	 * @param string $data
-	 * @return ZipFile
-	 */
-	public static function parse($data, $baseDir = null) {
-		$data = substr($data, strlen(self::ZIP_FILE_HEAD));
-		$fh = new ZipFile($baseDir);
-		$fh->version = substr($data, 0, 2);
-		$fh->flags = substr($data, 2, 2);
-		$fh->compression = substr($data, 4, 2);
-		$hexdtime_raw = unpack('V', substr($data, 6, 4));
-		$hexdtime = reset($hexdtime_raw);
-		$fh->modDateTime = ''.((($hexdtime >> 25) & 0xff) + 1980).'-'.
-				sprintf('%02d', ($hexdtime >> 21) & 0x0f).'-'.
-				sprintf('%02d', ($hexdtime >> 16) & 0x1f).' '.
-				sprintf('%02d', ($hexdtime >> 11) & 0x1f).':'.
-				sprintf('%02d', ($hexdtime >>  5) & 0x3f).':'.
-				sprintf('%02d', ($hexdtime <<  1) & 0x1f);
-		$fh->crc32Raw = substr($data, 10, 4);
-		$crc32 = unpack('V', $fh->crc32Raw);
-		$fh->crc32 = sprintf('%08x', reset($crc32));
-		$clen = unpack('V', substr($data, 14, 4));
-		$fh->compressedSize = reset($clen);
-		$fh->sizeRaw = substr($data, 18, 4);
-		$ulen = unpack('V', $fh->sizeRaw);
-		$fh->size = reset($ulen);
-		$nlen_raw = unpack('v', substr($data, 22, 2));
-		$nlen = reset($nlen_raw);
-		$elen_raw = unpack('v', substr($data, 24, 2));
-		$elen = reset($elen_raw);
-		$fh->name = substr($data, 26, $nlen);
-		$fh->extra = substr($data, 26 + $nlen, $elen);
-		return $fh;
-	}
-	
-}

+ 0 - 16
index.php

@@ -13,19 +13,15 @@ RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule ^(.*)$ index.php [QSA,L]
 */
 
-require_once __DIR__ . '/controllers/BackupController.php';
 require_once __DIR__ . '/controllers/GetSSLDaysController.php';
 require_once __DIR__ . '/controllers/QuotaController.php';
 require_once __DIR__ . '/controllers/AccountController.php';
 require_once __DIR__ . '/controllers/SiteController.php';
-require_once __DIR__ . '/controllers/ZipController.php';
 
-use application\controllers\BackupController;
 use application\controllers\AccountController;
 use application\controllers\GetSSLDaysController;
 use application\controllers\QuotaController;
 use application\controllers\SiteController;
-use application\controllers\ZipController;
 
 const API_PASSWORD = 'your-secure-password';
 
@@ -147,18 +143,6 @@ switch ($endpoint) {
             GetSSLDaysController::getSSLDays(['username' => $username, 'domain' => $domain]);
         }
         break;
-    case 'listbackups':
-        error_log("Request listbackups from " . get_client_ip());
-        if ($requestMethod === 'GET' && !empty($username)) {
-            BackupController::listBackups(['username' => $username, 'domain' => $domain]);
-        }
-        break;
-    case 'restorebackup':
-        error_log("Request restorebackup from " . get_client_ip());
-        if ($requestMethod === 'POST' && !empty($username) && !empty($domain)) {
-            BackupController::restoreBackup(array_merge($parameters, ['username' => $username, 'domain' => $domain]));
-        }
-        break;
     case 'create':
         error_log("Request user create from " . get_client_ip());
         if ($requestMethod === 'POST' && !empty($username) && !empty($domain)) {