From 4018534fbbea0cfc9c4ef18ac8c84f81d67cedd7 Mon Sep 17 00:00:00 2001 From: usmannasir Date: Fri, 4 Apr 2025 14:23:13 +0500 Subject: [PATCH 001/273] fix idendation issue --- .../websiteFunctions/websiteFunctions.js | 1891 ++++++++++-- .../websiteFunctions/listWebsites.html | 132 +- websiteFunctions/website.py | 2737 ++++++++++++++++- 3 files changed, 4318 insertions(+), 442 deletions(-) diff --git a/websiteFunctions/static/websiteFunctions/websiteFunctions.js b/websiteFunctions/static/websiteFunctions/websiteFunctions.js index e6fad7f0f..778da2a9f 100755 --- a/websiteFunctions/static/websiteFunctions/websiteFunctions.js +++ b/websiteFunctions/static/websiteFunctions/websiteFunctions.js @@ -2685,84 +2685,73 @@ app.controller('listWebsites', function ($scope, $http, $window) { // Call it immediately $scope.getFurtherWebsitesFromDB(); - $scope.showWPSites = function(domain) { - var config = { + $scope.showWPSites = function(index) { + console.log('showWPSites called with index:', index); + console.log('Current WebSitesList:', $scope.WebSitesList); + + $scope.selectedWebsite = $scope.WebSitesList[index]; + console.log('Selected website:', $scope.selectedWebsite); + + // Always fetch fresh data + var url = '/websites/FetchWPdata'; + var data = { + domain: $scope.selectedWebsite.domain, + websiteName: $scope.selectedWebsite.domain + }; + + $http({ + method: 'POST', + url: url, + data: JSON.stringify(data), headers: { + 'Content-Type': 'application/json', 'X-CSRFToken': getCookie('csrftoken') } - }; - - var data = { - domain: domain - }; - - var url = '/websites/GetWPSitesByDomain'; - - $http.post(url, data, config).then(function(response) { - if (response.data.status === 1) { - // Find the website in the list and update its WordPress sites - for (var i = 0; i < $scope.WebSitesList.length; i++) { - if ($scope.WebSitesList[i].domain === domain) { - $scope.WebSitesList[i].wp_sites = response.data.data; - $scope.WebSitesList[i].showWPSites = !$scope.WebSitesList[i].showWPSites; - break; - } + }).then(function(response) { + console.log('WP Details Response:', response); + + // Check if response is HTML (login page) + if (typeof response.data === 'string' && response.data.includes('')) { + console.log('Received HTML response, redirecting to login'); + window.location.href = '/login'; + return; + } + + if (response.data && response.data.status === 1) { + try { + // If single site, wrap in array + var sites = Array.isArray(response.data.data) ? response.data.data : [response.data.data]; + + $scope.selectedWebsite.wp_sites = sites.map(function(site) { + return { + id: site.id || $scope.selectedWebsite.domain, + title: site.title || site.domain || $scope.selectedWebsite.domain, + url: site.url || 'http://' + $scope.selectedWebsite.domain, + version: site.version || 'Unknown', + phpVersion: site.php_version || 'Unknown', + theme: site.theme || 'Unknown', + activePlugins: site.active_plugins || 0, + searchIndex: site.search_index === 'enabled', + debugging: site.debugging === 'enabled', + passwordProtection: site.password_protection === 'enabled', + maintenanceMode: site.maintenance_mode === 'enabled' + }; + }); + $scope.selectedWebsite.showWPSites = true; + } catch (e) { + console.error('Error processing WordPress data:', e); + $scope.selectedWebsite.showWPSites = false; + $scope.selectedWebsite.wp_sites = []; } } else { console.error('Error fetching WordPress sites:', response.data.error_message); - new PNotify({ - title: 'Error!', - text: response.data.error_message, - type: 'error' - }); + $scope.selectedWebsite.showWPSites = false; + $scope.selectedWebsite.wp_sites = []; } }, function(error) { console.error('Error fetching WordPress sites:', error); - new PNotify({ - title: 'Error!', - text: 'Failed to fetch WordPress sites. Please try again.', - type: 'error' - }); - }); - }; - - $scope.updateSetting = function(wpId, setting, value) { - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - var data = { - siteId: wpId, - setting: setting, - value: value - }; - - var url = '/websites/UpdateWPSettings'; - - $http.post(url, data, config).then(function(response) { - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Setting updated successfully.', - type: 'success' - }); - } else { - console.error('Error updating setting:', response.data.error_message); - new PNotify({ - title: 'Error!', - text: response.data.error_message, - type: 'error' - }); - } - }, function(error) { - console.error('Error updating setting:', error); - new PNotify({ - title: 'Error!', - text: 'Failed to update setting. Please try again.', - type: 'error' - }); + $scope.selectedWebsite.showWPSites = false; + $scope.selectedWebsite.wp_sites = []; }); }; @@ -2778,6 +2767,59 @@ app.controller('listWebsites', function ($scope, $http, $window) { window.location.href = '/websites/listWPsites?wpID=' + wpId; }; + $scope.updateSetting = function(wp, setting) { + var settingMap = { + 'search-indexing': 'searchIndex', + 'debugging': 'debugging', + 'password-protection': 'passwordProtection', + 'maintenance-mode': 'maintenanceMode' + }; + + var data = { + wpID: wp.id, + setting: setting, + value: wp[settingMap[setting]] ? 'enable' : 'disable' + }; + + $http({ + method: 'POST', + url: '/websites/UpdateWPSettings', + data: data, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'X-CSRFToken': getCookie('csrftoken') + }, + transformRequest: function(obj) { + var str = []; + for(var p in obj) + str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); + return str.join("&"); + } + }).then(function(response) { + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: 'Setting updated successfully.', + type: 'success' + }); + } else { + wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change + new PNotify({ + title: 'Error', + text: 'Failed to update setting.', + type: 'error' + }); + } + }).catch(function(error) { + wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change + new PNotify({ + title: 'Error', + text: 'Connection failed while updating setting.', + type: 'error' + }); + }); + }; + $scope.cyberPanelLoading = true; $scope.issueSSL = function (virtualHost) { @@ -8198,84 +8240,73 @@ app.controller('listWebsites', function ($scope, $http, $window) { // Call it immediately $scope.getFurtherWebsitesFromDB(); - $scope.showWPSites = function(domain) { - var config = { + $scope.showWPSites = function(index) { + console.log('showWPSites called with index:', index); + console.log('Current WebSitesList:', $scope.WebSitesList); + + $scope.selectedWebsite = $scope.WebSitesList[index]; + console.log('Selected website:', $scope.selectedWebsite); + + // Always fetch fresh data + var url = '/websites/FetchWPdata'; + var data = { + domain: $scope.selectedWebsite.domain, + websiteName: $scope.selectedWebsite.domain + }; + + $http({ + method: 'POST', + url: url, + data: JSON.stringify(data), headers: { + 'Content-Type': 'application/json', 'X-CSRFToken': getCookie('csrftoken') } - }; - - var data = { - domain: domain - }; - - var url = '/websites/GetWPSitesByDomain'; - - $http.post(url, data, config).then(function(response) { - if (response.data.status === 1) { - // Find the website in the list and update its WordPress sites - for (var i = 0; i < $scope.WebSitesList.length; i++) { - if ($scope.WebSitesList[i].domain === domain) { - $scope.WebSitesList[i].wp_sites = response.data.data; - $scope.WebSitesList[i].showWPSites = !$scope.WebSitesList[i].showWPSites; - break; - } + }).then(function(response) { + console.log('WP Details Response:', response); + + // Check if response is HTML (login page) + if (typeof response.data === 'string' && response.data.includes('')) { + console.log('Received HTML response, redirecting to login'); + window.location.href = '/login'; + return; + } + + if (response.data && response.data.status === 1) { + try { + // If single site, wrap in array + var sites = Array.isArray(response.data.data) ? response.data.data : [response.data.data]; + + $scope.selectedWebsite.wp_sites = sites.map(function(site) { + return { + id: site.id || $scope.selectedWebsite.domain, + title: site.title || site.domain || $scope.selectedWebsite.domain, + url: site.url || 'http://' + $scope.selectedWebsite.domain, + version: site.version || 'Unknown', + phpVersion: site.php_version || 'Unknown', + theme: site.theme || 'Unknown', + activePlugins: site.active_plugins || 0, + searchIndex: site.search_index === 'enabled', + debugging: site.debugging === 'enabled', + passwordProtection: site.password_protection === 'enabled', + maintenanceMode: site.maintenance_mode === 'enabled' + }; + }); + $scope.selectedWebsite.showWPSites = true; + } catch (e) { + console.error('Error processing WordPress data:', e); + $scope.selectedWebsite.showWPSites = false; + $scope.selectedWebsite.wp_sites = []; } } else { console.error('Error fetching WordPress sites:', response.data.error_message); - new PNotify({ - title: 'Error!', - text: response.data.error_message, - type: 'error' - }); + $scope.selectedWebsite.showWPSites = false; + $scope.selectedWebsite.wp_sites = []; } }, function(error) { console.error('Error fetching WordPress sites:', error); - new PNotify({ - title: 'Error!', - text: 'Failed to fetch WordPress sites. Please try again.', - type: 'error' - }); - }); - }; - - $scope.updateSetting = function(wpId, setting, value) { - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - var data = { - siteId: wpId, - setting: setting, - value: value - }; - - var url = '/websites/UpdateWPSettings'; - - $http.post(url, data, config).then(function(response) { - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Setting updated successfully.', - type: 'success' - }); - } else { - console.error('Error updating setting:', response.data.error_message); - new PNotify({ - title: 'Error!', - text: response.data.error_message, - type: 'error' - }); - } - }, function(error) { - console.error('Error updating setting:', error); - new PNotify({ - title: 'Error!', - text: 'Failed to update setting. Please try again.', - type: 'error' - }); + $scope.selectedWebsite.showWPSites = false; + $scope.selectedWebsite.wp_sites = []; }); }; @@ -8291,6 +8322,59 @@ app.controller('listWebsites', function ($scope, $http, $window) { window.location.href = '/websites/listWPsites?wpID=' + wpId; }; + $scope.updateSetting = function(wp, setting) { + var settingMap = { + 'search-indexing': 'searchIndex', + 'debugging': 'debugging', + 'password-protection': 'passwordProtection', + 'maintenance-mode': 'maintenanceMode' + }; + + var data = { + wpID: wp.id, + setting: setting, + value: wp[settingMap[setting]] ? 'enable' : 'disable' + }; + + $http({ + method: 'POST', + url: '/websites/UpdateWPSettings', + data: data, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'X-CSRFToken': getCookie('csrftoken') + }, + transformRequest: function(obj) { + var str = []; + for(var p in obj) + str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); + return str.join("&"); + } + }).then(function(response) { + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: 'Setting updated successfully.', + type: 'success' + }); + } else { + wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change + new PNotify({ + title: 'Error', + text: 'Failed to update setting.', + type: 'error' + }); + } + }).catch(function(error) { + wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change + new PNotify({ + title: 'Error', + text: 'Connection failed while updating setting.', + type: 'error' + }); + }); + }; + $scope.cyberPanelLoading = true; $scope.issueSSL = function (virtualHost) { @@ -12093,82 +12177,124 @@ app.controller('manageAliasController', function ($scope, $http, $timeout, $wind } - $scope.showWPSites = function(domain) { - var config = { + $scope.showWPSites = function(index) { + console.log('showWPSites called with index:', index); + console.log('Current WebSitesList:', $scope.WebSitesList); + + $scope.selectedWebsite = $scope.WebSitesList[index]; + console.log('Selected website:', $scope.selectedWebsite); + + // Always fetch fresh data + var url = '/websites/FetchWPdata'; + var data = { + domain: $scope.selectedWebsite.domain, + websiteName: $scope.selectedWebsite.domain + }; + + $http({ + method: 'POST', + url: url, + data: JSON.stringify(data), headers: { + 'Content-Type': 'application/json', 'X-CSRFToken': getCookie('csrftoken') } - }; - - var data = { - domain: domain - }; - - var url = '/websites/GetWPSitesByDomain'; - - $http.post(url, data, config).then(function(response) { - if (response.data.status === 1) { - // Find the website in the list and update its WordPress sites - for (var i = 0; i < $scope.WebSitesList.length; i++) { - if ($scope.WebSitesList[i].domain === domain) { - $scope.WebSitesList[i].wp_sites = response.data.data; - $scope.WebSitesList[i].showWPSites = !$scope.WebSitesList[i].showWPSites; - break; - } + }).then(function(response) { + console.log('WP Details Response:', response); + + // Check if response is HTML (login page) + if (typeof response.data === 'string' && response.data.includes('')) { + console.log('Received HTML response, redirecting to login'); + window.location.href = '/login'; + return; + } + + if (response.data && response.data.status === 1) { + try { + // If single site, wrap in array + var sites = Array.isArray(response.data.data) ? response.data.data : [response.data.data]; + + $scope.selectedWebsite.wp_sites = sites.map(function(site) { + return { + id: site.id || $scope.selectedWebsite.domain, + title: site.title || site.domain || $scope.selectedWebsite.domain, + url: site.url || 'http://' + $scope.selectedWebsite.domain, + version: site.version || 'Unknown', + phpVersion: site.php_version || 'Unknown', + theme: site.theme || 'Unknown', + activePlugins: site.active_plugins || 0, + searchIndex: site.search_index === 'enabled', + debugging: site.debugging === 'enabled', + passwordProtection: site.password_protection === 'enabled', + maintenanceMode: site.maintenance_mode === 'enabled' + }; + }); + $scope.selectedWebsite.showWPSites = true; + } catch (e) { + console.error('Error processing WordPress data:', e); + $scope.selectedWebsite.showWPSites = false; + $scope.selectedWebsite.wp_sites = []; } } else { console.error('Error fetching WordPress sites:', response.data.error_message); - new PNotify({ - title: 'Error!', - text: response.data.error_message, - type: 'error' - }); + $scope.selectedWebsite.showWPSites = false; + $scope.selectedWebsite.wp_sites = []; } }, function(error) { console.error('Error fetching WordPress sites:', error); - new PNotify({ - title: 'Error!', - text: 'Failed to fetch WordPress sites. Please try again.', - type: 'error' - }); + $scope.selectedWebsite.showWPSites = false; + $scope.selectedWebsite.wp_sites = []; }); }; - $scope.updateSetting = function(wpId, setting, value) { - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } + $scope.updateSetting = function(wp, setting) { + var settingMap = { + 'search-indexing': 'searchIndex', + 'debugging': 'debugging', + 'password-protection': 'passwordProtection', + 'maintenance-mode': 'maintenanceMode' }; var data = { - siteId: wpId, + wpID: wp.id, setting: setting, - value: value + value: wp[settingMap[setting]] ? 'enable' : 'disable' }; - var url = '/websites/UpdateWPSettings'; - - $http.post(url, data, config).then(function(response) { + $http({ + method: 'POST', + url: '/websites/UpdateWPSettings', + data: data, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'X-CSRFToken': getCookie('csrftoken') + }, + transformRequest: function(obj) { + var str = []; + for(var p in obj) + str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); + return str.join("&"); + } + }).then(function(response) { if (response.data.status === 1) { new PNotify({ - title: 'Success!', + title: 'Success', text: 'Setting updated successfully.', type: 'success' }); } else { - console.error('Error updating setting:', response.data.error_message); + wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change new PNotify({ - title: 'Error!', - text: response.data.error_message, + title: 'Error', + text: 'Failed to update setting.', type: 'error' }); } - }, function(error) { - console.error('Error updating setting:', error); + }).catch(function(error) { + wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change new PNotify({ - title: 'Error!', - text: 'Failed to update setting. Please try again.', + title: 'Error', + text: 'Connection failed while updating setting.', type: 'error' }); }); @@ -12186,15 +12312,73 @@ app.controller('manageAliasController', function ($scope, $http, $timeout, $wind window.location.href = '/websites/listWPsites?wpID=' + wpId; }; - $scope.cyberPanelLoading = true; - - $scope.issueSSL = function (virtualHost) { - $scope.cyberPanelLoading = false; - - url = "/websites/issueSSL"; + $scope.updateSetting = function(wp, setting) { + var settingMap = { + 'search-indexing': 'searchIndex', + 'debugging': 'debugging', + 'password-protection': 'passwordProtection', + 'maintenance-mode': 'maintenanceMode' + }; var data = { - virtualHost: virtualHost + wpID: wp.id, + setting: setting, + value: wp[settingMap[setting]] ? 'enable' : 'disable' + }; + + $http({ + method: 'POST', + url: '/websites/UpdateWPSettings', + data: data, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'X-CSRFToken': getCookie('csrftoken') + }, + transformRequest: function(obj) { + var str = []; + for(var p in obj) + str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); + return str.join("&"); + } + }).then(function(response) { + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: 'Setting updated successfully.', + type: 'success' + }); + } else { + wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change + new PNotify({ + title: 'Error', + text: 'Failed to update setting.', + type: 'error' + }); + } + }).catch(function(error) { + wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change + new PNotify({ + title: 'Error', + text: 'Connection failed while updating setting.', + type: 'error' + }); + }); + }; + + $scope.saveRewriteRules = function () { + + $scope.configFileLoading = false; + + + url = "/websites/saveRewriteRules"; + + var virtualHost = $("#childDomain").text(); + var rewriteRules = $scope.rewriteRules; + + + var data = { + virtualHost: virtualHost, + rewriteRules: rewriteRules, }; var config = { @@ -12205,34 +12389,69 @@ app.controller('manageAliasController', function ($scope, $http, $timeout, $wind $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + function ListInitialDatas(response) { - if (response.data.status === 1) { - $scope.cyberPanelLoading = true; - $scope.sslIssued = false; - $scope.couldNotIssueSSL = true; - $scope.couldNotConnect = true; + + if (response.data.rewriteStatus == 1) { + + $scope.configurationsBoxRewrite = false; + $scope.rewriteRulesFetched = true; + $scope.couldNotFetchRewriteRules = true; + $scope.rewriteRulesSaved = false; + $scope.couldNotSaveRewriteRules = true; + $scope.fetchedRewriteRules = true; + $scope.saveRewriteRulesBTN = true; + $scope.configFileLoading = true; + + } else { - $scope.cyberPanelLoading = true; - $scope.sslIssued = true; - $scope.couldNotIssueSSL = false; - $scope.couldNotConnect = true; + $scope.configurationsBoxRewrite = false; + $scope.rewriteRulesFetched = false; + $scope.couldNotFetchRewriteRules = true; + $scope.rewriteRulesSaved = true; + $scope.couldNotSaveRewriteRules = false; + $scope.fetchedRewriteRules = true; + $scope.saveRewriteRulesBTN = false; + + $scope.configFileLoading = true; + + $scope.errorMessage = response.data.error_message; + } + + } function cantLoadInitialDatas(response) { - $scope.cyberPanelLoading = true; - $scope.sslIssued = true; - $scope.couldNotIssueSSL = true; + + $scope.configurationsBoxRewrite = false; + $scope.rewriteRulesFetched = false; + $scope.couldNotFetchRewriteRules = true; + $scope.rewriteRulesSaved = true; + $scope.couldNotSaveRewriteRules = true; + $scope.fetchedRewriteRules = true; + $scope.saveRewriteRulesBTN = false; + + $scope.configFileLoading = true; + $scope.couldNotConnect = false; + + } + + }; + + //////// SSL Part + $scope.sslSaved = true; $scope.couldNotSaveSSL = true; $scope.hidsslconfigs = true; $scope.couldNotConnect = true; + $scope.hidesslbtn = function () { $scope.hidsslconfigs = true; }; @@ -12244,7 +12463,10 @@ app.controller('manageAliasController', function ($scope, $http, $timeout, $wind $scope.changePHPView = true; }; + $scope.saveSSL = function () { + + $scope.configFileLoading = false; url = "/websites/saveSSL"; @@ -12253,6 +12475,7 @@ app.controller('manageAliasController', function ($scope, $http, $timeout, $wind var cert = $scope.cert; var key = $scope.key; + var data = { virtualHost: virtualHost, cert: cert, @@ -12267,34 +12490,53 @@ app.controller('manageAliasController', function ($scope, $http, $timeout, $wind $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + function ListInitialDatas(response) { + if (response.data.sslStatus === 1) { + $scope.sslSaved = false; $scope.couldNotSaveSSL = true; $scope.couldNotConnect = true; $scope.configFileLoading = true; + + } else { + $scope.sslSaved = true; $scope.couldNotSaveSSL = false; $scope.couldNotConnect = true; $scope.configFileLoading = true; + $scope.errorMessage = response.data.error_message; + } + + } function cantLoadInitialDatas(response) { + $scope.sslSaved = true; $scope.couldNotSaveSSL = true; $scope.couldNotConnect = false; $scope.configFileLoading = true; + + } + }; + + //// Change PHP Master + $scope.failedToChangePHPMaster = true; $scope.phpChangedMaster = true; $scope.couldNotConnect = true; + $scope.changePHPView = true; + $scope.hideChangePHPMaster = function () { $scope.changePHPView = true; }; @@ -12306,7 +12548,11 @@ app.controller('manageAliasController', function ($scope, $http, $timeout, $wind $scope.changePHPView = false; }; + $scope.changePHPVersionMaster = function (childDomain, phpSelection) { + + // notifcations + $scope.configFileLoading = false; var url = "/websites/changePHP"; @@ -12324,36 +12570,63 @@ app.controller('manageAliasController', function ($scope, $http, $timeout, $wind $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + function ListInitialDatas(response) { + + if (response.data.changePHP === 1) { + $scope.configFileLoading = true; $scope.websiteDomain = $("#childDomain").text(); + + + // notifcations + $scope.failedToChangePHPMaster = true; $scope.phpChangedMaster = false; $scope.couldNotConnect = true; + + } else { + $scope.configFileLoading = true; $scope.errorMessage = response.data.error_message; + + // notifcations + $scope.failedToChangePHPMaster = false; $scope.phpChangedMaster = true; $scope.couldNotConnect = true; + } + + } function cantLoadInitialDatas(response) { + $scope.configFileLoading = true; + + // notifcations + $scope.failedToChangePHPMaster = true; $scope.phpChangedMaster = true; $scope.couldNotConnect = false; + } + }; + + /// Open_basedir protection + $scope.baseDirLoading = true; $scope.operationFailed = true; $scope.operationSuccessfull = true; $scope.couldNotConnect = true; $scope.openBaseDirBox = true; + $scope.openBaseDirView = function () { $scope.openBaseDirBox = false; }; @@ -12363,12 +12636,16 @@ app.controller('manageAliasController', function ($scope, $http, $timeout, $wind }; $scope.applyOpenBasedirChanges = function (childDomain, phpSelection) { + + // notifcations + $scope.baseDirLoading = false; $scope.operationFailed = true; $scope.operationSuccessfull = true; $scope.couldNotConnect = true; $scope.openBaseDirBox = false; + var url = "/websites/changeOpenBasedir"; var data = { @@ -12384,36 +12661,52 @@ app.controller('manageAliasController', function ($scope, $http, $timeout, $wind $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + function ListInitialDatas(response) { + + if (response.data.changeOpenBasedir === 1) { + $scope.baseDirLoading = true; $scope.operationFailed = true; $scope.operationSuccessfull = false; $scope.couldNotConnect = true; $scope.openBaseDirBox = false; + } else { + $scope.baseDirLoading = true; $scope.operationFailed = false; $scope.operationSuccessfull = true; $scope.couldNotConnect = true; $scope.openBaseDirBox = false; + $scope.errorMessage = response.data.error_message; + } + + } function cantLoadInitialDatas(response) { + $scope.baseDirLoading = true; $scope.operationFailed = true; $scope.operationSuccessfull = true; $scope.couldNotConnect = false; $scope.openBaseDirBox = false; + + } + } + }); /* Application Installer */ app.controller('installWordPressCTRL', function ($scope, $http, $timeout) { + $scope.installationDetailsForm = false; $scope.installationProgress = true; $scope.installationFailed = true; @@ -12426,6 +12719,7 @@ app.controller('installWordPressCTRL', function ($scope, $http, $timeout) { var domain = $("#domainNamePage").text(); var path; + $scope.goBack = function () { $scope.installationDetailsForm = false; $scope.installationProgress = true; @@ -12438,6 +12732,7 @@ app.controller('installWordPressCTRL', function ($scope, $http, $timeout) { }; $scope.installWordPress = function () { + $scope.installationDetailsForm = true; $scope.installationProgress = false; $scope.installationFailed = true; @@ -12449,6 +12744,7 @@ app.controller('installWordPressCTRL', function ($scope, $http, $timeout) { path = $scope.installPath; + url = "/websites/installWordpress"; var home = "1"; @@ -12457,6 +12753,7 @@ app.controller('installWordPressCTRL', function ($scope, $http, $timeout) { home = "0"; } + var data = { domain: domain, home: home, @@ -12475,11 +12772,14 @@ app.controller('installWordPressCTRL', function ($scope, $http, $timeout) { $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + function ListInitialDatas(response) { + if (response.data.installStatus === 1) { statusFile = response.data.tempStatusPath; getInstallStatus(); } else { + $scope.installationDetailsForm = true; $scope.installationProgress = false; $scope.installationFailed = false; @@ -12487,15 +12787,23 @@ app.controller('installWordPressCTRL', function ($scope, $http, $timeout) { $scope.couldNotConnect = true; $scope.wpInstallLoading = true; $scope.goBackDisable = false; + $scope.errorMessage = response.data.error_message; + } + + } function cantLoadInitialDatas(response) { + + } + }; function getInstallStatus() { + url = "/websites/installWordpressStatus"; var data = { @@ -12509,11 +12817,17 @@ app.controller('installWordPressCTRL', function ($scope, $http, $timeout) { } }; + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + function ListInitialDatas(response) { + + if (response.data.abort === 1) { + if (response.data.installStatus === 1) { + $scope.installationDetailsForm = true; $scope.installationProgress = false; $scope.installationFailed = true; @@ -12528,11 +12842,14 @@ app.controller('installWordPressCTRL', function ($scope, $http, $timeout) { $scope.installationURL = domain; } + $("#installProgress").css("width", "100%"); $scope.installPercentage = "100"; $scope.currentStatus = response.data.currentStatus; $timeout.cancel(); + } else { + $scope.installationDetailsForm = true; $scope.installationProgress = false; $scope.installationFailed = false; @@ -12545,21 +12862,33 @@ app.controller('installWordPressCTRL', function ($scope, $http, $timeout) { $("#installProgress").css("width", "0%"); $scope.installPercentage = "0"; + } + } else { $("#installProgress").css("width", response.data.installationProgress + "%"); $scope.installPercentage = response.data.installationProgress; $scope.currentStatus = response.data.currentStatus; $timeout(getInstallStatus, 1000); + + } + } function cantLoadInitialDatas(response) { + $scope.canNotFetch = true; $scope.couldNotConnect = false; + + } + + } + + }); app.controller('installJoomlaCTRL', function ($scope, $http, $timeout) { @@ -14748,108 +15077,16 @@ app.controller('manageGIT', function ($scope, $http, $timeout, $window) { } }; - $scope.showWPSites = function(domain) { - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + $scope.fetchGitignore = function () { + + $scope.cyberpanelLoading = false; + + url = "/websites/fetchGitignore"; + var data = { - domain: domain - }; - - var url = '/websites/GetWPSitesByDomain'; - - $http.post(url, data, config).then(function(response) { - if (response.data.status === 1) { - // Find the website in the list and update its WordPress sites - for (var i = 0; i < $scope.WebSitesList.length; i++) { - if ($scope.WebSitesList[i].domain === domain) { - $scope.WebSitesList[i].wp_sites = response.data.data; - $scope.WebSitesList[i].showWPSites = !$scope.WebSitesList[i].showWPSites; - break; - } - } - } else { - console.error('Error fetching WordPress sites:', response.data.error_message); - new PNotify({ - title: 'Error!', - text: response.data.error_message, - type: 'error' - }); - } - }, function(error) { - console.error('Error fetching WordPress sites:', error); - new PNotify({ - title: 'Error!', - text: 'Failed to fetch WordPress sites. Please try again.', - type: 'error' - }); - }); - }; - - $scope.updateSetting = function(wpId, setting, value) { - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - var data = { - siteId: wpId, - setting: setting, - value: value - }; - - var url = '/websites/UpdateWPSettings'; - - $http.post(url, data, config).then(function(response) { - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Setting updated successfully.', - type: 'success' - }); - } else { - console.error('Error updating setting:', response.data.error_message); - new PNotify({ - title: 'Error!', - text: response.data.error_message, - type: 'error' - }); - } - }, function(error) { - console.error('Error updating setting:', error); - new PNotify({ - title: 'Error!', - text: 'Failed to update setting. Please try again.', - type: 'error' - }); - }); - }; - - $scope.visitSite = function(url) { - window.open(url, '_blank'); - }; - - $scope.wpLogin = function(wpId) { - window.open('/websites/wpLogin?wpID=' + wpId, '_blank'); - }; - - $scope.manageWP = function(wpId) { - window.location.href = '/websites/listWPsites?wpID=' + wpId; - }; - - $scope.cyberPanelLoading = true; - - $scope.issueSSL = function (virtualHost) { - $scope.cyberPanelLoading = false; - - url = "/websites/issueSSL"; - - var data = { - virtualHost: virtualHost + domain: $("#domain").text(), + folder: $scope.folder }; var config = { @@ -14861,65 +15098,1051 @@ app.controller('manageGIT', function ($scope, $http, $timeout, $window) { $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); function ListInitialDatas(response) { - $scope.cyberPanelLoading = true; + $scope.cyberpanelLoading = true; if (response.data.status === 1) { - $scope.sslIssued = false; - $scope.couldNotIssueSSL = true; - $scope.couldNotConnect = true; + new PNotify({ + title: 'Success', + text: 'Successfully fetched.', + type: 'success' + }); + $scope.gitIgnoreContent = response.data.gitIgnoreContent; } else { - $scope.sslIssued = true; - $scope.couldNotIssueSSL = false; - $scope.couldNotConnect = true; - $scope.errorMessage = response.data.error_message; + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + + + } + + function cantLoadInitialDatas(response) { + $scope.cyberpanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page.', + type: 'error' + }); + + + } + }; + + $scope.saveGitIgnore = function () { + + $scope.cyberpanelLoading = false; + + url = "/websites/saveGitIgnore"; + + + var data = { + domain: $("#domain").text(), + folder: $scope.folder, + gitIgnoreContent: $scope.gitIgnoreContent + + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + function ListInitialDatas(response) { + $scope.cyberpanelLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: 'Successfully saved.', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + + + } + + function cantLoadInitialDatas(response) { + $scope.cyberpanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page.', + type: 'error' + }); + + + } + }; + + $scope.fetchCommits = function () { + + $scope.cyberpanelLoading = false; + + url = "/websites/fetchCommits"; + + + var data = { + domain: $("#domain").text(), + folder: $scope.folder + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + function ListInitialDatas(response) { + $scope.cyberpanelLoading = true; + $scope.gitCommitsTable = false; + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: 'Successfully fetched.', + type: 'success' + }); + $scope.commits = JSON.parse(response.data.commits); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + + + } + + function cantLoadInitialDatas(response) { + $scope.cyberpanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page.', + type: 'error' + }); + + + } + }; + + var currentComit; + var fetchFileCheck = 0; + var initial = 1; + + $scope.fetchFiles = function (commit) { + + currentComit = commit; + $scope.cyberpanelLoading = false; + + if (initial === 1) { + initial = 0; + } else { + fetchFileCheck = 1; + } + + url = "/websites/fetchFiles"; + + + var data = { + domain: $("#domain").text(), + folder: $scope.folder, + commit: commit + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + function ListInitialDatas(response) { + $scope.cyberpanelLoading = true; + $scope.gitCommitsTable = false; + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: 'Successfully fetched.', + type: 'success' + }); + $scope.files = response.data.files; + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + + + } + + function cantLoadInitialDatas(response) { + $scope.cyberpanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page.', + type: 'error' + }); + + + } + }; + + $scope.fileStatus = true; + + $scope.fetchChangesInFile = function () { + $scope.fileStatus = true; + + if (fetchFileCheck === 1) { + fetchFileCheck = 0; + return 0; + } + + $scope.cyberpanelLoading = false; + $scope.currentSelectedFile = $scope.changeFile; + + url = "/websites/fetchChangesInFile"; + + var data = { + domain: $("#domain").text(), + folder: $scope.folder, + file: $scope.changeFile, + commit: currentComit + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + function ListInitialDatas(response) { + $scope.cyberpanelLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: 'Successfully fetched.', + type: 'success' + }); + $scope.fileStatus = false; + document.getElementById("fileChangedContent").innerHTML = response.data.fileChangedContent; + } else { + $scope.fileStatus = true; + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); } } function cantLoadInitialDatas(response) { - $scope.cyberPanelLoading = true; - $scope.sslIssued = true; - $scope.couldNotIssueSSL = true; - $scope.couldNotConnect = false; + $scope.cyberpanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page.', + type: 'error' + }); + + } }; + + $scope.saveGitConfigurations = function () { + + $scope.cyberpanelLoading = false; + + url = "/websites/saveGitConfigurations"; + + var data = { + domain: $("#domain").text(), + folder: $scope.folder, + autoCommit: $scope.autoCommit, + autoPush: $scope.autoPush, + emailLogs: $scope.emailLogs, + commands: document.getElementById("currentCommands").value, + webhookCommand: $scope.webhookCommand + }; + + if ($scope.autoCommit === undefined) { + $scope.autoCommitCurrent = 'Never'; + } else { + $scope.autoCommitCurrent = $scope.autoCommit; + } + + if ($scope.autoPush === undefined) { + $scope.autoPushCurrent = 'Never'; + } else { + $scope.autoPushCurrent = $scope.autoPush; + } + + if ($scope.emailLogs === undefined) { + $scope.emailLogsCurrent = false; + } else { + $scope.emailLogsCurrent = $scope.emailLogs; + } + + if ($scope.webhookCommand === undefined) { + $scope.webhookCommandCurrent = false; + } else { + $scope.webhookCommandCurrent = $scope.webhookCommand; + } + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + function ListInitialDatas(response) { + $scope.cyberpanelLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: 'Successfully saved.', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialDatas(response) { + $scope.cyberpanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page.', + type: 'error' + }); + + + } + }; + + $scope.currentPage = 1; + $scope.recordsToShow = 10; + + $scope.fetchGitLogs = function () { + $scope.cyberpanelLoading = false; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + var data = { + domain: $("#domain").text(), + folder: $scope.folder, + page: $scope.currentPage, + recordsToShow: $scope.recordsToShow + }; + + + dataurl = "/websites/fetchGitLogs"; + + $http.post(dataurl, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + function ListInitialDatas(response) { + $scope.cyberpanelLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: 'Successfully fetched.', + type: 'success' + }); + $scope.logs = JSON.parse(response.data.logs); + $scope.pagination = response.data.pagination; + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialDatas(response) { + $scope.cyberpanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page.', + type: 'error' + }); + + + } + + + }; + }); -/* Java script code to delete website ends here */ +/* Java script code to git tracking ends here */ -/* Java script code to modify package ends here */ -/* Java script code to suspend/un-suspend ends here */ +app.controller('ApacheManager', function ($scope, $http, $timeout) { + $scope.cyberpanelloading = true; + $scope.apacheOLS = true; + $scope.pureOLS = true; + $scope.lswsEnt = true; -/* Java script code to manage cron */ + var apache = 1, ols = 2, lsws = 3; + var statusFile; -/* Java script code to manage cron ends here */ + $scope.getSwitchStatus = function () { + $scope.cyberpanelloading = false; + url = "/websites/getSwitchStatus"; -/* Java script code to manage cron */ + var data = { + domainName: $("#domainNamePage").text() + }; -/* Java script code to syncWebsite ends here */ + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; -/* Application Installer */ + $http.post(url, data, config).then(ListInitialData, cantLoadInitialData); -app.controller('installWordPressCTRL', function ($scope, $http, $timeout) { + + function ListInitialData(response) { + $scope.cyberpanelloading = true; + if (response.data.status === 1) { + if (response.data.server === apache) { + $scope.apacheOLS = false; + $scope.pureOLS = true; + $scope.lswsEnt = true; + $scope.configData = response.data.configData; + + $scope.pmMaxChildren = response.data.pmMaxChildren; + $scope.pmStartServers = response.data.pmStartServers; + $scope.pmMinSpareServers = response.data.pmMinSpareServers; + $scope.pmMaxSpareServers = response.data.pmMaxSpareServers; + $scope.phpPath = response.data.phpPath; + + + } else if (response.data.server === ols) { + $scope.apacheOLS = true; + $scope.pureOLS = false; + $scope.lswsEnt = true; + } else { + $scope.apacheOLS = true; + $scope.pureOLS = true; + $scope.lswsEnt = false; + } + //$scope.records = JSON.parse(response.data.data); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialData(response) { + $scope.cyberpanelloading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page.', + type: 'error' + }); + } + + + }; + $scope.getSwitchStatus(); + + $scope.switchServer = function (server) { + $scope.cyberpanelloading = false; + $scope.functionProgress = {"width": "0%"}; + $scope.functionStatus = 'Starting conversion..'; + + url = "/websites/switchServer"; + + var data = { + domainName: $("#domainNamePage").text(), + phpSelection: $scope.phpSelection, + server: server + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialData, cantLoadInitialData); + + function ListInitialData(response) { + if (response.data.status === 1) { + statusFile = response.data.tempStatusPath; + statusFunc(); + + } else { + $scope.cyberpanelloading = true; + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + + } + + function cantLoadInitialData(response) { + $scope.cyberpanelloading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page.', + type: 'error' + }); + } + + + }; + + function statusFunc() { + $scope.cyberpanelloading = false; + url = "/websites/statusFunc"; + + var data = { + statusFile: statusFile + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialData, cantLoadInitialData); + + + function ListInitialData(response) { + if (response.data.status === 1) { + if (response.data.abort === 1) { + $scope.functionProgress = {"width": "100%"}; + $scope.functionStatus = response.data.currentStatus; + $scope.cyberpanelloading = true; + $timeout.cancel(); + $scope.getSwitchStatus(); + } else { + $scope.functionProgress = {"width": response.data.installationProgress + "%"}; + $scope.functionStatus = response.data.currentStatus; + $timeout(statusFunc, 3000); + } + + } else { + $scope.cyberpanelloading = true; + $scope.functionStatus = response.data.error_message; + $scope.functionProgress = {"width": response.data.installationProgress + "%"}; + $timeout.cancel(); + } + + } + + function cantLoadInitialData(response) { + $scope.functionProgress = {"width": response.data.installationProgress + "%"}; + $scope.functionStatus = 'Could not connect to server, please refresh this page.'; + $timeout.cancel(); + } + + } + + + $scope.tuneSettings = function () { + $scope.cyberpanelloading = false; + + url = "/websites/tuneSettings"; + + var data = { + domainName: $("#domainNamePage").text(), + pmMaxChildren: $scope.pmMaxChildren, + pmStartServers: $scope.pmStartServers, + pmMinSpareServers: $scope.pmMinSpareServers, + pmMaxSpareServers: $scope.pmMaxSpareServers, + phpPath: $scope.phpPath + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialData, cantLoadInitialData); + + function ListInitialData(response) { + $scope.cyberpanelloading = true; + if (response.data.status === 1) { + + new PNotify({ + title: 'Success', + text: 'Changes successfully applied.', + type: 'success' + }); + + } else { + $scope.cyberpanelloading = true; + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + + } + + function cantLoadInitialData(response) { + $scope.cyberpanelloading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page.', + type: 'error' + }); + } + + + }; + + $scope.saveApacheConfig = function () { + $scope.cyberpanelloading = false; + + url = "/websites/saveApacheConfigsToFile"; + + var data = { + domainName: $("#domainNamePage").text(), + configData: $scope.configData + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialData, cantLoadInitialData); + + function ListInitialData(response) { + $scope.cyberpanelloading = true; + if (response.data.status === 1) { + + new PNotify({ + title: 'Success', + text: 'Changes successfully applied.', + type: 'success' + }); + + } else { + $scope.cyberpanelloading = true; + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + + } + + function cantLoadInitialData(response) { + $scope.cyberpanelloading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page.', + type: 'error' + }); + } + + + }; + +}); + + +app.controller('createDockerPackage', function ($scope, $http, $window) { + $scope.cyberpanelLoading = true; + + $scope.createdockerpackage = function () { + + $scope.cyberpanelLoading = false; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + var data = { + name: $scope.packagesname, + cpu: $scope.CPU, + Memory: $scope.Memory, + Bandwidth: $scope.Bandwidth, + disk: $scope.disk + }; + + + dataurl = "/websites/AddDockerpackage"; + + $http.post(dataurl, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + function ListInitialDatas(response) { + $scope.cyberpanelLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: 'Successfully Saved.', + type: 'success' + }); + + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialDatas(response) { + $scope.cyberpanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page.', + type: 'error' + }); + + + } + } + + + $scope.Getpackage = function (packid) { + + $scope.cyberpanelLoading = false; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + var data = { + id: packid, + }; + + + dataurl = "/websites/Getpackage"; + + $http.post(dataurl, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + function ListInitialDatas(response) { + $scope.cyberpanelLoading = true; + if (response.data.status === 1) { + $scope.U_Name = response.data.error_message.obj.Name + $scope.U_CPU = response.data.error_message.obj.CPU + $scope.U_Memory = response.data.error_message.obj.Memory + $scope.U_Bandwidth = response.data.error_message.obj.Bandwidth + $scope.U_DiskSpace = response.data.error_message.obj.DiskSpace + + $scope.EidtID = packid; + + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialDatas(response) { + $scope.cyberpanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page.', + type: 'error' + }); + + + } + } + + + $scope.SaveUpdate = function () { + + $scope.cyberpanelLoading = false; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + var data = { + id: $scope.EidtID, + CPU: $scope.U_CPU, + RAM: $scope.U_Memory, + Bandwidth: $scope.U_Bandwidth, + DiskSpace: $scope.U_DiskSpace, + }; + + + dataurl = "/websites/Updatepackage"; + + $http.post(dataurl, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + function ListInitialDatas(response) { + $scope.cyberpanelLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: 'Successfully Updated.', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialDatas(response) { + $scope.cyberpanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page.', + type: 'error' + }); + + + } + } + + var FinalDeletepackageURL; + $scope.Deletepackage = function (url) { + FinalDeletepackageURL = url; + // console.log(FinalDeletepackageURL); + } + + $scope.ConfirmDelete = function () { + window.location.href = FinalDeletepackageURL + } + +}) +app.controller('AssignPackage', function ($scope, $http,) { + $scope.cyberpanelLoading = true; + $scope.AddAssignment = function () { + $scope.cyberpanelLoading = false; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + var data = { + package: $('#packageSelection').val(), + user: $scope.userSelection, + }; + + + dataurl = "/websites/AddAssignment"; + + $http.post(dataurl, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + function ListInitialDatas(response) { + $scope.cyberpanelLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: 'Successfully saved.', + type: 'success' + }); + + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialDatas(response) { + $scope.cyberpanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page.', + type: 'error' + }); + + + } + } + + var FinalDeletepackageURL; + $scope.Deleteassingment = function (url) { + FinalDeletepackageURL = url; + // console.log(FinalDeletepackageURL); + } + + $scope.ConfirmDelete = function () { + window.location.href = FinalDeletepackageURL + } + +}) +app.controller('createDockerSite', function ($scope, $http, $timeout) { + $scope.cyberpanelLoading = true; $scope.installationDetailsForm = false; $scope.installationProgress = true; - $scope.installationFailed = true; - $scope.installationSuccessfull = true; + $scope.errorMessageBox = true; + $scope.success = true; $scope.couldNotConnect = true; - $scope.wpInstallLoading = true; $scope.goBackDisable = true; var statusFile; - var domain = $("#domainNamePage").text(); - var path; + $scope.createdockersite = function () { + + $scope.cyberpanelLoading = false; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + + $scope.currentStatus = "Starting creation.."; + + + url = "/websites/submitDockerSiteCreation"; + + var package = $scope.packageForWebsite; + + + var data = { + sitename: $scope.siteName, + Owner: $scope.userSelection, + Domain: $scope.domainNameCreate, + MysqlCPU: $scope.CPUMysql, + MYsqlRam: $scope.rammysql, + SiteCPU: $scope.CPUSite, + SiteRam: $scope.RamSite, + App: $scope.App, + WPusername: $scope.WPUsername, + WPemal: $scope.wpEmail, + WPpasswd: $scope.WPpassword + }; + + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + console.log('.........................') + if (response.data.installStatus === 1) { + console.log(response.data.installsatus) + statusFile = response.data.tempStatusPath; + getCreationStatus(); + } else { + + $scope.cyberpanelLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = false; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $scope.errorMessage = response.data.error_message; + } + + + } + + function cantLoadInitialDatas(response) { + + $scope.cyberpanelLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = false; + $scope.goBackDisable = false; + + } + + + }; $scope.goBack = function () { + $scope.cyberpanelLoading = true; $scope.installationDetailsForm = false; $scope.installationProgress = true; - $scope.installationFailed = true; - $scope.installationSuccessfull = true; + $scope.errorMessageBox = true; + $scope.success = true; $scope.couldNotConnect = true; - $scope.wpInstallLoading = true; - $scope.goBackDisable = false; + $scope.goBackDisable = true; + $("#installProgress").css("width", "0%"); + }; + + function getCreationStatus() { + + url = "/websites/installWordpressStatus"; + + var data = { + statusFile: statusFile + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + + if (response.data.abort === 1) { + + if (response.data.installStatus === 1) { + + $scope.cyberpanelLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = false; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; $("#installProgress").css("width", "100%"); $scope.installPercentage = "100"; diff --git a/websiteFunctions/templates/websiteFunctions/listWebsites.html b/websiteFunctions/templates/websiteFunctions/listWebsites.html index 0238e3a86..a0a4481cf 100755 --- a/websiteFunctions/templates/websiteFunctions/listWebsites.html +++ b/websiteFunctions/templates/websiteFunctions/listWebsites.html @@ -101,7 +101,7 @@
- {$ web.wp_sites.length $} WordPress Sites @@ -110,76 +110,68 @@
-
-
-
WordPress Sites
-
-
+
+
-
-
-
-
{{site.title}}
-
- - - -
-
-
-
-
-

WordPress Version: {{site.version}}

-

PHP Version: {{site.phpVersion}}

-

Active Theme: {{site.theme}}

-

Active Plugins: {{site.activePlugins}}

-
-
-
-
- - -
-
-
-
- - -
-
-
-
- - -
-
-
-
- - -
-
-
-
-
+
+

+
+
+ + +
+
+ +
+
+
+
WordPress
+
+
+
+
+
+
PHP Version
+
PHP {$ wp.phpVersion $}
+
+
+
+
+
Theme
+
+
+
+
+
+
Plugins
+
{$ wp.activePlugins $} active
+
+
+
+ +
+
+
+ + Search engine indexing +
+
+ + Debugging +
+
+
+
+ + Password protection +
+
+ + Maintenance mode
diff --git a/websiteFunctions/website.py b/websiteFunctions/website.py index dda9715a9..132f4db93 100755 --- a/websiteFunctions/website.py +++ b/websiteFunctions/website.py @@ -1940,7 +1940,7 @@ class WebsiteManager: try: currentACL = ACLManager.loadedACL(userID) admin = Administrator.objects.get(pk=userID) - + siteId = data['siteId'] setting = data['setting'] value = data['value'] @@ -1949,7 +1949,7 @@ class WebsiteManager: if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) != 1: return ACLManager.loadError() - + extraArgs = {} extraArgs['adminID'] = admin.pk extraArgs['siteId'] = siteId @@ -1979,7 +1979,7 @@ class WebsiteManager: if ACLManager.checkOwnership(domain, admin, currentACL) == 1: pass - else: + else: return ACLManager.loadError() # Get all WP sites for this website @@ -2008,28 +2008,29 @@ class WebsiteManager: # Get active theme command = f'sudo -u {website.externalApp} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp theme list --skip-plugins --skip-themes --format=json --path={wp.path}' - theme_output = ProcessUtilities.outputExecutioner(command) + themes_output = ProcessUtilities.outputExecutioner(command) try: - themes = json.loads(theme_output.splitlines()[-1]) + themes = json.loads(themes_output.splitlines()[-1]) active_theme = next((t['name'] for t in themes if t['status'] == 'active'), 'Unknown') except: active_theme = 'Unknown' - # Get debugging status - command = f'sudo -u {website.externalApp} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp config get WP_DEBUG --skip-plugins --skip-themes --path={wp.path}' - debugging = ProcessUtilities.outputExecutioner(command).strip() == 'true' + # Get other WP settings + command = f'sudo -u {website.externalApp} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp config list --skip-plugins --skip-themes --path={wp.path}' + config_output = ProcessUtilities.outputExecutioner(command) + debugging = 1 if 'WP_DEBUG\ttrue\tconstant' in config_output else 0 - # Get search indexing status command = f'sudo -u {website.externalApp} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp option get blog_public --skip-plugins --skip-themes --path={wp.path}' - search_index = ProcessUtilities.outputExecutioner(command).strip() == '1' + search_index = int(ProcessUtilities.outputExecutioner(command).splitlines()[-1]) - # Get maintenance mode status command = f'sudo -u {website.externalApp} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp maintenance-mode status --skip-plugins --skip-themes --path={wp.path}' - maintenance_mode = 'Active' in ProcessUtilities.outputExecutioner(command) + maintenance_output = ProcessUtilities.outputExecutioner(command) + maintenance_mode = 0 if 'not active' in maintenance_output.splitlines()[-1] else 1 - # Get password protection status - command = f'sudo -u {website.externalApp} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp option get wp_page_for_privacy_policy --skip-plugins --skip-themes --path={wp.path}' - password_protection = ProcessUtilities.outputExecutioner(command).strip() != '0' + # Check password protection + vhost_pass_dir = f'/home/{domain}' + path = f'{vhost_pass_dir}/{wp.id}' + password_protection = 1 if os.path.exists(path) else 0 sites_data.append({ 'id': wp.id, @@ -2062,37 +2063,2697 @@ class WebsiteManager: 'error_message': str(e) })) - def submitWebsiteModify(self, userID=None, data=None): + +class WebsiteManager: + apache = 1 + ols = 2 + lsws = 3 + + def __init__(self, domain=None, childDomain=None): + self.domain = domain + self.childDomain = childDomain + + def createWebsite(self, request=None, userID=None, data=None): + + url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" + data = { + "name": "all", + "IP": ACLManager.GetServerIP() + } + + import requests + response = requests.post(url, data=json.dumps(data)) + Status = response.json()['status'] + + test_domain_status = 0 + + if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: + test_domain_status = 1 + + currentACL = ACLManager.loadedACL(userID) + adminNames = ACLManager.loadAllUsers(userID) + packagesName = ACLManager.loadPackages(userID, currentACL) + phps = PHPManager.findPHPVersions() + + rnpss = randomPassword.generate_pass(10) + + Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps, 'Randam_String': rnpss.lower(), + 'test_domain_data': test_domain_status} + proc = httpProc(request, 'websiteFunctions/createWebsite.html', + Data, 'createWebsite') + return proc.render() + + def WPCreate(self, request=None, userID=None, data=None): + url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" + data = { + "name": "wp-manager", + "IP": ACLManager.GetServerIP() + } + + import requests + response = requests.post(url, data=json.dumps(data)) + Status = response.json()['status'] + + + if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: + currentACL = ACLManager.loadedACL(userID) + adminNames = ACLManager.loadAllUsers(userID) + packagesName = ACLManager.loadPackages(userID, currentACL) + + if len(packagesName) == 0: + packagesName = ['Default'] + + FinalVersions = [] + userobj = Administrator.objects.get(pk=userID) + counter = 0 + try: + import requests + WPVersions = json.loads(requests.get('https://api.wordpress.org/core/version-check/1.7/').text)[ + 'offers'] + + for versions in WPVersions: + if counter == 7: + break + if versions['current'] not in FinalVersions: + FinalVersions.append(versions['current']) + counter = counter + 1 + except: + FinalVersions = ['5.6', '5.5.3', '5.5.2'] + + Plugins = wpplugins.objects.filter(owner=userobj) + rnpss = randomPassword.generate_pass(10) + + ## + + test_domain_status = 1 + + Data = {'packageList': packagesName, "owernList": adminNames, 'WPVersions': FinalVersions, + 'Plugins': Plugins, 'Randam_String': rnpss.lower(), 'test_domain_data': test_domain_status} + proc = httpProc(request, 'websiteFunctions/WPCreate.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def ListWPSites(self, request=None, userID=None, DeleteID=None): + import json + currentACL = ACLManager.loadedACL(userID) + + admin = Administrator.objects.get(pk=userID) + data = {} + wp_sites = ACLManager.GetALLWPObjects(currentACL, userID) + data['wp'] = wp_sites + + try: + if DeleteID != None: + WPDelete = WPSites.objects.get(pk=DeleteID) + + if ACLManager.checkOwnership(WPDelete.owner.domain, admin, currentACL) == 1: + WPDelete.delete() + except BaseException as msg: + pass + + sites = [] + for site in data['wp']: + sites.append({ + 'id': site.id, + 'title': site.title, + 'url': site.FinalURL, + 'production_status': True + }) + + context = { + "wpsite": json.dumps(sites), + "status": 1, + "total_sites": len(sites), + "debug_info": json.dumps({ + "user_id": userID, + "is_admin": bool(currentACL.get('admin', 0)), + "wp_sites_count": wp_sites.count() + }) + } + + proc = httpProc(request, 'websiteFunctions/WPsitesList.html', context) + return proc.render() + + def WPHome(self, request=None, userID=None, WPid=None, DeleteID=None): + Data = {} + currentACL = ACLManager.loadedACL(userID) + WPobj = WPSites.objects.get(pk=WPid) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(WPobj.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + try: + + url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" + data = { + "name": "wp-manager", + "IP": ACLManager.GetServerIP() + } + + import requests + response = requests.post(url, data=json.dumps(data)) + Status = response.json()['status'] + + rnpss = randomPassword.generate_pass(10) + + Data['Randam_String'] = rnpss.lower() + + if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: + Data['wpsite'] = WPobj + Data['test_domain_data'] = 1 + + try: + DeleteID = request.GET.get('DeleteID', None) + + if DeleteID != None: + wstagingDelete = WPStaging.objects.get(pk=DeleteID, owner=WPobj) + wstagingDelete.delete() + + except BaseException as msg: + da = str(msg) + + proc = httpProc(request, 'websiteFunctions/WPsiteHome.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + except: + proc = httpProc(request, 'websiteFunctions/WPsiteHome.html', + Data, 'createDatabase') + return proc.render() + + def RestoreHome(self, request=None, userID=None, BackupID=None): + Data = {} + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.CheckForPremFeature('wp-manager'): + + Data['backupobj'] = WPSitesBackup.objects.get(pk=BackupID) + + if ACLManager.CheckIPBackupObjectOwner(currentACL, Data['backupobj'], admin) == 1: + pass + else: + return ACLManager.loadError() + + config = json.loads(Data['backupobj'].config) + Data['FileName'] = config['name'] + try: + Data['Backuptype'] = config['Backuptype'] + + if Data['Backuptype'] == 'DataBase Backup' or Data['Backuptype'] == 'Website Backup': + Data['WPsites'] = [WPSites.objects.get(pk=Data['backupobj'].WPSiteID)] + else: + Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) + + except: + Data['Backuptype'] = None + Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) + + proc = httpProc(request, 'websiteFunctions/WPRestoreHome.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def RemoteBackupConfig(self, request=None, userID=None, DeleteID=None): + Data = {} + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + try: + if DeleteID != None: + BackupconfigDelete = RemoteBackupConfig.objects.get(pk=DeleteID) + BackupconfigDelete.delete() + except: + pass + + if ACLManager.CheckForPremFeature('wp-manager'): + + Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) + allcon = RemoteBackupConfig.objects.all() + Data['backupconfigs'] = [] + for i in allcon: + configr = json.loads(i.config) + if i.configtype == "SFTP": + Data['backupconfigs'].append({ + 'id': i.pk, + 'Type': i.configtype, + 'HostName': configr['Hostname'], + 'Path': configr['Path'] + }) + elif i.configtype == "S3": + Provider = configr['Provider'] + if Provider == "Backblaze": + Data['backupconfigs'].append({ + 'id': i.pk, + 'Type': i.configtype, + 'HostName': Provider, + 'Path': configr['S3keyname'] + }) + else: + Data['backupconfigs'].append({ + 'id': i.pk, + 'Type': i.configtype, + 'HostName': Provider, + 'Path': configr['S3keyname'] + }) + + proc = httpProc(request, 'websiteFunctions/RemoteBackupConfig.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def BackupfileConfig(self, request=None, userID=None, RemoteConfigID=None, DeleteID=None): + Data = {} + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + Data['RemoteConfigID'] = RemoteConfigID + RemoteConfigobj = RemoteBackupConfig.objects.get(pk=RemoteConfigID) + try: + if DeleteID != None: + RemoteBackupConfigDelete = RemoteBackupSchedule.objects.get(pk=DeleteID) + RemoteBackupConfigDelete.delete() + except: + pass + + if ACLManager.CheckForPremFeature('wp-manager'): + Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) + allsechedule = RemoteBackupSchedule.objects.filter(RemoteBackupConfig=RemoteConfigobj) + Data['Backupschedule'] = [] + for i in allsechedule: + lastrun = i.lastrun + LastRun = time.strftime('%Y-%m-%d', time.localtime(float(lastrun))) + Data['Backupschedule'].append({ + 'id': i.pk, + 'Name': i.Name, + 'RemoteConfiguration': i.RemoteBackupConfig.configtype, + 'Retention': i.fileretention, + 'Frequency': i.timeintervel, + 'LastRun': LastRun + }) + proc = httpProc(request, 'websiteFunctions/BackupfileConfig.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def AddRemoteBackupsite(self, request=None, userID=None, RemoteScheduleID=None, DeleteSiteID=None): + Data = {} + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + Data['RemoteScheduleID'] = RemoteScheduleID + RemoteBackupScheduleobj = RemoteBackupSchedule.objects.get(pk=RemoteScheduleID) + + try: + if DeleteSiteID != None: + RemoteBackupsitesDelete = RemoteBackupsites.objects.get(pk=DeleteSiteID) + RemoteBackupsitesDelete.delete() + except: + pass + + if ACLManager.CheckForPremFeature('wp-manager'): + Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) + allRemoteBackupsites = RemoteBackupsites.objects.filter(owner=RemoteBackupScheduleobj) + Data['RemoteBackupsites'] = [] + for i in allRemoteBackupsites: + try: + wpsite = WPSites.objects.get(pk=i.WPsites) + Data['RemoteBackupsites'].append({ + 'id': i.pk, + 'Title': wpsite.title, + }) + except: + pass + proc = httpProc(request, 'websiteFunctions/AddRemoteBackupSite.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def WordpressPricing(self, request=None, userID=None, ): + Data = {} + proc = httpProc(request, 'websiteFunctions/CyberpanelPricing.html', Data, 'createWebsite') + return proc.render() + + def RestoreBackups(self, request=None, userID=None, DeleteID=None): + Data = {} + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" + data = { + "name": "wp-manager", + "IP": ACLManager.GetServerIP() + } + + import requests + response = requests.post(url, data=json.dumps(data)) + Status = response.json()['status'] + + if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: + + backobj = WPSitesBackup.objects.filter(owner=admin).order_by('-id') + + # if ACLManager.CheckIPBackupObjectOwner(currentACL, backobj, admin) == 1: + # pass + # else: + # return ACLManager.loadError() + + try: + if DeleteID != None: + DeleteIDobj = WPSitesBackup.objects.get(pk=DeleteID) + + if ACLManager.CheckIPBackupObjectOwner(currentACL, DeleteIDobj, admin) == 1: + config = DeleteIDobj.config + conf = json.loads(config) + FileName = conf['name'] + command = "rm -r /home/backup/%s.tar.gz" % FileName + ProcessUtilities.executioner(command) + DeleteIDobj.delete() + + except BaseException as msg: + pass + Data['job'] = [] + + for sub in backobj: + try: + wpsite = WPSites.objects.get(pk=sub.WPSiteID) + web = wpsite.title + except: + web = "Website Not Found" + + try: + config = sub.config + conf = json.loads(config) + Backuptype = conf['Backuptype'] + BackupDestination = conf['BackupDestination'] + except: + Backuptype = "Backup type not exists" + + Data['job'].append({ + 'id': sub.id, + 'title': web, + 'Backuptype': Backuptype, + 'BackupDestination': BackupDestination + }) + + proc = httpProc(request, 'websiteFunctions/RestoreBackups.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def AutoLogin(self, request=None, userID=None): + + WPid = request.GET.get('id') + currentACL = ACLManager.loadedACL(userID) + WPobj = WPSites.objects.get(pk=WPid) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(WPobj.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + from managePHP.phpManager import PHPManager + + php = PHPManager.getPHPString(WPobj.owner.phpSelection) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" + data = { + "name": "wp-manager", + "IP": ACLManager.GetServerIP() + } + + import requests + response = requests.post(url, data=json.dumps(data)) + Status = response.json()['status'] + + if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: + + ## Get title + + password = randomPassword.generate_pass(10) + + command = f'sudo -u %s {FinalPHPPath} /usr/bin/wp user create autologin %s --role=administrator --user_pass="%s" --path=%s --skip-plugins --skip-themes' % ( + WPobj.owner.externalApp, 'autologin@cloudpages.cloud', password, WPobj.path) + ProcessUtilities.executioner(command) + + command = f'sudo -u %s {FinalPHPPath} /usr/bin/wp user update autologin --user_pass="%s" --path=%s --skip-plugins --skip-themes' % ( + WPobj.owner.externalApp, password, WPobj.path) + ProcessUtilities.executioner(command) + + data = {} + + if WPobj.FinalURL.endswith('/'): + FinalURL = WPobj.FinalURL[:-1] + else: + FinalURL = WPobj.FinalURL + + data['url'] = 'https://%s' % (FinalURL) + data['userName'] = 'autologin' + data['password'] = password + + proc = httpProc(request, 'websiteFunctions/AutoLogin.html', + data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def ConfigurePlugins(self, request=None, userID=None, data=None): + + if ACLManager.CheckForPremFeature('wp-manager'): + currentACL = ACLManager.loadedACL(userID) + userobj = Administrator.objects.get(pk=userID) + + Selectedplugins = wpplugins.objects.filter(owner=userobj) + # data['Selectedplugins'] = wpplugins.objects.filter(ProjectOwner=HostingCompany) + + Data = {'Selectedplugins': Selectedplugins, } + proc = httpProc(request, 'websiteFunctions/WPConfigurePlugins.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def Addnewplugin(self, request=None, userID=None, data=None): + from django.shortcuts import reverse + if ACLManager.CheckForPremFeature('wp-manager'): + currentACL = ACLManager.loadedACL(userID) + adminNames = ACLManager.loadAllUsers(userID) + packagesName = ACLManager.loadPackages(userID, currentACL) + phps = PHPManager.findPHPVersions() + + Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps} + proc = httpProc(request, 'websiteFunctions/WPAddNewPlugin.html', + Data, 'createDatabase') + return proc.render() + + return redirect(reverse('pricing')) + + def SearchOnkeyupPlugin(self, userID=None, data=None): + try: + if ACLManager.CheckForPremFeature('wp-manager'): + currentACL = ACLManager.loadedACL(userID) + + pluginname = data['pluginname'] + # logging.CyberCPLogFileWriter.writeToFile("Plugin Name ....... %s"%pluginname) + + url = "http://api.wordpress.org/plugins/info/1.1/?action=query_plugins&request[search]=%s" % str( + pluginname) + import requests + + res = requests.get(url) + r = res.json() + + # return proc.ajax(1, 'Done', {'plugins': r}) + + data_ret = {'status': 1, 'plugns': r, } + + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': 'Premium feature not available.'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def AddNewpluginAjax(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + + userobj = Administrator.objects.get(pk=userID) + + config = data['config'] + Name = data['Name'] + # pluginname = data['pluginname'] + # logging.CyberCPLogFileWriter.writeToFile("config ....... %s"%config) + # logging.CyberCPLogFileWriter.writeToFile(" Name ....... %s"%Name) + + addpl = wpplugins(Name=Name, config=json.dumps(config), owner=userobj) + addpl.save() + + data_ret = {'status': 1} + + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'AddNewpluginAjax': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def EidtPlugin(self, request=None, userID=None, pluginbID=None): + Data = {} + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + pluginobj = wpplugins.objects.get(pk=pluginbID) + + if ACLManager.CheckIPPluginObjectOwner(currentACL, pluginobj, admin) == 1: + pass + else: + return ACLManager.loadError() + + lmo = json.loads(pluginobj.config) + Data['Selectedplugins'] = lmo + Data['pluginbID'] = pluginbID + Data['BucketName'] = pluginobj.Name + + proc = httpProc(request, 'websiteFunctions/WPEidtPlugin.html', + Data, 'createDatabase') + return proc.render() + + def deletesPlgin(self, userID=None, data=None, ): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + userobj = Administrator.objects.get(pk=userID) + pluginname = data['pluginname'] + pluginbBucketID = data['pluginbBucketID'] + # logging.CyberCPLogFileWriter.writeToFile("pluginbID ....... %s" % pluginbBucketID) + # logging.CyberCPLogFileWriter.writeToFile("pluginname ....... %s" % pluginname) + + obj = wpplugins.objects.get(pk=pluginbBucketID, owner=userobj) + + if ACLManager.CheckIPPluginObjectOwner(currentACL, obj, admin) == 1: + pass + else: + return ACLManager.loadError() + + ab = [] + ab = json.loads(obj.config) + ab.remove(pluginname) + obj.config = json.dumps(ab) + obj.save() + + data_ret = {'status': 1} + + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + except BaseException as msg: + data_ret = {'status': 0, 'deletesPlgin': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def Addplugineidt(self, userID=None, data=None, ): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + userobj = Administrator.objects.get(pk=userID) + pluginname = data['pluginname'] + pluginbBucketID = data['pluginbBucketID'] + + # logging.CyberCPLogFileWriter.writeToFile("pluginbID ....... %s" % pluginbBucketID) + # logging.CyberCPLogFileWriter.writeToFile("pluginname ....... %s" % pluginname) + + pObj = wpplugins.objects.get(pk=pluginbBucketID, owner=userobj) + + if ACLManager.CheckIPPluginObjectOwner(currentACL, pObj, admin) == 1: + pass + else: + return ACLManager.loadError() + + listofplugin = json.loads(pObj.config) + try: + index = listofplugin.index(pluginname) + print('index.....%s' % index) + if (index >= 0): + data_ret = {'status': 0, 'deletesPlgin': 0, 'error_message': str('Already Save in your Plugin lis')} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except: + ab = [] + ab = json.loads(pObj.config) + ab.append(pluginname) + pObj.config = json.dumps(ab) + pObj.save() + + data_ret = {'status': 1} + + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + except BaseException as msg: + data_ret = {'status': 0, 'deletesPlgin': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def modifyWebsite(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + + websitesName = ACLManager.findAllSites(currentACL, userID) + phps = PHPManager.findPHPVersions() + proc = httpProc(request, 'websiteFunctions/modifyWebsite.html', + {'websiteList': websitesName, 'phps': phps}, 'modifyWebsite') + return proc.render() + + def deleteWebsite(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + websitesName = ACLManager.findAllSites(currentACL, userID) + proc = httpProc(request, 'websiteFunctions/deleteWebsite.html', + {'websiteList': websitesName}, 'deleteWebsite') + return proc.render() + + def CreateNewDomain(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + websitesName = ACLManager.findAllSites(currentACL, userID) + + try: + admin = Administrator.objects.get(pk=userID) + if admin.defaultSite == 0: + websites = ACLManager.findWebsiteObjects(currentACL, userID) + admin.defaultSite = websites[0].id + admin.save() + except: + pass + + try: + admin = Administrator.objects.get(pk=userID) + defaultDomain = Websites.objects.get(pk=admin.defaultSite).domain + except: + try: + admin = Administrator.objects.get(pk=userID) + websites = ACLManager.findWebsiteObjects(currentACL, userID) + admin.defaultSite = websites[0].id + admin.save() + defaultDomain = websites[0].domain + except: + defaultDomain='NONE' + + + url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" + data = { + "name": "all", + "IP": ACLManager.GetServerIP() + } + + import requests + response = requests.post(url, data=json.dumps(data)) + Status = response.json()['status'] + + test_domain_status = 0 + + if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: + test_domain_status = 1 + + rnpss = randomPassword.generate_pass(10) + proc = httpProc(request, 'websiteFunctions/createDomain.html', + {'websiteList': websitesName, 'phps': PHPManager.findPHPVersions(), 'Randam_String': rnpss, + 'test_domain_data': test_domain_status, 'defaultSite': defaultDomain}) + return proc.render() + + def siteState(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + + websitesName = ACLManager.findAllSites(currentACL, userID) + + proc = httpProc(request, 'websiteFunctions/suspendWebsite.html', + {'websiteList': websitesName}, 'suspendWebsite') + return proc.render() + + def listWebsites(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + pagination = self.websitePagination(currentACL, userID) + proc = httpProc(request, 'websiteFunctions/listWebsites.html', + {"pagination": pagination}) + return proc.render() + + def listChildDomains(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + adminNames = ACLManager.loadAllUsers(userID) + packagesName = ACLManager.loadPackages(userID, currentACL) + phps = PHPManager.findPHPVersions() + + Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps} + proc = httpProc(request, 'websiteFunctions/listChildDomains.html', + Data) + return proc.render() + + def listCron(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(request.GET.get('domain'), admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + proc = httpProc(request, 'websiteFunctions/listCron.html', + {'domain': request.GET.get('domain')}) + return proc.render() + + def domainAlias(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + aliasManager = AliasManager(self.domain) + noAlias, finalAlisList = aliasManager.fetchAlisForDomains() + + path = "/home/" + self.domain + "/public_html" + + proc = httpProc(request, 'websiteFunctions/domainAlias.html', { + 'masterDomain': self.domain, + 'aliases': finalAlisList, + 'path': path, + 'noAlias': noAlias + }) + return proc.render() + + def FetchWPdata(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core version --skip-plugins --skip-themes --path=%s 2>/dev/null' % ( + Vhuser, FinalPHPPath, path) + version = ProcessUtilities.outputExecutioner(command, None, True) + version = html.escape(version) + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin status litespeed-cache --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, path) + lscachee = ProcessUtilities.outputExecutioner(command) + + if lscachee.find('Status: Active') > -1: + lscache = 1 + else: + lscache = 0 + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp config list --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, path) + stdout = ProcessUtilities.outputExecutioner(command) + debugging = 0 + for items in stdout.split('\n'): + if items.find('WP_DEBUG true constant') > -1: + debugging = 1 + break + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp option get blog_public --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, path) + stdoutput = ProcessUtilities.outputExecutioner(command) + searchindex = int(stdoutput.splitlines()[-1]) + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp maintenance-mode status --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, path) + maintenanceMod = ProcessUtilities.outputExecutioner(command) + + result = maintenanceMod.splitlines()[-1] + if result.find('not active') > -1: + maintenanceMode = 0 + else: + maintenanceMode = 1 + + ##### Check passwd protection + vhostName = wpsite.owner.domain + vhostPassDir = f'/home/{vhostName}' + path = f'{vhostPassDir}/{WPManagerID}' + if os.path.exists(path): + passwd = 1 + else: + passwd = 0 + + #### Check WP cron + command = "sudo -u %s cat %s/wp-config.php" % (Vhuser, wpsite.path) + stdout = ProcessUtilities.outputExecutioner(command) + if stdout.find("'DISABLE_WP_CRON', 'true'") > -1: + wpcron = 1 + else: + wpcron = 0 + + fb = { + 'version': version.rstrip('\n'), + 'lscache': lscache, + 'debugging': debugging, + 'searchIndex': searchindex, + 'maintenanceMode': maintenanceMode, + 'passwordprotection': passwd, + 'wpcron': wpcron + + } + + data_ret = {'status': 1, 'error_message': 'None', 'ret_data': fb} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def GetCurrentPlugins(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin list --skip-plugins --skip-themes --format=json --path=%s' % ( + Vhuser, FinalPHPPath, path) + stdoutput = ProcessUtilities.outputExecutioner(command) + json_data = stdoutput.splitlines()[-1] + + data_ret = {'status': 1, 'error_message': 'None', 'plugins': json_data} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def GetCurrentThemes(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp theme list --skip-plugins --skip-themes --format=json --path=%s' % ( + Vhuser, FinalPHPPath, path) + stdoutput = ProcessUtilities.outputExecutioner(command) + json_data = stdoutput.splitlines()[-1] + + data_ret = {'status': 1, 'error_message': 'None', 'themes': json_data} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def fetchstaging(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + from plogical.phpUtilities import phpUtilities + + json_data = phpUtilities.GetStagingInJson(wpsite.wpstaging_set.all().order_by('-id')) + + data_ret = {'status': 1, 'error_message': 'None', 'wpsites': json_data} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def fetchDatabase(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + php = PHPManager.getPHPString(wpsite.owner.phpSelection) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + command = f'{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config get DB_NAME --skip-plugins --skip-themes --path={wpsite.path} 2>/dev/null' + retStatus, stdoutput = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp, True, None, 1) + + if stdoutput.find('Error:') == -1: + DataBaseName = stdoutput.rstrip("\n") + DataBaseName = html.escape(DataBaseName) + else: + data_ret = {'status': 0, 'error_message': stdoutput} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + command = f'{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config get DB_USER --skip-plugins --skip-themes --path={wpsite.path} 2>/dev/null' + retStatus, stdoutput = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp, True, None, 1) + + if stdoutput.find('Error:') == -1: + DataBaseUser = stdoutput.rstrip("\n") + DataBaseUser = html.escape(DataBaseUser) + else: + data_ret = {'status': 0, 'error_message': stdoutput} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + command = f'{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config get table_prefix --skip-plugins --skip-themes --path={wpsite.path} 2>/dev/null' + retStatus, stdoutput = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp, True, None, 1) + + if stdoutput.find('Error:') == -1: + tableprefix = stdoutput.rstrip("\n") + tableprefix = html.escape(tableprefix) + else: + data_ret = {'status': 0, 'error_message': stdoutput} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + data_ret = {'status': 1, 'error_message': 'None', "DataBaseUser": DataBaseUser, + "DataBaseName": DataBaseName, 'tableprefix': tableprefix} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def SaveUpdateConfig(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + Plugins = data['Plugins'] + Themes = data['Themes'] + AutomaticUpdates = data['AutomaticUpdates'] + + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + + php = PHPManager.getPHPString(wpsite.owner.phpSelection) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + if AutomaticUpdates == 'Disabled': + command = f"{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_AUTO_UPDATE_CORE false --raw --allow-root --path=" + wpsite.path + result = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp) + + if result.find('Success:') == -1: + raise BaseException(result) + elif AutomaticUpdates == 'Minor and Security Updates': + command = f"{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_AUTO_UPDATE_CORE minor --allow-root --path=" + wpsite.path + result = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp) + + if result.find('Success:') == -1: + raise BaseException(result) + else: + command = f"{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_AUTO_UPDATE_CORE true --raw --allow-root --path=" + wpsite.path + result = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp) + + if result.find('Success:') == -1: + raise BaseException(result) + + wpsite.AutoUpdates = AutomaticUpdates + wpsite.PluginUpdates = Plugins + wpsite.ThemeUpdates = Themes + wpsite.save() + + data_ret = {'status': 1, 'error_message': 'None', } + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def DeploytoProduction(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + statgingID = data['StagingID'] + wpsite = WPSites.objects.get(pk=WPManagerID) + StagingObj = WPSites.objects.get(pk=statgingID) + + ### + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + if ACLManager.checkOwnership(StagingObj.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + ### + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['statgingID'] = statgingID + extraArgs['WPid'] = WPManagerID + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + background = ApplicationInstaller('DeploytoProduction', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def WPCreateBackup(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + Backuptype = data['Backuptype'] + + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['WPid'] = WPManagerID + extraArgs['Backuptype'] = Backuptype + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + background = ApplicationInstaller('WPCreateBackup', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def RestoreWPbackupNow(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + backupid = data['backupid'] + DesSiteID = data['DesSite'] + + # try: + # + # bwp = WPSites.objects.get(pk=int(backupid)) + # + # if ACLManager.checkOwnership(bwp.owner.domain, admin, currentACL) == 1: + # pass + # else: + # return ACLManager.loadError() + # + # except: + # pass + # + # dwp = WPSites.objects.get(pk=int(DesSiteID)) + # if ACLManager.checkOwnership(dwp.owner.domain, admin, currentACL) == 1: + # pass + # else: + # return ACLManager.loadError() + + Domain = data['Domain'] + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['backupid'] = backupid + extraArgs['DesSiteID'] = DesSiteID + extraArgs['Domain'] = Domain + extraArgs['path'] = data['path'] + extraArgs['home'] = data['home'] + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + background = ApplicationInstaller('RestoreWPbackupNow', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def SaveBackupConfig(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + ConfigType = data['type'] + if ConfigType == 'SFTP': + Hname = data['Hname'] + Uname = data['Uname'] + Passwd = data['Passwd'] + path = data['path'] + config = { + "Hostname": Hname, + "Username": Uname, + "Password": Passwd, + "Path": path + } + elif ConfigType == "S3": + Provider = data['Provider'] + if Provider == "Backblaze": + S3keyname = data['S3keyname'] + SecertKey = data['SecertKey'] + AccessKey = data['AccessKey'] + EndUrl = data['EndUrl'] + config = { + "Provider": Provider, + "S3keyname": S3keyname, + "SecertKey": SecertKey, + "AccessKey": AccessKey, + "EndUrl": EndUrl + + } + else: + S3keyname = data['S3keyname'] + SecertKey = data['SecertKey'] + AccessKey = data['AccessKey'] + config = { + "Provider": Provider, + "S3keyname": S3keyname, + "SecertKey": SecertKey, + "AccessKey": AccessKey, + + } + + mkobj = RemoteBackupConfig(owner=admin, configtype=ConfigType, config=json.dumps(config)) + mkobj.save() + + time.sleep(1) + + data_ret = {'status': 1, 'error_message': 'None', } + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def SaveBackupSchedule(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + FileRetention = data['FileRetention'] + Backfrequency = data['Backfrequency'] + ScheduleName = data['ScheduleName'] + RemoteConfigID = data['RemoteConfigID'] + BackupType = data['BackupType'] + + RemoteBackupConfigobj = RemoteBackupConfig.objects.get(pk=RemoteConfigID) + Rconfig = json.loads(RemoteBackupConfigobj.config) + + try: + # This code is only supposed to run if backups are s3, not for SFTP + provider = Rconfig['Provider'] + if provider == "Backblaze": + EndURl = Rconfig['EndUrl'] + elif provider == "Amazon": + EndURl = "https://s3.us-east-1.amazonaws.com" + elif provider == "Wasabi": + EndURl = "https://s3.wasabisys.com" + + AccessKey = Rconfig['AccessKey'] + SecertKey = Rconfig['SecertKey'] + + session = boto3.session.Session() + + client = session.client( + 's3', + endpoint_url=EndURl, + aws_access_key_id=AccessKey, + aws_secret_access_key=SecertKey, + verify=False + ) + + ############Creating Bucket + BucketName = randomPassword.generate_pass().lower() + + try: + client.create_bucket(Bucket=BucketName) + except BaseException as msg: + logging.CyberCPLogFileWriter.writeToFile("Creating Bucket Error: %s" % str(msg)) + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + config = { + 'BackupType': BackupType, + 'BucketName': BucketName + } + except BaseException as msg: + config = {'BackupType': BackupType} + pass + + svobj = RemoteBackupSchedule(RemoteBackupConfig=RemoteBackupConfigobj, Name=ScheduleName, + timeintervel=Backfrequency, fileretention=FileRetention, + config=json.dumps(config), + lastrun=str(time.time())) + svobj.save() + + data_ret = {'status': 1, 'error_message': 'None', } + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def AddWPsiteforRemoteBackup(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + WPid = data['WpsiteID'] + RemoteScheduleID = data['RemoteScheduleID'] + + wpsiteobj = WPSites.objects.get(pk=WPid) + WPpath = wpsiteobj.path + VHuser = wpsiteobj.owner.externalApp + PhpVersion = wpsiteobj.owner.phpSelection + php = PHPManager.getPHPString(PhpVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + ####Get DB Name + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp config get DB_NAME --skip-plugins --skip-themes --path=%s' % ( + VHuser, FinalPHPPath, WPpath) + result, stdout = ProcessUtilities.outputExecutioner(command, None, None, None, 1) + + if stdout.find('Error:') > -1: + raise BaseException(stdout) + else: + Finaldbname = stdout.rstrip("\n") + + ## Get DB obj + try: + DBobj = Databases.objects.get(dbName=Finaldbname) + except: + raise BaseException(str("DataBase Not Found")) + RemoteScheduleIDobj = RemoteBackupSchedule.objects.get(pk=RemoteScheduleID) + + svobj = RemoteBackupsites(owner=RemoteScheduleIDobj, WPsites=WPid, database=DBobj.pk) + svobj.save() + + data_ret = {'status': 1, 'error_message': 'None', } + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def UpdateRemoteschedules(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + ScheduleID = data['ScheduleID'] + Frequency = data['Frequency'] + FileRetention = data['FileRetention'] + + scheduleobj = RemoteBackupSchedule.objects.get(pk=ScheduleID) + scheduleobj.timeintervel = Frequency + scheduleobj.fileretention = FileRetention + scheduleobj.save() + + data_ret = {'status': 1, 'error_message': 'None', } + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def ScanWordpressSite(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + allweb = Websites.objects.all() + + childdomain = ChildDomains.objects.all() + + for web in allweb: + webpath = "/home/%s/public_html/" % web.domain + command = "cat %swp-config.php" % webpath + result = ProcessUtilities.outputExecutioner(command, web.externalApp) + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(result) + + if result.find('No such file or directory') == -1: + try: + WPSites.objects.get(path=webpath) + except: + wpobj = WPSites(owner=web, title=web.domain, path=webpath, FinalURL=web.domain, + AutoUpdates="Enabled", PluginUpdates="Enabled", + ThemeUpdates="Enabled", ) + wpobj.save() + + for chlid in childdomain: + childPath = chlid.path.rstrip('/') + + command = "cat %s/wp-config.php" % childPath + result = ProcessUtilities.outputExecutioner(command, chlid.master.externalApp) + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(result) + + if result.find('No such file or directory') == -1: + fChildPath = f'{childPath}/' + try: + WPSites.objects.get(path=fChildPath) + except: + + wpobj = WPSites(owner=chlid.master, title=chlid.domain, path=fChildPath, FinalURL=chlid.domain, + AutoUpdates="Enabled", PluginUpdates="Enabled", + ThemeUpdates="Enabled", ) + wpobj.save() + + data_ret = {'status': 1, 'error_message': 'None', } + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def installwpcore(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + ###fetch WP version + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core version --skip-plugins --skip-themes --path=%s 2>/dev/null' % ( + Vhuser, FinalPHPPath, path) + version = ProcessUtilities.outputExecutioner(command, None, True) + version = version.rstrip("\n") + + ###install wp core + command = f"sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp core download --force --skip-content --version={version} --path={path}" + output = ProcessUtilities.outputExecutioner(command) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', 'result': output} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def dataintegrity(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + ###fetch WP version + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core verify-checksums --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, path) + result = ProcessUtilities.outputExecutioner(command) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', 'result': result} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def UpdatePlugins(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + plugin = data['plugin'] + pluginarray = data['pluginarray'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['plugin'] = plugin + extraArgs['pluginarray'] = pluginarray + extraArgs['FinalPHPPath'] = FinalPHPPath + extraArgs['path'] = path + extraArgs['Vhuser'] = Vhuser + + background = ApplicationInstaller('UpdateWPPlugin', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def UpdateThemes(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + Theme = data['Theme'] + Themearray = data['Themearray'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['Theme'] = Theme + extraArgs['Themearray'] = Themearray + extraArgs['FinalPHPPath'] = FinalPHPPath + extraArgs['path'] = path + extraArgs['Vhuser'] = Vhuser + + background = ApplicationInstaller('UpdateWPTheme', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def DeletePlugins(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + plugin = data['plugin'] + pluginarray = data['pluginarray'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['plugin'] = plugin + extraArgs['pluginarray'] = pluginarray + extraArgs['FinalPHPPath'] = FinalPHPPath + extraArgs['path'] = path + extraArgs['Vhuser'] = Vhuser + + background = ApplicationInstaller('DeletePlugins', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def DeleteThemes(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + Theme = data['Theme'] + Themearray = data['Themearray'] + wpsite = WPSites.objects.get(pk=WPManagerID) + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['Theme'] = Theme + extraArgs['Themearray'] = Themearray + extraArgs['FinalPHPPath'] = FinalPHPPath + extraArgs['path'] = path + extraArgs['Vhuser'] = Vhuser + + background = ApplicationInstaller('DeleteThemes', extraArgs) + background.start() + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def ChangeStatus(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + plugin = data['plugin'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin status %s --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, plugin, path) + stdoutput = ProcessUtilities.outputExecutioner(command) + + if stdoutput.find('Status: Active') > -1: + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin deactivate %s --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, plugin, path) + stdoutput = ProcessUtilities.outputExecutioner(command) + time.sleep(3) + + else: + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin activate %s --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, plugin, path) + stdoutput = ProcessUtilities.outputExecutioner(command) + time.sleep(3) + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def ChangeStatusThemes(self, userID=None, data=None): + try: + # logging.CyberCPLogFileWriter.writeToFile("Error WP ChangeStatusThemes ....... %s") + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + Theme = data['theme'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['Theme'] = Theme + extraArgs['FinalPHPPath'] = FinalPHPPath + extraArgs['path'] = path + extraArgs['Vhuser'] = Vhuser + + background = ApplicationInstaller('ChangeStatusThemes', extraArgs) + background.start() + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def CreateStagingNow(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['StagingDomain'] = data['StagingDomain'] + extraArgs['StagingName'] = data['StagingName'] + extraArgs['WPid'] = data['WPid'] + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + wpsite = WPSites.objects.get(pk=data['WPid']) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + background = ApplicationInstaller('CreateStagingNow', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def UpdateWPSettings(self, userID=None, data=None): try: currentACL = ACLManager.loadedACL(userID) admin = Administrator.objects.get(pk=userID) - if ACLManager.currentContextPermission(currentACL, 'modifyWebsite') == 0: - return ACLManager.loadErrorJson('modifyWebSiteStatus', 0) + siteId = data['siteId'] + setting = data['setting'] + value = data['value'] + + wpsite = WPSites.objects.get(pk=siteId) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) != 1: + return ACLManager.loadError() + + # Get PHP version and path + Webobj = Websites.objects.get(pk=wpsite.owner_id) + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - website = Websites.objects.get(domain=data['websiteName']) - - if ACLManager.checkOwnership(website.domain, admin, currentACL) == 0: - return ACLManager.loadErrorJson() - - if website.package.packageName != data['package']: - package = Package.objects.get(packageName=data['package']) - website.package = package - - website.adminEmail = data['email'] + # Update the appropriate setting based on the setting type + if setting == 'search-indexing': + # Update search engine indexing + command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp option update blog_public {value} --skip-plugins --skip-themes --path={wpsite.path}' + elif setting == 'debugging': + # Update debugging in wp-config.php + if value: + command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_DEBUG true --raw --skip-plugins --skip-themes --path={wpsite.path}' + else: + command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_DEBUG false --raw --skip-plugins --skip-themes --path={wpsite.path}' + elif setting == 'password-protection': + vhostName = wpsite.owner.domain + vhostPassDir = f'/home/{vhostName}' + path = f'{vhostPassDir}/{siteId}' + if value: + # Enable password protection + if not os.path.exists(path): + os.makedirs(path) + htpasswd = f'{path}/.htpasswd' + htaccess = f'{wpsite.path}/.htaccess' + password = randomPassword.generate_pass(12) + + # Create .htpasswd file + command = f"htpasswd -cb {htpasswd} admin {password}" + ProcessUtilities.executioner(command) + + # Create .htaccess file + htaccess_content = f"""AuthType Basic +AuthName "Restricted Access" +AuthUserFile {htpasswd} +Require valid-user""" + with open(htaccess, 'w') as f: + f.write(htaccess_content) + + def submitWebsiteModify(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + if ACLManager.currentContextPermission(currentACL, 'modifyWebsite') == 0: + return ACLManager.loadErrorJson('modifyStatus', 0) + + admin = Administrator.objects.get(pk=userID) + if ACLManager.checkOwnership(data['websiteToBeModified'], admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('websiteDeleteStatus', 0) + + packs = ACLManager.loadPackages(userID, currentACL) + admins = ACLManager.loadAllUsers(userID) + + ## Get packs name + + json_data = "[" + checker = 0 + + for items in packs: + dic = {"pack": items} + + if checker == 0: + json_data = json_data + json.dumps(dic) + checker = 1 + else: + json_data = json_data + ',' + json.dumps(dic) + + json_data = json_data + ']' + + ### Get admin names + + admin_data = "[" + checker = 0 + + for items in admins: + dic = {"adminNames": items} + + if checker == 0: + admin_data = admin_data + json.dumps(dic) + checker = 1 + else: + admin_data = admin_data + ',' + json.dumps(dic) + + admin_data = admin_data + ']' + + websiteToBeModified = data['websiteToBeModified'] + + modifyWeb = Websites.objects.get(domain=websiteToBeModified) + + email = modifyWeb.adminEmail + currentPack = modifyWeb.package.packageName + owner = modifyWeb.admin.userName + + data_ret = {'status': 1, 'modifyStatus': 1, 'error_message': "None", "adminEmail": email, + "packages": json_data, "current_pack": currentPack, "adminNames": admin_data, + 'currentAdmin': owner} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + + except BaseException as msg: + dic = {'status': 0, 'modifyStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def fetchWebsiteDataJSON(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + if ACLManager.currentContextPermission(currentACL, 'createWebsite') == 0: + return ACLManager.loadErrorJson('createWebSiteStatus', 0) + + packs = ACLManager.loadPackages(userID, currentACL) + admins = ACLManager.loadAllUsers(userID) + + ## Get packs name + + json_data = "[" + checker = 0 + + for items in packs: + dic = {"pack": items} + + if checker == 0: + json_data = json_data + json.dumps(dic) + checker = 1 + else: + json_data = json_data + ',' + json.dumps(dic) + + json_data = json_data + ']' + + ### Get admin names + + admin_data = "[" + checker = 0 + + for items in admins: + dic = {"adminNames": items} + + if checker == 0: + admin_data = admin_data + json.dumps(dic) + checker = 1 + else: + admin_data = admin_data + ',' + json.dumps(dic) + + admin_data = admin_data + ']' + + data_ret = {'status': 1, 'error_message': "None", + "packages": json_data, "adminNames": admin_data} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + + except BaseException as msg: + dic = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def saveWebsiteChanges(self, userID=None, data=None): + try: + domain = data['domain'] + package = data['packForWeb'] + email = data['email'] + phpVersion = data['phpVersion'] + newUser = data['admin'] + + currentACL = ACLManager.loadedACL(userID) + if ACLManager.currentContextPermission(currentACL, 'modifyWebsite') == 0: + return ACLManager.loadErrorJson('saveStatus', 0) + + admin = Administrator.objects.get(pk=userID) + if ACLManager.checkOwnership(domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('websiteDeleteStatus', 0) + + newOwner = Administrator.objects.get(userName=newUser) + if ACLManager.checkUserOwnerShip(currentACL, admin, newOwner) == 1: + pass + else: + return ACLManager.loadErrorJson('websiteDeleteStatus', 0) + + confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + domain + completePathToConfigFile = confPath + "/vhost.conf" + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " changePHP --phpVersion '" + phpVersion + "' --path " + completePathToConfigFile + ProcessUtilities.popenExecutioner(execPath) + + #### + + newOwner = Administrator.objects.get(userName=newUser) + + modifyWeb = Websites.objects.get(domain=domain) + webpack = Package.objects.get(packageName=package) + + modifyWeb.package = webpack + modifyWeb.adminEmail = email + modifyWeb.phpSelection = phpVersion + modifyWeb.admin = newOwner + + modifyWeb.save() + + ## Fix https://github.com/usmannasir/cyberpanel/issues/998 + + # from plogical.IncScheduler import IncScheduler + # isPU = IncScheduler('CalculateAndUpdateDiskUsage', {}) + # isPU.start() + + command = '/usr/local/CyberCP/bin/python /usr/local/CyberCP/plogical/IncScheduler.py UpdateDiskUsageForce' + ProcessUtilities.outputExecutioner(command) + + ## + + data_ret = {'status': 1, 'saveStatus': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'saveStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def loadDomainHome(self, request=None, userID=None, data=None): + + if Websites.objects.filter(domain=self.domain).exists(): + + currentACL = ACLManager.loadedACL(userID) + website = Websites.objects.get(domain=self.domain) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + Data = {} + + marketingStatus = emACL.checkIfEMEnabled(admin.userName) + + Data['marketingStatus'] = marketingStatus + Data['ftpTotal'] = website.package.ftpAccounts + Data['ftpUsed'] = website.users_set.all().count() + + Data['databasesUsed'] = website.databases_set.all().count() + Data['databasesTotal'] = website.package.dataBases + + Data['domain'] = self.domain + + DiskUsage, DiskUsagePercentage, bwInMB, bwUsage = virtualHostUtilities.FindStats(website) + + ## bw usage calculations + + Data['bwInMBTotal'] = website.package.bandwidth + Data['bwInMB'] = bwInMB + Data['bwUsage'] = bwUsage + + if DiskUsagePercentage > 100: + DiskUsagePercentage = 100 + + Data['diskUsage'] = DiskUsagePercentage + Data['diskInMB'] = DiskUsage + Data['diskInMBTotal'] = website.package.diskSpace + + Data['phps'] = PHPManager.findPHPVersions() + + servicePath = '/home/cyberpanel/postfix' + if os.path.exists(servicePath): + Data['email'] = 1 + else: + Data['email'] = 0 + + ## Getting SSL Information + try: + import OpenSSL + from datetime import datetime + filePath = '/etc/letsencrypt/live/%s/fullchain.pem' % (self.domain) + x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, + open(filePath, 'r').read()) + expireData = x509.get_notAfter().decode('ascii') + finalDate = datetime.strptime(expireData, '%Y%m%d%H%M%SZ') + + now = datetime.now() + diff = finalDate - now + Data['viewSSL'] = 1 + Data['days'] = str(diff.days) + Data['authority'] = x509.get_issuer().get_components()[1][1].decode('utf-8') + + if Data['authority'] == 'Denial': + Data['authority'] = '%s has SELF-SIGNED SSL.' % (self.domain) + else: + Data['authority'] = '%s has SSL from %s.' % (self.domain, Data['authority']) + + except BaseException as msg: + Data['viewSSL'] = 0 + logging.CyberCPLogFileWriter.writeToFile(str(msg)) + + servicePath = '/home/cyberpanel/pureftpd' + if os.path.exists(servicePath): + Data['ftp'] = 1 + else: + Data['ftp'] = 0 + + proc = httpProc(request, 'websiteFunctions/website.html', Data) + return proc.render() + else: + proc = httpProc(request, 'websiteFunctions/website.html', + {"error": 1, "domain": "This domain does not exists."}) + return proc.render() + + def launchChild(self, request=None, userID=None, data=None): + + if ChildDomains.objects.filter(domain=self.childDomain).exists(): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + website = Websites.objects.get(domain=self.domain) + + Data = {} + + Data['ftpTotal'] = website.package.ftpAccounts + Data['ftpUsed'] = website.users_set.all().count() + + Data['databasesUsed'] = website.databases_set.all().count() + Data['databasesTotal'] = website.package.dataBases + + Data['domain'] = self.domain + Data['childDomain'] = self.childDomain + + DiskUsage, DiskUsagePercentage, bwInMB, bwUsage = virtualHostUtilities.FindStats(website) + + ## bw usage calculations + + Data['bwInMBTotal'] = website.package.bandwidth + Data['bwInMB'] = bwInMB + Data['bwUsage'] = bwUsage + + if DiskUsagePercentage > 100: + DiskUsagePercentage = 100 + + Data['diskUsage'] = DiskUsagePercentage + Data['diskInMB'] = DiskUsage + Data['diskInMBTotal'] = website.package.diskSpace + + Data['phps'] = PHPManager.findPHPVersions() + + servicePath = '/home/cyberpanel/postfix' + if os.path.exists(servicePath): + Data['email'] = 1 + else: + Data['email'] = 0 + + servicePath = '/home/cyberpanel/pureftpd' + if os.path.exists(servicePath): + Data['ftp'] = 1 + else: + Data['ftp'] = 0 + + ## Getting SSL Information + try: + import OpenSSL + from datetime import datetime + filePath = '/etc/letsencrypt/live/%s/fullchain.pem' % (self.childDomain) + x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, + open(filePath, 'r').read()) + expireData = x509.get_notAfter().decode('ascii') + finalDate = datetime.strptime(expireData, '%Y%m%d%H%M%SZ') + + now = datetime.now() + diff = finalDate - now + Data['viewSSL'] = 1 + Data['days'] = str(diff.days) + Data['authority'] = x509.get_issuer().get_components()[1][1].decode('utf-8') + + if Data['authority'] == 'Denial': + Data['authority'] = '%s has SELF-SIGNED SSL.' % (self.childDomain) + else: + Data['authority'] = '%s has SSL from %s.' % (self.childDomain, Data['authority']) + + except BaseException as msg: + Data['viewSSL'] = 0 + logging.CyberCPLogFileWriter.writeToFile(str(msg)) + + proc = httpProc(request, 'websiteFunctions/launchChild.html', Data) + return proc.render() + else: + proc = httpProc(request, 'websiteFunctions/launchChild.html', + {"error": 1, "domain": "This child domain does not exists"}) + return proc.render() + + def getDataFromLogFile(self, userID=None, data=None): + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + logType = data['logType'] + self.domain = data['virtualHost'] + page = data['page'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('logstatus', 0) + + if logType == 1: + fileName = "/home/" + self.domain + "/logs/" + self.domain + ".access_log" + else: + fileName = "/home/" + self.domain + "/logs/" + self.domain + ".error_log" + + command = 'ls -la %s' % fileName + result = ProcessUtilities.outputExecutioner(command) + + if result.find('->') > -1: + final_json = json.dumps( + {'status': 0, 'logstatus': 0, + 'error_message': "Symlink attack."}) + return HttpResponse(final_json) + + ## get Logs + website = Websites.objects.get(domain=self.domain) + + output = virtualHostUtilities.getAccessLogs(fileName, page, website.externalApp) + + if output.find("1,None") > -1: + final_json = json.dumps( + {'status': 0, 'logstatus': 0, + 'error_message': "Not able to fetch logs, see CyberPanel main log file, Error: %s" % (output)}) + return HttpResponse(final_json) + + ## get log ends here. + + data = output.split("\n") + + json_data = "[" + checker = 0 + + for items in reversed(data): + if len(items) > 10: + logData = items.split(" ") + domain = logData[5].strip('"') + ipAddress = logData[0].strip('"') + time = (logData[3]).strip("[").strip("]") + resource = logData[6].strip('"') + size = logData[9].replace('"', '') + + dic = {'domain': domain, + 'ipAddress': ipAddress, + 'time': time, + 'resource': resource, + 'size': size, + } + + if checker == 0: + json_data = json_data + json.dumps(dic) + checker = 1 + else: + json_data = json_data + ',' + json.dumps(dic) + + json_data = json_data + ']' + final_json = json.dumps({'status': 1, 'logstatus': 1, 'error_message': "None", "data": json_data}) + return HttpResponse(final_json) + + def fetchErrorLogs(self, userID=None, data=None): + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['virtualHost'] + page = data['page'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('logstatus', 0) + + fileName = "/home/" + self.domain + "/logs/" + self.domain + ".error_log" + + command = 'ls -la %s' % fileName + result = ProcessUtilities.outputExecutioner(command) + + if result.find('->') > -1: + final_json = json.dumps( + {'status': 0, 'logstatus': 0, + 'error_message': "Symlink attack."}) + return HttpResponse(final_json) + + ## get Logs + website = Websites.objects.get(domain=self.domain) + + output = virtualHostUtilities.getErrorLogs(fileName, page, website.externalApp) + + if output.find("1,None") > -1: + final_json = json.dumps( + {'status': 0, 'logstatus': 0, 'error_message': "Not able to fetch logs, see CyberPanel main log file!"}) + return HttpResponse(final_json) + + ## get log ends here. + + final_json = json.dumps({'status': 1, 'logstatus': 1, 'error_message': "None", "data": output}) + return HttpResponse(final_json) + + def getDataFromConfigFile(self, userID=None, data=None): + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + self.domain = data['virtualHost'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('configstatus', 0) + + command = 'cat %s' % ('/usr/local/lsws/conf/dvhost_redis.conf') + + if ProcessUtilities.outputExecutioner(command).find('127.0.0.1') == -1: + filePath = installUtilities.Server_root_path + "/conf/vhosts/" + self.domain + "/vhost.conf" + + command = 'cat ' + filePath + configData = ProcessUtilities.outputExecutioner(command, 'lsadm') + + if len(configData) == 0: + status = {'status': 0, "configstatus": 0, "error_message": "Configuration file is currently empty!"} + + final_json = json.dumps(status) + return HttpResponse(final_json) + + else: + command = 'redis-cli get "vhost:%s"' % (self.domain) + configData = ProcessUtilities.outputExecutioner(command) + configData = '#### This configuration is fetched from redis as Redis-Mass Hosting is being used.\n%s' % ( + configData) + + status = {'status': 1, "configstatus": 1, "configData": configData} + final_json = json.dumps(status) + return HttpResponse(final_json) + + def saveConfigsToFile(self, userID=None, data=None): + + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] != 1: + return ACLManager.loadErrorJson('configstatus', 0) + + configData = data['configData'] + self.domain = data['virtualHost'] + + if len(configData) == 0: + status = {"configstatus": 0, 'error_message': 'Error: you are trying to save empty vhost file, your website will stop working.'} + + final_json = json.dumps(status) + return HttpResponse(final_json) + + + command = 'cat %s' % ('/usr/local/lsws/conf/dvhost_redis.conf') + + if ProcessUtilities.outputExecutioner(command).find('127.0.0.1') == -1: + + mailUtilities.checkHome() + + tempPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + + vhost = open(tempPath, "w") + + vhost.write(configData) + + vhost.close() + + ## writing data temporary to file + + filePath = installUtilities.Server_root_path + "/conf/vhosts/" + self.domain + "/vhost.conf" + + ## save configuration data + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " saveVHostConfigs --path " + filePath + " --tempPath " + tempPath + + output = ProcessUtilities.outputExecutioner(execPath) + + if output.find("1,None") > -1: + status = {"configstatus": 1} + + final_json = json.dumps(status) + return HttpResponse(final_json) + else: + data_ret = {'configstatus': 0, 'error_message': output} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + ## save configuration data ends + else: + command = "redis-cli set vhost:%s '%s'" % (self.domain, configData.replace( + '#### This configuration is fetched from redis as Redis-Mass Hosting is being used.\n', '')) + ProcessUtilities.executioner(command) + + status = {"configstatus": 1} + + final_json = json.dumps(status) + return HttpResponse(final_json) + + def getRewriteRules(self, userID=None, data=None): + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + self.domain = data['virtualHost'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('rewriteStatus', 0) + + try: + childDom = ChildDomains.objects.get(domain=self.domain) + filePath = childDom.path + '/.htaccess' + externalApp = childDom.master.externalApp + except: + website = Websites.objects.get(domain=self.domain) + externalApp = website.externalApp + filePath = "/home/" + self.domain + "/public_html/.htaccess" + + try: + command = 'cat %s' % (filePath) + rewriteRules = ProcessUtilities.outputExecutioner(command, externalApp) + + if len(rewriteRules) == 0: + status = {"rewriteStatus": 1, "error_message": "Rules file is currently empty"} + final_json = json.dumps(status) + return HttpResponse(final_json) + + status = {"rewriteStatus": 1, "rewriteRules": rewriteRules} + + final_json = json.dumps(status) + return HttpResponse(final_json) + + except BaseException as msg: + status = {"rewriteStatus": 1, "error_message": str(msg), "rewriteRules": ""} + final_json = json.dumps(status) + return HttpResponse(final_json) + + def saveRewriteRules(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + self.domain = data['virtualHost'] + rewriteRules = data['rewriteRules'].encode('utf-8') + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('rewriteStatus', 0) + + ## writing data temporary to file + + mailUtilities.checkHome() + tempPath = "/tmp/" + str(randint(1000, 9999)) + vhost = open(tempPath, "wb") + vhost.write(rewriteRules) + vhost.close() + + ## writing data temporary to file + + try: + childDomain = ChildDomains.objects.get(domain=self.domain) + filePath = childDomain.path + '/.htaccess' + externalApp = childDomain.master.externalApp + except: + filePath = "/home/" + self.domain + "/public_html/.htaccess" + website = Websites.objects.get(domain=self.domain) + externalApp = website.externalApp + + ## save configuration data + + command = 'cp %s %s' % (tempPath, filePath) + ProcessUtilities.executioner(command, externalApp) + + command = 'rm -f %s' % (tempPath) + ProcessUtilities.executioner(command, 'cyberpanel') + + installUtilities.reStartLiteSpeedSocket() + status = {"rewriteStatus": 1, 'error_message': 'None'} + final_json = json.dumps(status) + return HttpResponse(final_json) + except BaseException as msg: + status = {"rewriteStatus": 0, 'error_message': str(msg)} + final_json = json.dumps(status) + return HttpResponse(final_json) + + def saveSSL(self, userID=None, data=None): + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + self.domain = data['virtualHost'] + key = data['key'] + cert = data['cert'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('sslStatus', 0) + + mailUtilities.checkHome() + + ## writing data temporary to file + + tempKeyPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + vhost = open(tempKeyPath, "w") + vhost.write(key) + vhost.close() + + tempCertPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + vhost = open(tempCertPath, "w") + vhost.write(cert) + vhost.close() + + ## writing data temporary to file + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " saveSSL --virtualHostName " + self.domain + " --tempKeyPath " + tempKeyPath + " --tempCertPath " + tempCertPath + output = ProcessUtilities.outputExecutioner(execPath) + + if output.find("1,None") > -1: + data_ret = {'sslStatus': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + logging.CyberCPLogFileWriter.writeToFile( + output) + data_ret = {'sslStatus': 0, 'error_message': output} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def changePHP(self, userID=None, data=None): + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + self.domain = data['childDomain'] + phpVersion = data['phpSelection'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('changePHP', 0) + + confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + self.domain + completePathToConfigFile = confPath + "/vhost.conf" + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " changePHP --phpVersion '" + phpVersion + "' --path " + completePathToConfigFile + ProcessUtilities.popenExecutioner(execPath) + + try: + website = Websites.objects.get(domain=self.domain) website.phpSelection = data['phpSelection'] website.save() - return HttpResponse(json.dumps({ - 'status': 1, - 'error_message': "None" - })) - - except BaseException as msg: - return HttpResponse(json.dumps({ - 'status': 0, - 'error_message': str(msg) - })) + ### check if there are any alias domains under the main website and then change php for them too + + for alias in website.childdomains_set.filter(alais=1): + + try: + + confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + alias.domain + completePathToConfigFile = confPath + "/vhost.conf" + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " changePHP --phpVersion '" + phpVersion + "' --path " + completePathToConfigFile + ProcessUtilities.popenExecutioner(execPath) + except BaseException as msg: + logging.CyberCPLogFileWriter.writeToFile(f'Error changing PHP for alias: {str(msg)}') + + + except: + website = ChildDomains.objects.get(domain=self.domain) + website.phpSelection = data['phpSelection'] + website.save() + + data_ret = {'status': 1, 'changePHP': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) def getWebsiteCron(self, userID=None, data=None): try: From 2a7b39c264709030950aeea53360100e8983f83a Mon Sep 17 00:00:00 2001 From: usmannasir Date: Fri, 4 Apr 2025 14:39:38 +0500 Subject: [PATCH 002/273] fix idendation issue --- .../websiteFunctions/websiteFunctions.js | 165 +- .../websiteFunctions/listWebsites.html | 39 +- websiteFunctions/website.py | 2811 +---------------- 3 files changed, 140 insertions(+), 2875 deletions(-) diff --git a/websiteFunctions/static/websiteFunctions/websiteFunctions.js b/websiteFunctions/static/websiteFunctions/websiteFunctions.js index 778da2a9f..2476a370b 100755 --- a/websiteFunctions/static/websiteFunctions/websiteFunctions.js +++ b/websiteFunctions/static/websiteFunctions/websiteFunctions.js @@ -2692,11 +2692,10 @@ app.controller('listWebsites', function ($scope, $http, $window) { $scope.selectedWebsite = $scope.WebSitesList[index]; console.log('Selected website:', $scope.selectedWebsite); - // Always fetch fresh data - var url = '/websites/FetchWPdata'; + // Call the new GetWPSitesByDomain endpoint + var url = '/websites/GetWPSitesByDomain'; var data = { - domain: $scope.selectedWebsite.domain, - websiteName: $scope.selectedWebsite.domain + domain: $scope.selectedWebsite.domain }; $http({ @@ -2708,48 +2707,48 @@ app.controller('listWebsites', function ($scope, $http, $window) { 'X-CSRFToken': getCookie('csrftoken') } }).then(function(response) { - console.log('WP Details Response:', response); - - // Check if response is HTML (login page) - if (typeof response.data === 'string' && response.data.includes('')) { - console.log('Received HTML response, redirecting to login'); - window.location.href = '/login'; - return; - } + console.log('WP Sites Response:', response); if (response.data && response.data.status === 1) { try { - // If single site, wrap in array - var sites = Array.isArray(response.data.data) ? response.data.data : [response.data.data]; + // Display the data in an alert + var wpSites = response.data.data; + var alertMessage = 'WordPress Sites for ' + $scope.selectedWebsite.domain + ':\n\n'; - $scope.selectedWebsite.wp_sites = sites.map(function(site) { - return { - id: site.id || $scope.selectedWebsite.domain, - title: site.title || site.domain || $scope.selectedWebsite.domain, - url: site.url || 'http://' + $scope.selectedWebsite.domain, - version: site.version || 'Unknown', - phpVersion: site.php_version || 'Unknown', - theme: site.theme || 'Unknown', - activePlugins: site.active_plugins || 0, - searchIndex: site.search_index === 'enabled', - debugging: site.debugging === 'enabled', - passwordProtection: site.password_protection === 'enabled', - maintenanceMode: site.maintenance_mode === 'enabled' - }; + wpSites.forEach(function(site, index) { + alertMessage += 'Site ' + (index + 1) + ':\n'; + alertMessage += 'Title: ' + site.title + '\n'; + alertMessage += 'URL: ' + site.url + '\n'; + alertMessage += 'Version: ' + site.version + '\n'; + alertMessage += 'PHP Version: ' + site.phpVersion + '\n'; + alertMessage += 'Active Plugins: ' + site.activePlugins + '\n'; + alertMessage += 'Theme: ' + site.theme + '\n'; + alertMessage += 'Debugging: ' + (site.debugging ? 'Enabled' : 'Disabled') + '\n'; + alertMessage += 'Search Index: ' + (site.searchIndex ? 'Enabled' : 'Disabled') + '\n'; + alertMessage += 'Maintenance Mode: ' + (site.maintenanceMode ? 'Enabled' : 'Disabled') + '\n'; + alertMessage += 'Password Protection: ' + (site.passwordProtection ? 'Enabled' : 'Disabled') + '\n\n'; }); + + alert(alertMessage); + + // Update the UI with the data + $scope.selectedWebsite.wp_sites = wpSites; $scope.selectedWebsite.showWPSites = true; } catch (e) { console.error('Error processing WordPress data:', e); + alert('Error processing WordPress data: ' + e.message); $scope.selectedWebsite.showWPSites = false; $scope.selectedWebsite.wp_sites = []; } } else { console.error('Error fetching WordPress sites:', response.data.error_message); + alert('Error fetching WordPress sites: ' + response.data.error_message); $scope.selectedWebsite.showWPSites = false; $scope.selectedWebsite.wp_sites = []; } }, function(error) { console.error('Error fetching WordPress sites:', error); + alert('Error fetching WordPress sites: ' + error.message); $scope.selectedWebsite.showWPSites = false; $scope.selectedWebsite.wp_sites = []; }); @@ -8247,11 +8246,10 @@ app.controller('listWebsites', function ($scope, $http, $window) { $scope.selectedWebsite = $scope.WebSitesList[index]; console.log('Selected website:', $scope.selectedWebsite); - // Always fetch fresh data - var url = '/websites/FetchWPdata'; + // Call the new GetWPSitesByDomain endpoint + var url = '/websites/GetWPSitesByDomain'; var data = { - domain: $scope.selectedWebsite.domain, - websiteName: $scope.selectedWebsite.domain + domain: $scope.selectedWebsite.domain }; $http({ @@ -8263,48 +8261,48 @@ app.controller('listWebsites', function ($scope, $http, $window) { 'X-CSRFToken': getCookie('csrftoken') } }).then(function(response) { - console.log('WP Details Response:', response); - - // Check if response is HTML (login page) - if (typeof response.data === 'string' && response.data.includes('')) { - console.log('Received HTML response, redirecting to login'); - window.location.href = '/login'; - return; - } + console.log('WP Sites Response:', response); if (response.data && response.data.status === 1) { try { - // If single site, wrap in array - var sites = Array.isArray(response.data.data) ? response.data.data : [response.data.data]; + // Display the data in an alert + var wpSites = response.data.data; + var alertMessage = 'WordPress Sites for ' + $scope.selectedWebsite.domain + ':\n\n'; - $scope.selectedWebsite.wp_sites = sites.map(function(site) { - return { - id: site.id || $scope.selectedWebsite.domain, - title: site.title || site.domain || $scope.selectedWebsite.domain, - url: site.url || 'http://' + $scope.selectedWebsite.domain, - version: site.version || 'Unknown', - phpVersion: site.php_version || 'Unknown', - theme: site.theme || 'Unknown', - activePlugins: site.active_plugins || 0, - searchIndex: site.search_index === 'enabled', - debugging: site.debugging === 'enabled', - passwordProtection: site.password_protection === 'enabled', - maintenanceMode: site.maintenance_mode === 'enabled' - }; + wpSites.forEach(function(site, index) { + alertMessage += 'Site ' + (index + 1) + ':\n'; + alertMessage += 'Title: ' + site.title + '\n'; + alertMessage += 'URL: ' + site.url + '\n'; + alertMessage += 'Version: ' + site.version + '\n'; + alertMessage += 'PHP Version: ' + site.phpVersion + '\n'; + alertMessage += 'Active Plugins: ' + site.activePlugins + '\n'; + alertMessage += 'Theme: ' + site.theme + '\n'; + alertMessage += 'Debugging: ' + (site.debugging ? 'Enabled' : 'Disabled') + '\n'; + alertMessage += 'Search Index: ' + (site.searchIndex ? 'Enabled' : 'Disabled') + '\n'; + alertMessage += 'Maintenance Mode: ' + (site.maintenanceMode ? 'Enabled' : 'Disabled') + '\n'; + alertMessage += 'Password Protection: ' + (site.passwordProtection ? 'Enabled' : 'Disabled') + '\n\n'; }); + + alert(alertMessage); + + // Update the UI with the data + $scope.selectedWebsite.wp_sites = wpSites; $scope.selectedWebsite.showWPSites = true; } catch (e) { console.error('Error processing WordPress data:', e); + alert('Error processing WordPress data: ' + e.message); $scope.selectedWebsite.showWPSites = false; $scope.selectedWebsite.wp_sites = []; } } else { console.error('Error fetching WordPress sites:', response.data.error_message); + alert('Error fetching WordPress sites: ' + response.data.error_message); $scope.selectedWebsite.showWPSites = false; $scope.selectedWebsite.wp_sites = []; } }, function(error) { console.error('Error fetching WordPress sites:', error); + alert('Error fetching WordPress sites: ' + error.message); $scope.selectedWebsite.showWPSites = false; $scope.selectedWebsite.wp_sites = []; }); @@ -12184,11 +12182,10 @@ app.controller('manageAliasController', function ($scope, $http, $timeout, $wind $scope.selectedWebsite = $scope.WebSitesList[index]; console.log('Selected website:', $scope.selectedWebsite); - // Always fetch fresh data - var url = '/websites/FetchWPdata'; + // Call the new GetWPSitesByDomain endpoint + var url = '/websites/GetWPSitesByDomain'; var data = { - domain: $scope.selectedWebsite.domain, - websiteName: $scope.selectedWebsite.domain + domain: $scope.selectedWebsite.domain }; $http({ @@ -12200,48 +12197,48 @@ app.controller('manageAliasController', function ($scope, $http, $timeout, $wind 'X-CSRFToken': getCookie('csrftoken') } }).then(function(response) { - console.log('WP Details Response:', response); - - // Check if response is HTML (login page) - if (typeof response.data === 'string' && response.data.includes('')) { - console.log('Received HTML response, redirecting to login'); - window.location.href = '/login'; - return; - } + console.log('WP Sites Response:', response); if (response.data && response.data.status === 1) { try { - // If single site, wrap in array - var sites = Array.isArray(response.data.data) ? response.data.data : [response.data.data]; + // Display the data in an alert + var wpSites = response.data.data; + var alertMessage = 'WordPress Sites for ' + $scope.selectedWebsite.domain + ':\n\n'; - $scope.selectedWebsite.wp_sites = sites.map(function(site) { - return { - id: site.id || $scope.selectedWebsite.domain, - title: site.title || site.domain || $scope.selectedWebsite.domain, - url: site.url || 'http://' + $scope.selectedWebsite.domain, - version: site.version || 'Unknown', - phpVersion: site.php_version || 'Unknown', - theme: site.theme || 'Unknown', - activePlugins: site.active_plugins || 0, - searchIndex: site.search_index === 'enabled', - debugging: site.debugging === 'enabled', - passwordProtection: site.password_protection === 'enabled', - maintenanceMode: site.maintenance_mode === 'enabled' - }; + wpSites.forEach(function(site, index) { + alertMessage += 'Site ' + (index + 1) + ':\n'; + alertMessage += 'Title: ' + site.title + '\n'; + alertMessage += 'URL: ' + site.url + '\n'; + alertMessage += 'Version: ' + site.version + '\n'; + alertMessage += 'PHP Version: ' + site.phpVersion + '\n'; + alertMessage += 'Active Plugins: ' + site.activePlugins + '\n'; + alertMessage += 'Theme: ' + site.theme + '\n'; + alertMessage += 'Debugging: ' + (site.debugging ? 'Enabled' : 'Disabled') + '\n'; + alertMessage += 'Search Index: ' + (site.searchIndex ? 'Enabled' : 'Disabled') + '\n'; + alertMessage += 'Maintenance Mode: ' + (site.maintenanceMode ? 'Enabled' : 'Disabled') + '\n'; + alertMessage += 'Password Protection: ' + (site.passwordProtection ? 'Enabled' : 'Disabled') + '\n\n'; }); + + alert(alertMessage); + + // Update the UI with the data + $scope.selectedWebsite.wp_sites = wpSites; $scope.selectedWebsite.showWPSites = true; } catch (e) { console.error('Error processing WordPress data:', e); + alert('Error processing WordPress data: ' + e.message); $scope.selectedWebsite.showWPSites = false; $scope.selectedWebsite.wp_sites = []; } } else { console.error('Error fetching WordPress sites:', response.data.error_message); + alert('Error fetching WordPress sites: ' + response.data.error_message); $scope.selectedWebsite.showWPSites = false; $scope.selectedWebsite.wp_sites = []; } }, function(error) { console.error('Error fetching WordPress sites:', error); + alert('Error fetching WordPress sites: ' + error.message); $scope.selectedWebsite.showWPSites = false; $scope.selectedWebsite.wp_sites = []; }); diff --git a/websiteFunctions/templates/websiteFunctions/listWebsites.html b/websiteFunctions/templates/websiteFunctions/listWebsites.html index a0a4481cf..4d85fdbae 100755 --- a/websiteFunctions/templates/websiteFunctions/listWebsites.html +++ b/websiteFunctions/templates/websiteFunctions/listWebsites.html @@ -111,44 +111,41 @@
-
+
-

+
- - + + +
-
+
-
+
WordPress
-
+
-
+
PHP Version
-
PHP {$ wp.phpVersion $}
+
-
+
Theme
-
+
-
+
Plugins
-
{$ wp.activePlugins $} active
+
{$ wp.activePlugins || '0' $} active
@@ -156,21 +153,21 @@
- + Search engine indexing
- + Debugging
- + Password protection
- + Maintenance mode
diff --git a/websiteFunctions/website.py b/websiteFunctions/website.py index 132f4db93..e12624ed1 100755 --- a/websiteFunctions/website.py +++ b/websiteFunctions/website.py @@ -1235,25 +1235,7 @@ class WebsiteManager: admin = Administrator.objects.get(pk=userID) backupid = data['backupid'] - DesSiteID = data['DesSite'] - - # try: - # - # bwp = WPSites.objects.get(pk=int(backupid)) - # - # if ACLManager.checkOwnership(bwp.owner.domain, admin, currentACL) == 1: - # pass - # else: - # return ACLManager.loadError() - # - # except: - # pass - # - # dwp = WPSites.objects.get(pk=int(DesSiteID)) - # if ACLManager.checkOwnership(dwp.owner.domain, admin, currentACL) == 1: - # pass - # else: - # return ACLManager.loadError() + DesSiteID = data['DesSiteID'] Domain = data['Domain'] @@ -1949,2026 +1931,7 @@ class WebsiteManager: if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) != 1: return ACLManager.loadError() - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['siteId'] = siteId - extraArgs['setting'] = setting - extraArgs['value'] = value - background = ApplicationInstaller('UpdateWPSettings', extraArgs) - background.start() - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def GetWPSitesByDomain(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - domain = data['domain'] - - # Get the website object for the domain - website = Websites.objects.get(domain=domain) - - if ACLManager.checkOwnership(domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - # Get all WP sites for this website - wp_sites = WPSites.objects.filter(owner=website) - - sites_data = [] - - for wp in wp_sites: - # Get PHP version - php = ACLManager.getPHPString(website.phpSelection) - FinalPHPPath = f'/usr/local/lsws/lsphp{php}/bin/php' - - # Get WP version - command = f'sudo -u {website.externalApp} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp core version --skip-plugins --skip-themes --path={wp.path} 2>/dev/null' - version = ProcessUtilities.outputExecutioner(command, None, True) - version = version.rstrip("\n") if version else 'Unknown' - - # Get active plugins count - command = f'sudo -u {website.externalApp} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp plugin list --skip-plugins --skip-themes --format=json --path={wp.path}' - plugins_output = ProcessUtilities.outputExecutioner(command) - try: - plugins = json.loads(plugins_output.splitlines()[-1]) - active_plugins = len([p for p in plugins if p['status'] == 'active']) - except: - active_plugins = 0 - - # Get active theme - command = f'sudo -u {website.externalApp} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp theme list --skip-plugins --skip-themes --format=json --path={wp.path}' - themes_output = ProcessUtilities.outputExecutioner(command) - try: - themes = json.loads(themes_output.splitlines()[-1]) - active_theme = next((t['name'] for t in themes if t['status'] == 'active'), 'Unknown') - except: - active_theme = 'Unknown' - - # Get other WP settings - command = f'sudo -u {website.externalApp} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp config list --skip-plugins --skip-themes --path={wp.path}' - config_output = ProcessUtilities.outputExecutioner(command) - debugging = 1 if 'WP_DEBUG\ttrue\tconstant' in config_output else 0 - - command = f'sudo -u {website.externalApp} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp option get blog_public --skip-plugins --skip-themes --path={wp.path}' - search_index = int(ProcessUtilities.outputExecutioner(command).splitlines()[-1]) - - command = f'sudo -u {website.externalApp} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp maintenance-mode status --skip-plugins --skip-themes --path={wp.path}' - maintenance_output = ProcessUtilities.outputExecutioner(command) - maintenance_mode = 0 if 'not active' in maintenance_output.splitlines()[-1] else 1 - - # Check password protection - vhost_pass_dir = f'/home/{domain}' - path = f'{vhost_pass_dir}/{wp.id}' - password_protection = 1 if os.path.exists(path) else 0 - - sites_data.append({ - 'id': wp.id, - 'title': wp.title, - 'url': wp.FinalURL, - 'version': version, - 'phpVersion': website.phpSelection, - 'theme': active_theme, - 'activePlugins': active_plugins, - 'debugging': debugging, - 'searchIndex': search_index, - 'maintenanceMode': maintenance_mode, - 'passwordProtection': password_protection - }) - - return HttpResponse(json.dumps({ - 'status': 1, - 'error_message': None, - 'data': sites_data - })) - - except Websites.DoesNotExist: - return HttpResponse(json.dumps({ - 'status': 0, - 'error_message': f'Website with domain {domain} does not exist' - })) - except Exception as e: - return HttpResponse(json.dumps({ - 'status': 0, - 'error_message': str(e) - })) - - -class WebsiteManager: - apache = 1 - ols = 2 - lsws = 3 - - def __init__(self, domain=None, childDomain=None): - self.domain = domain - self.childDomain = childDomain - - def createWebsite(self, request=None, userID=None, data=None): - - url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" - data = { - "name": "all", - "IP": ACLManager.GetServerIP() - } - - import requests - response = requests.post(url, data=json.dumps(data)) - Status = response.json()['status'] - - test_domain_status = 0 - - if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: - test_domain_status = 1 - - currentACL = ACLManager.loadedACL(userID) - adminNames = ACLManager.loadAllUsers(userID) - packagesName = ACLManager.loadPackages(userID, currentACL) - phps = PHPManager.findPHPVersions() - - rnpss = randomPassword.generate_pass(10) - - Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps, 'Randam_String': rnpss.lower(), - 'test_domain_data': test_domain_status} - proc = httpProc(request, 'websiteFunctions/createWebsite.html', - Data, 'createWebsite') - return proc.render() - - def WPCreate(self, request=None, userID=None, data=None): - url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" - data = { - "name": "wp-manager", - "IP": ACLManager.GetServerIP() - } - - import requests - response = requests.post(url, data=json.dumps(data)) - Status = response.json()['status'] - - - if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: - currentACL = ACLManager.loadedACL(userID) - adminNames = ACLManager.loadAllUsers(userID) - packagesName = ACLManager.loadPackages(userID, currentACL) - - if len(packagesName) == 0: - packagesName = ['Default'] - - FinalVersions = [] - userobj = Administrator.objects.get(pk=userID) - counter = 0 - try: - import requests - WPVersions = json.loads(requests.get('https://api.wordpress.org/core/version-check/1.7/').text)[ - 'offers'] - - for versions in WPVersions: - if counter == 7: - break - if versions['current'] not in FinalVersions: - FinalVersions.append(versions['current']) - counter = counter + 1 - except: - FinalVersions = ['5.6', '5.5.3', '5.5.2'] - - Plugins = wpplugins.objects.filter(owner=userobj) - rnpss = randomPassword.generate_pass(10) - - ## - - test_domain_status = 1 - - Data = {'packageList': packagesName, "owernList": adminNames, 'WPVersions': FinalVersions, - 'Plugins': Plugins, 'Randam_String': rnpss.lower(), 'test_domain_data': test_domain_status} - proc = httpProc(request, 'websiteFunctions/WPCreate.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def ListWPSites(self, request=None, userID=None, DeleteID=None): - import json - currentACL = ACLManager.loadedACL(userID) - - admin = Administrator.objects.get(pk=userID) - data = {} - wp_sites = ACLManager.GetALLWPObjects(currentACL, userID) - data['wp'] = wp_sites - - try: - if DeleteID != None: - WPDelete = WPSites.objects.get(pk=DeleteID) - - if ACLManager.checkOwnership(WPDelete.owner.domain, admin, currentACL) == 1: - WPDelete.delete() - except BaseException as msg: - pass - - sites = [] - for site in data['wp']: - sites.append({ - 'id': site.id, - 'title': site.title, - 'url': site.FinalURL, - 'production_status': True - }) - - context = { - "wpsite": json.dumps(sites), - "status": 1, - "total_sites": len(sites), - "debug_info": json.dumps({ - "user_id": userID, - "is_admin": bool(currentACL.get('admin', 0)), - "wp_sites_count": wp_sites.count() - }) - } - - proc = httpProc(request, 'websiteFunctions/WPsitesList.html', context) - return proc.render() - - def WPHome(self, request=None, userID=None, WPid=None, DeleteID=None): - Data = {} - currentACL = ACLManager.loadedACL(userID) - WPobj = WPSites.objects.get(pk=WPid) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(WPobj.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - try: - - url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" - data = { - "name": "wp-manager", - "IP": ACLManager.GetServerIP() - } - - import requests - response = requests.post(url, data=json.dumps(data)) - Status = response.json()['status'] - - rnpss = randomPassword.generate_pass(10) - - Data['Randam_String'] = rnpss.lower() - - if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: - Data['wpsite'] = WPobj - Data['test_domain_data'] = 1 - - try: - DeleteID = request.GET.get('DeleteID', None) - - if DeleteID != None: - wstagingDelete = WPStaging.objects.get(pk=DeleteID, owner=WPobj) - wstagingDelete.delete() - - except BaseException as msg: - da = str(msg) - - proc = httpProc(request, 'websiteFunctions/WPsiteHome.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - except: - proc = httpProc(request, 'websiteFunctions/WPsiteHome.html', - Data, 'createDatabase') - return proc.render() - - def RestoreHome(self, request=None, userID=None, BackupID=None): - Data = {} - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.CheckForPremFeature('wp-manager'): - - Data['backupobj'] = WPSitesBackup.objects.get(pk=BackupID) - - if ACLManager.CheckIPBackupObjectOwner(currentACL, Data['backupobj'], admin) == 1: - pass - else: - return ACLManager.loadError() - - config = json.loads(Data['backupobj'].config) - Data['FileName'] = config['name'] - try: - Data['Backuptype'] = config['Backuptype'] - - if Data['Backuptype'] == 'DataBase Backup' or Data['Backuptype'] == 'Website Backup': - Data['WPsites'] = [WPSites.objects.get(pk=Data['backupobj'].WPSiteID)] - else: - Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) - - except: - Data['Backuptype'] = None - Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) - - proc = httpProc(request, 'websiteFunctions/WPRestoreHome.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def RemoteBackupConfig(self, request=None, userID=None, DeleteID=None): - Data = {} - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - try: - if DeleteID != None: - BackupconfigDelete = RemoteBackupConfig.objects.get(pk=DeleteID) - BackupconfigDelete.delete() - except: - pass - - if ACLManager.CheckForPremFeature('wp-manager'): - - Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) - allcon = RemoteBackupConfig.objects.all() - Data['backupconfigs'] = [] - for i in allcon: - configr = json.loads(i.config) - if i.configtype == "SFTP": - Data['backupconfigs'].append({ - 'id': i.pk, - 'Type': i.configtype, - 'HostName': configr['Hostname'], - 'Path': configr['Path'] - }) - elif i.configtype == "S3": - Provider = configr['Provider'] - if Provider == "Backblaze": - Data['backupconfigs'].append({ - 'id': i.pk, - 'Type': i.configtype, - 'HostName': Provider, - 'Path': configr['S3keyname'] - }) - else: - Data['backupconfigs'].append({ - 'id': i.pk, - 'Type': i.configtype, - 'HostName': Provider, - 'Path': configr['S3keyname'] - }) - - proc = httpProc(request, 'websiteFunctions/RemoteBackupConfig.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def BackupfileConfig(self, request=None, userID=None, RemoteConfigID=None, DeleteID=None): - Data = {} - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - Data['RemoteConfigID'] = RemoteConfigID - RemoteConfigobj = RemoteBackupConfig.objects.get(pk=RemoteConfigID) - try: - if DeleteID != None: - RemoteBackupConfigDelete = RemoteBackupSchedule.objects.get(pk=DeleteID) - RemoteBackupConfigDelete.delete() - except: - pass - - if ACLManager.CheckForPremFeature('wp-manager'): - Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) - allsechedule = RemoteBackupSchedule.objects.filter(RemoteBackupConfig=RemoteConfigobj) - Data['Backupschedule'] = [] - for i in allsechedule: - lastrun = i.lastrun - LastRun = time.strftime('%Y-%m-%d', time.localtime(float(lastrun))) - Data['Backupschedule'].append({ - 'id': i.pk, - 'Name': i.Name, - 'RemoteConfiguration': i.RemoteBackupConfig.configtype, - 'Retention': i.fileretention, - 'Frequency': i.timeintervel, - 'LastRun': LastRun - }) - proc = httpProc(request, 'websiteFunctions/BackupfileConfig.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def AddRemoteBackupsite(self, request=None, userID=None, RemoteScheduleID=None, DeleteSiteID=None): - Data = {} - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - Data['RemoteScheduleID'] = RemoteScheduleID - RemoteBackupScheduleobj = RemoteBackupSchedule.objects.get(pk=RemoteScheduleID) - - try: - if DeleteSiteID != None: - RemoteBackupsitesDelete = RemoteBackupsites.objects.get(pk=DeleteSiteID) - RemoteBackupsitesDelete.delete() - except: - pass - - if ACLManager.CheckForPremFeature('wp-manager'): - Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) - allRemoteBackupsites = RemoteBackupsites.objects.filter(owner=RemoteBackupScheduleobj) - Data['RemoteBackupsites'] = [] - for i in allRemoteBackupsites: - try: - wpsite = WPSites.objects.get(pk=i.WPsites) - Data['RemoteBackupsites'].append({ - 'id': i.pk, - 'Title': wpsite.title, - }) - except: - pass - proc = httpProc(request, 'websiteFunctions/AddRemoteBackupSite.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def WordpressPricing(self, request=None, userID=None, ): - Data = {} - proc = httpProc(request, 'websiteFunctions/CyberpanelPricing.html', Data, 'createWebsite') - return proc.render() - - def RestoreBackups(self, request=None, userID=None, DeleteID=None): - Data = {} - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" - data = { - "name": "wp-manager", - "IP": ACLManager.GetServerIP() - } - - import requests - response = requests.post(url, data=json.dumps(data)) - Status = response.json()['status'] - - if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: - - backobj = WPSitesBackup.objects.filter(owner=admin).order_by('-id') - - # if ACLManager.CheckIPBackupObjectOwner(currentACL, backobj, admin) == 1: - # pass - # else: - # return ACLManager.loadError() - - try: - if DeleteID != None: - DeleteIDobj = WPSitesBackup.objects.get(pk=DeleteID) - - if ACLManager.CheckIPBackupObjectOwner(currentACL, DeleteIDobj, admin) == 1: - config = DeleteIDobj.config - conf = json.loads(config) - FileName = conf['name'] - command = "rm -r /home/backup/%s.tar.gz" % FileName - ProcessUtilities.executioner(command) - DeleteIDobj.delete() - - except BaseException as msg: - pass - Data['job'] = [] - - for sub in backobj: - try: - wpsite = WPSites.objects.get(pk=sub.WPSiteID) - web = wpsite.title - except: - web = "Website Not Found" - - try: - config = sub.config - conf = json.loads(config) - Backuptype = conf['Backuptype'] - BackupDestination = conf['BackupDestination'] - except: - Backuptype = "Backup type not exists" - - Data['job'].append({ - 'id': sub.id, - 'title': web, - 'Backuptype': Backuptype, - 'BackupDestination': BackupDestination - }) - - proc = httpProc(request, 'websiteFunctions/RestoreBackups.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def AutoLogin(self, request=None, userID=None): - - WPid = request.GET.get('id') - currentACL = ACLManager.loadedACL(userID) - WPobj = WPSites.objects.get(pk=WPid) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(WPobj.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - from managePHP.phpManager import PHPManager - - php = PHPManager.getPHPString(WPobj.owner.phpSelection) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" - data = { - "name": "wp-manager", - "IP": ACLManager.GetServerIP() - } - - import requests - response = requests.post(url, data=json.dumps(data)) - Status = response.json()['status'] - - if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: - - ## Get title - - password = randomPassword.generate_pass(10) - - command = f'sudo -u %s {FinalPHPPath} /usr/bin/wp user create autologin %s --role=administrator --user_pass="%s" --path=%s --skip-plugins --skip-themes' % ( - WPobj.owner.externalApp, 'autologin@cloudpages.cloud', password, WPobj.path) - ProcessUtilities.executioner(command) - - command = f'sudo -u %s {FinalPHPPath} /usr/bin/wp user update autologin --user_pass="%s" --path=%s --skip-plugins --skip-themes' % ( - WPobj.owner.externalApp, password, WPobj.path) - ProcessUtilities.executioner(command) - - data = {} - - if WPobj.FinalURL.endswith('/'): - FinalURL = WPobj.FinalURL[:-1] - else: - FinalURL = WPobj.FinalURL - - data['url'] = 'https://%s' % (FinalURL) - data['userName'] = 'autologin' - data['password'] = password - - proc = httpProc(request, 'websiteFunctions/AutoLogin.html', - data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def ConfigurePlugins(self, request=None, userID=None, data=None): - - if ACLManager.CheckForPremFeature('wp-manager'): - currentACL = ACLManager.loadedACL(userID) - userobj = Administrator.objects.get(pk=userID) - - Selectedplugins = wpplugins.objects.filter(owner=userobj) - # data['Selectedplugins'] = wpplugins.objects.filter(ProjectOwner=HostingCompany) - - Data = {'Selectedplugins': Selectedplugins, } - proc = httpProc(request, 'websiteFunctions/WPConfigurePlugins.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def Addnewplugin(self, request=None, userID=None, data=None): - from django.shortcuts import reverse - if ACLManager.CheckForPremFeature('wp-manager'): - currentACL = ACLManager.loadedACL(userID) - adminNames = ACLManager.loadAllUsers(userID) - packagesName = ACLManager.loadPackages(userID, currentACL) - phps = PHPManager.findPHPVersions() - - Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps} - proc = httpProc(request, 'websiteFunctions/WPAddNewPlugin.html', - Data, 'createDatabase') - return proc.render() - - return redirect(reverse('pricing')) - - def SearchOnkeyupPlugin(self, userID=None, data=None): - try: - if ACLManager.CheckForPremFeature('wp-manager'): - currentACL = ACLManager.loadedACL(userID) - - pluginname = data['pluginname'] - # logging.CyberCPLogFileWriter.writeToFile("Plugin Name ....... %s"%pluginname) - - url = "http://api.wordpress.org/plugins/info/1.1/?action=query_plugins&request[search]=%s" % str( - pluginname) - import requests - - res = requests.get(url) - r = res.json() - - # return proc.ajax(1, 'Done', {'plugins': r}) - - data_ret = {'status': 1, 'plugns': r, } - - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': 'Premium feature not available.'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def AddNewpluginAjax(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - - userobj = Administrator.objects.get(pk=userID) - - config = data['config'] - Name = data['Name'] - # pluginname = data['pluginname'] - # logging.CyberCPLogFileWriter.writeToFile("config ....... %s"%config) - # logging.CyberCPLogFileWriter.writeToFile(" Name ....... %s"%Name) - - addpl = wpplugins(Name=Name, config=json.dumps(config), owner=userobj) - addpl.save() - - data_ret = {'status': 1} - - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'AddNewpluginAjax': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def EidtPlugin(self, request=None, userID=None, pluginbID=None): - Data = {} - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - pluginobj = wpplugins.objects.get(pk=pluginbID) - - if ACLManager.CheckIPPluginObjectOwner(currentACL, pluginobj, admin) == 1: - pass - else: - return ACLManager.loadError() - - lmo = json.loads(pluginobj.config) - Data['Selectedplugins'] = lmo - Data['pluginbID'] = pluginbID - Data['BucketName'] = pluginobj.Name - - proc = httpProc(request, 'websiteFunctions/WPEidtPlugin.html', - Data, 'createDatabase') - return proc.render() - - def deletesPlgin(self, userID=None, data=None, ): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - userobj = Administrator.objects.get(pk=userID) - pluginname = data['pluginname'] - pluginbBucketID = data['pluginbBucketID'] - # logging.CyberCPLogFileWriter.writeToFile("pluginbID ....... %s" % pluginbBucketID) - # logging.CyberCPLogFileWriter.writeToFile("pluginname ....... %s" % pluginname) - - obj = wpplugins.objects.get(pk=pluginbBucketID, owner=userobj) - - if ACLManager.CheckIPPluginObjectOwner(currentACL, obj, admin) == 1: - pass - else: - return ACLManager.loadError() - - ab = [] - ab = json.loads(obj.config) - ab.remove(pluginname) - obj.config = json.dumps(ab) - obj.save() - - data_ret = {'status': 1} - - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except BaseException as msg: - data_ret = {'status': 0, 'deletesPlgin': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def Addplugineidt(self, userID=None, data=None, ): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - userobj = Administrator.objects.get(pk=userID) - pluginname = data['pluginname'] - pluginbBucketID = data['pluginbBucketID'] - - # logging.CyberCPLogFileWriter.writeToFile("pluginbID ....... %s" % pluginbBucketID) - # logging.CyberCPLogFileWriter.writeToFile("pluginname ....... %s" % pluginname) - - pObj = wpplugins.objects.get(pk=pluginbBucketID, owner=userobj) - - if ACLManager.CheckIPPluginObjectOwner(currentACL, pObj, admin) == 1: - pass - else: - return ACLManager.loadError() - - listofplugin = json.loads(pObj.config) - try: - index = listofplugin.index(pluginname) - print('index.....%s' % index) - if (index >= 0): - data_ret = {'status': 0, 'deletesPlgin': 0, 'error_message': str('Already Save in your Plugin lis')} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except: - ab = [] - ab = json.loads(pObj.config) - ab.append(pluginname) - pObj.config = json.dumps(ab) - pObj.save() - - data_ret = {'status': 1} - - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except BaseException as msg: - data_ret = {'status': 0, 'deletesPlgin': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def modifyWebsite(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - - websitesName = ACLManager.findAllSites(currentACL, userID) - phps = PHPManager.findPHPVersions() - proc = httpProc(request, 'websiteFunctions/modifyWebsite.html', - {'websiteList': websitesName, 'phps': phps}, 'modifyWebsite') - return proc.render() - - def deleteWebsite(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - websitesName = ACLManager.findAllSites(currentACL, userID) - proc = httpProc(request, 'websiteFunctions/deleteWebsite.html', - {'websiteList': websitesName}, 'deleteWebsite') - return proc.render() - - def CreateNewDomain(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - websitesName = ACLManager.findAllSites(currentACL, userID) - - try: - admin = Administrator.objects.get(pk=userID) - if admin.defaultSite == 0: - websites = ACLManager.findWebsiteObjects(currentACL, userID) - admin.defaultSite = websites[0].id - admin.save() - except: - pass - - try: - admin = Administrator.objects.get(pk=userID) - defaultDomain = Websites.objects.get(pk=admin.defaultSite).domain - except: - try: - admin = Administrator.objects.get(pk=userID) - websites = ACLManager.findWebsiteObjects(currentACL, userID) - admin.defaultSite = websites[0].id - admin.save() - defaultDomain = websites[0].domain - except: - defaultDomain='NONE' - - - url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" - data = { - "name": "all", - "IP": ACLManager.GetServerIP() - } - - import requests - response = requests.post(url, data=json.dumps(data)) - Status = response.json()['status'] - - test_domain_status = 0 - - if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: - test_domain_status = 1 - - rnpss = randomPassword.generate_pass(10) - proc = httpProc(request, 'websiteFunctions/createDomain.html', - {'websiteList': websitesName, 'phps': PHPManager.findPHPVersions(), 'Randam_String': rnpss, - 'test_domain_data': test_domain_status, 'defaultSite': defaultDomain}) - return proc.render() - - def siteState(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - - websitesName = ACLManager.findAllSites(currentACL, userID) - - proc = httpProc(request, 'websiteFunctions/suspendWebsite.html', - {'websiteList': websitesName}, 'suspendWebsite') - return proc.render() - - def listWebsites(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - pagination = self.websitePagination(currentACL, userID) - proc = httpProc(request, 'websiteFunctions/listWebsites.html', - {"pagination": pagination}) - return proc.render() - - def listChildDomains(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - adminNames = ACLManager.loadAllUsers(userID) - packagesName = ACLManager.loadPackages(userID, currentACL) - phps = PHPManager.findPHPVersions() - - Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps} - proc = httpProc(request, 'websiteFunctions/listChildDomains.html', - Data) - return proc.render() - - def listCron(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(request.GET.get('domain'), admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - proc = httpProc(request, 'websiteFunctions/listCron.html', - {'domain': request.GET.get('domain')}) - return proc.render() - - def domainAlias(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - aliasManager = AliasManager(self.domain) - noAlias, finalAlisList = aliasManager.fetchAlisForDomains() - - path = "/home/" + self.domain + "/public_html" - - proc = httpProc(request, 'websiteFunctions/domainAlias.html', { - 'masterDomain': self.domain, - 'aliases': finalAlisList, - 'path': path, - 'noAlias': noAlias - }) - return proc.render() - - def FetchWPdata(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core version --skip-plugins --skip-themes --path=%s 2>/dev/null' % ( - Vhuser, FinalPHPPath, path) - version = ProcessUtilities.outputExecutioner(command, None, True) - version = html.escape(version) - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin status litespeed-cache --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, path) - lscachee = ProcessUtilities.outputExecutioner(command) - - if lscachee.find('Status: Active') > -1: - lscache = 1 - else: - lscache = 0 - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp config list --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, path) - stdout = ProcessUtilities.outputExecutioner(command) - debugging = 0 - for items in stdout.split('\n'): - if items.find('WP_DEBUG true constant') > -1: - debugging = 1 - break - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp option get blog_public --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, path) - stdoutput = ProcessUtilities.outputExecutioner(command) - searchindex = int(stdoutput.splitlines()[-1]) - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp maintenance-mode status --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, path) - maintenanceMod = ProcessUtilities.outputExecutioner(command) - - result = maintenanceMod.splitlines()[-1] - if result.find('not active') > -1: - maintenanceMode = 0 - else: - maintenanceMode = 1 - - ##### Check passwd protection - vhostName = wpsite.owner.domain - vhostPassDir = f'/home/{vhostName}' - path = f'{vhostPassDir}/{WPManagerID}' - if os.path.exists(path): - passwd = 1 - else: - passwd = 0 - - #### Check WP cron - command = "sudo -u %s cat %s/wp-config.php" % (Vhuser, wpsite.path) - stdout = ProcessUtilities.outputExecutioner(command) - if stdout.find("'DISABLE_WP_CRON', 'true'") > -1: - wpcron = 1 - else: - wpcron = 0 - - fb = { - 'version': version.rstrip('\n'), - 'lscache': lscache, - 'debugging': debugging, - 'searchIndex': searchindex, - 'maintenanceMode': maintenanceMode, - 'passwordprotection': passwd, - 'wpcron': wpcron - - } - - data_ret = {'status': 1, 'error_message': 'None', 'ret_data': fb} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def GetCurrentPlugins(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin list --skip-plugins --skip-themes --format=json --path=%s' % ( - Vhuser, FinalPHPPath, path) - stdoutput = ProcessUtilities.outputExecutioner(command) - json_data = stdoutput.splitlines()[-1] - - data_ret = {'status': 1, 'error_message': 'None', 'plugins': json_data} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def GetCurrentThemes(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp theme list --skip-plugins --skip-themes --format=json --path=%s' % ( - Vhuser, FinalPHPPath, path) - stdoutput = ProcessUtilities.outputExecutioner(command) - json_data = stdoutput.splitlines()[-1] - - data_ret = {'status': 1, 'error_message': 'None', 'themes': json_data} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def fetchstaging(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - from plogical.phpUtilities import phpUtilities - - json_data = phpUtilities.GetStagingInJson(wpsite.wpstaging_set.all().order_by('-id')) - - data_ret = {'status': 1, 'error_message': 'None', 'wpsites': json_data} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def fetchDatabase(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - php = PHPManager.getPHPString(wpsite.owner.phpSelection) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - command = f'{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config get DB_NAME --skip-plugins --skip-themes --path={wpsite.path} 2>/dev/null' - retStatus, stdoutput = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp, True, None, 1) - - if stdoutput.find('Error:') == -1: - DataBaseName = stdoutput.rstrip("\n") - DataBaseName = html.escape(DataBaseName) - else: - data_ret = {'status': 0, 'error_message': stdoutput} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - command = f'{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config get DB_USER --skip-plugins --skip-themes --path={wpsite.path} 2>/dev/null' - retStatus, stdoutput = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp, True, None, 1) - - if stdoutput.find('Error:') == -1: - DataBaseUser = stdoutput.rstrip("\n") - DataBaseUser = html.escape(DataBaseUser) - else: - data_ret = {'status': 0, 'error_message': stdoutput} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - command = f'{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config get table_prefix --skip-plugins --skip-themes --path={wpsite.path} 2>/dev/null' - retStatus, stdoutput = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp, True, None, 1) - - if stdoutput.find('Error:') == -1: - tableprefix = stdoutput.rstrip("\n") - tableprefix = html.escape(tableprefix) - else: - data_ret = {'status': 0, 'error_message': stdoutput} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - data_ret = {'status': 1, 'error_message': 'None', "DataBaseUser": DataBaseUser, - "DataBaseName": DataBaseName, 'tableprefix': tableprefix} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def SaveUpdateConfig(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - Plugins = data['Plugins'] - Themes = data['Themes'] - AutomaticUpdates = data['AutomaticUpdates'] - - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - - php = PHPManager.getPHPString(wpsite.owner.phpSelection) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - if AutomaticUpdates == 'Disabled': - command = f"{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_AUTO_UPDATE_CORE false --raw --allow-root --path=" + wpsite.path - result = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp) - - if result.find('Success:') == -1: - raise BaseException(result) - elif AutomaticUpdates == 'Minor and Security Updates': - command = f"{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_AUTO_UPDATE_CORE minor --allow-root --path=" + wpsite.path - result = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp) - - if result.find('Success:') == -1: - raise BaseException(result) - else: - command = f"{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_AUTO_UPDATE_CORE true --raw --allow-root --path=" + wpsite.path - result = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp) - - if result.find('Success:') == -1: - raise BaseException(result) - - wpsite.AutoUpdates = AutomaticUpdates - wpsite.PluginUpdates = Plugins - wpsite.ThemeUpdates = Themes - wpsite.save() - - data_ret = {'status': 1, 'error_message': 'None', } - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def DeploytoProduction(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - statgingID = data['StagingID'] - wpsite = WPSites.objects.get(pk=WPManagerID) - StagingObj = WPSites.objects.get(pk=statgingID) - - ### - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - if ACLManager.checkOwnership(StagingObj.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - ### - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['statgingID'] = statgingID - extraArgs['WPid'] = WPManagerID - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - background = ApplicationInstaller('DeploytoProduction', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def WPCreateBackup(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - Backuptype = data['Backuptype'] - - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['WPid'] = WPManagerID - extraArgs['Backuptype'] = Backuptype - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - background = ApplicationInstaller('WPCreateBackup', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def RestoreWPbackupNow(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - backupid = data['backupid'] - DesSiteID = data['DesSite'] - - # try: - # - # bwp = WPSites.objects.get(pk=int(backupid)) - # - # if ACLManager.checkOwnership(bwp.owner.domain, admin, currentACL) == 1: - # pass - # else: - # return ACLManager.loadError() - # - # except: - # pass - # - # dwp = WPSites.objects.get(pk=int(DesSiteID)) - # if ACLManager.checkOwnership(dwp.owner.domain, admin, currentACL) == 1: - # pass - # else: - # return ACLManager.loadError() - - Domain = data['Domain'] - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['backupid'] = backupid - extraArgs['DesSiteID'] = DesSiteID - extraArgs['Domain'] = Domain - extraArgs['path'] = data['path'] - extraArgs['home'] = data['home'] - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - background = ApplicationInstaller('RestoreWPbackupNow', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def SaveBackupConfig(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - ConfigType = data['type'] - if ConfigType == 'SFTP': - Hname = data['Hname'] - Uname = data['Uname'] - Passwd = data['Passwd'] - path = data['path'] - config = { - "Hostname": Hname, - "Username": Uname, - "Password": Passwd, - "Path": path - } - elif ConfigType == "S3": - Provider = data['Provider'] - if Provider == "Backblaze": - S3keyname = data['S3keyname'] - SecertKey = data['SecertKey'] - AccessKey = data['AccessKey'] - EndUrl = data['EndUrl'] - config = { - "Provider": Provider, - "S3keyname": S3keyname, - "SecertKey": SecertKey, - "AccessKey": AccessKey, - "EndUrl": EndUrl - - } - else: - S3keyname = data['S3keyname'] - SecertKey = data['SecertKey'] - AccessKey = data['AccessKey'] - config = { - "Provider": Provider, - "S3keyname": S3keyname, - "SecertKey": SecertKey, - "AccessKey": AccessKey, - - } - - mkobj = RemoteBackupConfig(owner=admin, configtype=ConfigType, config=json.dumps(config)) - mkobj.save() - - time.sleep(1) - - data_ret = {'status': 1, 'error_message': 'None', } - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def SaveBackupSchedule(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - FileRetention = data['FileRetention'] - Backfrequency = data['Backfrequency'] - ScheduleName = data['ScheduleName'] - RemoteConfigID = data['RemoteConfigID'] - BackupType = data['BackupType'] - - RemoteBackupConfigobj = RemoteBackupConfig.objects.get(pk=RemoteConfigID) - Rconfig = json.loads(RemoteBackupConfigobj.config) - - try: - # This code is only supposed to run if backups are s3, not for SFTP - provider = Rconfig['Provider'] - if provider == "Backblaze": - EndURl = Rconfig['EndUrl'] - elif provider == "Amazon": - EndURl = "https://s3.us-east-1.amazonaws.com" - elif provider == "Wasabi": - EndURl = "https://s3.wasabisys.com" - - AccessKey = Rconfig['AccessKey'] - SecertKey = Rconfig['SecertKey'] - - session = boto3.session.Session() - - client = session.client( - 's3', - endpoint_url=EndURl, - aws_access_key_id=AccessKey, - aws_secret_access_key=SecertKey, - verify=False - ) - - ############Creating Bucket - BucketName = randomPassword.generate_pass().lower() - - try: - client.create_bucket(Bucket=BucketName) - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile("Creating Bucket Error: %s" % str(msg)) - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - config = { - 'BackupType': BackupType, - 'BucketName': BucketName - } - except BaseException as msg: - config = {'BackupType': BackupType} - pass - - svobj = RemoteBackupSchedule(RemoteBackupConfig=RemoteBackupConfigobj, Name=ScheduleName, - timeintervel=Backfrequency, fileretention=FileRetention, - config=json.dumps(config), - lastrun=str(time.time())) - svobj.save() - - data_ret = {'status': 1, 'error_message': 'None', } - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def AddWPsiteforRemoteBackup(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - WPid = data['WpsiteID'] - RemoteScheduleID = data['RemoteScheduleID'] - - wpsiteobj = WPSites.objects.get(pk=WPid) - WPpath = wpsiteobj.path - VHuser = wpsiteobj.owner.externalApp - PhpVersion = wpsiteobj.owner.phpSelection - php = PHPManager.getPHPString(PhpVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - ####Get DB Name - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp config get DB_NAME --skip-plugins --skip-themes --path=%s' % ( - VHuser, FinalPHPPath, WPpath) - result, stdout = ProcessUtilities.outputExecutioner(command, None, None, None, 1) - - if stdout.find('Error:') > -1: - raise BaseException(stdout) - else: - Finaldbname = stdout.rstrip("\n") - - ## Get DB obj - try: - DBobj = Databases.objects.get(dbName=Finaldbname) - except: - raise BaseException(str("DataBase Not Found")) - RemoteScheduleIDobj = RemoteBackupSchedule.objects.get(pk=RemoteScheduleID) - - svobj = RemoteBackupsites(owner=RemoteScheduleIDobj, WPsites=WPid, database=DBobj.pk) - svobj.save() - - data_ret = {'status': 1, 'error_message': 'None', } - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def UpdateRemoteschedules(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - ScheduleID = data['ScheduleID'] - Frequency = data['Frequency'] - FileRetention = data['FileRetention'] - - scheduleobj = RemoteBackupSchedule.objects.get(pk=ScheduleID) - scheduleobj.timeintervel = Frequency - scheduleobj.fileretention = FileRetention - scheduleobj.save() - - data_ret = {'status': 1, 'error_message': 'None', } - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def ScanWordpressSite(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - allweb = Websites.objects.all() - - childdomain = ChildDomains.objects.all() - - for web in allweb: - webpath = "/home/%s/public_html/" % web.domain - command = "cat %swp-config.php" % webpath - result = ProcessUtilities.outputExecutioner(command, web.externalApp) - - if os.path.exists(ProcessUtilities.debugPath): - logging.CyberCPLogFileWriter.writeToFile(result) - - if result.find('No such file or directory') == -1: - try: - WPSites.objects.get(path=webpath) - except: - wpobj = WPSites(owner=web, title=web.domain, path=webpath, FinalURL=web.domain, - AutoUpdates="Enabled", PluginUpdates="Enabled", - ThemeUpdates="Enabled", ) - wpobj.save() - - for chlid in childdomain: - childPath = chlid.path.rstrip('/') - - command = "cat %s/wp-config.php" % childPath - result = ProcessUtilities.outputExecutioner(command, chlid.master.externalApp) - - if os.path.exists(ProcessUtilities.debugPath): - logging.CyberCPLogFileWriter.writeToFile(result) - - if result.find('No such file or directory') == -1: - fChildPath = f'{childPath}/' - try: - WPSites.objects.get(path=fChildPath) - except: - - wpobj = WPSites(owner=chlid.master, title=chlid.domain, path=fChildPath, FinalURL=chlid.domain, - AutoUpdates="Enabled", PluginUpdates="Enabled", - ThemeUpdates="Enabled", ) - wpobj.save() - - data_ret = {'status': 1, 'error_message': 'None', } - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def installwpcore(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - ###fetch WP version - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core version --skip-plugins --skip-themes --path=%s 2>/dev/null' % ( - Vhuser, FinalPHPPath, path) - version = ProcessUtilities.outputExecutioner(command, None, True) - version = version.rstrip("\n") - - ###install wp core - command = f"sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp core download --force --skip-content --version={version} --path={path}" - output = ProcessUtilities.outputExecutioner(command) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', 'result': output} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def dataintegrity(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - ###fetch WP version - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core verify-checksums --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, path) - result = ProcessUtilities.outputExecutioner(command) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', 'result': result} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def UpdatePlugins(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - plugin = data['plugin'] - pluginarray = data['pluginarray'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['plugin'] = plugin - extraArgs['pluginarray'] = pluginarray - extraArgs['FinalPHPPath'] = FinalPHPPath - extraArgs['path'] = path - extraArgs['Vhuser'] = Vhuser - - background = ApplicationInstaller('UpdateWPPlugin', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def UpdateThemes(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - Theme = data['Theme'] - Themearray = data['Themearray'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['Theme'] = Theme - extraArgs['Themearray'] = Themearray - extraArgs['FinalPHPPath'] = FinalPHPPath - extraArgs['path'] = path - extraArgs['Vhuser'] = Vhuser - - background = ApplicationInstaller('UpdateWPTheme', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def DeletePlugins(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - plugin = data['plugin'] - pluginarray = data['pluginarray'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['plugin'] = plugin - extraArgs['pluginarray'] = pluginarray - extraArgs['FinalPHPPath'] = FinalPHPPath - extraArgs['path'] = path - extraArgs['Vhuser'] = Vhuser - - background = ApplicationInstaller('DeletePlugins', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def DeleteThemes(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - Theme = data['Theme'] - Themearray = data['Themearray'] - wpsite = WPSites.objects.get(pk=WPManagerID) - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['Theme'] = Theme - extraArgs['Themearray'] = Themearray - extraArgs['FinalPHPPath'] = FinalPHPPath - extraArgs['path'] = path - extraArgs['Vhuser'] = Vhuser - - background = ApplicationInstaller('DeleteThemes', extraArgs) - background.start() - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def ChangeStatus(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - plugin = data['plugin'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin status %s --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, plugin, path) - stdoutput = ProcessUtilities.outputExecutioner(command) - - if stdoutput.find('Status: Active') > -1: - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin deactivate %s --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, plugin, path) - stdoutput = ProcessUtilities.outputExecutioner(command) - time.sleep(3) - - else: - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin activate %s --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, plugin, path) - stdoutput = ProcessUtilities.outputExecutioner(command) - time.sleep(3) - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def ChangeStatusThemes(self, userID=None, data=None): - try: - # logging.CyberCPLogFileWriter.writeToFile("Error WP ChangeStatusThemes ....... %s") - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - Theme = data['theme'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['Theme'] = Theme - extraArgs['FinalPHPPath'] = FinalPHPPath - extraArgs['path'] = path - extraArgs['Vhuser'] = Vhuser - - background = ApplicationInstaller('ChangeStatusThemes', extraArgs) - background.start() - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def CreateStagingNow(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['StagingDomain'] = data['StagingDomain'] - extraArgs['StagingName'] = data['StagingName'] - extraArgs['WPid'] = data['WPid'] - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - wpsite = WPSites.objects.get(pk=data['WPid']) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - background = ApplicationInstaller('CreateStagingNow', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def UpdateWPSettings(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - siteId = data['siteId'] - setting = data['setting'] - value = data['value'] - - wpsite = WPSites.objects.get(pk=siteId) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) != 1: - return ACLManager.loadError() - # Get PHP version and path Webobj = Websites.objects.get(pk=wpsite.owner_id) Vhuser = Webobj.externalApp @@ -4010,751 +1973,59 @@ Require valid-user""" with open(htaccess, 'w') as f: f.write(htaccess_content) - def submitWebsiteModify(self, userID=None, data=None): + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def GetWPSitesByDomain(self, userID=None, data=None): try: - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'modifyWebsite') == 0: - return ACLManager.loadErrorJson('modifyStatus', 0) - admin = Administrator.objects.get(pk=userID) - if ACLManager.checkOwnership(data['websiteToBeModified'], admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('websiteDeleteStatus', 0) - - packs = ACLManager.loadPackages(userID, currentACL) - admins = ACLManager.loadAllUsers(userID) - - ## Get packs name - - json_data = "[" - checker = 0 - - for items in packs: - dic = {"pack": items} - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - - json_data = json_data + ']' - - ### Get admin names - - admin_data = "[" - checker = 0 - - for items in admins: - dic = {"adminNames": items} - - if checker == 0: - admin_data = admin_data + json.dumps(dic) - checker = 1 - else: - admin_data = admin_data + ',' + json.dumps(dic) - - admin_data = admin_data + ']' - - websiteToBeModified = data['websiteToBeModified'] - - modifyWeb = Websites.objects.get(domain=websiteToBeModified) - - email = modifyWeb.adminEmail - currentPack = modifyWeb.package.packageName - owner = modifyWeb.admin.userName - - data_ret = {'status': 1, 'modifyStatus': 1, 'error_message': "None", "adminEmail": email, - "packages": json_data, "current_pack": currentPack, "adminNames": admin_data, - 'currentAdmin': owner} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - - except BaseException as msg: - dic = {'status': 0, 'modifyStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def fetchWebsiteDataJSON(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'createWebsite') == 0: - return ACLManager.loadErrorJson('createWebSiteStatus', 0) - - packs = ACLManager.loadPackages(userID, currentACL) - admins = ACLManager.loadAllUsers(userID) - - ## Get packs name - - json_data = "[" - checker = 0 - - for items in packs: - dic = {"pack": items} - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - - json_data = json_data + ']' - - ### Get admin names - - admin_data = "[" - checker = 0 - - for items in admins: - dic = {"adminNames": items} - - if checker == 0: - admin_data = admin_data + json.dumps(dic) - checker = 1 - else: - admin_data = admin_data + ',' + json.dumps(dic) - - admin_data = admin_data + ']' - - data_ret = {'status': 1, 'error_message': "None", - "packages": json_data, "adminNames": admin_data} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - - except BaseException as msg: - dic = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def saveWebsiteChanges(self, userID=None, data=None): - try: + domain = data['domain'] - package = data['packForWeb'] - email = data['email'] - phpVersion = data['phpVersion'] - newUser = data['admin'] - - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'modifyWebsite') == 0: - return ACLManager.loadErrorJson('saveStatus', 0) - - admin = Administrator.objects.get(pk=userID) + website = Websites.objects.get(domain=domain) + if ACLManager.checkOwnership(domain, admin, currentACL) == 1: pass else: - return ACLManager.loadErrorJson('websiteDeleteStatus', 0) - - newOwner = Administrator.objects.get(userName=newUser) - if ACLManager.checkUserOwnerShip(currentACL, admin, newOwner) == 1: - pass - else: - return ACLManager.loadErrorJson('websiteDeleteStatus', 0) - - confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + domain - completePathToConfigFile = confPath + "/vhost.conf" - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " changePHP --phpVersion '" + phpVersion + "' --path " + completePathToConfigFile - ProcessUtilities.popenExecutioner(execPath) - - #### - - newOwner = Administrator.objects.get(userName=newUser) - - modifyWeb = Websites.objects.get(domain=domain) - webpack = Package.objects.get(packageName=package) - - modifyWeb.package = webpack - modifyWeb.adminEmail = email - modifyWeb.phpSelection = phpVersion - modifyWeb.admin = newOwner - - modifyWeb.save() - - ## Fix https://github.com/usmannasir/cyberpanel/issues/998 - - # from plogical.IncScheduler import IncScheduler - # isPU = IncScheduler('CalculateAndUpdateDiskUsage', {}) - # isPU.start() - - command = '/usr/local/CyberCP/bin/python /usr/local/CyberCP/plogical/IncScheduler.py UpdateDiskUsageForce' - ProcessUtilities.outputExecutioner(command) - - ## - - data_ret = {'status': 1, 'saveStatus': 1, 'error_message': "None"} + return ACLManager.loadErrorJson('fetchStatus', 0) + + # Get all WordPress sites for this website + wp_sites = [] + for wp in website.wp_sites.all(): + site_data = { + 'id': wp.id, + 'title': wp.title, + 'url': wp.url, + 'version': wp.version, + 'phpVersion': wp.phpVersion, + 'activePlugins': wp.activePlugins, + 'theme': wp.theme, + 'debugging': wp.debugging, + 'searchIndex': wp.searchIndex, + 'maintenanceMode': wp.maintenanceMode, + 'passwordProtection': wp.passwordProtection + } + wp_sites.append(site_data) + + data_ret = {'status': 1, 'data': wp_sites} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except Websites.DoesNotExist: + data_ret = {'status': 0, 'error_message': 'Website not found'} json_data = json.dumps(data_ret) return HttpResponse(json_data) - except BaseException as msg: - data_ret = {'status': 0, 'saveStatus': 0, 'error_message': str(msg)} + data_ret = {'status': 0, 'error_message': str(msg)} json_data = json.dumps(data_ret) return HttpResponse(json_data) - def loadDomainHome(self, request=None, userID=None, data=None): - - if Websites.objects.filter(domain=self.domain).exists(): - - currentACL = ACLManager.loadedACL(userID) - website = Websites.objects.get(domain=self.domain) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - Data = {} - - marketingStatus = emACL.checkIfEMEnabled(admin.userName) - - Data['marketingStatus'] = marketingStatus - Data['ftpTotal'] = website.package.ftpAccounts - Data['ftpUsed'] = website.users_set.all().count() - - Data['databasesUsed'] = website.databases_set.all().count() - Data['databasesTotal'] = website.package.dataBases - - Data['domain'] = self.domain - - DiskUsage, DiskUsagePercentage, bwInMB, bwUsage = virtualHostUtilities.FindStats(website) - - ## bw usage calculations - - Data['bwInMBTotal'] = website.package.bandwidth - Data['bwInMB'] = bwInMB - Data['bwUsage'] = bwUsage - - if DiskUsagePercentage > 100: - DiskUsagePercentage = 100 - - Data['diskUsage'] = DiskUsagePercentage - Data['diskInMB'] = DiskUsage - Data['diskInMBTotal'] = website.package.diskSpace - - Data['phps'] = PHPManager.findPHPVersions() - - servicePath = '/home/cyberpanel/postfix' - if os.path.exists(servicePath): - Data['email'] = 1 - else: - Data['email'] = 0 - - ## Getting SSL Information - try: - import OpenSSL - from datetime import datetime - filePath = '/etc/letsencrypt/live/%s/fullchain.pem' % (self.domain) - x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, - open(filePath, 'r').read()) - expireData = x509.get_notAfter().decode('ascii') - finalDate = datetime.strptime(expireData, '%Y%m%d%H%M%SZ') - - now = datetime.now() - diff = finalDate - now - Data['viewSSL'] = 1 - Data['days'] = str(diff.days) - Data['authority'] = x509.get_issuer().get_components()[1][1].decode('utf-8') - - if Data['authority'] == 'Denial': - Data['authority'] = '%s has SELF-SIGNED SSL.' % (self.domain) - else: - Data['authority'] = '%s has SSL from %s.' % (self.domain, Data['authority']) - - except BaseException as msg: - Data['viewSSL'] = 0 - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - - servicePath = '/home/cyberpanel/pureftpd' - if os.path.exists(servicePath): - Data['ftp'] = 1 - else: - Data['ftp'] = 0 - - proc = httpProc(request, 'websiteFunctions/website.html', Data) - return proc.render() - else: - proc = httpProc(request, 'websiteFunctions/website.html', - {"error": 1, "domain": "This domain does not exists."}) - return proc.render() - - def launchChild(self, request=None, userID=None, data=None): - - if ChildDomains.objects.filter(domain=self.childDomain).exists(): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - website = Websites.objects.get(domain=self.domain) - - Data = {} - - Data['ftpTotal'] = website.package.ftpAccounts - Data['ftpUsed'] = website.users_set.all().count() - - Data['databasesUsed'] = website.databases_set.all().count() - Data['databasesTotal'] = website.package.dataBases - - Data['domain'] = self.domain - Data['childDomain'] = self.childDomain - - DiskUsage, DiskUsagePercentage, bwInMB, bwUsage = virtualHostUtilities.FindStats(website) - - ## bw usage calculations - - Data['bwInMBTotal'] = website.package.bandwidth - Data['bwInMB'] = bwInMB - Data['bwUsage'] = bwUsage - - if DiskUsagePercentage > 100: - DiskUsagePercentage = 100 - - Data['diskUsage'] = DiskUsagePercentage - Data['diskInMB'] = DiskUsage - Data['diskInMBTotal'] = website.package.diskSpace - - Data['phps'] = PHPManager.findPHPVersions() - - servicePath = '/home/cyberpanel/postfix' - if os.path.exists(servicePath): - Data['email'] = 1 - else: - Data['email'] = 0 - - servicePath = '/home/cyberpanel/pureftpd' - if os.path.exists(servicePath): - Data['ftp'] = 1 - else: - Data['ftp'] = 0 - - ## Getting SSL Information - try: - import OpenSSL - from datetime import datetime - filePath = '/etc/letsencrypt/live/%s/fullchain.pem' % (self.childDomain) - x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, - open(filePath, 'r').read()) - expireData = x509.get_notAfter().decode('ascii') - finalDate = datetime.strptime(expireData, '%Y%m%d%H%M%SZ') - - now = datetime.now() - diff = finalDate - now - Data['viewSSL'] = 1 - Data['days'] = str(diff.days) - Data['authority'] = x509.get_issuer().get_components()[1][1].decode('utf-8') - - if Data['authority'] == 'Denial': - Data['authority'] = '%s has SELF-SIGNED SSL.' % (self.childDomain) - else: - Data['authority'] = '%s has SSL from %s.' % (self.childDomain, Data['authority']) - - except BaseException as msg: - Data['viewSSL'] = 0 - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - - proc = httpProc(request, 'websiteFunctions/launchChild.html', Data) - return proc.render() - else: - proc = httpProc(request, 'websiteFunctions/launchChild.html', - {"error": 1, "domain": "This child domain does not exists"}) - return proc.render() - - def getDataFromLogFile(self, userID=None, data=None): - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - logType = data['logType'] - self.domain = data['virtualHost'] - page = data['page'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('logstatus', 0) - - if logType == 1: - fileName = "/home/" + self.domain + "/logs/" + self.domain + ".access_log" - else: - fileName = "/home/" + self.domain + "/logs/" + self.domain + ".error_log" - - command = 'ls -la %s' % fileName - result = ProcessUtilities.outputExecutioner(command) - - if result.find('->') > -1: - final_json = json.dumps( - {'status': 0, 'logstatus': 0, - 'error_message': "Symlink attack."}) - return HttpResponse(final_json) - - ## get Logs - website = Websites.objects.get(domain=self.domain) - - output = virtualHostUtilities.getAccessLogs(fileName, page, website.externalApp) - - if output.find("1,None") > -1: - final_json = json.dumps( - {'status': 0, 'logstatus': 0, - 'error_message': "Not able to fetch logs, see CyberPanel main log file, Error: %s" % (output)}) - return HttpResponse(final_json) - - ## get log ends here. - - data = output.split("\n") - - json_data = "[" - checker = 0 - - for items in reversed(data): - if len(items) > 10: - logData = items.split(" ") - domain = logData[5].strip('"') - ipAddress = logData[0].strip('"') - time = (logData[3]).strip("[").strip("]") - resource = logData[6].strip('"') - size = logData[9].replace('"', '') - - dic = {'domain': domain, - 'ipAddress': ipAddress, - 'time': time, - 'resource': resource, - 'size': size, - } - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - - json_data = json_data + ']' - final_json = json.dumps({'status': 1, 'logstatus': 1, 'error_message': "None", "data": json_data}) - return HttpResponse(final_json) - - def fetchErrorLogs(self, userID=None, data=None): - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['virtualHost'] - page = data['page'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('logstatus', 0) - - fileName = "/home/" + self.domain + "/logs/" + self.domain + ".error_log" - - command = 'ls -la %s' % fileName - result = ProcessUtilities.outputExecutioner(command) - - if result.find('->') > -1: - final_json = json.dumps( - {'status': 0, 'logstatus': 0, - 'error_message': "Symlink attack."}) - return HttpResponse(final_json) - - ## get Logs - website = Websites.objects.get(domain=self.domain) - - output = virtualHostUtilities.getErrorLogs(fileName, page, website.externalApp) - - if output.find("1,None") > -1: - final_json = json.dumps( - {'status': 0, 'logstatus': 0, 'error_message': "Not able to fetch logs, see CyberPanel main log file!"}) - return HttpResponse(final_json) - - ## get log ends here. - - final_json = json.dumps({'status': 1, 'logstatus': 1, 'error_message': "None", "data": output}) - return HttpResponse(final_json) - - def getDataFromConfigFile(self, userID=None, data=None): - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - self.domain = data['virtualHost'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('configstatus', 0) - - command = 'cat %s' % ('/usr/local/lsws/conf/dvhost_redis.conf') - - if ProcessUtilities.outputExecutioner(command).find('127.0.0.1') == -1: - filePath = installUtilities.Server_root_path + "/conf/vhosts/" + self.domain + "/vhost.conf" - - command = 'cat ' + filePath - configData = ProcessUtilities.outputExecutioner(command, 'lsadm') - - if len(configData) == 0: - status = {'status': 0, "configstatus": 0, "error_message": "Configuration file is currently empty!"} - - final_json = json.dumps(status) - return HttpResponse(final_json) - - else: - command = 'redis-cli get "vhost:%s"' % (self.domain) - configData = ProcessUtilities.outputExecutioner(command) - configData = '#### This configuration is fetched from redis as Redis-Mass Hosting is being used.\n%s' % ( - configData) - - status = {'status': 1, "configstatus": 1, "configData": configData} - final_json = json.dumps(status) - return HttpResponse(final_json) - - def saveConfigsToFile(self, userID=None, data=None): - - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] != 1: - return ACLManager.loadErrorJson('configstatus', 0) - - configData = data['configData'] - self.domain = data['virtualHost'] - - if len(configData) == 0: - status = {"configstatus": 0, 'error_message': 'Error: you are trying to save empty vhost file, your website will stop working.'} - - final_json = json.dumps(status) - return HttpResponse(final_json) - - - command = 'cat %s' % ('/usr/local/lsws/conf/dvhost_redis.conf') - - if ProcessUtilities.outputExecutioner(command).find('127.0.0.1') == -1: - - mailUtilities.checkHome() - - tempPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - - vhost = open(tempPath, "w") - - vhost.write(configData) - - vhost.close() - - ## writing data temporary to file - - filePath = installUtilities.Server_root_path + "/conf/vhosts/" + self.domain + "/vhost.conf" - - ## save configuration data - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " saveVHostConfigs --path " + filePath + " --tempPath " + tempPath - - output = ProcessUtilities.outputExecutioner(execPath) - - if output.find("1,None") > -1: - status = {"configstatus": 1} - - final_json = json.dumps(status) - return HttpResponse(final_json) - else: - data_ret = {'configstatus': 0, 'error_message': output} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - ## save configuration data ends - else: - command = "redis-cli set vhost:%s '%s'" % (self.domain, configData.replace( - '#### This configuration is fetched from redis as Redis-Mass Hosting is being used.\n', '')) - ProcessUtilities.executioner(command) - - status = {"configstatus": 1} - - final_json = json.dumps(status) - return HttpResponse(final_json) - - def getRewriteRules(self, userID=None, data=None): - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - self.domain = data['virtualHost'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('rewriteStatus', 0) - - try: - childDom = ChildDomains.objects.get(domain=self.domain) - filePath = childDom.path + '/.htaccess' - externalApp = childDom.master.externalApp - except: - website = Websites.objects.get(domain=self.domain) - externalApp = website.externalApp - filePath = "/home/" + self.domain + "/public_html/.htaccess" - - try: - command = 'cat %s' % (filePath) - rewriteRules = ProcessUtilities.outputExecutioner(command, externalApp) - - if len(rewriteRules) == 0: - status = {"rewriteStatus": 1, "error_message": "Rules file is currently empty"} - final_json = json.dumps(status) - return HttpResponse(final_json) - - status = {"rewriteStatus": 1, "rewriteRules": rewriteRules} - - final_json = json.dumps(status) - return HttpResponse(final_json) - - except BaseException as msg: - status = {"rewriteStatus": 1, "error_message": str(msg), "rewriteRules": ""} - final_json = json.dumps(status) - return HttpResponse(final_json) - - def saveRewriteRules(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - self.domain = data['virtualHost'] - rewriteRules = data['rewriteRules'].encode('utf-8') - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('rewriteStatus', 0) - - ## writing data temporary to file - - mailUtilities.checkHome() - tempPath = "/tmp/" + str(randint(1000, 9999)) - vhost = open(tempPath, "wb") - vhost.write(rewriteRules) - vhost.close() - - ## writing data temporary to file - - try: - childDomain = ChildDomains.objects.get(domain=self.domain) - filePath = childDomain.path + '/.htaccess' - externalApp = childDomain.master.externalApp - except: - filePath = "/home/" + self.domain + "/public_html/.htaccess" - website = Websites.objects.get(domain=self.domain) - externalApp = website.externalApp - - ## save configuration data - - command = 'cp %s %s' % (tempPath, filePath) - ProcessUtilities.executioner(command, externalApp) - - command = 'rm -f %s' % (tempPath) - ProcessUtilities.executioner(command, 'cyberpanel') - - installUtilities.reStartLiteSpeedSocket() - status = {"rewriteStatus": 1, 'error_message': 'None'} - final_json = json.dumps(status) - return HttpResponse(final_json) - except BaseException as msg: - status = {"rewriteStatus": 0, 'error_message': str(msg)} - final_json = json.dumps(status) - return HttpResponse(final_json) - - def saveSSL(self, userID=None, data=None): - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - self.domain = data['virtualHost'] - key = data['key'] - cert = data['cert'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('sslStatus', 0) - - mailUtilities.checkHome() - - ## writing data temporary to file - - tempKeyPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - vhost = open(tempKeyPath, "w") - vhost.write(key) - vhost.close() - - tempCertPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - vhost = open(tempCertPath, "w") - vhost.write(cert) - vhost.close() - - ## writing data temporary to file - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " saveSSL --virtualHostName " + self.domain + " --tempKeyPath " + tempKeyPath + " --tempCertPath " + tempCertPath - output = ProcessUtilities.outputExecutioner(execPath) - - if output.find("1,None") > -1: - data_ret = {'sslStatus': 1, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - logging.CyberCPLogFileWriter.writeToFile( - output) - data_ret = {'sslStatus': 0, 'error_message': output} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def changePHP(self, userID=None, data=None): - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - self.domain = data['childDomain'] - phpVersion = data['phpSelection'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('changePHP', 0) - - confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + self.domain - completePathToConfigFile = confPath + "/vhost.conf" - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " changePHP --phpVersion '" + phpVersion + "' --path " + completePathToConfigFile - ProcessUtilities.popenExecutioner(execPath) - - try: - website = Websites.objects.get(domain=self.domain) - website.phpSelection = data['phpSelection'] - website.save() - - ### check if there are any alias domains under the main website and then change php for them too - - for alias in website.childdomains_set.filter(alais=1): - - try: - - confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + alias.domain - completePathToConfigFile = confPath + "/vhost.conf" - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " changePHP --phpVersion '" + phpVersion + "' --path " + completePathToConfigFile - ProcessUtilities.popenExecutioner(execPath) - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile(f'Error changing PHP for alias: {str(msg)}') - - - except: - website = ChildDomains.objects.get(domain=self.domain) - website.phpSelection = data['phpSelection'] - website.save() - - data_ret = {'status': 1, 'changePHP': 1, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - def getWebsiteCron(self, userID=None, data=None): try: From d1ab8bd29f95d55036b40f8ea1faae362baa9c63 Mon Sep 17 00:00:00 2001 From: usmannasir Date: Fri, 4 Apr 2025 14:49:48 +0500 Subject: [PATCH 003/273] add missing function --- websiteFunctions/website.py | 38 +++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/websiteFunctions/website.py b/websiteFunctions/website.py index e12624ed1..7b5f3402c 100755 --- a/websiteFunctions/website.py +++ b/websiteFunctions/website.py @@ -2213,6 +2213,44 @@ Require valid-user""" dic = {'getWebsiteCron': 0, 'error_message': str(msg)} json_data = json.dumps(dic) return HttpResponse(json_data) + + def fetchWebsitesList(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + pageNumber = int(data['page']) + recordsToShow = int(data['recordsToShow']) + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(f'Fetch sites step 1..') + + endPageNumber, finalPageNumber = self.recordsPointer(pageNumber, recordsToShow) + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(f'Fetch sites step 2..') + + websites = ACLManager.findWebsiteObjects(currentACL, userID) + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(f'Fetch sites step 3..') + + pagination = self.getPagination(len(websites), recordsToShow) + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(f'Fetch sites step 4..') + + json_data = self.findWebsitesListJson(websites[finalPageNumber:endPageNumber]) + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(f'Fetch sites step 5..') + + final_dic = {'status': 1, 'listWebSiteStatus': 1, 'error_message': "None", "data": json_data, + 'pagination': pagination} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + except BaseException as msg: + dic = {'status': 1, 'listWebSiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) def remCronbyLine(self, userID=None, data=None): try: From 867d5abea92b65c60d52ada90c7041dfc6e67b7f Mon Sep 17 00:00:00 2001 From: usmannasir Date: Fri, 4 Apr 2025 14:56:48 +0500 Subject: [PATCH 004/273] add missing function --- .../websiteFunctions/websiteFunctions.js | 5887 +---------------- websiteFunctions/urls.py | 2 - websiteFunctions/views.py | 19 +- websiteFunctions/website.py | 1570 ++++- 4 files changed, 1692 insertions(+), 5786 deletions(-) diff --git a/websiteFunctions/static/websiteFunctions/websiteFunctions.js b/websiteFunctions/static/websiteFunctions/websiteFunctions.js index 2476a370b..970f8dcd0 100755 --- a/websiteFunctions/static/websiteFunctions/websiteFunctions.js +++ b/websiteFunctions/static/websiteFunctions/websiteFunctions.js @@ -2455,6 +2455,7 @@ app.controller('createWebsite', function ($scope, $http, $timeout, $window) { mailDomain = 0 } + url = "/websites/submitWebsiteCreation"; var package = $scope.packageForWebsite; @@ -2634,16 +2635,14 @@ $("#listFail").hide(); app.controller('listWebsites', function ($scope, $http, $window) { - console.log('Initializing listWebsites controller'); $scope.web = {}; $scope.WebSitesList = []; - + $scope.currentPage = 1; $scope.recordsToShow = 10; // Initial fetch of websites $scope.getFurtherWebsitesFromDB = function () { - console.log('Fetching websites from DB'); var config = { headers: { 'X-CSRFToken': getCookie('csrftoken') @@ -2656,5581 +2655,17 @@ app.controller('listWebsites', function ($scope, $http, $window) { }; var dataurl = "/websites/fetchWebsitesList"; - console.log('Making request to:', dataurl); $http.post(dataurl, data, config).then(function(response) { - console.log('Received response:', response); if (response.data.listWebSiteStatus === 1) { - try { - $scope.WebSitesList = JSON.parse(response.data.data); - console.log('Parsed WebSitesList:', $scope.WebSitesList); - $scope.pagination = response.data.pagination; - $("#listFail").hide(); - } catch (e) { - console.error('Error parsing response data:', e); - $("#listFail").fadeIn(); - $scope.errorMessage = 'Error parsing server response'; - } - } else { - $("#listFail").fadeIn(); - $scope.errorMessage = response.data.error_message; - } - }).catch(function(error) { - console.error('Error fetching websites:', error); - $("#listFail").fadeIn(); - $scope.errorMessage = error.message || 'An error occurred while fetching websites'; - }); - }; - - // Call it immediately - $scope.getFurtherWebsitesFromDB(); - - $scope.showWPSites = function(index) { - console.log('showWPSites called with index:', index); - console.log('Current WebSitesList:', $scope.WebSitesList); - - $scope.selectedWebsite = $scope.WebSitesList[index]; - console.log('Selected website:', $scope.selectedWebsite); - - // Call the new GetWPSitesByDomain endpoint - var url = '/websites/GetWPSitesByDomain'; - var data = { - domain: $scope.selectedWebsite.domain - }; - - $http({ - method: 'POST', - url: url, - data: JSON.stringify(data), - headers: { - 'Content-Type': 'application/json', - 'X-CSRFToken': getCookie('csrftoken') - } - }).then(function(response) { - console.log('WP Sites Response:', response); - - if (response.data && response.data.status === 1) { - try { - // Display the data in an alert - var wpSites = response.data.data; - var alertMessage = 'WordPress Sites for ' + $scope.selectedWebsite.domain + ':\n\n'; - - wpSites.forEach(function(site, index) { - alertMessage += 'Site ' + (index + 1) + ':\n'; - alertMessage += 'Title: ' + site.title + '\n'; - alertMessage += 'URL: ' + site.url + '\n'; - alertMessage += 'Version: ' + site.version + '\n'; - alertMessage += 'PHP Version: ' + site.phpVersion + '\n'; - alertMessage += 'Active Plugins: ' + site.activePlugins + '\n'; - alertMessage += 'Theme: ' + site.theme + '\n'; - alertMessage += 'Debugging: ' + (site.debugging ? 'Enabled' : 'Disabled') + '\n'; - alertMessage += 'Search Index: ' + (site.searchIndex ? 'Enabled' : 'Disabled') + '\n'; - alertMessage += 'Maintenance Mode: ' + (site.maintenanceMode ? 'Enabled' : 'Disabled') + '\n'; - alertMessage += 'Password Protection: ' + (site.passwordProtection ? 'Enabled' : 'Disabled') + '\n\n'; - }); - - alert(alertMessage); - - // Update the UI with the data - $scope.selectedWebsite.wp_sites = wpSites; - $scope.selectedWebsite.showWPSites = true; - } catch (e) { - console.error('Error processing WordPress data:', e); - alert('Error processing WordPress data: ' + e.message); - $scope.selectedWebsite.showWPSites = false; - $scope.selectedWebsite.wp_sites = []; - } - } else { - console.error('Error fetching WordPress sites:', response.data.error_message); - alert('Error fetching WordPress sites: ' + response.data.error_message); - $scope.selectedWebsite.showWPSites = false; - $scope.selectedWebsite.wp_sites = []; - } - }, function(error) { - console.error('Error fetching WordPress sites:', error); - alert('Error fetching WordPress sites: ' + error.message); - $scope.selectedWebsite.showWPSites = false; - $scope.selectedWebsite.wp_sites = []; - }); - }; - - $scope.visitSite = function(url) { - window.open(url, '_blank'); - }; - - $scope.wpLogin = function(wpId) { - window.open('/websites/wpLogin?wpID=' + wpId, '_blank'); - }; - - $scope.manageWP = function(wpId) { - window.location.href = '/websites/listWPsites?wpID=' + wpId; - }; - - $scope.updateSetting = function(wp, setting) { - var settingMap = { - 'search-indexing': 'searchIndex', - 'debugging': 'debugging', - 'password-protection': 'passwordProtection', - 'maintenance-mode': 'maintenanceMode' - }; - - var data = { - wpID: wp.id, - setting: setting, - value: wp[settingMap[setting]] ? 'enable' : 'disable' - }; - - $http({ - method: 'POST', - url: '/websites/UpdateWPSettings', - data: data, - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', - 'X-CSRFToken': getCookie('csrftoken') - }, - transformRequest: function(obj) { - var str = []; - for(var p in obj) - str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); - return str.join("&"); - } - }).then(function(response) { - if (response.data.status === 1) { - new PNotify({ - title: 'Success', - text: 'Setting updated successfully.', - type: 'success' - }); - } else { - wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change - new PNotify({ - title: 'Error', - text: 'Failed to update setting.', - type: 'error' - }); - } - }).catch(function(error) { - wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change - new PNotify({ - title: 'Error', - text: 'Connection failed while updating setting.', - type: 'error' - }); - }); - }; - - $scope.cyberPanelLoading = true; - - $scope.issueSSL = function (virtualHost) { - $scope.cyberPanelLoading = false; - - var url = "/manageSSL/issueSSL"; - - - var data = { - virtualHost: virtualHost - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.cyberPanelLoading = true; - if (response.data.SSL === 1) { - new PNotify({ - title: 'Success!', - text: 'SSL successfully issued.', - type: 'success' - }); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - } - - } - - function cantLoadInitialDatas(response) { - $scope.cyberPanelLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: 'Could not connect to server, please refresh this page', - type: 'error' - }); - } - - - }; - - $scope.cyberPanelLoading = true; - - $scope.searchWebsites = function () { - - $scope.cyberPanelLoading = false; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - var data = { - patternAdded: $scope.patternAdded - }; - - dataurl = "/websites/searchWebsites"; - - $http.post(dataurl, data, config).then(ListInitialData, cantLoadInitialData); - - - function ListInitialData(response) { - $scope.cyberPanelLoading = true; - if (response.data.listWebSiteStatus === 1) { - - var finalData = JSON.parse(response.data.data); - $scope.WebSitesList = finalData; - $("#listFail").hide(); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - } - - function cantLoadInitialData(response) { - $scope.cyberPanelLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: 'Connect disrupted, refresh the page.', - type: 'error' - }); - } - - - }; - - $scope.ScanWordpressSite = function () { - - $('#cyberPanelLoading').show(); - - - var url = "/websites/ScanWordpressSite"; - - var data = {} - - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - $('#cyberPanelLoading').hide(); - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Successfully Saved!.', - type: 'success' - }); - location.reload(); - - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#cyberPanelLoading').hide(); - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - - } - - - }; - -}); - -app.controller('listChildDomainsMain', function ($scope, $http, $timeout) { - - $scope.currentPage = 1; - $scope.recordsToShow = 10; - - $scope.getFurtherWebsitesFromDB = function () { - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - var data = { - page: $scope.currentPage, - recordsToShow: $scope.recordsToShow - }; - - - dataurl = "/websites/fetchChildDomainsMain"; - - $http.post(dataurl, data, config).then(ListInitialData, cantLoadInitialData); - - - function ListInitialData(response) { - if (response.data.listWebSiteStatus === 1) { - $scope.WebSitesList = JSON.parse(response.data.data); $scope.pagination = response.data.pagination; - $scope.clients = JSON.parse(response.data.data); $("#listFail").hide(); } else { $("#listFail").fadeIn(); $scope.errorMessage = response.data.error_message; - - } - } - - function cantLoadInitialData(response) { - } - - - }; - $scope.getFurtherWebsitesFromDB(); - - $scope.cyberPanelLoading = true; - - $scope.issueSSL = function (virtualHost) { - $scope.cyberPanelLoading = false; - - var url = "/manageSSL/issueSSL"; - - - var data = { - virtualHost: virtualHost - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.cyberPanelLoading = true; - if (response.data.SSL === 1) { - new PNotify({ - title: 'Success!', - text: 'SSL successfully issued.', - type: 'success' - }); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - } - - } - - function cantLoadInitialDatas(response) { - $scope.cyberPanelLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: 'Could not connect to server, please refresh this page', - type: 'error' - }); - } - - - }; - - $scope.cyberPanelLoading = true; - - $scope.searchWebsites = function () { - - $scope.cyberPanelLoading = false; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - var data = { - patternAdded: $scope.patternAdded - }; - - dataurl = "/websites/searchChilds"; - - $http.post(dataurl, data, config).then(ListInitialData, cantLoadInitialData); - - - function ListInitialData(response) { - $scope.cyberPanelLoading = true; - if (response.data.listWebSiteStatus === 1) { - - var finalData = JSON.parse(response.data.data); - $scope.WebSitesList = finalData; - $("#listFail").hide(); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - } - - function cantLoadInitialData(response) { - $scope.cyberPanelLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: 'Connect disrupted, refresh the page.', - type: 'error' - }); - } - - - }; - - $scope.initConvert = function (virtualHost) { - $scope.domainName = virtualHost; - }; - - var statusFile; - - $scope.installationProgress = true; - - $scope.convert = function () { - - $scope.cyberPanelLoading = false; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.goBackDisable = true; - - $scope.currentStatus = "Starting creation.."; - - var ssl, dkimCheck, openBasedir; - - if ($scope.sslCheck === true) { - ssl = 1; - } else { - ssl = 0 - } - - if ($scope.dkimCheck === true) { - dkimCheck = 1; - } else { - dkimCheck = 0 - } - - if ($scope.openBasedir === true) { - openBasedir = 1; - } else { - openBasedir = 0 - } - - url = "/websites/convertDomainToSite"; - - - var data = { - package: $scope.packageForWebsite, - domainName: $scope.domainName, - adminEmail: $scope.adminEmail, - phpSelection: $scope.phpSelection, - websiteOwner: $scope.websiteOwner, - ssl: ssl, - dkimCheck: dkimCheck, - openBasedir: openBasedir - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.createWebSiteStatus === 1) { - statusFile = response.data.tempStatusPath; - getCreationStatus(); - } else { - - $scope.cyberPanelLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.goBackDisable = false; - - $scope.currentStatus = response.data.error_message; - } - - - } - - function cantLoadInitialDatas(response) { - - $scope.cyberPanelLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.goBackDisable = false; - - } - - - }; - $scope.goBack = function () { - $scope.cyberPanelLoading = true; - $scope.installationDetailsForm = false; - $scope.installationProgress = true; - $scope.goBackDisable = true; - $("#installProgress").css("width", "0%"); - }; - - function getCreationStatus() { - - url = "/websites/installWordpressStatus"; - - var data = { - statusFile: statusFile - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - - if (response.data.abort === 1) { - - if (response.data.installStatus === 1) { - - $scope.cyberPanelLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.goBackDisable = false; - - $("#installProgress").css("width", "100%"); - $scope.installPercentage = "100"; - $scope.currentStatus = response.data.currentStatus; - $timeout.cancel(); - - } else { - - $scope.cyberPanelLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.goBackDisable = false; - - $scope.currentStatus = response.data.error_message; - - $("#installProgress").css("width", "0%"); - $scope.installPercentage = "0"; - $scope.goBackDisable = false; - - } - - } else { - $("#installProgress").css("width", response.data.installationProgress + "%"); - $scope.installPercentage = response.data.installationProgress; - $scope.currentStatus = response.data.currentStatus; - $timeout(getCreationStatus, 1000); - } - - } - - function cantLoadInitialDatas(response) { - - $scope.cyberPanelLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.goBackDisable = false; - - } - - - } - - var DeleteDomain; - $scope.deleteDomainInit = function (childDomainForDeletion) { - DeleteDomain = childDomainForDeletion; - }; - - $scope.deleteChildDomain = function () { - $scope.cyberPanelLoading = false; - url = "/websites/submitDomainDeletion"; - - var data = { - websiteName: DeleteDomain, - DeleteDocRoot: $scope.DeleteDocRoot - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - function ListInitialDatas(response) { - $scope.cyberPanelLoading = true; - if (response.data.websiteDeleteStatus === 1) { - new PNotify({ - title: 'Success!', - text: 'Child Domain successfully deleted.', - type: 'success' - }); - $scope.getFurtherWebsitesFromDB(); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - } - } - - function cantLoadInitialDatas(response) { - $scope.cyberPanelLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: 'Could not connect to server, please refresh this page', - type: 'error' - }); - - } - - }; - -}); - -/* Java script code to list accounts ends here */ - - -/* Java script code to delete Website */ - - -$("#websiteDeleteFailure").hide(); -$("#websiteDeleteSuccess").hide(); - -$("#deleteWebsiteButton").hide(); -$("#deleteLoading").hide(); - -app.controller('deleteWebsiteControl', function ($scope, $http) { - - - $scope.deleteWebsite = function () { - - $("#deleteWebsiteButton").fadeIn(); - - - }; - - $scope.deleteWebsiteFinal = function () { - - $("#deleteLoading").show(); - - var websiteName = $scope.websiteToBeDeleted; - - - url = "/websites/submitWebsiteDeletion"; - - var data = { - websiteName: websiteName - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.websiteDeleteStatus === 0) { - $scope.errorMessage = response.data.error_message; - $("#websiteDeleteFailure").fadeIn(); - $("#websiteDeleteSuccess").hide(); - $("#deleteWebsiteButton").hide(); - - - $("#deleteLoading").hide(); - - } else { - $("#websiteDeleteFailure").hide(); - $("#websiteDeleteSuccess").fadeIn(); - $("#deleteWebsiteButton").hide(); - $scope.deletedWebsite = websiteName; - $("#deleteLoading").hide(); - - } - - - } - - function cantLoadInitialDatas(response) { - } - - - }; - -}); - - -/* Java script code to delete website ends here */ - - -/* Java script code to modify package ends here */ - -$("#canNotModify").hide(); -$("#webSiteDetailsToBeModified").hide(); -$("#websiteModifyFailure").hide(); -$("#websiteModifySuccess").hide(); -$("#websiteSuccessfullyModified").hide(); -$("#modifyWebsiteLoading").hide(); -$("#modifyWebsiteButton").hide(); - -app.controller('modifyWebsitesController', function ($scope, $http) { - - $scope.fetchWebsites = function () { - - $("#modifyWebsiteLoading").show(); - - - var websiteToBeModified = $scope.websiteToBeModified; - - url = "/websites/getWebsiteDetails"; - - var data = { - websiteToBeModified: websiteToBeModified, - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.modifyStatus === 0) { - console.log(response.data); - $scope.errorMessage = response.data.error_message; - $("#websiteModifyFailure").fadeIn(); - $("#websiteModifySuccess").hide(); - $("#modifyWebsiteButton").hide(); - $("#modifyWebsiteLoading").hide(); - $("#canNotModify").hide(); - - - } else { - console.log(response.data); - $("#modifyWebsiteButton").fadeIn(); - - $scope.adminEmail = response.data.adminEmail; - $scope.currentPack = response.data.current_pack; - $scope.webpacks = JSON.parse(response.data.packages); - $scope.adminNames = JSON.parse(response.data.adminNames); - $scope.currentAdmin = response.data.currentAdmin; - - $("#webSiteDetailsToBeModified").fadeIn(); - $("#websiteModifySuccess").fadeIn(); - $("#modifyWebsiteButton").fadeIn(); - $("#modifyWebsiteLoading").hide(); - $("#canNotModify").hide(); - - - } - - - } - - function cantLoadInitialDatas(response) { - $("#websiteModifyFailure").fadeIn(); - } - - }; - - - $scope.modifyWebsiteFunc = function () { - - var domain = $scope.websiteToBeModified; - var packForWeb = $scope.selectedPack; - var email = $scope.adminEmail; - var phpVersion = $scope.phpSelection; - var admin = $scope.selectedAdmin; - - - $("#websiteModifyFailure").hide(); - $("#websiteModifySuccess").hide(); - $("#websiteSuccessfullyModified").hide(); - $("#canNotModify").hide(); - $("#modifyWebsiteLoading").fadeIn(); - - - url = "/websites/saveWebsiteChanges"; - - var data = { - domain: domain, - packForWeb: packForWeb, - email: email, - phpVersion: phpVersion, - admin: admin - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.saveStatus === 0) { - $scope.errMessage = response.data.error_message; - - $("#canNotModify").fadeIn(); - $("#websiteModifyFailure").hide(); - $("#websiteModifySuccess").hide(); - $("#websiteSuccessfullyModified").hide(); - $("#modifyWebsiteLoading").hide(); - - - } else { - $("#modifyWebsiteButton").hide(); - $("#canNotModify").hide(); - $("#websiteModifyFailure").hide(); - $("#websiteModifySuccess").hide(); - - $("#websiteSuccessfullyModified").fadeIn(); - $("#modifyWebsiteLoading").hide(); - - $scope.websiteModified = domain; - - - } - - - } - - function cantLoadInitialDatas(response) { - $scope.errMessage = response.data.error_message; - $("#canNotModify").fadeIn(); - } - - - }; - -}); - -/* Java script code to Modify Pacakge ends here */ - - -/* Java script code to create account */ -var website_child_domain_check = 0; - -function website_child_domain_checkbox_function() { - - var checkBox = document.getElementById("myCheck"); - // Get the output text - - - // If the checkbox is checked, display the output text - if (checkBox.checked == true) { - website_child_domain_check = 0; - document.getElementById('Website_Create_Test_Domain').style.display = "block"; - document.getElementById('Website_Create_Own_Domain').style.display = "none"; - - } else { - document.getElementById('Website_Create_Test_Domain').style.display = "none"; - document.getElementById('Website_Create_Own_Domain').style.display = "block"; - website_child_domain_check = 1; - } - - // alert(domain_check); -} - -app.controller('websitePages', function ($scope, $http, $timeout, $window) { - - $scope.logFileLoading = true; - $scope.logsFeteched = true; - $scope.couldNotFetchLogs = true; - $scope.couldNotConnect = true; - $scope.fetchedData = true; - $scope.hideLogs = true; - $scope.hideErrorLogs = true; - - $scope.hidelogsbtn = function () { - $scope.hideLogs = true; - }; - - $scope.hideErrorLogsbtn = function () { - $scope.hideLogs = true; - }; - - $scope.fileManagerURL = "/filemanager/" + $("#domainNamePage").text(); - $scope.wordPressInstallURL = $("#domainNamePage").text() + "/wordpressInstall"; - $scope.joomlaInstallURL = $("#domainNamePage").text() + "/joomlaInstall"; - $scope.setupGit = $("#domainNamePage").text() + "/setupGit"; - $scope.installPrestaURL = $("#domainNamePage").text() + "/installPrestaShop"; - $scope.installMagentoURL = $("#domainNamePage").text() + "/installMagento"; - $scope.installMauticURL = $("#domainNamePage").text() + "/installMautic"; - $scope.domainAliasURL = "/websites/" + $("#domainNamePage").text() + "/domainAlias"; - $scope.previewUrl = "/preview/" + $("#domainNamePage").text() + "/"; - - var logType = 0; - $scope.pageNumber = 1; - - $scope.fetchLogs = function (type) { - - var pageNumber = $scope.pageNumber; - - - if (type == 3) { - pageNumber = $scope.pageNumber + 1; - $scope.pageNumber = pageNumber; - } else if (type == 4) { - pageNumber = $scope.pageNumber - 1; - $scope.pageNumber = pageNumber; - } else { - logType = type; - } - - - $scope.logFileLoading = false; - $scope.logsFeteched = true; - $scope.couldNotFetchLogs = true; - $scope.couldNotConnect = true; - $scope.fetchedData = false; - $scope.hideErrorLogs = true; - - - url = "/websites/getDataFromLogFile"; - - var domainNamePage = $("#domainNamePage").text(); - - - var data = { - logType: logType, - virtualHost: domainNamePage, - page: pageNumber, - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.logstatus == 1) { - - - $scope.logFileLoading = true; - $scope.logsFeteched = false; - $scope.couldNotFetchLogs = true; - $scope.couldNotConnect = true; - $scope.fetchedData = false; - $scope.hideLogs = false; - - - $scope.records = JSON.parse(response.data.data); - - } else { - - $scope.logFileLoading = true; - $scope.logsFeteched = true; - $scope.couldNotFetchLogs = false; - $scope.couldNotConnect = true; - $scope.fetchedData = true; - $scope.hideLogs = false; - - - $scope.errorMessage = response.data.error_message; - console.log(domainNamePage) - - } - - - } - - function cantLoadInitialDatas(response) { - - $scope.logFileLoading = true; - $scope.logsFeteched = true; - $scope.couldNotFetchLogs = true; - $scope.couldNotConnect = false; - $scope.fetchedData = true; - $scope.hideLogs = false; - - } - - - }; - - $scope.errorPageNumber = 1; - - - $scope.fetchErrorLogs = function (type) { - - var errorPageNumber = $scope.errorPageNumber; - - - if (type == 3) { - errorPageNumber = $scope.errorPageNumber + 1; - $scope.errorPageNumber = errorPageNumber; - } else if (type == 4) { - errorPageNumber = $scope.errorPageNumber - 1; - $scope.errorPageNumber = errorPageNumber; - } else { - logType = type; - } - - // notifications - - $scope.logFileLoading = false; - $scope.logsFeteched = true; - $scope.couldNotFetchLogs = true; - $scope.couldNotConnect = true; - $scope.fetchedData = true; - $scope.hideErrorLogs = true; - $scope.hideLogs = false; - - - url = "/websites/fetchErrorLogs"; - - var domainNamePage = $("#domainNamePage").text(); - - - var data = { - virtualHost: domainNamePage, - page: errorPageNumber, - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.logstatus === 1) { - - - // notifications - - $scope.logFileLoading = true; - $scope.logsFeteched = false; - $scope.couldNotFetchLogs = true; - $scope.couldNotConnect = true; - $scope.fetchedData = true; - $scope.hideLogs = false; - $scope.hideErrorLogs = false; - - - $scope.errorLogsData = response.data.data; - - } else { - - // notifications - - $scope.logFileLoading = true; - $scope.logsFeteched = true; - $scope.couldNotFetchLogs = false; - $scope.couldNotConnect = true; - $scope.fetchedData = true; - $scope.hideLogs = true; - $scope.hideErrorLogs = true; - - - $scope.errorMessage = response.data.error_message; - - } - - - } - - function cantLoadInitialDatas(response) { - - // notifications - - $scope.logFileLoading = true; - $scope.logsFeteched = true; - $scope.couldNotFetchLogs = true; - $scope.couldNotConnect = false; - $scope.fetchedData = true; - $scope.hideLogs = true; - $scope.hideErrorLogs = true; - - } - - - }; - - ///////// Configurations Part - - $scope.configurationsBox = true; - $scope.configsFetched = true; - $scope.couldNotFetchConfigs = true; - $scope.couldNotConnect = true; - $scope.fetchedConfigsData = true; - $scope.configFileLoading = true; - $scope.configSaved = true; - $scope.couldNotSaveConfigurations = true; - - $scope.hideconfigbtn = function () { - - $scope.configurationsBox = true; - }; - - $scope.fetchConfigurations = function () { - - - $scope.hidsslconfigs = true; - $scope.configurationsBoxRewrite = true; - $scope.changePHPView = true; - - - //Rewrite rules - $scope.configurationsBoxRewrite = true; - $scope.rewriteRulesFetched = true; - $scope.couldNotFetchRewriteRules = true; - $scope.rewriteRulesSaved = true; - $scope.couldNotSaveRewriteRules = true; - $scope.fetchedRewriteRules = true; - $scope.saveRewriteRulesBTN = true; - - /// - - $scope.configFileLoading = false; - - - url = "/websites/getDataFromConfigFile"; - - var virtualHost = $("#domainNamePage").text(); - - - var data = { - virtualHost: virtualHost, - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.configstatus === 1) { - - //Rewrite rules - - $scope.configurationsBoxRewrite = true; - $scope.rewriteRulesFetched = true; - $scope.couldNotFetchRewriteRules = true; - $scope.rewriteRulesSaved = true; - $scope.couldNotSaveRewriteRules = true; - $scope.fetchedRewriteRules = true; - $scope.saveRewriteRulesBTN = true; - - /// - - $scope.configurationsBox = false; - $scope.configsFetched = false; - $scope.couldNotFetchConfigs = true; - $scope.couldNotConnect = true; - $scope.fetchedConfigsData = false; - $scope.configFileLoading = true; - $scope.configSaved = true; - $scope.couldNotSaveConfigurations = true; - $scope.saveConfigBtn = false; - - - $scope.configData = response.data.configData; - - } else { - - //Rewrite rules - $scope.configurationsBoxRewrite = true; - $scope.rewriteRulesFetched = true; - $scope.couldNotFetchRewriteRules = true; - $scope.rewriteRulesSaved = true; - $scope.couldNotSaveRewriteRules = true; - $scope.fetchedRewriteRules = true; - $scope.saveRewriteRulesBTN = true; - - /// - $scope.configurationsBox = false; - $scope.configsFetched = true; - $scope.couldNotFetchConfigs = false; - $scope.couldNotConnect = true; - $scope.fetchedConfigsData = true; - $scope.configFileLoading = true; - $scope.configSaved = true; - $scope.couldNotSaveConfigurations = true; - - - $scope.errorMessage = response.data.error_message; - - } - - - } - - function cantLoadInitialDatas(response) { - - //Rewrite rules - $scope.configurationsBoxRewrite = true; - $scope.rewriteRulesFetched = true; - $scope.couldNotFetchRewriteRules = true; - $scope.rewriteRulesSaved = true; - $scope.couldNotSaveRewriteRules = true; - $scope.fetchedRewriteRules = true; - $scope.saveRewriteRulesBTN = true; - /// - - $scope.configurationsBox = false; - $scope.configsFetched = true; - $scope.couldNotFetchConfigs = true; - $scope.couldNotConnect = false; - $scope.fetchedConfigsData = true; - $scope.configFileLoading = true; - $scope.configSaved = true; - $scope.couldNotSaveConfigurations = true; - - - } - - - }; - - $scope.saveCongiruations = function () { - - $scope.configFileLoading = false; - - - url = "/websites/saveConfigsToFile"; - - var virtualHost = $("#domainNamePage").text(); - var configData = $scope.configData; - - - var data = { - virtualHost: virtualHost, - configData: configData, - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.configstatus === 1) { - - $scope.configurationsBox = false; - $scope.configsFetched = true; - $scope.couldNotFetchConfigs = true; - $scope.couldNotConnect = true; - $scope.fetchedConfigsData = true; - $scope.configFileLoading = true; - $scope.configSaved = false; - $scope.couldNotSaveConfigurations = true; - $scope.saveConfigBtn = true; - - - } else { - $scope.configurationsBox = false; - $scope.configsFetched = true; - $scope.couldNotFetchConfigs = true; - $scope.couldNotConnect = true; - $scope.fetchedConfigsData = false; - $scope.configFileLoading = true; - $scope.configSaved = true; - $scope.couldNotSaveConfigurations = false; - - - $scope.errorMessage = response.data.error_message; - - } - - - } - - function cantLoadInitialDatas(response) { - - $scope.configurationsBox = false; - $scope.configsFetched = true; - $scope.couldNotFetchConfigs = true; - $scope.couldNotConnect = false; - $scope.fetchedConfigsData = true; - $scope.configFileLoading = true; - $scope.configSaved = true; - $scope.couldNotSaveConfigurations = true; - - - } - - - }; - - - ///////// Rewrite Rules - - $scope.configurationsBoxRewrite = true; - $scope.rewriteRulesFetched = true; - $scope.couldNotFetchRewriteRules = true; - $scope.rewriteRulesSaved = true; - $scope.couldNotSaveRewriteRules = true; - $scope.fetchedRewriteRules = true; - $scope.saveRewriteRulesBTN = true; - - $scope.hideRewriteRulesbtn = function () { - $scope.configurationsBoxRewrite = true; - }; - - $scope.fetchRewriteFules = function () { - - $scope.hidsslconfigs = true; - $scope.configurationsBox = true; - $scope.changePHPView = true; - - - $scope.configurationsBox = true; - $scope.configsFetched = true; - $scope.couldNotFetchConfigs = true; - $scope.couldNotConnect = true; - $scope.fetchedConfigsData = true; - $scope.configFileLoading = true; - $scope.configSaved = true; - $scope.couldNotSaveConfigurations = true; - $scope.saveConfigBtn = true; - - $scope.configFileLoading = false; - - - url = "/websites/getRewriteRules"; - - var virtualHost = $("#domainNamePage").text(); - - - var data = { - virtualHost: virtualHost, - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.rewriteStatus == 1) { - - - // from main - - $scope.configurationsBox = true; - $scope.configsFetched = true; - $scope.couldNotFetchConfigs = true; - $scope.fetchedConfigsData = true; - $scope.configSaved = true; - $scope.couldNotSaveConfigurations = true; - $scope.saveConfigBtn = true; - - // main ends - - $scope.configFileLoading = true; - - // - - - $scope.configurationsBoxRewrite = false; - $scope.rewriteRulesFetched = false; - $scope.couldNotFetchRewriteRules = true; - $scope.rewriteRulesSaved = true; - $scope.couldNotSaveRewriteRules = true; - $scope.fetchedRewriteRules = false; - $scope.saveRewriteRulesBTN = false; - $scope.couldNotConnect = true; - - - $scope.rewriteRules = response.data.rewriteRules; - - } else { - // from main - $scope.configurationsBox = true; - $scope.configsFetched = true; - $scope.couldNotFetchConfigs = true; - $scope.fetchedConfigsData = true; - $scope.configFileLoading = true; - $scope.configSaved = true; - $scope.couldNotSaveConfigurations = true; - $scope.saveConfigBtn = true; - // from main - - $scope.configFileLoading = true; - - /// - - $scope.configurationsBoxRewrite = true; - $scope.rewriteRulesFetched = true; - $scope.couldNotFetchRewriteRules = false; - $scope.rewriteRulesSaved = true; - $scope.couldNotSaveRewriteRules = true; - $scope.fetchedRewriteRules = true; - $scope.saveRewriteRulesBTN = true; - $scope.couldNotConnect = true; - - - $scope.errorMessage = response.data.error_message; - - } - - - } - - function cantLoadInitialDatas(response) { - // from main - - $scope.configurationsBox = true; - $scope.configsFetched = true; - $scope.couldNotFetchConfigs = true; - $scope.fetchedConfigsData = true; - $scope.configFileLoading = true; - $scope.configSaved = true; - $scope.couldNotSaveConfigurations = true; - $scope.saveConfigBtn = true; - - // from main - - $scope.configFileLoading = true; - - /// - - $scope.configurationsBoxRewrite = true; - $scope.rewriteRulesFetched = true; - $scope.couldNotFetchRewriteRules = true; - $scope.rewriteRulesSaved = true; - $scope.couldNotSaveRewriteRules = true; - $scope.fetchedRewriteRules = true; - $scope.saveRewriteRulesBTN = true; - - $scope.couldNotConnect = false; - - - } - - - }; - - $scope.saveRewriteRules = function () { - - $scope.configFileLoading = false; - - - url = "/websites/saveRewriteRules"; - - var virtualHost = $("#domainNamePage").text(); - var rewriteRules = $scope.rewriteRules; - - - var data = { - virtualHost: virtualHost, - rewriteRules: rewriteRules, - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.rewriteStatus == 1) { - - $scope.configurationsBoxRewrite = false; - $scope.rewriteRulesFetched = true; - $scope.couldNotFetchRewriteRules = true; - $scope.rewriteRulesSaved = false; - $scope.couldNotSaveRewriteRules = true; - $scope.fetchedRewriteRules = true; - $scope.saveRewriteRulesBTN = true; - $scope.configFileLoading = true; - - - } else { - $scope.configurationsBoxRewrite = false; - $scope.rewriteRulesFetched = false; - $scope.couldNotFetchRewriteRules = true; - $scope.rewriteRulesSaved = true; - $scope.couldNotSaveRewriteRules = false; - $scope.fetchedRewriteRules = true; - $scope.saveRewriteRulesBTN = false; - - $scope.configFileLoading = true; - - - $scope.errorMessage = response.data.error_message; - - } - - - } - - function cantLoadInitialDatas(response) { - - $scope.configurationsBoxRewrite = false; - $scope.rewriteRulesFetched = false; - $scope.couldNotFetchRewriteRules = true; - $scope.rewriteRulesSaved = true; - $scope.couldNotSaveRewriteRules = true; - $scope.fetchedRewriteRules = true; - $scope.saveRewriteRulesBTN = false; - - $scope.configFileLoading = true; - - $scope.couldNotConnect = false; - - - } - - - }; - - //////// Application Installation part - - $scope.installationDetailsForm = true; - $scope.installationDetailsFormJoomla = true; - $scope.applicationInstallerLoading = true; - $scope.installationFailed = true; - $scope.installationSuccessfull = true; - $scope.couldNotConnect = true; - - - $scope.installationDetails = function () { - - $scope.installationDetailsForm = !$scope.installationDetailsForm; - $scope.installationDetailsFormJoomla = true; - - }; - - $scope.installationDetailsJoomla = function () { - - $scope.installationDetailsFormJoomla = !$scope.installationDetailsFormJoomla; - $scope.installationDetailsForm = true; - - }; - - $scope.installWordpress = function () { - - - $scope.installationDetailsForm = false; - $scope.applicationInstallerLoading = false; - $scope.installationFailed = true; - $scope.installationSuccessfull = true; - $scope.couldNotConnect = true; - - var domain = $("#domainNamePage").text(); - var path = $scope.installPath; - - url = "/websites/installWordpress"; - - var home = "1"; - - if (typeof path != 'undefined') { - home = "0"; - } - - - var data = { - domain: domain, - home: home, - path: path, - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.installStatus === 1) { - if (typeof path != 'undefined') { - $scope.installationURL = "http://" + domain + "/" + path; - } else { - $scope.installationURL = domain; - } - - $scope.installationDetailsForm = false; - $scope.applicationInstallerLoading = true; - $scope.installationFailed = true; - $scope.installationSuccessfull = false; - $scope.couldNotConnect = true; - - } else { - - $scope.installationDetailsForm = false; - $scope.applicationInstallerLoading = true; - $scope.installationFailed = false; - $scope.installationSuccessfull = true; - $scope.couldNotConnect = true; - - $scope.errorMessage = response.data.error_message; - - } - - - } - - function cantLoadInitialDatas(response) { - - $scope.installationDetailsForm = false; - $scope.applicationInstallerLoading = true; - $scope.installationFailed = true; - $scope.installationSuccessfull = true; - $scope.couldNotConnect = false; - - } - - }; - - $scope.installJoomla = function () { - - - $scope.installationDetailsFormJoomla = false; - $scope.applicationInstallerLoading = false; - $scope.installationFailed = true; - $scope.installationSuccessfull = true; - $scope.couldNotConnect = true; - - var domain = $("#domainNamePage").text(); - var path = $scope.installPath; - var username = 'admin'; - var password = $scope.password; - var prefix = $scope.prefix; - - - url = "/websites/installJoomla"; - - var home = "1"; - - if (typeof path != 'undefined') { - home = "0"; - } - - - var data = { - domain: domain, - siteName: $scope.siteName, - home: home, - path: path, - password: password, - prefix: prefix, - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.installStatus === 1) { - if (typeof path != 'undefined') { - $scope.installationURL = "http://" + domain + "/" + path; - } else { - $scope.installationURL = domain; - } - - $scope.installationDetailsFormJoomla = false; - $scope.applicationInstallerLoading = true; - $scope.installationFailed = true; - $scope.installationSuccessfull = false; - $scope.couldNotConnect = true; - - } else { - - $scope.installationDetailsFormJoomla = false; - $scope.applicationInstallerLoading = true; - $scope.installationFailed = false; - $scope.installationSuccessfull = true; - $scope.couldNotConnect = true; - - $scope.errorMessage = response.data.error_message; - - } - - - } - - function cantLoadInitialDatas(response) { - - $scope.installationDetailsFormJoomla = false; - $scope.applicationInstallerLoading = true; - $scope.installationFailed = true; - $scope.installationSuccessfull = true; - $scope.couldNotConnect = false; - - } - - }; - - - //////// SSL Part - - $scope.sslSaved = true; - $scope.couldNotSaveSSL = true; - $scope.hidsslconfigs = true; - $scope.couldNotConnect = true; - - - $scope.hidesslbtn = function () { - $scope.hidsslconfigs = true; - }; - - $scope.addSSL = function () { - $scope.hidsslconfigs = false; - $scope.configurationsBox = true; - $scope.configurationsBoxRewrite = true; - $scope.changePHPView = true; - }; - - $scope.saveSSL = function () { - - - $scope.configFileLoading = false; - - url = "/websites/saveSSL"; - - var virtualHost = $("#domainNamePage").text(); - var cert = $scope.cert; - var key = $scope.key; - - - var data = { - virtualHost: virtualHost, - cert: cert, - key: key - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.sslStatus === 1) { - - $scope.sslSaved = false; - $scope.couldNotSaveSSL = true; - $scope.couldNotConnect = true; - $scope.configFileLoading = true; - - - } else { - - $scope.sslSaved = true; - $scope.couldNotSaveSSL = false; - $scope.couldNotConnect = true; - $scope.configFileLoading = true; - - $scope.errorMessage = response.data.error_message; - - } - - - } - - function cantLoadInitialDatas(response) { - - $scope.sslSaved = true; - $scope.couldNotSaveSSL = true; - $scope.couldNotConnect = false; - $scope.configFileLoading = true; - - - } - - }; - - //// Change PHP Master - - $scope.failedToChangePHPMaster = true; - $scope.phpChangedMaster = true; - $scope.couldNotConnect = true; - - $scope.changePHPView = true; - - - $scope.hideChangePHPMaster = function () { - $scope.changePHPView = true; - }; - - $scope.changePHPMaster = function () { - $scope.hidsslconfigs = true; - $scope.configurationsBox = true; - $scope.configurationsBoxRewrite = true; - $scope.changePHPView = false; - }; - - $scope.changePHPVersionMaster = function (childDomain, phpSelection) { - - // notifcations - - $scope.configFileLoading = false; - - var url = "/websites/changePHP"; - - var data = { - childDomain: $("#domainNamePage").text(), - phpSelection: $scope.phpSelectionMaster, - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - - if (response.data.changePHP === 1) { - - $scope.configFileLoading = true; - $scope.websiteDomain = $("#domainNamePage").text(); - - - // notifcations - - $scope.failedToChangePHPMaster = true; - $scope.phpChangedMaster = false; - $scope.couldNotConnect = true; - - - } else { - - $scope.configFileLoading = true; - $scope.errorMessage = response.data.error_message; - - // notifcations - - $scope.failedToChangePHPMaster = false; - $scope.phpChangedMaster = true; - $scope.couldNotConnect = true; - - } - - - } - - function cantLoadInitialDatas(response) { - - $scope.configFileLoading = true; - - // notifcations - - $scope.failedToChangePHPMaster = true; - $scope.phpChangedMaster = true; - $scope.couldNotConnect = false; - - } - - }; - - ////// create domain part - - $("#domainCreationForm").hide(); - - $scope.showCreateDomainForm = function () { - $("#domainCreationForm").fadeIn(); - }; - - $scope.hideDomainCreationForm = function () { - $("#domainCreationForm").fadeOut(); - }; - - $scope.masterDomain = $("#domainNamePage").text(); - - // notifcations settings - $scope.domainLoading = true; - $scope.installationDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - $scope.DomainCreateForm = true; - - var statusFile; - - - $scope.webselection = true; - $scope.WebsiteType = function () { - var type = $scope.websitetype; - if (type == 'Sub Domain') { - $scope.webselection = false; - $scope.DomainCreateForm = true; - - } else if (type == 'Addon Domain') { - $scope.DomainCreateForm = false; - $scope.webselection = true; - $scope.masterDomain = $('#defaultSite').html() - } - }; - - $scope.WebsiteSelection = function () { - $scope.DomainCreateForm = false; - }; - - $scope.createDomain = function () { - - $scope.domainLoading = false; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - $scope.currentStatus = "Starting creation.."; - $scope.DomainCreateForm = true; - - var ssl, dkimCheck, openBasedir, apacheBackend; - - if ($scope.sslCheck === true) { - ssl = 1; - } else { - ssl = 0 - } - - if ($scope.dkimCheck === true) { - dkimCheck = 1; - } else { - dkimCheck = 0 - } - - if ($scope.openBasedir === true) { - openBasedir = 1; - } else { - openBasedir = 0 - } - - - if ($scope.apacheBackend === true) { - apacheBackend = 1; - } else { - apacheBackend = 0 - } - - - url = "/websites/submitDomainCreation"; - var domainName = $scope.domainNameCreate; - var phpSelection = $scope.phpSelection; - - var path = $scope.docRootPath; - - if (typeof path === 'undefined') { - path = ""; - } - var package = $scope.packageForWebsite; - - // if (website_child_domain_check == 0) { - // var Part2_domainNameCreate = document.getElementById('Part2_domainNameCreate').value; - // var domainName = document.getElementById('TestDomainNameCreate').value + Part2_domainNameCreate; - // } - // if (website_child_domain_check == 1) { - // - // var domainName = $scope.own_domainNameCreate; - // } - var type = $scope.websitetype; - - var domainName = $scope.domainNameCreate; - - - var data = { - domainName: domainName, - phpSelection: phpSelection, - ssl: ssl, - path: path, - masterDomain: $scope.masterDomain, - dkimCheck: dkimCheck, - openBasedir: openBasedir, - apacheBackend: apacheBackend - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - // console.log(data) - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.createWebSiteStatus === 1) { - statusFile = response.data.tempStatusPath; - getCreationStatus(); - } else { - - $scope.domainLoading = true; - $scope.installationDetailsForm = true; - $scope.DomainCreateForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = false; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $scope.errorMessage = response.data.error_message; - } - - - } - - function cantLoadInitialDatas(response) { - - $scope.domainLoading = true; - $scope.installationDetailsForm = true; - $scope.DomainCreateForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - }; - - $scope.goBack = function () { - $scope.domainLoading = true; - $scope.installationDetailsForm = false; - $scope.DomainCreateForm = true; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - $scope.DomainCreateForm = true; - $("#installProgress").css("width", "0%"); - }; - - function getCreationStatus() { - - url = "/websites/installWordpressStatus"; - - var data = { - statusFile: statusFile - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - - if (response.data.abort === 1) { - - if (response.data.installStatus === 1) { - - $scope.domainLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = false; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $("#installProgress").css("width", "100%"); - $scope.installPercentage = "100"; - $scope.currentStatus = response.data.currentStatus; - $timeout.cancel(); - - } else { - - $scope.domainLoading = true; - $scope.installationDetailsForm = true; - $scope.DomainCreateForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = false; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $scope.errorMessage = response.data.error_message; - - $("#installProgress").css("width", "0%"); - $scope.installPercentage = "0"; - $scope.goBackDisable = false; - - } - - } else { - $("#installProgress").css("width", response.data.installationProgress + "%"); - $scope.installPercentage = response.data.installationProgress; - $scope.currentStatus = response.data.currentStatus; - $timeout(getCreationStatus, 1000); - } - - } - - function cantLoadInitialDatas(response) { - - $scope.domainLoading = true; - $scope.installationDetailsForm = true; - $scope.DomainCreateForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - } - - - ////// List Domains Part - - //////////////////////// - - // notifcations - - $scope.phpChanged = true; - $scope.domainError = true; - $scope.couldNotConnect = true; - $scope.domainDeleted = true; - $scope.sslIssued = true; - $scope.childBaseDirChanged = true; - - $("#listDomains").hide(); - - - $scope.showListDomains = function () { - fetchDomains(); - $("#listDomains").fadeIn(); - }; - - $scope.hideListDomains = function () { - $("#listDomains").fadeOut(); - }; - - function fetchDomains() { - $scope.domainLoading = false; - - var url = "/websites/fetchDomains"; - - var data = { - masterDomain: $("#domainNamePage").text(), - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - - if (response.data.fetchStatus === 1) { - - $scope.childDomains = JSON.parse(response.data.data); - $scope.domainLoading = true; - - - } else { - $scope.domainError = false; - $scope.errorMessage = response.data.error_message; - $scope.domainLoading = true; - } - - - } - - function cantLoadInitialDatas(response) { - - $scope.couldNotConnect = false; - - } - - } - - $scope.changePHP = function (childDomain, phpSelection) { - - // notifcations - - $scope.phpChanged = true; - $scope.domainError = true; - $scope.couldNotConnect = true; - $scope.domainDeleted = true; - $scope.sslIssued = true; - $scope.domainLoading = false; - $scope.childBaseDirChanged = true; - - var url = "/websites/changePHP"; - - var data = { - childDomain: childDomain, - phpSelection: phpSelection, - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - - if (response.data.changePHP === 1) { - - $scope.domainLoading = true; - - $scope.changedPHPVersion = phpSelection; - - - // notifcations - - $scope.phpChanged = false; - $scope.domainError = true; - $scope.couldNotConnect = true; - $scope.domainDeleted = true; - $scope.sslIssued = true; - $scope.childBaseDirChanged = true; - - - } else { - $scope.errorMessage = response.data.error_message; - $scope.domainLoading = true; - - // notifcations - - $scope.phpChanged = true; - $scope.domainError = false; - $scope.couldNotConnect = true; - $scope.domainDeleted = true; - $scope.sslIssued = true; - $scope.childBaseDirChanged = true; - } - - - } - - function cantLoadInitialDatas(response) { - - $scope.domainLoading = true; - - // notifcations - - $scope.phpChanged = true; - $scope.domainError = false; - $scope.couldNotConnect = true; - $scope.domainDeleted = true; - $scope.sslIssued = true; - $scope.childBaseDirChanged = true; - - } - - }; - - $scope.changeChildBaseDir = function (childDomain, openBasedirValue) { - - // notifcations - - $scope.phpChanged = true; - $scope.domainError = true; - $scope.couldNotConnect = true; - $scope.domainDeleted = true; - $scope.sslIssued = true; - $scope.domainLoading = false; - $scope.childBaseDirChanged = true; - - - var url = "/websites/changeOpenBasedir"; - - var data = { - domainName: childDomain, - openBasedirValue: openBasedirValue - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - - if (response.data.changeOpenBasedir === 1) { - - $scope.phpChanged = true; - $scope.domainError = true; - $scope.couldNotConnect = true; - $scope.domainDeleted = true; - $scope.sslIssued = true; - $scope.domainLoading = true; - $scope.childBaseDirChanged = false; - - } else { - - $scope.phpChanged = true; - $scope.domainError = false; - $scope.couldNotConnect = true; - $scope.domainDeleted = true; - $scope.sslIssued = true; - $scope.domainLoading = true; - $scope.childBaseDirChanged = true; - - $scope.errorMessage = response.data.error_message; - - } - - - } - - function cantLoadInitialDatas(response) { - - $scope.phpChanged = true; - $scope.domainError = true; - $scope.couldNotConnect = false; - $scope.domainDeleted = true; - $scope.sslIssued = true; - $scope.domainLoading = true; - $scope.childBaseDirChanged = true; - - - } - - } - - $scope.deleteChildDomain = function (childDomain) { - $scope.domainLoading = false; - - // notifcations - - $scope.phpChanged = true; - $scope.domainError = true; - $scope.couldNotConnect = true; - $scope.domainDeleted = true; - $scope.sslIssued = true; - - url = "/websites/submitDomainDeletion"; - - var data = { - websiteName: childDomain, - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - - if (response.data.websiteDeleteStatus === 1) { - - $scope.domainLoading = true; - $scope.deletedDomain = childDomain; - - fetchDomains(); - - - // notifications - - $scope.phpChanged = true; - $scope.domainError = true; - $scope.couldNotConnect = true; - $scope.domainDeleted = false; - $scope.sslIssued = true; - - - } else { - $scope.errorMessage = response.data.error_message; - $scope.domainLoading = true; - - // notifcations - - $scope.phpChanged = true; - $scope.domainError = false; - $scope.couldNotConnect = true; - $scope.domainDeleted = true; - $scope.sslIssued = true; - } - - - } - - function cantLoadInitialDatas(response) { - - $scope.domainLoading = true; - - // notifcations - - $scope.phpChanged = true; - $scope.domainError = true; - $scope.couldNotConnect = false; - $scope.domainDeleted = true; - $scope.sslIssued = true; - - } - - }; - - $scope.issueSSL = function (childDomain, path) { - $scope.domainLoading = false; - - // notifcations - - $scope.phpChanged = true; - $scope.domainError = true; - $scope.couldNotConnect = true; - $scope.domainDeleted = true; - $scope.sslIssued = true; - $scope.childBaseDirChanged = true; - - var url = "/manageSSL/issueSSL"; - - - var data = { - virtualHost: childDomain, - path: path, - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - - if (response.data.SSL === 1) { - - $scope.domainLoading = true; - - // notifcations - - $scope.phpChanged = true; - $scope.domainError = true; - $scope.couldNotConnect = true; - $scope.domainDeleted = true; - $scope.sslIssued = false; - $scope.childBaseDirChanged = true; - - - $scope.sslDomainIssued = childDomain; - - - } else { - $scope.domainLoading = true; - - $scope.errorMessage = response.data.error_message; - - // notifcations - - $scope.phpChanged = true; - $scope.domainError = false; - $scope.couldNotConnect = true; - $scope.domainDeleted = true; - $scope.sslIssued = true; - $scope.childBaseDirChanged = true; - - } - - - } - - function cantLoadInitialDatas(response) { - - // notifcations - - $scope.phpChanged = true; - $scope.domainError = true; - $scope.couldNotConnect = false; - $scope.domainDeleted = true; - $scope.sslIssued = true; - $scope.childBaseDirChanged = true; - - - } - - - }; - - - /// Open_basedir protection - - $scope.baseDirLoading = true; - $scope.operationFailed = true; - $scope.operationSuccessfull = true; - $scope.couldNotConnect = true; - $scope.openBaseDirBox = true; - - - $scope.openBaseDirView = function () { - $scope.openBaseDirBox = false; - }; - - $scope.hideOpenBasedir = function () { - $scope.openBaseDirBox = true; - }; - - $scope.applyOpenBasedirChanges = function (childDomain, phpSelection) { - - // notifcations - - $scope.baseDirLoading = false; - $scope.operationFailed = true; - $scope.operationSuccessfull = true; - $scope.couldNotConnect = true; - $scope.openBaseDirBox = false; - - - var url = "/websites/changeOpenBasedir"; - - var data = { - domainName: $("#domainNamePage").text(), - openBasedirValue: $scope.openBasedirValue - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - - if (response.data.changeOpenBasedir === 1) { - - $scope.baseDirLoading = true; - $scope.operationFailed = true; - $scope.operationSuccessfull = false; - $scope.couldNotConnect = true; - $scope.openBaseDirBox = false; - - } else { - - $scope.baseDirLoading = true; - $scope.operationFailed = false; - $scope.operationSuccessfull = true; - $scope.couldNotConnect = true; - $scope.openBaseDirBox = false; - - $scope.errorMessage = response.data.error_message; - - } - - - } - - function cantLoadInitialDatas(response) { - - $scope.baseDirLoading = true; - $scope.operationFailed = true; - $scope.operationSuccessfull = true; - $scope.couldNotConnect = false; - $scope.openBaseDirBox = false; - - - } - - } - - - // REWRITE Template - - const httpToHTTPS = `### Rewrite Rules Added by CyberPanel Rewrite Rule Generator - -RewriteEngine On -RewriteCond %{HTTPS} !=on -RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L] - -### End CyberPanel Generated Rules. - -`; - - const WWWToNonWWW = `### Rewrite Rules Added by CyberPanel Rewrite Rule Generator - -RewriteEngine On -RewriteCond %{HTTP_HOST} ^www\.(.*)$ -RewriteRule ^(.*)$ http://%1/$1 [L,R=301] - -### End CyberPanel Generated Rules. - -`; - - const nonWWWToWWW = `### Rewrite Rules Added by CyberPanel Rewrite Rule Generator - -RewriteEngine On -RewriteCond %{HTTP_HOST} !^www\. [NC] -RewriteRule ^(.*)$ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L] - -### End CyberPanel Generated Rules. - -`; - - const WordpressProtect = `### Rewrite Rules Added by CyberPanel Rewrite Rule Generator - -RewriteEngine On -RewriteRule ^/(xmlrpc|wp-trackback)\.php - [F,L,NC] - -### End CyberPanel Generated Rules. - -`; - - $scope.applyRewriteTemplate = function () { - - if ($scope.rewriteTemplate === "Force HTTP -> HTTPS") { - $scope.rewriteRules = httpToHTTPS + $scope.rewriteRules; - } else if ($scope.rewriteTemplate === "Force NON-WWW -> WWW") { - $scope.rewriteRules = nonWWWToWWW + $scope.rewriteRules; - } else if ($scope.rewriteTemplate === "Force WWW -> NON-WWW") { - $scope.rewriteRules = WWWToNonWWW + $scope.rewriteRules; - } else if ($scope.rewriteTemplate === "Disable Wordpress XMLRPC & Trackback") { - $scope.rewriteRules = WordpressProtect + $scope.rewriteRules; - } - }; - - -}); - -/* Java script code to create account ends here */ - -/* Java script code to suspend/un-suspend Website */ - -app.controller('suspendWebsiteControl', function ($scope, $http) { - - $scope.suspendLoading = true; - $scope.stateView = true; - - $scope.websiteSuspendFailure = true; - $scope.websiteUnsuspendFailure = true; - $scope.websiteSuccess = true; - $scope.couldNotConnect = true; - - $scope.showSuspendUnsuspend = function () { - - $scope.stateView = false; - - - }; - - $scope.save = function () { - - $scope.suspendLoading = false; - - var websiteName = $scope.websiteToBeSuspended - var state = $scope.state; - - - url = "/websites/submitWebsiteStatus"; - - var data = { - websiteName: websiteName, - state: state, - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.websiteStatus === 1) { - if (state == "Suspend") { - - $scope.suspendLoading = true; - $scope.stateView = false; - - $scope.websiteSuspendFailure = true; - $scope.websiteUnsuspendFailure = true; - $scope.websiteSuccess = false; - $scope.couldNotConnect = true; - - $scope.websiteStatus = websiteName; - $scope.finalStatus = "Suspended"; - - } else { - $scope.suspendLoading = true; - $scope.stateView = false; - - $scope.websiteSuspendFailure = true; - $scope.websiteUnsuspendFailure = true; - $scope.websiteSuccess = false; - $scope.couldNotConnect = true; - - $scope.websiteStatus = websiteName; - $scope.finalStatus = "Un-suspended"; - - } - - } else { - - if (state == "Suspend") { - - $scope.suspendLoading = true; - $scope.stateView = false; - - $scope.websiteSuspendFailure = false; - $scope.websiteUnsuspendFailure = true; - $scope.websiteSuccess = true; - $scope.couldNotConnect = true; - - - } else { - $scope.suspendLoading = true; - $scope.stateView = false; - - $scope.websiteSuspendFailure = true; - $scope.websiteUnsuspendFailure = false; - $scope.websiteSuccess = true; - $scope.couldNotConnect = true; - - - } - - - $scope.errorMessage = response.data.error_message; - - } - - - } - - function cantLoadInitialDatas(response) { - $scope.couldNotConnect = false; - $scope.suspendLoading = true; - $scope.stateView = true; - - $scope.websiteSuspendFailure = true; - $scope.websiteUnsuspendFailure = true; - $scope.websiteSuccess = true; - - } - - - }; - -}); - -/** - * Created by usman on 7/26/17. - */ -function getCookie(name) { - var cookieValue = null; - var t = document.cookie; - if (document.cookie && document.cookie !== '') { - var cookies = document.cookie.split(';'); - for (var i = 0; i < cookies.length; i++) { - var cookie = jQuery.trim(cookies[i]); - // Does this cookie string begin with the name we want? - if (cookie.substring(0, name.length + 1) === (name + '=')) { - cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); - break; - } - } - } - return cookieValue; -} - - -var arry = [] - -function selectpluginJs(val) { - $('#mysearch').hide() - arry.push(val) - - // console.log(arry) - document.getElementById('selJS').innerHTML = ""; - - for (var i = 0; i < arry.length; i++) { - $('#selJS').show() - var mlm = ' ' + arry[i] + '    ' - $('#selJS').append(mlm) - } - - -} - - -var DeletePluginURL; - -function DeletePluginBuucket(url) { - DeletePluginURL = url; -} - -function FinalDeletePluginBuucket() { - window.location.href = DeletePluginURL; -} - -var SPVal; - -app.controller('WPAddNewPlugin', function ($scope, $http, $timeout, $window, $compile) { - $scope.webSiteCreationLoading = true; - - $scope.SearchPluginName = function (val) { - $scope.webSiteCreationLoading = false; - SPVal = val; - url = "/websites/SearchOnkeyupPlugin"; - - var searchcontent = $scope.searchcontent; - - - var data = { - pluginname: searchcontent - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.webSiteCreationLoading = true; - - if (response.data.status === 1) { - if (SPVal == 'add') { - $('#mysearch').show() - document.getElementById('mysearch').innerHTML = ""; - var res = response.data.plugns.plugins - // console.log(res); - for (i = 0; i <= res.length; i++) { - // - var tml = '
'; - $('#mysearch').append(tml); - } - } else if (SPVal == 'eidt') { - $('#mysearch').show() - document.getElementById('mysearch').innerHTML = ""; - var res = response.data.plugns.plugins - // console.log(res); - for (i = 0; i <= res.length; i++) { - // - var tml = '
'; - var temp = $compile(tml)($scope) - angular.element(document.getElementById('mysearch')).append(temp); - } - - } - - - } else { - - // $scope.errorMessage = response.data.error_message; - alert("Status not = 1: Error..." + response.data.error_message) - } - - - } - - function cantLoadInitialDatas(response) { - - alert("Error..." + response) - - } - } - - $scope.AddNewplugin = function () { - - url = "/websites/AddNewpluginAjax"; - - var bucketname = $scope.PluginbucketName - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - var data = { - config: arry, - Name: bucketname - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - function ListInitialDatas(response) { - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Bucket created.', - type: 'success' - }); - location.reload(); - } else { - - new PNotify({ - title: 'Error!', - text: response.data.error_message, - type: 'error' - }); - } - - - } - - function cantLoadInitialDatas(response) { - - alert("Error..." + response) - - } - } - - $scope.deletesPlgin = function (val) { - - url = "/websites/deletesPlgin"; - - - var data = { - pluginname: val, - pluginbBucketID: $('#pluginbID').html() - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.status === 1) { - location.reload(); - - } else { - - // $scope.errorMessage = response.data.error_message; - alert("Status not = 1: Error..." + response.data.error_message) - } - - - } - - function cantLoadInitialDatas(response) { - - alert("Error..." + response) - - } - - } - - $scope.Addplugin = function (slug) { - $('#mysearch').hide() - - url = "/websites/Addplugineidt"; - - - var data = { - pluginname: slug, - pluginbBucketID: $('#pluginbID').html() - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.status === 1) { - location.reload(); - - } else { - - // $scope.errorMessage = response.data.error_message; - alert("Status not = 1: Error..." + response.data.error_message) - } - - - } - - function cantLoadInitialDatas(response) { - - alert("Error..." + response) - - } - - - } - -}); - -var domain_check = 0; - -function checkbox_function() { - - var checkBox = document.getElementById("myCheck"); - // Get the output text - - - // If the checkbox is checked, display the output text - if (checkBox.checked == true) { - domain_check = 0; - document.getElementById('Test_Domain').style.display = "block"; - document.getElementById('Own_Domain').style.display = "none"; - - } else { - document.getElementById('Test_Domain').style.display = "none"; - document.getElementById('Own_Domain').style.display = "block"; - domain_check = 1; - } - - // alert(domain_check); -} - -app.controller('createWordpress', function ($scope, $http, $timeout, $compile, $window) { - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - - - var statusFile; - - $scope.createWordPresssite = function () { - - $scope.webSiteCreationLoading = false; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - - - $scope.currentStatus = "Starting creation.."; - - var apacheBackend = 0; - - if ($scope.apacheBackend === true) { - apacheBackend = 1; - } else { - apacheBackend = 0 - } - - var package = $scope.packageForWebsite; - var websiteOwner = $scope.websiteOwner; - var WPtitle = $scope.WPtitle; - - // if (domain_check == 0) { - // var Part2_domainNameCreate = document.getElementById('Part2_domainNameCreate').value; - // var domainNameCreate = document.getElementById('TestDomainNameCreate').value + Part2_domainNameCreate; - // } - // if (domain_check == 1) { - // - // var domainNameCreate = $scope.own_domainNameCreate; - // } - - var domainNameCreate = $scope.domainNameCreate; - - - var WPUsername = $scope.WPUsername; - var adminEmail = $scope.adminEmail; - var WPPassword = $scope.WPPassword; - var WPVersions = $scope.WPVersions; - var pluginbucket = $scope.pluginbucket; - var autoupdates = $scope.autoupdates; - var pluginupdates = $scope.pluginupdates; - var themeupdates = $scope.themeupdates; - - if (domain_check == 0) { - - var path = ""; - - } - if (domain_check = 1) { - - var path = $scope.installPath; - - } - - - var home = "1"; - - if (typeof path != 'undefined') { - home = "0"; - } - - //alert(domainNameCreate); - var data = { - - title: WPtitle, - domain: domainNameCreate, - WPVersion: WPVersions, - pluginbucket: pluginbucket, - adminUser: WPUsername, - Email: adminEmail, - PasswordByPass: WPPassword, - AutomaticUpdates: autoupdates, - Plugins: pluginupdates, - Themes: themeupdates, - websiteOwner: websiteOwner, - package: package, - home: home, - path: path, - apacheBackend: apacheBackend - } - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - var url = "/websites/submitWorpressCreation"; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.webSiteCreationLoading = true; - if (response.data.status === 1) { - statusFile = response.data.tempStatusPath; - getCreationStatus(); - - } else { - $scope.goBackDisable = false; - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - } - - } - - function cantLoadInitialDatas(response) { - - alert("Error..." + response) - - } - - }; - $scope.goBack = function () { - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - $("#installProgress").css("width", "0%"); - }; - - function getCreationStatus() { - - url = "/websites/installWordpressStatus"; - - var data = { - statusFile: statusFile - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.abort === 1) { - - if (response.data.installStatus === 1) { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = false; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $("#installProgress").css("width", "100%"); - $scope.installPercentage = "100"; - $scope.currentStatus = response.data.currentStatus; - $timeout.cancel(); - - } else { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = false; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $scope.errorMessage = response.data.error_message; - - $("#installProgress").css("width", "0%"); - $scope.installPercentage = "0"; - $scope.goBackDisable = false; - - } - - } else { - $scope.webSiteCreationLoading = false; - $("#installProgress").css("width", response.data.installationProgress + "%"); - $scope.installPercentage = response.data.installationProgress; - $scope.currentStatus = response.data.currentStatus; - $timeout(getCreationStatus, 1000); - } - - } - - function cantLoadInitialDatas(response) { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - } - - -}); - - -//........... delete wp list -var FurlDeleteWP; - -function DeleteWPNow(url) { - FurlDeleteWP = url; -} - -function FinalDeleteWPNow() { - window.location.href = FurlDeleteWP; -} - -var DeploytoProductionID; - -function DeployToProductionInitial(vall) { - DeploytoProductionID = vall; -} - -var create_staging_domain_check = 0; - -function create_staging_checkbox_function() { - - try { - - var checkBox = document.getElementById("Create_Staging_Check"); - // Get the output text - - - // If the checkbox is checked, display the output text - if (checkBox.checked == true) { - create_staging_domain_check = 0; - document.getElementById('Website_Create_Test_Domain').style.display = "block"; - document.getElementById('Website_Create_Own_Domain').style.display = "none"; - - } else { - document.getElementById('Website_Create_Test_Domain').style.display = "none"; - document.getElementById('Website_Create_Own_Domain').style.display = "block"; - create_staging_domain_check = 1; - } - } catch (e) { - - } - - // alert(domain_check); -} - -create_staging_checkbox_function(); - -app.controller('WPsiteHome', function ($scope, $http, $timeout, $compile, $window) { - - var CheckBoxpasssword = 0; - - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - $(document).ready(function () { - var checkstatus = document.getElementById("wordpresshome"); - if (checkstatus !== null) { - $scope.LoadWPdata(); - - } - }); - - - $scope.LoadWPdata = function () { - - $scope.wordpresshomeloading = false; - $('#wordpresshomeloading').show(); - - var url = "/websites/FetchWPdata"; - - var data = { - WPid: $('#WPid').html(), - } - - console.log(data); - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - wordpresshomeloading = true; - $('#wordpresshomeloading').hide(); - - if (response.data.status === 1) { - $('#WPVersion').text(response.data.ret_data.version); - if (response.data.ret_data.lscache === 1) { - $('#lscache').prop('checked', true); - } - if (response.data.ret_data.debugging === 1) { - $('#debugging').prop('checked', true); - } - if (response.data.ret_data.searchIndex === 1) { - $('#searchIndex').prop('checked', true); - } - if (response.data.ret_data.maintenanceMode === 1) { - $('#maintenanceMode').prop('checked', true); - } - if (response.data.ret_data.wpcron === 1) { - $('#wpcron').prop('checked', true); - } - if (response.data.ret_data.passwordprotection == 1) { - - var dc = '\n' + - ' ' - var mp = $compile(dc)($scope); - angular.element(document.getElementById('prsswdprodata')).append(mp); - CheckBoxpasssword = 1; - } else if (response.data.ret_data.passwordprotection == 0) { - var dc = '\n' + - ' ' - $('#prsswdprodata').append(dc); - CheckBoxpasssword = 0; - } - - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - }; - - $scope.UpdateWPSettings = function (setting) { - - $scope.wordpresshomeloading = false; - $('#wordpresshomeloading').show(); - - - var url = "/websites/UpdateWPSettings"; - - if (setting === "PasswordProtection") { - if (CheckBoxpasssword == 0) { - var data = { - WPid: $('#WPid').html(), - setting: setting, - PPUsername: $scope.PPUsername, - PPPassword: $scope.PPPassword, - } - - } else { - var data = { - WPid: $('#WPid').html(), - setting: setting, - PPUsername: '', - PPPassword: '', - } - - } - - } else { - var settingValue = 0; - if ($('#' + setting).is(":checked")) { - settingValue = 1; - } - var data = { - WPid: $('#WPid').html(), - setting: setting, - settingValue: settingValue - } - } - - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.wordpresshomeloading = true; - $('#wordpresshomeloading').hide(); - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Successfully Updated!.', - type: 'success' - }); - if (setting === "PasswordProtection") { - location.reload(); - } - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - if (setting === "PasswordProtection") { - location.reload(); - } - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - - - }; - - $scope.GetCurrentPlugins = function () { - $('#wordpresshomeloading').show(); - - $scope.wordpresshomeloading = false; - - var url = "/websites/GetCurrentPlugins"; - - var data = { - WPid: $('#WPid').html(), - } - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - wordpresshomeloading = true; - $('#wordpresshomeloading').hide(); - - if (response.data.status === 1) { - $('#PluginBody').html(''); - var plugins = JSON.parse(response.data.plugins); - plugins.forEach(AddPlugins); - - } else { - alert("Error:" + response.data.error_message) - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - }; - - $scope.GetCurrentThemes = function () { - $('#wordpresshomeloading').show(); - - $scope.wordpresshomeloading = false; - - var url = "/websites/GetCurrentThemes"; - - var data = { - WPid: $('#WPid').html(), - } - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - wordpresshomeloading = true; - $('#wordpresshomeloading').hide(); - - if (response.data.status === 1) { - - $('#ThemeBody').html(''); - var themes = JSON.parse(response.data.themes); - themes.forEach(AddThemes); - - } else { - alert("Error:" + response.data.error_message) - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - }; - - $scope.UpdatePlugins = function (plugin) { - $('#wordpresshomeloading').show(); - var data = { - plugin: plugin, - pluginarray: PluginsList, - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/UpdatePlugins"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Updating Plugins in Background!.', - type: 'success' - }); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - - - }; - - $scope.DeletePlugins = function (plugin) { - $('#wordpresshomeloading').show(); - var data = { - plugin: plugin, - pluginarray: PluginsList, - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/DeletePlugins"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Deleting Plugin in Background!', - type: 'success' - }); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - - } - - $scope.ChangeStatus = function (plugin) { - $('#wordpresshomeloading').show(); - var data = { - plugin: plugin, - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/ChangeStatus"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Changed Plugin state Successfully !.', - type: 'success' - }); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - - } - - function AddPlugins(value, index, array) { - var FinalMarkup = '' - FinalMarkup = FinalMarkup + ''; - for (let x in value) { - if (x === 'status') { - if (value[x] === 'inactive') { - FinalMarkup = FinalMarkup + '
'; - } else { - FinalMarkup = FinalMarkup + '
'; - } - } else if (x === 'update') { - if (value[x] === 'none') { - FinalMarkup = FinalMarkup + 'Upto Date'; - } else { - FinalMarkup = FinalMarkup + ''; - } - } else { - FinalMarkup = FinalMarkup + '' + value[x] + ""; - } - } - FinalMarkup = FinalMarkup + '' - FinalMarkup = FinalMarkup + '' - var temp = $compile(FinalMarkup)($scope) - AppendToTable('#PluginBody', temp) - } - - $scope.UpdateThemes = function (theme) { - $('#wordpresshomeloading').show(); - var data = { - Theme: theme, - Themearray: ThemesList, - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/UpdateThemes"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Updating Theme in background !.', - type: 'success' - }); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - - - }; - - $scope.DeleteThemes = function (theme) { - $('#wordpresshomeloading').show(); - var data = { - Theme: theme, - Themearray: ThemesList, - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/DeleteThemes"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Deleting Theme in Background!.', - type: 'success' - }); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - }; - - $scope.ChangeStatusThemes = function (theme) { - $('#wordpresshomeloading').show(); - var data = { - theme: theme, - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/StatusThemes"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Change Theme state in Bsckground!.', - type: 'success' - }); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - - }; - - function AddThemes(value, index, array) { - var FinalMarkup = '' - FinalMarkup = FinalMarkup + ''; - for (let x in value) { - if (x === 'status') { - if (value[x] === 'inactive') { - FinalMarkup = FinalMarkup + '
'; - } else { - FinalMarkup = FinalMarkup + '
'; - } - } else if (x === 'update') { - if (value[x] === 'none') { - FinalMarkup = FinalMarkup + 'Upto Date'; - } else { - FinalMarkup = FinalMarkup + ''; - } - } else { - FinalMarkup = FinalMarkup + '' + value[x] + ""; - } - } - FinalMarkup = FinalMarkup + '' - FinalMarkup = FinalMarkup + '' - var temp = $compile(FinalMarkup)($scope) - AppendToTable('#ThemeBody', temp) - } - - $scope.CreateStagingNow = function () { - $('#wordpresshomeloading').show(); - - $scope.wordpresshomeloading = false; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - - - $scope.currentStatus = "Starting creation Staging.."; - - //here enter domain name - if (create_staging_domain_check == 0) { - var Part2_domainNameCreate = document.getElementById('Part2_domainNameCreate').value; - var domainNameCreate = document.getElementById('TestDomainNameCreate').value + Part2_domainNameCreate; - } - if (create_staging_domain_check == 1) { - - var domainNameCreate = $scope.own_domainNameCreate; - } - var data = { - StagingName: $('#stagingName').val(), - StagingDomain: domainNameCreate, - WPid: $('#WPid').html(), - } - var url = "/websites/CreateStagingNow"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - if (response.data.status === 1) { - statusFile = response.data.tempStatusPath; - getCreationStatus(); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - }; - - function getCreationStatus() { - $('#wordpresshomeloading').show(); - - url = "/websites/installWordpressStatus"; - - var data = { - statusFile: statusFile - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - //$('#wordpresshomeloading').hide(); - - if (response.data.abort === 1) { - if (response.data.installStatus === 1) { - - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = false; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - - $("#installProgress").css("width", "100%"); - $("#installProgressbackup").css("width", "100%"); - $scope.installPercentage = "100"; - $scope.currentStatus = response.data.currentStatus; - $timeout.cancel(); - - - } else { - - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = false; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $scope.errorMessage = response.data.error_message; - - $("#installProgress").css("width", "0%"); - $("#installProgressbackup").css("width", "0%"); - $scope.installPercentage = "0"; - $scope.goBackDisable = false; - - - } - - } else { - - $("#installProgress").css("width", response.data.installationProgress + "%"); - $("#installProgressbackup").css("width", response.data.installationProgress + "%"); - $scope.installPercentage = response.data.installationProgress; - $scope.currentStatus = response.data.currentStatus; - $timeout(getCreationStatus, 1000); - - } - - } - - function cantLoadInitialDatas(response) { - //$('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - } - - $scope.goBack = function () { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - $("#installProgress").css("width", "0%"); - }; - - $scope.fetchstaging = function () { - - $('#wordpresshomeloading').show(); - $scope.wordpresshomeloading = false; - - var url = "/websites/fetchstaging"; - - var data = { - WPid: $('#WPid').html(), - } - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - wordpresshomeloading = true; - $('#wordpresshomeloading').hide(); - - if (response.data.status === 1) { - - // $('#ThemeBody').html(''); - // var themes = JSON.parse(response.data.themes); - // themes.forEach(AddThemes); - - $('#StagingBody').html(''); - var staging = JSON.parse(response.data.wpsites); - staging.forEach(AddStagings); - - } else { - alert("Error data.error_message:" + response.data.error_message) - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - alert("Error" + response) - - } - - }; - - $scope.fetchDatabase = function () { - - $('#wordpresshomeloading').show(); - $scope.wordpresshomeloading = false; - - var url = "/websites/fetchDatabase"; - - var data = { - WPid: $('#WPid').html(), - } - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - wordpresshomeloading = true; - $('#wordpresshomeloading').hide(); - - if (response.data.status === 1) { - $('#DB_Name').html(response.data.DataBaseName); - $('#DB_User').html(response.data.DataBaseUser); - $('#tableprefix').html(response.data.tableprefix); - } else { - alert("Error data.error_message:" + response.data.error_message) - - } - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - alert("Error" + response) - - } - - }; - - $scope.SaveUpdateConfig = function () { - $('#wordpresshomeloading').show(); - var data = { - AutomaticUpdates: $('#AutomaticUpdates').find(":selected").text(), - Plugins: $('#Plugins').find(":selected").text(), - Themes: $('#Themes').find(":selected").text(), - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/SaveUpdateConfig"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Update Configurations Sucessfully!.', - type: 'success' - }); - $("#autoUpdateConfig").modal('hide'); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - new PNotify({ - title: 'Operation Failed!', - text: response, - type: 'error' - }); - - } - }; - - function AddStagings(value, index, array) { - var FinalMarkup = '' - for (let x in value) { - if (x === 'name') { - FinalMarkup = FinalMarkup + '' + value[x] + ''; - } else if (x !== 'url' && x !== 'deleteURL' && x !== 'id') { - FinalMarkup = FinalMarkup + '' + value[x] + ""; - } - } - FinalMarkup = FinalMarkup + '' + - ' ' - FinalMarkup = FinalMarkup + '' - AppendToTable('#StagingBody', FinalMarkup); - } - - $scope.FinalDeployToProduction = function () { - - $('#wordpresshomeloading').show(); - - $scope.wordpresshomeloading = false; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - - var data = { - WPid: $('#WPid').html(), - StagingID: DeploytoProductionID - } - - var url = "/websites/DeploytoProduction"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - function ListInitialDatas(response) { - - $('#wordpresshomeloading').hide(); - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Deploy To Production start!.', - type: 'success' - }); - statusFile = response.data.tempStatusPath; - getCreationStatus(); - - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - new PNotify({ - title: 'Operation Failed!', - text: response, - type: 'error' - }); - - } - - }; - - - $scope.CreateBackup = function () { - $('#wordpresshomeloading').show(); - - $scope.wordpresshomeloading = false; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - $scope.currentStatus = "Starting creation Backups.."; - var data = { - WPid: $('#WPid').html(), - Backuptype: $('#backuptype').val() - } - var url = "/websites/WPCreateBackup"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $('createbackupbutton').hide(); - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Creating Backups!.', - type: 'success' - }); - statusFile = response.data.tempStatusPath; - getCreationStatus(); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - alert(response) - - } - - }; - - - $scope.installwpcore = function () { - - $('#wordpresshomeloading').show(); - $('#wordpresshomeloadingsec').show(); - var data = { - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/installwpcore"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $('#wordpresshomeloadingsec').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Results fetched..', - type: 'success' - }); - $('#SecurityResult').html(response.data.result); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $('#wordpresshomeloadingsec').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - - }; - - $scope.dataintegrity = function () { - - $('#wordpresshomeloading').show(); - $('#wordpresshomeloadingsec').show(); - var data = { - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/dataintegrity"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $('#wordpresshomeloadingsec').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Results fetched', - type: 'success' - }); - $('#SecurityResult').html(response.data.result); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $('#wordpresshomeloadingsec').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - }; - -}); - - -var PluginsList = []; - - -function AddPluginToArray(cBox, name) { - if (cBox.checked) { - PluginsList.push(name); - // alert(PluginsList); - } else { - const index = PluginsList.indexOf(name); - if (index > -1) { - PluginsList.splice(index, 1); - } - // alert(PluginsList); - } -} - -var ThemesList = []; - -function AddThemeToArray(cBox, name) { - if (cBox.checked) { - ThemesList.push(name); - // alert(ThemesList); - } else { - const index = ThemesList.indexOf(name); - if (index > -1) { - ThemesList.splice(index, 1); - } - // alert(ThemesList); - } -} - - -function AppendToTable(table, markup) { - $(table).append(markup); -} - - -//..................Restore Backup Home - - -app.controller('RestoreWPBackup', function ($scope, $http, $timeout, $window) { - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - - - $scope.checkmethode = function () { - var val = $('#RestoreMethode').children("option:selected").val(); - if (val == 1) { - $('#Newsitediv').show(); - $('#exinstingsitediv').hide(); - } else if (val == 0) { - $('#exinstingsitediv').show(); - $('#Newsitediv').hide(); - } else { - - } - }; - - - $scope.RestoreWPbackupNow = function () { - $('#wordpresshomeloading').show(); - $scope.wordpresshomeloading = false; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - $scope.currentStatus = "Start Restoring WordPress.."; - - var Domain = $('#wprestoresubdirdomain').val() - var path = $('#wprestoresubdirpath').val(); - var home = "1"; - - if (typeof path != 'undefined' || path != '') { - home = "0"; - } - if (typeof path == 'undefined') { - path = ""; - } - - - var backuptype = $('#backuptype').html(); - var data; - if (backuptype == "DataBase Backup") { - data = { - backupid: $('#backupid').html(), - DesSite: $('#DesSite').children("option:selected").val(), - Domain: '', - path: path, - home: home, - } - } else { - data = { - backupid: $('#backupid').html(), - DesSite: $('#DesSite').children("option:selected").val(), - Domain: Domain, - path: path, - home: home, - } - - } - - var url = "/websites/RestoreWPbackupNow"; - - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - // console.log(data) - - var d = $('#DesSite').children("option:selected").val(); - var c = $("input[name=Newdomain]").val(); - // if (d == -1 || c == "") { - // alert("Please Select Method of Backup Restore"); - // } else { - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - // } - - - function ListInitialDatas(response) { - wordpresshomeloading = true; - $('#wordpresshomeloading').hide(); - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Restoring process starts!.', - type: 'success' - }); - statusFile = response.data.tempStatusPath; - getCreationStatus(); - - } else { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = false; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $scope.errorMessage = response.data.error_message; - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - - } - } - - function getCreationStatus() { - $('#wordpresshomeloading').show(); - - url = "/websites/installWordpressStatus"; - - var data = { - statusFile: statusFile - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - //$('#wordpresshomeloading').hide(); - - if (response.data.abort === 1) { - - if (response.data.installStatus === 1) { - - - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = false; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - - $("#installProgress").css("width", "100%"); - $("#installProgressbackup").css("width", "100%"); - $scope.installPercentage = "100"; - $scope.currentStatus = response.data.currentStatus; - $timeout.cancel(); - - - } else { - - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = false; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $scope.errorMessage = response.data.error_message; - - $("#installProgress").css("width", "0%"); - $("#installProgressbackup").css("width", "0%"); - $scope.installPercentage = "0"; - $scope.goBackDisable = false; - - - } - - } else { - - $("#installProgress").css("width", response.data.installationProgress + "%"); - $("#installProgressbackup").css("width", response.data.installationProgress + "%"); - $scope.installPercentage = response.data.installationProgress; - $scope.currentStatus = response.data.currentStatus; - $timeout(getCreationStatus, 1000); - - } - - } - - function cantLoadInitialDatas(response) { - //$('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - } - - $scope.goBack = function () { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - $("#installProgress").css("width", "0%"); - }; -}); - - -//.......................................Remote Backup - -//........... delete DeleteBackupConfigNow - -function DeleteBackupConfigNow(url) { - window.location.href = url; -} - -function DeleteRemoteBackupsiteNow(url) { - window.location.href = url; -} - -function DeleteBackupfileConfigNow(url) { - window.location.href = url; -} - - -app.controller('RemoteBackupConfig', function ($scope, $http, $timeout, $window) { - $scope.RemoteBackupLoading = true; - $scope.SFTPBackUpdiv = true; - - $scope.EndpointURLdiv = true; - $scope.Selectprovider = true; - $scope.S3keyNamediv = true; - $scope.Accesskeydiv = true; - $scope.SecretKeydiv = true; - $scope.SelectRemoteBackuptype = function () { - var val = $scope.RemoteBackuptype; - if (val == "SFTP") { - $scope.SFTPBackUpdiv = false; - $scope.EndpointURLdiv = true; - $scope.Selectprovider = true; - $scope.S3keyNamediv = true; - $scope.Accesskeydiv = true; - $scope.SecretKeydiv = true; - } else if (val == "S3") { - $scope.EndpointURLdiv = true; - $scope.Selectprovider = false; - $scope.S3keyNamediv = false; - $scope.Accesskeydiv = false; - $scope.SecretKeydiv = false; - $scope.SFTPBackUpdiv = true; - } else { - $scope.RemoteBackupLoading = true; - $scope.SFTPBackUpdiv = true; - - $scope.EndpointURLdiv = true; - $scope.Selectprovider = true; - $scope.S3keyNamediv = true; - $scope.Accesskeydiv = true; - $scope.SecretKeydiv = true; - } - } - - $scope.SelectProvidertype = function () { - $scope.EndpointURLdiv = true; - var provider = $scope.Providervalue - if (provider == 'Backblaze') { - $scope.EndpointURLdiv = false; - } else { - $scope.EndpointURLdiv = true; - } - } - - $scope.SaveBackupConfig = function () { - $scope.RemoteBackupLoading = false; - var Hname = $scope.Hostname; - var Uname = $scope.Username; - var Passwd = $scope.Password; - var path = $scope.path; - var type = $scope.RemoteBackuptype; - var Providervalue = $scope.Providervalue; - var data; - if (type == "SFTP") { - - data = { - Hname: Hname, - Uname: Uname, - Passwd: Passwd, - path: path, - type: type - } - } else if (type == "S3") { - if (Providervalue == "Backblaze") { - data = { - S3keyname: $scope.S3keyName, - Provider: Providervalue, - AccessKey: $scope.Accesskey, - SecertKey: $scope.SecretKey, - EndUrl: $scope.EndpointURL, - type: type - } - } else { - data = { - S3keyname: $scope.S3keyName, - Provider: Providervalue, - AccessKey: $scope.Accesskey, - SecertKey: $scope.SecretKey, - type: type - } - - } - - } - var url = "/websites/SaveBackupConfig"; - - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.RemoteBackupLoading = true; - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Successfully Saved!.', - type: 'success' - }); - location.reload(); - - - } else { - new PNotify({ - title: 'Error!', - text: response.data.error_message, - type: 'error' - }); - } - } - - function cantLoadInitialDatas(response) { - $scope.RemoteBackupLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - - } - - - } - -}); - -var UpdatescheduleID; -app.controller('BackupSchedule', function ($scope, $http, $timeout, $window) { - $scope.BackupScheduleLoading = true; - $scope.SaveBackupSchedule = function () { - $scope.RemoteBackupLoading = false; - var FileRetention = $scope.Fretention; - var Backfrequency = $scope.Bfrequency; - - - var data = { - FileRetention: FileRetention, - Backfrequency: Backfrequency, - ScheduleName: $scope.ScheduleName, - RemoteConfigID: $('#RemoteConfigID').html(), - BackupType: $scope.BackupType - } - var url = "/websites/SaveBackupSchedule"; - - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.RemoteBackupLoading = true; - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Successfully Saved!.', - type: 'success' - }); - location.reload(); - - - } else { - new PNotify({ - title: 'Error!', - text: response.data.error_message, - type: 'error' - }); - } - } - - function cantLoadInitialDatas(response) { - $scope.RemoteBackupLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - - } - - - }; - - - $scope.getupdateid = function (ID) { - UpdatescheduleID = ID; - } - - $scope.UpdateRemoteschedules = function () { - $scope.RemoteBackupLoading = false; - var Frequency = $scope.RemoteFrequency; - var fretention = $scope.RemoteFileretention; - - var data = { - ScheduleID: UpdatescheduleID, - Frequency: Frequency, - FileRetention: fretention - } - var url = "/websites/UpdateRemoteschedules"; - - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.RemoteBackupLoading = true; - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Successfully Updated!.', - type: 'success' - }); - location.reload(); - - - } else { - new PNotify({ - title: 'Error!', - text: response.data.error_message, - type: 'error' - }); - } - } - - function cantLoadInitialDatas(response) { - $scope.RemoteBackupLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - - } - }; - - $scope.AddWPsiteforRemoteBackup = function () { - $scope.RemoteBackupLoading = false; - - - var data = { - WpsiteID: $('#Wpsite').val(), - RemoteScheduleID: $('#RemoteScheduleID').html() - } - var url = "/websites/AddWPsiteforRemoteBackup"; - - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.RemoteBackupLoading = true; - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Successfully Saved!.', - type: 'success' - }); - location.reload(); - - - } else { - new PNotify({ - title: 'Error!', - text: response.data.error_message, - type: 'error' - }); - } - } - - function cantLoadInitialDatas(response) { - $scope.RemoteBackupLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - - } - - - }; -}); -/* Java script code to create account */ - -var website_create_domain_check = 0; - -function website_create_checkbox_function() { - - var checkBox = document.getElementById("myCheck"); - // Get the output text - - - // If the checkbox is checked, display the output text - if (checkBox.checked == true) { - website_create_domain_check = 0; - document.getElementById('Website_Create_Test_Domain').style.display = "block"; - document.getElementById('Website_Create_Own_Domain').style.display = "none"; - - } else { - document.getElementById('Website_Create_Test_Domain').style.display = "none"; - document.getElementById('Website_Create_Own_Domain').style.display = "block"; - website_create_domain_check = 1; - } - - // alert(domain_check); -} - -app.controller('createWebsite', function ($scope, $http, $timeout, $window) { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - - var statusFile; - - $scope.createWebsite = function () { - - $scope.webSiteCreationLoading = false; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - - $scope.currentStatus = "Starting creation.."; - - var ssl, dkimCheck, openBasedir, mailDomain, apacheBackend; - - if ($scope.sslCheck === true) { - ssl = 1; - } else { - ssl = 0 - } - - if ($scope.apacheBackend === true) { - apacheBackend = 1; - } else { - apacheBackend = 0 - } - - if ($scope.dkimCheck === true) { - dkimCheck = 1; - } else { - dkimCheck = 0 - } - - if ($scope.openBasedir === true) { - openBasedir = 1; - } else { - openBasedir = 0 - } - - if ($scope.mailDomain === true) { - mailDomain = 1; - } else { - mailDomain = 0 - } - - url = "/websites/submitWebsiteCreation"; - - var package = $scope.packageForWebsite; - - // if (website_create_domain_check == 0) { - // var Part2_domainNameCreate = document.getElementById('Part2_domainNameCreate').value; - // var domainName = document.getElementById('TestDomainNameCreate').value + Part2_domainNameCreate; - // } - // if (website_create_domain_check == 1) { - // - // var domainName = $scope.domainNameCreate; - // } - var domainName = $scope.domainNameCreate; - - // var domainName = $scope.domainNameCreate; - - var adminEmail = $scope.adminEmail; - var phpSelection = $scope.phpSelection; - var websiteOwner = $scope.websiteOwner; - - - var data = { - package: package, - domainName: domainName, - adminEmail: adminEmail, - phpSelection: phpSelection, - ssl: ssl, - websiteOwner: websiteOwner, - dkimCheck: dkimCheck, - openBasedir: openBasedir, - mailDomain: mailDomain, - apacheBackend: apacheBackend - }; - - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.createWebSiteStatus === 1) { - statusFile = response.data.tempStatusPath; - getCreationStatus(); - } else { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = false; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $scope.errorMessage = response.data.error_message; - } - - - } - - function cantLoadInitialDatas(response) { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - }; - $scope.goBack = function () { - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - $("#installProgress").css("width", "0%"); - }; - - function getCreationStatus() { - - url = "/websites/installWordpressStatus"; - - var data = { - statusFile: statusFile - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - - if (response.data.abort === 1) { - - if (response.data.installStatus === 1) { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = false; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $("#installProgress").css("width", "100%"); - $scope.installPercentage = "100"; - $scope.currentStatus = response.data.currentStatus; - $timeout.cancel(); - - } else { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = false; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $scope.errorMessage = response.data.error_message; - - $("#installProgress").css("width", "0%"); - $scope.installPercentage = "0"; - $scope.goBackDisable = false; - - } - - } else { - $("#installProgress").css("width", response.data.installationProgress + "%"); - $scope.installPercentage = response.data.installationProgress; - $scope.currentStatus = response.data.currentStatus; - $timeout(getCreationStatus, 1000); - } - - } - - function cantLoadInitialDatas(response) { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - } - -}); -/* Java script code to create account ends here */ - -/* Java script code to list accounts */ - -$("#listFail").hide(); - - -app.controller('listWebsites', function ($scope, $http, $window) { - console.log('Initializing listWebsites controller'); - $scope.web = {}; - $scope.WebSitesList = []; - - $scope.currentPage = 1; - $scope.recordsToShow = 10; - - // Initial fetch of websites - $scope.getFurtherWebsitesFromDB = function () { - console.log('Fetching websites from DB'); - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - var data = { - page: $scope.currentPage, - recordsToShow: $scope.recordsToShow - }; - - var dataurl = "/websites/fetchWebsitesList"; - console.log('Making request to:', dataurl); - - $http.post(dataurl, data, config).then(function(response) { - console.log('Received response:', response); - if (response.data.listWebSiteStatus === 1) { - try { - $scope.WebSitesList = JSON.parse(response.data.data); - console.log('Parsed WebSitesList:', $scope.WebSitesList); - $scope.pagination = response.data.pagination; - $("#listFail").hide(); - } catch (e) { - console.error('Error parsing response data:', e); - $("#listFail").fadeIn(); - $scope.errorMessage = 'Error parsing server response'; - } - } else { - $("#listFail").fadeIn(); - $scope.errorMessage = response.data.error_message; } }).catch(function(error) { - console.error('Error fetching websites:', error); $("#listFail").fadeIn(); $scope.errorMessage = error.message || 'An error occurred while fetching websites'; }); @@ -8240,72 +2675,110 @@ app.controller('listWebsites', function ($scope, $http, $window) { $scope.getFurtherWebsitesFromDB(); $scope.showWPSites = function(index) { - console.log('showWPSites called with index:', index); - console.log('Current WebSitesList:', $scope.WebSitesList); - $scope.selectedWebsite = $scope.WebSitesList[index]; - console.log('Selected website:', $scope.selectedWebsite); - // Call the new GetWPSitesByDomain endpoint - var url = '/websites/GetWPSitesByDomain'; - var data = { - domain: $scope.selectedWebsite.domain - }; - - $http({ - method: 'POST', - url: url, - data: JSON.stringify(data), - headers: { - 'Content-Type': 'application/json', - 'X-CSRFToken': getCookie('csrftoken') - } - }).then(function(response) { - console.log('WP Sites Response:', response); + if (!$scope.selectedWebsite.wp_sites) { + var url = '/websites/fetchWPDetails'; + var data = { + domain: $scope.selectedWebsite.domain, + websiteName: $scope.selectedWebsite.domain + }; - if (response.data && response.data.status === 1) { - try { - // Display the data in an alert - var wpSites = response.data.data; - var alertMessage = 'WordPress Sites for ' + $scope.selectedWebsite.domain + ':\n\n'; - - wpSites.forEach(function(site, index) { - alertMessage += 'Site ' + (index + 1) + ':\n'; - alertMessage += 'Title: ' + site.title + '\n'; - alertMessage += 'URL: ' + site.url + '\n'; - alertMessage += 'Version: ' + site.version + '\n'; - alertMessage += 'PHP Version: ' + site.phpVersion + '\n'; - alertMessage += 'Active Plugins: ' + site.activePlugins + '\n'; - alertMessage += 'Theme: ' + site.theme + '\n'; - alertMessage += 'Debugging: ' + (site.debugging ? 'Enabled' : 'Disabled') + '\n'; - alertMessage += 'Search Index: ' + (site.searchIndex ? 'Enabled' : 'Disabled') + '\n'; - alertMessage += 'Maintenance Mode: ' + (site.maintenanceMode ? 'Enabled' : 'Disabled') + '\n'; - alertMessage += 'Password Protection: ' + (site.passwordProtection ? 'Enabled' : 'Disabled') + '\n\n'; - }); - - alert(alertMessage); - - // Update the UI with the data - $scope.selectedWebsite.wp_sites = wpSites; - $scope.selectedWebsite.showWPSites = true; - } catch (e) { - console.error('Error processing WordPress data:', e); - alert('Error processing WordPress data: ' + e.message); - $scope.selectedWebsite.showWPSites = false; - $scope.selectedWebsite.wp_sites = []; + $http({ + method: 'POST', + url: url, + data: $.param(data), + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'X-CSRFToken': getCookie('csrftoken') } - } else { - console.error('Error fetching WordPress sites:', response.data.error_message); - alert('Error fetching WordPress sites: ' + response.data.error_message); - $scope.selectedWebsite.showWPSites = false; - $scope.selectedWebsite.wp_sites = []; - } - }, function(error) { - console.error('Error fetching WordPress sites:', error); - alert('Error fetching WordPress sites: ' + error.message); - $scope.selectedWebsite.showWPSites = false; - $scope.selectedWebsite.wp_sites = []; - }); + }).then(function(response) { + console.log('WP Details Response:', response); + + // Check if response is HTML (login page) + if (typeof response.data === 'string' && response.data.includes('')) { + console.log('Received HTML response, redirecting to login'); + window.location.href = '/login'; + return; + } + + if (response.data && response.data.status === 1) { + try { + // If single site, wrap in array + var sites = Array.isArray(response.data.data) ? response.data.data : [response.data.data]; + + $scope.selectedWebsite.wp_sites = sites.map(function(site) { + return { + id: site.id || $scope.selectedWebsite.domain, + title: site.title || site.domain || $scope.selectedWebsite.domain, + url: site.url || 'http://' + $scope.selectedWebsite.domain, + version: site.version || 'Unknown', + phpVersion: site.php_version || 'Unknown', + theme: site.theme || 'Unknown', + activePlugins: site.active_plugins || 0, + searchIndex: site.search_index === 'enabled', + debugging: site.debugging === 'enabled', + passwordProtection: site.password_protection === 'enabled', + maintenanceMode: site.maintenance_mode === 'enabled' + }; + }); + $scope.selectedWebsite.showWPSites = true; + } catch (e) { + console.error('Error processing WordPress data:', e); + // Create default site on error + $scope.selectedWebsite.wp_sites = [{ + id: $scope.selectedWebsite.domain, + title: $scope.selectedWebsite.domain, + url: 'http://' + $scope.selectedWebsite.domain, + version: 'Unknown', + phpVersion: 'Unknown', + theme: 'Unknown', + activePlugins: 0, + searchIndex: false, + debugging: false, + passwordProtection: false, + maintenanceMode: false + }]; + $scope.selectedWebsite.showWPSites = true; + } + } else { + // Create default site if no data + $scope.selectedWebsite.wp_sites = [{ + id: $scope.selectedWebsite.domain, + title: $scope.selectedWebsite.domain, + url: 'http://' + $scope.selectedWebsite.domain, + version: 'Unknown', + phpVersion: 'Unknown', + theme: 'Unknown', + activePlugins: 0, + searchIndex: false, + debugging: false, + passwordProtection: false, + maintenanceMode: false + }]; + $scope.selectedWebsite.showWPSites = true; + } + }).catch(function(error) { + console.error('WP Details Error:', error); + // Create default site on error + $scope.selectedWebsite.wp_sites = [{ + id: $scope.selectedWebsite.domain, + title: $scope.selectedWebsite.domain, + url: 'http://' + $scope.selectedWebsite.domain, + version: 'Unknown', + phpVersion: 'Unknown', + theme: 'Unknown', + activePlugins: 0, + searchIndex: false, + debugging: false, + passwordProtection: false, + maintenanceMode: false + }]; + $scope.selectedWebsite.showWPSites = true; + }); + } else { + $scope.selectedWebsite.showWPSites = !$scope.selectedWebsite.showWPSites; + } }; $scope.visitSite = function(url) { @@ -12176,72 +6649,110 @@ app.controller('manageAliasController', function ($scope, $http, $timeout, $wind } $scope.showWPSites = function(index) { - console.log('showWPSites called with index:', index); - console.log('Current WebSitesList:', $scope.WebSitesList); - $scope.selectedWebsite = $scope.WebSitesList[index]; - console.log('Selected website:', $scope.selectedWebsite); - // Call the new GetWPSitesByDomain endpoint - var url = '/websites/GetWPSitesByDomain'; + if (!$scope.selectedWebsite.wp_sites) { + var url = '/websites/fetchWPDetails'; var data = { - domain: $scope.selectedWebsite.domain + domain: $scope.selectedWebsite.domain, + websiteName: $scope.selectedWebsite.domain }; - - $http({ - method: 'POST', - url: url, - data: JSON.stringify(data), + + $http({ + method: 'POST', + url: url, + data: $.param(data), headers: { - 'Content-Type': 'application/json', + 'Content-Type': 'application/x-www-form-urlencoded', 'X-CSRFToken': getCookie('csrftoken') } - }).then(function(response) { - console.log('WP Sites Response:', response); - - if (response.data && response.data.status === 1) { - try { - // Display the data in an alert - var wpSites = response.data.data; - var alertMessage = 'WordPress Sites for ' + $scope.selectedWebsite.domain + ':\n\n'; - - wpSites.forEach(function(site, index) { - alertMessage += 'Site ' + (index + 1) + ':\n'; - alertMessage += 'Title: ' + site.title + '\n'; - alertMessage += 'URL: ' + site.url + '\n'; - alertMessage += 'Version: ' + site.version + '\n'; - alertMessage += 'PHP Version: ' + site.phpVersion + '\n'; - alertMessage += 'Active Plugins: ' + site.activePlugins + '\n'; - alertMessage += 'Theme: ' + site.theme + '\n'; - alertMessage += 'Debugging: ' + (site.debugging ? 'Enabled' : 'Disabled') + '\n'; - alertMessage += 'Search Index: ' + (site.searchIndex ? 'Enabled' : 'Disabled') + '\n'; - alertMessage += 'Maintenance Mode: ' + (site.maintenanceMode ? 'Enabled' : 'Disabled') + '\n'; - alertMessage += 'Password Protection: ' + (site.passwordProtection ? 'Enabled' : 'Disabled') + '\n\n'; - }); - - alert(alertMessage); - - // Update the UI with the data - $scope.selectedWebsite.wp_sites = wpSites; - $scope.selectedWebsite.showWPSites = true; - } catch (e) { - console.error('Error processing WordPress data:', e); - alert('Error processing WordPress data: ' + e.message); - $scope.selectedWebsite.showWPSites = false; - $scope.selectedWebsite.wp_sites = []; + }).then(function(response) { + console.log('WP Details Response:', response); + + // Check if response is HTML (login page) + if (typeof response.data === 'string' && response.data.includes('')) { + console.log('Received HTML response, redirecting to login'); + window.location.href = '/login'; + return; } + + if (response.data && response.data.status === 1) { + try { + // If single site, wrap in array + var sites = Array.isArray(response.data.data) ? response.data.data : [response.data.data]; + + $scope.selectedWebsite.wp_sites = sites.map(function(site) { + return { + id: site.id || $scope.selectedWebsite.domain, + title: site.title || site.domain || $scope.selectedWebsite.domain, + url: site.url || 'http://' + $scope.selectedWebsite.domain, + version: site.version || 'Unknown', + phpVersion: site.php_version || 'Unknown', + theme: site.theme || 'Unknown', + activePlugins: site.active_plugins || 0, + searchIndex: site.search_index === 'enabled', + debugging: site.debugging === 'enabled', + passwordProtection: site.password_protection === 'enabled', + maintenanceMode: site.maintenance_mode === 'enabled' + }; + }); + $scope.selectedWebsite.showWPSites = true; + } catch(e) { + console.error('Error processing WordPress data:', e); + // Create default site on error + $scope.selectedWebsite.wp_sites = [{ + id: $scope.selectedWebsite.domain, + title: $scope.selectedWebsite.domain, + url: 'http://' + $scope.selectedWebsite.domain, + version: 'Unknown', + phpVersion: 'Unknown', + theme: 'Unknown', + activePlugins: 0, + searchIndex: false, + debugging: false, + passwordProtection: false, + maintenanceMode: false + }]; + $scope.selectedWebsite.showWPSites = true; + } } else { - console.error('Error fetching WordPress sites:', response.data.error_message); - alert('Error fetching WordPress sites: ' + response.data.error_message); - $scope.selectedWebsite.showWPSites = false; - $scope.selectedWebsite.wp_sites = []; - } - }, function(error) { - console.error('Error fetching WordPress sites:', error); - alert('Error fetching WordPress sites: ' + error.message); - $scope.selectedWebsite.showWPSites = false; - $scope.selectedWebsite.wp_sites = []; - }); + // Create default site if no data + $scope.selectedWebsite.wp_sites = [{ + id: $scope.selectedWebsite.domain, + title: $scope.selectedWebsite.domain, + url: 'http://' + $scope.selectedWebsite.domain, + version: 'Unknown', + phpVersion: 'Unknown', + theme: 'Unknown', + activePlugins: 0, + searchIndex: false, + debugging: false, + passwordProtection: false, + maintenanceMode: false + }]; + $scope.selectedWebsite.showWPSites = true; + } + }).catch(function(error) { + console.error('WP Details Error:', error); + // Create default site on error + $scope.selectedWebsite.wp_sites = [{ + id: $scope.selectedWebsite.domain, + title: $scope.selectedWebsite.domain, + url: 'http://' + $scope.selectedWebsite.domain, + version: 'Unknown', + phpVersion: 'Unknown', + theme: 'Unknown', + activePlugins: 0, + searchIndex: false, + debugging: false, + passwordProtection: false, + maintenanceMode: false + }]; + $scope.selectedWebsite.showWPSites = true; + }); + } else { + $scope.selectedWebsite.showWPSites = !$scope.selectedWebsite.showWPSites; + } }; $scope.updateSetting = function(wp, setting) { @@ -13631,8 +8142,8 @@ app.controller('installMauticCTRL', function ($scope, $http, $timeout) { $scope.installationDetailsForm = true; $scope.installationProgress = false; - $scope.installationFailed = false; - $scope.installationSuccessfull = true; + $scope.installationFailed = true; + $scope.installationSuccessfull = false; $scope.couldNotConnect = true; $scope.wpInstallLoading = true; $scope.goBackDisable = false; diff --git a/websiteFunctions/urls.py b/websiteFunctions/urls.py index 285f16931..9469ca672 100755 --- a/websiteFunctions/urls.py +++ b/websiteFunctions/urls.py @@ -194,6 +194,4 @@ urlpatterns = [ # Catch all for domains path('/', views.launchChild, name='launchChild'), path('', views.domain, name='domain'), - - path(r'GetWPSitesByDomain', views.GetWPSitesByDomain, name='GetWPSitesByDomain'), ] diff --git a/websiteFunctions/views.py b/websiteFunctions/views.py index 70e6b3dc4..bcefc8a77 100755 --- a/websiteFunctions/views.py +++ b/websiteFunctions/views.py @@ -1841,21 +1841,4 @@ def Dockersitehome(request, dockerapp): wm = WebsiteManager(dockerapp) return wm.Dockersitehome(request, userID, None) except KeyError: - return redirect(loadLoginPage) - -def GetWPSitesByDomain(request): - try: - userID = request.session['userID'] - data = json.loads(request.body) - domain = data['domain'] - - wm = WebsiteManager() - response = wm.GetWPSitesByDomain(userID, data) - - return response - except KeyError: - return redirect(reverse('login')) - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) \ No newline at end of file + return redirect(loadLoginPage) \ No newline at end of file diff --git a/websiteFunctions/website.py b/websiteFunctions/website.py index 7b5f3402c..e2e6c08e6 100755 --- a/websiteFunctions/website.py +++ b/websiteFunctions/website.py @@ -1235,7 +1235,25 @@ class WebsiteManager: admin = Administrator.objects.get(pk=userID) backupid = data['backupid'] - DesSiteID = data['DesSiteID'] + DesSiteID = data['DesSite'] + + # try: + # + # bwp = WPSites.objects.get(pk=int(backupid)) + # + # if ACLManager.checkOwnership(bwp.owner.domain, admin, currentACL) == 1: + # pass + # else: + # return ACLManager.loadError() + # + # except: + # pass + # + # dwp = WPSites.objects.get(pk=int(DesSiteID)) + # if ACLManager.checkOwnership(dwp.owner.domain, admin, currentACL) == 1: + # pass + # else: + # return ACLManager.loadError() Domain = data['Domain'] @@ -1931,7 +1949,7 @@ class WebsiteManager: if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) != 1: return ACLManager.loadError() - + # Get PHP version and path Webobj = Websites.objects.get(pk=wpsite.owner_id) Vhuser = Webobj.externalApp @@ -1972,60 +1990,1494 @@ AuthUserFile {htpasswd} Require valid-user""" with open(htaccess, 'w') as f: f.write(htaccess_content) - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) + else: + # Disable password protection + if os.path.exists(path): + import shutil + shutil.rmtree(path) + htaccess = f'{wpsite.path}/.htaccess' + if os.path.exists(htaccess): + os.remove(htaccess) + return JsonResponse({'status': 1, 'error_message': 'None'}) + elif setting == 'maintenance-mode': + if value: + command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp maintenance-mode activate --skip-plugins --skip-themes --path={wpsite.path}' + else: + command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp maintenance-mode deactivate --skip-plugins --skip-themes --path={wpsite.path}' + else: + return JsonResponse({'status': 0, 'error_message': 'Invalid setting type'}) + + result = ProcessUtilities.outputExecutioner(command) + if result.find('Error:') > -1: + return JsonResponse({'status': 0, 'error_message': result}) + + return JsonResponse({'status': 1, 'error_message': 'None'}) except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) + return JsonResponse({'status': 0, 'error_message': str(msg)}) - def GetWPSitesByDomain(self, userID=None, data=None): + def submitWorpressCreation(self, userID=None, data=None): try: currentACL = ACLManager.loadedACL(userID) admin = Administrator.objects.get(pk=userID) - - domain = data['domain'] - website = Websites.objects.get(domain=domain) - - if ACLManager.checkOwnership(domain, admin, currentACL) == 1: + + extraArgs = {} + extraArgs['currentACL'] = currentACL + extraArgs['adminID'] = admin.pk + extraArgs['domainName'] = data['domain'] + extraArgs['WPVersion'] = data['WPVersion'] + extraArgs['blogTitle'] = data['title'] + try: + extraArgs['pluginbucket'] = data['pluginbucket'] + except: + extraArgs['pluginbucket'] = '-1' + extraArgs['adminUser'] = data['adminUser'] + extraArgs['PasswordByPass'] = data['PasswordByPass'] + extraArgs['adminPassword'] = data['PasswordByPass'] + extraArgs['adminEmail'] = data['Email'] + extraArgs['updates'] = data['AutomaticUpdates'] + extraArgs['Plugins'] = data['Plugins'] + extraArgs['Themes'] = data['Themes'] + extraArgs['websiteOwner'] = data['websiteOwner'] + extraArgs['package'] = data['package'] + extraArgs['home'] = data['home'] + extraArgs['apacheBackend'] = data['apacheBackend'] + try: + extraArgs['path'] = data['path'] + if extraArgs['path'] == '': + extraArgs['home'] = '1' + except: + pass + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + background = ApplicationInstaller('wordpressInstallNew', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def submitWebsiteCreation(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + + domain = data['domainName'] + adminEmail = data['adminEmail'] + phpSelection = data['phpSelection'] + packageName = data['package'] + websiteOwner = data['websiteOwner'].lower() + + if data['domainName'].find("cyberpanel.website") > -1: + url = "https://platform.cyberpersons.com/CyberpanelAdOns/CreateDomain" + + domain_data = { + "name": "test-domain", + "IP": ACLManager.GetServerIP(), + "domain": data['domainName'] + } + + import requests + response = requests.post(url, data=json.dumps(domain_data)) + domain_status = response.json()['status'] + + if domain_status == 0: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': response.json()['error_message']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + loggedUser = Administrator.objects.get(pk=userID) + newOwner = Administrator.objects.get(userName=websiteOwner) + + if ACLManager.currentContextPermission(currentACL, 'createWebsite') == 0: + return ACLManager.loadErrorJson('createWebSiteStatus', 0) + + if ACLManager.checkOwnerProtection(currentACL, loggedUser, newOwner) == 0: + return ACLManager.loadErrorJson('createWebSiteStatus', 0) + + if currentACL['admin'] == 0: + if ACLManager.CheckDomainBlackList(domain) == 0: + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Blacklisted domain."} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + if not validators.domain(domain): + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Invalid domain."} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + if not validators.email(adminEmail) or adminEmail.find('--') > -1: + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Invalid email."} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + try: + HA = data['HA'] + externalApp = 'nobody' + except: + externalApp = "".join(re.findall("[a-zA-Z]+", domain))[:5] + str(randint(1000, 9999)) + + try: + counter = 0 + while 1: + tWeb = Websites.objects.get(externalApp=externalApp) + externalApp = '%s%s' % (tWeb.externalApp, str(counter)) + counter = counter + 1 + except: + pass + + tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + + try: + apacheBackend = str(data['apacheBackend']) + except: + apacheBackend = "0" + + try: + mailDomain = str(data['mailDomain']) + except: + mailDomain = "1" + + import pwd + counter = 0 + + ## Create Configurations + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " createVirtualHost --virtualHostName " + domain + \ + " --administratorEmail " + adminEmail + " --phpVersion '" + phpSelection + \ + "' --virtualHostUser " + externalApp + " --ssl " + str(1) + " --dkimCheck " \ + + str(1) + " --openBasedir " + str(data['openBasedir']) + \ + ' --websiteOwner "' + websiteOwner + '" --package "' + packageName + '" --tempStatusPath ' + tempStatusPath + " --apache " + apacheBackend + " --mailDomain %s" % ( + mailDomain) + + ProcessUtilities.popenExecutioner(execPath) + time.sleep(2) + + data_ret = {'status': 1, 'createWebSiteStatus': 1, 'error_message': "None", + 'tempStatusPath': tempStatusPath, 'LinuxUser': externalApp} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def submitDomainCreation(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + try: + alias = data['alias'] + except: + alias = 0 + + masterDomain = data['masterDomain'] + domain = data['domainName'] + + + if alias == 0: + phpSelection = data['phpSelection'] + path = data['path'] + else: + + ### if master website have apache then create this sub-domain also as ols + apache + + apachePath = ApacheVhost.configBasePath + masterDomain + '.conf' + + if os.path.exists(apachePath): + data['apacheBackend'] = 1 + + phpSelection = Websites.objects.get(domain=masterDomain).phpSelection + + tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + + if not validators.domain(domain): + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Invalid domain."} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + if data['domainName'].find("cyberpanel.website") > -1: + url = "https://platform.cyberpersons.com/CyberpanelAdOns/CreateDomain" + + domain_data = { + "name": "test-domain", + "IP": ACLManager.GetServerIP(), + "domain": data['domainName'] + } + + import requests + response = requests.post(url, data=json.dumps(domain_data)) + domain_status = response.json()['status'] + + if domain_status == 0: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': response.json()['error_message']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + if ACLManager.checkOwnership(masterDomain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('createWebSiteStatus', 0) + + if data['path'].find('..') > -1: + return ACLManager.loadErrorJson('createWebSiteStatus', 0) + + if currentACL['admin'] != 1: + data['openBasedir'] = 1 + + if alias == 0: + + if len(path) > 0: + path = path.lstrip("/") + path = "/home/" + masterDomain + "/" + path + else: + path = "/home/" + masterDomain + "/" + domain + else: + path = f'/home/{masterDomain}/public_html' + + try: + apacheBackend = str(data['apacheBackend']) + except: + apacheBackend = "0" + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + + execPath = execPath + " createDomain --masterDomain " + masterDomain + " --virtualHostName " + domain + \ + " --phpVersion '" + phpSelection + "' --ssl " + str(1) + " --dkimCheck " + str(1) \ + + " --openBasedir " + str(data['openBasedir']) + ' --path ' + path + ' --websiteOwner ' \ + + admin.userName + ' --tempStatusPath ' + tempStatusPath + " --apache " + apacheBackend + f' --aliasDomain {str(alias)}' + + ProcessUtilities.popenExecutioner(execPath) + time.sleep(2) + + data_ret = {'status': 1, 'createWebSiteStatus': 1, 'error_message': "None", + 'tempStatusPath': tempStatusPath} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def fetchDomains(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + masterDomain = data['masterDomain'] + + try: + alias = data['alias'] + except: + alias = 0 + + if ACLManager.checkOwnership(masterDomain, admin, currentACL) == 1: pass else: return ACLManager.loadErrorJson('fetchStatus', 0) - - # Get all WordPress sites for this website + + cdManager = ChildDomainManager(masterDomain) + json_data = cdManager.findChildDomainsJson(alias) + + final_json = json.dumps({'status': 1, 'fetchStatus': 1, 'error_message': "None", "data": json_data}) + return HttpResponse(final_json) + + except BaseException as msg: + final_dic = {'status': 0, 'fetchStatus': 0, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def searchWebsites(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + try: + json_data = self.searchWebsitesJson(currentACL, userID, data['patternAdded']) + except BaseException as msg: + tempData = {} + tempData['page'] = 1 + return self.getFurtherAccounts(userID, tempData) + + pagination = self.websitePagination(currentACL, userID) + final_dic = {'status': 1, 'listWebSiteStatus': 1, 'error_message': "None", "data": json_data, + 'pagination': pagination} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + except BaseException as msg: + dic = {'status': 1, 'listWebSiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def searchChilds(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + + websites = ACLManager.findWebsiteObjects(currentACL, userID) + childDomains = [] + + for web in websites: + for child in web.childdomains_set.filter(domain__istartswith=data['patternAdded']): + childDomains.append(child) + + json_data = self.findChildsListJson(childDomains) + + final_dic = {'status': 1, 'listWebSiteStatus': 1, 'error_message': "None", "data": json_data} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + except BaseException as msg: + dic = {'status': 1, 'listWebSiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def getFurtherAccounts(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + pageNumber = int(data['page']) + json_data = self.findWebsitesJson(currentACL, userID, pageNumber) + pagination = self.websitePagination(currentACL, userID) + final_dic = {'status': 1, 'listWebSiteStatus': 1, 'error_message': "None", "data": json_data, + 'pagination': pagination} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + except BaseException as msg: + dic = {'status': 1, 'listWebSiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def fetchWebsitesList(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + pageNumber = int(data['page']) + recordsToShow = int(data['recordsToShow']) + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(f'Fetch sites step 1..') + + endPageNumber, finalPageNumber = self.recordsPointer(pageNumber, recordsToShow) + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(f'Fetch sites step 2..') + + websites = ACLManager.findWebsiteObjects(currentACL, userID) + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(f'Fetch sites step 3..') + + pagination = self.getPagination(len(websites), recordsToShow) + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(f'Fetch sites step 4..') + + json_data = self.findWebsitesListJson(websites[finalPageNumber:endPageNumber]) + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(f'Fetch sites step 5..') + + final_dic = {'status': 1, 'listWebSiteStatus': 1, 'error_message': "None", "data": json_data, + 'pagination': pagination} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + except BaseException as msg: + dic = {'status': 1, 'listWebSiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def fetchChildDomainsMain(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + pageNumber = int(data['page']) + recordsToShow = int(data['recordsToShow']) + + endPageNumber, finalPageNumber = self.recordsPointer(pageNumber, recordsToShow) + websites = ACLManager.findWebsiteObjects(currentACL, userID) + childDomains = [] + + for web in websites: + for child in web.childdomains_set.filter(alais=0): + if child.domain == f'mail.{web.domain}': + pass + else: + childDomains.append(child) + + pagination = self.getPagination(len(childDomains), recordsToShow) + json_data = self.findChildsListJson(childDomains[finalPageNumber:endPageNumber]) + + final_dic = {'status': 1, 'listWebSiteStatus': 1, 'error_message': "None", "data": json_data, + 'pagination': pagination} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + except BaseException as msg: + dic = {'status': 1, 'listWebSiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def findWebsitesListJson(self, websites): + try: + ipFile = "/etc/cyberpanel/machineIP" + f = open(ipFile) + ipData = f.read() + ipAddress = ipData.split('\n', 1)[0] + except BaseException as msg: + logging.CyberCPLogFileWriter.writeToFile("Failed to read machine IP, error:" + str(msg)) + ipAddress = "192.168.100.1" + + json_data = [] + + for website in websites: wp_sites = [] - for wp in website.wp_sites.all(): - site_data = { + try: + wp_sites = WPSites.objects.filter(owner=website) + wp_sites = [{ 'id': wp.id, 'title': wp.title, - 'url': wp.url, - 'version': wp.version, - 'phpVersion': wp.phpVersion, - 'activePlugins': wp.activePlugins, - 'theme': wp.theme, - 'debugging': wp.debugging, - 'searchIndex': wp.searchIndex, - 'maintenanceMode': wp.maintenanceMode, - 'passwordProtection': wp.passwordProtection - } - wp_sites.append(site_data) - - data_ret = {'status': 1, 'data': wp_sites} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except Websites.DoesNotExist: - data_ret = {'status': 0, 'error_message': 'Website not found'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) + 'url': wp.FinalURL, + 'version': wp.version if hasattr(wp, 'version') else 'Unknown', + 'phpVersion': wp.phpVersion if hasattr(wp, 'phpVersion') else 'Unknown' + } for wp in wp_sites] + except: + pass + + # Calculate disk usage + DiskUsage, DiskUsagePercentage, bwInMB, bwUsage = virtualHostUtilities.FindStats(website) + diskUsed = "%sMB" % str(DiskUsage) + + # Convert numeric state to text + state = "Active" if website.state == 1 else "Suspended" + + json_data.append({ + 'domain': website.domain, + 'adminEmail': website.adminEmail, + 'phpVersion': website.phpSelection, + 'state': state, + 'ipAddress': ipAddress, + 'package': website.package.packageName, + 'admin': website.admin.userName, + 'wp_sites': wp_sites, + 'diskUsed': diskUsed + }) + return json.dumps(json_data) + + + + def findDockersitesListJson(self, Dockersite): + + json_data = "[" + checker = 0 + + try: + ipFile = "/etc/cyberpanel/machineIP" + f = open(ipFile) + ipData = f.read() + ipAddress = ipData.split('\n', 1)[0] except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} + logging.CyberCPLogFileWriter.writeToFile("Failed to read machine IP, error:" + str(msg)) + ipAddress = "192.168.100.1" + + from plogical.phpUtilities import phpUtilities + for items in Dockersite: + website = Websites.objects.get(pk=items.admin.pk) + vhFile = f'/usr/local/lsws/conf/vhosts/{website.domain}/vhost.conf' + + try: + PHPVersionActual = phpUtilities.WrapGetPHPVersionFromFileToGetVersionWithPHP(website) + except: + PHPVersionActual = 'PHP 8.1' + + + if items.state == 0: + state = "Suspended" + else: + state = "Active" + + dpkg = PackageAssignment.objects.get(user=website.admin) + + + dic = {'id':items.pk, 'domain': website.domain, 'adminEmail': website.adminEmail, 'ipAddress': ipAddress, + 'admin': website.admin.userName, 'package': dpkg.package.Name, 'state': state, + 'CPU': int(items.CPUsMySQL)+int(items.CPUsSite), 'Ram': int(items.MemorySite)+int(items.MemoryMySQL), 'phpVersion': PHPVersionActual } + + if checker == 0: + json_data = json_data + json.dumps(dic) + checker = 1 + else: + json_data = json_data + ',' + json.dumps(dic) + + json_data = json_data + ']' + + return json_data + + def findChildsListJson(self, childs): + + json_data = "[" + checker = 0 + + try: + ipFile = "/etc/cyberpanel/machineIP" + f = open(ipFile) + ipData = f.read() + ipAddress = ipData.split('\n', 1)[0] + except BaseException as msg: + logging.CyberCPLogFileWriter.writeToFile("Failed to read machine IP, error:" + str(msg)) + ipAddress = "192.168.100.1" + + for items in childs: + + dic = {'domain': items.domain, 'masterDomain': items.master.domain, 'adminEmail': items.master.adminEmail, + 'ipAddress': ipAddress, + 'admin': items.master.admin.userName, 'package': items.master.package.packageName, + 'path': items.path} + + if checker == 0: + json_data = json_data + json.dumps(dic) + checker = 1 + else: + json_data = json_data + ',' + json.dumps(dic) + + json_data = json_data + ']' + + return json_data + + def recordsPointer(self, page, toShow): + finalPageNumber = ((page * toShow)) - toShow + endPageNumber = finalPageNumber + toShow + return endPageNumber, finalPageNumber + + def getPagination(self, records, toShow): + pages = float(records) / float(toShow) + + pagination = [] + counter = 1 + + if pages <= 1.0: + pages = 1 + pagination.append(counter) + else: + pages = ceil(pages) + finalPages = int(pages) + 1 + + for i in range(1, finalPages): + pagination.append(counter) + counter = counter + 1 + + return pagination + + def submitWebsiteDeletion(self, userID=None, data=None): + try: + if data['websiteName'].find("cyberpanel.website") > -1: + url = "https://platform.cyberpersons.com/CyberpanelAdOns/DeleteDomain" + + domain_data = { + "name": "test-domain", + "IP": ACLManager.GetServerIP(), + "domain": data['websiteName'] + } + + import requests + response = requests.post(url, data=json.dumps(domain_data)) + + currentACL = ACLManager.loadedACL(userID) + if ACLManager.currentContextPermission(currentACL, 'deleteWebsite') == 0: + return ACLManager.loadErrorJson('websiteDeleteStatus', 0) + + websiteName = data['websiteName'] + + admin = Administrator.objects.get(pk=userID) + if ACLManager.checkOwnership(websiteName, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('websiteDeleteStatus', 0) + + ## Deleting master domain + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " deleteVirtualHostConfigurations --virtualHostName " + websiteName + ProcessUtilities.popenExecutioner(execPath) + + ### delete site from dgdrive backups + + try: + + from websiteFunctions.models import GDriveSites + GDriveSites.objects.filter(domain=websiteName).delete() + except: + pass + + data_ret = {'status': 1, 'websiteDeleteStatus': 1, 'error_message': "None"} json_data = json.dumps(data_ret) return HttpResponse(json_data) + except BaseException as msg: + data_ret = {'status': 0, 'websiteDeleteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def submitDomainDeletion(self, userID=None, data=None): + try: + + if data['websiteName'].find("cyberpanel.website") > -1: + url = "https://platform.cyberpersons.com/CyberpanelAdOns/DeleteDomain" + + domain_data = { + "name": "test-domain", + "IP": ACLManager.GetServerIP(), + "domain": data['websiteName'] + } + + import requests + response = requests.post(url, data=json.dumps(domain_data)) + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + websiteName = data['websiteName'] + + try: + DeleteDocRoot = int(data['DeleteDocRoot']) + except: + DeleteDocRoot = 0 + + if ACLManager.checkOwnership(websiteName, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('websiteDeleteStatus', 0) + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " deleteDomain --virtualHostName " + websiteName + ' --DeleteDocRoot %s' % ( + str(DeleteDocRoot)) + ProcessUtilities.outputExecutioner(execPath) + + data_ret = {'status': 1, 'websiteDeleteStatus': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'websiteDeleteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def submitWebsiteStatus(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + if ACLManager.currentContextPermission(currentACL, 'suspendWebsite') == 0: + return ACLManager.loadErrorJson('websiteStatus', 0) + + websiteName = data['websiteName'] + state = data['state'] + + website = Websites.objects.get(domain=websiteName) + + admin = Administrator.objects.get(pk=userID) + if ACLManager.checkOwnership(websiteName, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('websiteStatus', 0) + + if state == "Suspend": + confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + websiteName + command = "mv " + confPath + " " + confPath + "-suspended" + ProcessUtilities.popenExecutioner(command) + + childDomains = website.childdomains_set.all() + + for items in childDomains: + confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + items.domain + command = "mv " + confPath + " " + confPath + "-suspended" + ProcessUtilities.executioner(command) + + installUtilities.reStartLiteSpeedSocket() + website.state = 0 + else: + confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + websiteName + + command = "mv " + confPath + "-suspended" + " " + confPath + ProcessUtilities.executioner(command) + + command = "chown -R " + "lsadm" + ":" + "lsadm" + " " + confPath + ProcessUtilities.popenExecutioner(command) + + childDomains = website.childdomains_set.all() + + for items in childDomains: + confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + items.domain + + command = "mv " + confPath + "-suspended" + " " + confPath + ProcessUtilities.executioner(command) + + command = "chown -R " + "lsadm" + ":" + "lsadm" + " " + confPath + ProcessUtilities.popenExecutioner(command) + + installUtilities.reStartLiteSpeedSocket() + website.state = 1 + + website.save() + + data_ret = {'websiteStatus': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + + data_ret = {'websiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def submitWebsiteModify(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + if ACLManager.currentContextPermission(currentACL, 'modifyWebsite') == 0: + return ACLManager.loadErrorJson('modifyStatus', 0) + + admin = Administrator.objects.get(pk=userID) + if ACLManager.checkOwnership(data['websiteToBeModified'], admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('websiteDeleteStatus', 0) + + packs = ACLManager.loadPackages(userID, currentACL) + admins = ACLManager.loadAllUsers(userID) + + ## Get packs name + + json_data = "[" + checker = 0 + + for items in packs: + dic = {"pack": items} + + if checker == 0: + json_data = json_data + json.dumps(dic) + checker = 1 + else: + json_data = json_data + ',' + json.dumps(dic) + + json_data = json_data + ']' + + ### Get admin names + + admin_data = "[" + checker = 0 + + for items in admins: + dic = {"adminNames": items} + + if checker == 0: + admin_data = admin_data + json.dumps(dic) + checker = 1 + else: + admin_data = admin_data + ',' + json.dumps(dic) + + admin_data = admin_data + ']' + + websiteToBeModified = data['websiteToBeModified'] + + modifyWeb = Websites.objects.get(domain=websiteToBeModified) + + email = modifyWeb.adminEmail + currentPack = modifyWeb.package.packageName + owner = modifyWeb.admin.userName + + data_ret = {'status': 1, 'modifyStatus': 1, 'error_message': "None", "adminEmail": email, + "packages": json_data, "current_pack": currentPack, "adminNames": admin_data, + 'currentAdmin': owner} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + + except BaseException as msg: + dic = {'status': 0, 'modifyStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def fetchWebsiteDataJSON(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + if ACLManager.currentContextPermission(currentACL, 'createWebsite') == 0: + return ACLManager.loadErrorJson('createWebSiteStatus', 0) + + packs = ACLManager.loadPackages(userID, currentACL) + admins = ACLManager.loadAllUsers(userID) + + ## Get packs name + + json_data = "[" + checker = 0 + + for items in packs: + dic = {"pack": items} + + if checker == 0: + json_data = json_data + json.dumps(dic) + checker = 1 + else: + json_data = json_data + ',' + json.dumps(dic) + + json_data = json_data + ']' + + ### Get admin names + + admin_data = "[" + checker = 0 + + for items in admins: + dic = {"adminNames": items} + + if checker == 0: + admin_data = admin_data + json.dumps(dic) + checker = 1 + else: + admin_data = admin_data + ',' + json.dumps(dic) + + admin_data = admin_data + ']' + + data_ret = {'status': 1, 'error_message': "None", + "packages": json_data, "adminNames": admin_data} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + + except BaseException as msg: + dic = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def saveWebsiteChanges(self, userID=None, data=None): + try: + domain = data['domain'] + package = data['packForWeb'] + email = data['email'] + phpVersion = data['phpVersion'] + newUser = data['admin'] + + currentACL = ACLManager.loadedACL(userID) + if ACLManager.currentContextPermission(currentACL, 'modifyWebsite') == 0: + return ACLManager.loadErrorJson('saveStatus', 0) + + admin = Administrator.objects.get(pk=userID) + if ACLManager.checkOwnership(domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('websiteDeleteStatus', 0) + + newOwner = Administrator.objects.get(userName=newUser) + if ACLManager.checkUserOwnerShip(currentACL, admin, newOwner) == 1: + pass + else: + return ACLManager.loadErrorJson('websiteDeleteStatus', 0) + + confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + domain + completePathToConfigFile = confPath + "/vhost.conf" + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " changePHP --phpVersion '" + phpVersion + "' --path " + completePathToConfigFile + ProcessUtilities.popenExecutioner(execPath) + + #### + + newOwner = Administrator.objects.get(userName=newUser) + + modifyWeb = Websites.objects.get(domain=domain) + webpack = Package.objects.get(packageName=package) + + modifyWeb.package = webpack + modifyWeb.adminEmail = email + modifyWeb.phpSelection = phpVersion + modifyWeb.admin = newOwner + + modifyWeb.save() + + ## Fix https://github.com/usmannasir/cyberpanel/issues/998 + + # from plogical.IncScheduler import IncScheduler + # isPU = IncScheduler('CalculateAndUpdateDiskUsage', {}) + # isPU.start() + + command = '/usr/local/CyberCP/bin/python /usr/local/CyberCP/plogical/IncScheduler.py UpdateDiskUsageForce' + ProcessUtilities.outputExecutioner(command) + + ## + + data_ret = {'status': 1, 'saveStatus': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'saveStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def loadDomainHome(self, request=None, userID=None, data=None): + + if Websites.objects.filter(domain=self.domain).exists(): + + currentACL = ACLManager.loadedACL(userID) + website = Websites.objects.get(domain=self.domain) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + Data = {} + + marketingStatus = emACL.checkIfEMEnabled(admin.userName) + + Data['marketingStatus'] = marketingStatus + Data['ftpTotal'] = website.package.ftpAccounts + Data['ftpUsed'] = website.users_set.all().count() + + Data['databasesUsed'] = website.databases_set.all().count() + Data['databasesTotal'] = website.package.dataBases + + Data['domain'] = self.domain + + DiskUsage, DiskUsagePercentage, bwInMB, bwUsage = virtualHostUtilities.FindStats(website) + + ## bw usage calculations + + Data['bwInMBTotal'] = website.package.bandwidth + Data['bwInMB'] = bwInMB + Data['bwUsage'] = bwUsage + + if DiskUsagePercentage > 100: + DiskUsagePercentage = 100 + + Data['diskUsage'] = DiskUsagePercentage + Data['diskInMB'] = DiskUsage + Data['diskInMBTotal'] = website.package.diskSpace + + Data['phps'] = PHPManager.findPHPVersions() + + servicePath = '/home/cyberpanel/postfix' + if os.path.exists(servicePath): + Data['email'] = 1 + else: + Data['email'] = 0 + + ## Getting SSL Information + try: + import OpenSSL + from datetime import datetime + filePath = '/etc/letsencrypt/live/%s/fullchain.pem' % (self.domain) + x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, + open(filePath, 'r').read()) + expireData = x509.get_notAfter().decode('ascii') + finalDate = datetime.strptime(expireData, '%Y%m%d%H%M%SZ') + + now = datetime.now() + diff = finalDate - now + Data['viewSSL'] = 1 + Data['days'] = str(diff.days) + Data['authority'] = x509.get_issuer().get_components()[1][1].decode('utf-8') + + if Data['authority'] == 'Denial': + Data['authority'] = '%s has SELF-SIGNED SSL.' % (self.domain) + else: + Data['authority'] = '%s has SSL from %s.' % (self.domain, Data['authority']) + + except BaseException as msg: + Data['viewSSL'] = 0 + logging.CyberCPLogFileWriter.writeToFile(str(msg)) + + servicePath = '/home/cyberpanel/pureftpd' + if os.path.exists(servicePath): + Data['ftp'] = 1 + else: + Data['ftp'] = 0 + + proc = httpProc(request, 'websiteFunctions/website.html', Data) + return proc.render() + else: + proc = httpProc(request, 'websiteFunctions/website.html', + {"error": 1, "domain": "This domain does not exists."}) + return proc.render() + + def launchChild(self, request=None, userID=None, data=None): + + if ChildDomains.objects.filter(domain=self.childDomain).exists(): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + website = Websites.objects.get(domain=self.domain) + + Data = {} + + Data['ftpTotal'] = website.package.ftpAccounts + Data['ftpUsed'] = website.users_set.all().count() + + Data['databasesUsed'] = website.databases_set.all().count() + Data['databasesTotal'] = website.package.dataBases + + Data['domain'] = self.domain + Data['childDomain'] = self.childDomain + + DiskUsage, DiskUsagePercentage, bwInMB, bwUsage = virtualHostUtilities.FindStats(website) + + ## bw usage calculations + + Data['bwInMBTotal'] = website.package.bandwidth + Data['bwInMB'] = bwInMB + Data['bwUsage'] = bwUsage + + if DiskUsagePercentage > 100: + DiskUsagePercentage = 100 + + Data['diskUsage'] = DiskUsagePercentage + Data['diskInMB'] = DiskUsage + Data['diskInMBTotal'] = website.package.diskSpace + + Data['phps'] = PHPManager.findPHPVersions() + + servicePath = '/home/cyberpanel/postfix' + if os.path.exists(servicePath): + Data['email'] = 1 + else: + Data['email'] = 0 + + servicePath = '/home/cyberpanel/pureftpd' + if os.path.exists(servicePath): + Data['ftp'] = 1 + else: + Data['ftp'] = 0 + + ## Getting SSL Information + try: + import OpenSSL + from datetime import datetime + filePath = '/etc/letsencrypt/live/%s/fullchain.pem' % (self.childDomain) + x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, + open(filePath, 'r').read()) + expireData = x509.get_notAfter().decode('ascii') + finalDate = datetime.strptime(expireData, '%Y%m%d%H%M%SZ') + + now = datetime.now() + diff = finalDate - now + Data['viewSSL'] = 1 + Data['days'] = str(diff.days) + Data['authority'] = x509.get_issuer().get_components()[1][1].decode('utf-8') + + if Data['authority'] == 'Denial': + Data['authority'] = '%s has SELF-SIGNED SSL.' % (self.childDomain) + else: + Data['authority'] = '%s has SSL from %s.' % (self.childDomain, Data['authority']) + + except BaseException as msg: + Data['viewSSL'] = 0 + logging.CyberCPLogFileWriter.writeToFile(str(msg)) + + proc = httpProc(request, 'websiteFunctions/launchChild.html', Data) + return proc.render() + else: + proc = httpProc(request, 'websiteFunctions/launchChild.html', + {"error": 1, "domain": "This child domain does not exists"}) + return proc.render() + + def getDataFromLogFile(self, userID=None, data=None): + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + logType = data['logType'] + self.domain = data['virtualHost'] + page = data['page'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('logstatus', 0) + + if logType == 1: + fileName = "/home/" + self.domain + "/logs/" + self.domain + ".access_log" + else: + fileName = "/home/" + self.domain + "/logs/" + self.domain + ".error_log" + + command = 'ls -la %s' % fileName + result = ProcessUtilities.outputExecutioner(command) + + if result.find('->') > -1: + final_json = json.dumps( + {'status': 0, 'logstatus': 0, + 'error_message': "Symlink attack."}) + return HttpResponse(final_json) + + ## get Logs + website = Websites.objects.get(domain=self.domain) + + output = virtualHostUtilities.getAccessLogs(fileName, page, website.externalApp) + + if output.find("1,None") > -1: + final_json = json.dumps( + {'status': 0, 'logstatus': 0, + 'error_message': "Not able to fetch logs, see CyberPanel main log file, Error: %s" % (output)}) + return HttpResponse(final_json) + + ## get log ends here. + + data = output.split("\n") + + json_data = "[" + checker = 0 + + for items in reversed(data): + if len(items) > 10: + logData = items.split(" ") + domain = logData[5].strip('"') + ipAddress = logData[0].strip('"') + time = (logData[3]).strip("[").strip("]") + resource = logData[6].strip('"') + size = logData[9].replace('"', '') + + dic = {'domain': domain, + 'ipAddress': ipAddress, + 'time': time, + 'resource': resource, + 'size': size, + } + + if checker == 0: + json_data = json_data + json.dumps(dic) + checker = 1 + else: + json_data = json_data + ',' + json.dumps(dic) + + json_data = json_data + ']' + final_json = json.dumps({'status': 1, 'logstatus': 1, 'error_message': "None", "data": json_data}) + return HttpResponse(final_json) + + def fetchErrorLogs(self, userID=None, data=None): + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['virtualHost'] + page = data['page'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('logstatus', 0) + + fileName = "/home/" + self.domain + "/logs/" + self.domain + ".error_log" + + command = 'ls -la %s' % fileName + result = ProcessUtilities.outputExecutioner(command) + + if result.find('->') > -1: + final_json = json.dumps( + {'status': 0, 'logstatus': 0, + 'error_message': "Symlink attack."}) + return HttpResponse(final_json) + + ## get Logs + website = Websites.objects.get(domain=self.domain) + + output = virtualHostUtilities.getErrorLogs(fileName, page, website.externalApp) + + if output.find("1,None") > -1: + final_json = json.dumps( + {'status': 0, 'logstatus': 0, 'error_message': "Not able to fetch logs, see CyberPanel main log file!"}) + return HttpResponse(final_json) + + ## get log ends here. + + final_json = json.dumps({'status': 1, 'logstatus': 1, 'error_message': "None", "data": output}) + return HttpResponse(final_json) + + def getDataFromConfigFile(self, userID=None, data=None): + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + self.domain = data['virtualHost'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('configstatus', 0) + + command = 'cat %s' % ('/usr/local/lsws/conf/dvhost_redis.conf') + + if ProcessUtilities.outputExecutioner(command).find('127.0.0.1') == -1: + filePath = installUtilities.Server_root_path + "/conf/vhosts/" + self.domain + "/vhost.conf" + + command = 'cat ' + filePath + configData = ProcessUtilities.outputExecutioner(command, 'lsadm') + + if len(configData) == 0: + status = {'status': 0, "configstatus": 0, "error_message": "Configuration file is currently empty!"} + + final_json = json.dumps(status) + return HttpResponse(final_json) + + else: + command = 'redis-cli get "vhost:%s"' % (self.domain) + configData = ProcessUtilities.outputExecutioner(command) + configData = '#### This configuration is fetched from redis as Redis-Mass Hosting is being used.\n%s' % ( + configData) + + status = {'status': 1, "configstatus": 1, "configData": configData} + final_json = json.dumps(status) + return HttpResponse(final_json) + + def saveConfigsToFile(self, userID=None, data=None): + + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] != 1: + return ACLManager.loadErrorJson('configstatus', 0) + + configData = data['configData'] + self.domain = data['virtualHost'] + + if len(configData) == 0: + status = {"configstatus": 0, 'error_message': 'Error: you are trying to save empty vhost file, your website will stop working.'} + + final_json = json.dumps(status) + return HttpResponse(final_json) + + + command = 'cat %s' % ('/usr/local/lsws/conf/dvhost_redis.conf') + + if ProcessUtilities.outputExecutioner(command).find('127.0.0.1') == -1: + + mailUtilities.checkHome() + + tempPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + + vhost = open(tempPath, "w") + + vhost.write(configData) + + vhost.close() + + ## writing data temporary to file + + filePath = installUtilities.Server_root_path + "/conf/vhosts/" + self.domain + "/vhost.conf" + + ## save configuration data + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " saveVHostConfigs --path " + filePath + " --tempPath " + tempPath + + output = ProcessUtilities.outputExecutioner(execPath) + + if output.find("1,None") > -1: + status = {"configstatus": 1} + + final_json = json.dumps(status) + return HttpResponse(final_json) + else: + data_ret = {'configstatus': 0, 'error_message': output} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + ## save configuration data ends + else: + command = "redis-cli set vhost:%s '%s'" % (self.domain, configData.replace( + '#### This configuration is fetched from redis as Redis-Mass Hosting is being used.\n', '')) + ProcessUtilities.executioner(command) + + status = {"configstatus": 1} + + final_json = json.dumps(status) + return HttpResponse(final_json) + + def getRewriteRules(self, userID=None, data=None): + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + self.domain = data['virtualHost'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('rewriteStatus', 0) + + try: + childDom = ChildDomains.objects.get(domain=self.domain) + filePath = childDom.path + '/.htaccess' + externalApp = childDom.master.externalApp + except: + website = Websites.objects.get(domain=self.domain) + externalApp = website.externalApp + filePath = "/home/" + self.domain + "/public_html/.htaccess" + + try: + command = 'cat %s' % (filePath) + rewriteRules = ProcessUtilities.outputExecutioner(command, externalApp) + + if len(rewriteRules) == 0: + status = {"rewriteStatus": 1, "error_message": "Rules file is currently empty"} + final_json = json.dumps(status) + return HttpResponse(final_json) + + status = {"rewriteStatus": 1, "rewriteRules": rewriteRules} + + final_json = json.dumps(status) + return HttpResponse(final_json) + + except BaseException as msg: + status = {"rewriteStatus": 1, "error_message": str(msg), "rewriteRules": ""} + final_json = json.dumps(status) + return HttpResponse(final_json) + + def saveRewriteRules(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + self.domain = data['virtualHost'] + rewriteRules = data['rewriteRules'].encode('utf-8') + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('rewriteStatus', 0) + + ## writing data temporary to file + + mailUtilities.checkHome() + tempPath = "/tmp/" + str(randint(1000, 9999)) + vhost = open(tempPath, "wb") + vhost.write(rewriteRules) + vhost.close() + + ## writing data temporary to file + + try: + childDomain = ChildDomains.objects.get(domain=self.domain) + filePath = childDomain.path + '/.htaccess' + externalApp = childDomain.master.externalApp + except: + filePath = "/home/" + self.domain + "/public_html/.htaccess" + website = Websites.objects.get(domain=self.domain) + externalApp = website.externalApp + + ## save configuration data + + command = 'cp %s %s' % (tempPath, filePath) + ProcessUtilities.executioner(command, externalApp) + + command = 'rm -f %s' % (tempPath) + ProcessUtilities.executioner(command, 'cyberpanel') + + installUtilities.reStartLiteSpeedSocket() + status = {"rewriteStatus": 1, 'error_message': 'None'} + final_json = json.dumps(status) + return HttpResponse(final_json) + except BaseException as msg: + status = {"rewriteStatus": 0, 'error_message': str(msg)} + final_json = json.dumps(status) + return HttpResponse(final_json) + + def saveSSL(self, userID=None, data=None): + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + self.domain = data['virtualHost'] + key = data['key'] + cert = data['cert'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('sslStatus', 0) + + mailUtilities.checkHome() + + ## writing data temporary to file + + tempKeyPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + vhost = open(tempKeyPath, "w") + vhost.write(key) + vhost.close() + + tempCertPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + vhost = open(tempCertPath, "w") + vhost.write(cert) + vhost.close() + + ## writing data temporary to file + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " saveSSL --virtualHostName " + self.domain + " --tempKeyPath " + tempKeyPath + " --tempCertPath " + tempCertPath + output = ProcessUtilities.outputExecutioner(execPath) + + if output.find("1,None") > -1: + data_ret = {'sslStatus': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + logging.CyberCPLogFileWriter.writeToFile( + output) + data_ret = {'sslStatus': 0, 'error_message': output} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def changePHP(self, userID=None, data=None): + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + self.domain = data['childDomain'] + phpVersion = data['phpSelection'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('changePHP', 0) + + confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + self.domain + completePathToConfigFile = confPath + "/vhost.conf" + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " changePHP --phpVersion '" + phpVersion + "' --path " + completePathToConfigFile + ProcessUtilities.popenExecutioner(execPath) + + try: + website = Websites.objects.get(domain=self.domain) + website.phpSelection = data['phpSelection'] + website.save() + + ### check if there are any alias domains under the main website and then change php for them too + + for alias in website.childdomains_set.filter(alais=1): + + try: + + confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + alias.domain + completePathToConfigFile = confPath + "/vhost.conf" + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " changePHP --phpVersion '" + phpVersion + "' --path " + completePathToConfigFile + ProcessUtilities.popenExecutioner(execPath) + except BaseException as msg: + logging.CyberCPLogFileWriter.writeToFile(f'Error changing PHP for alias: {str(msg)}') + + + except: + website = ChildDomains.objects.get(domain=self.domain) + website.phpSelection = data['phpSelection'] + website.save() + + data_ret = {'status': 1, 'changePHP': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + def getWebsiteCron(self, userID=None, data=None): try: @@ -2213,44 +3665,6 @@ Require valid-user""" dic = {'getWebsiteCron': 0, 'error_message': str(msg)} json_data = json.dumps(dic) return HttpResponse(json_data) - - def fetchWebsitesList(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - pageNumber = int(data['page']) - recordsToShow = int(data['recordsToShow']) - - if os.path.exists(ProcessUtilities.debugPath): - logging.CyberCPLogFileWriter.writeToFile(f'Fetch sites step 1..') - - endPageNumber, finalPageNumber = self.recordsPointer(pageNumber, recordsToShow) - - if os.path.exists(ProcessUtilities.debugPath): - logging.CyberCPLogFileWriter.writeToFile(f'Fetch sites step 2..') - - websites = ACLManager.findWebsiteObjects(currentACL, userID) - - if os.path.exists(ProcessUtilities.debugPath): - logging.CyberCPLogFileWriter.writeToFile(f'Fetch sites step 3..') - - pagination = self.getPagination(len(websites), recordsToShow) - - if os.path.exists(ProcessUtilities.debugPath): - logging.CyberCPLogFileWriter.writeToFile(f'Fetch sites step 4..') - - json_data = self.findWebsitesListJson(websites[finalPageNumber:endPageNumber]) - - if os.path.exists(ProcessUtilities.debugPath): - logging.CyberCPLogFileWriter.writeToFile(f'Fetch sites step 5..') - - final_dic = {'status': 1, 'listWebSiteStatus': 1, 'error_message': "None", "data": json_data, - 'pagination': pagination} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - except BaseException as msg: - dic = {'status': 1, 'listWebSiteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) def remCronbyLine(self, userID=None, data=None): try: From 2ad810d628d574f493fdbb99ec1289d5e685d460 Mon Sep 17 00:00:00 2001 From: usmannasir Date: Fri, 4 Apr 2025 15:13:57 +0500 Subject: [PATCH 005/273] add missing function --- .../websiteFunctions/websiteFunctions.js | 236 +- .../websiteFunctions/listWebsites.html | 2 +- websiteFunctions/urls.py | 1 + websiteFunctions/views.py | 9 + websiteFunctions/website.py | 11756 ++++++++++++++-- 5 files changed, 10417 insertions(+), 1587 deletions(-) diff --git a/websiteFunctions/static/websiteFunctions/websiteFunctions.js b/websiteFunctions/static/websiteFunctions/websiteFunctions.js index 970f8dcd0..09b210069 100755 --- a/websiteFunctions/static/websiteFunctions/websiteFunctions.js +++ b/websiteFunctions/static/websiteFunctions/websiteFunctions.js @@ -2674,111 +2674,25 @@ app.controller('listWebsites', function ($scope, $http, $window) { // Call it immediately $scope.getFurtherWebsitesFromDB(); - $scope.showWPSites = function(index) { - $scope.selectedWebsite = $scope.WebSitesList[index]; + $scope.showWPSites = function(domain) { + var url = '/websites/fetchWPDetails'; + var data = { + domain: domain + }; - if (!$scope.selectedWebsite.wp_sites) { - var url = '/websites/fetchWPDetails'; - var data = { - domain: $scope.selectedWebsite.domain, - websiteName: $scope.selectedWebsite.domain - }; - - $http({ - method: 'POST', - url: url, - data: $.param(data), - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', - 'X-CSRFToken': getCookie('csrftoken') - } - }).then(function(response) { - console.log('WP Details Response:', response); - - // Check if response is HTML (login page) - if (typeof response.data === 'string' && response.data.includes('')) { - console.log('Received HTML response, redirecting to login'); - window.location.href = '/login'; - return; - } - - if (response.data && response.data.status === 1) { - try { - // If single site, wrap in array - var sites = Array.isArray(response.data.data) ? response.data.data : [response.data.data]; - - $scope.selectedWebsite.wp_sites = sites.map(function(site) { - return { - id: site.id || $scope.selectedWebsite.domain, - title: site.title || site.domain || $scope.selectedWebsite.domain, - url: site.url || 'http://' + $scope.selectedWebsite.domain, - version: site.version || 'Unknown', - phpVersion: site.php_version || 'Unknown', - theme: site.theme || 'Unknown', - activePlugins: site.active_plugins || 0, - searchIndex: site.search_index === 'enabled', - debugging: site.debugging === 'enabled', - passwordProtection: site.password_protection === 'enabled', - maintenanceMode: site.maintenance_mode === 'enabled' - }; - }); - $scope.selectedWebsite.showWPSites = true; - } catch (e) { - console.error('Error processing WordPress data:', e); - // Create default site on error - $scope.selectedWebsite.wp_sites = [{ - id: $scope.selectedWebsite.domain, - title: $scope.selectedWebsite.domain, - url: 'http://' + $scope.selectedWebsite.domain, - version: 'Unknown', - phpVersion: 'Unknown', - theme: 'Unknown', - activePlugins: 0, - searchIndex: false, - debugging: false, - passwordProtection: false, - maintenanceMode: false - }]; - $scope.selectedWebsite.showWPSites = true; - } - } else { - // Create default site if no data - $scope.selectedWebsite.wp_sites = [{ - id: $scope.selectedWebsite.domain, - title: $scope.selectedWebsite.domain, - url: 'http://' + $scope.selectedWebsite.domain, - version: 'Unknown', - phpVersion: 'Unknown', - theme: 'Unknown', - activePlugins: 0, - searchIndex: false, - debugging: false, - passwordProtection: false, - maintenanceMode: false - }]; - $scope.selectedWebsite.showWPSites = true; - } - }).catch(function(error) { - console.error('WP Details Error:', error); - // Create default site on error - $scope.selectedWebsite.wp_sites = [{ - id: $scope.selectedWebsite.domain, - title: $scope.selectedWebsite.domain, - url: 'http://' + $scope.selectedWebsite.domain, - version: 'Unknown', - phpVersion: 'Unknown', - theme: 'Unknown', - activePlugins: 0, - searchIndex: false, - debugging: false, - passwordProtection: false, - maintenanceMode: false - }]; - $scope.selectedWebsite.showWPSites = true; - }); - } else { - $scope.selectedWebsite.showWPSites = !$scope.selectedWebsite.showWPSites; - } + $http({ + method: 'POST', + url: url, + data: $.param(data), + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'X-CSRFToken': getCookie('csrftoken') + } + }).then(function(response) { + alert(JSON.stringify(response.data, null, 2)); + }).catch(function(error) { + alert('Error fetching WordPress sites: ' + JSON.stringify(error)); + }); }; $scope.visitSite = function(url) { @@ -6648,111 +6562,25 @@ app.controller('manageAliasController', function ($scope, $http, $timeout, $wind } - $scope.showWPSites = function(index) { - $scope.selectedWebsite = $scope.WebSitesList[index]; - - if (!$scope.selectedWebsite.wp_sites) { - var url = '/websites/fetchWPDetails'; + $scope.showWPSites = function(domain) { + var url = '/websites/fetchWPDetails'; var data = { - domain: $scope.selectedWebsite.domain, - websiteName: $scope.selectedWebsite.domain + domain: domain }; - - $http({ - method: 'POST', - url: url, - data: $.param(data), + + $http({ + method: 'POST', + url: url, + data: $.param(data), headers: { - 'Content-Type': 'application/x-www-form-urlencoded', + 'Content-Type': 'application/x-www-form-urlencoded', 'X-CSRFToken': getCookie('csrftoken') } - }).then(function(response) { - console.log('WP Details Response:', response); - - // Check if response is HTML (login page) - if (typeof response.data === 'string' && response.data.includes('')) { - console.log('Received HTML response, redirecting to login'); - window.location.href = '/login'; - return; - } - - if (response.data && response.data.status === 1) { - try { - // If single site, wrap in array - var sites = Array.isArray(response.data.data) ? response.data.data : [response.data.data]; - - $scope.selectedWebsite.wp_sites = sites.map(function(site) { - return { - id: site.id || $scope.selectedWebsite.domain, - title: site.title || site.domain || $scope.selectedWebsite.domain, - url: site.url || 'http://' + $scope.selectedWebsite.domain, - version: site.version || 'Unknown', - phpVersion: site.php_version || 'Unknown', - theme: site.theme || 'Unknown', - activePlugins: site.active_plugins || 0, - searchIndex: site.search_index === 'enabled', - debugging: site.debugging === 'enabled', - passwordProtection: site.password_protection === 'enabled', - maintenanceMode: site.maintenance_mode === 'enabled' - }; - }); - $scope.selectedWebsite.showWPSites = true; - } catch(e) { - console.error('Error processing WordPress data:', e); - // Create default site on error - $scope.selectedWebsite.wp_sites = [{ - id: $scope.selectedWebsite.domain, - title: $scope.selectedWebsite.domain, - url: 'http://' + $scope.selectedWebsite.domain, - version: 'Unknown', - phpVersion: 'Unknown', - theme: 'Unknown', - activePlugins: 0, - searchIndex: false, - debugging: false, - passwordProtection: false, - maintenanceMode: false - }]; - $scope.selectedWebsite.showWPSites = true; - } - } else { - // Create default site if no data - $scope.selectedWebsite.wp_sites = [{ - id: $scope.selectedWebsite.domain, - title: $scope.selectedWebsite.domain, - url: 'http://' + $scope.selectedWebsite.domain, - version: 'Unknown', - phpVersion: 'Unknown', - theme: 'Unknown', - activePlugins: 0, - searchIndex: false, - debugging: false, - passwordProtection: false, - maintenanceMode: false - }]; - $scope.selectedWebsite.showWPSites = true; - } - }).catch(function(error) { - console.error('WP Details Error:', error); - // Create default site on error - $scope.selectedWebsite.wp_sites = [{ - id: $scope.selectedWebsite.domain, - title: $scope.selectedWebsite.domain, - url: 'http://' + $scope.selectedWebsite.domain, - version: 'Unknown', - phpVersion: 'Unknown', - theme: 'Unknown', - activePlugins: 0, - searchIndex: false, - debugging: false, - passwordProtection: false, - maintenanceMode: false - }]; - $scope.selectedWebsite.showWPSites = true; - }); - } else { - $scope.selectedWebsite.showWPSites = !$scope.selectedWebsite.showWPSites; - } + }).then(function(response) { + alert(JSON.stringify(response.data, null, 2)); + }).catch(function(error) { + alert('Error fetching WordPress sites: ' + JSON.stringify(error)); + }); }; $scope.updateSetting = function(wp, setting) { diff --git a/websiteFunctions/templates/websiteFunctions/listWebsites.html b/websiteFunctions/templates/websiteFunctions/listWebsites.html index 4d85fdbae..370e2a94a 100755 --- a/websiteFunctions/templates/websiteFunctions/listWebsites.html +++ b/websiteFunctions/templates/websiteFunctions/listWebsites.html @@ -101,7 +101,7 @@
- {$ web.wp_sites.length $} WordPress Sites diff --git a/websiteFunctions/urls.py b/websiteFunctions/urls.py index 9469ca672..d084ca9ec 100755 --- a/websiteFunctions/urls.py +++ b/websiteFunctions/urls.py @@ -51,6 +51,7 @@ urlpatterns = [ path('AddWPsiteforRemoteBackup', views.AddWPsiteforRemoteBackup, name='AddWPsiteforRemoteBackup'), path('UpdateRemoteschedules', views.UpdateRemoteschedules, name='UpdateRemoteschedules'), path('ScanWordpressSite', views.ScanWordpressSite, name='ScanWordpressSite'), + path('fetchWPDetails', views.fetchWPDetails, name='fetchWPDetails'), # AddPlugin path('ConfigurePlugins', views.ConfigurePlugins, name='ConfigurePlugins'), diff --git a/websiteFunctions/views.py b/websiteFunctions/views.py index bcefc8a77..36aa3f78f 100755 --- a/websiteFunctions/views.py +++ b/websiteFunctions/views.py @@ -1840,5 +1840,14 @@ def Dockersitehome(request, dockerapp): userID = request.session['userID'] wm = WebsiteManager(dockerapp) return wm.Dockersitehome(request, userID, None) + except KeyError: + return redirect(loadLoginPage) + +def fetchWPDetails(request): + try: + userID = request.session['userID'] + data = json.loads(request.body) + wm = WebsiteManager() + return wm.fetchWPSitesForDomain(userID, data) except KeyError: return redirect(loadLoginPage) \ No newline at end of file diff --git a/websiteFunctions/website.py b/websiteFunctions/website.py index e2e6c08e6..84344d3c2 100755 --- a/websiteFunctions/website.py +++ b/websiteFunctions/website.py @@ -96,6 +96,8318 @@ class WebsiteManager: Status = response.json()['status'] + if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: + currentACL = ACLManager.loadedACL(userID) + adminNames = ACLManager.loadAllUsers(userID) + packagesName = ACLManager.loadPackages(userID, currentACL) + + if len(packagesName) == 0: + packagesName = ['Default'] + + FinalVersions = [] + userobj = Administrator.objects.get(pk=userID) + counter = 0 + try: + import requests + WPVersions = json.loads(requests.get('https://api.wordpress.org/core/version-check/1.7/').text)[ + 'offers'] + + for versions in WPVersions: + if counter == 7: + break + if versions['current'] not in FinalVersions: + FinalVersions.append(versions['current']) + counter = counter + 1 + except: + FinalVersions = ['5.6', '5.5.3', '5.5.2'] + + Plugins = wpplugins.objects.filter(owner=userobj) + rnpss = randomPassword.generate_pass(10) + + ## + + test_domain_status = 1 + + Data = {'packageList': packagesName, "owernList": adminNames, 'WPVersions': FinalVersions, + 'Plugins': Plugins, 'Randam_String': rnpss.lower(), 'test_domain_data': test_domain_status} + proc = httpProc(request, 'websiteFunctions/WPCreate.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def ListWPSites(self, request=None, userID=None, DeleteID=None): + import json + currentACL = ACLManager.loadedACL(userID) + + admin = Administrator.objects.get(pk=userID) + data = {} + wp_sites = ACLManager.GetALLWPObjects(currentACL, userID) + data['wp'] = wp_sites + + try: + if DeleteID != None: + WPDelete = WPSites.objects.get(pk=DeleteID) + + if ACLManager.checkOwnership(WPDelete.owner.domain, admin, currentACL) == 1: + WPDelete.delete() + except BaseException as msg: + pass + + sites = [] + for site in data['wp']: + sites.append({ + 'id': site.id, + 'title': site.title, + 'url': site.FinalURL, + 'production_status': True + }) + + context = { + "wpsite": json.dumps(sites), + "status": 1, + "total_sites": len(sites), + "debug_info": json.dumps({ + "user_id": userID, + "is_admin": bool(currentACL.get('admin', 0)), + "wp_sites_count": wp_sites.count() + }) + } + + proc = httpProc(request, 'websiteFunctions/WPsitesList.html', context) + return proc.render() + + def fetchWPSitesForDomain(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + domain = data['domain'] + website = Websites.objects.get(domain=domain) + + if ACLManager.checkOwnership(domain, admin, currentACL) != 1: + return ACLManager.loadErrorJson('fetchStatus', 0) + + wp_sites = WPSites.objects.filter(owner=website) + sites = [] + + for site in wp_sites: + sites.append({ + 'id': site.id, + 'title': site.title, + 'url': site.FinalURL, + 'path': site.path, + 'version': site.version, + 'status': site.status + }) + + data_ret = {'status': 1, 'fetchStatus': 1, 'error_message': "None", "sites": sites} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'fetchStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def WPHome(self, request=None, userID=None, WPid=None, DeleteID=None): + Data = {} + currentACL = ACLManager.loadedACL(userID) + WPobj = WPSites.objects.get(pk=WPid) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(WPobj.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + try: + + url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" + data = { + "name": "wp-manager", + "IP": ACLManager.GetServerIP() + } + + import requests + response = requests.post(url, data=json.dumps(data)) + Status = response.json()['status'] + + rnpss = randomPassword.generate_pass(10) + + Data['Randam_String'] = rnpss.lower() + + if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: + Data['wpsite'] = WPobj + Data['test_domain_data'] = 1 + + try: + DeleteID = request.GET.get('DeleteID', None) + + if DeleteID != None: + wstagingDelete = WPStaging.objects.get(pk=DeleteID, owner=WPobj) + wstagingDelete.delete() + + except BaseException as msg: + da = str(msg) + + proc = httpProc(request, 'websiteFunctions/WPsiteHome.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + except: + proc = httpProc(request, 'websiteFunctions/WPsiteHome.html', + Data, 'createDatabase') + return proc.render() + + def RestoreHome(self, request=None, userID=None, BackupID=None): + Data = {} + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.CheckForPremFeature('wp-manager'): + + Data['backupobj'] = WPSitesBackup.objects.get(pk=BackupID) + + if ACLManager.CheckIPBackupObjectOwner(currentACL, Data['backupobj'], admin) == 1: + pass + else: + return ACLManager.loadError() + + config = json.loads(Data['backupobj'].config) + Data['FileName'] = config['name'] + try: + Data['Backuptype'] = config['Backuptype'] + + if Data['Backuptype'] == 'DataBase Backup' or Data['Backuptype'] == 'Website Backup': + Data['WPsites'] = [WPSites.objects.get(pk=Data['backupobj'].WPSiteID)] + else: + Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) + + except: + Data['Backuptype'] = None + Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) + + proc = httpProc(request, 'websiteFunctions/WPRestoreHome.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def RemoteBackupConfig(self, request=None, userID=None, DeleteID=None): + Data = {} + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + try: + if DeleteID != None: + BackupconfigDelete = RemoteBackupConfig.objects.get(pk=DeleteID) + BackupconfigDelete.delete() + except: + pass + + if ACLManager.CheckForPremFeature('wp-manager'): + + Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) + allcon = RemoteBackupConfig.objects.all() + Data['backupconfigs'] = [] + for i in allcon: + configr = json.loads(i.config) + if i.configtype == "SFTP": + Data['backupconfigs'].append({ + 'id': i.pk, + 'Type': i.configtype, + 'HostName': configr['Hostname'], + 'Path': configr['Path'] + }) + elif i.configtype == "S3": + Provider = configr['Provider'] + if Provider == "Backblaze": + Data['backupconfigs'].append({ + 'id': i.pk, + 'Type': i.configtype, + 'HostName': Provider, + 'Path': configr['S3keyname'] + }) + else: + Data['backupconfigs'].append({ + 'id': i.pk, + 'Type': i.configtype, + 'HostName': Provider, + 'Path': configr['S3keyname'] + }) + + proc = httpProc(request, 'websiteFunctions/RemoteBackupConfig.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def BackupfileConfig(self, request=None, userID=None, RemoteConfigID=None, DeleteID=None): + Data = {} + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + Data['RemoteConfigID'] = RemoteConfigID + RemoteConfigobj = RemoteBackupConfig.objects.get(pk=RemoteConfigID) + try: + if DeleteID != None: + RemoteBackupConfigDelete = RemoteBackupSchedule.objects.get(pk=DeleteID) + RemoteBackupConfigDelete.delete() + except: + pass + + if ACLManager.CheckForPremFeature('wp-manager'): + Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) + allsechedule = RemoteBackupSchedule.objects.filter(RemoteBackupConfig=RemoteConfigobj) + Data['Backupschedule'] = [] + for i in allsechedule: + lastrun = i.lastrun + LastRun = time.strftime('%Y-%m-%d', time.localtime(float(lastrun))) + Data['Backupschedule'].append({ + 'id': i.pk, + 'Name': i.Name, + 'RemoteConfiguration': i.RemoteBackupConfig.configtype, + 'Retention': i.fileretention, + 'Frequency': i.timeintervel, + 'LastRun': LastRun + }) + proc = httpProc(request, 'websiteFunctions/BackupfileConfig.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def AddRemoteBackupsite(self, request=None, userID=None, RemoteScheduleID=None, DeleteSiteID=None): + Data = {} + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + Data['RemoteScheduleID'] = RemoteScheduleID + RemoteBackupScheduleobj = RemoteBackupSchedule.objects.get(pk=RemoteScheduleID) + + try: + if DeleteSiteID != None: + RemoteBackupsitesDelete = RemoteBackupsites.objects.get(pk=DeleteSiteID) + RemoteBackupsitesDelete.delete() + except: + pass + + if ACLManager.CheckForPremFeature('wp-manager'): + Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) + allRemoteBackupsites = RemoteBackupsites.objects.filter(owner=RemoteBackupScheduleobj) + Data['RemoteBackupsites'] = [] + for i in allRemoteBackupsites: + try: + wpsite = WPSites.objects.get(pk=i.WPsites) + Data['RemoteBackupsites'].append({ + 'id': i.pk, + 'Title': wpsite.title, + }) + except: + pass + proc = httpProc(request, 'websiteFunctions/AddRemoteBackupSite.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def WordpressPricing(self, request=None, userID=None, ): + Data = {} + proc = httpProc(request, 'websiteFunctions/CyberpanelPricing.html', Data, 'createWebsite') + return proc.render() + + def RestoreBackups(self, request=None, userID=None, DeleteID=None): + Data = {} + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" + data = { + "name": "wp-manager", + "IP": ACLManager.GetServerIP() + } + + import requests + response = requests.post(url, data=json.dumps(data)) + Status = response.json()['status'] + + if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: + + backobj = WPSitesBackup.objects.filter(owner=admin).order_by('-id') + + # if ACLManager.CheckIPBackupObjectOwner(currentACL, backobj, admin) == 1: + # pass + # else: + # return ACLManager.loadError() + + try: + if DeleteID != None: + DeleteIDobj = WPSitesBackup.objects.get(pk=DeleteID) + + if ACLManager.CheckIPBackupObjectOwner(currentACL, DeleteIDobj, admin) == 1: + config = DeleteIDobj.config + conf = json.loads(config) + FileName = conf['name'] + command = "rm -r /home/backup/%s.tar.gz" % FileName + ProcessUtilities.executioner(command) + DeleteIDobj.delete() + + except BaseException as msg: + pass + Data['job'] = [] + + for sub in backobj: + try: + wpsite = WPSites.objects.get(pk=sub.WPSiteID) + web = wpsite.title + except: + web = "Website Not Found" + + try: + config = sub.config + conf = json.loads(config) + Backuptype = conf['Backuptype'] + BackupDestination = conf['BackupDestination'] + except: + Backuptype = "Backup type not exists" + + Data['job'].append({ + 'id': sub.id, + 'title': web, + 'Backuptype': Backuptype, + 'BackupDestination': BackupDestination + }) + + proc = httpProc(request, 'websiteFunctions/RestoreBackups.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def AutoLogin(self, request=None, userID=None): + + WPid = request.GET.get('id') + currentACL = ACLManager.loadedACL(userID) + WPobj = WPSites.objects.get(pk=WPid) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(WPobj.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + from managePHP.phpManager import PHPManager + + php = PHPManager.getPHPString(WPobj.owner.phpSelection) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" + data = { + "name": "wp-manager", + "IP": ACLManager.GetServerIP() + } + + import requests + response = requests.post(url, data=json.dumps(data)) + Status = response.json()['status'] + + if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: + + ## Get title + + password = randomPassword.generate_pass(10) + + command = f'sudo -u %s {FinalPHPPath} /usr/bin/wp user create autologin %s --role=administrator --user_pass="%s" --path=%s --skip-plugins --skip-themes' % ( + WPobj.owner.externalApp, 'autologin@cloudpages.cloud', password, WPobj.path) + ProcessUtilities.executioner(command) + + command = f'sudo -u %s {FinalPHPPath} /usr/bin/wp user update autologin --user_pass="%s" --path=%s --skip-plugins --skip-themes' % ( + WPobj.owner.externalApp, password, WPobj.path) + ProcessUtilities.executioner(command) + + data = {} + + if WPobj.FinalURL.endswith('/'): + FinalURL = WPobj.FinalURL[:-1] + else: + FinalURL = WPobj.FinalURL + + data['url'] = 'https://%s' % (FinalURL) + data['userName'] = 'autologin' + data['password'] = password + + proc = httpProc(request, 'websiteFunctions/AutoLogin.html', + data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def ConfigurePlugins(self, request=None, userID=None, data=None): + + if ACLManager.CheckForPremFeature('wp-manager'): + currentACL = ACLManager.loadedACL(userID) + userobj = Administrator.objects.get(pk=userID) + + Selectedplugins = wpplugins.objects.filter(owner=userobj) + # data['Selectedplugins'] = wpplugins.objects.filter(ProjectOwner=HostingCompany) + + Data = {'Selectedplugins': Selectedplugins, } + proc = httpProc(request, 'websiteFunctions/WPConfigurePlugins.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def Addnewplugin(self, request=None, userID=None, data=None): + from django.shortcuts import reverse + if ACLManager.CheckForPremFeature('wp-manager'): + currentACL = ACLManager.loadedACL(userID) + adminNames = ACLManager.loadAllUsers(userID) + packagesName = ACLManager.loadPackages(userID, currentACL) + phps = PHPManager.findPHPVersions() + + Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps} + proc = httpProc(request, 'websiteFunctions/WPAddNewPlugin.html', + Data, 'createDatabase') + return proc.render() + + return redirect(reverse('pricing')) + + def SearchOnkeyupPlugin(self, userID=None, data=None): + try: + if ACLManager.CheckForPremFeature('wp-manager'): + currentACL = ACLManager.loadedACL(userID) + + pluginname = data['pluginname'] + # logging.CyberCPLogFileWriter.writeToFile("Plugin Name ....... %s"%pluginname) + + url = "http://api.wordpress.org/plugins/info/1.1/?action=query_plugins&request[search]=%s" % str( + pluginname) + import requests + + res = requests.get(url) + r = res.json() + + # return proc.ajax(1, 'Done', {'plugins': r}) + + data_ret = {'status': 1, 'plugns': r, } + + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': 'Premium feature not available.'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def AddNewpluginAjax(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + + userobj = Administrator.objects.get(pk=userID) + + config = data['config'] + Name = data['Name'] + # pluginname = data['pluginname'] + # logging.CyberCPLogFileWriter.writeToFile("config ....... %s"%config) + # logging.CyberCPLogFileWriter.writeToFile(" Name ....... %s"%Name) + + addpl = wpplugins(Name=Name, config=json.dumps(config), owner=userobj) + addpl.save() + + data_ret = {'status': 1} + + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'AddNewpluginAjax': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def EidtPlugin(self, request=None, userID=None, pluginbID=None): + Data = {} + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + pluginobj = wpplugins.objects.get(pk=pluginbID) + + if ACLManager.CheckIPPluginObjectOwner(currentACL, pluginobj, admin) == 1: + pass + else: + return ACLManager.loadError() + + lmo = json.loads(pluginobj.config) + Data['Selectedplugins'] = lmo + Data['pluginbID'] = pluginbID + Data['BucketName'] = pluginobj.Name + + proc = httpProc(request, 'websiteFunctions/WPEidtPlugin.html', + Data, 'createDatabase') + return proc.render() + + def deletesPlgin(self, userID=None, data=None, ): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + userobj = Administrator.objects.get(pk=userID) + pluginname = data['pluginname'] + pluginbBucketID = data['pluginbBucketID'] + # logging.CyberCPLogFileWriter.writeToFile("pluginbID ....... %s" % pluginbBucketID) + # logging.CyberCPLogFileWriter.writeToFile("pluginname ....... %s" % pluginname) + + obj = wpplugins.objects.get(pk=pluginbBucketID, owner=userobj) + + if ACLManager.CheckIPPluginObjectOwner(currentACL, obj, admin) == 1: + pass + else: + return ACLManager.loadError() + + ab = [] + ab = json.loads(obj.config) + ab.remove(pluginname) + obj.config = json.dumps(ab) + obj.save() + + data_ret = {'status': 1} + + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + except BaseException as msg: + data_ret = {'status': 0, 'deletesPlgin': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def Addplugineidt(self, userID=None, data=None, ): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + userobj = Administrator.objects.get(pk=userID) + pluginname = data['pluginname'] + pluginbBucketID = data['pluginbBucketID'] + + # logging.CyberCPLogFileWriter.writeToFile("pluginbID ....... %s" % pluginbBucketID) + # logging.CyberCPLogFileWriter.writeToFile("pluginname ....... %s" % pluginname) + + pObj = wpplugins.objects.get(pk=pluginbBucketID, owner=userobj) + + if ACLManager.CheckIPPluginObjectOwner(currentACL, pObj, admin) == 1: + pass + else: + return ACLManager.loadError() + + listofplugin = json.loads(pObj.config) + try: + index = listofplugin.index(pluginname) + print('index.....%s' % index) + if (index >= 0): + data_ret = {'status': 0, 'deletesPlgin': 0, 'error_message': str('Already Save in your Plugin lis')} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except: + ab = [] + ab = json.loads(pObj.config) + ab.append(pluginname) + pObj.config = json.dumps(ab) + pObj.save() + + data_ret = {'status': 1} + + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + except BaseException as msg: + data_ret = {'status': 0, 'deletesPlgin': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def modifyWebsite(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + + websitesName = ACLManager.findAllSites(currentACL, userID) + phps = PHPManager.findPHPVersions() + proc = httpProc(request, 'websiteFunctions/modifyWebsite.html', + {'websiteList': websitesName, 'phps': phps}, 'modifyWebsite') + return proc.render() + + def deleteWebsite(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + websitesName = ACLManager.findAllSites(currentACL, userID) + proc = httpProc(request, 'websiteFunctions/deleteWebsite.html', + {'websiteList': websitesName}, 'deleteWebsite') + return proc.render() + + def CreateNewDomain(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + websitesName = ACLManager.findAllSites(currentACL, userID) + + try: + admin = Administrator.objects.get(pk=userID) + if admin.defaultSite == 0: + websites = ACLManager.findWebsiteObjects(currentACL, userID) + admin.defaultSite = websites[0].id + admin.save() + except: + pass + + try: + admin = Administrator.objects.get(pk=userID) + defaultDomain = Websites.objects.get(pk=admin.defaultSite).domain + except: + try: + admin = Administrator.objects.get(pk=userID) + websites = ACLManager.findWebsiteObjects(currentACL, userID) + admin.defaultSite = websites[0].id + admin.save() + defaultDomain = websites[0].domain + except: + defaultDomain='NONE' + + + url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" + data = { + "name": "all", + "IP": ACLManager.GetServerIP() + } + + import requests + response = requests.post(url, data=json.dumps(data)) + Status = response.json()['status'] + + test_domain_status = 0 + + if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: + test_domain_status = 1 + + rnpss = randomPassword.generate_pass(10) + proc = httpProc(request, 'websiteFunctions/createDomain.html', + {'websiteList': websitesName, 'phps': PHPManager.findPHPVersions(), 'Randam_String': rnpss, + 'test_domain_data': test_domain_status, 'defaultSite': defaultDomain}) + return proc.render() + + def siteState(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + + websitesName = ACLManager.findAllSites(currentACL, userID) + + proc = httpProc(request, 'websiteFunctions/suspendWebsite.html', + {'websiteList': websitesName}, 'suspendWebsite') + return proc.render() + + def listWebsites(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + pagination = self.websitePagination(currentACL, userID) + proc = httpProc(request, 'websiteFunctions/listWebsites.html', + {"pagination": pagination}) + return proc.render() + + def listChildDomains(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + adminNames = ACLManager.loadAllUsers(userID) + packagesName = ACLManager.loadPackages(userID, currentACL) + phps = PHPManager.findPHPVersions() + + Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps} + proc = httpProc(request, 'websiteFunctions/listChildDomains.html', + Data) + return proc.render() + + def listCron(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(request.GET.get('domain'), admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + proc = httpProc(request, 'websiteFunctions/listCron.html', + {'domain': request.GET.get('domain')}) + return proc.render() + + def domainAlias(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + aliasManager = AliasManager(self.domain) + noAlias, finalAlisList = aliasManager.fetchAlisForDomains() + + path = "/home/" + self.domain + "/public_html" + + proc = httpProc(request, 'websiteFunctions/domainAlias.html', { + 'masterDomain': self.domain, + 'aliases': finalAlisList, + 'path': path, + 'noAlias': noAlias + }) + return proc.render() + + def FetchWPdata(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core version --skip-plugins --skip-themes --path=%s 2>/dev/null' % ( + Vhuser, FinalPHPPath, path) + version = ProcessUtilities.outputExecutioner(command, None, True) + version = html.escape(version) + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin status litespeed-cache --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, path) + lscachee = ProcessUtilities.outputExecutioner(command) + + if lscachee.find('Status: Active') > -1: + lscache = 1 + else: + lscache = 0 + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp config list --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, path) + stdout = ProcessUtilities.outputExecutioner(command) + debugging = 0 + for items in stdout.split('\n'): + if items.find('WP_DEBUG true constant') > -1: + debugging = 1 + break + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp option get blog_public --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, path) + stdoutput = ProcessUtilities.outputExecutioner(command) + searchindex = int(stdoutput.splitlines()[-1]) + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp maintenance-mode status --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, path) + maintenanceMod = ProcessUtilities.outputExecutioner(command) + + result = maintenanceMod.splitlines()[-1] + if result.find('not active') > -1: + maintenanceMode = 0 + else: + maintenanceMode = 1 + + ##### Check passwd protection + vhostName = wpsite.owner.domain + vhostPassDir = f'/home/{vhostName}' + path = f'{vhostPassDir}/{WPManagerID}' + if os.path.exists(path): + passwd = 1 + else: + passwd = 0 + + #### Check WP cron + command = "sudo -u %s cat %s/wp-config.php" % (Vhuser, wpsite.path) + stdout = ProcessUtilities.outputExecutioner(command) + if stdout.find("'DISABLE_WP_CRON', 'true'") > -1: + wpcron = 1 + else: + wpcron = 0 + + fb = { + 'version': version.rstrip('\n'), + 'lscache': lscache, + 'debugging': debugging, + 'searchIndex': searchindex, + 'maintenanceMode': maintenanceMode, + 'passwordprotection': passwd, + 'wpcron': wpcron + + } + + data_ret = {'status': 1, 'error_message': 'None', 'ret_data': fb} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def GetCurrentPlugins(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin list --skip-plugins --skip-themes --format=json --path=%s' % ( + Vhuser, FinalPHPPath, path) + stdoutput = ProcessUtilities.outputExecutioner(command) + json_data = stdoutput.splitlines()[-1] + + data_ret = {'status': 1, 'error_message': 'None', 'plugins': json_data} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def GetCurrentThemes(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp theme list --skip-plugins --skip-themes --format=json --path=%s' % ( + Vhuser, FinalPHPPath, path) + stdoutput = ProcessUtilities.outputExecutioner(command) + json_data = stdoutput.splitlines()[-1] + + data_ret = {'status': 1, 'error_message': 'None', 'themes': json_data} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def fetchstaging(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + from plogical.phpUtilities import phpUtilities + + json_data = phpUtilities.GetStagingInJson(wpsite.wpstaging_set.all().order_by('-id')) + + data_ret = {'status': 1, 'error_message': 'None', 'wpsites': json_data} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def fetchDatabase(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + php = PHPManager.getPHPString(wpsite.owner.phpSelection) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + command = f'{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config get DB_NAME --skip-plugins --skip-themes --path={wpsite.path} 2>/dev/null' + retStatus, stdoutput = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp, True, None, 1) + + if stdoutput.find('Error:') == -1: + DataBaseName = stdoutput.rstrip("\n") + DataBaseName = html.escape(DataBaseName) + else: + data_ret = {'status': 0, 'error_message': stdoutput} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + command = f'{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config get DB_USER --skip-plugins --skip-themes --path={wpsite.path} 2>/dev/null' + retStatus, stdoutput = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp, True, None, 1) + + if stdoutput.find('Error:') == -1: + DataBaseUser = stdoutput.rstrip("\n") + DataBaseUser = html.escape(DataBaseUser) + else: + data_ret = {'status': 0, 'error_message': stdoutput} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + command = f'{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config get table_prefix --skip-plugins --skip-themes --path={wpsite.path} 2>/dev/null' + retStatus, stdoutput = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp, True, None, 1) + + if stdoutput.find('Error:') == -1: + tableprefix = stdoutput.rstrip("\n") + tableprefix = html.escape(tableprefix) + else: + data_ret = {'status': 0, 'error_message': stdoutput} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + data_ret = {'status': 1, 'error_message': 'None', "DataBaseUser": DataBaseUser, + "DataBaseName": DataBaseName, 'tableprefix': tableprefix} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def SaveUpdateConfig(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + Plugins = data['Plugins'] + Themes = data['Themes'] + AutomaticUpdates = data['AutomaticUpdates'] + + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + + php = PHPManager.getPHPString(wpsite.owner.phpSelection) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + if AutomaticUpdates == 'Disabled': + command = f"{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_AUTO_UPDATE_CORE false --raw --allow-root --path=" + wpsite.path + result = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp) + + if result.find('Success:') == -1: + raise BaseException(result) + elif AutomaticUpdates == 'Minor and Security Updates': + command = f"{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_AUTO_UPDATE_CORE minor --allow-root --path=" + wpsite.path + result = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp) + + if result.find('Success:') == -1: + raise BaseException(result) + else: + command = f"{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_AUTO_UPDATE_CORE true --raw --allow-root --path=" + wpsite.path + result = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp) + + if result.find('Success:') == -1: + raise BaseException(result) + + wpsite.AutoUpdates = AutomaticUpdates + wpsite.PluginUpdates = Plugins + wpsite.ThemeUpdates = Themes + wpsite.save() + + data_ret = {'status': 1, 'error_message': 'None', } + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def DeploytoProduction(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + statgingID = data['StagingID'] + wpsite = WPSites.objects.get(pk=WPManagerID) + StagingObj = WPSites.objects.get(pk=statgingID) + + ### + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + if ACLManager.checkOwnership(StagingObj.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + ### + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['statgingID'] = statgingID + extraArgs['WPid'] = WPManagerID + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + background = ApplicationInstaller('DeploytoProduction', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def WPCreateBackup(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + Backuptype = data['Backuptype'] + + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['WPid'] = WPManagerID + extraArgs['Backuptype'] = Backuptype + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + background = ApplicationInstaller('WPCreateBackup', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def RestoreWPbackupNow(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + backupid = data['backupid'] + DesSiteID = data['DesSite'] + + # try: + # + # bwp = WPSites.objects.get(pk=int(backupid)) + # + # if ACLManager.checkOwnership(bwp.owner.domain, admin, currentACL) == 1: + # pass + # else: + # return ACLManager.loadError() + # + # except: + # pass + # + # dwp = WPSites.objects.get(pk=int(DesSiteID)) + # if ACLManager.checkOwnership(dwp.owner.domain, admin, currentACL) == 1: + # pass + # else: + # return ACLManager.loadError() + + Domain = data['Domain'] + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['backupid'] = backupid + extraArgs['DesSiteID'] = DesSiteID + extraArgs['Domain'] = Domain + extraArgs['path'] = data['path'] + extraArgs['home'] = data['home'] + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + background = ApplicationInstaller('RestoreWPbackupNow', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def SaveBackupConfig(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + ConfigType = data['type'] + if ConfigType == 'SFTP': + Hname = data['Hname'] + Uname = data['Uname'] + Passwd = data['Passwd'] + path = data['path'] + config = { + "Hostname": Hname, + "Username": Uname, + "Password": Passwd, + "Path": path + } + elif ConfigType == "S3": + Provider = data['Provider'] + if Provider == "Backblaze": + S3keyname = data['S3keyname'] + SecertKey = data['SecertKey'] + AccessKey = data['AccessKey'] + EndUrl = data['EndUrl'] + config = { + "Provider": Provider, + "S3keyname": S3keyname, + "SecertKey": SecertKey, + "AccessKey": AccessKey, + "EndUrl": EndUrl + + } + else: + S3keyname = data['S3keyname'] + SecertKey = data['SecertKey'] + AccessKey = data['AccessKey'] + config = { + "Provider": Provider, + "S3keyname": S3keyname, + "SecertKey": SecertKey, + "AccessKey": AccessKey, + + } + + mkobj = RemoteBackupConfig(owner=admin, configtype=ConfigType, config=json.dumps(config)) + mkobj.save() + + time.sleep(1) + + data_ret = {'status': 1, 'error_message': 'None', } + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def SaveBackupSchedule(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + FileRetention = data['FileRetention'] + Backfrequency = data['Backfrequency'] + ScheduleName = data['ScheduleName'] + RemoteConfigID = data['RemoteConfigID'] + BackupType = data['BackupType'] + + RemoteBackupConfigobj = RemoteBackupConfig.objects.get(pk=RemoteConfigID) + Rconfig = json.loads(RemoteBackupConfigobj.config) + + try: + # This code is only supposed to run if backups are s3, not for SFTP + provider = Rconfig['Provider'] + if provider == "Backblaze": + EndURl = Rconfig['EndUrl'] + elif provider == "Amazon": + EndURl = "https://s3.us-east-1.amazonaws.com" + elif provider == "Wasabi": + EndURl = "https://s3.wasabisys.com" + + AccessKey = Rconfig['AccessKey'] + SecertKey = Rconfig['SecertKey'] + + session = boto3.session.Session() + + client = session.client( + 's3', + endpoint_url=EndURl, + aws_access_key_id=AccessKey, + aws_secret_access_key=SecertKey, + verify=False + ) + + ############Creating Bucket + BucketName = randomPassword.generate_pass().lower() + + try: + client.create_bucket(Bucket=BucketName) + except BaseException as msg: + logging.CyberCPLogFileWriter.writeToFile("Creating Bucket Error: %s" % str(msg)) + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + config = { + 'BackupType': BackupType, + 'BucketName': BucketName + } + except BaseException as msg: + config = {'BackupType': BackupType} + pass + + svobj = RemoteBackupSchedule(RemoteBackupConfig=RemoteBackupConfigobj, Name=ScheduleName, + timeintervel=Backfrequency, fileretention=FileRetention, + config=json.dumps(config), + lastrun=str(time.time())) + svobj.save() + + data_ret = {'status': 1, 'error_message': 'None', } + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def AddWPsiteforRemoteBackup(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + WPid = data['WpsiteID'] + RemoteScheduleID = data['RemoteScheduleID'] + + wpsiteobj = WPSites.objects.get(pk=WPid) + WPpath = wpsiteobj.path + VHuser = wpsiteobj.owner.externalApp + PhpVersion = wpsiteobj.owner.phpSelection + php = PHPManager.getPHPString(PhpVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + ####Get DB Name + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp config get DB_NAME --skip-plugins --skip-themes --path=%s' % ( + VHuser, FinalPHPPath, WPpath) + result, stdout = ProcessUtilities.outputExecutioner(command, None, None, None, 1) + + if stdout.find('Error:') > -1: + raise BaseException(stdout) + else: + Finaldbname = stdout.rstrip("\n") + + ## Get DB obj + try: + DBobj = Databases.objects.get(dbName=Finaldbname) + except: + raise BaseException(str("DataBase Not Found")) + RemoteScheduleIDobj = RemoteBackupSchedule.objects.get(pk=RemoteScheduleID) + + svobj = RemoteBackupsites(owner=RemoteScheduleIDobj, WPsites=WPid, database=DBobj.pk) + svobj.save() + + data_ret = {'status': 1, 'error_message': 'None', } + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def UpdateRemoteschedules(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + ScheduleID = data['ScheduleID'] + Frequency = data['Frequency'] + FileRetention = data['FileRetention'] + + scheduleobj = RemoteBackupSchedule.objects.get(pk=ScheduleID) + scheduleobj.timeintervel = Frequency + scheduleobj.fileretention = FileRetention + scheduleobj.save() + + data_ret = {'status': 1, 'error_message': 'None', } + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def ScanWordpressSite(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + allweb = Websites.objects.all() + + childdomain = ChildDomains.objects.all() + + for web in allweb: + webpath = "/home/%s/public_html/" % web.domain + command = "cat %swp-config.php" % webpath + result = ProcessUtilities.outputExecutioner(command, web.externalApp) + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(result) + + if result.find('No such file or directory') == -1: + try: + WPSites.objects.get(path=webpath) + except: + wpobj = WPSites(owner=web, title=web.domain, path=webpath, FinalURL=web.domain, + AutoUpdates="Enabled", PluginUpdates="Enabled", + ThemeUpdates="Enabled", ) + wpobj.save() + + for chlid in childdomain: + childPath = chlid.path.rstrip('/') + + command = "cat %s/wp-config.php" % childPath + result = ProcessUtilities.outputExecutioner(command, chlid.master.externalApp) + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(result) + + if result.find('No such file or directory') == -1: + fChildPath = f'{childPath}/' + try: + WPSites.objects.get(path=fChildPath) + except: + + wpobj = WPSites(owner=chlid.master, title=chlid.domain, path=fChildPath, FinalURL=chlid.domain, + AutoUpdates="Enabled", PluginUpdates="Enabled", + ThemeUpdates="Enabled", ) + wpobj.save() + + data_ret = {'status': 1, 'error_message': 'None', } + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def installwpcore(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + ###fetch WP version + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core version --skip-plugins --skip-themes --path=%s 2>/dev/null' % ( + Vhuser, FinalPHPPath, path) + version = ProcessUtilities.outputExecutioner(command, None, True) + version = version.rstrip("\n") + + ###install wp core + command = f"sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp core download --force --skip-content --version={version} --path={path}" + output = ProcessUtilities.outputExecutioner(command) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', 'result': output} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def dataintegrity(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + ###fetch WP version + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core verify-checksums --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, path) + result = ProcessUtilities.outputExecutioner(command) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', 'result': result} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def UpdatePlugins(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + plugin = data['plugin'] + pluginarray = data['pluginarray'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['plugin'] = plugin + extraArgs['pluginarray'] = pluginarray + extraArgs['FinalPHPPath'] = FinalPHPPath + extraArgs['path'] = path + extraArgs['Vhuser'] = Vhuser + + background = ApplicationInstaller('UpdateWPPlugin', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def UpdateThemes(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + Theme = data['Theme'] + Themearray = data['Themearray'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['Theme'] = Theme + extraArgs['Themearray'] = Themearray + extraArgs['FinalPHPPath'] = FinalPHPPath + extraArgs['path'] = path + extraArgs['Vhuser'] = Vhuser + + background = ApplicationInstaller('UpdateWPTheme', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def DeletePlugins(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + plugin = data['plugin'] + pluginarray = data['pluginarray'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['plugin'] = plugin + extraArgs['pluginarray'] = pluginarray + extraArgs['FinalPHPPath'] = FinalPHPPath + extraArgs['path'] = path + extraArgs['Vhuser'] = Vhuser + + background = ApplicationInstaller('DeletePlugins', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def DeleteThemes(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + Theme = data['Theme'] + Themearray = data['Themearray'] + wpsite = WPSites.objects.get(pk=WPManagerID) + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['Theme'] = Theme + extraArgs['Themearray'] = Themearray + extraArgs['FinalPHPPath'] = FinalPHPPath + extraArgs['path'] = path + extraArgs['Vhuser'] = Vhuser + + background = ApplicationInstaller('DeleteThemes', extraArgs) + background.start() + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def ChangeStatus(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + plugin = data['plugin'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin status %s --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, plugin, path) + stdoutput = ProcessUtilities.outputExecutioner(command) + + if stdoutput.find('Status: Active') > -1: + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin deactivate %s --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, plugin, path) + stdoutput = ProcessUtilities.outputExecutioner(command) + time.sleep(3) + + else: + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin activate %s --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, plugin, path) + stdoutput = ProcessUtilities.outputExecutioner(command) + time.sleep(3) + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def ChangeStatusThemes(self, userID=None, data=None): + try: + # logging.CyberCPLogFileWriter.writeToFile("Error WP ChangeStatusThemes ....... %s") + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + Theme = data['theme'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['Theme'] = Theme + extraArgs['FinalPHPPath'] = FinalPHPPath + extraArgs['path'] = path + extraArgs['Vhuser'] = Vhuser + + background = ApplicationInstaller('ChangeStatusThemes', extraArgs) + background.start() + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def CreateStagingNow(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['StagingDomain'] = data['StagingDomain'] + extraArgs['StagingName'] = data['StagingName'] + extraArgs['WPid'] = data['WPid'] + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + wpsite = WPSites.objects.get(pk=data['WPid']) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + background = ApplicationInstaller('CreateStagingNow', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def UpdateWPSettings(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + siteId = data['siteId'] + setting = data['setting'] + value = data['value'] + + wpsite = WPSites.objects.get(pk=siteId) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) != 1: + return ACLManager.loadError() + + # Get PHP version and path + Webobj = Websites.objects.get(pk=wpsite.owner_id) + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + # Update the appropriate setting based on the setting type + if setting == 'search-indexing': + # Update search engine indexing + command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp option update blog_public {value} --skip-plugins --skip-themes --path={wpsite.path}' + elif setting == 'debugging': + # Update debugging in wp-config.php + if value: + command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_DEBUG true --raw --skip-plugins --skip-themes --path={wpsite.path}' + else: + command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_DEBUG false --raw --skip-plugins --skip-themes --path={wpsite.path}' + elif setting == 'password-protection': + vhostName = wpsite.owner.domain + vhostPassDir = f'/home/{vhostName}' + path = f'{vhostPassDir}/{siteId}' + if value: + # Enable password protection + if not os.path.exists(path): + os.makedirs(path) + htpasswd = f'{path}/.htpasswd' + htaccess = f'{wpsite.path}/.htaccess' + password = randomPassword.generate_pass(12) + + # Create .htpasswd file + command = f"htpasswd -cb {htpasswd} admin {password}" + ProcessUtilities.executioner(command) + + # Create .htaccess file + htaccess_content = f"""AuthType Basic +AuthName "Restricted Access" +AuthUserFile {htpasswd} +Require valid-user +""" + with open(htaccess, 'w') as f: + f.write(htaccess_content) + else: + # Disable password protection + if os.path.exists(path): + shutil.rmtree(path) + htaccess = f'{wpsite.path}/.htaccess' + if os.path.exists(htaccess): + os.remove(htaccess) + + # Execute the command + ProcessUtilities.executioner(command) + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + +class WebsiteManager: + apache = 1 + ols = 2 + lsws = 3 + + def __init__(self, domain=None, childDomain=None): + self.domain = domain + self.childDomain = childDomain + + def createWebsite(self, request=None, userID=None, data=None): + + url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" + data = { + "name": "all", + "IP": ACLManager.GetServerIP() + } + + import requests + response = requests.post(url, data=json.dumps(data)) + Status = response.json()['status'] + + test_domain_status = 0 + + if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: + test_domain_status = 1 + + currentACL = ACLManager.loadedACL(userID) + adminNames = ACLManager.loadAllUsers(userID) + packagesName = ACLManager.loadPackages(userID, currentACL) + phps = PHPManager.findPHPVersions() + + rnpss = randomPassword.generate_pass(10) + + Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps, 'Randam_String': rnpss.lower(), + 'test_domain_data': test_domain_status} + proc = httpProc(request, 'websiteFunctions/createWebsite.html', + Data, 'createWebsite') + return proc.render() + + def WPCreate(self, request=None, userID=None, data=None): + url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" + data = { + "name": "wp-manager", + "IP": ACLManager.GetServerIP() + } + + import requests + response = requests.post(url, data=json.dumps(data)) + Status = response.json()['status'] + + + if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: + currentACL = ACLManager.loadedACL(userID) + adminNames = ACLManager.loadAllUsers(userID) + packagesName = ACLManager.loadPackages(userID, currentACL) + + if len(packagesName) == 0: + packagesName = ['Default'] + + FinalVersions = [] + userobj = Administrator.objects.get(pk=userID) + counter = 0 + try: + import requests + WPVersions = json.loads(requests.get('https://api.wordpress.org/core/version-check/1.7/').text)[ + 'offers'] + + for versions in WPVersions: + if counter == 7: + break + if versions['current'] not in FinalVersions: + FinalVersions.append(versions['current']) + counter = counter + 1 + except: + FinalVersions = ['5.6', '5.5.3', '5.5.2'] + + Plugins = wpplugins.objects.filter(owner=userobj) + rnpss = randomPassword.generate_pass(10) + + ## + + test_domain_status = 1 + + Data = {'packageList': packagesName, "owernList": adminNames, 'WPVersions': FinalVersions, + 'Plugins': Plugins, 'Randam_String': rnpss.lower(), 'test_domain_data': test_domain_status} + proc = httpProc(request, 'websiteFunctions/WPCreate.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def ListWPSites(self, request=None, userID=None, DeleteID=None): + import json + currentACL = ACLManager.loadedACL(userID) + + admin = Administrator.objects.get(pk=userID) + data = {} + wp_sites = ACLManager.GetALLWPObjects(currentACL, userID) + data['wp'] = wp_sites + + try: + if DeleteID != None: + WPDelete = WPSites.objects.get(pk=DeleteID) + + if ACLManager.checkOwnership(WPDelete.owner.domain, admin, currentACL) == 1: + WPDelete.delete() + except BaseException as msg: + pass + + sites = [] + for site in data['wp']: + sites.append({ + 'id': site.id, + 'title': site.title, + 'url': site.FinalURL, + 'production_status': True + }) + + context = { + "wpsite": json.dumps(sites), + "status": 1, + "total_sites": len(sites), + "debug_info": json.dumps({ + "user_id": userID, + "is_admin": bool(currentACL.get('admin', 0)), + "wp_sites_count": wp_sites.count() + }) + } + + proc = httpProc(request, 'websiteFunctions/WPsitesList.html', context) + return proc.render() + + def fetchWPSitesForDomain(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + domain = data['domain'] + website = Websites.objects.get(domain=domain) + + if ACLManager.checkOwnership(domain, admin, currentACL) != 1: + return ACLManager.loadErrorJson('fetchStatus', 0) + + wp_sites = WPSites.objects.filter(owner=website) + sites = [] + + for site in wp_sites: + sites.append({ + 'id': site.id, + 'title': site.title, + 'url': site.FinalURL, + 'path': site.path, + 'version': site.version, + 'status': site.status + }) + + data_ret = {'status': 1, 'fetchStatus': 1, 'error_message': "None", "sites": sites} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'fetchStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def WPHome(self, request=None, userID=None, WPid=None, DeleteID=None): + Data = {} + currentACL = ACLManager.loadedACL(userID) + WPobj = WPSites.objects.get(pk=WPid) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(WPobj.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + try: + + url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" + data = { + "name": "wp-manager", + "IP": ACLManager.GetServerIP() + } + + import requests + response = requests.post(url, data=json.dumps(data)) + Status = response.json()['status'] + + rnpss = randomPassword.generate_pass(10) + + Data['Randam_String'] = rnpss.lower() + + if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: + Data['wpsite'] = WPobj + Data['test_domain_data'] = 1 + + try: + DeleteID = request.GET.get('DeleteID', None) + + if DeleteID != None: + wstagingDelete = WPStaging.objects.get(pk=DeleteID, owner=WPobj) + wstagingDelete.delete() + + except BaseException as msg: + da = str(msg) + + proc = httpProc(request, 'websiteFunctions/WPsiteHome.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + except: + proc = httpProc(request, 'websiteFunctions/WPsiteHome.html', + Data, 'createDatabase') + return proc.render() + + def RestoreHome(self, request=None, userID=None, BackupID=None): + Data = {} + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.CheckForPremFeature('wp-manager'): + + Data['backupobj'] = WPSitesBackup.objects.get(pk=BackupID) + + if ACLManager.CheckIPBackupObjectOwner(currentACL, Data['backupobj'], admin) == 1: + pass + else: + return ACLManager.loadError() + + config = json.loads(Data['backupobj'].config) + Data['FileName'] = config['name'] + try: + Data['Backuptype'] = config['Backuptype'] + + if Data['Backuptype'] == 'DataBase Backup' or Data['Backuptype'] == 'Website Backup': + Data['WPsites'] = [WPSites.objects.get(pk=Data['backupobj'].WPSiteID)] + else: + Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) + + except: + Data['Backuptype'] = None + Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) + + proc = httpProc(request, 'websiteFunctions/WPRestoreHome.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def RemoteBackupConfig(self, request=None, userID=None, DeleteID=None): + Data = {} + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + try: + if DeleteID != None: + BackupconfigDelete = RemoteBackupConfig.objects.get(pk=DeleteID) + BackupconfigDelete.delete() + except: + pass + + if ACLManager.CheckForPremFeature('wp-manager'): + + Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) + allcon = RemoteBackupConfig.objects.all() + Data['backupconfigs'] = [] + for i in allcon: + configr = json.loads(i.config) + if i.configtype == "SFTP": + Data['backupconfigs'].append({ + 'id': i.pk, + 'Type': i.configtype, + 'HostName': configr['Hostname'], + 'Path': configr['Path'] + }) + elif i.configtype == "S3": + Provider = configr['Provider'] + if Provider == "Backblaze": + Data['backupconfigs'].append({ + 'id': i.pk, + 'Type': i.configtype, + 'HostName': Provider, + 'Path': configr['S3keyname'] + }) + else: + Data['backupconfigs'].append({ + 'id': i.pk, + 'Type': i.configtype, + 'HostName': Provider, + 'Path': configr['S3keyname'] + }) + + proc = httpProc(request, 'websiteFunctions/RemoteBackupConfig.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def BackupfileConfig(self, request=None, userID=None, RemoteConfigID=None, DeleteID=None): + Data = {} + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + Data['RemoteConfigID'] = RemoteConfigID + RemoteConfigobj = RemoteBackupConfig.objects.get(pk=RemoteConfigID) + try: + if DeleteID != None: + RemoteBackupConfigDelete = RemoteBackupSchedule.objects.get(pk=DeleteID) + RemoteBackupConfigDelete.delete() + except: + pass + + if ACLManager.CheckForPremFeature('wp-manager'): + Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) + allsechedule = RemoteBackupSchedule.objects.filter(RemoteBackupConfig=RemoteConfigobj) + Data['Backupschedule'] = [] + for i in allsechedule: + lastrun = i.lastrun + LastRun = time.strftime('%Y-%m-%d', time.localtime(float(lastrun))) + Data['Backupschedule'].append({ + 'id': i.pk, + 'Name': i.Name, + 'RemoteConfiguration': i.RemoteBackupConfig.configtype, + 'Retention': i.fileretention, + 'Frequency': i.timeintervel, + 'LastRun': LastRun + }) + proc = httpProc(request, 'websiteFunctions/BackupfileConfig.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def AddRemoteBackupsite(self, request=None, userID=None, RemoteScheduleID=None, DeleteSiteID=None): + Data = {} + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + Data['RemoteScheduleID'] = RemoteScheduleID + RemoteBackupScheduleobj = RemoteBackupSchedule.objects.get(pk=RemoteScheduleID) + + try: + if DeleteSiteID != None: + RemoteBackupsitesDelete = RemoteBackupsites.objects.get(pk=DeleteSiteID) + RemoteBackupsitesDelete.delete() + except: + pass + + if ACLManager.CheckForPremFeature('wp-manager'): + Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) + allRemoteBackupsites = RemoteBackupsites.objects.filter(owner=RemoteBackupScheduleobj) + Data['RemoteBackupsites'] = [] + for i in allRemoteBackupsites: + try: + wpsite = WPSites.objects.get(pk=i.WPsites) + Data['RemoteBackupsites'].append({ + 'id': i.pk, + 'Title': wpsite.title, + }) + except: + pass + proc = httpProc(request, 'websiteFunctions/AddRemoteBackupSite.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def WordpressPricing(self, request=None, userID=None, ): + Data = {} + proc = httpProc(request, 'websiteFunctions/CyberpanelPricing.html', Data, 'createWebsite') + return proc.render() + + def RestoreBackups(self, request=None, userID=None, DeleteID=None): + Data = {} + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" + data = { + "name": "wp-manager", + "IP": ACLManager.GetServerIP() + } + + import requests + response = requests.post(url, data=json.dumps(data)) + Status = response.json()['status'] + + if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: + + backobj = WPSitesBackup.objects.filter(owner=admin).order_by('-id') + + # if ACLManager.CheckIPBackupObjectOwner(currentACL, backobj, admin) == 1: + # pass + # else: + # return ACLManager.loadError() + + try: + if DeleteID != None: + DeleteIDobj = WPSitesBackup.objects.get(pk=DeleteID) + + if ACLManager.CheckIPBackupObjectOwner(currentACL, DeleteIDobj, admin) == 1: + config = DeleteIDobj.config + conf = json.loads(config) + FileName = conf['name'] + command = "rm -r /home/backup/%s.tar.gz" % FileName + ProcessUtilities.executioner(command) + DeleteIDobj.delete() + + except BaseException as msg: + pass + Data['job'] = [] + + for sub in backobj: + try: + wpsite = WPSites.objects.get(pk=sub.WPSiteID) + web = wpsite.title + except: + web = "Website Not Found" + + try: + config = sub.config + conf = json.loads(config) + Backuptype = conf['Backuptype'] + BackupDestination = conf['BackupDestination'] + except: + Backuptype = "Backup type not exists" + + Data['job'].append({ + 'id': sub.id, + 'title': web, + 'Backuptype': Backuptype, + 'BackupDestination': BackupDestination + }) + + proc = httpProc(request, 'websiteFunctions/RestoreBackups.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def AutoLogin(self, request=None, userID=None): + + WPid = request.GET.get('id') + currentACL = ACLManager.loadedACL(userID) + WPobj = WPSites.objects.get(pk=WPid) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(WPobj.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + from managePHP.phpManager import PHPManager + + php = PHPManager.getPHPString(WPobj.owner.phpSelection) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" + data = { + "name": "wp-manager", + "IP": ACLManager.GetServerIP() + } + + import requests + response = requests.post(url, data=json.dumps(data)) + Status = response.json()['status'] + + if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: + + ## Get title + + password = randomPassword.generate_pass(10) + + command = f'sudo -u %s {FinalPHPPath} /usr/bin/wp user create autologin %s --role=administrator --user_pass="%s" --path=%s --skip-plugins --skip-themes' % ( + WPobj.owner.externalApp, 'autologin@cloudpages.cloud', password, WPobj.path) + ProcessUtilities.executioner(command) + + command = f'sudo -u %s {FinalPHPPath} /usr/bin/wp user update autologin --user_pass="%s" --path=%s --skip-plugins --skip-themes' % ( + WPobj.owner.externalApp, password, WPobj.path) + ProcessUtilities.executioner(command) + + data = {} + + if WPobj.FinalURL.endswith('/'): + FinalURL = WPobj.FinalURL[:-1] + else: + FinalURL = WPobj.FinalURL + + data['url'] = 'https://%s' % (FinalURL) + data['userName'] = 'autologin' + data['password'] = password + + proc = httpProc(request, 'websiteFunctions/AutoLogin.html', + data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def ConfigurePlugins(self, request=None, userID=None, data=None): + + if ACLManager.CheckForPremFeature('wp-manager'): + currentACL = ACLManager.loadedACL(userID) + userobj = Administrator.objects.get(pk=userID) + + Selectedplugins = wpplugins.objects.filter(owner=userobj) + # data['Selectedplugins'] = wpplugins.objects.filter(ProjectOwner=HostingCompany) + + Data = {'Selectedplugins': Selectedplugins, } + proc = httpProc(request, 'websiteFunctions/WPConfigurePlugins.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def Addnewplugin(self, request=None, userID=None, data=None): + from django.shortcuts import reverse + if ACLManager.CheckForPremFeature('wp-manager'): + currentACL = ACLManager.loadedACL(userID) + adminNames = ACLManager.loadAllUsers(userID) + packagesName = ACLManager.loadPackages(userID, currentACL) + phps = PHPManager.findPHPVersions() + + Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps} + proc = httpProc(request, 'websiteFunctions/WPAddNewPlugin.html', + Data, 'createDatabase') + return proc.render() + + return redirect(reverse('pricing')) + + def SearchOnkeyupPlugin(self, userID=None, data=None): + try: + if ACLManager.CheckForPremFeature('wp-manager'): + currentACL = ACLManager.loadedACL(userID) + + pluginname = data['pluginname'] + # logging.CyberCPLogFileWriter.writeToFile("Plugin Name ....... %s"%pluginname) + + url = "http://api.wordpress.org/plugins/info/1.1/?action=query_plugins&request[search]=%s" % str( + pluginname) + import requests + + res = requests.get(url) + r = res.json() + + # return proc.ajax(1, 'Done', {'plugins': r}) + + data_ret = {'status': 1, 'plugns': r, } + + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': 'Premium feature not available.'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def AddNewpluginAjax(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + + userobj = Administrator.objects.get(pk=userID) + + config = data['config'] + Name = data['Name'] + # pluginname = data['pluginname'] + # logging.CyberCPLogFileWriter.writeToFile("config ....... %s"%config) + # logging.CyberCPLogFileWriter.writeToFile(" Name ....... %s"%Name) + + addpl = wpplugins(Name=Name, config=json.dumps(config), owner=userobj) + addpl.save() + + data_ret = {'status': 1} + + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'AddNewpluginAjax': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def EidtPlugin(self, request=None, userID=None, pluginbID=None): + Data = {} + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + pluginobj = wpplugins.objects.get(pk=pluginbID) + + if ACLManager.CheckIPPluginObjectOwner(currentACL, pluginobj, admin) == 1: + pass + else: + return ACLManager.loadError() + + lmo = json.loads(pluginobj.config) + Data['Selectedplugins'] = lmo + Data['pluginbID'] = pluginbID + Data['BucketName'] = pluginobj.Name + + proc = httpProc(request, 'websiteFunctions/WPEidtPlugin.html', + Data, 'createDatabase') + return proc.render() + + def deletesPlgin(self, userID=None, data=None, ): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + userobj = Administrator.objects.get(pk=userID) + pluginname = data['pluginname'] + pluginbBucketID = data['pluginbBucketID'] + # logging.CyberCPLogFileWriter.writeToFile("pluginbID ....... %s" % pluginbBucketID) + # logging.CyberCPLogFileWriter.writeToFile("pluginname ....... %s" % pluginname) + + obj = wpplugins.objects.get(pk=pluginbBucketID, owner=userobj) + + if ACLManager.CheckIPPluginObjectOwner(currentACL, obj, admin) == 1: + pass + else: + return ACLManager.loadError() + + ab = [] + ab = json.loads(obj.config) + ab.remove(pluginname) + obj.config = json.dumps(ab) + obj.save() + + data_ret = {'status': 1} + + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + except BaseException as msg: + data_ret = {'status': 0, 'deletesPlgin': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def Addplugineidt(self, userID=None, data=None, ): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + userobj = Administrator.objects.get(pk=userID) + pluginname = data['pluginname'] + pluginbBucketID = data['pluginbBucketID'] + + # logging.CyberCPLogFileWriter.writeToFile("pluginbID ....... %s" % pluginbBucketID) + # logging.CyberCPLogFileWriter.writeToFile("pluginname ....... %s" % pluginname) + + pObj = wpplugins.objects.get(pk=pluginbBucketID, owner=userobj) + + if ACLManager.CheckIPPluginObjectOwner(currentACL, pObj, admin) == 1: + pass + else: + return ACLManager.loadError() + + listofplugin = json.loads(pObj.config) + try: + index = listofplugin.index(pluginname) + print('index.....%s' % index) + if (index >= 0): + data_ret = {'status': 0, 'deletesPlgin': 0, 'error_message': str('Already Save in your Plugin lis')} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except: + ab = [] + ab = json.loads(pObj.config) + ab.append(pluginname) + pObj.config = json.dumps(ab) + pObj.save() + + data_ret = {'status': 1} + + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + except BaseException as msg: + data_ret = {'status': 0, 'deletesPlgin': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def modifyWebsite(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + + websitesName = ACLManager.findAllSites(currentACL, userID) + phps = PHPManager.findPHPVersions() + proc = httpProc(request, 'websiteFunctions/modifyWebsite.html', + {'websiteList': websitesName, 'phps': phps}, 'modifyWebsite') + return proc.render() + + def deleteWebsite(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + websitesName = ACLManager.findAllSites(currentACL, userID) + proc = httpProc(request, 'websiteFunctions/deleteWebsite.html', + {'websiteList': websitesName}, 'deleteWebsite') + return proc.render() + + def CreateNewDomain(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + websitesName = ACLManager.findAllSites(currentACL, userID) + + try: + admin = Administrator.objects.get(pk=userID) + if admin.defaultSite == 0: + websites = ACLManager.findWebsiteObjects(currentACL, userID) + admin.defaultSite = websites[0].id + admin.save() + except: + pass + + try: + admin = Administrator.objects.get(pk=userID) + defaultDomain = Websites.objects.get(pk=admin.defaultSite).domain + except: + try: + admin = Administrator.objects.get(pk=userID) + websites = ACLManager.findWebsiteObjects(currentACL, userID) + admin.defaultSite = websites[0].id + admin.save() + defaultDomain = websites[0].domain + except: + defaultDomain='NONE' + + + url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" + data = { + "name": "all", + "IP": ACLManager.GetServerIP() + } + + import requests + response = requests.post(url, data=json.dumps(data)) + Status = response.json()['status'] + + test_domain_status = 0 + + if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: + test_domain_status = 1 + + rnpss = randomPassword.generate_pass(10) + proc = httpProc(request, 'websiteFunctions/createDomain.html', + {'websiteList': websitesName, 'phps': PHPManager.findPHPVersions(), 'Randam_String': rnpss, + 'test_domain_data': test_domain_status, 'defaultSite': defaultDomain}) + return proc.render() + + def siteState(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + + websitesName = ACLManager.findAllSites(currentACL, userID) + + proc = httpProc(request, 'websiteFunctions/suspendWebsite.html', + {'websiteList': websitesName}, 'suspendWebsite') + return proc.render() + + def listWebsites(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + pagination = self.websitePagination(currentACL, userID) + proc = httpProc(request, 'websiteFunctions/listWebsites.html', + {"pagination": pagination}) + return proc.render() + + def listChildDomains(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + adminNames = ACLManager.loadAllUsers(userID) + packagesName = ACLManager.loadPackages(userID, currentACL) + phps = PHPManager.findPHPVersions() + + Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps} + proc = httpProc(request, 'websiteFunctions/listChildDomains.html', + Data) + return proc.render() + + def listCron(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(request.GET.get('domain'), admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + proc = httpProc(request, 'websiteFunctions/listCron.html', + {'domain': request.GET.get('domain')}) + return proc.render() + + def domainAlias(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + aliasManager = AliasManager(self.domain) + noAlias, finalAlisList = aliasManager.fetchAlisForDomains() + + path = "/home/" + self.domain + "/public_html" + + proc = httpProc(request, 'websiteFunctions/domainAlias.html', { + 'masterDomain': self.domain, + 'aliases': finalAlisList, + 'path': path, + 'noAlias': noAlias + }) + return proc.render() + + def FetchWPdata(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core version --skip-plugins --skip-themes --path=%s 2>/dev/null' % ( + Vhuser, FinalPHPPath, path) + version = ProcessUtilities.outputExecutioner(command, None, True) + version = html.escape(version) + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin status litespeed-cache --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, path) + lscachee = ProcessUtilities.outputExecutioner(command) + + if lscachee.find('Status: Active') > -1: + lscache = 1 + else: + lscache = 0 + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp config list --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, path) + stdout = ProcessUtilities.outputExecutioner(command) + debugging = 0 + for items in stdout.split('\n'): + if items.find('WP_DEBUG true constant') > -1: + debugging = 1 + break + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp option get blog_public --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, path) + stdoutput = ProcessUtilities.outputExecutioner(command) + searchindex = int(stdoutput.splitlines()[-1]) + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp maintenance-mode status --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, path) + maintenanceMod = ProcessUtilities.outputExecutioner(command) + + result = maintenanceMod.splitlines()[-1] + if result.find('not active') > -1: + maintenanceMode = 0 + else: + maintenanceMode = 1 + + ##### Check passwd protection + vhostName = wpsite.owner.domain + vhostPassDir = f'/home/{vhostName}' + path = f'{vhostPassDir}/{WPManagerID}' + if os.path.exists(path): + passwd = 1 + else: + passwd = 0 + + #### Check WP cron + command = "sudo -u %s cat %s/wp-config.php" % (Vhuser, wpsite.path) + stdout = ProcessUtilities.outputExecutioner(command) + if stdout.find("'DISABLE_WP_CRON', 'true'") > -1: + wpcron = 1 + else: + wpcron = 0 + + fb = { + 'version': version.rstrip('\n'), + 'lscache': lscache, + 'debugging': debugging, + 'searchIndex': searchindex, + 'maintenanceMode': maintenanceMode, + 'passwordprotection': passwd, + 'wpcron': wpcron + + } + + data_ret = {'status': 1, 'error_message': 'None', 'ret_data': fb} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def GetCurrentPlugins(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin list --skip-plugins --skip-themes --format=json --path=%s' % ( + Vhuser, FinalPHPPath, path) + stdoutput = ProcessUtilities.outputExecutioner(command) + json_data = stdoutput.splitlines()[-1] + + data_ret = {'status': 1, 'error_message': 'None', 'plugins': json_data} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def GetCurrentThemes(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp theme list --skip-plugins --skip-themes --format=json --path=%s' % ( + Vhuser, FinalPHPPath, path) + stdoutput = ProcessUtilities.outputExecutioner(command) + json_data = stdoutput.splitlines()[-1] + + data_ret = {'status': 1, 'error_message': 'None', 'themes': json_data} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def fetchstaging(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + from plogical.phpUtilities import phpUtilities + + json_data = phpUtilities.GetStagingInJson(wpsite.wpstaging_set.all().order_by('-id')) + + data_ret = {'status': 1, 'error_message': 'None', 'wpsites': json_data} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def fetchDatabase(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + php = PHPManager.getPHPString(wpsite.owner.phpSelection) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + command = f'{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config get DB_NAME --skip-plugins --skip-themes --path={wpsite.path} 2>/dev/null' + retStatus, stdoutput = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp, True, None, 1) + + if stdoutput.find('Error:') == -1: + DataBaseName = stdoutput.rstrip("\n") + DataBaseName = html.escape(DataBaseName) + else: + data_ret = {'status': 0, 'error_message': stdoutput} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + command = f'{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config get DB_USER --skip-plugins --skip-themes --path={wpsite.path} 2>/dev/null' + retStatus, stdoutput = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp, True, None, 1) + + if stdoutput.find('Error:') == -1: + DataBaseUser = stdoutput.rstrip("\n") + DataBaseUser = html.escape(DataBaseUser) + else: + data_ret = {'status': 0, 'error_message': stdoutput} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + command = f'{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config get table_prefix --skip-plugins --skip-themes --path={wpsite.path} 2>/dev/null' + retStatus, stdoutput = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp, True, None, 1) + + if stdoutput.find('Error:') == -1: + tableprefix = stdoutput.rstrip("\n") + tableprefix = html.escape(tableprefix) + else: + data_ret = {'status': 0, 'error_message': stdoutput} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + data_ret = {'status': 1, 'error_message': 'None', "DataBaseUser": DataBaseUser, + "DataBaseName": DataBaseName, 'tableprefix': tableprefix} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def SaveUpdateConfig(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + Plugins = data['Plugins'] + Themes = data['Themes'] + AutomaticUpdates = data['AutomaticUpdates'] + + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + + php = PHPManager.getPHPString(wpsite.owner.phpSelection) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + if AutomaticUpdates == 'Disabled': + command = f"{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_AUTO_UPDATE_CORE false --raw --allow-root --path=" + wpsite.path + result = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp) + + if result.find('Success:') == -1: + raise BaseException(result) + elif AutomaticUpdates == 'Minor and Security Updates': + command = f"{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_AUTO_UPDATE_CORE minor --allow-root --path=" + wpsite.path + result = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp) + + if result.find('Success:') == -1: + raise BaseException(result) + else: + command = f"{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_AUTO_UPDATE_CORE true --raw --allow-root --path=" + wpsite.path + result = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp) + + if result.find('Success:') == -1: + raise BaseException(result) + + wpsite.AutoUpdates = AutomaticUpdates + wpsite.PluginUpdates = Plugins + wpsite.ThemeUpdates = Themes + wpsite.save() + + data_ret = {'status': 1, 'error_message': 'None', } + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def DeploytoProduction(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + statgingID = data['StagingID'] + wpsite = WPSites.objects.get(pk=WPManagerID) + StagingObj = WPSites.objects.get(pk=statgingID) + + ### + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + if ACLManager.checkOwnership(StagingObj.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + ### + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['statgingID'] = statgingID + extraArgs['WPid'] = WPManagerID + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + background = ApplicationInstaller('DeploytoProduction', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def WPCreateBackup(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + Backuptype = data['Backuptype'] + + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['WPid'] = WPManagerID + extraArgs['Backuptype'] = Backuptype + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + background = ApplicationInstaller('WPCreateBackup', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def RestoreWPbackupNow(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + backupid = data['backupid'] + DesSiteID = data['DesSite'] + + # try: + # + # bwp = WPSites.objects.get(pk=int(backupid)) + # + # if ACLManager.checkOwnership(bwp.owner.domain, admin, currentACL) == 1: + # pass + # else: + # return ACLManager.loadError() + # + # except: + # pass + # + # dwp = WPSites.objects.get(pk=int(DesSiteID)) + # if ACLManager.checkOwnership(dwp.owner.domain, admin, currentACL) == 1: + # pass + # else: + # return ACLManager.loadError() + + Domain = data['Domain'] + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['backupid'] = backupid + extraArgs['DesSiteID'] = DesSiteID + extraArgs['Domain'] = Domain + extraArgs['path'] = data['path'] + extraArgs['home'] = data['home'] + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + background = ApplicationInstaller('RestoreWPbackupNow', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def SaveBackupConfig(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + ConfigType = data['type'] + if ConfigType == 'SFTP': + Hname = data['Hname'] + Uname = data['Uname'] + Passwd = data['Passwd'] + path = data['path'] + config = { + "Hostname": Hname, + "Username": Uname, + "Password": Passwd, + "Path": path + } + elif ConfigType == "S3": + Provider = data['Provider'] + if Provider == "Backblaze": + S3keyname = data['S3keyname'] + SecertKey = data['SecertKey'] + AccessKey = data['AccessKey'] + EndUrl = data['EndUrl'] + config = { + "Provider": Provider, + "S3keyname": S3keyname, + "SecertKey": SecertKey, + "AccessKey": AccessKey, + "EndUrl": EndUrl + + } + else: + S3keyname = data['S3keyname'] + SecertKey = data['SecertKey'] + AccessKey = data['AccessKey'] + config = { + "Provider": Provider, + "S3keyname": S3keyname, + "SecertKey": SecertKey, + "AccessKey": AccessKey, + + } + + mkobj = RemoteBackupConfig(owner=admin, configtype=ConfigType, config=json.dumps(config)) + mkobj.save() + + time.sleep(1) + + data_ret = {'status': 1, 'error_message': 'None', } + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def SaveBackupSchedule(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + FileRetention = data['FileRetention'] + Backfrequency = data['Backfrequency'] + ScheduleName = data['ScheduleName'] + RemoteConfigID = data['RemoteConfigID'] + BackupType = data['BackupType'] + + RemoteBackupConfigobj = RemoteBackupConfig.objects.get(pk=RemoteConfigID) + Rconfig = json.loads(RemoteBackupConfigobj.config) + + try: + # This code is only supposed to run if backups are s3, not for SFTP + provider = Rconfig['Provider'] + if provider == "Backblaze": + EndURl = Rconfig['EndUrl'] + elif provider == "Amazon": + EndURl = "https://s3.us-east-1.amazonaws.com" + elif provider == "Wasabi": + EndURl = "https://s3.wasabisys.com" + + AccessKey = Rconfig['AccessKey'] + SecertKey = Rconfig['SecertKey'] + + session = boto3.session.Session() + + client = session.client( + 's3', + endpoint_url=EndURl, + aws_access_key_id=AccessKey, + aws_secret_access_key=SecertKey, + verify=False + ) + + ############Creating Bucket + BucketName = randomPassword.generate_pass().lower() + + try: + client.create_bucket(Bucket=BucketName) + except BaseException as msg: + logging.CyberCPLogFileWriter.writeToFile("Creating Bucket Error: %s" % str(msg)) + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + config = { + 'BackupType': BackupType, + 'BucketName': BucketName + } + except BaseException as msg: + config = {'BackupType': BackupType} + pass + + svobj = RemoteBackupSchedule(RemoteBackupConfig=RemoteBackupConfigobj, Name=ScheduleName, + timeintervel=Backfrequency, fileretention=FileRetention, + config=json.dumps(config), + lastrun=str(time.time())) + svobj.save() + + data_ret = {'status': 1, 'error_message': 'None', } + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def AddWPsiteforRemoteBackup(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + WPid = data['WpsiteID'] + RemoteScheduleID = data['RemoteScheduleID'] + + wpsiteobj = WPSites.objects.get(pk=WPid) + WPpath = wpsiteobj.path + VHuser = wpsiteobj.owner.externalApp + PhpVersion = wpsiteobj.owner.phpSelection + php = PHPManager.getPHPString(PhpVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + ####Get DB Name + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp config get DB_NAME --skip-plugins --skip-themes --path=%s' % ( + VHuser, FinalPHPPath, WPpath) + result, stdout = ProcessUtilities.outputExecutioner(command, None, None, None, 1) + + if stdout.find('Error:') > -1: + raise BaseException(stdout) + else: + Finaldbname = stdout.rstrip("\n") + + ## Get DB obj + try: + DBobj = Databases.objects.get(dbName=Finaldbname) + except: + raise BaseException(str("DataBase Not Found")) + RemoteScheduleIDobj = RemoteBackupSchedule.objects.get(pk=RemoteScheduleID) + + svobj = RemoteBackupsites(owner=RemoteScheduleIDobj, WPsites=WPid, database=DBobj.pk) + svobj.save() + + data_ret = {'status': 1, 'error_message': 'None', } + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def UpdateRemoteschedules(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + ScheduleID = data['ScheduleID'] + Frequency = data['Frequency'] + FileRetention = data['FileRetention'] + + scheduleobj = RemoteBackupSchedule.objects.get(pk=ScheduleID) + scheduleobj.timeintervel = Frequency + scheduleobj.fileretention = FileRetention + scheduleobj.save() + + data_ret = {'status': 1, 'error_message': 'None', } + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def ScanWordpressSite(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + allweb = Websites.objects.all() + + childdomain = ChildDomains.objects.all() + + for web in allweb: + webpath = "/home/%s/public_html/" % web.domain + command = "cat %swp-config.php" % webpath + result = ProcessUtilities.outputExecutioner(command, web.externalApp) + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(result) + + if result.find('No such file or directory') == -1: + try: + WPSites.objects.get(path=webpath) + except: + wpobj = WPSites(owner=web, title=web.domain, path=webpath, FinalURL=web.domain, + AutoUpdates="Enabled", PluginUpdates="Enabled", + ThemeUpdates="Enabled", ) + wpobj.save() + + for chlid in childdomain: + childPath = chlid.path.rstrip('/') + + command = "cat %s/wp-config.php" % childPath + result = ProcessUtilities.outputExecutioner(command, chlid.master.externalApp) + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(result) + + if result.find('No such file or directory') == -1: + fChildPath = f'{childPath}/' + try: + WPSites.objects.get(path=fChildPath) + except: + + wpobj = WPSites(owner=chlid.master, title=chlid.domain, path=fChildPath, FinalURL=chlid.domain, + AutoUpdates="Enabled", PluginUpdates="Enabled", + ThemeUpdates="Enabled", ) + wpobj.save() + + data_ret = {'status': 1, 'error_message': 'None', } + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def installwpcore(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + ###fetch WP version + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core version --skip-plugins --skip-themes --path=%s 2>/dev/null' % ( + Vhuser, FinalPHPPath, path) + version = ProcessUtilities.outputExecutioner(command, None, True) + version = version.rstrip("\n") + + ###install wp core + command = f"sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp core download --force --skip-content --version={version} --path={path}" + output = ProcessUtilities.outputExecutioner(command) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', 'result': output} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def dataintegrity(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + ###fetch WP version + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core verify-checksums --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, path) + result = ProcessUtilities.outputExecutioner(command) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', 'result': result} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def UpdatePlugins(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + plugin = data['plugin'] + pluginarray = data['pluginarray'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['plugin'] = plugin + extraArgs['pluginarray'] = pluginarray + extraArgs['FinalPHPPath'] = FinalPHPPath + extraArgs['path'] = path + extraArgs['Vhuser'] = Vhuser + + background = ApplicationInstaller('UpdateWPPlugin', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def UpdateThemes(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + Theme = data['Theme'] + Themearray = data['Themearray'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['Theme'] = Theme + extraArgs['Themearray'] = Themearray + extraArgs['FinalPHPPath'] = FinalPHPPath + extraArgs['path'] = path + extraArgs['Vhuser'] = Vhuser + + background = ApplicationInstaller('UpdateWPTheme', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def DeletePlugins(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + plugin = data['plugin'] + pluginarray = data['pluginarray'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['plugin'] = plugin + extraArgs['pluginarray'] = pluginarray + extraArgs['FinalPHPPath'] = FinalPHPPath + extraArgs['path'] = path + extraArgs['Vhuser'] = Vhuser + + background = ApplicationInstaller('DeletePlugins', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def DeleteThemes(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + Theme = data['Theme'] + Themearray = data['Themearray'] + wpsite = WPSites.objects.get(pk=WPManagerID) + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['Theme'] = Theme + extraArgs['Themearray'] = Themearray + extraArgs['FinalPHPPath'] = FinalPHPPath + extraArgs['path'] = path + extraArgs['Vhuser'] = Vhuser + + background = ApplicationInstaller('DeleteThemes', extraArgs) + background.start() + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def ChangeStatus(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + plugin = data['plugin'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin status %s --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, plugin, path) + stdoutput = ProcessUtilities.outputExecutioner(command) + + if stdoutput.find('Status: Active') > -1: + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin deactivate %s --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, plugin, path) + stdoutput = ProcessUtilities.outputExecutioner(command) + time.sleep(3) + + else: + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin activate %s --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, plugin, path) + stdoutput = ProcessUtilities.outputExecutioner(command) + time.sleep(3) + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def ChangeStatusThemes(self, userID=None, data=None): + try: + # logging.CyberCPLogFileWriter.writeToFile("Error WP ChangeStatusThemes ....... %s") + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + Theme = data['theme'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['Theme'] = Theme + extraArgs['FinalPHPPath'] = FinalPHPPath + extraArgs['path'] = path + extraArgs['Vhuser'] = Vhuser + + background = ApplicationInstaller('ChangeStatusThemes', extraArgs) + background.start() + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def CreateStagingNow(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['StagingDomain'] = data['StagingDomain'] + extraArgs['StagingName'] = data['StagingName'] + extraArgs['WPid'] = data['WPid'] + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + wpsite = WPSites.objects.get(pk=data['WPid']) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + background = ApplicationInstaller('CreateStagingNow', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def UpdateWPSettings(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + siteId = data['siteId'] + setting = data['setting'] + value = data['value'] + + wpsite = WPSites.objects.get(pk=siteId) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) != 1: + return ACLManager.loadError() + + # Get PHP version and path + Webobj = Websites.objects.get(pk=wpsite.owner_id) + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + # Update the appropriate setting based on the setting type + if setting == 'search-indexing': + # Update search engine indexing + command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp option update blog_public {value} --skip-plugins --skip-themes --path={wpsite.path}' + elif setting == 'debugging': + # Update debugging in wp-config.php + if value: + command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_DEBUG true --raw --skip-plugins --skip-themes --path={wpsite.path}' + else: + command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_DEBUG false --raw --skip-plugins --skip-themes --path={wpsite.path}' + elif setting == 'password-protection': + vhostName = wpsite.owner.domain + vhostPassDir = f'/home/{vhostName}' + path = f'{vhostPassDir}/{siteId}' + if value: + # Enable password protection + if not os.path.exists(path): + os.makedirs(path) + htpasswd = f'{path}/.htpasswd' + htaccess = f'{wpsite.path}/.htaccess' + password = randomPassword.generate_pass(12) + + # Create .htpasswd file + command = f"htpasswd -cb {htpasswd} admin {password}" + ProcessUtilities.executioner(command) + + # Create .htaccess file + htaccess_content = f"""AuthType Basic +AuthName "Restricted Access" +AuthUserFile {htpasswd} +Require valid-user +Require valid-user""" + with open(htaccess, 'w') as f: + f.write(htaccess_content) + else: + # Disable password protection + if os.path.exists(path): + import shutil + shutil.rmtree(path) + htaccess = f'{wpsite.path}/.htaccess' + if os.path.exists(htaccess): + os.remove(htaccess) + return JsonResponse({'status': 1, 'error_message': 'None'}) + + def submitWebsiteModify(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + if ACLManager.currentContextPermission(currentACL, 'modifyWebsite') == 0: + return ACLManager.loadErrorJson('modifyStatus', 0) + + admin = Administrator.objects.get(pk=userID) + if ACLManager.checkOwnership(data['websiteToBeModified'], admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('websiteDeleteStatus', 0) + + packs = ACLManager.loadPackages(userID, currentACL) + admins = ACLManager.loadAllUsers(userID) + + ## Get packs name + + json_data = "[" + checker = 0 + + for items in packs: + dic = {"pack": items} + + if checker == 0: + json_data = json_data + json.dumps(dic) + checker = 1 + else: + json_data = json_data + ',' + json.dumps(dic) + + json_data = json_data + ']' + + ### Get admin names + + admin_data = "[" + checker = 0 + + for items in admins: + dic = {"adminNames": items} + + if checker == 0: + admin_data = admin_data + json.dumps(dic) + checker = 1 + else: + admin_data = admin_data + ',' + json.dumps(dic) + + admin_data = admin_data + ']' + + websiteToBeModified = data['websiteToBeModified'] + + modifyWeb = Websites.objects.get(domain=websiteToBeModified) + + email = modifyWeb.adminEmail + currentPack = modifyWeb.package.packageName + owner = modifyWeb.admin.userName + + data_ret = {'status': 1, 'modifyStatus': 1, 'error_message': "None", "adminEmail": email, + "packages": json_data, "current_pack": currentPack, "adminNames": admin_data, + 'currentAdmin': owner} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + + except BaseException as msg: + dic = {'status': 0, 'modifyStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def fetchWebsiteDataJSON(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + if ACLManager.currentContextPermission(currentACL, 'createWebsite') == 0: + return ACLManager.loadErrorJson('createWebSiteStatus', 0) + + packs = ACLManager.loadPackages(userID, currentACL) + admins = ACLManager.loadAllUsers(userID) + + ## Get packs name + + json_data = "[" + checker = 0 + + for items in packs: + dic = {"pack": items} + + if checker == 0: + json_data = json_data + json.dumps(dic) + checker = 1 + else: + json_data = json_data + ',' + json.dumps(dic) + + json_data = json_data + ']' + + ### Get admin names + + admin_data = "[" + checker = 0 + + for items in admins: + dic = {"adminNames": items} + + if checker == 0: + admin_data = admin_data + json.dumps(dic) + checker = 1 + else: + admin_data = admin_data + ',' + json.dumps(dic) + + admin_data = admin_data + ']' + + data_ret = {'status': 1, 'error_message': "None", + "packages": json_data, "adminNames": admin_data} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + + except BaseException as msg: + dic = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def saveWebsiteChanges(self, userID=None, data=None): + try: + domain = data['domain'] + package = data['packForWeb'] + email = data['email'] + phpVersion = data['phpVersion'] + newUser = data['admin'] + + currentACL = ACLManager.loadedACL(userID) + if ACLManager.currentContextPermission(currentACL, 'modifyWebsite') == 0: + return ACLManager.loadErrorJson('saveStatus', 0) + + admin = Administrator.objects.get(pk=userID) + if ACLManager.checkOwnership(domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('websiteDeleteStatus', 0) + + newOwner = Administrator.objects.get(userName=newUser) + if ACLManager.checkUserOwnerShip(currentACL, admin, newOwner) == 1: + pass + else: + return ACLManager.loadErrorJson('websiteDeleteStatus', 0) + + confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + domain + completePathToConfigFile = confPath + "/vhost.conf" + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " changePHP --phpVersion '" + phpVersion + "' --path " + completePathToConfigFile + ProcessUtilities.popenExecutioner(execPath) + + #### + + newOwner = Administrator.objects.get(userName=newUser) + + modifyWeb = Websites.objects.get(domain=domain) + webpack = Package.objects.get(packageName=package) + + modifyWeb.package = webpack + modifyWeb.adminEmail = email + modifyWeb.phpSelection = phpVersion + modifyWeb.admin = newOwner + + modifyWeb.save() + + ## Fix https://github.com/usmannasir/cyberpanel/issues/998 + + # from plogical.IncScheduler import IncScheduler + # isPU = IncScheduler('CalculateAndUpdateDiskUsage', {}) + # isPU.start() + + command = '/usr/local/CyberCP/bin/python /usr/local/CyberCP/plogical/IncScheduler.py UpdateDiskUsageForce' + ProcessUtilities.outputExecutioner(command) + + ## + + data_ret = {'status': 1, 'saveStatus': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'saveStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def loadDomainHome(self, request=None, userID=None, data=None): + + if Websites.objects.filter(domain=self.domain).exists(): + + currentACL = ACLManager.loadedACL(userID) + website = Websites.objects.get(domain=self.domain) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + Data = {} + + marketingStatus = emACL.checkIfEMEnabled(admin.userName) + + Data['marketingStatus'] = marketingStatus + Data['ftpTotal'] = website.package.ftpAccounts + Data['ftpUsed'] = website.users_set.all().count() + + Data['databasesUsed'] = website.databases_set.all().count() + Data['databasesTotal'] = website.package.dataBases + + Data['domain'] = self.domain + + DiskUsage, DiskUsagePercentage, bwInMB, bwUsage = virtualHostUtilities.FindStats(website) + + ## bw usage calculations + + Data['bwInMBTotal'] = website.package.bandwidth + Data['bwInMB'] = bwInMB + Data['bwUsage'] = bwUsage + + if DiskUsagePercentage > 100: + DiskUsagePercentage = 100 + + Data['diskUsage'] = DiskUsagePercentage + Data['diskInMB'] = DiskUsage + Data['diskInMBTotal'] = website.package.diskSpace + + Data['phps'] = PHPManager.findPHPVersions() + + servicePath = '/home/cyberpanel/postfix' + if os.path.exists(servicePath): + Data['email'] = 1 + else: + Data['email'] = 0 + + ## Getting SSL Information + try: + import OpenSSL + from datetime import datetime + filePath = '/etc/letsencrypt/live/%s/fullchain.pem' % (self.domain) + x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, + open(filePath, 'r').read()) + expireData = x509.get_notAfter().decode('ascii') + finalDate = datetime.strptime(expireData, '%Y%m%d%H%M%SZ') + + now = datetime.now() + diff = finalDate - now + Data['viewSSL'] = 1 + Data['days'] = str(diff.days) + Data['authority'] = x509.get_issuer().get_components()[1][1].decode('utf-8') + + if Data['authority'] == 'Denial': + Data['authority'] = '%s has SELF-SIGNED SSL.' % (self.domain) + else: + Data['authority'] = '%s has SSL from %s.' % (self.domain, Data['authority']) + + except BaseException as msg: + Data['viewSSL'] = 0 + logging.CyberCPLogFileWriter.writeToFile(str(msg)) + + servicePath = '/home/cyberpanel/pureftpd' + if os.path.exists(servicePath): + Data['ftp'] = 1 + else: + Data['ftp'] = 0 + + proc = httpProc(request, 'websiteFunctions/website.html', Data) + return proc.render() + else: + proc = httpProc(request, 'websiteFunctions/website.html', + {"error": 1, "domain": "This domain does not exists."}) + return proc.render() + + def launchChild(self, request=None, userID=None, data=None): + + if ChildDomains.objects.filter(domain=self.childDomain).exists(): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + website = Websites.objects.get(domain=self.domain) + + Data = {} + + Data['ftpTotal'] = website.package.ftpAccounts + Data['ftpUsed'] = website.users_set.all().count() + + Data['databasesUsed'] = website.databases_set.all().count() + Data['databasesTotal'] = website.package.dataBases + + Data['domain'] = self.domain + Data['childDomain'] = self.childDomain + + DiskUsage, DiskUsagePercentage, bwInMB, bwUsage = virtualHostUtilities.FindStats(website) + + ## bw usage calculations + + Data['bwInMBTotal'] = website.package.bandwidth + Data['bwInMB'] = bwInMB + Data['bwUsage'] = bwUsage + + if DiskUsagePercentage > 100: + DiskUsagePercentage = 100 + + Data['diskUsage'] = DiskUsagePercentage + Data['diskInMB'] = DiskUsage + Data['diskInMBTotal'] = website.package.diskSpace + + Data['phps'] = PHPManager.findPHPVersions() + + servicePath = '/home/cyberpanel/postfix' + if os.path.exists(servicePath): + Data['email'] = 1 + else: + Data['email'] = 0 + + servicePath = '/home/cyberpanel/pureftpd' + if os.path.exists(servicePath): + Data['ftp'] = 1 + else: + Data['ftp'] = 0 + + ## Getting SSL Information + try: + import OpenSSL + from datetime import datetime + filePath = '/etc/letsencrypt/live/%s/fullchain.pem' % (self.childDomain) + x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, + open(filePath, 'r').read()) + expireData = x509.get_notAfter().decode('ascii') + finalDate = datetime.strptime(expireData, '%Y%m%d%H%M%SZ') + + now = datetime.now() + diff = finalDate - now + Data['viewSSL'] = 1 + Data['days'] = str(diff.days) + Data['authority'] = x509.get_issuer().get_components()[1][1].decode('utf-8') + + if Data['authority'] == 'Denial': + Data['authority'] = '%s has SELF-SIGNED SSL.' % (self.childDomain) + else: + Data['authority'] = '%s has SSL from %s.' % (self.childDomain, Data['authority']) + + except BaseException as msg: + Data['viewSSL'] = 0 + logging.CyberCPLogFileWriter.writeToFile(str(msg)) + + proc = httpProc(request, 'websiteFunctions/launchChild.html', Data) + return proc.render() + else: + proc = httpProc(request, 'websiteFunctions/launchChild.html', + {"error": 1, "domain": "This child domain does not exists"}) + return proc.render() + + def getDataFromLogFile(self, userID=None, data=None): + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + logType = data['logType'] + self.domain = data['virtualHost'] + page = data['page'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('logstatus', 0) + + if logType == 1: + fileName = "/home/" + self.domain + "/logs/" + self.domain + ".access_log" + else: + fileName = "/home/" + self.domain + "/logs/" + self.domain + ".error_log" + + command = 'ls -la %s' % fileName + result = ProcessUtilities.outputExecutioner(command) + + if result.find('->') > -1: + final_json = json.dumps( + {'status': 0, 'logstatus': 0, + 'error_message': "Symlink attack."}) + return HttpResponse(final_json) + + ## get Logs + website = Websites.objects.get(domain=self.domain) + + output = virtualHostUtilities.getAccessLogs(fileName, page, website.externalApp) + + if output.find("1,None") > -1: + final_json = json.dumps( + {'status': 0, 'logstatus': 0, + 'error_message': "Not able to fetch logs, see CyberPanel main log file, Error: %s" % (output)}) + return HttpResponse(final_json) + + ## get log ends here. + + data = output.split("\n") + + json_data = "[" + checker = 0 + + for items in reversed(data): + if len(items) > 10: + logData = items.split(" ") + domain = logData[5].strip('"') + ipAddress = logData[0].strip('"') + time = (logData[3]).strip("[").strip("]") + resource = logData[6].strip('"') + size = logData[9].replace('"', '') + + dic = {'domain': domain, + 'ipAddress': ipAddress, + 'time': time, + 'resource': resource, + 'size': size, + } + + if checker == 0: + json_data = json_data + json.dumps(dic) + checker = 1 + else: + json_data = json_data + ',' + json.dumps(dic) + + json_data = json_data + ']' + final_json = json.dumps({'status': 1, 'logstatus': 1, 'error_message': "None", "data": json_data}) + return HttpResponse(final_json) + + def fetchErrorLogs(self, userID=None, data=None): + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['virtualHost'] + page = data['page'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('logstatus', 0) + + fileName = "/home/" + self.domain + "/logs/" + self.domain + ".error_log" + + command = 'ls -la %s' % fileName + result = ProcessUtilities.outputExecutioner(command) + + if result.find('->') > -1: + final_json = json.dumps( + {'status': 0, 'logstatus': 0, + 'error_message': "Symlink attack."}) + return HttpResponse(final_json) + + ## get Logs + website = Websites.objects.get(domain=self.domain) + + output = virtualHostUtilities.getErrorLogs(fileName, page, website.externalApp) + + if output.find("1,None") > -1: + final_json = json.dumps( + {'status': 0, 'logstatus': 0, 'error_message': "Not able to fetch logs, see CyberPanel main log file!"}) + return HttpResponse(final_json) + + ## get log ends here. + + final_json = json.dumps({'status': 1, 'logstatus': 1, 'error_message': "None", "data": output}) + return HttpResponse(final_json) + + def getDataFromConfigFile(self, userID=None, data=None): + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + self.domain = data['virtualHost'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('configstatus', 0) + + command = 'cat %s' % ('/usr/local/lsws/conf/dvhost_redis.conf') + + if ProcessUtilities.outputExecutioner(command).find('127.0.0.1') == -1: + filePath = installUtilities.Server_root_path + "/conf/vhosts/" + self.domain + "/vhost.conf" + + command = 'cat ' + filePath + configData = ProcessUtilities.outputExecutioner(command, 'lsadm') + + if len(configData) == 0: + status = {'status': 0, "configstatus": 0, "error_message": "Configuration file is currently empty!"} + + final_json = json.dumps(status) + return HttpResponse(final_json) + + else: + command = 'redis-cli get "vhost:%s"' % (self.domain) + configData = ProcessUtilities.outputExecutioner(command) + configData = '#### This configuration is fetched from redis as Redis-Mass Hosting is being used.\n%s' % ( + configData) + + status = {'status': 1, "configstatus": 1, "configData": configData} + final_json = json.dumps(status) + return HttpResponse(final_json) + + def saveConfigsToFile(self, userID=None, data=None): + + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] != 1: + return ACLManager.loadErrorJson('configstatus', 0) + + configData = data['configData'] + self.domain = data['virtualHost'] + + if len(configData) == 0: + status = {"configstatus": 0, 'error_message': 'Error: you are trying to save empty vhost file, your website will stop working.'} + + final_json = json.dumps(status) + return HttpResponse(final_json) + + + command = 'cat %s' % ('/usr/local/lsws/conf/dvhost_redis.conf') + + if ProcessUtilities.outputExecutioner(command).find('127.0.0.1') == -1: + + mailUtilities.checkHome() + + tempPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + + vhost = open(tempPath, "w") + + vhost.write(configData) + + vhost.close() + + ## writing data temporary to file + + filePath = installUtilities.Server_root_path + "/conf/vhosts/" + self.domain + "/vhost.conf" + + ## save configuration data + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " saveVHostConfigs --path " + filePath + " --tempPath " + tempPath + + output = ProcessUtilities.outputExecutioner(execPath) + + if output.find("1,None") > -1: + status = {"configstatus": 1} + + final_json = json.dumps(status) + return HttpResponse(final_json) + else: + data_ret = {'configstatus': 0, 'error_message': output} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + ## save configuration data ends + else: + command = "redis-cli set vhost:%s '%s'" % (self.domain, configData.replace( + '#### This configuration is fetched from redis as Redis-Mass Hosting is being used.\n', '')) + ProcessUtilities.executioner(command) + + status = {"configstatus": 1} + + final_json = json.dumps(status) + return HttpResponse(final_json) + + def getRewriteRules(self, userID=None, data=None): + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + self.domain = data['virtualHost'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('rewriteStatus', 0) + + try: + childDom = ChildDomains.objects.get(domain=self.domain) + filePath = childDom.path + '/.htaccess' + externalApp = childDom.master.externalApp + except: + website = Websites.objects.get(domain=self.domain) + externalApp = website.externalApp + filePath = "/home/" + self.domain + "/public_html/.htaccess" + + try: + command = 'cat %s' % (filePath) + rewriteRules = ProcessUtilities.outputExecutioner(command, externalApp) + + if len(rewriteRules) == 0: + status = {"rewriteStatus": 1, "error_message": "Rules file is currently empty"} + final_json = json.dumps(status) + return HttpResponse(final_json) + + status = {"rewriteStatus": 1, "rewriteRules": rewriteRules} + + final_json = json.dumps(status) + return HttpResponse(final_json) + + except BaseException as msg: + status = {"rewriteStatus": 1, "error_message": str(msg), "rewriteRules": ""} + final_json = json.dumps(status) + return HttpResponse(final_json) + + def saveRewriteRules(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + self.domain = data['virtualHost'] + rewriteRules = data['rewriteRules'].encode('utf-8') + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('rewriteStatus', 0) + + ## writing data temporary to file + + mailUtilities.checkHome() + tempPath = "/tmp/" + str(randint(1000, 9999)) + vhost = open(tempPath, "wb") + vhost.write(rewriteRules) + vhost.close() + + ## writing data temporary to file + + try: + childDomain = ChildDomains.objects.get(domain=self.domain) + filePath = childDomain.path + '/.htaccess' + externalApp = childDomain.master.externalApp + except: + filePath = "/home/" + self.domain + "/public_html/.htaccess" + website = Websites.objects.get(domain=self.domain) + externalApp = website.externalApp + + ## save configuration data + + command = 'cp %s %s' % (tempPath, filePath) + ProcessUtilities.executioner(command, externalApp) + + command = 'rm -f %s' % (tempPath) + ProcessUtilities.executioner(command, 'cyberpanel') + + installUtilities.reStartLiteSpeedSocket() + status = {"rewriteStatus": 1, 'error_message': 'None'} + final_json = json.dumps(status) + return HttpResponse(final_json) + except BaseException as msg: + status = {"rewriteStatus": 0, 'error_message': str(msg)} + final_json = json.dumps(status) + return HttpResponse(final_json) + + def saveSSL(self, userID=None, data=None): + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + self.domain = data['virtualHost'] + key = data['key'] + cert = data['cert'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('sslStatus', 0) + + mailUtilities.checkHome() + + ## writing data temporary to file + + tempKeyPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + vhost = open(tempKeyPath, "w") + vhost.write(key) + vhost.close() + + tempCertPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + vhost = open(tempCertPath, "w") + vhost.write(cert) + vhost.close() + + ## writing data temporary to file + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " saveSSL --virtualHostName " + self.domain + " --tempKeyPath " + tempKeyPath + " --tempCertPath " + tempCertPath + output = ProcessUtilities.outputExecutioner(execPath) + + if output.find("1,None") > -1: + data_ret = {'sslStatus': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + logging.CyberCPLogFileWriter.writeToFile( + output) + data_ret = {'sslStatus': 0, 'error_message': output} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def changePHP(self, userID=None, data=None): + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + self.domain = data['childDomain'] + phpVersion = data['phpSelection'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('changePHP', 0) + + confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + self.domain + completePathToConfigFile = confPath + "/vhost.conf" + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " changePHP --phpVersion '" + phpVersion + "' --path " + completePathToConfigFile + ProcessUtilities.popenExecutioner(execPath) + + try: + website = Websites.objects.get(domain=self.domain) + website.phpSelection = data['phpSelection'] + website.save() + + ### check if there are any alias domains under the main website and then change php for them too + + for alias in website.childdomains_set.filter(alais=1): + + try: + + confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + alias.domain + completePathToConfigFile = confPath + "/vhost.conf" + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " changePHP --phpVersion '" + phpVersion + "' --path " + completePathToConfigFile + ProcessUtilities.popenExecutioner(execPath) + except BaseException as msg: + logging.CyberCPLogFileWriter.writeToFile(f'Error changing PHP for alias: {str(msg)}') + + + except: + website = ChildDomains.objects.get(domain=self.domain) + website.phpSelection = data['phpSelection'] + website.save() + + data_ret = {'status': 1, 'changePHP': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def getWebsiteCron(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + self.domain = data['domain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('getWebsiteCron', 0) + + website = Websites.objects.get(domain=self.domain) + + if Websites.objects.filter(domain=self.domain).exists(): + pass + else: + dic = {'getWebsiteCron': 0, 'error_message': 'You do not own this domain'} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + CronUtil.CronPrem(1) + + crons = [] + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" + execPath = execPath + " getWebsiteCron --externalApp " + website.externalApp + + f = ProcessUtilities.outputExecutioner(execPath, website.externalApp) + + CronUtil.CronPrem(0) + + if ProcessUtilities.decideDistro() == ProcessUtilities.centos or ProcessUtilities.decideDistro() == ProcessUtilities.cent8: + cronPath = "/var/spool/cron/" + website.externalApp + else: + cronPath = "/var/spool/cron/crontabs/" + website.externalApp + + if f.find('Permission denied') > -1: + command = 'chmod 644 %s' % (cronPath) + ProcessUtilities.executioner(command) + + command = 'chown %s:%s %s' % (website.externalApp, website.externalApp, cronPath) + ProcessUtilities.executioner(command) + + f = ProcessUtilities.outputExecutioner(execPath, website.externalApp) + + if f.find("0,CyberPanel,") > -1: + data_ret = {'getWebsiteCron': 0, "user": website.externalApp, "crons": {}} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + + counter = 0 + for line in f.split("\n"): + if line: + split = line.split(" ", 5) + if len(split) == 6: + counter += 1 + crons.append({"line": counter, + "minute": split[0], + "hour": split[1], + "monthday": split[2], + "month": split[3], + "weekday": split[4], + "command": split[5]}) + + data_ret = {'getWebsiteCron': 1, "user": website.externalApp, "crons": crons} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + except BaseException as msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg)) + dic = {'getWebsiteCron': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def getCronbyLine(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + line = data['line'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('getWebsiteCron', 0) + + if Websites.objects.filter(domain=self.domain).exists(): + pass + else: + dic = {'getWebsiteCron': 0, 'error_message': 'You do not own this domain'} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + line -= 1 + website = Websites.objects.get(domain=self.domain) + + try: + CronUtil.CronPrem(1) + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" + execPath = execPath + " getWebsiteCron --externalApp " + website.externalApp + + f = ProcessUtilities.outputExecutioner(execPath, website.externalApp) + CronUtil.CronPrem(0) + except subprocess.CalledProcessError as error: + dic = {'getWebsiteCron': 0, 'error_message': 'Unable to access Cron file'} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + f = f.split("\n") + cron = f[line] + + cron = cron.split(" ", 5) + if len(cron) != 6: + dic = {'getWebsiteCron': 0, 'error_message': 'Cron line incorrect'} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + data_ret = {"getWebsiteCron": 1, + "user": website.externalApp, + "cron": { + "minute": cron[0], + "hour": cron[1], + "monthday": cron[2], + "month": cron[3], + "weekday": cron[4], + "command": cron[5], + }, + "line": line} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + except BaseException as msg: + print(msg) + dic = {'getWebsiteCron': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def saveCronChanges(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + line = data['line'] + + minute = data['minute'] + hour = data['hour'] + monthday = data['monthday'] + month = data['month'] + weekday = data['weekday'] + command = data['cronCommand'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('getWebsiteCron', 0) + + website = Websites.objects.get(domain=self.domain) + + finalCron = "%s %s %s %s %s %s" % (minute, hour, monthday, month, weekday, command) + + CronUtil.CronPrem(1) + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" + execPath = execPath + " saveCronChanges --externalApp " + website.externalApp + " --line " + str( + line) + " --finalCron '" + finalCron + "'" + output = ProcessUtilities.outputExecutioner(execPath, website.externalApp) + CronUtil.CronPrem(0) + + if output.find("1,") > -1: + data_ret = {"getWebsiteCron": 1, + "user": website.externalApp, + "cron": finalCron, + "line": line} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + else: + dic = {'getWebsiteCron': 0, 'error_message': output} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + except BaseException as msg: + dic = {'getWebsiteCron': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def remCronbyLine(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + line = data['line'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('addNewCron', 0) + + website = Websites.objects.get(domain=self.domain) + + CronUtil.CronPrem(1) + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" + execPath = execPath + " remCronbyLine --externalApp " + website.externalApp + " --line " + str( + line) + output = ProcessUtilities.outputExecutioner(execPath, website.externalApp) + + CronUtil.CronPrem(0) + + if output.find("1,") > -1: + data_ret = {"remCronbyLine": 1, + "user": website.externalApp, + "removeLine": output.split(',')[1], + "line": line} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + else: + dic = {'remCronbyLine': 0, 'error_message': output} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + except BaseException as msg: + dic = {'remCronbyLine': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def addNewCron(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + minute = data['minute'] + hour = data['hour'] + monthday = data['monthday'] + month = data['month'] + weekday = data['weekday'] + command = data['cronCommand'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('addNewCron', 0) + + website = Websites.objects.get(domain=self.domain) + + if ProcessUtilities.decideDistro() == ProcessUtilities.centos or ProcessUtilities.decideDistro() == ProcessUtilities.cent8: + cronPath = "/var/spool/cron/" + website.externalApp + else: + cronPath = "/var/spool/cron/crontabs/" + website.externalApp + + commandT = 'touch %s' % (cronPath) + ProcessUtilities.executioner(commandT, 'root') + commandT = 'chown %s:%s %s' % (website.externalApp, website.externalApp, cronPath) + ProcessUtilities.executioner(commandT, 'root') + + CronUtil.CronPrem(1) + + finalCron = "%s %s %s %s %s %s" % (minute, hour, monthday, month, weekday, command) + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" + execPath = execPath + " addNewCron --externalApp " + website.externalApp + " --finalCron '" + finalCron + "'" + output = ProcessUtilities.outputExecutioner(execPath, website.externalApp) + + if ProcessUtilities.decideDistro() == ProcessUtilities.ubuntu or ProcessUtilities.decideDistro() == ProcessUtilities.ubuntu20: + command = 'chmod 600 %s' % (cronPath) + ProcessUtilities.executioner(command) + + command = 'systemctl restart cron' + ProcessUtilities.executioner(command) + + CronUtil.CronPrem(0) + + if output.find("1,") > -1: + data_ret = {"addNewCron": 1, + "user": website.externalApp, + "cron": finalCron} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + else: + dic = {'addNewCron': 0, 'error_message': output} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + except BaseException as msg: + dic = {'addNewCron': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def submitAliasCreation(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['masterDomain'] + aliasDomain = data['aliasDomain'] + ssl = data['ssl'] + + if not validators.domain(aliasDomain): + data_ret = {'status': 0, 'createAliasStatus': 0, 'error_message': "Invalid domain."} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('createAliasStatus', 0) + + sslpath = "/home/" + self.domain + "/public_html" + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + + execPath = execPath + " createAlias --masterDomain " + self.domain + " --aliasDomain " + aliasDomain + " --ssl " + str( + ssl) + " --sslPath " + sslpath + " --administratorEmail " + admin.email + ' --websiteOwner ' + admin.userName + + output = ProcessUtilities.outputExecutioner(execPath) + + if output.find("1,None") > -1: + pass + else: + data_ret = {'createAliasStatus': 0, 'error_message': output, "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + data_ret = {'createAliasStatus': 1, 'error_message': "None", "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'createAliasStatus': 0, 'error_message': str(msg), "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def issueAliasSSL(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['masterDomain'] + aliasDomain = data['aliasDomain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('sslStatus', 0) + + if ACLManager.AliasDomainCheck(currentACL, aliasDomain, self.domain) == 1: + pass + else: + return ACLManager.loadErrorJson('sslStatus', 0) + + sslpath = "/home/" + self.domain + "/public_html" + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " issueAliasSSL --masterDomain " + self.domain + " --aliasDomain " + aliasDomain + " --sslPath " + sslpath + " --administratorEmail " + admin.email + + output = ProcessUtilities.outputExecutioner(execPath) + + if output.find("1,None") > -1: + data_ret = {'sslStatus': 1, 'error_message': "None", "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + data_ret = {'sslStatus': 0, 'error_message': output, "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'sslStatus': 0, 'error_message': str(msg), "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def delateAlias(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['masterDomain'] + aliasDomain = data['aliasDomain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('deleteAlias', 0) + + if ACLManager.AliasDomainCheck(currentACL, aliasDomain, self.domain) == 1: + pass + else: + return ACLManager.loadErrorJson('deleteAlias', 0) + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " deleteAlias --masterDomain " + self.domain + " --aliasDomain " + aliasDomain + output = ProcessUtilities.outputExecutioner(execPath) + + if output.find("1,None") > -1: + data_ret = {'deleteAlias': 1, 'error_message': "None", "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + data_ret = {'deleteAlias': 0, 'error_message': output, "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'deleteAlias': 0, 'error_message': str(msg), "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def changeOpenBasedir(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + + self.domain = data['domainName'] + openBasedirValue = data['openBasedirValue'] + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson('changeOpenBasedir', 0) + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " changeOpenBasedir --virtualHostName '" + self.domain + "' --openBasedirValue " + openBasedirValue + output = ProcessUtilities.popenExecutioner(execPath) + + data_ret = {'status': 1, 'changeOpenBasedir': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'changeOpenBasedir': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def wordpressInstall(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + proc = httpProc(request, 'websiteFunctions/installWordPress.html', {'domainName': self.domain}) + return proc.render() + + def installWordpress(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('installStatus', 0) + + mailUtilities.checkHome() + + extraArgs = {} + extraArgs['admin'] = admin + extraArgs['domainName'] = data['domain'] + extraArgs['home'] = data['home'] + extraArgs['blogTitle'] = data['blogTitle'] + extraArgs['adminUser'] = data['adminUser'] + extraArgs['adminPassword'] = data['passwordByPass'] + extraArgs['adminEmail'] = data['adminEmail'] + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + if data['home'] == '0': + extraArgs['path'] = data['path'] + + background = ApplicationInstaller('wordpress', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def installWordpressStatus(self, userID=None, data=None): + try: + statusFile = data['statusFile'] + + if ACLManager.CheckStatusFilleLoc(statusFile): + pass + else: + data_ret = {'abort': 1, 'installStatus': 0, 'installationProgress': "100", + 'currentStatus': 'Invalid status file.'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + statusData = ProcessUtilities.outputExecutioner("cat " + statusFile).splitlines() + + lastLine = statusData[-1] + + if lastLine.find('[200]') > -1: + command = 'rm -f ' + statusFile + subprocess.call(shlex.split(command)) + data_ret = {'abort': 1, 'installStatus': 1, 'installationProgress': "100", + 'currentStatus': 'Successfully Installed.'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + elif lastLine.find('[404]') > -1: + data_ret = {'abort': 1, 'installStatus': 0, 'installationProgress': "0", + 'error_message': ProcessUtilities.outputExecutioner("cat " + statusFile).splitlines()} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + progress = lastLine.split(',') + currentStatus = progress[0] + try: + installationProgress = progress[1] + except: + installationProgress = 0 + data_ret = {'abort': 0, 'installStatus': 0, 'installationProgress': installationProgress, + 'currentStatus': currentStatus} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'abort': 0, 'installStatus': 0, 'installationProgress': "0", 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def joomlaInstall(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + proc = httpProc(request, 'websiteFunctions/installJoomla.html', {'domainName': self.domain}) + return proc.render() + + def installJoomla(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('installStatus', 0) + + extraArgs = {} + + extraArgs['password'] = data['passwordByPass'] + extraArgs['prefix'] = data['prefix'] + extraArgs['domain'] = data['domain'] + extraArgs['home'] = data['home'] + extraArgs['siteName'] = data['siteName'] + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + mailUtilities.checkHome() + + if data['home'] == '0': + extraArgs['path'] = data['path'] + + background = ApplicationInstaller('joomla', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def setupGit(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + website = Websites.objects.get(domain=self.domain) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson() + + path = '/home/cyberpanel/' + self.domain + '.git' + + if os.path.exists(path): + ipFile = "/etc/cyberpanel/machineIP" + f = open(ipFile) + ipData = f.read() + ipAddress = ipData.split('\n', 1)[0] + + port = ProcessUtilities.fetchCurrentPort() + + webhookURL = 'https://' + ipAddress + ':%s/websites/' % (port) + self.domain + '/gitNotify' + + proc = httpProc(request, 'websiteFunctions/setupGit.html', + {'domainName': self.domain, 'installed': 1, 'webhookURL': webhookURL}) + return proc.render() + else: + command = "ssh-keygen -f /home/%s/.ssh/%s -t rsa -N ''" % (self.domain, website.externalApp) + ProcessUtilities.executioner(command, website.externalApp) + + configContent = """Host github.com +IdentityFile /home/%s/.ssh/%s +StrictHostKeyChecking no +""" % (self.domain, website.externalApp) + + path = "/home/cyberpanel/config" + writeToFile = open(path, 'w') + writeToFile.writelines(configContent) + writeToFile.close() + + command = 'mv %s /home/%s/.ssh/config' % (path, self.domain) + ProcessUtilities.executioner(command) + + command = 'chown %s:%s /home/%s/.ssh/config' % (website.externalApp, website.externalApp, self.domain) + ProcessUtilities.executioner(command) + + command = 'cat /home/%s/.ssh/%s.pub' % (self.domain, website.externalApp) + deploymentKey = ProcessUtilities.outputExecutioner(command, website.externalApp) + + proc = httpProc(request, 'websiteFunctions/setupGit.html', + {'domainName': self.domain, 'deploymentKey': deploymentKey, 'installed': 0}) + return proc.render() + + def setupGitRepo(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('installStatus', 0) + + mailUtilities.checkHome() + + extraArgs = {} + extraArgs['admin'] = admin + extraArgs['domainName'] = data['domain'] + extraArgs['username'] = data['username'] + extraArgs['reponame'] = data['reponame'] + extraArgs['branch'] = data['branch'] + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + extraArgs['defaultProvider'] = data['defaultProvider'] + + background = ApplicationInstaller('git', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def gitNotify(self, userID=None, data=None): + try: + + extraArgs = {} + extraArgs['domain'] = self.domain + + background = ApplicationInstaller('pull', extraArgs) + background.start() + + data_ret = {'pulled': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'pulled': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def detachRepo(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson() + + mailUtilities.checkHome() + + extraArgs = {} + extraArgs['domainName'] = data['domain'] + extraArgs['admin'] = admin + + background = ApplicationInstaller('detach', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def changeBranch(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson() + + mailUtilities.checkHome() + + extraArgs = {} + extraArgs['domainName'] = data['domain'] + extraArgs['githubBranch'] = data['githubBranch'] + extraArgs['admin'] = admin + + background = ApplicationInstaller('changeBranch', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def installPrestaShop(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + proc = httpProc(request, 'websiteFunctions/installPrestaShop.html', {'domainName': self.domain}) + return proc.render() + + def installMagento(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + proc = httpProc(request, 'websiteFunctions/installMagento.html', {'domainName': self.domain}) + return proc.render() + + def magentoInstall(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('installStatus', 0) + + mailUtilities.checkHome() + + extraArgs = {} + extraArgs['admin'] = admin + extraArgs['domainName'] = data['domain'] + extraArgs['home'] = data['home'] + extraArgs['firstName'] = data['firstName'] + extraArgs['lastName'] = data['lastName'] + extraArgs['username'] = data['username'] + extraArgs['email'] = data['email'] + extraArgs['password'] = data['passwordByPass'] + extraArgs['sampleData'] = data['sampleData'] + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + if data['home'] == '0': + extraArgs['path'] = data['path'] + + background = ApplicationInstaller('magento', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + ## Installation ends + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def installMautic(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + proc = httpProc(request, 'websiteFunctions/installMautic.html', {'domainName': self.domain}) + return proc.render() + + def mauticInstall(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('installStatus', 0) + + #### Before installing mautic change php to 8.1 + + completePathToConfigFile = f'/usr/local/lsws/conf/vhosts/{self.domain}/vhost.conf' + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " changePHP --phpVersion 'PHP 8.1' --path " + completePathToConfigFile + ProcessUtilities.executioner(execPath) + + mailUtilities.checkHome() + + extraArgs = {} + extraArgs['admin'] = admin + extraArgs['domainName'] = data['domain'] + extraArgs['home'] = data['home'] + extraArgs['username'] = data['username'] + extraArgs['email'] = data['email'] + extraArgs['password'] = data['passwordByPass'] + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + if data['home'] == '0': + extraArgs['path'] = data['path'] + + background = ApplicationInstaller('mautic', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + ## Installation ends + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def prestaShopInstall(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('installStatus', 0) + + mailUtilities.checkHome() + + extraArgs = {} + extraArgs['admin'] = admin + extraArgs['domainName'] = data['domain'] + extraArgs['home'] = data['home'] + extraArgs['shopName'] = data['shopName'] + extraArgs['firstName'] = data['firstName'] + extraArgs['lastName'] = data['lastName'] + extraArgs['databasePrefix'] = data['databasePrefix'] + extraArgs['email'] = data['email'] + extraArgs['password'] = data['passwordByPass'] + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + if data['home'] == '0': + extraArgs['path'] = data['path'] + + #### Before installing Prestashop change php to 8.3 + + completePathToConfigFile = f'/usr/local/lsws/conf/vhosts/{self.domain}/vhost.conf' + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " changePHP --phpVersion 'PHP 8.3' --path " + completePathToConfigFile + ProcessUtilities.executioner(execPath) + + background = ApplicationInstaller('prestashop', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + ## Installation ends + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def createWebsiteAPI(self, data=None): + try: + + adminUser = data['adminUser'] + adminPass = data['adminPass'] + adminEmail = data['ownerEmail'] + websiteOwner = data['websiteOwner'] + ownerPassword = data['ownerPassword'] + data['ssl'] = 1 + data['dkimCheck'] = 1 + data['openBasedir'] = 1 + data['adminEmail'] = data['ownerEmail'] + + try: + data['phpSelection'] = data['phpSelection'] + except: + data['phpSelection'] = "PHP 7.4" + + data['package'] = data['packageName'] + try: + websitesLimit = data['websitesLimit'] + except: + websitesLimit = 1 + + try: + apiACL = data['acl'] + except: + apiACL = 'user' + + admin = Administrator.objects.get(userName=adminUser) + + if hashPassword.check_password(admin.password, adminPass): + + if adminEmail is None: + data['adminEmail'] = "example@example.org" + + try: + acl = ACL.objects.get(name=apiACL) + websiteOwn = Administrator(userName=websiteOwner, + password=hashPassword.hash_password(ownerPassword), + email=adminEmail, type=3, owner=admin.pk, + initWebsitesLimit=websitesLimit, acl=acl, api=1) + websiteOwn.save() + except BaseException: + pass + + else: + data_ret = {"existsStatus": 0, 'createWebSiteStatus': 0, + 'error_message': "Could not authorize access to API"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + return self.submitWebsiteCreation(admin.pk, data) + + except BaseException as msg: + data_ret = {'createWebSiteStatus': 0, 'error_message': str(msg), "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def searchWebsitesJson(self, currentlACL, userID, searchTerm): + + websites = ACLManager.searchWebsiteObjects(currentlACL, userID, searchTerm) + + json_data = "[" + checker = 0 + + try: + ipFile = "/etc/cyberpanel/machineIP" + f = open(ipFile) + ipData = f.read() + ipAddress = ipData.split('\n', 1)[0] + except BaseException as msg: + logging.CyberCPLogFileWriter.writeToFile("Failed to read machine IP, error:" + str(msg)) + ipAddress = "192.168.100.1" + + for items in websites: + if items.state == 0: + state = "Suspended" + else: + state = "Active" + + DiskUsage, DiskUsagePercentage, bwInMB, bwUsage = virtualHostUtilities.FindStats(items) + + vhFile = f'/usr/local/lsws/conf/vhosts/{items.domain}/vhost.conf' + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(vhFile) + + try: + from plogical.phpUtilities import phpUtilities + PHPVersionActual = phpUtilities.WrapGetPHPVersionFromFileToGetVersionWithPHP(vhFile) + except: + PHPVersionActual = 'PHP 8.1' + + diskUsed = "%sMB" % str(DiskUsage) + dic = {'domain': items.domain, 'adminEmail': items.adminEmail, 'ipAddress': ipAddress, + 'admin': items.admin.userName, 'package': items.package.packageName, 'state': state, + 'diskUsed': diskUsed, 'phpVersion': PHPVersionActual} + + if checker == 0: + json_data = json_data + json.dumps(dic) + checker = 1 + else: + json_data = json_data + ',' + json.dumps(dic) + + json_data = json_data + ']' + + return json_data + + def findWebsitesJson(self, currentACL, userID, pageNumber): + finalPageNumber = ((pageNumber * 10)) - 10 + endPageNumber = finalPageNumber + 10 + websites = ACLManager.findWebsiteObjects(currentACL, userID)[finalPageNumber:endPageNumber] + + json_data = "[" + checker = 0 + + try: + ipFile = "/etc/cyberpanel/machineIP" + f = open(ipFile) + ipData = f.read() + ipAddress = ipData.split('\n', 1)[0] + except BaseException as msg: + logging.CyberCPLogFileWriter.writeToFile("Failed to read machine IP, error:" + str(msg)) + ipAddress = "192.168.100.1" + + for items in websites: + if items.state == 0: + state = "Suspended" + else: + state = "Active" + + DiskUsage, DiskUsagePercentage, bwInMB, bwUsage = virtualHostUtilities.FindStats(items) + + diskUsed = "%sMB" % str(DiskUsage) + + dic = {'domain': items.domain, 'adminEmail': items.adminEmail, 'ipAddress': ipAddress, + 'admin': items.admin.userName, 'package': items.package.packageName, 'state': state, + 'diskUsed': diskUsed} + + if checker == 0: + json_data = json_data + json.dumps(dic) + checker = 1 + else: + json_data = json_data + ',' + json.dumps(dic) + + json_data = json_data + ']' + + return json_data + + def websitePagination(self, currentACL, userID): + websites = ACLManager.findAllSites(currentACL, userID) + + pages = float(len(websites)) / float(10) + pagination = [] + + if pages <= 1.0: + pages = 1 + pagination.append('
  • ') + else: + pages = ceil(pages) + finalPages = int(pages) + 1 + + for i in range(1, finalPages): + pagination.append('
  • ' + str(i) + '
  • ') + + return pagination + + def DockersitePagination(self, currentACL, userID): + websites = DockerSites.objects.all() + + pages = float(len(websites)) / float(10) + pagination = [] + + if pages <= 1.0: + pages = 1 + pagination.append('
  • ') + else: + pages = ceil(pages) + finalPages = int(pages) + 1 + + for i in range(1, finalPages): + pagination.append('
  • ' + str(i) + '
  • ') + + return pagination + + def getSwitchStatus(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + try: + globalData = data['global'] + + data = {} + data['status'] = 1 + + if os.path.exists('/etc/httpd'): + data['server'] = 1 + else: + data['server'] = 0 + + json_data = json.dumps(data) + return HttpResponse(json_data) + except: + pass + + self.domain = data['domainName'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + if ProcessUtilities.decideServer() == ProcessUtilities.OLS: + finalConfPath = ApacheVhost.configBasePath + self.domain + '.conf' + + if os.path.exists(finalConfPath): + + phpPath = ApacheVhost.whichPHPExists(self.domain) + command = 'sudo cat ' + phpPath + phpConf = ProcessUtilities.outputExecutioner(command).splitlines() + pmMaxChildren = phpConf[8].split(' ')[2] + pmStartServers = phpConf[9].split(' ')[2] + pmMinSpareServers = phpConf[10].split(' ')[2] + pmMaxSpareServers = phpConf[11].split(' ')[2] + + data = {} + data['status'] = 1 + + data['server'] = WebsiteManager.apache + data['pmMaxChildren'] = pmMaxChildren + data['pmStartServers'] = pmStartServers + data['pmMinSpareServers'] = pmMinSpareServers + data['pmMaxSpareServers'] = pmMaxSpareServers + data['phpPath'] = phpPath + data['configData'] = ProcessUtilities.outputExecutioner(f'cat {finalConfPath}') + else: + data = {} + data['status'] = 1 + data['server'] = WebsiteManager.ols + + else: + data = {} + data['status'] = 1 + data['server'] = WebsiteManager.lsws + + json_data = json.dumps(data) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'saveStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def switchServer(self, userID=None, data=None): + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + domainName = data['domainName'] + phpVersion = data['phpSelection'] + server = data['server'] + + if ACLManager.checkOwnership(domainName, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson() + + tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " switchServer --phpVersion '" + phpVersion + "' --server " + str( + server) + " --virtualHostName " + domainName + " --tempStatusPath " + tempStatusPath + ProcessUtilities.popenExecutioner(execPath) + + time.sleep(3) + + data_ret = {'status': 1, 'tempStatusPath': tempStatusPath} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def tuneSettings(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + domainName = data['domainName'] + pmMaxChildren = data['pmMaxChildren'] + pmStartServers = data['pmStartServers'] + pmMinSpareServers = data['pmMinSpareServers'] + pmMaxSpareServers = data['pmMaxSpareServers'] + phpPath = data['phpPath'] + + if ACLManager.checkOwnership(domainName, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson() + + if int(pmStartServers) < int(pmMinSpareServers) or int(pmStartServers) > int(pmMinSpareServers): + data_ret = {'status': 0, + 'error_message': 'pm.start_servers must not be less than pm.min_spare_servers and not greater than pm.max_spare_servers.'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + if int(pmMinSpareServers) > int(pmMaxSpareServers): + data_ret = {'status': 0, + 'error_message': 'pm.max_spare_servers must not be less than pm.min_spare_servers'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + try: + website = Websites.objects.get(domain=domainName) + externalApp = website.externalApp + except: + website = ChildDomains.objects.get(domain=domainName) + externalApp = website.master.externalApp + + tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + + if ProcessUtilities.decideDistro() == ProcessUtilities.centos or ProcessUtilities.decideDistro() == ProcessUtilities.cent8: + sockPath = '/var/run/php-fpm/' + group = 'nobody' + else: + sockPath = '/var/run/php/' + group = 'nogroup' + + phpFPMConf = vhostConfs.phpFpmPoolReplace + phpFPMConf = phpFPMConf.replace('{externalApp}', externalApp) + phpFPMConf = phpFPMConf.replace('{pmMaxChildren}', pmMaxChildren) + phpFPMConf = phpFPMConf.replace('{pmStartServers}', pmStartServers) + phpFPMConf = phpFPMConf.replace('{pmMinSpareServers}', pmMinSpareServers) + phpFPMConf = phpFPMConf.replace('{pmMaxSpareServers}', pmMaxSpareServers) + phpFPMConf = phpFPMConf.replace('{www}', "".join(re.findall("[a-zA-Z]+", domainName))[:7]) + phpFPMConf = phpFPMConf.replace('{Sock}', domainName) + phpFPMConf = phpFPMConf.replace('{sockPath}', sockPath) + phpFPMConf = phpFPMConf.replace('{group}', group) + + writeToFile = open(tempStatusPath, 'w') + writeToFile.writelines(phpFPMConf) + writeToFile.close() + + command = 'sudo mv %s %s' % (tempStatusPath, phpPath) + ProcessUtilities.executioner(command) + + phpPath = phpPath.split('/') + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(f'PHP path in tune settings {phpPath}') + + if ProcessUtilities.decideDistro() == ProcessUtilities.centos or ProcessUtilities.decideDistro() == ProcessUtilities.cent8: + if phpPath[1] == 'etc': + phpVersion = phpPath[4][3] + phpPath[4][4] + phpVersion = f'PHP {phpPath[4][3]}.{phpPath[4][4]}' + else: + phpVersion = phpPath[3][3] + phpPath[3][4] + phpVersion = f'PHP {phpPath[3][3]}.{phpPath[3][4]}' + else: + phpVersion = f'PHP {phpPath[2]}' + + # php = PHPManager.getPHPString(phpVersion) + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(f'PHP Version in tune settings {phpVersion}') + + phpService = ApacheVhost.DecideFPMServiceName(phpVersion) + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(f'PHP service in tune settings {phpService}') + + command = f"systemctl stop {phpService}" + ProcessUtilities.normalExecutioner(command) + + command = f"systemctl restart {phpService}" + ProcessUtilities.normalExecutioner(command) + + data_ret = {'status': 1} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def sshAccess(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + website = Websites.objects.get(domain=self.domain) + externalApp = website.externalApp + + proc = httpProc(request, 'websiteFunctions/sshAccess.html', + {'domainName': self.domain, 'externalApp': externalApp}) + return proc.render() + + def saveSSHAccessChanges(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + website = Websites.objects.get(domain=self.domain) + + # if website.externalApp != data['externalApp']: + # data_ret = {'status': 0, 'error_message': 'External app mis-match.'} + # json_data = json.dumps(data_ret) + # return HttpResponse(json_data) + + uBuntuPath = '/etc/lsb-release' + + if os.path.exists(uBuntuPath): + command = "echo '%s:%s' | chpasswd" % (website.externalApp, data['password']) + else: + command = 'echo "%s" | passwd --stdin %s' % (data['password'], website.externalApp) + + ProcessUtilities.executioner(command) + + data_ret = {'status': 1, 'error_message': 'None', 'LinuxUser': website.externalApp} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def setupStaging(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + website = Websites.objects.get(domain=self.domain) + externalApp = website.externalApp + + proc = httpProc(request, 'websiteFunctions/setupStaging.html', + {'domainName': self.domain, 'externalApp': externalApp}) + return proc.render() + + def startCloning(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['masterDomain'] + + if not validators.domain(self.domain): + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Invalid domain."} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + if not validators.domain(data['domainName']): + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Invalid domain."} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + extraArgs = {} + extraArgs['domain'] = data['domainName'] + extraArgs['masterDomain'] = data['masterDomain'] + extraArgs['admin'] = admin + + tempStatusPath = "/tmp/" + str(randint(1000, 9999)) + writeToFile = open(tempStatusPath, 'a') + message = 'Cloning process has started..,5' + writeToFile.write(message) + writeToFile.close() + + extraArgs['tempStatusPath'] = tempStatusPath + + st = StagingSetup('startCloning', extraArgs) + st.start() + + data_ret = {'status': 1, 'error_message': 'None', 'tempStatusPath': tempStatusPath} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def syncToMaster(self, request=None, userID=None, data=None, childDomain=None): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + website = Websites.objects.get(domain=self.domain) + externalApp = website.externalApp + + proc = httpProc(request, 'websiteFunctions/syncMaster.html', + {'domainName': self.domain, 'externalApp': externalApp, 'childDomain': childDomain}) + return proc.render() + + def startSync(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if not validators.domain(data['childDomain']): + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Invalid domain."} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + self.domain = data['childDomain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + extraArgs = {} + extraArgs['childDomain'] = data['childDomain'] + try: + extraArgs['eraseCheck'] = data['eraseCheck'] + except: + extraArgs['eraseCheck'] = False + try: + extraArgs['dbCheck'] = data['dbCheck'] + except: + extraArgs['dbCheck'] = False + try: + extraArgs['copyChanged'] = data['copyChanged'] + except: + extraArgs['copyChanged'] = False + + extraArgs['admin'] = admin + + tempStatusPath = "/tmp/" + str(randint(1000, 9999)) + writeToFile = open(tempStatusPath, 'a') + message = 'Syncing process has started..,5' + writeToFile.write(message) + writeToFile.close() + + extraArgs['tempStatusPath'] = tempStatusPath + + st = StagingSetup('startSyncing', extraArgs) + st.start() + + data_ret = {'status': 1, 'error_message': 'None', 'tempStatusPath': tempStatusPath} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def convertDomainToSite(self, userID=None, request=None): + try: + + extraArgs = {} + extraArgs['request'] = request + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + background = ApplicationInstaller('convertDomainToSite', extraArgs) + background.start() + + data_ret = {'status': 1, 'createWebSiteStatus': 1, 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def manageGIT(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + try: + website = Websites.objects.get(domain=self.domain) + folders = ['/home/%s/public_html' % (self.domain)] + + databases = website.databases_set.all() + + # for database in databases: + # basePath = '/var/lib/mysql/' + # folders.append('%s%s' % (basePath, database.dbName)) + except: + + self.childWebsite = ChildDomains.objects.get(domain=self.domain) + + folders = [self.childWebsite.path] + + databases = self.childWebsite.master.databases_set.all() + + # for database in databases: + # basePath = '/var/lib/mysql/' + # folders.append('%s%s' % (basePath, database.dbName)) + + proc = httpProc(request, 'websiteFunctions/manageGIT.html', + {'domainName': self.domain, 'folders': folders}) + return proc.render() + + def folderCheck(self): + + try: + + domainPath = '/home/%s/public_html' % (self.domain) + vhRoot = '/home/%s' % (self.domain) + vmailPath = '/home/vmail/%s' % (self.domain) + + ## + + try: + + website = Websites.objects.get(domain=self.domain) + + self.masterWebsite = website + self.masterDomain = website.domain + externalApp = website.externalApp + self.externalAppLocal = website.externalApp + self.adminEmail = website.adminEmail + self.firstName = website.admin.firstName + self.lastName = website.admin.lastName + + self.home = 0 + if self.folder == '/home/%s/public_html' % (self.domain): + self.home = 1 + + except: + + website = ChildDomains.objects.get(domain=self.domain) + self.masterWebsite = website.master + self.masterDomain = website.master.domain + externalApp = website.master.externalApp + self.externalAppLocal = website.master.externalApp + self.adminEmail = website.master.adminEmail + self.firstName = website.master.admin.firstName + self.lastName = website.master.admin.lastName + + self.home = 0 + if self.folder == website.path: + self.home = 1 + + ### Fetch git configurations + + self.confCheck = 1 + + gitConfFolder = '/home/cyberpanel/git' + gitConFile = '%s/%s' % (gitConfFolder, self.masterDomain) + + if not os.path.exists(gitConfFolder): + os.mkdir(gitConfFolder) + + if not os.path.exists(gitConFile): + os.mkdir(gitConFile) + + if os.path.exists(gitConFile): + files = os.listdir(gitConFile) + + if len(files) >= 1: + for file in files: + self.finalFile = '%s/%s' % (gitConFile, file) + + gitConf = json.loads(open(self.finalFile, 'r').read()) + + if gitConf['folder'] == self.folder: + + self.autoCommitCurrent = gitConf['autoCommit'] + self.autoPushCurrent = gitConf['autoPush'] + self.emailLogsCurrent = gitConf['emailLogs'] + try: + self.commands = gitConf['commands'] + except: + self.commands = "Add Commands to run after every commit, separate commands using comma." + + try: + self.webhookCommandCurrent = gitConf['webhookCommand'] + except: + self.webhookCommandCurrent = "False" + + self.confCheck = 0 + break + + if self.confCheck: + self.autoCommitCurrent = 'Never' + self.autoPushCurrent = 'Never' + self.emailLogsCurrent = 'False' + self.webhookCommandCurrent = 'False' + self.commands = "Add Commands to run after every commit, separate commands using comma." + + ## + + if self.folder == domainPath: + self.externalApp = externalApp + return 1 + + ## + + if self.folder == vhRoot: + self.externalApp = externalApp + return 1 + + ## + + try: + childDomain = ChildDomains.objects.get(domain=self.domain) + + if self.folder == childDomain.path: + self.externalApp = externalApp + return 1 + + except: + pass + + ## + + if self.folder == vmailPath: + self.externalApp = 'vmail' + return 1 + + try: + + for database in website.databases_set.all(): + self.externalApp = 'mysql' + basePath = '/var/lib/mysql/' + dbPath = '%s%s' % (basePath, database.dbName) + + if self.folder == dbPath: + return 1 + except: + for database in website.master.databases_set.all(): + self.externalApp = 'mysql' + basePath = '/var/lib/mysql/' + dbPath = '%s%s' % (basePath, database.dbName) + + if self.folder == dbPath: + return 1 + + return 0 + + + except BaseException as msg: + logging.CyberCPLogFileWriter.writeToFile('%s. [folderCheck:3002]' % (str(msg))) + + return 0 + + def fetchFolderDetails(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + self.folder = data['folder'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + if self.folderCheck(): + pass + else: + return ACLManager.loadErrorJson() + + gitPath = '%s/.git' % (self.folder) + command = 'ls -la %s' % (gitPath) + + if ProcessUtilities.outputExecutioner(command, self.externalAppLocal).find( + 'No such file or directory') > -1: + + command = 'cat /home/%s/.ssh/%s.pub' % (self.masterDomain, self.externalAppLocal) + deploymentKey = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) + + if deploymentKey.find('No such file or directory') > -1: + command = "ssh-keygen -f /home/%s/.ssh/%s -t rsa -N ''" % (self.masterDomain, self.externalAppLocal) + ProcessUtilities.executioner(command, self.externalAppLocal) + + command = 'cat /home/%s/.ssh/%s.pub' % (self.masterDomain, self.externalAppLocal) + deploymentKey = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) + + data_ret = {'status': 1, 'repo': 0, 'deploymentKey': deploymentKey, 'home': self.home} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + + ## Find git branches + + command = 'git -C %s branch' % (self.folder) + branches = ProcessUtilities.outputExecutioner(command, self.externalAppLocal).split('\n')[:-1] + + ## Fetch key + + command = 'cat /home/%s/.ssh/%s.pub' % (self.domain, self.externalAppLocal) + deploymentKey = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) + + if deploymentKey.find('No such file or directory') > -1: + command = "ssh-keygen -f /home/%s/.ssh/%s -t rsa -N ''" % (self.masterDomain, self.externalAppLocal) + ProcessUtilities.executioner(command, self.externalAppLocal) + + command = 'cat /home/%s/.ssh/%s.pub' % (self.masterDomain, self.externalAppLocal) + deploymentKey = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) + + ## Find Remote if any + + command = 'git -C %s remote -v' % (self.folder) + remoteResult = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) + + remote = 1 + if remoteResult.find('origin') == -1: + remote = 0 + remoteResult = 'Remote currently not set.' + + ## Find Total commits on current branch + + command = 'git -C %s rev-list --count HEAD' % (self.folder) + totalCommits = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) + + if totalCommits.find('fatal') > -1: + totalCommits = '0' + + ## + + port = ProcessUtilities.fetchCurrentPort() + + webHookURL = 'https://%s:%s/websites/%s/webhook' % (ACLManager.fetchIP(), port, self.domain) + + data_ret = {'status': 1, 'repo': 1, 'finalBranches': branches, 'deploymentKey': deploymentKey, + 'remote': remote, 'remoteResult': remoteResult, 'totalCommits': totalCommits, + 'home': self.home, + 'webHookURL': webHookURL, 'autoCommitCurrent': self.autoCommitCurrent, + 'autoPushCurrent': self.autoPushCurrent, 'emailLogsCurrent': self.emailLogsCurrent, + 'commands': self.commands, "webhookCommandCurrent": self.webhookCommandCurrent} + + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def initRepo(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + self.folder = data['folder'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + if self.folderCheck(): + pass + else: + return ACLManager.loadErrorJson() + + website = Websites.objects.get(domain=self.masterDomain) + + command = 'git -C %s init' % (self.folder) + result = ProcessUtilities.outputExecutioner(command, website.externalApp) + + if result.find('Initialized empty Git repository in') > -1: + + command = 'git -C %s config --local user.email %s' % (self.folder, self.adminEmail) + ProcessUtilities.executioner(command, website.externalApp) + + command = 'git -C %s config --local user.name "%s %s"' % ( + self.folder, self.firstName, self.lastName) + ProcessUtilities.executioner(command, website.externalApp) + + ## Fix permissions + + # from filemanager.filemanager import FileManager + # + # fm = FileManager(None, None) + # fm.fixPermissions(self.masterDomain) + + data_ret = {'status': 1} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + data_ret = {'status': 0, 'error_message': result} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def setupRemote(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + self.folder = data['folder'] + self.gitHost = data['gitHost'] + self.gitUsername = data['gitUsername'] + self.gitReponame = data['gitReponame'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + ## Security checks + + if self.folderCheck(): + pass + else: + return ACLManager.loadErrorJson() + + if self.gitHost.find(':') > -1: + gitHostDomain = self.gitHost.split(':')[0] + gitHostPort = self.gitHost.split(':')[1] + + if not validators.domain(gitHostDomain): + return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') + + try: + gitHostPort = int(gitHostPort) + except: + return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') + + else: + if not validators.domain(self.gitHost): + return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') + + if ACLManager.validateInput(self.gitUsername) and ACLManager.validateInput(self.gitReponame): + pass + else: + return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') + + ### set default ssh key + + command = 'git -C %s config --local core.sshCommand "ssh -i /home/%s/.ssh/%s -o "StrictHostKeyChecking=no""' % ( + self.folder, self.masterDomain, self.externalAppLocal) + ProcessUtilities.executioner(command, self.externalAppLocal) + + ## Check if remote exists + + command = 'git -C %s remote -v' % (self.folder) + remoteResult = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) + + ## Set new remote + + if remoteResult.find('origin') == -1: + command = 'git -C %s remote add origin git@%s:%s/%s.git' % ( + self.folder, self.gitHost, self.gitUsername, self.gitReponame) + else: + command = 'git -C %s remote set-url origin git@%s:%s/%s.git' % ( + self.folder, self.gitHost, self.gitUsername, self.gitReponame) + + possibleError = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) + + ## Check if set correctly. + + command = 'git -C %s remote -v' % (self.folder) + remoteResult = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) + + if remoteResult.find(self.gitUsername) > -1: + + # ## Fix permissions + # + # from filemanager.filemanager import FileManager + # + # fm = FileManager(None, None) + # fm.fixPermissions(self.masterDomain) + + data_ret = {'status': 1} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + data_ret = {'status': 0, 'error_message': possibleError} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def changeGitBranch(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + self.folder = data['folder'] + self.branchName = data['branchName'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + if self.folderCheck(): + pass + else: + return ACLManager.loadErrorJson() + + ## Security check + + if ACLManager.validateInput(self.branchName): + pass + else: + return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') + + if self.branchName.find('*') > -1: + data_ret = {'status': 0, 'commandStatus': 'Already on this branch.', + 'error_message': 'Already on this branch.'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + self.externalApp = ACLManager.FetchExternalApp(self.domain) + + command = 'git -C %s checkout %s' % (self.folder, self.branchName.strip(' ')) + commandStatus = ProcessUtilities.outputExecutioner(command, self.externalApp) + + if commandStatus.find('Switched to branch') > -1: + + # ## Fix permissions + # + # from filemanager.filemanager import FileManager + # + # fm = FileManager(None, None) + # fm.fixPermissions(self.masterDomain) + + data_ret = {'status': 1, 'commandStatus': commandStatus + 'Refreshing page in 3 seconds..'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + data_ret = {'status': 0, 'error_message': 'Failed to change branch', 'commandStatus': commandStatus} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def createNewBranch(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + self.folder = data['folder'] + self.newBranchName = data['newBranchName'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + if self.folderCheck(): + pass + else: + return ACLManager.loadErrorJson() + + ## Security check + + if ACLManager.validateInput(self.newBranchName): + pass + else: + return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') + + ## + + self.externalApp = ACLManager.FetchExternalApp(self.domain) + + command = 'git -C %s checkout -b "%s"' % (self.folder, self.newBranchName) + commandStatus = ProcessUtilities.outputExecutioner(command, self.externalApp) + + if commandStatus.find(self.newBranchName) > -1: + + # ## Fix permissions + # + # from filemanager.filemanager import FileManager + # + # fm = FileManager(None, None) + # fm.fixPermissions(self.masterDomain) + + data_ret = {'status': 1, 'commandStatus': commandStatus} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + data_ret = {'status': 0, 'error_message': 'Failed to create branch', 'commandStatus': commandStatus} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def commitChanges(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + self.folder = data['folder'] + self.commitMessage = data['commitMessage'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + if self.folderCheck(): + pass + else: + return ACLManager.loadErrorJson('status', 0) + + # security check + + if ACLManager.validateInput(self.commitMessage): + pass + else: + return ACLManager.loadErrorJson() + + self.externalApp = ACLManager.FetchExternalApp(self.domain) + + ## Check if remote exists + + command = 'git -C %s add -A' % (self.folder) + ProcessUtilities.outputExecutioner(command, self.externalApp) + + command = 'git -C %s commit -m "%s"' % (self.folder, self.commitMessage.replace('"', '')) + commandStatus = ProcessUtilities.outputExecutioner(command, self.externalApp) + + if commandStatus.find('nothing to commit') == -1: + + try: + if self.commands != 'NONE': + + GitLogs(owner=self.masterWebsite, type='INFO', + message='Running commands after successful git commit..').save() + + if self.commands.find('\n') > -1: + commands = self.commands.split('\n') + + for command in commands: + GitLogs(owner=self.masterWebsite, type='INFO', + message='Running: %s' % (command)).save() + + result = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) + GitLogs(owner=self.masterWebsite, type='INFO', + message='Result: %s' % (result)).save() + else: + GitLogs(owner=self.masterWebsite, type='INFO', + message='Running: %s' % (self.commands)).save() + + result = ProcessUtilities.outputExecutioner(self.commands, self.externalAppLocal) + GitLogs(owner=self.masterWebsite, type='INFO', + message='Result: %s' % (result)).save() + + GitLogs(owner=self.masterWebsite, type='INFO', + message='Finished running commands.').save() + except: + pass + + ## Fix permissions + + # from filemanager.filemanager import FileManager + # + # fm = FileManager(None, None) + # fm.fixPermissions(self.masterDomain) + + data_ret = {'status': 1, 'commandStatus': commandStatus} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + data_ret = {'status': 0, 'error_message': 'Nothing to commit.', 'commandStatus': commandStatus} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg), 'commandStatus': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def gitPull(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + self.folder = data['folder'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + if self.folderCheck(): + pass + else: + return ACLManager.loadErrorJson() + + self.externalApp = ACLManager.FetchExternalApp(self.domain) + + ### set default ssh key + + command = 'git -C %s config --local core.sshCommand "ssh -i /home/%s/.ssh/%s -o "StrictHostKeyChecking=no""' % ( + self.folder, self.masterDomain, self.externalAppLocal) + ProcessUtilities.executioner(command, self.externalApp) + + ## Check if remote exists + + command = 'git -C %s pull' % (self.folder) + commandStatus = ProcessUtilities.outputExecutioner(command, self.externalApp) + + if commandStatus.find('Already up to date') == -1: + + ## Fix permissions + + # from filemanager.filemanager import FileManager + # + # fm = FileManager(None, None) + # fm.fixPermissions(self.masterDomain) + + data_ret = {'status': 1, 'commandStatus': commandStatus} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + data_ret = {'status': 0, 'error_message': 'Pull not required.', 'commandStatus': commandStatus} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def gitPush(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + self.folder = data['folder'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + if self.folderCheck(): + pass + else: + return ACLManager.loadErrorJson() + + self.externalApp = ACLManager.FetchExternalApp(self.domain) + + ### set default ssh key + + command = 'git -C %s config --local core.sshCommand "ssh -i /home/%s/.ssh/%s -o "StrictHostKeyChecking=no""' % ( + self.folder, self.masterDomain, self.externalAppLocal) + ProcessUtilities.executioner(command, self.externalApp) + + ## + + command = 'git -C %s push' % (self.folder) + commandStatus = ProcessUtilities.outputExecutioner(command, self.externalApp, False) + + if commandStatus.find('has no upstream branch') > -1: + command = 'git -C %s rev-parse --abbrev-ref HEAD' % (self.folder) + currentBranch = ProcessUtilities.outputExecutioner(command, self.externalApp, False).rstrip('\n') + + if currentBranch.find('fatal: ambiguous argument') > -1: + data_ret = {'status': 0, 'error_message': 'You need to commit first.', + 'commandStatus': 'You need to commit first.'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + command = 'git -C %s push --set-upstream origin %s' % (self.folder, currentBranch) + commandStatus = ProcessUtilities.outputExecutioner(command, self.externalApp, False) + + if commandStatus.find('Everything up-to-date') == -1 and commandStatus.find( + 'rejected') == -1 and commandStatus.find('Permission denied') == -1: + data_ret = {'status': 1, 'commandStatus': commandStatus} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + data_ret = {'status': 0, 'error_message': 'Push failed.', 'commandStatus': commandStatus} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg), 'commandStatus': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def attachRepoGIT(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + self.folder = data['folder'] + self.gitHost = data['gitHost'] + self.gitUsername = data['gitUsername'] + self.gitReponame = data['gitReponame'] + + try: + self.overrideData = data['overrideData'] + except: + self.overrideData = False + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + if self.folderCheck(): + pass + else: + return ACLManager.loadErrorJson() + + if self.gitHost.find(':') > -1: + gitHostDomain = self.gitHost.split(':')[0] + gitHostPort = self.gitHost.split(':')[1] + + if not validators.domain(gitHostDomain): + return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') + + try: + gitHostPort = int(gitHostPort) + except: + return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') + else: + if not validators.domain(self.gitHost): + return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') + + ## Security check + + if ACLManager.validateInput(self.gitUsername) and ACLManager.validateInput(self.gitReponame): + pass + else: + return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') + + ## + + self.externalApp = ACLManager.FetchExternalApp(self.domain) + + if self.overrideData: + command = 'rm -rf %s' % (self.folder) + ProcessUtilities.executioner(command, self.externalApp) + + ## Set defauly key + + command = 'git config --global core.sshCommand "ssh -i /home/%s/.ssh/%s -o "StrictHostKeyChecking=no""' % ( + self.masterDomain, self.externalAppLocal) + ProcessUtilities.executioner(command, self.externalApp) + + ## + + command = 'git clone git@%s:%s/%s.git %s' % (self.gitHost, self.gitUsername, self.gitReponame, self.folder) + commandStatus = ProcessUtilities.outputExecutioner(command, self.externalApp) + + if commandStatus.find('already exists') == -1 and commandStatus.find('Permission denied') == -1: + + # from filemanager.filemanager import FileManager + # + # fm = FileManager(None, None) + # fm.fixPermissions(self.masterDomain) + + command = 'git -C %s config --local user.email %s' % (self.folder, self.adminEmail) + ProcessUtilities.executioner(command, self.externalApp) + + command = 'git -C %s config --local user.name "%s %s"' % (self.folder, self.firstName, self.lastName) + ProcessUtilities.executioner(command, self.externalApp) + + data_ret = {'status': 1, 'commandStatus': commandStatus} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + else: + + # from filemanager.filemanager import FileManager + # + # fm = FileManager(None, None) + # fm.fixPermissions(self.masterDomain) + + data_ret = {'status': 0, 'error_message': 'Failed to clone.', 'commandStatus': commandStatus} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def removeTracking(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + self.folder = data['folder'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + if self.folderCheck(): + pass + else: + return ACLManager.loadErrorJson() + + self.externalApp = ACLManager.FetchExternalApp(self.domain) + + command = 'rm -rf %s/.git' % (self.folder) + ProcessUtilities.executioner(command, self.externalApp) + + gitConfFolder = '/home/cyberpanel/git' + gitConFile = '%s/%s' % (gitConfFolder, self.masterDomain) + finalFile = '%s/%s' % (gitConFile, self.folder.split('/')[-1]) + + command = 'rm -rf %s' % (finalFile) + ProcessUtilities.outputExecutioner(command, self.externalApp) + + ## Fix permissions + + # from filemanager.filemanager import FileManager + # + # fm = FileManager(None, None) + # fm.fixPermissions(self.masterDomain) + + data_ret = {'status': 1} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def fetchGitignore(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + self.folder = data['folder'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + if self.folderCheck(): + pass + else: + return ACLManager.loadErrorJson() + + command = 'cat %s/.gitignore' % (self.folder) + gitIgnoreContent = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) + + if gitIgnoreContent.find('No such file or directory') > -1: + gitIgnoreContent = 'File is currently empty.' + + data_ret = {'status': 1, 'gitIgnoreContent': gitIgnoreContent} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def saveGitIgnore(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + self.folder = data['folder'] + self.gitIgnoreContent = data['gitIgnoreContent'] + + tempPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + if self.folderCheck(): + pass + else: + return ACLManager.loadErrorJson() + + ## Write to temp file + + writeToFile = open(tempPath, 'w') + writeToFile.write(self.gitIgnoreContent) + writeToFile.close() + + ## Move to original file + + self.externalApp = ACLManager.FetchExternalApp(self.domain) + + command = 'mv %s %s/.gitignore' % (tempPath, self.folder) + ProcessUtilities.executioner(command, self.externalApp) + + ## Fix permissions + + # from filemanager.filemanager import FileManager + # + # fm = FileManager(None, None) + # fm.fixPermissions(self.masterDomain) + + data_ret = {'status': 1} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def fetchCommits(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + self.folder = data['folder'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + if self.folderCheck(): + pass + else: + return ACLManager.loadErrorJson() + + initCommand = """log --pretty=format:"%h|%s|%cn|%cd" -50""" + + self.externalApp = ACLManager.FetchExternalApp(self.domain) + + command = 'git -C %s %s' % (self.folder, initCommand) + commits = ProcessUtilities.outputExecutioner(command, self.externalApp).split('\n') + + json_data = "[" + checker = 0 + id = 1 + + for commit in commits: + cm = commit.split('|') + + dic = {'id': str(id), 'commit': cm[0], 'message': cm[1].replace('"', "'"), 'name': cm[2], 'date': cm[3]} + id = id + 1 + + if checker == 0: + json_data = json_data + json.dumps(dic) + checker = 1 + else: + json_data = json_data + ',' + json.dumps(dic) + + commits = json_data + ']' + + data_ret = {'status': 1, 'commits': commits} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except IndexError: + data_ret = {'status': 0, 'error_message': 'No commits found.'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def fetchFiles(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + self.folder = data['folder'] + self.commit = data['commit'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + if self.folderCheck(): + pass + else: + return ACLManager.loadErrorJson() + + ## Security check + + if ACLManager.validateInput(self.commit): + pass + else: + return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') + + ## + + self.externalApp = ACLManager.FetchExternalApp(self.domain) + + command = 'git -C %s diff-tree --no-commit-id --name-only -r %s' % (self.folder, self.commit) + files = ProcessUtilities.outputExecutioner(command, self.externalApp).split('\n') + + FinalFiles = [] + + for items in files: + if items != '': + FinalFiles.append(items.rstrip('\n').lstrip('\n')) + + data_ret = {'status': 1, 'files': FinalFiles} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def fetchChangesInFile(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + self.folder = data['folder'] + self.file = data['file'] + self.commit = data['commit'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + if self.folderCheck(): + pass + else: + return ACLManager.loadErrorJson() + + ## security check + + if ACLManager.validateInput(self.commit) and self.file.find('..') == -1: + pass + else: + return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') + + self.externalApp = ACLManager.FetchExternalApp(self.domain) + + command = 'git -C %s show %s -- %s/%s' % ( + self.folder, self.commit, self.folder, self.file.strip('\n').strip(' ')) + fileChangedContent = ProcessUtilities.outputExecutioner(command, self.externalApp).split('\n') + + initialNumber = 0 + ## Find initial line numbers + for items in fileChangedContent: + if len(items) == 0: + initialNumber = initialNumber + 1 + elif items[0] == '@': + break + else: + initialNumber = initialNumber + 1 + + try: + lineNumber = int(fileChangedContent[initialNumber].split('+')[1].split(',')[0]) + except: + lineNumber = int(fileChangedContent[initialNumber].split('+')[1].split(' ')[0]) + + fileLen = len(fileChangedContent) + finalConent = '%s

    %s

    ' % ( + '#', fileChangedContent[initialNumber]) + + for i in range(initialNumber + 1, fileLen - 1): + if fileChangedContent[i][0] == '@': + lineNumber = int(fileChangedContent[i].split('+')[1].split(',')[0]) + finalConent = finalConent + '%s

    %s

    ' % ( + '#', fileChangedContent[i]) + continue + + else: + if fileChangedContent[i][0] == '+': + content = '

    %s

    ' % ( + fileChangedContent[i].replace('<', "<").replace('>', ">")) + finalConent = finalConent + '%s%s' % ( + str(lineNumber), content) + lineNumber = lineNumber + 1 + elif fileChangedContent[i][0] == '-': + content = '

    %s

    ' % ( + fileChangedContent[i].replace('<', "<").replace('>', ">")) + finalConent = finalConent + '%s%s' % ( + str(lineNumber), content) + lineNumber = lineNumber + 1 + else: + content = '

    %s

    ' % (fileChangedContent[i].replace('<', "<").replace('>', ">")) + finalConent = finalConent + '%s%s' % ( + str(lineNumber), content) + lineNumber = lineNumber + 1 + + data_ret = {'status': 1, 'fileChangedContent': finalConent} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + except IndexError: + data_ret = {'status': 0, 'error_message': 'Not a text file.'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def saveGitConfigurations(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + self.folder = data['folder'] + + dic = {} + + dic['domain'] = self.domain + + dic['autoCommit'] = data['autoCommit'] + + try: + dic['autoPush'] = data['autoPush'] + except: + dic['autoPush'] = 'Never' + + try: + dic['emailLogs'] = data['emailLogs'] + except: + dic['emailLogs'] = False + + try: + dic['commands'] = data['commands'] + except: + dic['commands'] = 'NONE' + + try: + dic['webhookCommand'] = data['webhookCommand'] + except: + dic['webhookCommand'] = False + + dic['folder'] = self.folder + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + if self.folderCheck(): + pass + else: + return ACLManager.loadErrorJson() + + ## + + if self.confCheck == 1: + gitConfFolder = '/home/cyberpanel/git' + gitConFile = '%s/%s' % (gitConfFolder, self.masterDomain) + self.finalFile = '%s/%s' % (gitConFile, str(randint(1000, 9999))) + + if not os.path.exists(gitConfFolder): + os.mkdir(gitConfFolder) + + if not os.path.exists(gitConFile): + os.mkdir(gitConFile) + + writeToFile = open(self.finalFile, 'w') + writeToFile.write(json.dumps(dic)) + writeToFile.close() + + data_ret = {'status': 1} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def getLogsInJson(self, logs): + json_data = "[" + checker = 0 + counter = 1 + + for items in logs: + dic = {'type': items.type, 'date': items.date.strftime('%m.%d.%Y_%H-%M-%S'), 'message': items.message} + + if checker == 0: + json_data = json_data + json.dumps(dic) + checker = 1 + else: + json_data = json_data + ',' + json.dumps(dic) + counter = counter + 1 + + json_data = json_data + ']' + return json_data + + def fetchGitLogs(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + self.folder = data['folder'] + recordsToShow = int(data['recordsToShow']) + page = int(data['page']) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + if self.folderCheck(): + pass + else: + return ACLManager.loadErrorJson() + + logs = self.masterWebsite.gitlogs_set.all().order_by('-id') + + from s3Backups.s3Backups import S3Backups + + pagination = S3Backups.getPagination(len(logs), recordsToShow) + endPageNumber, finalPageNumber = S3Backups.recordsPointer(page, recordsToShow) + jsonData = self.getLogsInJson(logs[finalPageNumber:endPageNumber]) + + data_ret = {'status': 1, 'logs': jsonData, 'pagination': pagination} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + except IndexError: + data_ret = {'status': 0, 'error_message': 'Not a text file.'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def webhook(self, domain, data=None): + try: + + self.domain = domain + + ### set default ssh key + + try: + web = Websites.objects.get(domain=self.domain) + self.web = web + self.folder = '/home/%s/public_html' % (domain) + self.masterDomain = domain + except: + web = ChildDomains.objects.get(domain=self.domain) + self.folder = web.path + self.masterDomain = web.master.domain + self.web = web.master + + ## Check if remote exists + + self.externalApp = ACLManager.FetchExternalApp(self.domain) + + command = 'git -C %s pull' % (self.folder) + commandStatus = ProcessUtilities.outputExecutioner(command, self.externalApp) + + if commandStatus.find('Already up to date') == -1: + message = '[Webhook Fired] Status: %s.' % (commandStatus) + GitLogs(owner=self.web, type='INFO', message=message).save() + + ### Fetch git configurations + + found = 0 + + gitConfFolder = '/home/cyberpanel/git' + gitConFile = '%s/%s' % (gitConfFolder, self.masterDomain) + + if not os.path.exists(gitConfFolder): + os.mkdir(gitConfFolder) + + if not os.path.exists(gitConFile): + os.mkdir(gitConFile) + + if os.path.exists(gitConFile): + files = os.listdir(gitConFile) + + if len(files) >= 1: + for file in files: + finalFile = '%s/%s' % (gitConFile, file) + gitConf = json.loads(open(finalFile, 'r').read()) + if gitConf['folder'] == self.folder: + found = 1 + break + if found: + try: + if gitConf['webhookCommand']: + if gitConf['commands'] != 'NONE': + + GitLogs(owner=self.web, type='INFO', + message='Running commands after successful git commit..').save() + + if gitConf['commands'].find('\n') > -1: + commands = gitConf['commands'].split('\n') + + for command in commands: + GitLogs(owner=self.web, type='INFO', + message='Running: %s' % (command)).save() + + result = ProcessUtilities.outputExecutioner(command, self.web.externalApp, None, + self.folder) + GitLogs(owner=self.web, type='INFO', + message='Result: %s' % (result)).save() + else: + GitLogs(owner=self.web, type='INFO', + message='Running: %s' % (gitConf['commands'])).save() + + result = ProcessUtilities.outputExecutioner(gitConf['commands'], + self.web.externalApp, None, self.folder) + GitLogs(owner=self.web, type='INFO', + message='Result: %s' % (result)).save() + + GitLogs(owner=self.web, type='INFO', + message='Finished running commands.').save() + except: + pass + + ## Fix permissions + + # from filemanager.filemanager import FileManager + # + # fm = FileManager(None, None) + # fm.fixPermissions(self.masterDomain) + + data_ret = {'status': 1, 'commandStatus': commandStatus} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + message = '[Webhook Fired] Status: %s.' % (commandStatus) + GitLogs(owner=self.web, type='ERROR', message=message).save() + data_ret = {'status': 0, 'error_message': 'Pull not required.', 'commandStatus': commandStatus} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def getSSHConfigs(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + domain = data['domain'] + website = Websites.objects.get(domain=domain) + + if ACLManager.checkOwnership(domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + pathToKeyFile = "/home/%s/.ssh/authorized_keys" % (domain) + + cat = "cat " + pathToKeyFile + data = ProcessUtilities.outputExecutioner(cat, website.externalApp).split('\n') + + json_data = "[" + checker = 0 + + for items in data: + if items.find("ssh-rsa") > -1: + keydata = items.split(" ") + + try: + key = "ssh-rsa " + keydata[1][:50] + " .. " + keydata[2] + try: + userName = keydata[2][:keydata[2].index("@")] + except: + userName = keydata[2] + except: + key = "ssh-rsa " + keydata[1][:50] + userName = '' + + dic = {'userName': userName, + 'key': key, + } + + if checker == 0: + json_data = json_data + json.dumps(dic) + checker = 1 + else: + json_data = json_data + ',' + json.dumps(dic) + + json_data = json_data + ']' + + final_json = json.dumps({'status': 1, 'error_message': "None", "data": json_data}) + return HttpResponse(final_json) + + except BaseException as msg: + final_dic = {'status': 0, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def deleteSSHKey(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + domain = data['domain'] + + if ACLManager.checkOwnership(domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + key = data['key'] + pathToKeyFile = "/home/%s/.ssh/authorized_keys" % (domain) + website = Websites.objects.get(domain=domain) + + command = f'chown {website.externalApp}:{website.externalApp} {pathToKeyFile}' + ProcessUtilities.outputExecutioner(command) + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/firewallUtilities.py" + execPath = execPath + " deleteSSHKey --key '%s' --path %s" % (key, pathToKeyFile) + + output = ProcessUtilities.outputExecutioner(execPath, website.externalApp) + + if output.find("1,None") > -1: + final_dic = {'status': 1, 'delete_status': 1} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + else: + final_dic = {'status': 1, 'delete_status': 1, "error_mssage": output} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + except BaseException as msg: + final_dic = {'status': 0, 'delete_status': 0, 'error_mssage': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def addSSHKey(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + domain = data['domain'] + website = Websites.objects.get(domain=domain) + + if ACLManager.checkOwnership(domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + key = data['key'] + pathToKeyFile = "/home/%s/.ssh/authorized_keys" % (domain) + + command = 'mkdir -p /home/%s/.ssh/' % (domain) + ProcessUtilities.executioner(command) + + command = 'chown %s:%s /home/%s/.ssh/' % (website.externalApp, website.externalApp, domain) + ProcessUtilities.executioner(command) + + tempPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + + writeToFile = open(tempPath, "w") + writeToFile.write(key) + writeToFile.close() + + execPath = "sudo /usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/firewallUtilities.py" + execPath = execPath + " addSSHKey --tempPath %s --path %s" % (tempPath, pathToKeyFile) + + output = ProcessUtilities.outputExecutioner(execPath) + + if output.find("1,None") > -1: + final_dic = {'status': 1, 'add_status': 1} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + else: + final_dic = {'status': 0, 'add_status': 0, "error_mssage": output} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + except BaseException as msg: + final_dic = {'status': 0, 'add_status': 0, 'error_mssage': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def ApacheManager(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + phps = PHPManager.findPHPVersions() + apachePHPs = PHPManager.findApachePHPVersions() + + if ACLManager.CheckForPremFeature('all'): + apachemanager = 1 + else: + apachemanager = 0 + + proc = httpProc(request, 'websiteFunctions/ApacheManager.html', + {'domainName': self.domain, 'phps': phps, 'apachemanager': apachemanager, 'apachePHPs': apachePHPs}) + return proc.render() + + def saveApacheConfigsToFile(self, userID=None, data=None): + + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] != 1: + return ACLManager.loadErrorJson('configstatus', 0) + + configData = data['configData'] + self.domain = data['domainName'] + + mailUtilities.checkHome() + + tempPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + + vhost = open(tempPath, "w") + + vhost.write(configData) + + vhost.close() + + ## writing data temporary to file + + filePath = ApacheVhost.configBasePath + self.domain + '.conf' + + ## save configuration data + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " saveApacheConfigsToFile --path " + filePath + " --tempPath " + tempPath + + output = ProcessUtilities.outputExecutioner(execPath) + + if output.find("1,None") > -1: + status = {"status": 1} + final_json = json.dumps(status) + return HttpResponse(final_json) + else: + final_dic = {'status': 0, 'error_message': output} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def CreateDockerPackage(self, request=None, userID=None, data=None, DeleteID=None): + Data = {} + + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadError() + + try: + if DeleteID != None: + DockerPackagesDelete = DockerPackages.objects.get(pk=DeleteID) + DockerPackagesDelete.delete() + except: + pass + + Data['packages'] = DockerPackages.objects.all() + + proc = httpProc(request, 'websiteFunctions/CreateDockerPackage.html', + Data, 'createWebsite') + return proc.render() + + def AssignPackage(self, request=None, userID=None, data=None, DeleteID=None): + + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadError() + + try: + if DeleteID != None: + DockerPackagesDelete = PackageAssignment.objects.get(pk=DeleteID) + DockerPackagesDelete.delete() + except: + pass + + adminNames = ACLManager.loadAllUsers(userID) + dockerpackages = DockerPackages.objects.all() + assignpackage = PackageAssignment.objects.all() + Data = {'adminNames': adminNames, 'DockerPackages': dockerpackages, 'assignpackage': assignpackage} + proc = httpProc(request, 'websiteFunctions/assignPackage.html', + Data, 'createWebsite') + return proc.render() + + def CreateDockersite(self, request=None, userID=None, data=None): + adminNames = ACLManager.loadAllUsers(userID) + Data = {'adminNames': adminNames} + + + if PackageAssignment.objects.all().count() == 0: + + name = 'Default' + cpu = 2 + Memory = 1024 + Bandwidth = '100' + disk = '100' + + saveobj = DockerPackages(Name=name, CPUs=cpu, Ram=Memory, Bandwidth=Bandwidth, DiskSpace=disk, config='') + saveobj.save() + + userobj = Administrator.objects.get(pk=1) + + sv = PackageAssignment(user=userobj, package=saveobj) + sv.save() + + proc = httpProc(request, 'websiteFunctions/CreateDockerSite.html', + Data, 'createWebsite') + return proc.render() + + def AddDockerpackage(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadError() + + admin = Administrator.objects.get(pk=userID) + + name = data['name'] + cpu = data['cpu'] + Memory = data['Memory'] + Bandwidth = data['Bandwidth'] + disk = data['disk'] + + saveobj = DockerPackages(Name=name, CPUs=cpu, Ram=Memory, Bandwidth=Bandwidth, DiskSpace=disk, config='') + saveobj.save() + + status = {"status": 1, 'error_message': None} + final_json = json.dumps(status) + return HttpResponse(final_json) + except BaseException as msg: + final_dic = {'status': 0, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def Getpackage(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadError() + + admin = Administrator.objects.get(pk=userID) + id = data['id'] + + docker_package = DockerPackages.objects.get(pk=id) + + # Convert DockerPackages object to dictionary + package_data = { + 'Name': docker_package.Name, + 'CPU': docker_package.CPUs, + 'Memory': docker_package.Ram, + 'Bandwidth': docker_package.Bandwidth, + 'DiskSpace': docker_package.DiskSpace, + } + + rdata = {'obj': package_data} + + status = {"status": 1, 'error_message': rdata} + final_json = json.dumps(status) + return HttpResponse(final_json) + except BaseException as msg: + final_dic = {'status': 0, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def Updatepackage(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadError() + + admin = Administrator.objects.get(pk=userID) + id = data['id'] + CPU = data['CPU'] + RAM = data['RAM'] + Bandwidth = data['Bandwidth'] + DiskSpace = data['DiskSpace'] + + docker_package = DockerPackages.objects.get(pk=id) + + docker_package.CPUs = CPU + docker_package.Ram = RAM + docker_package.Bandwidth = Bandwidth + docker_package.DiskSpace = DiskSpace + docker_package.save() + + status = {"status": 1, 'error_message': None} + final_json = json.dumps(status) + return HttpResponse(final_json) + + except BaseException as msg: + final_dic = {'status': 0, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def AddAssignment(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadError() + + + admin = Administrator.objects.get(pk=userID) + + package = data['package'] + user = data['user'] + + userobj = Administrator.objects.get(userName=user) + + try: + delasg = PackageAssignment.objects.get(user=userobj) + delasg.delete() + except: + pass + + docker_package = DockerPackages.objects.get(pk=int(package)) + + sv = PackageAssignment(user=userobj, package=docker_package) + sv.save() + + status = {"status": 1, 'error_message': None} + final_json = json.dumps(status) + return HttpResponse(final_json) + + except BaseException as msg: + final_dic = {'status': 0, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def submitDockerSiteCreation(self, userID=None, data=None): + try: + admin = Administrator.objects.get(pk=userID) + currentACL = ACLManager.loadedACL(userID) + + sitename = data['sitename'] + Owner = data['Owner'] + Domain = data['Domain'] + MysqlCPU = int(data['MysqlCPU']) + MYsqlRam = int(data['MYsqlRam']) + SiteCPU = int(data['SiteCPU']) + SiteRam = int(data['SiteRam']) + App = data['App'] + WPusername = data['WPusername'] + WPemal = data['WPemal'] + WPpasswd = data['WPpasswd'] + + if int(MYsqlRam) < 256: + final_dic = {'status': 0, 'error_message': 'Minimum MySQL ram should be 256MB.'} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + if int(SiteRam) < 256: + final_dic = {'status': 0, 'error_message': 'Minimum site ram should be 256MB.'} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + + pattern = r"^[a-z0-9][a-z0-9]*$" + + if re.match(pattern, sitename): + pass + else: + final_dic = {'status': 0, 'error_message': f'invalid site name "{sitename}": must consist only of lowercase alphanumeric characters, as well as start with a letter or number.'} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + loggedUser = Administrator.objects.get(pk=userID) + newOwner = Administrator.objects.get(userName=Owner) + + try: + pkaobj = PackageAssignment.objects.get(user=newOwner) + except: + final_dic = {'status': 0, 'error_message': str('Please assign package to selected user')} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + Dpkgobj = DockerPackages.objects.get(pk=pkaobj.package.id) + + pkg_cpu = Dpkgobj.CPUs + pkg_Ram = Dpkgobj.Ram + + totalcup = SiteCPU + MysqlCPU + totalRam = SiteRam + MYsqlRam + + if (totalcup > pkg_cpu): + final_dic = {'status': 0, 'error_message': str(f'You can add {pkg_cpu} or less then {pkg_cpu} CPUs.')} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + if (totalRam > pkg_Ram): + final_dic = {'status': 0, 'error_message': str(f'You can add {pkg_Ram} or less then {pkg_Ram} Ram.')} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + if ACLManager.currentContextPermission(currentACL, 'createWebsite') == 0: + return ACLManager.loadErrorJson('createWebSiteStatus', 0) + + if ACLManager.checkOwnerProtection(currentACL, loggedUser, newOwner) == 0: + return ACLManager.loadErrorJson('createWebSiteStatus', 0) + + if ACLManager.CheckDomainBlackList(Domain) == 0: + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Blacklisted domain."} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + data = {} + + data['JobID'] = tempStatusPath + data['Domain'] = Domain + data['WPemal'] = WPemal + data['Owner'] = Owner + data['userID'] = userID + data['MysqlCPU'] = MysqlCPU + data['MYsqlRam'] = MYsqlRam + data['SiteCPU'] = SiteCPU + data['SiteRam'] = SiteRam + data['sitename'] = sitename + data['WPusername'] = WPusername + data['WPpasswd'] = WPpasswd + data['externalApp'] = "".join(re.findall("[a-zA-Z]+", Domain))[:5] + str(randint(1000, 9999)) + data['App'] = App + + background = Docker_Sites('SubmitDockersiteCreation', data) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': tempStatusPath} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + final_dic = {'status': 0, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def ListDockerSites(self, request=None, userID=None, data=None, DeleteID=None): + admin = Administrator.objects.get(pk=userID) + currentACL = ACLManager.loadedACL(userID) + fdata={} + + try: + if DeleteID != None: + + DockerSitesDelete = DockerSites.objects.get(pk=DeleteID) + if ACLManager.checkOwnership(DockerSitesDelete.admin.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + passdata={} + passdata["domain"] = DockerSitesDelete.admin.domain + passdata["JobID"] = None + passdata['name'] = DockerSitesDelete.SiteName + da = Docker_Sites(None, passdata) + da.DeleteDockerApp() + DockerSitesDelete.delete() + fdata['Deleted'] = 1 + except BaseException as msg: + fdata['LPError'] = 1 + fdata['LPMessage'] = str(msg) + + + fdata['pagination'] = self.DockersitePagination(currentACL, userID) + + proc = httpProc(request, 'websiteFunctions/ListDockersite.html', + fdata) + return proc.render() + + def fetchDockersite(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + pageNumber = int(data['page']) + recordsToShow = int(data['recordsToShow']) + + + endPageNumber, finalPageNumber = self.recordsPointer(pageNumber, recordsToShow) + + dockersites = ACLManager.findDockersiteObjects(currentACL, userID) + pagination = self.getPagination(len(dockersites), recordsToShow) + logging.CyberCPLogFileWriter.writeToFile("Our dockersite" + str(dockersites)) + + + json_data = self.findDockersitesListJson(dockersites[finalPageNumber:endPageNumber]) + + + final_dic = {'status': 1, 'listWebSiteStatus': 1, 'error_message': "None", "data": json_data, + 'pagination': pagination} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + except BaseException as msg: + final_dic = {'status': 0, 'listWebSiteStatus': 1, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def Dockersitehome(self, request=None, userID=None, data=None, DeleteID=None): + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + ds = DockerSites.objects.get(pk=self.domain) + + if ACLManager.checkOwnership(ds.admin.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + proc = httpProc(request, 'websiteFunctions/DockerSiteHome.html', + {'dockerSite': ds}) + return proc.render() + + def fetchWPSitesForDomain(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + domain = data['domain'] + website = Websites.objects.get(domain=domain) + + if ACLManager.checkOwnership(domain, admin, currentACL) != 1: + return ACLManager.loadErrorJson('fetchStatus', 0) + + wp_sites = WPSites.objects.filter(owner=website) + sites = [] + + for site in wp_sites: + sites.append({ + 'id': site.id, + 'title': site.title, + 'url': site.FinalURL, + 'path': site.path, + 'version': site.version, + 'status': site.status + }) + + data_ret = {'status': 1, 'fetchStatus': 1, 'error_message': "None", "sites": sites} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'fetchStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + +class WebsiteManager: + apache = 1 + ols = 2 + lsws = 3 + + def __init__(self, domain=None, childDomain=None): + self.domain = domain + self.childDomain = childDomain + + def createWebsite(self, request=None, userID=None, data=None): + + url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" + data = { + "name": "all", + "IP": ACLManager.GetServerIP() + } + + import requests + response = requests.post(url, data=json.dumps(data)) + Status = response.json()['status'] + + test_domain_status = 0 + + if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: + test_domain_status = 1 + + currentACL = ACLManager.loadedACL(userID) + adminNames = ACLManager.loadAllUsers(userID) + packagesName = ACLManager.loadPackages(userID, currentACL) + phps = PHPManager.findPHPVersions() + + rnpss = randomPassword.generate_pass(10) + + Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps, 'Randam_String': rnpss.lower(), + 'test_domain_data': test_domain_status} + proc = httpProc(request, 'websiteFunctions/createWebsite.html', + Data, 'createWebsite') + return proc.render() + + def WPCreate(self, request=None, userID=None, data=None): + url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" + data = { + "name": "wp-manager", + "IP": ACLManager.GetServerIP() + } + + import requests + response = requests.post(url, data=json.dumps(data)) + Status = response.json()['status'] + + if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: currentACL = ACLManager.loadedACL(userID) adminNames = ACLManager.loadAllUsers(userID) @@ -1990,67 +10302,537 @@ AuthUserFile {htpasswd} Require valid-user""" with open(htaccess, 'w') as f: f.write(htaccess_content) - else: - # Disable password protection - if os.path.exists(path): - import shutil - shutil.rmtree(path) - htaccess = f'{wpsite.path}/.htaccess' - if os.path.exists(htaccess): - os.remove(htaccess) - return JsonResponse({'status': 1, 'error_message': 'None'}) - elif setting == 'maintenance-mode': - if value: - command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp maintenance-mode activate --skip-plugins --skip-themes --path={wpsite.path}' - else: - command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp maintenance-mode deactivate --skip-plugins --skip-themes --path={wpsite.path}' - else: - return JsonResponse({'status': 0, 'error_message': 'Invalid setting type'}) + + def submitWebsiteModify(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) - result = ProcessUtilities.outputExecutioner(command) - if result.find('Error:') > -1: - return JsonResponse({'status': 0, 'error_message': result}) + domain = data['domain'] + website = Websites.objects.get(domain=domain) + + if ACLManager.checkOwnership(domain, admin, currentACL) != 1: + return ACLManager.loadErrorJson('fetchStatus', 0) - return JsonResponse({'status': 1, 'error_message': 'None'}) + wp_sites = WPSites.objects.filter(owner=website) + sites = [] + + for site in wp_sites: + sites.append({ + 'id': site.id, + 'title': site.title, + 'url': site.FinalURL, + 'path': site.path, + 'version': site.version, + 'status': site.status + }) + + data_ret = {'status': 1, 'fetchStatus': 1, 'error_message': "None", "sites": sites} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'fetchStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def getWebsiteCron(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + self.domain = data['domain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('getWebsiteCron', 0) + + website = Websites.objects.get(domain=self.domain) + + if Websites.objects.filter(domain=self.domain).exists(): + pass + else: + dic = {'getWebsiteCron': 0, 'error_message': 'You do not own this domain'} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + CronUtil.CronPrem(1) + + crons = [] + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" + execPath = execPath + " getWebsiteCron --externalApp " + website.externalApp + + f = ProcessUtilities.outputExecutioner(execPath, website.externalApp) + + CronUtil.CronPrem(0) + + if ProcessUtilities.decideDistro() == ProcessUtilities.centos or ProcessUtilities.decideDistro() == ProcessUtilities.cent8: + cronPath = "/var/spool/cron/" + website.externalApp + else: + cronPath = "/var/spool/cron/crontabs/" + website.externalApp + + if f.find('Permission denied') > -1: + command = 'chmod 644 %s' % (cronPath) + ProcessUtilities.executioner(command) + + command = 'chown %s:%s %s' % (website.externalApp, website.externalApp, cronPath) + ProcessUtilities.executioner(command) + + f = ProcessUtilities.outputExecutioner(execPath, website.externalApp) + + if f.find("0,CyberPanel,") > -1: + data_ret = {'getWebsiteCron': 0, "user": website.externalApp, "crons": {}} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + + counter = 0 + for line in f.split("\n"): + if line: + split = line.split(" ", 5) + if len(split) == 6: + counter += 1 + crons.append({"line": counter, + "minute": split[0], + "hour": split[1], + "monthday": split[2], + "month": split[3], + "weekday": split[4], + "command": split[5]}) + + data_ret = {'getWebsiteCron': 1, "user": website.externalApp, "crons": crons} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + except BaseException as msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg)) + dic = {'getWebsiteCron': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def getCronbyLine(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + line = data['line'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('getWebsiteCron', 0) + + if Websites.objects.filter(domain=self.domain).exists(): + pass + else: + dic = {'getWebsiteCron': 0, 'error_message': 'You do not own this domain'} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + line -= 1 + website = Websites.objects.get(domain=self.domain) + + try: + CronUtil.CronPrem(1) + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" + execPath = execPath + " getWebsiteCron --externalApp " + website.externalApp + + f = ProcessUtilities.outputExecutioner(execPath, website.externalApp) + CronUtil.CronPrem(0) + except subprocess.CalledProcessError as error: + dic = {'getWebsiteCron': 0, 'error_message': 'Unable to access Cron file'} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + f = f.split("\n") + cron = f[line] + + cron = cron.split(" ", 5) + if len(cron) != 6: + dic = {'getWebsiteCron': 0, 'error_message': 'Cron line incorrect'} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + data_ret = {"getWebsiteCron": 1, + "user": website.externalApp, + "cron": { + "minute": cron[0], + "hour": cron[1], + "monthday": cron[2], + "month": cron[3], + "weekday": cron[4], + "command": cron[5], + }, + "line": line} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + except BaseException as msg: + print(msg) + dic = {'getWebsiteCron': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def saveCronChanges(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + line = data['line'] + + minute = data['minute'] + hour = data['hour'] + monthday = data['monthday'] + month = data['month'] + weekday = data['weekday'] + command = data['cronCommand'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('getWebsiteCron', 0) + + website = Websites.objects.get(domain=self.domain) + + finalCron = "%s %s %s %s %s %s" % (minute, hour, monthday, month, weekday, command) + + CronUtil.CronPrem(1) + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" + execPath = execPath + " saveCronChanges --externalApp " + website.externalApp + " --line " + str( + line) + " --finalCron '" + finalCron + "'" + output = ProcessUtilities.outputExecutioner(execPath, website.externalApp) + CronUtil.CronPrem(0) + + if output.find("1,") > -1: + data_ret = {"getWebsiteCron": 1, + "user": website.externalApp, + "cron": finalCron, + "line": line} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + else: + dic = {'getWebsiteCron': 0, 'error_message': output} + json_data = json.dumps(dic) + return HttpResponse(json_data) + except BaseException as msg: - return JsonResponse({'status': 0, 'error_message': str(msg)}) + dic = {'getWebsiteCron': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) - def submitWorpressCreation(self, userID=None, data=None): + def remCronbyLine(self, userID=None, data=None): try: currentACL = ACLManager.loadedACL(userID) admin = Administrator.objects.get(pk=userID) - extraArgs = {} - extraArgs['currentACL'] = currentACL - extraArgs['adminID'] = admin.pk - extraArgs['domainName'] = data['domain'] - extraArgs['WPVersion'] = data['WPVersion'] - extraArgs['blogTitle'] = data['title'] - try: - extraArgs['pluginbucket'] = data['pluginbucket'] - except: - extraArgs['pluginbucket'] = '-1' - extraArgs['adminUser'] = data['adminUser'] - extraArgs['PasswordByPass'] = data['PasswordByPass'] - extraArgs['adminPassword'] = data['PasswordByPass'] - extraArgs['adminEmail'] = data['Email'] - extraArgs['updates'] = data['AutomaticUpdates'] - extraArgs['Plugins'] = data['Plugins'] - extraArgs['Themes'] = data['Themes'] - extraArgs['websiteOwner'] = data['websiteOwner'] - extraArgs['package'] = data['package'] - extraArgs['home'] = data['home'] - extraArgs['apacheBackend'] = data['apacheBackend'] - try: - extraArgs['path'] = data['path'] - if extraArgs['path'] == '': - extraArgs['home'] = '1' - except: + self.domain = data['domain'] + line = data['line'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: pass + else: + return ACLManager.loadErrorJson('addNewCron', 0) + + website = Websites.objects.get(domain=self.domain) + + CronUtil.CronPrem(1) + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" + execPath = execPath + " remCronbyLine --externalApp " + website.externalApp + " --line " + str( + line) + output = ProcessUtilities.outputExecutioner(execPath, website.externalApp) + + CronUtil.CronPrem(0) + + if output.find("1,") > -1: + data_ret = {"remCronbyLine": 1, + "user": website.externalApp, + "removeLine": output.split(',')[1], + "line": line} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + else: + dic = {'remCronbyLine': 0, 'error_message': output} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + + except BaseException as msg: + dic = {'remCronbyLine': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def addNewCron(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + minute = data['minute'] + hour = data['hour'] + monthday = data['monthday'] + month = data['month'] + weekday = data['weekday'] + command = data['cronCommand'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('addNewCron', 0) + + website = Websites.objects.get(domain=self.domain) + + if ProcessUtilities.decideDistro() == ProcessUtilities.centos or ProcessUtilities.decideDistro() == ProcessUtilities.cent8: + cronPath = "/var/spool/cron/" + website.externalApp + else: + cronPath = "/var/spool/cron/crontabs/" + website.externalApp + + commandT = 'touch %s' % (cronPath) + ProcessUtilities.executioner(commandT, 'root') + commandT = 'chown %s:%s %s' % (website.externalApp, website.externalApp, cronPath) + ProcessUtilities.executioner(commandT, 'root') + + CronUtil.CronPrem(1) + + finalCron = "%s %s %s %s %s %s" % (minute, hour, monthday, month, weekday, command) + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" + execPath = execPath + " addNewCron --externalApp " + website.externalApp + " --finalCron '" + finalCron + "'" + output = ProcessUtilities.outputExecutioner(execPath, website.externalApp) + + if ProcessUtilities.decideDistro() == ProcessUtilities.ubuntu or ProcessUtilities.decideDistro() == ProcessUtilities.ubuntu20: + command = 'chmod 600 %s' % (cronPath) + ProcessUtilities.executioner(command) + + command = 'systemctl restart cron' + ProcessUtilities.executioner(command) + + CronUtil.CronPrem(0) + + if output.find("1,") > -1: + + data_ret = {"addNewCron": 1, + "user": website.externalApp, + "cron": finalCron} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + else: + dic = {'addNewCron': 0, 'error_message': output} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + + except BaseException as msg: + dic = {'addNewCron': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def submitAliasCreation(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['masterDomain'] + aliasDomain = data['aliasDomain'] + ssl = data['ssl'] + + if not validators.domain(aliasDomain): + data_ret = {'status': 0, 'createAliasStatus': 0, 'error_message': "Invalid domain."} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('createAliasStatus', 0) + + sslpath = "/home/" + self.domain + "/public_html" + + ## Create Configurations + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + + execPath = execPath + " createAlias --masterDomain " + self.domain + " --aliasDomain " + aliasDomain + " --ssl " + str( + ssl) + " --sslPath " + sslpath + " --administratorEmail " + admin.email + ' --websiteOwner ' + admin.userName + + output = ProcessUtilities.outputExecutioner(execPath) + + if output.find("1,None") > -1: + pass + else: + data_ret = {'createAliasStatus': 0, 'error_message': output, "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + ## Create Configurations ends here + + data_ret = {'createAliasStatus': 1, 'error_message': "None", "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + + except BaseException as msg: + data_ret = {'createAliasStatus': 0, 'error_message': str(msg), "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def issueAliasSSL(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['masterDomain'] + aliasDomain = data['aliasDomain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('sslStatus', 0) + + if ACLManager.AliasDomainCheck(currentACL, aliasDomain, self.domain) == 1: + pass + else: + return ACLManager.loadErrorJson('sslStatus', 0) + + sslpath = "/home/" + self.domain + "/public_html" + + ## Create Configurations + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " issueAliasSSL --masterDomain " + self.domain + " --aliasDomain " + aliasDomain + " --sslPath " + sslpath + " --administratorEmail " + admin.email + + output = ProcessUtilities.outputExecutioner(execPath) + + if output.find("1,None") > -1: + data_ret = {'sslStatus': 1, 'error_message': "None", "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + data_ret = {'sslStatus': 0, 'error_message': output, "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'sslStatus': 0, 'error_message': str(msg), "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def delateAlias(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['masterDomain'] + aliasDomain = data['aliasDomain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('deleteAlias', 0) + + if ACLManager.AliasDomainCheck(currentACL, aliasDomain, self.domain) == 1: + pass + else: + return ACLManager.loadErrorJson('deleteAlias', 0) + + ## Create Configurations + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " deleteAlias --masterDomain " + self.domain + " --aliasDomain " + aliasDomain + output = ProcessUtilities.outputExecutioner(execPath) + + if output.find("1,None") > -1: + data_ret = {'deleteAlias': 1, 'error_message': "None", "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + data_ret = {'deleteAlias': 0, 'error_message': output, "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'deleteAlias': 0, 'error_message': str(msg), "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def changeOpenBasedir(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + + self.domain = data['domainName'] + openBasedirValue = data['openBasedirValue'] + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson('changeOpenBasedir', 0) + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " changeOpenBasedir --virtualHostName '" + self.domain + "' --openBasedirValue " + openBasedirValue + output = ProcessUtilities.popenExecutioner(execPath) + + data_ret = {'status': 1, 'changeOpenBasedir': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'changeOpenBasedir': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def wordpressInstall(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + proc = httpProc(request, 'websiteFunctions/installWordPress.html', {'domainName': self.domain}) + return proc.render() + + def installWordpress(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('installStatus', 0) + + mailUtilities.checkHome() + + extraArgs = {} + extraArgs['admin'] = admin + extraArgs['domainName'] = data['domain'] + extraArgs['home'] = data['home'] + extraArgs['blogTitle'] = data['blogTitle'] + extraArgs['adminUser'] = data['adminUser'] + extraArgs['adminPassword'] = data['passwordByPass'] + extraArgs['adminEmail'] = data['adminEmail'] extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - background = ApplicationInstaller('wordpressInstallNew', extraArgs) + if data['home'] == '0': + extraArgs['path'] = data['path'] + + background = ApplicationInstaller('wordpress', extraArgs) background.start() time.sleep(2) @@ -2060,1423 +10842,1633 @@ Require valid-user""" json_data = json.dumps(data_ret) return HttpResponse(json_data) + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def installWordpressStatus(self, userID=None, data=None): + try: + statusFile = data['statusFile'] + + if ACLManager.CheckStatusFilleLoc(statusFile): + pass + else: + data_ret = {'abort': 1, 'installStatus': 0, 'installationProgress': "100", + 'currentStatus': 'Invalid status file.'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + statusData = ProcessUtilities.outputExecutioner("cat " + statusFile).splitlines() + + lastLine = statusData[-1] + + if lastLine.find('[200]') > -1: + command = 'rm -f ' + statusFile + subprocess.call(shlex.split(command)) + data_ret = {'abort': 1, 'installStatus': 1, 'installationProgress': "100", + 'currentStatus': 'Successfully Installed.'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + elif lastLine.find('[404]') > -1: + data_ret = {'abort': 1, 'installStatus': 0, 'installationProgress': "0", + 'error_message': ProcessUtilities.outputExecutioner("cat " + statusFile).splitlines()} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + progress = lastLine.split(',') + currentStatus = progress[0] + try: + installationProgress = progress[1] + except: + installationProgress = 0 + data_ret = {'abort': 0, 'installStatus': 0, 'installationProgress': installationProgress, + 'currentStatus': currentStatus} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'abort': 0, 'installStatus': 0, 'installationProgress': "0", 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def joomlaInstall(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + proc = httpProc(request, 'websiteFunctions/installJoomla.html', {'domainName': self.domain}) + return proc.render() + + def installJoomla(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('installStatus', 0) + + extraArgs = {} + + extraArgs['password'] = data['passwordByPass'] + extraArgs['prefix'] = data['prefix'] + extraArgs['domain'] = data['domain'] + extraArgs['home'] = data['home'] + extraArgs['siteName'] = data['siteName'] + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + mailUtilities.checkHome() + + if data['home'] == '0': + extraArgs['path'] = data['path'] + + background = ApplicationInstaller('joomla', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + ## Installation ends except BaseException as msg: data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} json_data = json.dumps(data_ret) return HttpResponse(json_data) - def submitWebsiteCreation(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) + def setupGit(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + website = Websites.objects.get(domain=self.domain) - domain = data['domainName'] - adminEmail = data['adminEmail'] - phpSelection = data['phpSelection'] - packageName = data['package'] - websiteOwner = data['websiteOwner'].lower() + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson() - if data['domainName'].find("cyberpanel.website") > -1: - url = "https://platform.cyberpersons.com/CyberpanelAdOns/CreateDomain" + path = '/home/cyberpanel/' + self.domain + '.git' - domain_data = { - "name": "test-domain", - "IP": ACLManager.GetServerIP(), - "domain": data['domainName'] - } + if os.path.exists(path): + ipFile = "/etc/cyberpanel/machineIP" + f = open(ipFile) + ipData = f.read() + ipAddress = ipData.split('\n', 1)[0] - import requests - response = requests.post(url, data=json.dumps(domain_data)) - domain_status = response.json()['status'] + port = ProcessUtilities.fetchCurrentPort() - if domain_status == 0: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': response.json()['error_message']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) + webhookURL = 'https://' + ipAddress + ':%s/websites/' % (port) + self.domain + '/gitNotify' - loggedUser = Administrator.objects.get(pk=userID) - newOwner = Administrator.objects.get(userName=websiteOwner) + proc = httpProc(request, 'websiteFunctions/setupGit.html', + {'domainName': self.domain, 'installed': 1, 'webhookURL': webhookURL}) + return proc.render() + else: - if ACLManager.currentContextPermission(currentACL, 'createWebsite') == 0: - return ACLManager.loadErrorJson('createWebSiteStatus', 0) + command = "ssh-keygen -f /home/%s/.ssh/%s -t rsa -N ''" % (self.domain, website.externalApp) + ProcessUtilities.executioner(command, website.externalApp) - if ACLManager.checkOwnerProtection(currentACL, loggedUser, newOwner) == 0: - return ACLManager.loadErrorJson('createWebSiteStatus', 0) + ### - if currentACL['admin'] == 0: - if ACLManager.CheckDomainBlackList(domain) == 0: - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Blacklisted domain."} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) + configContent = """Host github.com +IdentityFile /home/%s/.ssh/%s +StrictHostKeyChecking no +""" % (self.domain, website.externalApp) + + path = "/home/cyberpanel/config" + writeToFile = open(path, 'w') + writeToFile.write(configContent) + writeToFile.close() - if not validators.domain(domain): - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Invalid domain."} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) + command = "cp /home/cyberpanel/config /home/%s/.ssh/config" % (self.domain) + ProcessUtilities.executioner(command, website.externalApp) - if not validators.email(adminEmail) or adminEmail.find('--') > -1: - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Invalid email."} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) + command = "chown %s:%s /home/%s/.ssh/config" % (website.externalApp, website.externalApp, self.domain) + ProcessUtilities.executioner(command) - try: - HA = data['HA'] - externalApp = 'nobody' - except: - externalApp = "".join(re.findall("[a-zA-Z]+", domain))[:5] + str(randint(1000, 9999)) + command = "chmod 600 /home/%s/.ssh/config" % (self.domain) + ProcessUtilities.executioner(command, website.externalApp) - try: - counter = 0 - while 1: - tWeb = Websites.objects.get(externalApp=externalApp) - externalApp = '%s%s' % (tWeb.externalApp, str(counter)) - counter = counter + 1 - except: - pass + command = "rm -rf /home/cyberpanel/config" + ProcessUtilities.executioner(command) - tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + command = "cp /home/%s/.ssh/id_rsa.pub /home/cyberpanel/%s.pub" % (self.domain, self.domain) + ProcessUtilities.executioner(command) - try: - apacheBackend = str(data['apacheBackend']) - except: - apacheBackend = "0" + command = "chown cyberpanel:cyberpanel /home/cyberpanel/%s.pub" % (self.domain) + ProcessUtilities.executioner(command) - try: - mailDomain = str(data['mailDomain']) - except: - mailDomain = "1" + ipFile = "/etc/cyberpanel/machineIP" + f = open(ipFile) + ipData = f.read() + ipAddress = ipData.split('\n', 1)[0] - import pwd - counter = 0 + port = ProcessUtilities.fetchCurrentPort() - ## Create Configurations + webhookURL = 'https://' + ipAddress + ':%s/websites/' % (port) + self.domain + '/gitNotify' - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " createVirtualHost --virtualHostName " + domain + \ - " --administratorEmail " + adminEmail + " --phpVersion '" + phpSelection + \ - "' --virtualHostUser " + externalApp + " --ssl " + str(1) + " --dkimCheck " \ - + str(1) + " --openBasedir " + str(data['openBasedir']) + \ - ' --websiteOwner "' + websiteOwner + '" --package "' + packageName + '" --tempStatusPath ' + tempStatusPath + " --apache " + apacheBackend + " --mailDomain %s" % ( - mailDomain) + proc = httpProc(request, 'websiteFunctions/setupGit.html', + {'domainName': self.domain, 'installed': 0, 'webhookURL': webhookURL}) + return proc.render() - ProcessUtilities.popenExecutioner(execPath) - time.sleep(2) - - data_ret = {'status': 1, 'createWebSiteStatus': 1, 'error_message': "None", - 'tempStatusPath': tempStatusPath, 'LinuxUser': externalApp} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def submitDomainCreation(self, userID=None, data=None): + def startCloning(self, userID=None, data=None): try: currentACL = ACLManager.loadedACL(userID) admin = Administrator.objects.get(pk=userID) - try: - alias = data['alias'] - except: - alias = 0 - - masterDomain = data['masterDomain'] - domain = data['domainName'] - - - if alias == 0: - phpSelection = data['phpSelection'] - path = data['path'] - else: - - ### if master website have apache then create this sub-domain also as ols + apache - - apachePath = ApacheVhost.configBasePath + masterDomain + '.conf' - - if os.path.exists(apachePath): - data['apacheBackend'] = 1 - - phpSelection = Websites.objects.get(domain=masterDomain).phpSelection - + self.domain = data['domain'] + repoURL = data['repoURL'] + branch = data['branch'] + repoName = data['repoName'] tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - if not validators.domain(domain): - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Invalid domain."} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - if data['domainName'].find("cyberpanel.website") > -1: - url = "https://platform.cyberpersons.com/CyberpanelAdOns/CreateDomain" - - domain_data = { - "name": "test-domain", - "IP": ACLManager.GetServerIP(), - "domain": data['domainName'] - } - - import requests - response = requests.post(url, data=json.dumps(domain_data)) - domain_status = response.json()['status'] - - if domain_status == 0: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': response.json()['error_message']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - if ACLManager.checkOwnership(masterDomain, admin, currentACL) == 1: + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: pass else: - return ACLManager.loadErrorJson('createWebSiteStatus', 0) + return ACLManager.loadErrorJson('cloneStatus', 0) - if data['path'].find('..') > -1: - return ACLManager.loadErrorJson('createWebSiteStatus', 0) + background = Cloner(self.domain, repoURL, branch, repoName, tempStatusPath) + background.start() - if currentACL['admin'] != 1: - data['openBasedir'] = 1 - - if alias == 0: - - if len(path) > 0: - path = path.lstrip("/") - path = "/home/" + masterDomain + "/" + path - else: - path = "/home/" + masterDomain + "/" + domain - else: - path = f'/home/{masterDomain}/public_html' - - try: - apacheBackend = str(data['apacheBackend']) - except: - apacheBackend = "0" - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - - execPath = execPath + " createDomain --masterDomain " + masterDomain + " --virtualHostName " + domain + \ - " --phpVersion '" + phpSelection + "' --ssl " + str(1) + " --dkimCheck " + str(1) \ - + " --openBasedir " + str(data['openBasedir']) + ' --path ' + path + ' --websiteOwner ' \ - + admin.userName + ' --tempStatusPath ' + tempStatusPath + " --apache " + apacheBackend + f' --aliasDomain {str(alias)}' - - ProcessUtilities.popenExecutioner(execPath) time.sleep(2) - data_ret = {'status': 1, 'createWebSiteStatus': 1, 'error_message': "None", + data_ret = {'status': 1, 'cloneStatus': 1, 'error_message': 'None', 'tempStatusPath': tempStatusPath} json_data = json.dumps(data_ret) return HttpResponse(json_data) except BaseException as msg: - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': str(msg)} + data_ret = {'status': 0, 'cloneStatus': 0, 'error_message': str(msg)} json_data = json.dumps(data_ret) return HttpResponse(json_data) - def fetchDomains(self, userID=None, data=None): + def cloneStatus(self, userID=None, data=None): try: + statusFile = data['statusFile'] - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - masterDomain = data['masterDomain'] - - try: - alias = data['alias'] - except: - alias = 0 - - if ACLManager.checkOwnership(masterDomain, admin, currentACL) == 1: + if ACLManager.CheckStatusFilleLoc(statusFile): pass else: - return ACLManager.loadErrorJson('fetchStatus', 0) - - cdManager = ChildDomainManager(masterDomain) - json_data = cdManager.findChildDomainsJson(alias) - - final_json = json.dumps({'status': 1, 'fetchStatus': 1, 'error_message': "None", "data": json_data}) - return HttpResponse(final_json) - - except BaseException as msg: - final_dic = {'status': 0, 'fetchStatus': 0, 'error_message': str(msg)} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - def searchWebsites(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - try: - json_data = self.searchWebsitesJson(currentACL, userID, data['patternAdded']) - except BaseException as msg: - tempData = {} - tempData['page'] = 1 - return self.getFurtherAccounts(userID, tempData) - - pagination = self.websitePagination(currentACL, userID) - final_dic = {'status': 1, 'listWebSiteStatus': 1, 'error_message': "None", "data": json_data, - 'pagination': pagination} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - except BaseException as msg: - dic = {'status': 1, 'listWebSiteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def searchChilds(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - - websites = ACLManager.findWebsiteObjects(currentACL, userID) - childDomains = [] - - for web in websites: - for child in web.childdomains_set.filter(domain__istartswith=data['patternAdded']): - childDomains.append(child) - - json_data = self.findChildsListJson(childDomains) - - final_dic = {'status': 1, 'listWebSiteStatus': 1, 'error_message': "None", "data": json_data} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - except BaseException as msg: - dic = {'status': 1, 'listWebSiteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def getFurtherAccounts(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - pageNumber = int(data['page']) - json_data = self.findWebsitesJson(currentACL, userID, pageNumber) - pagination = self.websitePagination(currentACL, userID) - final_dic = {'status': 1, 'listWebSiteStatus': 1, 'error_message': "None", "data": json_data, - 'pagination': pagination} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - except BaseException as msg: - dic = {'status': 1, 'listWebSiteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def fetchWebsitesList(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - pageNumber = int(data['page']) - recordsToShow = int(data['recordsToShow']) - - if os.path.exists(ProcessUtilities.debugPath): - logging.CyberCPLogFileWriter.writeToFile(f'Fetch sites step 1..') - - endPageNumber, finalPageNumber = self.recordsPointer(pageNumber, recordsToShow) - - if os.path.exists(ProcessUtilities.debugPath): - logging.CyberCPLogFileWriter.writeToFile(f'Fetch sites step 2..') - - websites = ACLManager.findWebsiteObjects(currentACL, userID) - - if os.path.exists(ProcessUtilities.debugPath): - logging.CyberCPLogFileWriter.writeToFile(f'Fetch sites step 3..') - - pagination = self.getPagination(len(websites), recordsToShow) - - if os.path.exists(ProcessUtilities.debugPath): - logging.CyberCPLogFileWriter.writeToFile(f'Fetch sites step 4..') - - json_data = self.findWebsitesListJson(websites[finalPageNumber:endPageNumber]) - - if os.path.exists(ProcessUtilities.debugPath): - logging.CyberCPLogFileWriter.writeToFile(f'Fetch sites step 5..') - - final_dic = {'status': 1, 'listWebSiteStatus': 1, 'error_message': "None", "data": json_data, - 'pagination': pagination} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - except BaseException as msg: - dic = {'status': 1, 'listWebSiteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def fetchChildDomainsMain(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - pageNumber = int(data['page']) - recordsToShow = int(data['recordsToShow']) - - endPageNumber, finalPageNumber = self.recordsPointer(pageNumber, recordsToShow) - websites = ACLManager.findWebsiteObjects(currentACL, userID) - childDomains = [] - - for web in websites: - for child in web.childdomains_set.filter(alais=0): - if child.domain == f'mail.{web.domain}': - pass - else: - childDomains.append(child) - - pagination = self.getPagination(len(childDomains), recordsToShow) - json_data = self.findChildsListJson(childDomains[finalPageNumber:endPageNumber]) - - final_dic = {'status': 1, 'listWebSiteStatus': 1, 'error_message': "None", "data": json_data, - 'pagination': pagination} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - except BaseException as msg: - dic = {'status': 1, 'listWebSiteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def findWebsitesListJson(self, websites): - try: - ipFile = "/etc/cyberpanel/machineIP" - f = open(ipFile) - ipData = f.read() - ipAddress = ipData.split('\n', 1)[0] - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile("Failed to read machine IP, error:" + str(msg)) - ipAddress = "192.168.100.1" - - json_data = [] - - for website in websites: - wp_sites = [] - try: - wp_sites = WPSites.objects.filter(owner=website) - wp_sites = [{ - 'id': wp.id, - 'title': wp.title, - 'url': wp.FinalURL, - 'version': wp.version if hasattr(wp, 'version') else 'Unknown', - 'phpVersion': wp.phpVersion if hasattr(wp, 'phpVersion') else 'Unknown' - } for wp in wp_sites] - except: - pass - - # Calculate disk usage - DiskUsage, DiskUsagePercentage, bwInMB, bwUsage = virtualHostUtilities.FindStats(website) - diskUsed = "%sMB" % str(DiskUsage) - - # Convert numeric state to text - state = "Active" if website.state == 1 else "Suspended" - - json_data.append({ - 'domain': website.domain, - 'adminEmail': website.adminEmail, - 'phpVersion': website.phpSelection, - 'state': state, - 'ipAddress': ipAddress, - 'package': website.package.packageName, - 'admin': website.admin.userName, - 'wp_sites': wp_sites, - 'diskUsed': diskUsed - }) - return json.dumps(json_data) - - - - def findDockersitesListJson(self, Dockersite): - - json_data = "[" - checker = 0 - - try: - ipFile = "/etc/cyberpanel/machineIP" - f = open(ipFile) - ipData = f.read() - ipAddress = ipData.split('\n', 1)[0] - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile("Failed to read machine IP, error:" + str(msg)) - ipAddress = "192.168.100.1" - - from plogical.phpUtilities import phpUtilities - for items in Dockersite: - website = Websites.objects.get(pk=items.admin.pk) - vhFile = f'/usr/local/lsws/conf/vhosts/{website.domain}/vhost.conf' - - try: - PHPVersionActual = phpUtilities.WrapGetPHPVersionFromFileToGetVersionWithPHP(website) - except: - PHPVersionActual = 'PHP 8.1' - - - if items.state == 0: - state = "Suspended" - else: - state = "Active" - - dpkg = PackageAssignment.objects.get(user=website.admin) - - - dic = {'id':items.pk, 'domain': website.domain, 'adminEmail': website.adminEmail, 'ipAddress': ipAddress, - 'admin': website.admin.userName, 'package': dpkg.package.Name, 'state': state, - 'CPU': int(items.CPUsMySQL)+int(items.CPUsSite), 'Ram': int(items.MemorySite)+int(items.MemoryMySQL), 'phpVersion': PHPVersionActual } - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - - json_data = json_data + ']' - - return json_data - - def findChildsListJson(self, childs): - - json_data = "[" - checker = 0 - - try: - ipFile = "/etc/cyberpanel/machineIP" - f = open(ipFile) - ipData = f.read() - ipAddress = ipData.split('\n', 1)[0] - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile("Failed to read machine IP, error:" + str(msg)) - ipAddress = "192.168.100.1" - - for items in childs: - - dic = {'domain': items.domain, 'masterDomain': items.master.domain, 'adminEmail': items.master.adminEmail, - 'ipAddress': ipAddress, - 'admin': items.master.admin.userName, 'package': items.master.package.packageName, - 'path': items.path} - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - - json_data = json_data + ']' - - return json_data - - def recordsPointer(self, page, toShow): - finalPageNumber = ((page * toShow)) - toShow - endPageNumber = finalPageNumber + toShow - return endPageNumber, finalPageNumber - - def getPagination(self, records, toShow): - pages = float(records) / float(toShow) - - pagination = [] - counter = 1 - - if pages <= 1.0: - pages = 1 - pagination.append(counter) - else: - pages = ceil(pages) - finalPages = int(pages) + 1 - - for i in range(1, finalPages): - pagination.append(counter) - counter = counter + 1 - - return pagination - - def submitWebsiteDeletion(self, userID=None, data=None): - try: - if data['websiteName'].find("cyberpanel.website") > -1: - url = "https://platform.cyberpersons.com/CyberpanelAdOns/DeleteDomain" - - domain_data = { - "name": "test-domain", - "IP": ACLManager.GetServerIP(), - "domain": data['websiteName'] - } - - import requests - response = requests.post(url, data=json.dumps(domain_data)) - - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'deleteWebsite') == 0: - return ACLManager.loadErrorJson('websiteDeleteStatus', 0) - - websiteName = data['websiteName'] - - admin = Administrator.objects.get(pk=userID) - if ACLManager.checkOwnership(websiteName, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('websiteDeleteStatus', 0) - - ## Deleting master domain - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " deleteVirtualHostConfigurations --virtualHostName " + websiteName - ProcessUtilities.popenExecutioner(execPath) - - ### delete site from dgdrive backups - - try: - - from websiteFunctions.models import GDriveSites - GDriveSites.objects.filter(domain=websiteName).delete() - except: - pass - - data_ret = {'status': 1, 'websiteDeleteStatus': 1, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'websiteDeleteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def submitDomainDeletion(self, userID=None, data=None): - try: - - if data['websiteName'].find("cyberpanel.website") > -1: - url = "https://platform.cyberpersons.com/CyberpanelAdOns/DeleteDomain" - - domain_data = { - "name": "test-domain", - "IP": ACLManager.GetServerIP(), - "domain": data['websiteName'] - } - - import requests - response = requests.post(url, data=json.dumps(domain_data)) - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - websiteName = data['websiteName'] - - try: - DeleteDocRoot = int(data['DeleteDocRoot']) - except: - DeleteDocRoot = 0 - - if ACLManager.checkOwnership(websiteName, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('websiteDeleteStatus', 0) - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " deleteDomain --virtualHostName " + websiteName + ' --DeleteDocRoot %s' % ( - str(DeleteDocRoot)) - ProcessUtilities.outputExecutioner(execPath) - - data_ret = {'status': 1, 'websiteDeleteStatus': 1, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'websiteDeleteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def submitWebsiteStatus(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'suspendWebsite') == 0: - return ACLManager.loadErrorJson('websiteStatus', 0) - - websiteName = data['websiteName'] - state = data['state'] - - website = Websites.objects.get(domain=websiteName) - - admin = Administrator.objects.get(pk=userID) - if ACLManager.checkOwnership(websiteName, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('websiteStatus', 0) - - if state == "Suspend": - confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + websiteName - command = "mv " + confPath + " " + confPath + "-suspended" - ProcessUtilities.popenExecutioner(command) - - childDomains = website.childdomains_set.all() - - for items in childDomains: - confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + items.domain - command = "mv " + confPath + " " + confPath + "-suspended" - ProcessUtilities.executioner(command) - - installUtilities.reStartLiteSpeedSocket() - website.state = 0 - else: - confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + websiteName - - command = "mv " + confPath + "-suspended" + " " + confPath - ProcessUtilities.executioner(command) - - command = "chown -R " + "lsadm" + ":" + "lsadm" + " " + confPath - ProcessUtilities.popenExecutioner(command) - - childDomains = website.childdomains_set.all() - - for items in childDomains: - confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + items.domain - - command = "mv " + confPath + "-suspended" + " " + confPath - ProcessUtilities.executioner(command) - - command = "chown -R " + "lsadm" + ":" + "lsadm" + " " + confPath - ProcessUtilities.popenExecutioner(command) - - installUtilities.reStartLiteSpeedSocket() - website.state = 1 - - website.save() - - data_ret = {'websiteStatus': 1, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - - data_ret = {'websiteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def submitWebsiteModify(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'modifyWebsite') == 0: - return ACLManager.loadErrorJson('modifyStatus', 0) - - admin = Administrator.objects.get(pk=userID) - if ACLManager.checkOwnership(data['websiteToBeModified'], admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('websiteDeleteStatus', 0) - - packs = ACLManager.loadPackages(userID, currentACL) - admins = ACLManager.loadAllUsers(userID) - - ## Get packs name - - json_data = "[" - checker = 0 - - for items in packs: - dic = {"pack": items} - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - - json_data = json_data + ']' - - ### Get admin names - - admin_data = "[" - checker = 0 - - for items in admins: - dic = {"adminNames": items} - - if checker == 0: - admin_data = admin_data + json.dumps(dic) - checker = 1 - else: - admin_data = admin_data + ',' + json.dumps(dic) - - admin_data = admin_data + ']' - - websiteToBeModified = data['websiteToBeModified'] - - modifyWeb = Websites.objects.get(domain=websiteToBeModified) - - email = modifyWeb.adminEmail - currentPack = modifyWeb.package.packageName - owner = modifyWeb.admin.userName - - data_ret = {'status': 1, 'modifyStatus': 1, 'error_message': "None", "adminEmail": email, - "packages": json_data, "current_pack": currentPack, "adminNames": admin_data, - 'currentAdmin': owner} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - - except BaseException as msg: - dic = {'status': 0, 'modifyStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def fetchWebsiteDataJSON(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'createWebsite') == 0: - return ACLManager.loadErrorJson('createWebSiteStatus', 0) - - packs = ACLManager.loadPackages(userID, currentACL) - admins = ACLManager.loadAllUsers(userID) - - ## Get packs name - - json_data = "[" - checker = 0 - - for items in packs: - dic = {"pack": items} - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - - json_data = json_data + ']' - - ### Get admin names - - admin_data = "[" - checker = 0 - - for items in admins: - dic = {"adminNames": items} - - if checker == 0: - admin_data = admin_data + json.dumps(dic) - checker = 1 - else: - admin_data = admin_data + ',' + json.dumps(dic) - - admin_data = admin_data + ']' - - data_ret = {'status': 1, 'error_message': "None", - "packages": json_data, "adminNames": admin_data} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - - except BaseException as msg: - dic = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def saveWebsiteChanges(self, userID=None, data=None): - try: - domain = data['domain'] - package = data['packForWeb'] - email = data['email'] - phpVersion = data['phpVersion'] - newUser = data['admin'] - - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'modifyWebsite') == 0: - return ACLManager.loadErrorJson('saveStatus', 0) - - admin = Administrator.objects.get(pk=userID) - if ACLManager.checkOwnership(domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('websiteDeleteStatus', 0) - - newOwner = Administrator.objects.get(userName=newUser) - if ACLManager.checkUserOwnerShip(currentACL, admin, newOwner) == 1: - pass - else: - return ACLManager.loadErrorJson('websiteDeleteStatus', 0) - - confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + domain - completePathToConfigFile = confPath + "/vhost.conf" - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " changePHP --phpVersion '" + phpVersion + "' --path " + completePathToConfigFile - ProcessUtilities.popenExecutioner(execPath) - - #### - - newOwner = Administrator.objects.get(userName=newUser) - - modifyWeb = Websites.objects.get(domain=domain) - webpack = Package.objects.get(packageName=package) - - modifyWeb.package = webpack - modifyWeb.adminEmail = email - modifyWeb.phpSelection = phpVersion - modifyWeb.admin = newOwner - - modifyWeb.save() - - ## Fix https://github.com/usmannasir/cyberpanel/issues/998 - - # from plogical.IncScheduler import IncScheduler - # isPU = IncScheduler('CalculateAndUpdateDiskUsage', {}) - # isPU.start() - - command = '/usr/local/CyberCP/bin/python /usr/local/CyberCP/plogical/IncScheduler.py UpdateDiskUsageForce' - ProcessUtilities.outputExecutioner(command) - - ## - - data_ret = {'status': 1, 'saveStatus': 1, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'saveStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def loadDomainHome(self, request=None, userID=None, data=None): - - if Websites.objects.filter(domain=self.domain).exists(): - - currentACL = ACLManager.loadedACL(userID) - website = Websites.objects.get(domain=self.domain) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - Data = {} - - marketingStatus = emACL.checkIfEMEnabled(admin.userName) - - Data['marketingStatus'] = marketingStatus - Data['ftpTotal'] = website.package.ftpAccounts - Data['ftpUsed'] = website.users_set.all().count() - - Data['databasesUsed'] = website.databases_set.all().count() - Data['databasesTotal'] = website.package.dataBases - - Data['domain'] = self.domain - - DiskUsage, DiskUsagePercentage, bwInMB, bwUsage = virtualHostUtilities.FindStats(website) - - ## bw usage calculations - - Data['bwInMBTotal'] = website.package.bandwidth - Data['bwInMB'] = bwInMB - Data['bwUsage'] = bwUsage - - if DiskUsagePercentage > 100: - DiskUsagePercentage = 100 - - Data['diskUsage'] = DiskUsagePercentage - Data['diskInMB'] = DiskUsage - Data['diskInMBTotal'] = website.package.diskSpace - - Data['phps'] = PHPManager.findPHPVersions() - - servicePath = '/home/cyberpanel/postfix' - if os.path.exists(servicePath): - Data['email'] = 1 - else: - Data['email'] = 0 - - ## Getting SSL Information - try: - import OpenSSL - from datetime import datetime - filePath = '/etc/letsencrypt/live/%s/fullchain.pem' % (self.domain) - x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, - open(filePath, 'r').read()) - expireData = x509.get_notAfter().decode('ascii') - finalDate = datetime.strptime(expireData, '%Y%m%d%H%M%SZ') - - now = datetime.now() - diff = finalDate - now - Data['viewSSL'] = 1 - Data['days'] = str(diff.days) - Data['authority'] = x509.get_issuer().get_components()[1][1].decode('utf-8') - - if Data['authority'] == 'Denial': - Data['authority'] = '%s has SELF-SIGNED SSL.' % (self.domain) - else: - Data['authority'] = '%s has SSL from %s.' % (self.domain, Data['authority']) - - except BaseException as msg: - Data['viewSSL'] = 0 - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - - servicePath = '/home/cyberpanel/pureftpd' - if os.path.exists(servicePath): - Data['ftp'] = 1 - else: - Data['ftp'] = 0 - - proc = httpProc(request, 'websiteFunctions/website.html', Data) - return proc.render() - else: - proc = httpProc(request, 'websiteFunctions/website.html', - {"error": 1, "domain": "This domain does not exists."}) - return proc.render() - - def launchChild(self, request=None, userID=None, data=None): - - if ChildDomains.objects.filter(domain=self.childDomain).exists(): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - website = Websites.objects.get(domain=self.domain) - - Data = {} - - Data['ftpTotal'] = website.package.ftpAccounts - Data['ftpUsed'] = website.users_set.all().count() - - Data['databasesUsed'] = website.databases_set.all().count() - Data['databasesTotal'] = website.package.dataBases - - Data['domain'] = self.domain - Data['childDomain'] = self.childDomain - - DiskUsage, DiskUsagePercentage, bwInMB, bwUsage = virtualHostUtilities.FindStats(website) - - ## bw usage calculations - - Data['bwInMBTotal'] = website.package.bandwidth - Data['bwInMB'] = bwInMB - Data['bwUsage'] = bwUsage - - if DiskUsagePercentage > 100: - DiskUsagePercentage = 100 - - Data['diskUsage'] = DiskUsagePercentage - Data['diskInMB'] = DiskUsage - Data['diskInMBTotal'] = website.package.diskSpace - - Data['phps'] = PHPManager.findPHPVersions() - - servicePath = '/home/cyberpanel/postfix' - if os.path.exists(servicePath): - Data['email'] = 1 - else: - Data['email'] = 0 - - servicePath = '/home/cyberpanel/pureftpd' - if os.path.exists(servicePath): - Data['ftp'] = 1 - else: - Data['ftp'] = 0 - - ## Getting SSL Information - try: - import OpenSSL - from datetime import datetime - filePath = '/etc/letsencrypt/live/%s/fullchain.pem' % (self.childDomain) - x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, - open(filePath, 'r').read()) - expireData = x509.get_notAfter().decode('ascii') - finalDate = datetime.strptime(expireData, '%Y%m%d%H%M%SZ') - - now = datetime.now() - diff = finalDate - now - Data['viewSSL'] = 1 - Data['days'] = str(diff.days) - Data['authority'] = x509.get_issuer().get_components()[1][1].decode('utf-8') - - if Data['authority'] == 'Denial': - Data['authority'] = '%s has SELF-SIGNED SSL.' % (self.childDomain) - else: - Data['authority'] = '%s has SSL from %s.' % (self.childDomain, Data['authority']) - - except BaseException as msg: - Data['viewSSL'] = 0 - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - - proc = httpProc(request, 'websiteFunctions/launchChild.html', Data) - return proc.render() - else: - proc = httpProc(request, 'websiteFunctions/launchChild.html', - {"error": 1, "domain": "This child domain does not exists"}) - return proc.render() - - def getDataFromLogFile(self, userID=None, data=None): - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - logType = data['logType'] - self.domain = data['virtualHost'] - page = data['page'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('logstatus', 0) - - if logType == 1: - fileName = "/home/" + self.domain + "/logs/" + self.domain + ".access_log" - else: - fileName = "/home/" + self.domain + "/logs/" + self.domain + ".error_log" - - command = 'ls -la %s' % fileName - result = ProcessUtilities.outputExecutioner(command) - - if result.find('->') > -1: - final_json = json.dumps( - {'status': 0, 'logstatus': 0, - 'error_message': "Symlink attack."}) - return HttpResponse(final_json) - - ## get Logs - website = Websites.objects.get(domain=self.domain) - - output = virtualHostUtilities.getAccessLogs(fileName, page, website.externalApp) - - if output.find("1,None") > -1: - final_json = json.dumps( - {'status': 0, 'logstatus': 0, - 'error_message': "Not able to fetch logs, see CyberPanel main log file, Error: %s" % (output)}) - return HttpResponse(final_json) - - ## get log ends here. - - data = output.split("\n") - - json_data = "[" - checker = 0 - - for items in reversed(data): - if len(items) > 10: - logData = items.split(" ") - domain = logData[5].strip('"') - ipAddress = logData[0].strip('"') - time = (logData[3]).strip("[").strip("]") - resource = logData[6].strip('"') - size = logData[9].replace('"', '') - - dic = {'domain': domain, - 'ipAddress': ipAddress, - 'time': time, - 'resource': resource, - 'size': size, - } - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - - json_data = json_data + ']' - final_json = json.dumps({'status': 1, 'logstatus': 1, 'error_message': "None", "data": json_data}) - return HttpResponse(final_json) - - def fetchErrorLogs(self, userID=None, data=None): - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['virtualHost'] - page = data['page'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('logstatus', 0) - - fileName = "/home/" + self.domain + "/logs/" + self.domain + ".error_log" - - command = 'ls -la %s' % fileName - result = ProcessUtilities.outputExecutioner(command) - - if result.find('->') > -1: - final_json = json.dumps( - {'status': 0, 'logstatus': 0, - 'error_message': "Symlink attack."}) - return HttpResponse(final_json) - - ## get Logs - website = Websites.objects.get(domain=self.domain) - - output = virtualHostUtilities.getErrorLogs(fileName, page, website.externalApp) - - if output.find("1,None") > -1: - final_json = json.dumps( - {'status': 0, 'logstatus': 0, 'error_message': "Not able to fetch logs, see CyberPanel main log file!"}) - return HttpResponse(final_json) - - ## get log ends here. - - final_json = json.dumps({'status': 1, 'logstatus': 1, 'error_message': "None", "data": output}) - return HttpResponse(final_json) - - def getDataFromConfigFile(self, userID=None, data=None): - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - self.domain = data['virtualHost'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('configstatus', 0) - - command = 'cat %s' % ('/usr/local/lsws/conf/dvhost_redis.conf') - - if ProcessUtilities.outputExecutioner(command).find('127.0.0.1') == -1: - filePath = installUtilities.Server_root_path + "/conf/vhosts/" + self.domain + "/vhost.conf" - - command = 'cat ' + filePath - configData = ProcessUtilities.outputExecutioner(command, 'lsadm') - - if len(configData) == 0: - status = {'status': 0, "configstatus": 0, "error_message": "Configuration file is currently empty!"} - - final_json = json.dumps(status) - return HttpResponse(final_json) - - else: - command = 'redis-cli get "vhost:%s"' % (self.domain) - configData = ProcessUtilities.outputExecutioner(command) - configData = '#### This configuration is fetched from redis as Redis-Mass Hosting is being used.\n%s' % ( - configData) - - status = {'status': 1, "configstatus": 1, "configData": configData} - final_json = json.dumps(status) - return HttpResponse(final_json) - - def saveConfigsToFile(self, userID=None, data=None): - - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] != 1: - return ACLManager.loadErrorJson('configstatus', 0) - - configData = data['configData'] - self.domain = data['virtualHost'] - - if len(configData) == 0: - status = {"configstatus": 0, 'error_message': 'Error: you are trying to save empty vhost file, your website will stop working.'} - - final_json = json.dumps(status) - return HttpResponse(final_json) - - - command = 'cat %s' % ('/usr/local/lsws/conf/dvhost_redis.conf') - - if ProcessUtilities.outputExecutioner(command).find('127.0.0.1') == -1: - - mailUtilities.checkHome() - - tempPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - - vhost = open(tempPath, "w") - - vhost.write(configData) - - vhost.close() - - ## writing data temporary to file - - filePath = installUtilities.Server_root_path + "/conf/vhosts/" + self.domain + "/vhost.conf" - - ## save configuration data - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " saveVHostConfigs --path " + filePath + " --tempPath " + tempPath - - output = ProcessUtilities.outputExecutioner(execPath) - - if output.find("1,None") > -1: - status = {"configstatus": 1} - - final_json = json.dumps(status) - return HttpResponse(final_json) - else: - data_ret = {'configstatus': 0, 'error_message': output} + data_ret = {'abort': 1, 'cloneStatus': 0, 'installationProgress': "100", + 'currentStatus': 'Invalid status file.'} json_data = json.dumps(data_ret) return HttpResponse(json_data) - ## save configuration data ends - else: - command = "redis-cli set vhost:%s '%s'" % (self.domain, configData.replace( - '#### This configuration is fetched from redis as Redis-Mass Hosting is being used.\n', '')) - ProcessUtilities.executioner(command) + statusData = ProcessUtilities.outputExecutioner("cat " + statusFile).splitlines() - status = {"configstatus": 1} + lastLine = statusData[-1] - final_json = json.dumps(status) - return HttpResponse(final_json) - - def getRewriteRules(self, userID=None, data=None): - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - self.domain = data['virtualHost'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('rewriteStatus', 0) - - try: - childDom = ChildDomains.objects.get(domain=self.domain) - filePath = childDom.path + '/.htaccess' - externalApp = childDom.master.externalApp - except: - website = Websites.objects.get(domain=self.domain) - externalApp = website.externalApp - filePath = "/home/" + self.domain + "/public_html/.htaccess" - - try: - command = 'cat %s' % (filePath) - rewriteRules = ProcessUtilities.outputExecutioner(command, externalApp) - - if len(rewriteRules) == 0: - status = {"rewriteStatus": 1, "error_message": "Rules file is currently empty"} - final_json = json.dumps(status) - return HttpResponse(final_json) - - status = {"rewriteStatus": 1, "rewriteRules": rewriteRules} - - final_json = json.dumps(status) - return HttpResponse(final_json) + if lastLine.find('[200]') > -1: + command = 'rm -f ' + statusFile + subprocess.call(shlex.split(command)) + data_ret = {'abort': 1, 'cloneStatus': 1, 'installationProgress': "100", + 'currentStatus': 'Successfully Installed.'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + elif lastLine.find('[404]') > -1: + data_ret = {'abort': 1, 'cloneStatus': 0, 'installationProgress': "0", + 'error_message': ProcessUtilities.outputExecutioner("cat " + statusFile).splitlines()} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + progress = lastLine.split(',') + currentStatus = progress[0] + try: + installationProgress = progress[1] + except: + installationProgress = 0 + data_ret = {'abort': 0, 'cloneStatus': 0, 'installationProgress': installationProgress, + 'currentStatus': currentStatus} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) except BaseException as msg: - status = {"rewriteStatus": 1, "error_message": str(msg), "rewriteRules": ""} - final_json = json.dumps(status) - return HttpResponse(final_json) + data_ret = {'abort': 0, 'cloneStatus': 0, 'installationProgress': "0", 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) - def saveRewriteRules(self, userID=None, data=None): + def gitPull(self, userID=None, data=None): try: currentACL = ACLManager.loadedACL(userID) admin = Administrator.objects.get(pk=userID) - self.domain = data['virtualHost'] - rewriteRules = data['rewriteRules'].encode('utf-8') + + self.domain = data['domain'] + repoURL = data['repoURL'] + branch = data['branch'] + repoName = data['repoName'] + tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: pass else: - return ACLManager.loadErrorJson('rewriteStatus', 0) + return ACLManager.loadErrorJson('cloneStatus', 0) - ## writing data temporary to file + background = GitPuller(self.domain, repoURL, branch, repoName, tempStatusPath) + background.start() - mailUtilities.checkHome() - tempPath = "/tmp/" + str(randint(1000, 9999)) - vhost = open(tempPath, "wb") - vhost.write(rewriteRules) - vhost.close() + time.sleep(2) - ## writing data temporary to file + data_ret = {'status': 1, 'cloneStatus': 1, 'error_message': 'None', + 'tempStatusPath': tempStatusPath} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) - try: - childDomain = ChildDomains.objects.get(domain=self.domain) - filePath = childDomain.path + '/.htaccess' - externalApp = childDomain.master.externalApp - except: - filePath = "/home/" + self.domain + "/public_html/.htaccess" - website = Websites.objects.get(domain=self.domain) - externalApp = website.externalApp - - ## save configuration data - - command = 'cp %s %s' % (tempPath, filePath) - ProcessUtilities.executioner(command, externalApp) - - command = 'rm -f %s' % (tempPath) - ProcessUtilities.executioner(command, 'cyberpanel') - - installUtilities.reStartLiteSpeedSocket() - status = {"rewriteStatus": 1, 'error_message': 'None'} - final_json = json.dumps(status) - return HttpResponse(final_json) except BaseException as msg: - status = {"rewriteStatus": 0, 'error_message': str(msg)} - final_json = json.dumps(status) - return HttpResponse(final_json) - - def saveSSL(self, userID=None, data=None): - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - self.domain = data['virtualHost'] - key = data['key'] - cert = data['cert'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('sslStatus', 0) - - mailUtilities.checkHome() - - ## writing data temporary to file - - tempKeyPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - vhost = open(tempKeyPath, "w") - vhost.write(key) - vhost.close() - - tempCertPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - vhost = open(tempCertPath, "w") - vhost.write(cert) - vhost.close() - - ## writing data temporary to file - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " saveSSL --virtualHostName " + self.domain + " --tempKeyPath " + tempKeyPath + " --tempCertPath " + tempCertPath - output = ProcessUtilities.outputExecutioner(execPath) - - if output.find("1,None") > -1: - data_ret = {'sslStatus': 1, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - logging.CyberCPLogFileWriter.writeToFile( - output) - data_ret = {'sslStatus': 0, 'error_message': output} + data_ret = {'status': 0, 'cloneStatus': 0, 'error_message': str(msg)} json_data = json.dumps(data_ret) return HttpResponse(json_data) - def changePHP(self, userID=None, data=None): - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - self.domain = data['childDomain'] - phpVersion = data['phpSelection'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('changePHP', 0) - - confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + self.domain - completePathToConfigFile = confPath + "/vhost.conf" - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " changePHP --phpVersion '" + phpVersion + "' --path " + completePathToConfigFile - ProcessUtilities.popenExecutioner(execPath) - + def gitPullStatus(self, userID=None, data=None): try: - website = Websites.objects.get(domain=self.domain) - website.phpSelection = data['phpSelection'] - website.save() + statusFile = data['statusFile'] - ### check if there are any alias domains under the main website and then change php for them too + if ACLManager.CheckStatusFilleLoc(statusFile): + pass + else: + data_ret = {'abort': 1, 'cloneStatus': 0, 'installationProgress': "100", + 'currentStatus': 'Invalid status file.'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) - for alias in website.childdomains_set.filter(alais=1): + statusData = ProcessUtilities.outputExecutioner("cat " + statusFile).splitlines() + lastLine = statusData[-1] + + if lastLine.find('[200]') > -1: + command = 'rm -f ' + statusFile + subprocess.call(shlex.split(command)) + data_ret = {'abort': 1, 'cloneStatus': 1, 'installationProgress': "100", + 'currentStatus': 'Successfully Installed.'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + elif lastLine.find('[404]') > -1: + data_ret = {'abort': 1, 'cloneStatus': 0, 'installationProgress': "0", + 'error_message': ProcessUtilities.outputExecutioner("cat " + statusFile).splitlines()} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + progress = lastLine.split(',') + currentStatus = progress[0] try: + installationProgress = progress[1] + except: + installationProgress = 0 + data_ret = {'abort': 0, 'cloneStatus': 0, 'installationProgress': installationProgress, + 'currentStatus': currentStatus} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) - confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + alias.domain - completePathToConfigFile = confPath + "/vhost.conf" - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " changePHP --phpVersion '" + phpVersion + "' --path " + completePathToConfigFile - ProcessUtilities.popenExecutioner(execPath) - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile(f'Error changing PHP for alias: {str(msg)}') + except BaseException as msg: + data_ret = {'abort': 0, 'cloneStatus': 0, 'installationProgress': "0", 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + def getSSHConfigs(self, userID=None, data=None): + try: - except: - website = ChildDomains.objects.get(domain=self.domain) - website.phpSelection = data['phpSelection'] - website.save() + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) - data_ret = {'status': 1, 'changePHP': 1, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) + self.domain = data['domain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('getSSHConfigs', 0) + + website = Websites.objects.get(domain=self.domain) + + path = "/home/" + self.domain + "/.ssh/config" + + if os.path.exists(path): + f = open(path, 'r') + configData = f.read() + f.close() + else: + configData = "" + + data_ret = {'getSSHConfigs': 1, 'error_message': "None", "configData": configData} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'getSSHConfigs': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def saveSSHConfigs(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + configData = data['configData'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('saveSSHConfigs', 0) + + website = Websites.objects.get(domain=self.domain) + + path = "/home/" + self.domain + "/.ssh/config" + + writeToFile = open(path, 'w') + writeToFile.write(configData) + writeToFile.close() + + command = "chown %s:%s %s" % (website.externalApp, website.externalApp, path) + ProcessUtilities.executioner(command) + + command = "chmod 600 %s" % (path) + ProcessUtilities.executioner(command) + + data_ret = {'saveSSHConfigs': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'saveSSHConfigs': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def fetchWPSitesForDomain(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + domain = data['domain'] + website = Websites.objects.get(domain=domain) + + if ACLManager.checkOwnership(domain, admin, currentACL) != 1: + return ACLManager.loadErrorJson('fetchStatus', 0) + + wp_sites = WPSites.objects.filter(owner=website) + sites = [] + + for site in wp_sites: + sites.append({ + 'id': site.id, + 'title': site.title, + 'url': site.FinalURL, + 'path': site.path, + 'version': site.version, + 'status': site.status + }) + + data_ret = {'status': 1, 'fetchStatus': 1, 'error_message': "None", "sites": sites} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'fetchStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + +class WebsiteManager: + apache = 1 + ols = 2 + lsws = 3 + + def __init__(self, data=None): + self.domain = data['domain'] + self.adminEmail = data['adminEmail'] + + if 'phpVersion' in data.keys(): + self.phpVersion = data['phpVersion'] + else: + self.phpVersion = None + + if 'package' in data.keys(): + self.package = data['package'] + else: + self.package = None + + if 'websiteOwner' in data.keys(): + self.websiteOwner = data['websiteOwner'] + else: + self.websiteOwner = None + + if 'externalApp' in data.keys(): + self.externalApp = data['externalApp'] + else: + self.externalApp = None + + if 'ssl' in data.keys(): + self.ssl = data['ssl'] + else: + self.ssl = None + + if 'dkimCheck' in data.keys(): + self.dkimCheck = data['dkimCheck'] + else: + self.dkimCheck = None + + if 'openBasedir' in data.keys(): + self.openBasedir = data['openBasedir'] + else: + self.openBasedir = None + + if 'sslForced' in data.keys(): + self.sslForced = data['sslForced'] + else: + self.sslForced = None + + if 'http2' in data.keys(): + self.http2 = data['http2'] + else: + self.http2 = None + + if 'waf' in data.keys(): + self.waf = data['waf'] + else: + self.waf = None + + if 'wafRules' in data.keys(): + self.wafRules = data['wafRules'] + else: + self.wafRules = None + + if 'wafMode' in data.keys(): + self.wafMode = data['wafMode'] + else: + self.wafMode = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): + self.wafExclusions = data['wafExclusions'] + else: + self.wafExclusions = None + + if 'wafExclusions' in data.keys(): +Require valid-user""" + with open(htaccess, 'w') as f: + f.write(htaccess_content) + + def submitWebsiteModify(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + domain = data['domain'] + website = Websites.objects.get(domain=domain) + + if ACLManager.checkOwnership(domain, admin, currentACL) != 1: + return ACLManager.loadErrorJson('fetchStatus', 0) + + wp_sites = WPSites.objects.filter(owner=website) + sites = [] + + for site in wp_sites: + sites.append({ + 'id': site.id, + 'title': site.title, + 'url': site.FinalURL, + 'path': site.path, + 'version': site.version, + 'status': site.status + }) + + data_ret = {'status': 1, 'fetchStatus': 1, 'error_message': "None", "sites": sites} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'fetchStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) def getWebsiteCron(self, userID=None, data=None): try: From cbb949ab746070dc7b56f82317c1799e60ddf1a7 Mon Sep 17 00:00:00 2001 From: usmannasir Date: Fri, 4 Apr 2025 15:21:13 +0500 Subject: [PATCH 006/273] fix submitWebsiteModify --- websiteFunctions/website.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/websiteFunctions/website.py b/websiteFunctions/website.py index 84344d3c2..b69fe3d65 100755 --- a/websiteFunctions/website.py +++ b/websiteFunctions/website.py @@ -4033,6 +4033,10 @@ Require valid-user""" if os.path.exists(htaccess): os.remove(htaccess) return JsonResponse({'status': 1, 'error_message': 'None'}) + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) def submitWebsiteModify(self, userID=None, data=None): try: From bf30efa638190cb5a47a58b094ee7553a66e2897 Mon Sep 17 00:00:00 2001 From: usmannasir Date: Fri, 4 Apr 2025 17:27:24 +0500 Subject: [PATCH 007/273] fix fetchWPSitesForDomain --- websiteFunctions/website.py | 10489 +++------------------------------- 1 file changed, 763 insertions(+), 9726 deletions(-) diff --git a/websiteFunctions/website.py b/websiteFunctions/website.py index b69fe3d65..d11601526 100755 --- a/websiteFunctions/website.py +++ b/websiteFunctions/website.py @@ -178,39 +178,6 @@ class WebsiteManager: proc = httpProc(request, 'websiteFunctions/WPsitesList.html', context) return proc.render() - def fetchWPSitesForDomain(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - domain = data['domain'] - website = Websites.objects.get(domain=domain) - - if ACLManager.checkOwnership(domain, admin, currentACL) != 1: - return ACLManager.loadErrorJson('fetchStatus', 0) - - wp_sites = WPSites.objects.filter(owner=website) - sites = [] - - for site in wp_sites: - sites.append({ - 'id': site.id, - 'title': site.title, - 'url': site.FinalURL, - 'path': site.path, - 'version': site.version, - 'status': site.status - }) - - data_ret = {'status': 1, 'fetchStatus': 1, 'error_message': "None", "sites": sites} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'fetchStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - def WPHome(self, request=None, userID=None, WPid=None, DeleteID=None): Data = {} currentACL = ACLManager.loadedACL(userID) @@ -2020,2007 +1987,6 @@ class WebsiteManager: htaccess_content = f"""AuthType Basic AuthName "Restricted Access" AuthUserFile {htpasswd} -Require valid-user -""" - with open(htaccess, 'w') as f: - f.write(htaccess_content) - else: - # Disable password protection - if os.path.exists(path): - shutil.rmtree(path) - htaccess = f'{wpsite.path}/.htaccess' - if os.path.exists(htaccess): - os.remove(htaccess) - - # Execute the command - ProcessUtilities.executioner(command) - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - -class WebsiteManager: - apache = 1 - ols = 2 - lsws = 3 - - def __init__(self, domain=None, childDomain=None): - self.domain = domain - self.childDomain = childDomain - - def createWebsite(self, request=None, userID=None, data=None): - - url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" - data = { - "name": "all", - "IP": ACLManager.GetServerIP() - } - - import requests - response = requests.post(url, data=json.dumps(data)) - Status = response.json()['status'] - - test_domain_status = 0 - - if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: - test_domain_status = 1 - - currentACL = ACLManager.loadedACL(userID) - adminNames = ACLManager.loadAllUsers(userID) - packagesName = ACLManager.loadPackages(userID, currentACL) - phps = PHPManager.findPHPVersions() - - rnpss = randomPassword.generate_pass(10) - - Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps, 'Randam_String': rnpss.lower(), - 'test_domain_data': test_domain_status} - proc = httpProc(request, 'websiteFunctions/createWebsite.html', - Data, 'createWebsite') - return proc.render() - - def WPCreate(self, request=None, userID=None, data=None): - url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" - data = { - "name": "wp-manager", - "IP": ACLManager.GetServerIP() - } - - import requests - response = requests.post(url, data=json.dumps(data)) - Status = response.json()['status'] - - - if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: - currentACL = ACLManager.loadedACL(userID) - adminNames = ACLManager.loadAllUsers(userID) - packagesName = ACLManager.loadPackages(userID, currentACL) - - if len(packagesName) == 0: - packagesName = ['Default'] - - FinalVersions = [] - userobj = Administrator.objects.get(pk=userID) - counter = 0 - try: - import requests - WPVersions = json.loads(requests.get('https://api.wordpress.org/core/version-check/1.7/').text)[ - 'offers'] - - for versions in WPVersions: - if counter == 7: - break - if versions['current'] not in FinalVersions: - FinalVersions.append(versions['current']) - counter = counter + 1 - except: - FinalVersions = ['5.6', '5.5.3', '5.5.2'] - - Plugins = wpplugins.objects.filter(owner=userobj) - rnpss = randomPassword.generate_pass(10) - - ## - - test_domain_status = 1 - - Data = {'packageList': packagesName, "owernList": adminNames, 'WPVersions': FinalVersions, - 'Plugins': Plugins, 'Randam_String': rnpss.lower(), 'test_domain_data': test_domain_status} - proc = httpProc(request, 'websiteFunctions/WPCreate.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def ListWPSites(self, request=None, userID=None, DeleteID=None): - import json - currentACL = ACLManager.loadedACL(userID) - - admin = Administrator.objects.get(pk=userID) - data = {} - wp_sites = ACLManager.GetALLWPObjects(currentACL, userID) - data['wp'] = wp_sites - - try: - if DeleteID != None: - WPDelete = WPSites.objects.get(pk=DeleteID) - - if ACLManager.checkOwnership(WPDelete.owner.domain, admin, currentACL) == 1: - WPDelete.delete() - except BaseException as msg: - pass - - sites = [] - for site in data['wp']: - sites.append({ - 'id': site.id, - 'title': site.title, - 'url': site.FinalURL, - 'production_status': True - }) - - context = { - "wpsite": json.dumps(sites), - "status": 1, - "total_sites": len(sites), - "debug_info": json.dumps({ - "user_id": userID, - "is_admin": bool(currentACL.get('admin', 0)), - "wp_sites_count": wp_sites.count() - }) - } - - proc = httpProc(request, 'websiteFunctions/WPsitesList.html', context) - return proc.render() - - def fetchWPSitesForDomain(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - domain = data['domain'] - website = Websites.objects.get(domain=domain) - - if ACLManager.checkOwnership(domain, admin, currentACL) != 1: - return ACLManager.loadErrorJson('fetchStatus', 0) - - wp_sites = WPSites.objects.filter(owner=website) - sites = [] - - for site in wp_sites: - sites.append({ - 'id': site.id, - 'title': site.title, - 'url': site.FinalURL, - 'path': site.path, - 'version': site.version, - 'status': site.status - }) - - data_ret = {'status': 1, 'fetchStatus': 1, 'error_message': "None", "sites": sites} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'fetchStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def WPHome(self, request=None, userID=None, WPid=None, DeleteID=None): - Data = {} - currentACL = ACLManager.loadedACL(userID) - WPobj = WPSites.objects.get(pk=WPid) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(WPobj.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - try: - - url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" - data = { - "name": "wp-manager", - "IP": ACLManager.GetServerIP() - } - - import requests - response = requests.post(url, data=json.dumps(data)) - Status = response.json()['status'] - - rnpss = randomPassword.generate_pass(10) - - Data['Randam_String'] = rnpss.lower() - - if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: - Data['wpsite'] = WPobj - Data['test_domain_data'] = 1 - - try: - DeleteID = request.GET.get('DeleteID', None) - - if DeleteID != None: - wstagingDelete = WPStaging.objects.get(pk=DeleteID, owner=WPobj) - wstagingDelete.delete() - - except BaseException as msg: - da = str(msg) - - proc = httpProc(request, 'websiteFunctions/WPsiteHome.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - except: - proc = httpProc(request, 'websiteFunctions/WPsiteHome.html', - Data, 'createDatabase') - return proc.render() - - def RestoreHome(self, request=None, userID=None, BackupID=None): - Data = {} - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.CheckForPremFeature('wp-manager'): - - Data['backupobj'] = WPSitesBackup.objects.get(pk=BackupID) - - if ACLManager.CheckIPBackupObjectOwner(currentACL, Data['backupobj'], admin) == 1: - pass - else: - return ACLManager.loadError() - - config = json.loads(Data['backupobj'].config) - Data['FileName'] = config['name'] - try: - Data['Backuptype'] = config['Backuptype'] - - if Data['Backuptype'] == 'DataBase Backup' or Data['Backuptype'] == 'Website Backup': - Data['WPsites'] = [WPSites.objects.get(pk=Data['backupobj'].WPSiteID)] - else: - Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) - - except: - Data['Backuptype'] = None - Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) - - proc = httpProc(request, 'websiteFunctions/WPRestoreHome.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def RemoteBackupConfig(self, request=None, userID=None, DeleteID=None): - Data = {} - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - try: - if DeleteID != None: - BackupconfigDelete = RemoteBackupConfig.objects.get(pk=DeleteID) - BackupconfigDelete.delete() - except: - pass - - if ACLManager.CheckForPremFeature('wp-manager'): - - Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) - allcon = RemoteBackupConfig.objects.all() - Data['backupconfigs'] = [] - for i in allcon: - configr = json.loads(i.config) - if i.configtype == "SFTP": - Data['backupconfigs'].append({ - 'id': i.pk, - 'Type': i.configtype, - 'HostName': configr['Hostname'], - 'Path': configr['Path'] - }) - elif i.configtype == "S3": - Provider = configr['Provider'] - if Provider == "Backblaze": - Data['backupconfigs'].append({ - 'id': i.pk, - 'Type': i.configtype, - 'HostName': Provider, - 'Path': configr['S3keyname'] - }) - else: - Data['backupconfigs'].append({ - 'id': i.pk, - 'Type': i.configtype, - 'HostName': Provider, - 'Path': configr['S3keyname'] - }) - - proc = httpProc(request, 'websiteFunctions/RemoteBackupConfig.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def BackupfileConfig(self, request=None, userID=None, RemoteConfigID=None, DeleteID=None): - Data = {} - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - Data['RemoteConfigID'] = RemoteConfigID - RemoteConfigobj = RemoteBackupConfig.objects.get(pk=RemoteConfigID) - try: - if DeleteID != None: - RemoteBackupConfigDelete = RemoteBackupSchedule.objects.get(pk=DeleteID) - RemoteBackupConfigDelete.delete() - except: - pass - - if ACLManager.CheckForPremFeature('wp-manager'): - Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) - allsechedule = RemoteBackupSchedule.objects.filter(RemoteBackupConfig=RemoteConfigobj) - Data['Backupschedule'] = [] - for i in allsechedule: - lastrun = i.lastrun - LastRun = time.strftime('%Y-%m-%d', time.localtime(float(lastrun))) - Data['Backupschedule'].append({ - 'id': i.pk, - 'Name': i.Name, - 'RemoteConfiguration': i.RemoteBackupConfig.configtype, - 'Retention': i.fileretention, - 'Frequency': i.timeintervel, - 'LastRun': LastRun - }) - proc = httpProc(request, 'websiteFunctions/BackupfileConfig.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def AddRemoteBackupsite(self, request=None, userID=None, RemoteScheduleID=None, DeleteSiteID=None): - Data = {} - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - Data['RemoteScheduleID'] = RemoteScheduleID - RemoteBackupScheduleobj = RemoteBackupSchedule.objects.get(pk=RemoteScheduleID) - - try: - if DeleteSiteID != None: - RemoteBackupsitesDelete = RemoteBackupsites.objects.get(pk=DeleteSiteID) - RemoteBackupsitesDelete.delete() - except: - pass - - if ACLManager.CheckForPremFeature('wp-manager'): - Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) - allRemoteBackupsites = RemoteBackupsites.objects.filter(owner=RemoteBackupScheduleobj) - Data['RemoteBackupsites'] = [] - for i in allRemoteBackupsites: - try: - wpsite = WPSites.objects.get(pk=i.WPsites) - Data['RemoteBackupsites'].append({ - 'id': i.pk, - 'Title': wpsite.title, - }) - except: - pass - proc = httpProc(request, 'websiteFunctions/AddRemoteBackupSite.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def WordpressPricing(self, request=None, userID=None, ): - Data = {} - proc = httpProc(request, 'websiteFunctions/CyberpanelPricing.html', Data, 'createWebsite') - return proc.render() - - def RestoreBackups(self, request=None, userID=None, DeleteID=None): - Data = {} - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" - data = { - "name": "wp-manager", - "IP": ACLManager.GetServerIP() - } - - import requests - response = requests.post(url, data=json.dumps(data)) - Status = response.json()['status'] - - if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: - - backobj = WPSitesBackup.objects.filter(owner=admin).order_by('-id') - - # if ACLManager.CheckIPBackupObjectOwner(currentACL, backobj, admin) == 1: - # pass - # else: - # return ACLManager.loadError() - - try: - if DeleteID != None: - DeleteIDobj = WPSitesBackup.objects.get(pk=DeleteID) - - if ACLManager.CheckIPBackupObjectOwner(currentACL, DeleteIDobj, admin) == 1: - config = DeleteIDobj.config - conf = json.loads(config) - FileName = conf['name'] - command = "rm -r /home/backup/%s.tar.gz" % FileName - ProcessUtilities.executioner(command) - DeleteIDobj.delete() - - except BaseException as msg: - pass - Data['job'] = [] - - for sub in backobj: - try: - wpsite = WPSites.objects.get(pk=sub.WPSiteID) - web = wpsite.title - except: - web = "Website Not Found" - - try: - config = sub.config - conf = json.loads(config) - Backuptype = conf['Backuptype'] - BackupDestination = conf['BackupDestination'] - except: - Backuptype = "Backup type not exists" - - Data['job'].append({ - 'id': sub.id, - 'title': web, - 'Backuptype': Backuptype, - 'BackupDestination': BackupDestination - }) - - proc = httpProc(request, 'websiteFunctions/RestoreBackups.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def AutoLogin(self, request=None, userID=None): - - WPid = request.GET.get('id') - currentACL = ACLManager.loadedACL(userID) - WPobj = WPSites.objects.get(pk=WPid) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(WPobj.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - from managePHP.phpManager import PHPManager - - php = PHPManager.getPHPString(WPobj.owner.phpSelection) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" - data = { - "name": "wp-manager", - "IP": ACLManager.GetServerIP() - } - - import requests - response = requests.post(url, data=json.dumps(data)) - Status = response.json()['status'] - - if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: - - ## Get title - - password = randomPassword.generate_pass(10) - - command = f'sudo -u %s {FinalPHPPath} /usr/bin/wp user create autologin %s --role=administrator --user_pass="%s" --path=%s --skip-plugins --skip-themes' % ( - WPobj.owner.externalApp, 'autologin@cloudpages.cloud', password, WPobj.path) - ProcessUtilities.executioner(command) - - command = f'sudo -u %s {FinalPHPPath} /usr/bin/wp user update autologin --user_pass="%s" --path=%s --skip-plugins --skip-themes' % ( - WPobj.owner.externalApp, password, WPobj.path) - ProcessUtilities.executioner(command) - - data = {} - - if WPobj.FinalURL.endswith('/'): - FinalURL = WPobj.FinalURL[:-1] - else: - FinalURL = WPobj.FinalURL - - data['url'] = 'https://%s' % (FinalURL) - data['userName'] = 'autologin' - data['password'] = password - - proc = httpProc(request, 'websiteFunctions/AutoLogin.html', - data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def ConfigurePlugins(self, request=None, userID=None, data=None): - - if ACLManager.CheckForPremFeature('wp-manager'): - currentACL = ACLManager.loadedACL(userID) - userobj = Administrator.objects.get(pk=userID) - - Selectedplugins = wpplugins.objects.filter(owner=userobj) - # data['Selectedplugins'] = wpplugins.objects.filter(ProjectOwner=HostingCompany) - - Data = {'Selectedplugins': Selectedplugins, } - proc = httpProc(request, 'websiteFunctions/WPConfigurePlugins.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def Addnewplugin(self, request=None, userID=None, data=None): - from django.shortcuts import reverse - if ACLManager.CheckForPremFeature('wp-manager'): - currentACL = ACLManager.loadedACL(userID) - adminNames = ACLManager.loadAllUsers(userID) - packagesName = ACLManager.loadPackages(userID, currentACL) - phps = PHPManager.findPHPVersions() - - Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps} - proc = httpProc(request, 'websiteFunctions/WPAddNewPlugin.html', - Data, 'createDatabase') - return proc.render() - - return redirect(reverse('pricing')) - - def SearchOnkeyupPlugin(self, userID=None, data=None): - try: - if ACLManager.CheckForPremFeature('wp-manager'): - currentACL = ACLManager.loadedACL(userID) - - pluginname = data['pluginname'] - # logging.CyberCPLogFileWriter.writeToFile("Plugin Name ....... %s"%pluginname) - - url = "http://api.wordpress.org/plugins/info/1.1/?action=query_plugins&request[search]=%s" % str( - pluginname) - import requests - - res = requests.get(url) - r = res.json() - - # return proc.ajax(1, 'Done', {'plugins': r}) - - data_ret = {'status': 1, 'plugns': r, } - - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': 'Premium feature not available.'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def AddNewpluginAjax(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - - userobj = Administrator.objects.get(pk=userID) - - config = data['config'] - Name = data['Name'] - # pluginname = data['pluginname'] - # logging.CyberCPLogFileWriter.writeToFile("config ....... %s"%config) - # logging.CyberCPLogFileWriter.writeToFile(" Name ....... %s"%Name) - - addpl = wpplugins(Name=Name, config=json.dumps(config), owner=userobj) - addpl.save() - - data_ret = {'status': 1} - - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'AddNewpluginAjax': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def EidtPlugin(self, request=None, userID=None, pluginbID=None): - Data = {} - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - pluginobj = wpplugins.objects.get(pk=pluginbID) - - if ACLManager.CheckIPPluginObjectOwner(currentACL, pluginobj, admin) == 1: - pass - else: - return ACLManager.loadError() - - lmo = json.loads(pluginobj.config) - Data['Selectedplugins'] = lmo - Data['pluginbID'] = pluginbID - Data['BucketName'] = pluginobj.Name - - proc = httpProc(request, 'websiteFunctions/WPEidtPlugin.html', - Data, 'createDatabase') - return proc.render() - - def deletesPlgin(self, userID=None, data=None, ): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - userobj = Administrator.objects.get(pk=userID) - pluginname = data['pluginname'] - pluginbBucketID = data['pluginbBucketID'] - # logging.CyberCPLogFileWriter.writeToFile("pluginbID ....... %s" % pluginbBucketID) - # logging.CyberCPLogFileWriter.writeToFile("pluginname ....... %s" % pluginname) - - obj = wpplugins.objects.get(pk=pluginbBucketID, owner=userobj) - - if ACLManager.CheckIPPluginObjectOwner(currentACL, obj, admin) == 1: - pass - else: - return ACLManager.loadError() - - ab = [] - ab = json.loads(obj.config) - ab.remove(pluginname) - obj.config = json.dumps(ab) - obj.save() - - data_ret = {'status': 1} - - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except BaseException as msg: - data_ret = {'status': 0, 'deletesPlgin': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def Addplugineidt(self, userID=None, data=None, ): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - userobj = Administrator.objects.get(pk=userID) - pluginname = data['pluginname'] - pluginbBucketID = data['pluginbBucketID'] - - # logging.CyberCPLogFileWriter.writeToFile("pluginbID ....... %s" % pluginbBucketID) - # logging.CyberCPLogFileWriter.writeToFile("pluginname ....... %s" % pluginname) - - pObj = wpplugins.objects.get(pk=pluginbBucketID, owner=userobj) - - if ACLManager.CheckIPPluginObjectOwner(currentACL, pObj, admin) == 1: - pass - else: - return ACLManager.loadError() - - listofplugin = json.loads(pObj.config) - try: - index = listofplugin.index(pluginname) - print('index.....%s' % index) - if (index >= 0): - data_ret = {'status': 0, 'deletesPlgin': 0, 'error_message': str('Already Save in your Plugin lis')} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except: - ab = [] - ab = json.loads(pObj.config) - ab.append(pluginname) - pObj.config = json.dumps(ab) - pObj.save() - - data_ret = {'status': 1} - - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except BaseException as msg: - data_ret = {'status': 0, 'deletesPlgin': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def modifyWebsite(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - - websitesName = ACLManager.findAllSites(currentACL, userID) - phps = PHPManager.findPHPVersions() - proc = httpProc(request, 'websiteFunctions/modifyWebsite.html', - {'websiteList': websitesName, 'phps': phps}, 'modifyWebsite') - return proc.render() - - def deleteWebsite(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - websitesName = ACLManager.findAllSites(currentACL, userID) - proc = httpProc(request, 'websiteFunctions/deleteWebsite.html', - {'websiteList': websitesName}, 'deleteWebsite') - return proc.render() - - def CreateNewDomain(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - websitesName = ACLManager.findAllSites(currentACL, userID) - - try: - admin = Administrator.objects.get(pk=userID) - if admin.defaultSite == 0: - websites = ACLManager.findWebsiteObjects(currentACL, userID) - admin.defaultSite = websites[0].id - admin.save() - except: - pass - - try: - admin = Administrator.objects.get(pk=userID) - defaultDomain = Websites.objects.get(pk=admin.defaultSite).domain - except: - try: - admin = Administrator.objects.get(pk=userID) - websites = ACLManager.findWebsiteObjects(currentACL, userID) - admin.defaultSite = websites[0].id - admin.save() - defaultDomain = websites[0].domain - except: - defaultDomain='NONE' - - - url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" - data = { - "name": "all", - "IP": ACLManager.GetServerIP() - } - - import requests - response = requests.post(url, data=json.dumps(data)) - Status = response.json()['status'] - - test_domain_status = 0 - - if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: - test_domain_status = 1 - - rnpss = randomPassword.generate_pass(10) - proc = httpProc(request, 'websiteFunctions/createDomain.html', - {'websiteList': websitesName, 'phps': PHPManager.findPHPVersions(), 'Randam_String': rnpss, - 'test_domain_data': test_domain_status, 'defaultSite': defaultDomain}) - return proc.render() - - def siteState(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - - websitesName = ACLManager.findAllSites(currentACL, userID) - - proc = httpProc(request, 'websiteFunctions/suspendWebsite.html', - {'websiteList': websitesName}, 'suspendWebsite') - return proc.render() - - def listWebsites(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - pagination = self.websitePagination(currentACL, userID) - proc = httpProc(request, 'websiteFunctions/listWebsites.html', - {"pagination": pagination}) - return proc.render() - - def listChildDomains(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - adminNames = ACLManager.loadAllUsers(userID) - packagesName = ACLManager.loadPackages(userID, currentACL) - phps = PHPManager.findPHPVersions() - - Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps} - proc = httpProc(request, 'websiteFunctions/listChildDomains.html', - Data) - return proc.render() - - def listCron(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(request.GET.get('domain'), admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - proc = httpProc(request, 'websiteFunctions/listCron.html', - {'domain': request.GET.get('domain')}) - return proc.render() - - def domainAlias(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - aliasManager = AliasManager(self.domain) - noAlias, finalAlisList = aliasManager.fetchAlisForDomains() - - path = "/home/" + self.domain + "/public_html" - - proc = httpProc(request, 'websiteFunctions/domainAlias.html', { - 'masterDomain': self.domain, - 'aliases': finalAlisList, - 'path': path, - 'noAlias': noAlias - }) - return proc.render() - - def FetchWPdata(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core version --skip-plugins --skip-themes --path=%s 2>/dev/null' % ( - Vhuser, FinalPHPPath, path) - version = ProcessUtilities.outputExecutioner(command, None, True) - version = html.escape(version) - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin status litespeed-cache --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, path) - lscachee = ProcessUtilities.outputExecutioner(command) - - if lscachee.find('Status: Active') > -1: - lscache = 1 - else: - lscache = 0 - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp config list --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, path) - stdout = ProcessUtilities.outputExecutioner(command) - debugging = 0 - for items in stdout.split('\n'): - if items.find('WP_DEBUG true constant') > -1: - debugging = 1 - break - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp option get blog_public --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, path) - stdoutput = ProcessUtilities.outputExecutioner(command) - searchindex = int(stdoutput.splitlines()[-1]) - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp maintenance-mode status --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, path) - maintenanceMod = ProcessUtilities.outputExecutioner(command) - - result = maintenanceMod.splitlines()[-1] - if result.find('not active') > -1: - maintenanceMode = 0 - else: - maintenanceMode = 1 - - ##### Check passwd protection - vhostName = wpsite.owner.domain - vhostPassDir = f'/home/{vhostName}' - path = f'{vhostPassDir}/{WPManagerID}' - if os.path.exists(path): - passwd = 1 - else: - passwd = 0 - - #### Check WP cron - command = "sudo -u %s cat %s/wp-config.php" % (Vhuser, wpsite.path) - stdout = ProcessUtilities.outputExecutioner(command) - if stdout.find("'DISABLE_WP_CRON', 'true'") > -1: - wpcron = 1 - else: - wpcron = 0 - - fb = { - 'version': version.rstrip('\n'), - 'lscache': lscache, - 'debugging': debugging, - 'searchIndex': searchindex, - 'maintenanceMode': maintenanceMode, - 'passwordprotection': passwd, - 'wpcron': wpcron - - } - - data_ret = {'status': 1, 'error_message': 'None', 'ret_data': fb} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def GetCurrentPlugins(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin list --skip-plugins --skip-themes --format=json --path=%s' % ( - Vhuser, FinalPHPPath, path) - stdoutput = ProcessUtilities.outputExecutioner(command) - json_data = stdoutput.splitlines()[-1] - - data_ret = {'status': 1, 'error_message': 'None', 'plugins': json_data} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def GetCurrentThemes(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp theme list --skip-plugins --skip-themes --format=json --path=%s' % ( - Vhuser, FinalPHPPath, path) - stdoutput = ProcessUtilities.outputExecutioner(command) - json_data = stdoutput.splitlines()[-1] - - data_ret = {'status': 1, 'error_message': 'None', 'themes': json_data} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def fetchstaging(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - from plogical.phpUtilities import phpUtilities - - json_data = phpUtilities.GetStagingInJson(wpsite.wpstaging_set.all().order_by('-id')) - - data_ret = {'status': 1, 'error_message': 'None', 'wpsites': json_data} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def fetchDatabase(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - php = PHPManager.getPHPString(wpsite.owner.phpSelection) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - command = f'{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config get DB_NAME --skip-plugins --skip-themes --path={wpsite.path} 2>/dev/null' - retStatus, stdoutput = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp, True, None, 1) - - if stdoutput.find('Error:') == -1: - DataBaseName = stdoutput.rstrip("\n") - DataBaseName = html.escape(DataBaseName) - else: - data_ret = {'status': 0, 'error_message': stdoutput} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - command = f'{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config get DB_USER --skip-plugins --skip-themes --path={wpsite.path} 2>/dev/null' - retStatus, stdoutput = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp, True, None, 1) - - if stdoutput.find('Error:') == -1: - DataBaseUser = stdoutput.rstrip("\n") - DataBaseUser = html.escape(DataBaseUser) - else: - data_ret = {'status': 0, 'error_message': stdoutput} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - command = f'{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config get table_prefix --skip-plugins --skip-themes --path={wpsite.path} 2>/dev/null' - retStatus, stdoutput = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp, True, None, 1) - - if stdoutput.find('Error:') == -1: - tableprefix = stdoutput.rstrip("\n") - tableprefix = html.escape(tableprefix) - else: - data_ret = {'status': 0, 'error_message': stdoutput} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - data_ret = {'status': 1, 'error_message': 'None', "DataBaseUser": DataBaseUser, - "DataBaseName": DataBaseName, 'tableprefix': tableprefix} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def SaveUpdateConfig(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - Plugins = data['Plugins'] - Themes = data['Themes'] - AutomaticUpdates = data['AutomaticUpdates'] - - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - - php = PHPManager.getPHPString(wpsite.owner.phpSelection) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - if AutomaticUpdates == 'Disabled': - command = f"{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_AUTO_UPDATE_CORE false --raw --allow-root --path=" + wpsite.path - result = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp) - - if result.find('Success:') == -1: - raise BaseException(result) - elif AutomaticUpdates == 'Minor and Security Updates': - command = f"{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_AUTO_UPDATE_CORE minor --allow-root --path=" + wpsite.path - result = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp) - - if result.find('Success:') == -1: - raise BaseException(result) - else: - command = f"{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_AUTO_UPDATE_CORE true --raw --allow-root --path=" + wpsite.path - result = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp) - - if result.find('Success:') == -1: - raise BaseException(result) - - wpsite.AutoUpdates = AutomaticUpdates - wpsite.PluginUpdates = Plugins - wpsite.ThemeUpdates = Themes - wpsite.save() - - data_ret = {'status': 1, 'error_message': 'None', } - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def DeploytoProduction(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - statgingID = data['StagingID'] - wpsite = WPSites.objects.get(pk=WPManagerID) - StagingObj = WPSites.objects.get(pk=statgingID) - - ### - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - if ACLManager.checkOwnership(StagingObj.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - ### - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['statgingID'] = statgingID - extraArgs['WPid'] = WPManagerID - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - background = ApplicationInstaller('DeploytoProduction', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def WPCreateBackup(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - Backuptype = data['Backuptype'] - - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['WPid'] = WPManagerID - extraArgs['Backuptype'] = Backuptype - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - background = ApplicationInstaller('WPCreateBackup', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def RestoreWPbackupNow(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - backupid = data['backupid'] - DesSiteID = data['DesSite'] - - # try: - # - # bwp = WPSites.objects.get(pk=int(backupid)) - # - # if ACLManager.checkOwnership(bwp.owner.domain, admin, currentACL) == 1: - # pass - # else: - # return ACLManager.loadError() - # - # except: - # pass - # - # dwp = WPSites.objects.get(pk=int(DesSiteID)) - # if ACLManager.checkOwnership(dwp.owner.domain, admin, currentACL) == 1: - # pass - # else: - # return ACLManager.loadError() - - Domain = data['Domain'] - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['backupid'] = backupid - extraArgs['DesSiteID'] = DesSiteID - extraArgs['Domain'] = Domain - extraArgs['path'] = data['path'] - extraArgs['home'] = data['home'] - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - background = ApplicationInstaller('RestoreWPbackupNow', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def SaveBackupConfig(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - ConfigType = data['type'] - if ConfigType == 'SFTP': - Hname = data['Hname'] - Uname = data['Uname'] - Passwd = data['Passwd'] - path = data['path'] - config = { - "Hostname": Hname, - "Username": Uname, - "Password": Passwd, - "Path": path - } - elif ConfigType == "S3": - Provider = data['Provider'] - if Provider == "Backblaze": - S3keyname = data['S3keyname'] - SecertKey = data['SecertKey'] - AccessKey = data['AccessKey'] - EndUrl = data['EndUrl'] - config = { - "Provider": Provider, - "S3keyname": S3keyname, - "SecertKey": SecertKey, - "AccessKey": AccessKey, - "EndUrl": EndUrl - - } - else: - S3keyname = data['S3keyname'] - SecertKey = data['SecertKey'] - AccessKey = data['AccessKey'] - config = { - "Provider": Provider, - "S3keyname": S3keyname, - "SecertKey": SecertKey, - "AccessKey": AccessKey, - - } - - mkobj = RemoteBackupConfig(owner=admin, configtype=ConfigType, config=json.dumps(config)) - mkobj.save() - - time.sleep(1) - - data_ret = {'status': 1, 'error_message': 'None', } - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def SaveBackupSchedule(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - FileRetention = data['FileRetention'] - Backfrequency = data['Backfrequency'] - ScheduleName = data['ScheduleName'] - RemoteConfigID = data['RemoteConfigID'] - BackupType = data['BackupType'] - - RemoteBackupConfigobj = RemoteBackupConfig.objects.get(pk=RemoteConfigID) - Rconfig = json.loads(RemoteBackupConfigobj.config) - - try: - # This code is only supposed to run if backups are s3, not for SFTP - provider = Rconfig['Provider'] - if provider == "Backblaze": - EndURl = Rconfig['EndUrl'] - elif provider == "Amazon": - EndURl = "https://s3.us-east-1.amazonaws.com" - elif provider == "Wasabi": - EndURl = "https://s3.wasabisys.com" - - AccessKey = Rconfig['AccessKey'] - SecertKey = Rconfig['SecertKey'] - - session = boto3.session.Session() - - client = session.client( - 's3', - endpoint_url=EndURl, - aws_access_key_id=AccessKey, - aws_secret_access_key=SecertKey, - verify=False - ) - - ############Creating Bucket - BucketName = randomPassword.generate_pass().lower() - - try: - client.create_bucket(Bucket=BucketName) - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile("Creating Bucket Error: %s" % str(msg)) - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - config = { - 'BackupType': BackupType, - 'BucketName': BucketName - } - except BaseException as msg: - config = {'BackupType': BackupType} - pass - - svobj = RemoteBackupSchedule(RemoteBackupConfig=RemoteBackupConfigobj, Name=ScheduleName, - timeintervel=Backfrequency, fileretention=FileRetention, - config=json.dumps(config), - lastrun=str(time.time())) - svobj.save() - - data_ret = {'status': 1, 'error_message': 'None', } - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def AddWPsiteforRemoteBackup(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - WPid = data['WpsiteID'] - RemoteScheduleID = data['RemoteScheduleID'] - - wpsiteobj = WPSites.objects.get(pk=WPid) - WPpath = wpsiteobj.path - VHuser = wpsiteobj.owner.externalApp - PhpVersion = wpsiteobj.owner.phpSelection - php = PHPManager.getPHPString(PhpVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - ####Get DB Name - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp config get DB_NAME --skip-plugins --skip-themes --path=%s' % ( - VHuser, FinalPHPPath, WPpath) - result, stdout = ProcessUtilities.outputExecutioner(command, None, None, None, 1) - - if stdout.find('Error:') > -1: - raise BaseException(stdout) - else: - Finaldbname = stdout.rstrip("\n") - - ## Get DB obj - try: - DBobj = Databases.objects.get(dbName=Finaldbname) - except: - raise BaseException(str("DataBase Not Found")) - RemoteScheduleIDobj = RemoteBackupSchedule.objects.get(pk=RemoteScheduleID) - - svobj = RemoteBackupsites(owner=RemoteScheduleIDobj, WPsites=WPid, database=DBobj.pk) - svobj.save() - - data_ret = {'status': 1, 'error_message': 'None', } - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def UpdateRemoteschedules(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - ScheduleID = data['ScheduleID'] - Frequency = data['Frequency'] - FileRetention = data['FileRetention'] - - scheduleobj = RemoteBackupSchedule.objects.get(pk=ScheduleID) - scheduleobj.timeintervel = Frequency - scheduleobj.fileretention = FileRetention - scheduleobj.save() - - data_ret = {'status': 1, 'error_message': 'None', } - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def ScanWordpressSite(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - allweb = Websites.objects.all() - - childdomain = ChildDomains.objects.all() - - for web in allweb: - webpath = "/home/%s/public_html/" % web.domain - command = "cat %swp-config.php" % webpath - result = ProcessUtilities.outputExecutioner(command, web.externalApp) - - if os.path.exists(ProcessUtilities.debugPath): - logging.CyberCPLogFileWriter.writeToFile(result) - - if result.find('No such file or directory') == -1: - try: - WPSites.objects.get(path=webpath) - except: - wpobj = WPSites(owner=web, title=web.domain, path=webpath, FinalURL=web.domain, - AutoUpdates="Enabled", PluginUpdates="Enabled", - ThemeUpdates="Enabled", ) - wpobj.save() - - for chlid in childdomain: - childPath = chlid.path.rstrip('/') - - command = "cat %s/wp-config.php" % childPath - result = ProcessUtilities.outputExecutioner(command, chlid.master.externalApp) - - if os.path.exists(ProcessUtilities.debugPath): - logging.CyberCPLogFileWriter.writeToFile(result) - - if result.find('No such file or directory') == -1: - fChildPath = f'{childPath}/' - try: - WPSites.objects.get(path=fChildPath) - except: - - wpobj = WPSites(owner=chlid.master, title=chlid.domain, path=fChildPath, FinalURL=chlid.domain, - AutoUpdates="Enabled", PluginUpdates="Enabled", - ThemeUpdates="Enabled", ) - wpobj.save() - - data_ret = {'status': 1, 'error_message': 'None', } - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def installwpcore(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - ###fetch WP version - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core version --skip-plugins --skip-themes --path=%s 2>/dev/null' % ( - Vhuser, FinalPHPPath, path) - version = ProcessUtilities.outputExecutioner(command, None, True) - version = version.rstrip("\n") - - ###install wp core - command = f"sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp core download --force --skip-content --version={version} --path={path}" - output = ProcessUtilities.outputExecutioner(command) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', 'result': output} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def dataintegrity(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - ###fetch WP version - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core verify-checksums --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, path) - result = ProcessUtilities.outputExecutioner(command) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', 'result': result} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def UpdatePlugins(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - plugin = data['plugin'] - pluginarray = data['pluginarray'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['plugin'] = plugin - extraArgs['pluginarray'] = pluginarray - extraArgs['FinalPHPPath'] = FinalPHPPath - extraArgs['path'] = path - extraArgs['Vhuser'] = Vhuser - - background = ApplicationInstaller('UpdateWPPlugin', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def UpdateThemes(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - Theme = data['Theme'] - Themearray = data['Themearray'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['Theme'] = Theme - extraArgs['Themearray'] = Themearray - extraArgs['FinalPHPPath'] = FinalPHPPath - extraArgs['path'] = path - extraArgs['Vhuser'] = Vhuser - - background = ApplicationInstaller('UpdateWPTheme', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def DeletePlugins(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - plugin = data['plugin'] - pluginarray = data['pluginarray'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['plugin'] = plugin - extraArgs['pluginarray'] = pluginarray - extraArgs['FinalPHPPath'] = FinalPHPPath - extraArgs['path'] = path - extraArgs['Vhuser'] = Vhuser - - background = ApplicationInstaller('DeletePlugins', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def DeleteThemes(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - Theme = data['Theme'] - Themearray = data['Themearray'] - wpsite = WPSites.objects.get(pk=WPManagerID) - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['Theme'] = Theme - extraArgs['Themearray'] = Themearray - extraArgs['FinalPHPPath'] = FinalPHPPath - extraArgs['path'] = path - extraArgs['Vhuser'] = Vhuser - - background = ApplicationInstaller('DeleteThemes', extraArgs) - background.start() - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def ChangeStatus(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - plugin = data['plugin'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin status %s --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, plugin, path) - stdoutput = ProcessUtilities.outputExecutioner(command) - - if stdoutput.find('Status: Active') > -1: - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin deactivate %s --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, plugin, path) - stdoutput = ProcessUtilities.outputExecutioner(command) - time.sleep(3) - - else: - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin activate %s --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, plugin, path) - stdoutput = ProcessUtilities.outputExecutioner(command) - time.sleep(3) - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def ChangeStatusThemes(self, userID=None, data=None): - try: - # logging.CyberCPLogFileWriter.writeToFile("Error WP ChangeStatusThemes ....... %s") - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - Theme = data['theme'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['Theme'] = Theme - extraArgs['FinalPHPPath'] = FinalPHPPath - extraArgs['path'] = path - extraArgs['Vhuser'] = Vhuser - - background = ApplicationInstaller('ChangeStatusThemes', extraArgs) - background.start() - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def CreateStagingNow(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['StagingDomain'] = data['StagingDomain'] - extraArgs['StagingName'] = data['StagingName'] - extraArgs['WPid'] = data['WPid'] - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - wpsite = WPSites.objects.get(pk=data['WPid']) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - background = ApplicationInstaller('CreateStagingNow', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def UpdateWPSettings(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - siteId = data['siteId'] - setting = data['setting'] - value = data['value'] - - wpsite = WPSites.objects.get(pk=siteId) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) != 1: - return ACLManager.loadError() - - # Get PHP version and path - Webobj = Websites.objects.get(pk=wpsite.owner_id) - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - # Update the appropriate setting based on the setting type - if setting == 'search-indexing': - # Update search engine indexing - command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp option update blog_public {value} --skip-plugins --skip-themes --path={wpsite.path}' - elif setting == 'debugging': - # Update debugging in wp-config.php - if value: - command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_DEBUG true --raw --skip-plugins --skip-themes --path={wpsite.path}' - else: - command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_DEBUG false --raw --skip-plugins --skip-themes --path={wpsite.path}' - elif setting == 'password-protection': - vhostName = wpsite.owner.domain - vhostPassDir = f'/home/{vhostName}' - path = f'{vhostPassDir}/{siteId}' - if value: - # Enable password protection - if not os.path.exists(path): - os.makedirs(path) - htpasswd = f'{path}/.htpasswd' - htaccess = f'{wpsite.path}/.htaccess' - password = randomPassword.generate_pass(12) - - # Create .htpasswd file - command = f"htpasswd -cb {htpasswd} admin {password}" - ProcessUtilities.executioner(command) - - # Create .htaccess file - htaccess_content = f"""AuthType Basic -AuthName "Restricted Access" -AuthUserFile {htpasswd} -Require valid-user Require valid-user""" with open(htaccess, 'w') as f: f.write(htaccess_content) @@ -4033,13 +1999,743 @@ Require valid-user""" if os.path.exists(htaccess): os.remove(htaccess) return JsonResponse({'status': 1, 'error_message': 'None'}) + elif setting == 'maintenance-mode': + if value: + command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp maintenance-mode activate --skip-plugins --skip-themes --path={wpsite.path}' + else: + command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp maintenance-mode deactivate --skip-plugins --skip-themes --path={wpsite.path}' + else: + return JsonResponse({'status': 0, 'error_message': 'Invalid setting type'}) + + result = ProcessUtilities.outputExecutioner(command) + if result.find('Error:') > -1: + return JsonResponse({'status': 0, 'error_message': result}) + + return JsonResponse({'status': 1, 'error_message': 'None'}) + + except BaseException as msg: + return JsonResponse({'status': 0, 'error_message': str(msg)}) + + def submitWorpressCreation(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + extraArgs = {} + extraArgs['currentACL'] = currentACL + extraArgs['adminID'] = admin.pk + extraArgs['domainName'] = data['domain'] + extraArgs['WPVersion'] = data['WPVersion'] + extraArgs['blogTitle'] = data['title'] + try: + extraArgs['pluginbucket'] = data['pluginbucket'] + except: + extraArgs['pluginbucket'] = '-1' + extraArgs['adminUser'] = data['adminUser'] + extraArgs['PasswordByPass'] = data['PasswordByPass'] + extraArgs['adminPassword'] = data['PasswordByPass'] + extraArgs['adminEmail'] = data['Email'] + extraArgs['updates'] = data['AutomaticUpdates'] + extraArgs['Plugins'] = data['Plugins'] + extraArgs['Themes'] = data['Themes'] + extraArgs['websiteOwner'] = data['websiteOwner'] + extraArgs['package'] = data['package'] + extraArgs['home'] = data['home'] + extraArgs['apacheBackend'] = data['apacheBackend'] + try: + extraArgs['path'] = data['path'] + if extraArgs['path'] == '': + extraArgs['home'] = '1' + except: + pass + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + background = ApplicationInstaller('wordpressInstallNew', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} json_data = json.dumps(data_ret) return HttpResponse(json_data) + def submitWebsiteCreation(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + + domain = data['domainName'] + adminEmail = data['adminEmail'] + phpSelection = data['phpSelection'] + packageName = data['package'] + websiteOwner = data['websiteOwner'].lower() + + if data['domainName'].find("cyberpanel.website") > -1: + url = "https://platform.cyberpersons.com/CyberpanelAdOns/CreateDomain" + + domain_data = { + "name": "test-domain", + "IP": ACLManager.GetServerIP(), + "domain": data['domainName'] + } + + import requests + response = requests.post(url, data=json.dumps(domain_data)) + domain_status = response.json()['status'] + + if domain_status == 0: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': response.json()['error_message']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + loggedUser = Administrator.objects.get(pk=userID) + newOwner = Administrator.objects.get(userName=websiteOwner) + + if ACLManager.currentContextPermission(currentACL, 'createWebsite') == 0: + return ACLManager.loadErrorJson('createWebSiteStatus', 0) + + if ACLManager.checkOwnerProtection(currentACL, loggedUser, newOwner) == 0: + return ACLManager.loadErrorJson('createWebSiteStatus', 0) + + if currentACL['admin'] == 0: + if ACLManager.CheckDomainBlackList(domain) == 0: + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Blacklisted domain."} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + if not validators.domain(domain): + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Invalid domain."} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + if not validators.email(adminEmail) or adminEmail.find('--') > -1: + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Invalid email."} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + try: + HA = data['HA'] + externalApp = 'nobody' + except: + externalApp = "".join(re.findall("[a-zA-Z]+", domain))[:5] + str(randint(1000, 9999)) + + try: + counter = 0 + while 1: + tWeb = Websites.objects.get(externalApp=externalApp) + externalApp = '%s%s' % (tWeb.externalApp, str(counter)) + counter = counter + 1 + except: + pass + + tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + + try: + apacheBackend = str(data['apacheBackend']) + except: + apacheBackend = "0" + + try: + mailDomain = str(data['mailDomain']) + except: + mailDomain = "1" + + import pwd + counter = 0 + + ## Create Configurations + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " createVirtualHost --virtualHostName " + domain + \ + " --administratorEmail " + adminEmail + " --phpVersion '" + phpSelection + \ + "' --virtualHostUser " + externalApp + " --ssl " + str(1) + " --dkimCheck " \ + + str(1) + " --openBasedir " + str(data['openBasedir']) + \ + ' --websiteOwner "' + websiteOwner + '" --package "' + packageName + '" --tempStatusPath ' + tempStatusPath + " --apache " + apacheBackend + " --mailDomain %s" % ( + mailDomain) + + ProcessUtilities.popenExecutioner(execPath) + time.sleep(2) + + data_ret = {'status': 1, 'createWebSiteStatus': 1, 'error_message': "None", + 'tempStatusPath': tempStatusPath, 'LinuxUser': externalApp} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def submitDomainCreation(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + try: + alias = data['alias'] + except: + alias = 0 + + masterDomain = data['masterDomain'] + domain = data['domainName'] + + + if alias == 0: + phpSelection = data['phpSelection'] + path = data['path'] + else: + + ### if master website have apache then create this sub-domain also as ols + apache + + apachePath = ApacheVhost.configBasePath + masterDomain + '.conf' + + if os.path.exists(apachePath): + data['apacheBackend'] = 1 + + phpSelection = Websites.objects.get(domain=masterDomain).phpSelection + + tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + + if not validators.domain(domain): + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Invalid domain."} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + if data['domainName'].find("cyberpanel.website") > -1: + url = "https://platform.cyberpersons.com/CyberpanelAdOns/CreateDomain" + + domain_data = { + "name": "test-domain", + "IP": ACLManager.GetServerIP(), + "domain": data['domainName'] + } + + import requests + response = requests.post(url, data=json.dumps(domain_data)) + domain_status = response.json()['status'] + + if domain_status == 0: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': response.json()['error_message']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + if ACLManager.checkOwnership(masterDomain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('createWebSiteStatus', 0) + + if data['path'].find('..') > -1: + return ACLManager.loadErrorJson('createWebSiteStatus', 0) + + if currentACL['admin'] != 1: + data['openBasedir'] = 1 + + if alias == 0: + + if len(path) > 0: + path = path.lstrip("/") + path = "/home/" + masterDomain + "/" + path + else: + path = "/home/" + masterDomain + "/" + domain + else: + path = f'/home/{masterDomain}/public_html' + + try: + apacheBackend = str(data['apacheBackend']) + except: + apacheBackend = "0" + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + + execPath = execPath + " createDomain --masterDomain " + masterDomain + " --virtualHostName " + domain + \ + " --phpVersion '" + phpSelection + "' --ssl " + str(1) + " --dkimCheck " + str(1) \ + + " --openBasedir " + str(data['openBasedir']) + ' --path ' + path + ' --websiteOwner ' \ + + admin.userName + ' --tempStatusPath ' + tempStatusPath + " --apache " + apacheBackend + f' --aliasDomain {str(alias)}' + + ProcessUtilities.popenExecutioner(execPath) + time.sleep(2) + + data_ret = {'status': 1, 'createWebSiteStatus': 1, 'error_message': "None", + 'tempStatusPath': tempStatusPath} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def fetchDomains(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + masterDomain = data['masterDomain'] + + try: + alias = data['alias'] + except: + alias = 0 + + if ACLManager.checkOwnership(masterDomain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('fetchStatus', 0) + + cdManager = ChildDomainManager(masterDomain) + json_data = cdManager.findChildDomainsJson(alias) + + final_json = json.dumps({'status': 1, 'fetchStatus': 1, 'error_message': "None", "data": json_data}) + return HttpResponse(final_json) + + except BaseException as msg: + final_dic = {'status': 0, 'fetchStatus': 0, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def searchWebsites(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + try: + json_data = self.searchWebsitesJson(currentACL, userID, data['patternAdded']) + except BaseException as msg: + tempData = {} + tempData['page'] = 1 + return self.getFurtherAccounts(userID, tempData) + + pagination = self.websitePagination(currentACL, userID) + final_dic = {'status': 1, 'listWebSiteStatus': 1, 'error_message': "None", "data": json_data, + 'pagination': pagination} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + except BaseException as msg: + dic = {'status': 1, 'listWebSiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def searchChilds(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + + websites = ACLManager.findWebsiteObjects(currentACL, userID) + childDomains = [] + + for web in websites: + for child in web.childdomains_set.filter(domain__istartswith=data['patternAdded']): + childDomains.append(child) + + json_data = self.findChildsListJson(childDomains) + + final_dic = {'status': 1, 'listWebSiteStatus': 1, 'error_message': "None", "data": json_data} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + except BaseException as msg: + dic = {'status': 1, 'listWebSiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def getFurtherAccounts(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + pageNumber = int(data['page']) + json_data = self.findWebsitesJson(currentACL, userID, pageNumber) + pagination = self.websitePagination(currentACL, userID) + final_dic = {'status': 1, 'listWebSiteStatus': 1, 'error_message': "None", "data": json_data, + 'pagination': pagination} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + except BaseException as msg: + dic = {'status': 1, 'listWebSiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def fetchWebsitesList(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + pageNumber = int(data['page']) + recordsToShow = int(data['recordsToShow']) + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(f'Fetch sites step 1..') + + endPageNumber, finalPageNumber = self.recordsPointer(pageNumber, recordsToShow) + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(f'Fetch sites step 2..') + + websites = ACLManager.findWebsiteObjects(currentACL, userID) + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(f'Fetch sites step 3..') + + pagination = self.getPagination(len(websites), recordsToShow) + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(f'Fetch sites step 4..') + + json_data = self.findWebsitesListJson(websites[finalPageNumber:endPageNumber]) + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(f'Fetch sites step 5..') + + final_dic = {'status': 1, 'listWebSiteStatus': 1, 'error_message': "None", "data": json_data, + 'pagination': pagination} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + except BaseException as msg: + dic = {'status': 1, 'listWebSiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def fetchChildDomainsMain(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + pageNumber = int(data['page']) + recordsToShow = int(data['recordsToShow']) + + endPageNumber, finalPageNumber = self.recordsPointer(pageNumber, recordsToShow) + websites = ACLManager.findWebsiteObjects(currentACL, userID) + childDomains = [] + + for web in websites: + for child in web.childdomains_set.filter(alais=0): + if child.domain == f'mail.{web.domain}': + pass + else: + childDomains.append(child) + + pagination = self.getPagination(len(childDomains), recordsToShow) + json_data = self.findChildsListJson(childDomains[finalPageNumber:endPageNumber]) + + final_dic = {'status': 1, 'listWebSiteStatus': 1, 'error_message': "None", "data": json_data, + 'pagination': pagination} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + except BaseException as msg: + dic = {'status': 1, 'listWebSiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def findWebsitesListJson(self, websites): + try: + ipFile = "/etc/cyberpanel/machineIP" + f = open(ipFile) + ipData = f.read() + ipAddress = ipData.split('\n', 1)[0] + except BaseException as msg: + logging.CyberCPLogFileWriter.writeToFile("Failed to read machine IP, error:" + str(msg)) + ipAddress = "192.168.100.1" + + json_data = [] + + for website in websites: + wp_sites = [] + try: + wp_sites = WPSites.objects.filter(owner=website) + wp_sites = [{ + 'id': wp.id, + 'title': wp.title, + 'url': wp.FinalURL, + 'version': wp.version if hasattr(wp, 'version') else 'Unknown', + 'phpVersion': wp.phpVersion if hasattr(wp, 'phpVersion') else 'Unknown' + } for wp in wp_sites] + except: + pass + + # Calculate disk usage + DiskUsage, DiskUsagePercentage, bwInMB, bwUsage = virtualHostUtilities.FindStats(website) + diskUsed = "%sMB" % str(DiskUsage) + + # Convert numeric state to text + state = "Active" if website.state == 1 else "Suspended" + + json_data.append({ + 'domain': website.domain, + 'adminEmail': website.adminEmail, + 'phpVersion': website.phpSelection, + 'state': state, + 'ipAddress': ipAddress, + 'package': website.package.packageName, + 'admin': website.admin.userName, + 'wp_sites': wp_sites, + 'diskUsed': diskUsed + }) + return json.dumps(json_data) + + + + def findDockersitesListJson(self, Dockersite): + + json_data = "[" + checker = 0 + + try: + ipFile = "/etc/cyberpanel/machineIP" + f = open(ipFile) + ipData = f.read() + ipAddress = ipData.split('\n', 1)[0] + except BaseException as msg: + logging.CyberCPLogFileWriter.writeToFile("Failed to read machine IP, error:" + str(msg)) + ipAddress = "192.168.100.1" + + from plogical.phpUtilities import phpUtilities + for items in Dockersite: + website = Websites.objects.get(pk=items.admin.pk) + vhFile = f'/usr/local/lsws/conf/vhosts/{website.domain}/vhost.conf' + + try: + PHPVersionActual = phpUtilities.WrapGetPHPVersionFromFileToGetVersionWithPHP(website) + except: + PHPVersionActual = 'PHP 8.1' + + + if items.state == 0: + state = "Suspended" + else: + state = "Active" + + dpkg = PackageAssignment.objects.get(user=website.admin) + + + dic = {'id':items.pk, 'domain': website.domain, 'adminEmail': website.adminEmail, 'ipAddress': ipAddress, + 'admin': website.admin.userName, 'package': dpkg.package.Name, 'state': state, + 'CPU': int(items.CPUsMySQL)+int(items.CPUsSite), 'Ram': int(items.MemorySite)+int(items.MemoryMySQL), 'phpVersion': PHPVersionActual } + + if checker == 0: + json_data = json_data + json.dumps(dic) + checker = 1 + else: + json_data = json_data + ',' + json.dumps(dic) + + json_data = json_data + ']' + + return json_data + + def findChildsListJson(self, childs): + + json_data = "[" + checker = 0 + + try: + ipFile = "/etc/cyberpanel/machineIP" + f = open(ipFile) + ipData = f.read() + ipAddress = ipData.split('\n', 1)[0] + except BaseException as msg: + logging.CyberCPLogFileWriter.writeToFile("Failed to read machine IP, error:" + str(msg)) + ipAddress = "192.168.100.1" + + for items in childs: + + dic = {'domain': items.domain, 'masterDomain': items.master.domain, 'adminEmail': items.master.adminEmail, + 'ipAddress': ipAddress, + 'admin': items.master.admin.userName, 'package': items.master.package.packageName, + 'path': items.path} + + if checker == 0: + json_data = json_data + json.dumps(dic) + checker = 1 + else: + json_data = json_data + ',' + json.dumps(dic) + + json_data = json_data + ']' + + return json_data + + def recordsPointer(self, page, toShow): + finalPageNumber = ((page * toShow)) - toShow + endPageNumber = finalPageNumber + toShow + return endPageNumber, finalPageNumber + + def getPagination(self, records, toShow): + pages = float(records) / float(toShow) + + pagination = [] + counter = 1 + + if pages <= 1.0: + pages = 1 + pagination.append(counter) + else: + pages = ceil(pages) + finalPages = int(pages) + 1 + + for i in range(1, finalPages): + pagination.append(counter) + counter = counter + 1 + + return pagination + + def submitWebsiteDeletion(self, userID=None, data=None): + try: + if data['websiteName'].find("cyberpanel.website") > -1: + url = "https://platform.cyberpersons.com/CyberpanelAdOns/DeleteDomain" + + domain_data = { + "name": "test-domain", + "IP": ACLManager.GetServerIP(), + "domain": data['websiteName'] + } + + import requests + response = requests.post(url, data=json.dumps(domain_data)) + + currentACL = ACLManager.loadedACL(userID) + if ACLManager.currentContextPermission(currentACL, 'deleteWebsite') == 0: + return ACLManager.loadErrorJson('websiteDeleteStatus', 0) + + websiteName = data['websiteName'] + + admin = Administrator.objects.get(pk=userID) + if ACLManager.checkOwnership(websiteName, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('websiteDeleteStatus', 0) + + ## Deleting master domain + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " deleteVirtualHostConfigurations --virtualHostName " + websiteName + ProcessUtilities.popenExecutioner(execPath) + + ### delete site from dgdrive backups + + try: + + from websiteFunctions.models import GDriveSites + GDriveSites.objects.filter(domain=websiteName).delete() + except: + pass + + data_ret = {'status': 1, 'websiteDeleteStatus': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'websiteDeleteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def submitDomainDeletion(self, userID=None, data=None): + try: + + if data['websiteName'].find("cyberpanel.website") > -1: + url = "https://platform.cyberpersons.com/CyberpanelAdOns/DeleteDomain" + + domain_data = { + "name": "test-domain", + "IP": ACLManager.GetServerIP(), + "domain": data['websiteName'] + } + + import requests + response = requests.post(url, data=json.dumps(domain_data)) + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + websiteName = data['websiteName'] + + try: + DeleteDocRoot = int(data['DeleteDocRoot']) + except: + DeleteDocRoot = 0 + + if ACLManager.checkOwnership(websiteName, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('websiteDeleteStatus', 0) + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " deleteDomain --virtualHostName " + websiteName + ' --DeleteDocRoot %s' % ( + str(DeleteDocRoot)) + ProcessUtilities.outputExecutioner(execPath) + + data_ret = {'status': 1, 'websiteDeleteStatus': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'websiteDeleteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def submitWebsiteStatus(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + if ACLManager.currentContextPermission(currentACL, 'suspendWebsite') == 0: + return ACLManager.loadErrorJson('websiteStatus', 0) + + websiteName = data['websiteName'] + state = data['state'] + + website = Websites.objects.get(domain=websiteName) + + admin = Administrator.objects.get(pk=userID) + if ACLManager.checkOwnership(websiteName, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('websiteStatus', 0) + + if state == "Suspend": + confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + websiteName + command = "mv " + confPath + " " + confPath + "-suspended" + ProcessUtilities.popenExecutioner(command) + + childDomains = website.childdomains_set.all() + + for items in childDomains: + confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + items.domain + command = "mv " + confPath + " " + confPath + "-suspended" + ProcessUtilities.executioner(command) + + installUtilities.reStartLiteSpeedSocket() + website.state = 0 + else: + confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + websiteName + + command = "mv " + confPath + "-suspended" + " " + confPath + ProcessUtilities.executioner(command) + + command = "chown -R " + "lsadm" + ":" + "lsadm" + " " + confPath + ProcessUtilities.popenExecutioner(command) + + childDomains = website.childdomains_set.all() + + for items in childDomains: + confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + items.domain + + command = "mv " + confPath + "-suspended" + " " + confPath + ProcessUtilities.executioner(command) + + command = "chown -R " + "lsadm" + ":" + "lsadm" + " " + confPath + ProcessUtilities.popenExecutioner(command) + + installUtilities.reStartLiteSpeedSocket() + website.state = 1 + + website.save() + + data_ret = {'websiteStatus': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + + data_ret = {'websiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + def submitWebsiteModify(self, userID=None, data=None): try: + currentACL = ACLManager.loadedACL(userID) if ACLManager.currentContextPermission(currentACL, 'modifyWebsite') == 0: return ACLManager.loadErrorJson('modifyStatus', 0) @@ -4782,7698 +3478,6 @@ Require valid-user""" json_data = json.dumps(data_ret) return HttpResponse(json_data) - def getWebsiteCron(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - self.domain = data['domain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('getWebsiteCron', 0) - - website = Websites.objects.get(domain=self.domain) - - if Websites.objects.filter(domain=self.domain).exists(): - pass - else: - dic = {'getWebsiteCron': 0, 'error_message': 'You do not own this domain'} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - CronUtil.CronPrem(1) - - crons = [] - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" - execPath = execPath + " getWebsiteCron --externalApp " + website.externalApp - - f = ProcessUtilities.outputExecutioner(execPath, website.externalApp) - - CronUtil.CronPrem(0) - - if ProcessUtilities.decideDistro() == ProcessUtilities.centos or ProcessUtilities.decideDistro() == ProcessUtilities.cent8: - cronPath = "/var/spool/cron/" + website.externalApp - else: - cronPath = "/var/spool/cron/crontabs/" + website.externalApp - - if f.find('Permission denied') > -1: - command = 'chmod 644 %s' % (cronPath) - ProcessUtilities.executioner(command) - - command = 'chown %s:%s %s' % (website.externalApp, website.externalApp, cronPath) - ProcessUtilities.executioner(command) - - f = ProcessUtilities.outputExecutioner(execPath, website.externalApp) - - if f.find("0,CyberPanel,") > -1: - data_ret = {'getWebsiteCron': 0, "user": website.externalApp, "crons": {}} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - - counter = 0 - for line in f.split("\n"): - if line: - split = line.split(" ", 5) - if len(split) == 6: - counter += 1 - crons.append({"line": counter, - "minute": split[0], - "hour": split[1], - "monthday": split[2], - "month": split[3], - "weekday": split[4], - "command": split[5]}) - - data_ret = {'getWebsiteCron': 1, "user": website.externalApp, "crons": crons} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - dic = {'getWebsiteCron': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def getCronbyLine(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - line = data['line'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('getWebsiteCron', 0) - - if Websites.objects.filter(domain=self.domain).exists(): - pass - else: - dic = {'getWebsiteCron': 0, 'error_message': 'You do not own this domain'} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - line -= 1 - website = Websites.objects.get(domain=self.domain) - - try: - CronUtil.CronPrem(1) - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" - execPath = execPath + " getWebsiteCron --externalApp " + website.externalApp - - f = ProcessUtilities.outputExecutioner(execPath, website.externalApp) - CronUtil.CronPrem(0) - except subprocess.CalledProcessError as error: - dic = {'getWebsiteCron': 0, 'error_message': 'Unable to access Cron file'} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - f = f.split("\n") - cron = f[line] - - cron = cron.split(" ", 5) - if len(cron) != 6: - dic = {'getWebsiteCron': 0, 'error_message': 'Cron line incorrect'} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - data_ret = {"getWebsiteCron": 1, - "user": website.externalApp, - "cron": { - "minute": cron[0], - "hour": cron[1], - "monthday": cron[2], - "month": cron[3], - "weekday": cron[4], - "command": cron[5], - }, - "line": line} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - except BaseException as msg: - print(msg) - dic = {'getWebsiteCron': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def saveCronChanges(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - line = data['line'] - - minute = data['minute'] - hour = data['hour'] - monthday = data['monthday'] - month = data['month'] - weekday = data['weekday'] - command = data['cronCommand'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('getWebsiteCron', 0) - - website = Websites.objects.get(domain=self.domain) - - finalCron = "%s %s %s %s %s %s" % (minute, hour, monthday, month, weekday, command) - - CronUtil.CronPrem(1) - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" - execPath = execPath + " saveCronChanges --externalApp " + website.externalApp + " --line " + str( - line) + " --finalCron '" + finalCron + "'" - output = ProcessUtilities.outputExecutioner(execPath, website.externalApp) - CronUtil.CronPrem(0) - - if output.find("1,") > -1: - data_ret = {"getWebsiteCron": 1, - "user": website.externalApp, - "cron": finalCron, - "line": line} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - else: - dic = {'getWebsiteCron': 0, 'error_message': output} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - except BaseException as msg: - dic = {'getWebsiteCron': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def remCronbyLine(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - line = data['line'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('addNewCron', 0) - - website = Websites.objects.get(domain=self.domain) - - CronUtil.CronPrem(1) - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" - execPath = execPath + " remCronbyLine --externalApp " + website.externalApp + " --line " + str( - line) - output = ProcessUtilities.outputExecutioner(execPath, website.externalApp) - - CronUtil.CronPrem(0) - - if output.find("1,") > -1: - data_ret = {"remCronbyLine": 1, - "user": website.externalApp, - "removeLine": output.split(',')[1], - "line": line} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - else: - dic = {'remCronbyLine': 0, 'error_message': output} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - except BaseException as msg: - dic = {'remCronbyLine': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def addNewCron(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - minute = data['minute'] - hour = data['hour'] - monthday = data['monthday'] - month = data['month'] - weekday = data['weekday'] - command = data['cronCommand'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('addNewCron', 0) - - website = Websites.objects.get(domain=self.domain) - - if ProcessUtilities.decideDistro() == ProcessUtilities.centos or ProcessUtilities.decideDistro() == ProcessUtilities.cent8: - cronPath = "/var/spool/cron/" + website.externalApp - else: - cronPath = "/var/spool/cron/crontabs/" + website.externalApp - - commandT = 'touch %s' % (cronPath) - ProcessUtilities.executioner(commandT, 'root') - commandT = 'chown %s:%s %s' % (website.externalApp, website.externalApp, cronPath) - ProcessUtilities.executioner(commandT, 'root') - - CronUtil.CronPrem(1) - - finalCron = "%s %s %s %s %s %s" % (minute, hour, monthday, month, weekday, command) - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" - execPath = execPath + " addNewCron --externalApp " + website.externalApp + " --finalCron '" + finalCron + "'" - output = ProcessUtilities.outputExecutioner(execPath, website.externalApp) - - if ProcessUtilities.decideDistro() == ProcessUtilities.ubuntu or ProcessUtilities.decideDistro() == ProcessUtilities.ubuntu20: - command = 'chmod 600 %s' % (cronPath) - ProcessUtilities.executioner(command) - - command = 'systemctl restart cron' - ProcessUtilities.executioner(command) - - CronUtil.CronPrem(0) - - if output.find("1,") > -1: - data_ret = {"addNewCron": 1, - "user": website.externalApp, - "cron": finalCron} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - else: - dic = {'addNewCron': 0, 'error_message': output} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - except BaseException as msg: - dic = {'addNewCron': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def submitAliasCreation(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['masterDomain'] - aliasDomain = data['aliasDomain'] - ssl = data['ssl'] - - if not validators.domain(aliasDomain): - data_ret = {'status': 0, 'createAliasStatus': 0, 'error_message': "Invalid domain."} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('createAliasStatus', 0) - - sslpath = "/home/" + self.domain + "/public_html" - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - - execPath = execPath + " createAlias --masterDomain " + self.domain + " --aliasDomain " + aliasDomain + " --ssl " + str( - ssl) + " --sslPath " + sslpath + " --administratorEmail " + admin.email + ' --websiteOwner ' + admin.userName - - output = ProcessUtilities.outputExecutioner(execPath) - - if output.find("1,None") > -1: - pass - else: - data_ret = {'createAliasStatus': 0, 'error_message': output, "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - data_ret = {'createAliasStatus': 1, 'error_message': "None", "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'createAliasStatus': 0, 'error_message': str(msg), "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def issueAliasSSL(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['masterDomain'] - aliasDomain = data['aliasDomain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('sslStatus', 0) - - if ACLManager.AliasDomainCheck(currentACL, aliasDomain, self.domain) == 1: - pass - else: - return ACLManager.loadErrorJson('sslStatus', 0) - - sslpath = "/home/" + self.domain + "/public_html" - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " issueAliasSSL --masterDomain " + self.domain + " --aliasDomain " + aliasDomain + " --sslPath " + sslpath + " --administratorEmail " + admin.email - - output = ProcessUtilities.outputExecutioner(execPath) - - if output.find("1,None") > -1: - data_ret = {'sslStatus': 1, 'error_message': "None", "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - data_ret = {'sslStatus': 0, 'error_message': output, "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'sslStatus': 0, 'error_message': str(msg), "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def delateAlias(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['masterDomain'] - aliasDomain = data['aliasDomain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('deleteAlias', 0) - - if ACLManager.AliasDomainCheck(currentACL, aliasDomain, self.domain) == 1: - pass - else: - return ACLManager.loadErrorJson('deleteAlias', 0) - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " deleteAlias --masterDomain " + self.domain + " --aliasDomain " + aliasDomain - output = ProcessUtilities.outputExecutioner(execPath) - - if output.find("1,None") > -1: - data_ret = {'deleteAlias': 1, 'error_message': "None", "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - data_ret = {'deleteAlias': 0, 'error_message': output, "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'deleteAlias': 0, 'error_message': str(msg), "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def changeOpenBasedir(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - - self.domain = data['domainName'] - openBasedirValue = data['openBasedirValue'] - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadErrorJson('changeOpenBasedir', 0) - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " changeOpenBasedir --virtualHostName '" + self.domain + "' --openBasedirValue " + openBasedirValue - output = ProcessUtilities.popenExecutioner(execPath) - - data_ret = {'status': 1, 'changeOpenBasedir': 1, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'changeOpenBasedir': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def wordpressInstall(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - proc = httpProc(request, 'websiteFunctions/installWordPress.html', {'domainName': self.domain}) - return proc.render() - - def installWordpress(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('installStatus', 0) - - mailUtilities.checkHome() - - extraArgs = {} - extraArgs['admin'] = admin - extraArgs['domainName'] = data['domain'] - extraArgs['home'] = data['home'] - extraArgs['blogTitle'] = data['blogTitle'] - extraArgs['adminUser'] = data['adminUser'] - extraArgs['adminPassword'] = data['passwordByPass'] - extraArgs['adminEmail'] = data['adminEmail'] - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - if data['home'] == '0': - extraArgs['path'] = data['path'] - - background = ApplicationInstaller('wordpress', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def installWordpressStatus(self, userID=None, data=None): - try: - statusFile = data['statusFile'] - - if ACLManager.CheckStatusFilleLoc(statusFile): - pass - else: - data_ret = {'abort': 1, 'installStatus': 0, 'installationProgress': "100", - 'currentStatus': 'Invalid status file.'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - statusData = ProcessUtilities.outputExecutioner("cat " + statusFile).splitlines() - - lastLine = statusData[-1] - - if lastLine.find('[200]') > -1: - command = 'rm -f ' + statusFile - subprocess.call(shlex.split(command)) - data_ret = {'abort': 1, 'installStatus': 1, 'installationProgress': "100", - 'currentStatus': 'Successfully Installed.'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - elif lastLine.find('[404]') > -1: - data_ret = {'abort': 1, 'installStatus': 0, 'installationProgress': "0", - 'error_message': ProcessUtilities.outputExecutioner("cat " + statusFile).splitlines()} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - progress = lastLine.split(',') - currentStatus = progress[0] - try: - installationProgress = progress[1] - except: - installationProgress = 0 - data_ret = {'abort': 0, 'installStatus': 0, 'installationProgress': installationProgress, - 'currentStatus': currentStatus} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'abort': 0, 'installStatus': 0, 'installationProgress': "0", 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def joomlaInstall(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - proc = httpProc(request, 'websiteFunctions/installJoomla.html', {'domainName': self.domain}) - return proc.render() - - def installJoomla(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('installStatus', 0) - - extraArgs = {} - - extraArgs['password'] = data['passwordByPass'] - extraArgs['prefix'] = data['prefix'] - extraArgs['domain'] = data['domain'] - extraArgs['home'] = data['home'] - extraArgs['siteName'] = data['siteName'] - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - mailUtilities.checkHome() - - if data['home'] == '0': - extraArgs['path'] = data['path'] - - background = ApplicationInstaller('joomla', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def setupGit(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - website = Websites.objects.get(domain=self.domain) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson() - - path = '/home/cyberpanel/' + self.domain + '.git' - - if os.path.exists(path): - ipFile = "/etc/cyberpanel/machineIP" - f = open(ipFile) - ipData = f.read() - ipAddress = ipData.split('\n', 1)[0] - - port = ProcessUtilities.fetchCurrentPort() - - webhookURL = 'https://' + ipAddress + ':%s/websites/' % (port) + self.domain + '/gitNotify' - - proc = httpProc(request, 'websiteFunctions/setupGit.html', - {'domainName': self.domain, 'installed': 1, 'webhookURL': webhookURL}) - return proc.render() - else: - command = "ssh-keygen -f /home/%s/.ssh/%s -t rsa -N ''" % (self.domain, website.externalApp) - ProcessUtilities.executioner(command, website.externalApp) - - configContent = """Host github.com -IdentityFile /home/%s/.ssh/%s -StrictHostKeyChecking no -""" % (self.domain, website.externalApp) - - path = "/home/cyberpanel/config" - writeToFile = open(path, 'w') - writeToFile.writelines(configContent) - writeToFile.close() - - command = 'mv %s /home/%s/.ssh/config' % (path, self.domain) - ProcessUtilities.executioner(command) - - command = 'chown %s:%s /home/%s/.ssh/config' % (website.externalApp, website.externalApp, self.domain) - ProcessUtilities.executioner(command) - - command = 'cat /home/%s/.ssh/%s.pub' % (self.domain, website.externalApp) - deploymentKey = ProcessUtilities.outputExecutioner(command, website.externalApp) - - proc = httpProc(request, 'websiteFunctions/setupGit.html', - {'domainName': self.domain, 'deploymentKey': deploymentKey, 'installed': 0}) - return proc.render() - - def setupGitRepo(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('installStatus', 0) - - mailUtilities.checkHome() - - extraArgs = {} - extraArgs['admin'] = admin - extraArgs['domainName'] = data['domain'] - extraArgs['username'] = data['username'] - extraArgs['reponame'] = data['reponame'] - extraArgs['branch'] = data['branch'] - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - extraArgs['defaultProvider'] = data['defaultProvider'] - - background = ApplicationInstaller('git', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def gitNotify(self, userID=None, data=None): - try: - - extraArgs = {} - extraArgs['domain'] = self.domain - - background = ApplicationInstaller('pull', extraArgs) - background.start() - - data_ret = {'pulled': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'pulled': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def detachRepo(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson() - - mailUtilities.checkHome() - - extraArgs = {} - extraArgs['domainName'] = data['domain'] - extraArgs['admin'] = admin - - background = ApplicationInstaller('detach', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def changeBranch(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson() - - mailUtilities.checkHome() - - extraArgs = {} - extraArgs['domainName'] = data['domain'] - extraArgs['githubBranch'] = data['githubBranch'] - extraArgs['admin'] = admin - - background = ApplicationInstaller('changeBranch', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def installPrestaShop(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - proc = httpProc(request, 'websiteFunctions/installPrestaShop.html', {'domainName': self.domain}) - return proc.render() - - def installMagento(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - proc = httpProc(request, 'websiteFunctions/installMagento.html', {'domainName': self.domain}) - return proc.render() - - def magentoInstall(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('installStatus', 0) - - mailUtilities.checkHome() - - extraArgs = {} - extraArgs['admin'] = admin - extraArgs['domainName'] = data['domain'] - extraArgs['home'] = data['home'] - extraArgs['firstName'] = data['firstName'] - extraArgs['lastName'] = data['lastName'] - extraArgs['username'] = data['username'] - extraArgs['email'] = data['email'] - extraArgs['password'] = data['passwordByPass'] - extraArgs['sampleData'] = data['sampleData'] - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - if data['home'] == '0': - extraArgs['path'] = data['path'] - - background = ApplicationInstaller('magento', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - ## Installation ends - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def installMautic(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - proc = httpProc(request, 'websiteFunctions/installMautic.html', {'domainName': self.domain}) - return proc.render() - - def mauticInstall(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('installStatus', 0) - - #### Before installing mautic change php to 8.1 - - completePathToConfigFile = f'/usr/local/lsws/conf/vhosts/{self.domain}/vhost.conf' - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " changePHP --phpVersion 'PHP 8.1' --path " + completePathToConfigFile - ProcessUtilities.executioner(execPath) - - mailUtilities.checkHome() - - extraArgs = {} - extraArgs['admin'] = admin - extraArgs['domainName'] = data['domain'] - extraArgs['home'] = data['home'] - extraArgs['username'] = data['username'] - extraArgs['email'] = data['email'] - extraArgs['password'] = data['passwordByPass'] - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - if data['home'] == '0': - extraArgs['path'] = data['path'] - - background = ApplicationInstaller('mautic', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - ## Installation ends - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def prestaShopInstall(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('installStatus', 0) - - mailUtilities.checkHome() - - extraArgs = {} - extraArgs['admin'] = admin - extraArgs['domainName'] = data['domain'] - extraArgs['home'] = data['home'] - extraArgs['shopName'] = data['shopName'] - extraArgs['firstName'] = data['firstName'] - extraArgs['lastName'] = data['lastName'] - extraArgs['databasePrefix'] = data['databasePrefix'] - extraArgs['email'] = data['email'] - extraArgs['password'] = data['passwordByPass'] - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - if data['home'] == '0': - extraArgs['path'] = data['path'] - - #### Before installing Prestashop change php to 8.3 - - completePathToConfigFile = f'/usr/local/lsws/conf/vhosts/{self.domain}/vhost.conf' - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " changePHP --phpVersion 'PHP 8.3' --path " + completePathToConfigFile - ProcessUtilities.executioner(execPath) - - background = ApplicationInstaller('prestashop', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - ## Installation ends - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def createWebsiteAPI(self, data=None): - try: - - adminUser = data['adminUser'] - adminPass = data['adminPass'] - adminEmail = data['ownerEmail'] - websiteOwner = data['websiteOwner'] - ownerPassword = data['ownerPassword'] - data['ssl'] = 1 - data['dkimCheck'] = 1 - data['openBasedir'] = 1 - data['adminEmail'] = data['ownerEmail'] - - try: - data['phpSelection'] = data['phpSelection'] - except: - data['phpSelection'] = "PHP 7.4" - - data['package'] = data['packageName'] - try: - websitesLimit = data['websitesLimit'] - except: - websitesLimit = 1 - - try: - apiACL = data['acl'] - except: - apiACL = 'user' - - admin = Administrator.objects.get(userName=adminUser) - - if hashPassword.check_password(admin.password, adminPass): - - if adminEmail is None: - data['adminEmail'] = "example@example.org" - - try: - acl = ACL.objects.get(name=apiACL) - websiteOwn = Administrator(userName=websiteOwner, - password=hashPassword.hash_password(ownerPassword), - email=adminEmail, type=3, owner=admin.pk, - initWebsitesLimit=websitesLimit, acl=acl, api=1) - websiteOwn.save() - except BaseException: - pass - - else: - data_ret = {"existsStatus": 0, 'createWebSiteStatus': 0, - 'error_message': "Could not authorize access to API"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - return self.submitWebsiteCreation(admin.pk, data) - - except BaseException as msg: - data_ret = {'createWebSiteStatus': 0, 'error_message': str(msg), "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def searchWebsitesJson(self, currentlACL, userID, searchTerm): - - websites = ACLManager.searchWebsiteObjects(currentlACL, userID, searchTerm) - - json_data = "[" - checker = 0 - - try: - ipFile = "/etc/cyberpanel/machineIP" - f = open(ipFile) - ipData = f.read() - ipAddress = ipData.split('\n', 1)[0] - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile("Failed to read machine IP, error:" + str(msg)) - ipAddress = "192.168.100.1" - - for items in websites: - if items.state == 0: - state = "Suspended" - else: - state = "Active" - - DiskUsage, DiskUsagePercentage, bwInMB, bwUsage = virtualHostUtilities.FindStats(items) - - vhFile = f'/usr/local/lsws/conf/vhosts/{items.domain}/vhost.conf' - - if os.path.exists(ProcessUtilities.debugPath): - logging.CyberCPLogFileWriter.writeToFile(vhFile) - - try: - from plogical.phpUtilities import phpUtilities - PHPVersionActual = phpUtilities.WrapGetPHPVersionFromFileToGetVersionWithPHP(vhFile) - except: - PHPVersionActual = 'PHP 8.1' - - diskUsed = "%sMB" % str(DiskUsage) - dic = {'domain': items.domain, 'adminEmail': items.adminEmail, 'ipAddress': ipAddress, - 'admin': items.admin.userName, 'package': items.package.packageName, 'state': state, - 'diskUsed': diskUsed, 'phpVersion': PHPVersionActual} - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - - json_data = json_data + ']' - - return json_data - - def findWebsitesJson(self, currentACL, userID, pageNumber): - finalPageNumber = ((pageNumber * 10)) - 10 - endPageNumber = finalPageNumber + 10 - websites = ACLManager.findWebsiteObjects(currentACL, userID)[finalPageNumber:endPageNumber] - - json_data = "[" - checker = 0 - - try: - ipFile = "/etc/cyberpanel/machineIP" - f = open(ipFile) - ipData = f.read() - ipAddress = ipData.split('\n', 1)[0] - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile("Failed to read machine IP, error:" + str(msg)) - ipAddress = "192.168.100.1" - - for items in websites: - if items.state == 0: - state = "Suspended" - else: - state = "Active" - - DiskUsage, DiskUsagePercentage, bwInMB, bwUsage = virtualHostUtilities.FindStats(items) - - diskUsed = "%sMB" % str(DiskUsage) - - dic = {'domain': items.domain, 'adminEmail': items.adminEmail, 'ipAddress': ipAddress, - 'admin': items.admin.userName, 'package': items.package.packageName, 'state': state, - 'diskUsed': diskUsed} - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - - json_data = json_data + ']' - - return json_data - - def websitePagination(self, currentACL, userID): - websites = ACLManager.findAllSites(currentACL, userID) - - pages = float(len(websites)) / float(10) - pagination = [] - - if pages <= 1.0: - pages = 1 - pagination.append('
  • ') - else: - pages = ceil(pages) - finalPages = int(pages) + 1 - - for i in range(1, finalPages): - pagination.append('
  • ' + str(i) + '
  • ') - - return pagination - - def DockersitePagination(self, currentACL, userID): - websites = DockerSites.objects.all() - - pages = float(len(websites)) / float(10) - pagination = [] - - if pages <= 1.0: - pages = 1 - pagination.append('
  • ') - else: - pages = ceil(pages) - finalPages = int(pages) + 1 - - for i in range(1, finalPages): - pagination.append('
  • ' + str(i) + '
  • ') - - return pagination - - def getSwitchStatus(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - try: - globalData = data['global'] - - data = {} - data['status'] = 1 - - if os.path.exists('/etc/httpd'): - data['server'] = 1 - else: - data['server'] = 0 - - json_data = json.dumps(data) - return HttpResponse(json_data) - except: - pass - - self.domain = data['domainName'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - if ProcessUtilities.decideServer() == ProcessUtilities.OLS: - finalConfPath = ApacheVhost.configBasePath + self.domain + '.conf' - - if os.path.exists(finalConfPath): - - phpPath = ApacheVhost.whichPHPExists(self.domain) - command = 'sudo cat ' + phpPath - phpConf = ProcessUtilities.outputExecutioner(command).splitlines() - pmMaxChildren = phpConf[8].split(' ')[2] - pmStartServers = phpConf[9].split(' ')[2] - pmMinSpareServers = phpConf[10].split(' ')[2] - pmMaxSpareServers = phpConf[11].split(' ')[2] - - data = {} - data['status'] = 1 - - data['server'] = WebsiteManager.apache - data['pmMaxChildren'] = pmMaxChildren - data['pmStartServers'] = pmStartServers - data['pmMinSpareServers'] = pmMinSpareServers - data['pmMaxSpareServers'] = pmMaxSpareServers - data['phpPath'] = phpPath - data['configData'] = ProcessUtilities.outputExecutioner(f'cat {finalConfPath}') - else: - data = {} - data['status'] = 1 - data['server'] = WebsiteManager.ols - - else: - data = {} - data['status'] = 1 - data['server'] = WebsiteManager.lsws - - json_data = json.dumps(data) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'saveStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def switchServer(self, userID=None, data=None): - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - domainName = data['domainName'] - phpVersion = data['phpSelection'] - server = data['server'] - - if ACLManager.checkOwnership(domainName, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson() - - tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " switchServer --phpVersion '" + phpVersion + "' --server " + str( - server) + " --virtualHostName " + domainName + " --tempStatusPath " + tempStatusPath - ProcessUtilities.popenExecutioner(execPath) - - time.sleep(3) - - data_ret = {'status': 1, 'tempStatusPath': tempStatusPath} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def tuneSettings(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - domainName = data['domainName'] - pmMaxChildren = data['pmMaxChildren'] - pmStartServers = data['pmStartServers'] - pmMinSpareServers = data['pmMinSpareServers'] - pmMaxSpareServers = data['pmMaxSpareServers'] - phpPath = data['phpPath'] - - if ACLManager.checkOwnership(domainName, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson() - - if int(pmStartServers) < int(pmMinSpareServers) or int(pmStartServers) > int(pmMinSpareServers): - data_ret = {'status': 0, - 'error_message': 'pm.start_servers must not be less than pm.min_spare_servers and not greater than pm.max_spare_servers.'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - if int(pmMinSpareServers) > int(pmMaxSpareServers): - data_ret = {'status': 0, - 'error_message': 'pm.max_spare_servers must not be less than pm.min_spare_servers'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - try: - website = Websites.objects.get(domain=domainName) - externalApp = website.externalApp - except: - website = ChildDomains.objects.get(domain=domainName) - externalApp = website.master.externalApp - - tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - - if ProcessUtilities.decideDistro() == ProcessUtilities.centos or ProcessUtilities.decideDistro() == ProcessUtilities.cent8: - sockPath = '/var/run/php-fpm/' - group = 'nobody' - else: - sockPath = '/var/run/php/' - group = 'nogroup' - - phpFPMConf = vhostConfs.phpFpmPoolReplace - phpFPMConf = phpFPMConf.replace('{externalApp}', externalApp) - phpFPMConf = phpFPMConf.replace('{pmMaxChildren}', pmMaxChildren) - phpFPMConf = phpFPMConf.replace('{pmStartServers}', pmStartServers) - phpFPMConf = phpFPMConf.replace('{pmMinSpareServers}', pmMinSpareServers) - phpFPMConf = phpFPMConf.replace('{pmMaxSpareServers}', pmMaxSpareServers) - phpFPMConf = phpFPMConf.replace('{www}', "".join(re.findall("[a-zA-Z]+", domainName))[:7]) - phpFPMConf = phpFPMConf.replace('{Sock}', domainName) - phpFPMConf = phpFPMConf.replace('{sockPath}', sockPath) - phpFPMConf = phpFPMConf.replace('{group}', group) - - writeToFile = open(tempStatusPath, 'w') - writeToFile.writelines(phpFPMConf) - writeToFile.close() - - command = 'sudo mv %s %s' % (tempStatusPath, phpPath) - ProcessUtilities.executioner(command) - - phpPath = phpPath.split('/') - - if os.path.exists(ProcessUtilities.debugPath): - logging.CyberCPLogFileWriter.writeToFile(f'PHP path in tune settings {phpPath}') - - if ProcessUtilities.decideDistro() == ProcessUtilities.centos or ProcessUtilities.decideDistro() == ProcessUtilities.cent8: - if phpPath[1] == 'etc': - phpVersion = phpPath[4][3] + phpPath[4][4] - phpVersion = f'PHP {phpPath[4][3]}.{phpPath[4][4]}' - else: - phpVersion = phpPath[3][3] + phpPath[3][4] - phpVersion = f'PHP {phpPath[3][3]}.{phpPath[3][4]}' - else: - phpVersion = f'PHP {phpPath[2]}' - - # php = PHPManager.getPHPString(phpVersion) - - if os.path.exists(ProcessUtilities.debugPath): - logging.CyberCPLogFileWriter.writeToFile(f'PHP Version in tune settings {phpVersion}') - - phpService = ApacheVhost.DecideFPMServiceName(phpVersion) - - if os.path.exists(ProcessUtilities.debugPath): - logging.CyberCPLogFileWriter.writeToFile(f'PHP service in tune settings {phpService}') - - command = f"systemctl stop {phpService}" - ProcessUtilities.normalExecutioner(command) - - command = f"systemctl restart {phpService}" - ProcessUtilities.normalExecutioner(command) - - data_ret = {'status': 1} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def sshAccess(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - website = Websites.objects.get(domain=self.domain) - externalApp = website.externalApp - - proc = httpProc(request, 'websiteFunctions/sshAccess.html', - {'domainName': self.domain, 'externalApp': externalApp}) - return proc.render() - - def saveSSHAccessChanges(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - website = Websites.objects.get(domain=self.domain) - - # if website.externalApp != data['externalApp']: - # data_ret = {'status': 0, 'error_message': 'External app mis-match.'} - # json_data = json.dumps(data_ret) - # return HttpResponse(json_data) - - uBuntuPath = '/etc/lsb-release' - - if os.path.exists(uBuntuPath): - command = "echo '%s:%s' | chpasswd" % (website.externalApp, data['password']) - else: - command = 'echo "%s" | passwd --stdin %s' % (data['password'], website.externalApp) - - ProcessUtilities.executioner(command) - - data_ret = {'status': 1, 'error_message': 'None', 'LinuxUser': website.externalApp} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def setupStaging(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - website = Websites.objects.get(domain=self.domain) - externalApp = website.externalApp - - proc = httpProc(request, 'websiteFunctions/setupStaging.html', - {'domainName': self.domain, 'externalApp': externalApp}) - return proc.render() - - def startCloning(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['masterDomain'] - - if not validators.domain(self.domain): - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Invalid domain."} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - if not validators.domain(data['domainName']): - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Invalid domain."} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - extraArgs = {} - extraArgs['domain'] = data['domainName'] - extraArgs['masterDomain'] = data['masterDomain'] - extraArgs['admin'] = admin - - tempStatusPath = "/tmp/" + str(randint(1000, 9999)) - writeToFile = open(tempStatusPath, 'a') - message = 'Cloning process has started..,5' - writeToFile.write(message) - writeToFile.close() - - extraArgs['tempStatusPath'] = tempStatusPath - - st = StagingSetup('startCloning', extraArgs) - st.start() - - data_ret = {'status': 1, 'error_message': 'None', 'tempStatusPath': tempStatusPath} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def syncToMaster(self, request=None, userID=None, data=None, childDomain=None): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - website = Websites.objects.get(domain=self.domain) - externalApp = website.externalApp - - proc = httpProc(request, 'websiteFunctions/syncMaster.html', - {'domainName': self.domain, 'externalApp': externalApp, 'childDomain': childDomain}) - return proc.render() - - def startSync(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if not validators.domain(data['childDomain']): - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Invalid domain."} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - self.domain = data['childDomain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - extraArgs = {} - extraArgs['childDomain'] = data['childDomain'] - try: - extraArgs['eraseCheck'] = data['eraseCheck'] - except: - extraArgs['eraseCheck'] = False - try: - extraArgs['dbCheck'] = data['dbCheck'] - except: - extraArgs['dbCheck'] = False - try: - extraArgs['copyChanged'] = data['copyChanged'] - except: - extraArgs['copyChanged'] = False - - extraArgs['admin'] = admin - - tempStatusPath = "/tmp/" + str(randint(1000, 9999)) - writeToFile = open(tempStatusPath, 'a') - message = 'Syncing process has started..,5' - writeToFile.write(message) - writeToFile.close() - - extraArgs['tempStatusPath'] = tempStatusPath - - st = StagingSetup('startSyncing', extraArgs) - st.start() - - data_ret = {'status': 1, 'error_message': 'None', 'tempStatusPath': tempStatusPath} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def convertDomainToSite(self, userID=None, request=None): - try: - - extraArgs = {} - extraArgs['request'] = request - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - background = ApplicationInstaller('convertDomainToSite', extraArgs) - background.start() - - data_ret = {'status': 1, 'createWebSiteStatus': 1, 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def manageGIT(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - try: - website = Websites.objects.get(domain=self.domain) - folders = ['/home/%s/public_html' % (self.domain)] - - databases = website.databases_set.all() - - # for database in databases: - # basePath = '/var/lib/mysql/' - # folders.append('%s%s' % (basePath, database.dbName)) - except: - - self.childWebsite = ChildDomains.objects.get(domain=self.domain) - - folders = [self.childWebsite.path] - - databases = self.childWebsite.master.databases_set.all() - - # for database in databases: - # basePath = '/var/lib/mysql/' - # folders.append('%s%s' % (basePath, database.dbName)) - - proc = httpProc(request, 'websiteFunctions/manageGIT.html', - {'domainName': self.domain, 'folders': folders}) - return proc.render() - - def folderCheck(self): - - try: - - domainPath = '/home/%s/public_html' % (self.domain) - vhRoot = '/home/%s' % (self.domain) - vmailPath = '/home/vmail/%s' % (self.domain) - - ## - - try: - - website = Websites.objects.get(domain=self.domain) - - self.masterWebsite = website - self.masterDomain = website.domain - externalApp = website.externalApp - self.externalAppLocal = website.externalApp - self.adminEmail = website.adminEmail - self.firstName = website.admin.firstName - self.lastName = website.admin.lastName - - self.home = 0 - if self.folder == '/home/%s/public_html' % (self.domain): - self.home = 1 - - except: - - website = ChildDomains.objects.get(domain=self.domain) - self.masterWebsite = website.master - self.masterDomain = website.master.domain - externalApp = website.master.externalApp - self.externalAppLocal = website.master.externalApp - self.adminEmail = website.master.adminEmail - self.firstName = website.master.admin.firstName - self.lastName = website.master.admin.lastName - - self.home = 0 - if self.folder == website.path: - self.home = 1 - - ### Fetch git configurations - - self.confCheck = 1 - - gitConfFolder = '/home/cyberpanel/git' - gitConFile = '%s/%s' % (gitConfFolder, self.masterDomain) - - if not os.path.exists(gitConfFolder): - os.mkdir(gitConfFolder) - - if not os.path.exists(gitConFile): - os.mkdir(gitConFile) - - if os.path.exists(gitConFile): - files = os.listdir(gitConFile) - - if len(files) >= 1: - for file in files: - self.finalFile = '%s/%s' % (gitConFile, file) - - gitConf = json.loads(open(self.finalFile, 'r').read()) - - if gitConf['folder'] == self.folder: - - self.autoCommitCurrent = gitConf['autoCommit'] - self.autoPushCurrent = gitConf['autoPush'] - self.emailLogsCurrent = gitConf['emailLogs'] - try: - self.commands = gitConf['commands'] - except: - self.commands = "Add Commands to run after every commit, separate commands using comma." - - try: - self.webhookCommandCurrent = gitConf['webhookCommand'] - except: - self.webhookCommandCurrent = "False" - - self.confCheck = 0 - break - - if self.confCheck: - self.autoCommitCurrent = 'Never' - self.autoPushCurrent = 'Never' - self.emailLogsCurrent = 'False' - self.webhookCommandCurrent = 'False' - self.commands = "Add Commands to run after every commit, separate commands using comma." - - ## - - if self.folder == domainPath: - self.externalApp = externalApp - return 1 - - ## - - if self.folder == vhRoot: - self.externalApp = externalApp - return 1 - - ## - - try: - childDomain = ChildDomains.objects.get(domain=self.domain) - - if self.folder == childDomain.path: - self.externalApp = externalApp - return 1 - - except: - pass - - ## - - if self.folder == vmailPath: - self.externalApp = 'vmail' - return 1 - - try: - - for database in website.databases_set.all(): - self.externalApp = 'mysql' - basePath = '/var/lib/mysql/' - dbPath = '%s%s' % (basePath, database.dbName) - - if self.folder == dbPath: - return 1 - except: - for database in website.master.databases_set.all(): - self.externalApp = 'mysql' - basePath = '/var/lib/mysql/' - dbPath = '%s%s' % (basePath, database.dbName) - - if self.folder == dbPath: - return 1 - - return 0 - - - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile('%s. [folderCheck:3002]' % (str(msg))) - - return 0 - - def fetchFolderDetails(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - self.folder = data['folder'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - if self.folderCheck(): - pass - else: - return ACLManager.loadErrorJson() - - gitPath = '%s/.git' % (self.folder) - command = 'ls -la %s' % (gitPath) - - if ProcessUtilities.outputExecutioner(command, self.externalAppLocal).find( - 'No such file or directory') > -1: - - command = 'cat /home/%s/.ssh/%s.pub' % (self.masterDomain, self.externalAppLocal) - deploymentKey = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) - - if deploymentKey.find('No such file or directory') > -1: - command = "ssh-keygen -f /home/%s/.ssh/%s -t rsa -N ''" % (self.masterDomain, self.externalAppLocal) - ProcessUtilities.executioner(command, self.externalAppLocal) - - command = 'cat /home/%s/.ssh/%s.pub' % (self.masterDomain, self.externalAppLocal) - deploymentKey = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) - - data_ret = {'status': 1, 'repo': 0, 'deploymentKey': deploymentKey, 'home': self.home} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - - ## Find git branches - - command = 'git -C %s branch' % (self.folder) - branches = ProcessUtilities.outputExecutioner(command, self.externalAppLocal).split('\n')[:-1] - - ## Fetch key - - command = 'cat /home/%s/.ssh/%s.pub' % (self.domain, self.externalAppLocal) - deploymentKey = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) - - if deploymentKey.find('No such file or directory') > -1: - command = "ssh-keygen -f /home/%s/.ssh/%s -t rsa -N ''" % (self.masterDomain, self.externalAppLocal) - ProcessUtilities.executioner(command, self.externalAppLocal) - - command = 'cat /home/%s/.ssh/%s.pub' % (self.masterDomain, self.externalAppLocal) - deploymentKey = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) - - ## Find Remote if any - - command = 'git -C %s remote -v' % (self.folder) - remoteResult = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) - - remote = 1 - if remoteResult.find('origin') == -1: - remote = 0 - remoteResult = 'Remote currently not set.' - - ## Find Total commits on current branch - - command = 'git -C %s rev-list --count HEAD' % (self.folder) - totalCommits = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) - - if totalCommits.find('fatal') > -1: - totalCommits = '0' - - ## - - port = ProcessUtilities.fetchCurrentPort() - - webHookURL = 'https://%s:%s/websites/%s/webhook' % (ACLManager.fetchIP(), port, self.domain) - - data_ret = {'status': 1, 'repo': 1, 'finalBranches': branches, 'deploymentKey': deploymentKey, - 'remote': remote, 'remoteResult': remoteResult, 'totalCommits': totalCommits, - 'home': self.home, - 'webHookURL': webHookURL, 'autoCommitCurrent': self.autoCommitCurrent, - 'autoPushCurrent': self.autoPushCurrent, 'emailLogsCurrent': self.emailLogsCurrent, - 'commands': self.commands, "webhookCommandCurrent": self.webhookCommandCurrent} - - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def initRepo(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - self.folder = data['folder'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - if self.folderCheck(): - pass - else: - return ACLManager.loadErrorJson() - - website = Websites.objects.get(domain=self.masterDomain) - - command = 'git -C %s init' % (self.folder) - result = ProcessUtilities.outputExecutioner(command, website.externalApp) - - if result.find('Initialized empty Git repository in') > -1: - - command = 'git -C %s config --local user.email %s' % (self.folder, self.adminEmail) - ProcessUtilities.executioner(command, website.externalApp) - - command = 'git -C %s config --local user.name "%s %s"' % ( - self.folder, self.firstName, self.lastName) - ProcessUtilities.executioner(command, website.externalApp) - - ## Fix permissions - - # from filemanager.filemanager import FileManager - # - # fm = FileManager(None, None) - # fm.fixPermissions(self.masterDomain) - - data_ret = {'status': 1} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - data_ret = {'status': 0, 'error_message': result} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def setupRemote(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - self.folder = data['folder'] - self.gitHost = data['gitHost'] - self.gitUsername = data['gitUsername'] - self.gitReponame = data['gitReponame'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - ## Security checks - - if self.folderCheck(): - pass - else: - return ACLManager.loadErrorJson() - - if self.gitHost.find(':') > -1: - gitHostDomain = self.gitHost.split(':')[0] - gitHostPort = self.gitHost.split(':')[1] - - if not validators.domain(gitHostDomain): - return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') - - try: - gitHostPort = int(gitHostPort) - except: - return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') - - else: - if not validators.domain(self.gitHost): - return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') - - if ACLManager.validateInput(self.gitUsername) and ACLManager.validateInput(self.gitReponame): - pass - else: - return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') - - ### set default ssh key - - command = 'git -C %s config --local core.sshCommand "ssh -i /home/%s/.ssh/%s -o "StrictHostKeyChecking=no""' % ( - self.folder, self.masterDomain, self.externalAppLocal) - ProcessUtilities.executioner(command, self.externalAppLocal) - - ## Check if remote exists - - command = 'git -C %s remote -v' % (self.folder) - remoteResult = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) - - ## Set new remote - - if remoteResult.find('origin') == -1: - command = 'git -C %s remote add origin git@%s:%s/%s.git' % ( - self.folder, self.gitHost, self.gitUsername, self.gitReponame) - else: - command = 'git -C %s remote set-url origin git@%s:%s/%s.git' % ( - self.folder, self.gitHost, self.gitUsername, self.gitReponame) - - possibleError = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) - - ## Check if set correctly. - - command = 'git -C %s remote -v' % (self.folder) - remoteResult = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) - - if remoteResult.find(self.gitUsername) > -1: - - # ## Fix permissions - # - # from filemanager.filemanager import FileManager - # - # fm = FileManager(None, None) - # fm.fixPermissions(self.masterDomain) - - data_ret = {'status': 1} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - data_ret = {'status': 0, 'error_message': possibleError} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def changeGitBranch(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - self.folder = data['folder'] - self.branchName = data['branchName'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - if self.folderCheck(): - pass - else: - return ACLManager.loadErrorJson() - - ## Security check - - if ACLManager.validateInput(self.branchName): - pass - else: - return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') - - if self.branchName.find('*') > -1: - data_ret = {'status': 0, 'commandStatus': 'Already on this branch.', - 'error_message': 'Already on this branch.'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - self.externalApp = ACLManager.FetchExternalApp(self.domain) - - command = 'git -C %s checkout %s' % (self.folder, self.branchName.strip(' ')) - commandStatus = ProcessUtilities.outputExecutioner(command, self.externalApp) - - if commandStatus.find('Switched to branch') > -1: - - # ## Fix permissions - # - # from filemanager.filemanager import FileManager - # - # fm = FileManager(None, None) - # fm.fixPermissions(self.masterDomain) - - data_ret = {'status': 1, 'commandStatus': commandStatus + 'Refreshing page in 3 seconds..'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - data_ret = {'status': 0, 'error_message': 'Failed to change branch', 'commandStatus': commandStatus} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def createNewBranch(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - self.folder = data['folder'] - self.newBranchName = data['newBranchName'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - if self.folderCheck(): - pass - else: - return ACLManager.loadErrorJson() - - ## Security check - - if ACLManager.validateInput(self.newBranchName): - pass - else: - return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') - - ## - - self.externalApp = ACLManager.FetchExternalApp(self.domain) - - command = 'git -C %s checkout -b "%s"' % (self.folder, self.newBranchName) - commandStatus = ProcessUtilities.outputExecutioner(command, self.externalApp) - - if commandStatus.find(self.newBranchName) > -1: - - # ## Fix permissions - # - # from filemanager.filemanager import FileManager - # - # fm = FileManager(None, None) - # fm.fixPermissions(self.masterDomain) - - data_ret = {'status': 1, 'commandStatus': commandStatus} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - data_ret = {'status': 0, 'error_message': 'Failed to create branch', 'commandStatus': commandStatus} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def commitChanges(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - self.folder = data['folder'] - self.commitMessage = data['commitMessage'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - if self.folderCheck(): - pass - else: - return ACLManager.loadErrorJson('status', 0) - - # security check - - if ACLManager.validateInput(self.commitMessage): - pass - else: - return ACLManager.loadErrorJson() - - self.externalApp = ACLManager.FetchExternalApp(self.domain) - - ## Check if remote exists - - command = 'git -C %s add -A' % (self.folder) - ProcessUtilities.outputExecutioner(command, self.externalApp) - - command = 'git -C %s commit -m "%s"' % (self.folder, self.commitMessage.replace('"', '')) - commandStatus = ProcessUtilities.outputExecutioner(command, self.externalApp) - - if commandStatus.find('nothing to commit') == -1: - - try: - if self.commands != 'NONE': - - GitLogs(owner=self.masterWebsite, type='INFO', - message='Running commands after successful git commit..').save() - - if self.commands.find('\n') > -1: - commands = self.commands.split('\n') - - for command in commands: - GitLogs(owner=self.masterWebsite, type='INFO', - message='Running: %s' % (command)).save() - - result = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) - GitLogs(owner=self.masterWebsite, type='INFO', - message='Result: %s' % (result)).save() - else: - GitLogs(owner=self.masterWebsite, type='INFO', - message='Running: %s' % (self.commands)).save() - - result = ProcessUtilities.outputExecutioner(self.commands, self.externalAppLocal) - GitLogs(owner=self.masterWebsite, type='INFO', - message='Result: %s' % (result)).save() - - GitLogs(owner=self.masterWebsite, type='INFO', - message='Finished running commands.').save() - except: - pass - - ## Fix permissions - - # from filemanager.filemanager import FileManager - # - # fm = FileManager(None, None) - # fm.fixPermissions(self.masterDomain) - - data_ret = {'status': 1, 'commandStatus': commandStatus} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - data_ret = {'status': 0, 'error_message': 'Nothing to commit.', 'commandStatus': commandStatus} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg), 'commandStatus': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def gitPull(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - self.folder = data['folder'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - if self.folderCheck(): - pass - else: - return ACLManager.loadErrorJson() - - self.externalApp = ACLManager.FetchExternalApp(self.domain) - - ### set default ssh key - - command = 'git -C %s config --local core.sshCommand "ssh -i /home/%s/.ssh/%s -o "StrictHostKeyChecking=no""' % ( - self.folder, self.masterDomain, self.externalAppLocal) - ProcessUtilities.executioner(command, self.externalApp) - - ## Check if remote exists - - command = 'git -C %s pull' % (self.folder) - commandStatus = ProcessUtilities.outputExecutioner(command, self.externalApp) - - if commandStatus.find('Already up to date') == -1: - - ## Fix permissions - - # from filemanager.filemanager import FileManager - # - # fm = FileManager(None, None) - # fm.fixPermissions(self.masterDomain) - - data_ret = {'status': 1, 'commandStatus': commandStatus} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - data_ret = {'status': 0, 'error_message': 'Pull not required.', 'commandStatus': commandStatus} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def gitPush(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - self.folder = data['folder'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - if self.folderCheck(): - pass - else: - return ACLManager.loadErrorJson() - - self.externalApp = ACLManager.FetchExternalApp(self.domain) - - ### set default ssh key - - command = 'git -C %s config --local core.sshCommand "ssh -i /home/%s/.ssh/%s -o "StrictHostKeyChecking=no""' % ( - self.folder, self.masterDomain, self.externalAppLocal) - ProcessUtilities.executioner(command, self.externalApp) - - ## - - command = 'git -C %s push' % (self.folder) - commandStatus = ProcessUtilities.outputExecutioner(command, self.externalApp, False) - - if commandStatus.find('has no upstream branch') > -1: - command = 'git -C %s rev-parse --abbrev-ref HEAD' % (self.folder) - currentBranch = ProcessUtilities.outputExecutioner(command, self.externalApp, False).rstrip('\n') - - if currentBranch.find('fatal: ambiguous argument') > -1: - data_ret = {'status': 0, 'error_message': 'You need to commit first.', - 'commandStatus': 'You need to commit first.'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - command = 'git -C %s push --set-upstream origin %s' % (self.folder, currentBranch) - commandStatus = ProcessUtilities.outputExecutioner(command, self.externalApp, False) - - if commandStatus.find('Everything up-to-date') == -1 and commandStatus.find( - 'rejected') == -1 and commandStatus.find('Permission denied') == -1: - data_ret = {'status': 1, 'commandStatus': commandStatus} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - data_ret = {'status': 0, 'error_message': 'Push failed.', 'commandStatus': commandStatus} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg), 'commandStatus': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def attachRepoGIT(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - self.folder = data['folder'] - self.gitHost = data['gitHost'] - self.gitUsername = data['gitUsername'] - self.gitReponame = data['gitReponame'] - - try: - self.overrideData = data['overrideData'] - except: - self.overrideData = False - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - if self.folderCheck(): - pass - else: - return ACLManager.loadErrorJson() - - if self.gitHost.find(':') > -1: - gitHostDomain = self.gitHost.split(':')[0] - gitHostPort = self.gitHost.split(':')[1] - - if not validators.domain(gitHostDomain): - return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') - - try: - gitHostPort = int(gitHostPort) - except: - return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') - else: - if not validators.domain(self.gitHost): - return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') - - ## Security check - - if ACLManager.validateInput(self.gitUsername) and ACLManager.validateInput(self.gitReponame): - pass - else: - return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') - - ## - - self.externalApp = ACLManager.FetchExternalApp(self.domain) - - if self.overrideData: - command = 'rm -rf %s' % (self.folder) - ProcessUtilities.executioner(command, self.externalApp) - - ## Set defauly key - - command = 'git config --global core.sshCommand "ssh -i /home/%s/.ssh/%s -o "StrictHostKeyChecking=no""' % ( - self.masterDomain, self.externalAppLocal) - ProcessUtilities.executioner(command, self.externalApp) - - ## - - command = 'git clone git@%s:%s/%s.git %s' % (self.gitHost, self.gitUsername, self.gitReponame, self.folder) - commandStatus = ProcessUtilities.outputExecutioner(command, self.externalApp) - - if commandStatus.find('already exists') == -1 and commandStatus.find('Permission denied') == -1: - - # from filemanager.filemanager import FileManager - # - # fm = FileManager(None, None) - # fm.fixPermissions(self.masterDomain) - - command = 'git -C %s config --local user.email %s' % (self.folder, self.adminEmail) - ProcessUtilities.executioner(command, self.externalApp) - - command = 'git -C %s config --local user.name "%s %s"' % (self.folder, self.firstName, self.lastName) - ProcessUtilities.executioner(command, self.externalApp) - - data_ret = {'status': 1, 'commandStatus': commandStatus} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - else: - - # from filemanager.filemanager import FileManager - # - # fm = FileManager(None, None) - # fm.fixPermissions(self.masterDomain) - - data_ret = {'status': 0, 'error_message': 'Failed to clone.', 'commandStatus': commandStatus} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def removeTracking(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - self.folder = data['folder'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - if self.folderCheck(): - pass - else: - return ACLManager.loadErrorJson() - - self.externalApp = ACLManager.FetchExternalApp(self.domain) - - command = 'rm -rf %s/.git' % (self.folder) - ProcessUtilities.executioner(command, self.externalApp) - - gitConfFolder = '/home/cyberpanel/git' - gitConFile = '%s/%s' % (gitConfFolder, self.masterDomain) - finalFile = '%s/%s' % (gitConFile, self.folder.split('/')[-1]) - - command = 'rm -rf %s' % (finalFile) - ProcessUtilities.outputExecutioner(command, self.externalApp) - - ## Fix permissions - - # from filemanager.filemanager import FileManager - # - # fm = FileManager(None, None) - # fm.fixPermissions(self.masterDomain) - - data_ret = {'status': 1} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def fetchGitignore(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - self.folder = data['folder'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - if self.folderCheck(): - pass - else: - return ACLManager.loadErrorJson() - - command = 'cat %s/.gitignore' % (self.folder) - gitIgnoreContent = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) - - if gitIgnoreContent.find('No such file or directory') > -1: - gitIgnoreContent = 'File is currently empty.' - - data_ret = {'status': 1, 'gitIgnoreContent': gitIgnoreContent} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def saveGitIgnore(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - self.folder = data['folder'] - self.gitIgnoreContent = data['gitIgnoreContent'] - - tempPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - if self.folderCheck(): - pass - else: - return ACLManager.loadErrorJson() - - ## Write to temp file - - writeToFile = open(tempPath, 'w') - writeToFile.write(self.gitIgnoreContent) - writeToFile.close() - - ## Move to original file - - self.externalApp = ACLManager.FetchExternalApp(self.domain) - - command = 'mv %s %s/.gitignore' % (tempPath, self.folder) - ProcessUtilities.executioner(command, self.externalApp) - - ## Fix permissions - - # from filemanager.filemanager import FileManager - # - # fm = FileManager(None, None) - # fm.fixPermissions(self.masterDomain) - - data_ret = {'status': 1} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def fetchCommits(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - self.folder = data['folder'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - if self.folderCheck(): - pass - else: - return ACLManager.loadErrorJson() - - initCommand = """log --pretty=format:"%h|%s|%cn|%cd" -50""" - - self.externalApp = ACLManager.FetchExternalApp(self.domain) - - command = 'git -C %s %s' % (self.folder, initCommand) - commits = ProcessUtilities.outputExecutioner(command, self.externalApp).split('\n') - - json_data = "[" - checker = 0 - id = 1 - - for commit in commits: - cm = commit.split('|') - - dic = {'id': str(id), 'commit': cm[0], 'message': cm[1].replace('"', "'"), 'name': cm[2], 'date': cm[3]} - id = id + 1 - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - - commits = json_data + ']' - - data_ret = {'status': 1, 'commits': commits} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except IndexError: - data_ret = {'status': 0, 'error_message': 'No commits found.'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def fetchFiles(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - self.folder = data['folder'] - self.commit = data['commit'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - if self.folderCheck(): - pass - else: - return ACLManager.loadErrorJson() - - ## Security check - - if ACLManager.validateInput(self.commit): - pass - else: - return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') - - ## - - self.externalApp = ACLManager.FetchExternalApp(self.domain) - - command = 'git -C %s diff-tree --no-commit-id --name-only -r %s' % (self.folder, self.commit) - files = ProcessUtilities.outputExecutioner(command, self.externalApp).split('\n') - - FinalFiles = [] - - for items in files: - if items != '': - FinalFiles.append(items.rstrip('\n').lstrip('\n')) - - data_ret = {'status': 1, 'files': FinalFiles} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def fetchChangesInFile(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - self.folder = data['folder'] - self.file = data['file'] - self.commit = data['commit'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - if self.folderCheck(): - pass - else: - return ACLManager.loadErrorJson() - - ## security check - - if ACLManager.validateInput(self.commit) and self.file.find('..') == -1: - pass - else: - return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') - - self.externalApp = ACLManager.FetchExternalApp(self.domain) - - command = 'git -C %s show %s -- %s/%s' % ( - self.folder, self.commit, self.folder, self.file.strip('\n').strip(' ')) - fileChangedContent = ProcessUtilities.outputExecutioner(command, self.externalApp).split('\n') - - initialNumber = 0 - ## Find initial line numbers - for items in fileChangedContent: - if len(items) == 0: - initialNumber = initialNumber + 1 - elif items[0] == '@': - break - else: - initialNumber = initialNumber + 1 - - try: - lineNumber = int(fileChangedContent[initialNumber].split('+')[1].split(',')[0]) - except: - lineNumber = int(fileChangedContent[initialNumber].split('+')[1].split(' ')[0]) - - fileLen = len(fileChangedContent) - finalConent = '%s

    %s

    ' % ( - '#', fileChangedContent[initialNumber]) - - for i in range(initialNumber + 1, fileLen - 1): - if fileChangedContent[i][0] == '@': - lineNumber = int(fileChangedContent[i].split('+')[1].split(',')[0]) - finalConent = finalConent + '%s

    %s

    ' % ( - '#', fileChangedContent[i]) - continue - - else: - if fileChangedContent[i][0] == '+': - content = '

    %s

    ' % ( - fileChangedContent[i].replace('<', "<").replace('>', ">")) - finalConent = finalConent + '%s%s' % ( - str(lineNumber), content) - lineNumber = lineNumber + 1 - elif fileChangedContent[i][0] == '-': - content = '

    %s

    ' % ( - fileChangedContent[i].replace('<', "<").replace('>', ">")) - finalConent = finalConent + '%s%s' % ( - str(lineNumber), content) - lineNumber = lineNumber + 1 - else: - content = '

    %s

    ' % (fileChangedContent[i].replace('<', "<").replace('>', ">")) - finalConent = finalConent + '%s%s' % ( - str(lineNumber), content) - lineNumber = lineNumber + 1 - - data_ret = {'status': 1, 'fileChangedContent': finalConent} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except IndexError: - data_ret = {'status': 0, 'error_message': 'Not a text file.'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def saveGitConfigurations(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - self.folder = data['folder'] - - dic = {} - - dic['domain'] = self.domain - - dic['autoCommit'] = data['autoCommit'] - - try: - dic['autoPush'] = data['autoPush'] - except: - dic['autoPush'] = 'Never' - - try: - dic['emailLogs'] = data['emailLogs'] - except: - dic['emailLogs'] = False - - try: - dic['commands'] = data['commands'] - except: - dic['commands'] = 'NONE' - - try: - dic['webhookCommand'] = data['webhookCommand'] - except: - dic['webhookCommand'] = False - - dic['folder'] = self.folder - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - if self.folderCheck(): - pass - else: - return ACLManager.loadErrorJson() - - ## - - if self.confCheck == 1: - gitConfFolder = '/home/cyberpanel/git' - gitConFile = '%s/%s' % (gitConfFolder, self.masterDomain) - self.finalFile = '%s/%s' % (gitConFile, str(randint(1000, 9999))) - - if not os.path.exists(gitConfFolder): - os.mkdir(gitConfFolder) - - if not os.path.exists(gitConFile): - os.mkdir(gitConFile) - - writeToFile = open(self.finalFile, 'w') - writeToFile.write(json.dumps(dic)) - writeToFile.close() - - data_ret = {'status': 1} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def getLogsInJson(self, logs): - json_data = "[" - checker = 0 - counter = 1 - - for items in logs: - dic = {'type': items.type, 'date': items.date.strftime('%m.%d.%Y_%H-%M-%S'), 'message': items.message} - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - counter = counter + 1 - - json_data = json_data + ']' - return json_data - - def fetchGitLogs(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - self.folder = data['folder'] - recordsToShow = int(data['recordsToShow']) - page = int(data['page']) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - if self.folderCheck(): - pass - else: - return ACLManager.loadErrorJson() - - logs = self.masterWebsite.gitlogs_set.all().order_by('-id') - - from s3Backups.s3Backups import S3Backups - - pagination = S3Backups.getPagination(len(logs), recordsToShow) - endPageNumber, finalPageNumber = S3Backups.recordsPointer(page, recordsToShow) - jsonData = self.getLogsInJson(logs[finalPageNumber:endPageNumber]) - - data_ret = {'status': 1, 'logs': jsonData, 'pagination': pagination} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except IndexError: - data_ret = {'status': 0, 'error_message': 'Not a text file.'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def webhook(self, domain, data=None): - try: - - self.domain = domain - - ### set default ssh key - - try: - web = Websites.objects.get(domain=self.domain) - self.web = web - self.folder = '/home/%s/public_html' % (domain) - self.masterDomain = domain - except: - web = ChildDomains.objects.get(domain=self.domain) - self.folder = web.path - self.masterDomain = web.master.domain - self.web = web.master - - ## Check if remote exists - - self.externalApp = ACLManager.FetchExternalApp(self.domain) - - command = 'git -C %s pull' % (self.folder) - commandStatus = ProcessUtilities.outputExecutioner(command, self.externalApp) - - if commandStatus.find('Already up to date') == -1: - message = '[Webhook Fired] Status: %s.' % (commandStatus) - GitLogs(owner=self.web, type='INFO', message=message).save() - - ### Fetch git configurations - - found = 0 - - gitConfFolder = '/home/cyberpanel/git' - gitConFile = '%s/%s' % (gitConfFolder, self.masterDomain) - - if not os.path.exists(gitConfFolder): - os.mkdir(gitConfFolder) - - if not os.path.exists(gitConFile): - os.mkdir(gitConFile) - - if os.path.exists(gitConFile): - files = os.listdir(gitConFile) - - if len(files) >= 1: - for file in files: - finalFile = '%s/%s' % (gitConFile, file) - gitConf = json.loads(open(finalFile, 'r').read()) - if gitConf['folder'] == self.folder: - found = 1 - break - if found: - try: - if gitConf['webhookCommand']: - if gitConf['commands'] != 'NONE': - - GitLogs(owner=self.web, type='INFO', - message='Running commands after successful git commit..').save() - - if gitConf['commands'].find('\n') > -1: - commands = gitConf['commands'].split('\n') - - for command in commands: - GitLogs(owner=self.web, type='INFO', - message='Running: %s' % (command)).save() - - result = ProcessUtilities.outputExecutioner(command, self.web.externalApp, None, - self.folder) - GitLogs(owner=self.web, type='INFO', - message='Result: %s' % (result)).save() - else: - GitLogs(owner=self.web, type='INFO', - message='Running: %s' % (gitConf['commands'])).save() - - result = ProcessUtilities.outputExecutioner(gitConf['commands'], - self.web.externalApp, None, self.folder) - GitLogs(owner=self.web, type='INFO', - message='Result: %s' % (result)).save() - - GitLogs(owner=self.web, type='INFO', - message='Finished running commands.').save() - except: - pass - - ## Fix permissions - - # from filemanager.filemanager import FileManager - # - # fm = FileManager(None, None) - # fm.fixPermissions(self.masterDomain) - - data_ret = {'status': 1, 'commandStatus': commandStatus} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - message = '[Webhook Fired] Status: %s.' % (commandStatus) - GitLogs(owner=self.web, type='ERROR', message=message).save() - data_ret = {'status': 0, 'error_message': 'Pull not required.', 'commandStatus': commandStatus} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def getSSHConfigs(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - domain = data['domain'] - website = Websites.objects.get(domain=domain) - - if ACLManager.checkOwnership(domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - pathToKeyFile = "/home/%s/.ssh/authorized_keys" % (domain) - - cat = "cat " + pathToKeyFile - data = ProcessUtilities.outputExecutioner(cat, website.externalApp).split('\n') - - json_data = "[" - checker = 0 - - for items in data: - if items.find("ssh-rsa") > -1: - keydata = items.split(" ") - - try: - key = "ssh-rsa " + keydata[1][:50] + " .. " + keydata[2] - try: - userName = keydata[2][:keydata[2].index("@")] - except: - userName = keydata[2] - except: - key = "ssh-rsa " + keydata[1][:50] - userName = '' - - dic = {'userName': userName, - 'key': key, - } - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - - json_data = json_data + ']' - - final_json = json.dumps({'status': 1, 'error_message': "None", "data": json_data}) - return HttpResponse(final_json) - - except BaseException as msg: - final_dic = {'status': 0, 'error_message': str(msg)} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - def deleteSSHKey(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - domain = data['domain'] - - if ACLManager.checkOwnership(domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - key = data['key'] - pathToKeyFile = "/home/%s/.ssh/authorized_keys" % (domain) - website = Websites.objects.get(domain=domain) - - command = f'chown {website.externalApp}:{website.externalApp} {pathToKeyFile}' - ProcessUtilities.outputExecutioner(command) - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/firewallUtilities.py" - execPath = execPath + " deleteSSHKey --key '%s' --path %s" % (key, pathToKeyFile) - - output = ProcessUtilities.outputExecutioner(execPath, website.externalApp) - - if output.find("1,None") > -1: - final_dic = {'status': 1, 'delete_status': 1} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - else: - final_dic = {'status': 1, 'delete_status': 1, "error_mssage": output} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - except BaseException as msg: - final_dic = {'status': 0, 'delete_status': 0, 'error_mssage': str(msg)} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - def addSSHKey(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - domain = data['domain'] - website = Websites.objects.get(domain=domain) - - if ACLManager.checkOwnership(domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - key = data['key'] - pathToKeyFile = "/home/%s/.ssh/authorized_keys" % (domain) - - command = 'mkdir -p /home/%s/.ssh/' % (domain) - ProcessUtilities.executioner(command) - - command = 'chown %s:%s /home/%s/.ssh/' % (website.externalApp, website.externalApp, domain) - ProcessUtilities.executioner(command) - - tempPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - - writeToFile = open(tempPath, "w") - writeToFile.write(key) - writeToFile.close() - - execPath = "sudo /usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/firewallUtilities.py" - execPath = execPath + " addSSHKey --tempPath %s --path %s" % (tempPath, pathToKeyFile) - - output = ProcessUtilities.outputExecutioner(execPath) - - if output.find("1,None") > -1: - final_dic = {'status': 1, 'add_status': 1} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - else: - final_dic = {'status': 0, 'add_status': 0, "error_mssage": output} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - except BaseException as msg: - final_dic = {'status': 0, 'add_status': 0, 'error_mssage': str(msg)} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - def ApacheManager(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - phps = PHPManager.findPHPVersions() - apachePHPs = PHPManager.findApachePHPVersions() - - if ACLManager.CheckForPremFeature('all'): - apachemanager = 1 - else: - apachemanager = 0 - - proc = httpProc(request, 'websiteFunctions/ApacheManager.html', - {'domainName': self.domain, 'phps': phps, 'apachemanager': apachemanager, 'apachePHPs': apachePHPs}) - return proc.render() - - def saveApacheConfigsToFile(self, userID=None, data=None): - - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] != 1: - return ACLManager.loadErrorJson('configstatus', 0) - - configData = data['configData'] - self.domain = data['domainName'] - - mailUtilities.checkHome() - - tempPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - - vhost = open(tempPath, "w") - - vhost.write(configData) - - vhost.close() - - ## writing data temporary to file - - filePath = ApacheVhost.configBasePath + self.domain + '.conf' - - ## save configuration data - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " saveApacheConfigsToFile --path " + filePath + " --tempPath " + tempPath - - output = ProcessUtilities.outputExecutioner(execPath) - - if output.find("1,None") > -1: - status = {"status": 1} - final_json = json.dumps(status) - return HttpResponse(final_json) - else: - final_dic = {'status': 0, 'error_message': output} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - def CreateDockerPackage(self, request=None, userID=None, data=None, DeleteID=None): - Data = {} - - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - - try: - if DeleteID != None: - DockerPackagesDelete = DockerPackages.objects.get(pk=DeleteID) - DockerPackagesDelete.delete() - except: - pass - - Data['packages'] = DockerPackages.objects.all() - - proc = httpProc(request, 'websiteFunctions/CreateDockerPackage.html', - Data, 'createWebsite') - return proc.render() - - def AssignPackage(self, request=None, userID=None, data=None, DeleteID=None): - - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - - try: - if DeleteID != None: - DockerPackagesDelete = PackageAssignment.objects.get(pk=DeleteID) - DockerPackagesDelete.delete() - except: - pass - - adminNames = ACLManager.loadAllUsers(userID) - dockerpackages = DockerPackages.objects.all() - assignpackage = PackageAssignment.objects.all() - Data = {'adminNames': adminNames, 'DockerPackages': dockerpackages, 'assignpackage': assignpackage} - proc = httpProc(request, 'websiteFunctions/assignPackage.html', - Data, 'createWebsite') - return proc.render() - - def CreateDockersite(self, request=None, userID=None, data=None): - adminNames = ACLManager.loadAllUsers(userID) - Data = {'adminNames': adminNames} - - - if PackageAssignment.objects.all().count() == 0: - - name = 'Default' - cpu = 2 - Memory = 1024 - Bandwidth = '100' - disk = '100' - - saveobj = DockerPackages(Name=name, CPUs=cpu, Ram=Memory, Bandwidth=Bandwidth, DiskSpace=disk, config='') - saveobj.save() - - userobj = Administrator.objects.get(pk=1) - - sv = PackageAssignment(user=userobj, package=saveobj) - sv.save() - - proc = httpProc(request, 'websiteFunctions/CreateDockerSite.html', - Data, 'createWebsite') - return proc.render() - - def AddDockerpackage(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - - admin = Administrator.objects.get(pk=userID) - - name = data['name'] - cpu = data['cpu'] - Memory = data['Memory'] - Bandwidth = data['Bandwidth'] - disk = data['disk'] - - saveobj = DockerPackages(Name=name, CPUs=cpu, Ram=Memory, Bandwidth=Bandwidth, DiskSpace=disk, config='') - saveobj.save() - - status = {"status": 1, 'error_message': None} - final_json = json.dumps(status) - return HttpResponse(final_json) - except BaseException as msg: - final_dic = {'status': 0, 'error_message': str(msg)} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - def Getpackage(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - - admin = Administrator.objects.get(pk=userID) - id = data['id'] - - docker_package = DockerPackages.objects.get(pk=id) - - # Convert DockerPackages object to dictionary - package_data = { - 'Name': docker_package.Name, - 'CPU': docker_package.CPUs, - 'Memory': docker_package.Ram, - 'Bandwidth': docker_package.Bandwidth, - 'DiskSpace': docker_package.DiskSpace, - } - - rdata = {'obj': package_data} - - status = {"status": 1, 'error_message': rdata} - final_json = json.dumps(status) - return HttpResponse(final_json) - except BaseException as msg: - final_dic = {'status': 0, 'error_message': str(msg)} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - def Updatepackage(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - - admin = Administrator.objects.get(pk=userID) - id = data['id'] - CPU = data['CPU'] - RAM = data['RAM'] - Bandwidth = data['Bandwidth'] - DiskSpace = data['DiskSpace'] - - docker_package = DockerPackages.objects.get(pk=id) - - docker_package.CPUs = CPU - docker_package.Ram = RAM - docker_package.Bandwidth = Bandwidth - docker_package.DiskSpace = DiskSpace - docker_package.save() - - status = {"status": 1, 'error_message': None} - final_json = json.dumps(status) - return HttpResponse(final_json) - - except BaseException as msg: - final_dic = {'status': 0, 'error_message': str(msg)} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - def AddAssignment(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - - - admin = Administrator.objects.get(pk=userID) - - package = data['package'] - user = data['user'] - - userobj = Administrator.objects.get(userName=user) - - try: - delasg = PackageAssignment.objects.get(user=userobj) - delasg.delete() - except: - pass - - docker_package = DockerPackages.objects.get(pk=int(package)) - - sv = PackageAssignment(user=userobj, package=docker_package) - sv.save() - - status = {"status": 1, 'error_message': None} - final_json = json.dumps(status) - return HttpResponse(final_json) - - except BaseException as msg: - final_dic = {'status': 0, 'error_message': str(msg)} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - def submitDockerSiteCreation(self, userID=None, data=None): - try: - admin = Administrator.objects.get(pk=userID) - currentACL = ACLManager.loadedACL(userID) - - sitename = data['sitename'] - Owner = data['Owner'] - Domain = data['Domain'] - MysqlCPU = int(data['MysqlCPU']) - MYsqlRam = int(data['MYsqlRam']) - SiteCPU = int(data['SiteCPU']) - SiteRam = int(data['SiteRam']) - App = data['App'] - WPusername = data['WPusername'] - WPemal = data['WPemal'] - WPpasswd = data['WPpasswd'] - - if int(MYsqlRam) < 256: - final_dic = {'status': 0, 'error_message': 'Minimum MySQL ram should be 256MB.'} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - if int(SiteRam) < 256: - final_dic = {'status': 0, 'error_message': 'Minimum site ram should be 256MB.'} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - - pattern = r"^[a-z0-9][a-z0-9]*$" - - if re.match(pattern, sitename): - pass - else: - final_dic = {'status': 0, 'error_message': f'invalid site name "{sitename}": must consist only of lowercase alphanumeric characters, as well as start with a letter or number.'} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - loggedUser = Administrator.objects.get(pk=userID) - newOwner = Administrator.objects.get(userName=Owner) - - try: - pkaobj = PackageAssignment.objects.get(user=newOwner) - except: - final_dic = {'status': 0, 'error_message': str('Please assign package to selected user')} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - Dpkgobj = DockerPackages.objects.get(pk=pkaobj.package.id) - - pkg_cpu = Dpkgobj.CPUs - pkg_Ram = Dpkgobj.Ram - - totalcup = SiteCPU + MysqlCPU - totalRam = SiteRam + MYsqlRam - - if (totalcup > pkg_cpu): - final_dic = {'status': 0, 'error_message': str(f'You can add {pkg_cpu} or less then {pkg_cpu} CPUs.')} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - if (totalRam > pkg_Ram): - final_dic = {'status': 0, 'error_message': str(f'You can add {pkg_Ram} or less then {pkg_Ram} Ram.')} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - if ACLManager.currentContextPermission(currentACL, 'createWebsite') == 0: - return ACLManager.loadErrorJson('createWebSiteStatus', 0) - - if ACLManager.checkOwnerProtection(currentACL, loggedUser, newOwner) == 0: - return ACLManager.loadErrorJson('createWebSiteStatus', 0) - - if ACLManager.CheckDomainBlackList(Domain) == 0: - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Blacklisted domain."} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - data = {} - - data['JobID'] = tempStatusPath - data['Domain'] = Domain - data['WPemal'] = WPemal - data['Owner'] = Owner - data['userID'] = userID - data['MysqlCPU'] = MysqlCPU - data['MYsqlRam'] = MYsqlRam - data['SiteCPU'] = SiteCPU - data['SiteRam'] = SiteRam - data['sitename'] = sitename - data['WPusername'] = WPusername - data['WPpasswd'] = WPpasswd - data['externalApp'] = "".join(re.findall("[a-zA-Z]+", Domain))[:5] + str(randint(1000, 9999)) - data['App'] = App - - background = Docker_Sites('SubmitDockersiteCreation', data) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': tempStatusPath} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - final_dic = {'status': 0, 'error_message': str(msg)} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - def ListDockerSites(self, request=None, userID=None, data=None, DeleteID=None): - admin = Administrator.objects.get(pk=userID) - currentACL = ACLManager.loadedACL(userID) - fdata={} - - try: - if DeleteID != None: - - DockerSitesDelete = DockerSites.objects.get(pk=DeleteID) - if ACLManager.checkOwnership(DockerSitesDelete.admin.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - passdata={} - passdata["domain"] = DockerSitesDelete.admin.domain - passdata["JobID"] = None - passdata['name'] = DockerSitesDelete.SiteName - da = Docker_Sites(None, passdata) - da.DeleteDockerApp() - DockerSitesDelete.delete() - fdata['Deleted'] = 1 - except BaseException as msg: - fdata['LPError'] = 1 - fdata['LPMessage'] = str(msg) - - - fdata['pagination'] = self.DockersitePagination(currentACL, userID) - - proc = httpProc(request, 'websiteFunctions/ListDockersite.html', - fdata) - return proc.render() - - def fetchDockersite(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - pageNumber = int(data['page']) - recordsToShow = int(data['recordsToShow']) - - - endPageNumber, finalPageNumber = self.recordsPointer(pageNumber, recordsToShow) - - dockersites = ACLManager.findDockersiteObjects(currentACL, userID) - pagination = self.getPagination(len(dockersites), recordsToShow) - logging.CyberCPLogFileWriter.writeToFile("Our dockersite" + str(dockersites)) - - - json_data = self.findDockersitesListJson(dockersites[finalPageNumber:endPageNumber]) - - - final_dic = {'status': 1, 'listWebSiteStatus': 1, 'error_message': "None", "data": json_data, - 'pagination': pagination} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - except BaseException as msg: - final_dic = {'status': 0, 'listWebSiteStatus': 1, 'error_message': str(msg)} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - def Dockersitehome(self, request=None, userID=None, data=None, DeleteID=None): - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - ds = DockerSites.objects.get(pk=self.domain) - - if ACLManager.checkOwnership(ds.admin.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - proc = httpProc(request, 'websiteFunctions/DockerSiteHome.html', - {'dockerSite': ds}) - return proc.render() - - def fetchWPSitesForDomain(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - domain = data['domain'] - website = Websites.objects.get(domain=domain) - - if ACLManager.checkOwnership(domain, admin, currentACL) != 1: - return ACLManager.loadErrorJson('fetchStatus', 0) - - wp_sites = WPSites.objects.filter(owner=website) - sites = [] - - for site in wp_sites: - sites.append({ - 'id': site.id, - 'title': site.title, - 'url': site.FinalURL, - 'path': site.path, - 'version': site.version, - 'status': site.status - }) - - data_ret = {'status': 1, 'fetchStatus': 1, 'error_message': "None", "sites": sites} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'fetchStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - -class WebsiteManager: - apache = 1 - ols = 2 - lsws = 3 - - def __init__(self, domain=None, childDomain=None): - self.domain = domain - self.childDomain = childDomain - - def createWebsite(self, request=None, userID=None, data=None): - - url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" - data = { - "name": "all", - "IP": ACLManager.GetServerIP() - } - - import requests - response = requests.post(url, data=json.dumps(data)) - Status = response.json()['status'] - - test_domain_status = 0 - - if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: - test_domain_status = 1 - - currentACL = ACLManager.loadedACL(userID) - adminNames = ACLManager.loadAllUsers(userID) - packagesName = ACLManager.loadPackages(userID, currentACL) - phps = PHPManager.findPHPVersions() - - rnpss = randomPassword.generate_pass(10) - - Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps, 'Randam_String': rnpss.lower(), - 'test_domain_data': test_domain_status} - proc = httpProc(request, 'websiteFunctions/createWebsite.html', - Data, 'createWebsite') - return proc.render() - - def WPCreate(self, request=None, userID=None, data=None): - url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" - data = { - "name": "wp-manager", - "IP": ACLManager.GetServerIP() - } - - import requests - response = requests.post(url, data=json.dumps(data)) - Status = response.json()['status'] - - - if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: - currentACL = ACLManager.loadedACL(userID) - adminNames = ACLManager.loadAllUsers(userID) - packagesName = ACLManager.loadPackages(userID, currentACL) - - if len(packagesName) == 0: - packagesName = ['Default'] - - FinalVersions = [] - userobj = Administrator.objects.get(pk=userID) - counter = 0 - try: - import requests - WPVersions = json.loads(requests.get('https://api.wordpress.org/core/version-check/1.7/').text)[ - 'offers'] - - for versions in WPVersions: - if counter == 7: - break - if versions['current'] not in FinalVersions: - FinalVersions.append(versions['current']) - counter = counter + 1 - except: - FinalVersions = ['5.6', '5.5.3', '5.5.2'] - - Plugins = wpplugins.objects.filter(owner=userobj) - rnpss = randomPassword.generate_pass(10) - - ## - - test_domain_status = 1 - - Data = {'packageList': packagesName, "owernList": adminNames, 'WPVersions': FinalVersions, - 'Plugins': Plugins, 'Randam_String': rnpss.lower(), 'test_domain_data': test_domain_status} - proc = httpProc(request, 'websiteFunctions/WPCreate.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def ListWPSites(self, request=None, userID=None, DeleteID=None): - import json - currentACL = ACLManager.loadedACL(userID) - - admin = Administrator.objects.get(pk=userID) - data = {} - wp_sites = ACLManager.GetALLWPObjects(currentACL, userID) - data['wp'] = wp_sites - - try: - if DeleteID != None: - WPDelete = WPSites.objects.get(pk=DeleteID) - - if ACLManager.checkOwnership(WPDelete.owner.domain, admin, currentACL) == 1: - WPDelete.delete() - except BaseException as msg: - pass - - sites = [] - for site in data['wp']: - sites.append({ - 'id': site.id, - 'title': site.title, - 'url': site.FinalURL, - 'production_status': True - }) - - context = { - "wpsite": json.dumps(sites), - "status": 1, - "total_sites": len(sites), - "debug_info": json.dumps({ - "user_id": userID, - "is_admin": bool(currentACL.get('admin', 0)), - "wp_sites_count": wp_sites.count() - }) - } - - proc = httpProc(request, 'websiteFunctions/WPsitesList.html', context) - return proc.render() - - def WPHome(self, request=None, userID=None, WPid=None, DeleteID=None): - Data = {} - currentACL = ACLManager.loadedACL(userID) - WPobj = WPSites.objects.get(pk=WPid) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(WPobj.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - try: - - url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" - data = { - "name": "wp-manager", - "IP": ACLManager.GetServerIP() - } - - import requests - response = requests.post(url, data=json.dumps(data)) - Status = response.json()['status'] - - rnpss = randomPassword.generate_pass(10) - - Data['Randam_String'] = rnpss.lower() - - if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: - Data['wpsite'] = WPobj - Data['test_domain_data'] = 1 - - try: - DeleteID = request.GET.get('DeleteID', None) - - if DeleteID != None: - wstagingDelete = WPStaging.objects.get(pk=DeleteID, owner=WPobj) - wstagingDelete.delete() - - except BaseException as msg: - da = str(msg) - - proc = httpProc(request, 'websiteFunctions/WPsiteHome.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - except: - proc = httpProc(request, 'websiteFunctions/WPsiteHome.html', - Data, 'createDatabase') - return proc.render() - - def RestoreHome(self, request=None, userID=None, BackupID=None): - Data = {} - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.CheckForPremFeature('wp-manager'): - - Data['backupobj'] = WPSitesBackup.objects.get(pk=BackupID) - - if ACLManager.CheckIPBackupObjectOwner(currentACL, Data['backupobj'], admin) == 1: - pass - else: - return ACLManager.loadError() - - config = json.loads(Data['backupobj'].config) - Data['FileName'] = config['name'] - try: - Data['Backuptype'] = config['Backuptype'] - - if Data['Backuptype'] == 'DataBase Backup' or Data['Backuptype'] == 'Website Backup': - Data['WPsites'] = [WPSites.objects.get(pk=Data['backupobj'].WPSiteID)] - else: - Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) - - except: - Data['Backuptype'] = None - Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) - - proc = httpProc(request, 'websiteFunctions/WPRestoreHome.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def RemoteBackupConfig(self, request=None, userID=None, DeleteID=None): - Data = {} - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - try: - if DeleteID != None: - BackupconfigDelete = RemoteBackupConfig.objects.get(pk=DeleteID) - BackupconfigDelete.delete() - except: - pass - - if ACLManager.CheckForPremFeature('wp-manager'): - - Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) - allcon = RemoteBackupConfig.objects.all() - Data['backupconfigs'] = [] - for i in allcon: - configr = json.loads(i.config) - if i.configtype == "SFTP": - Data['backupconfigs'].append({ - 'id': i.pk, - 'Type': i.configtype, - 'HostName': configr['Hostname'], - 'Path': configr['Path'] - }) - elif i.configtype == "S3": - Provider = configr['Provider'] - if Provider == "Backblaze": - Data['backupconfigs'].append({ - 'id': i.pk, - 'Type': i.configtype, - 'HostName': Provider, - 'Path': configr['S3keyname'] - }) - else: - Data['backupconfigs'].append({ - 'id': i.pk, - 'Type': i.configtype, - 'HostName': Provider, - 'Path': configr['S3keyname'] - }) - - proc = httpProc(request, 'websiteFunctions/RemoteBackupConfig.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def BackupfileConfig(self, request=None, userID=None, RemoteConfigID=None, DeleteID=None): - Data = {} - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - Data['RemoteConfigID'] = RemoteConfigID - RemoteConfigobj = RemoteBackupConfig.objects.get(pk=RemoteConfigID) - try: - if DeleteID != None: - RemoteBackupConfigDelete = RemoteBackupSchedule.objects.get(pk=DeleteID) - RemoteBackupConfigDelete.delete() - except: - pass - - if ACLManager.CheckForPremFeature('wp-manager'): - Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) - allsechedule = RemoteBackupSchedule.objects.filter(RemoteBackupConfig=RemoteConfigobj) - Data['Backupschedule'] = [] - for i in allsechedule: - lastrun = i.lastrun - LastRun = time.strftime('%Y-%m-%d', time.localtime(float(lastrun))) - Data['Backupschedule'].append({ - 'id': i.pk, - 'Name': i.Name, - 'RemoteConfiguration': i.RemoteBackupConfig.configtype, - 'Retention': i.fileretention, - 'Frequency': i.timeintervel, - 'LastRun': LastRun - }) - proc = httpProc(request, 'websiteFunctions/BackupfileConfig.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def AddRemoteBackupsite(self, request=None, userID=None, RemoteScheduleID=None, DeleteSiteID=None): - Data = {} - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - Data['RemoteScheduleID'] = RemoteScheduleID - RemoteBackupScheduleobj = RemoteBackupSchedule.objects.get(pk=RemoteScheduleID) - - try: - if DeleteSiteID != None: - RemoteBackupsitesDelete = RemoteBackupsites.objects.get(pk=DeleteSiteID) - RemoteBackupsitesDelete.delete() - except: - pass - - if ACLManager.CheckForPremFeature('wp-manager'): - Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) - allRemoteBackupsites = RemoteBackupsites.objects.filter(owner=RemoteBackupScheduleobj) - Data['RemoteBackupsites'] = [] - for i in allRemoteBackupsites: - try: - wpsite = WPSites.objects.get(pk=i.WPsites) - Data['RemoteBackupsites'].append({ - 'id': i.pk, - 'Title': wpsite.title, - }) - except: - pass - proc = httpProc(request, 'websiteFunctions/AddRemoteBackupSite.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def WordpressPricing(self, request=None, userID=None, ): - Data = {} - proc = httpProc(request, 'websiteFunctions/CyberpanelPricing.html', Data, 'createWebsite') - return proc.render() - - def RestoreBackups(self, request=None, userID=None, DeleteID=None): - Data = {} - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" - data = { - "name": "wp-manager", - "IP": ACLManager.GetServerIP() - } - - import requests - response = requests.post(url, data=json.dumps(data)) - Status = response.json()['status'] - - if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: - - backobj = WPSitesBackup.objects.filter(owner=admin).order_by('-id') - - # if ACLManager.CheckIPBackupObjectOwner(currentACL, backobj, admin) == 1: - # pass - # else: - # return ACLManager.loadError() - - try: - if DeleteID != None: - DeleteIDobj = WPSitesBackup.objects.get(pk=DeleteID) - - if ACLManager.CheckIPBackupObjectOwner(currentACL, DeleteIDobj, admin) == 1: - config = DeleteIDobj.config - conf = json.loads(config) - FileName = conf['name'] - command = "rm -r /home/backup/%s.tar.gz" % FileName - ProcessUtilities.executioner(command) - DeleteIDobj.delete() - - except BaseException as msg: - pass - Data['job'] = [] - - for sub in backobj: - try: - wpsite = WPSites.objects.get(pk=sub.WPSiteID) - web = wpsite.title - except: - web = "Website Not Found" - - try: - config = sub.config - conf = json.loads(config) - Backuptype = conf['Backuptype'] - BackupDestination = conf['BackupDestination'] - except: - Backuptype = "Backup type not exists" - - Data['job'].append({ - 'id': sub.id, - 'title': web, - 'Backuptype': Backuptype, - 'BackupDestination': BackupDestination - }) - - proc = httpProc(request, 'websiteFunctions/RestoreBackups.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def AutoLogin(self, request=None, userID=None): - - WPid = request.GET.get('id') - currentACL = ACLManager.loadedACL(userID) - WPobj = WPSites.objects.get(pk=WPid) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(WPobj.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - from managePHP.phpManager import PHPManager - - php = PHPManager.getPHPString(WPobj.owner.phpSelection) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" - data = { - "name": "wp-manager", - "IP": ACLManager.GetServerIP() - } - - import requests - response = requests.post(url, data=json.dumps(data)) - Status = response.json()['status'] - - if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: - - ## Get title - - password = randomPassword.generate_pass(10) - - command = f'sudo -u %s {FinalPHPPath} /usr/bin/wp user create autologin %s --role=administrator --user_pass="%s" --path=%s --skip-plugins --skip-themes' % ( - WPobj.owner.externalApp, 'autologin@cloudpages.cloud', password, WPobj.path) - ProcessUtilities.executioner(command) - - command = f'sudo -u %s {FinalPHPPath} /usr/bin/wp user update autologin --user_pass="%s" --path=%s --skip-plugins --skip-themes' % ( - WPobj.owner.externalApp, password, WPobj.path) - ProcessUtilities.executioner(command) - - data = {} - - if WPobj.FinalURL.endswith('/'): - FinalURL = WPobj.FinalURL[:-1] - else: - FinalURL = WPobj.FinalURL - - data['url'] = 'https://%s' % (FinalURL) - data['userName'] = 'autologin' - data['password'] = password - - proc = httpProc(request, 'websiteFunctions/AutoLogin.html', - data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def ConfigurePlugins(self, request=None, userID=None, data=None): - - if ACLManager.CheckForPremFeature('wp-manager'): - currentACL = ACLManager.loadedACL(userID) - userobj = Administrator.objects.get(pk=userID) - - Selectedplugins = wpplugins.objects.filter(owner=userobj) - # data['Selectedplugins'] = wpplugins.objects.filter(ProjectOwner=HostingCompany) - - Data = {'Selectedplugins': Selectedplugins, } - proc = httpProc(request, 'websiteFunctions/WPConfigurePlugins.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def Addnewplugin(self, request=None, userID=None, data=None): - from django.shortcuts import reverse - if ACLManager.CheckForPremFeature('wp-manager'): - currentACL = ACLManager.loadedACL(userID) - adminNames = ACLManager.loadAllUsers(userID) - packagesName = ACLManager.loadPackages(userID, currentACL) - phps = PHPManager.findPHPVersions() - - Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps} - proc = httpProc(request, 'websiteFunctions/WPAddNewPlugin.html', - Data, 'createDatabase') - return proc.render() - - return redirect(reverse('pricing')) - - def SearchOnkeyupPlugin(self, userID=None, data=None): - try: - if ACLManager.CheckForPremFeature('wp-manager'): - currentACL = ACLManager.loadedACL(userID) - - pluginname = data['pluginname'] - # logging.CyberCPLogFileWriter.writeToFile("Plugin Name ....... %s"%pluginname) - - url = "http://api.wordpress.org/plugins/info/1.1/?action=query_plugins&request[search]=%s" % str( - pluginname) - import requests - - res = requests.get(url) - r = res.json() - - # return proc.ajax(1, 'Done', {'plugins': r}) - - data_ret = {'status': 1, 'plugns': r, } - - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': 'Premium feature not available.'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def AddNewpluginAjax(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - - userobj = Administrator.objects.get(pk=userID) - - config = data['config'] - Name = data['Name'] - # pluginname = data['pluginname'] - # logging.CyberCPLogFileWriter.writeToFile("config ....... %s"%config) - # logging.CyberCPLogFileWriter.writeToFile(" Name ....... %s"%Name) - - addpl = wpplugins(Name=Name, config=json.dumps(config), owner=userobj) - addpl.save() - - data_ret = {'status': 1} - - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'AddNewpluginAjax': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def EidtPlugin(self, request=None, userID=None, pluginbID=None): - Data = {} - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - pluginobj = wpplugins.objects.get(pk=pluginbID) - - if ACLManager.CheckIPPluginObjectOwner(currentACL, pluginobj, admin) == 1: - pass - else: - return ACLManager.loadError() - - lmo = json.loads(pluginobj.config) - Data['Selectedplugins'] = lmo - Data['pluginbID'] = pluginbID - Data['BucketName'] = pluginobj.Name - - proc = httpProc(request, 'websiteFunctions/WPEidtPlugin.html', - Data, 'createDatabase') - return proc.render() - - def deletesPlgin(self, userID=None, data=None, ): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - userobj = Administrator.objects.get(pk=userID) - pluginname = data['pluginname'] - pluginbBucketID = data['pluginbBucketID'] - # logging.CyberCPLogFileWriter.writeToFile("pluginbID ....... %s" % pluginbBucketID) - # logging.CyberCPLogFileWriter.writeToFile("pluginname ....... %s" % pluginname) - - obj = wpplugins.objects.get(pk=pluginbBucketID, owner=userobj) - - if ACLManager.CheckIPPluginObjectOwner(currentACL, obj, admin) == 1: - pass - else: - return ACLManager.loadError() - - ab = [] - ab = json.loads(obj.config) - ab.remove(pluginname) - obj.config = json.dumps(ab) - obj.save() - - data_ret = {'status': 1} - - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except BaseException as msg: - data_ret = {'status': 0, 'deletesPlgin': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def Addplugineidt(self, userID=None, data=None, ): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - userobj = Administrator.objects.get(pk=userID) - pluginname = data['pluginname'] - pluginbBucketID = data['pluginbBucketID'] - - # logging.CyberCPLogFileWriter.writeToFile("pluginbID ....... %s" % pluginbBucketID) - # logging.CyberCPLogFileWriter.writeToFile("pluginname ....... %s" % pluginname) - - pObj = wpplugins.objects.get(pk=pluginbBucketID, owner=userobj) - - if ACLManager.CheckIPPluginObjectOwner(currentACL, pObj, admin) == 1: - pass - else: - return ACLManager.loadError() - - listofplugin = json.loads(pObj.config) - try: - index = listofplugin.index(pluginname) - print('index.....%s' % index) - if (index >= 0): - data_ret = {'status': 0, 'deletesPlgin': 0, 'error_message': str('Already Save in your Plugin lis')} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except: - ab = [] - ab = json.loads(pObj.config) - ab.append(pluginname) - pObj.config = json.dumps(ab) - pObj.save() - - data_ret = {'status': 1} - - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except BaseException as msg: - data_ret = {'status': 0, 'deletesPlgin': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def modifyWebsite(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - - websitesName = ACLManager.findAllSites(currentACL, userID) - phps = PHPManager.findPHPVersions() - proc = httpProc(request, 'websiteFunctions/modifyWebsite.html', - {'websiteList': websitesName, 'phps': phps}, 'modifyWebsite') - return proc.render() - - def deleteWebsite(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - websitesName = ACLManager.findAllSites(currentACL, userID) - proc = httpProc(request, 'websiteFunctions/deleteWebsite.html', - {'websiteList': websitesName}, 'deleteWebsite') - return proc.render() - - def CreateNewDomain(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - websitesName = ACLManager.findAllSites(currentACL, userID) - - try: - admin = Administrator.objects.get(pk=userID) - if admin.defaultSite == 0: - websites = ACLManager.findWebsiteObjects(currentACL, userID) - admin.defaultSite = websites[0].id - admin.save() - except: - pass - - try: - admin = Administrator.objects.get(pk=userID) - defaultDomain = Websites.objects.get(pk=admin.defaultSite).domain - except: - try: - admin = Administrator.objects.get(pk=userID) - websites = ACLManager.findWebsiteObjects(currentACL, userID) - admin.defaultSite = websites[0].id - admin.save() - defaultDomain = websites[0].domain - except: - defaultDomain='NONE' - - - url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" - data = { - "name": "all", - "IP": ACLManager.GetServerIP() - } - - import requests - response = requests.post(url, data=json.dumps(data)) - Status = response.json()['status'] - - test_domain_status = 0 - - if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: - test_domain_status = 1 - - rnpss = randomPassword.generate_pass(10) - proc = httpProc(request, 'websiteFunctions/createDomain.html', - {'websiteList': websitesName, 'phps': PHPManager.findPHPVersions(), 'Randam_String': rnpss, - 'test_domain_data': test_domain_status, 'defaultSite': defaultDomain}) - return proc.render() - - def siteState(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - - websitesName = ACLManager.findAllSites(currentACL, userID) - - proc = httpProc(request, 'websiteFunctions/suspendWebsite.html', - {'websiteList': websitesName}, 'suspendWebsite') - return proc.render() - - def listWebsites(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - pagination = self.websitePagination(currentACL, userID) - proc = httpProc(request, 'websiteFunctions/listWebsites.html', - {"pagination": pagination}) - return proc.render() - - def listChildDomains(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - adminNames = ACLManager.loadAllUsers(userID) - packagesName = ACLManager.loadPackages(userID, currentACL) - phps = PHPManager.findPHPVersions() - - Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps} - proc = httpProc(request, 'websiteFunctions/listChildDomains.html', - Data) - return proc.render() - - def listCron(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(request.GET.get('domain'), admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - proc = httpProc(request, 'websiteFunctions/listCron.html', - {'domain': request.GET.get('domain')}) - return proc.render() - - def domainAlias(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - aliasManager = AliasManager(self.domain) - noAlias, finalAlisList = aliasManager.fetchAlisForDomains() - - path = "/home/" + self.domain + "/public_html" - - proc = httpProc(request, 'websiteFunctions/domainAlias.html', { - 'masterDomain': self.domain, - 'aliases': finalAlisList, - 'path': path, - 'noAlias': noAlias - }) - return proc.render() - - def FetchWPdata(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core version --skip-plugins --skip-themes --path=%s 2>/dev/null' % ( - Vhuser, FinalPHPPath, path) - version = ProcessUtilities.outputExecutioner(command, None, True) - version = html.escape(version) - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin status litespeed-cache --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, path) - lscachee = ProcessUtilities.outputExecutioner(command) - - if lscachee.find('Status: Active') > -1: - lscache = 1 - else: - lscache = 0 - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp config list --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, path) - stdout = ProcessUtilities.outputExecutioner(command) - debugging = 0 - for items in stdout.split('\n'): - if items.find('WP_DEBUG true constant') > -1: - debugging = 1 - break - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp option get blog_public --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, path) - stdoutput = ProcessUtilities.outputExecutioner(command) - searchindex = int(stdoutput.splitlines()[-1]) - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp maintenance-mode status --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, path) - maintenanceMod = ProcessUtilities.outputExecutioner(command) - - result = maintenanceMod.splitlines()[-1] - if result.find('not active') > -1: - maintenanceMode = 0 - else: - maintenanceMode = 1 - - ##### Check passwd protection - vhostName = wpsite.owner.domain - vhostPassDir = f'/home/{vhostName}' - path = f'{vhostPassDir}/{WPManagerID}' - if os.path.exists(path): - passwd = 1 - else: - passwd = 0 - - #### Check WP cron - command = "sudo -u %s cat %s/wp-config.php" % (Vhuser, wpsite.path) - stdout = ProcessUtilities.outputExecutioner(command) - if stdout.find("'DISABLE_WP_CRON', 'true'") > -1: - wpcron = 1 - else: - wpcron = 0 - - fb = { - 'version': version.rstrip('\n'), - 'lscache': lscache, - 'debugging': debugging, - 'searchIndex': searchindex, - 'maintenanceMode': maintenanceMode, - 'passwordprotection': passwd, - 'wpcron': wpcron - - } - - data_ret = {'status': 1, 'error_message': 'None', 'ret_data': fb} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def GetCurrentPlugins(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin list --skip-plugins --skip-themes --format=json --path=%s' % ( - Vhuser, FinalPHPPath, path) - stdoutput = ProcessUtilities.outputExecutioner(command) - json_data = stdoutput.splitlines()[-1] - - data_ret = {'status': 1, 'error_message': 'None', 'plugins': json_data} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def GetCurrentThemes(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp theme list --skip-plugins --skip-themes --format=json --path=%s' % ( - Vhuser, FinalPHPPath, path) - stdoutput = ProcessUtilities.outputExecutioner(command) - json_data = stdoutput.splitlines()[-1] - - data_ret = {'status': 1, 'error_message': 'None', 'themes': json_data} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def fetchstaging(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - from plogical.phpUtilities import phpUtilities - - json_data = phpUtilities.GetStagingInJson(wpsite.wpstaging_set.all().order_by('-id')) - - data_ret = {'status': 1, 'error_message': 'None', 'wpsites': json_data} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def fetchDatabase(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - php = PHPManager.getPHPString(wpsite.owner.phpSelection) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - command = f'{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config get DB_NAME --skip-plugins --skip-themes --path={wpsite.path} 2>/dev/null' - retStatus, stdoutput = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp, True, None, 1) - - if stdoutput.find('Error:') == -1: - DataBaseName = stdoutput.rstrip("\n") - DataBaseName = html.escape(DataBaseName) - else: - data_ret = {'status': 0, 'error_message': stdoutput} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - command = f'{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config get DB_USER --skip-plugins --skip-themes --path={wpsite.path} 2>/dev/null' - retStatus, stdoutput = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp, True, None, 1) - - if stdoutput.find('Error:') == -1: - DataBaseUser = stdoutput.rstrip("\n") - DataBaseUser = html.escape(DataBaseUser) - else: - data_ret = {'status': 0, 'error_message': stdoutput} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - command = f'{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config get table_prefix --skip-plugins --skip-themes --path={wpsite.path} 2>/dev/null' - retStatus, stdoutput = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp, True, None, 1) - - if stdoutput.find('Error:') == -1: - tableprefix = stdoutput.rstrip("\n") - tableprefix = html.escape(tableprefix) - else: - data_ret = {'status': 0, 'error_message': stdoutput} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - data_ret = {'status': 1, 'error_message': 'None', "DataBaseUser": DataBaseUser, - "DataBaseName": DataBaseName, 'tableprefix': tableprefix} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def SaveUpdateConfig(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - Plugins = data['Plugins'] - Themes = data['Themes'] - AutomaticUpdates = data['AutomaticUpdates'] - - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - - php = PHPManager.getPHPString(wpsite.owner.phpSelection) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - if AutomaticUpdates == 'Disabled': - command = f"{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_AUTO_UPDATE_CORE false --raw --allow-root --path=" + wpsite.path - result = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp) - - if result.find('Success:') == -1: - raise BaseException(result) - elif AutomaticUpdates == 'Minor and Security Updates': - command = f"{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_AUTO_UPDATE_CORE minor --allow-root --path=" + wpsite.path - result = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp) - - if result.find('Success:') == -1: - raise BaseException(result) - else: - command = f"{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_AUTO_UPDATE_CORE true --raw --allow-root --path=" + wpsite.path - result = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp) - - if result.find('Success:') == -1: - raise BaseException(result) - - wpsite.AutoUpdates = AutomaticUpdates - wpsite.PluginUpdates = Plugins - wpsite.ThemeUpdates = Themes - wpsite.save() - - data_ret = {'status': 1, 'error_message': 'None', } - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def DeploytoProduction(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - statgingID = data['StagingID'] - wpsite = WPSites.objects.get(pk=WPManagerID) - StagingObj = WPSites.objects.get(pk=statgingID) - - ### - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - if ACLManager.checkOwnership(StagingObj.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - ### - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['statgingID'] = statgingID - extraArgs['WPid'] = WPManagerID - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - background = ApplicationInstaller('DeploytoProduction', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def WPCreateBackup(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - Backuptype = data['Backuptype'] - - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['WPid'] = WPManagerID - extraArgs['Backuptype'] = Backuptype - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - background = ApplicationInstaller('WPCreateBackup', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def RestoreWPbackupNow(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - backupid = data['backupid'] - DesSiteID = data['DesSite'] - - # try: - # - # bwp = WPSites.objects.get(pk=int(backupid)) - # - # if ACLManager.checkOwnership(bwp.owner.domain, admin, currentACL) == 1: - # pass - # else: - # return ACLManager.loadError() - # - # except: - # pass - # - # dwp = WPSites.objects.get(pk=int(DesSiteID)) - # if ACLManager.checkOwnership(dwp.owner.domain, admin, currentACL) == 1: - # pass - # else: - # return ACLManager.loadError() - - Domain = data['Domain'] - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['backupid'] = backupid - extraArgs['DesSiteID'] = DesSiteID - extraArgs['Domain'] = Domain - extraArgs['path'] = data['path'] - extraArgs['home'] = data['home'] - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - background = ApplicationInstaller('RestoreWPbackupNow', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def SaveBackupConfig(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - ConfigType = data['type'] - if ConfigType == 'SFTP': - Hname = data['Hname'] - Uname = data['Uname'] - Passwd = data['Passwd'] - path = data['path'] - config = { - "Hostname": Hname, - "Username": Uname, - "Password": Passwd, - "Path": path - } - elif ConfigType == "S3": - Provider = data['Provider'] - if Provider == "Backblaze": - S3keyname = data['S3keyname'] - SecertKey = data['SecertKey'] - AccessKey = data['AccessKey'] - EndUrl = data['EndUrl'] - config = { - "Provider": Provider, - "S3keyname": S3keyname, - "SecertKey": SecertKey, - "AccessKey": AccessKey, - "EndUrl": EndUrl - - } - else: - S3keyname = data['S3keyname'] - SecertKey = data['SecertKey'] - AccessKey = data['AccessKey'] - config = { - "Provider": Provider, - "S3keyname": S3keyname, - "SecertKey": SecertKey, - "AccessKey": AccessKey, - - } - - mkobj = RemoteBackupConfig(owner=admin, configtype=ConfigType, config=json.dumps(config)) - mkobj.save() - - time.sleep(1) - - data_ret = {'status': 1, 'error_message': 'None', } - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def SaveBackupSchedule(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - FileRetention = data['FileRetention'] - Backfrequency = data['Backfrequency'] - ScheduleName = data['ScheduleName'] - RemoteConfigID = data['RemoteConfigID'] - BackupType = data['BackupType'] - - RemoteBackupConfigobj = RemoteBackupConfig.objects.get(pk=RemoteConfigID) - Rconfig = json.loads(RemoteBackupConfigobj.config) - - try: - # This code is only supposed to run if backups are s3, not for SFTP - provider = Rconfig['Provider'] - if provider == "Backblaze": - EndURl = Rconfig['EndUrl'] - elif provider == "Amazon": - EndURl = "https://s3.us-east-1.amazonaws.com" - elif provider == "Wasabi": - EndURl = "https://s3.wasabisys.com" - - AccessKey = Rconfig['AccessKey'] - SecertKey = Rconfig['SecertKey'] - - session = boto3.session.Session() - - client = session.client( - 's3', - endpoint_url=EndURl, - aws_access_key_id=AccessKey, - aws_secret_access_key=SecertKey, - verify=False - ) - - ############Creating Bucket - BucketName = randomPassword.generate_pass().lower() - - try: - client.create_bucket(Bucket=BucketName) - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile("Creating Bucket Error: %s" % str(msg)) - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - config = { - 'BackupType': BackupType, - 'BucketName': BucketName - } - except BaseException as msg: - config = {'BackupType': BackupType} - pass - - svobj = RemoteBackupSchedule(RemoteBackupConfig=RemoteBackupConfigobj, Name=ScheduleName, - timeintervel=Backfrequency, fileretention=FileRetention, - config=json.dumps(config), - lastrun=str(time.time())) - svobj.save() - - data_ret = {'status': 1, 'error_message': 'None', } - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def AddWPsiteforRemoteBackup(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - WPid = data['WpsiteID'] - RemoteScheduleID = data['RemoteScheduleID'] - - wpsiteobj = WPSites.objects.get(pk=WPid) - WPpath = wpsiteobj.path - VHuser = wpsiteobj.owner.externalApp - PhpVersion = wpsiteobj.owner.phpSelection - php = PHPManager.getPHPString(PhpVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - ####Get DB Name - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp config get DB_NAME --skip-plugins --skip-themes --path=%s' % ( - VHuser, FinalPHPPath, WPpath) - result, stdout = ProcessUtilities.outputExecutioner(command, None, None, None, 1) - - if stdout.find('Error:') > -1: - raise BaseException(stdout) - else: - Finaldbname = stdout.rstrip("\n") - - ## Get DB obj - try: - DBobj = Databases.objects.get(dbName=Finaldbname) - except: - raise BaseException(str("DataBase Not Found")) - RemoteScheduleIDobj = RemoteBackupSchedule.objects.get(pk=RemoteScheduleID) - - svobj = RemoteBackupsites(owner=RemoteScheduleIDobj, WPsites=WPid, database=DBobj.pk) - svobj.save() - - data_ret = {'status': 1, 'error_message': 'None', } - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def UpdateRemoteschedules(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - ScheduleID = data['ScheduleID'] - Frequency = data['Frequency'] - FileRetention = data['FileRetention'] - - scheduleobj = RemoteBackupSchedule.objects.get(pk=ScheduleID) - scheduleobj.timeintervel = Frequency - scheduleobj.fileretention = FileRetention - scheduleobj.save() - - data_ret = {'status': 1, 'error_message': 'None', } - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def ScanWordpressSite(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - allweb = Websites.objects.all() - - childdomain = ChildDomains.objects.all() - - for web in allweb: - webpath = "/home/%s/public_html/" % web.domain - command = "cat %swp-config.php" % webpath - result = ProcessUtilities.outputExecutioner(command, web.externalApp) - - if os.path.exists(ProcessUtilities.debugPath): - logging.CyberCPLogFileWriter.writeToFile(result) - - if result.find('No such file or directory') == -1: - try: - WPSites.objects.get(path=webpath) - except: - wpobj = WPSites(owner=web, title=web.domain, path=webpath, FinalURL=web.domain, - AutoUpdates="Enabled", PluginUpdates="Enabled", - ThemeUpdates="Enabled", ) - wpobj.save() - - for chlid in childdomain: - childPath = chlid.path.rstrip('/') - - command = "cat %s/wp-config.php" % childPath - result = ProcessUtilities.outputExecutioner(command, chlid.master.externalApp) - - if os.path.exists(ProcessUtilities.debugPath): - logging.CyberCPLogFileWriter.writeToFile(result) - - if result.find('No such file or directory') == -1: - fChildPath = f'{childPath}/' - try: - WPSites.objects.get(path=fChildPath) - except: - - wpobj = WPSites(owner=chlid.master, title=chlid.domain, path=fChildPath, FinalURL=chlid.domain, - AutoUpdates="Enabled", PluginUpdates="Enabled", - ThemeUpdates="Enabled", ) - wpobj.save() - - data_ret = {'status': 1, 'error_message': 'None', } - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def installwpcore(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - ###fetch WP version - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core version --skip-plugins --skip-themes --path=%s 2>/dev/null' % ( - Vhuser, FinalPHPPath, path) - version = ProcessUtilities.outputExecutioner(command, None, True) - version = version.rstrip("\n") - - ###install wp core - command = f"sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp core download --force --skip-content --version={version} --path={path}" - output = ProcessUtilities.outputExecutioner(command) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', 'result': output} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def dataintegrity(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - ###fetch WP version - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core verify-checksums --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, path) - result = ProcessUtilities.outputExecutioner(command) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', 'result': result} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def UpdatePlugins(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - plugin = data['plugin'] - pluginarray = data['pluginarray'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['plugin'] = plugin - extraArgs['pluginarray'] = pluginarray - extraArgs['FinalPHPPath'] = FinalPHPPath - extraArgs['path'] = path - extraArgs['Vhuser'] = Vhuser - - background = ApplicationInstaller('UpdateWPPlugin', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def UpdateThemes(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - Theme = data['Theme'] - Themearray = data['Themearray'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['Theme'] = Theme - extraArgs['Themearray'] = Themearray - extraArgs['FinalPHPPath'] = FinalPHPPath - extraArgs['path'] = path - extraArgs['Vhuser'] = Vhuser - - background = ApplicationInstaller('UpdateWPTheme', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def DeletePlugins(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - plugin = data['plugin'] - pluginarray = data['pluginarray'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['plugin'] = plugin - extraArgs['pluginarray'] = pluginarray - extraArgs['FinalPHPPath'] = FinalPHPPath - extraArgs['path'] = path - extraArgs['Vhuser'] = Vhuser - - background = ApplicationInstaller('DeletePlugins', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def DeleteThemes(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - Theme = data['Theme'] - Themearray = data['Themearray'] - wpsite = WPSites.objects.get(pk=WPManagerID) - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['Theme'] = Theme - extraArgs['Themearray'] = Themearray - extraArgs['FinalPHPPath'] = FinalPHPPath - extraArgs['path'] = path - extraArgs['Vhuser'] = Vhuser - - background = ApplicationInstaller('DeleteThemes', extraArgs) - background.start() - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def ChangeStatus(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - plugin = data['plugin'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin status %s --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, plugin, path) - stdoutput = ProcessUtilities.outputExecutioner(command) - - if stdoutput.find('Status: Active') > -1: - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin deactivate %s --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, plugin, path) - stdoutput = ProcessUtilities.outputExecutioner(command) - time.sleep(3) - - else: - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin activate %s --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, plugin, path) - stdoutput = ProcessUtilities.outputExecutioner(command) - time.sleep(3) - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def ChangeStatusThemes(self, userID=None, data=None): - try: - # logging.CyberCPLogFileWriter.writeToFile("Error WP ChangeStatusThemes ....... %s") - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - Theme = data['theme'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['Theme'] = Theme - extraArgs['FinalPHPPath'] = FinalPHPPath - extraArgs['path'] = path - extraArgs['Vhuser'] = Vhuser - - background = ApplicationInstaller('ChangeStatusThemes', extraArgs) - background.start() - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def CreateStagingNow(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['StagingDomain'] = data['StagingDomain'] - extraArgs['StagingName'] = data['StagingName'] - extraArgs['WPid'] = data['WPid'] - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - wpsite = WPSites.objects.get(pk=data['WPid']) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - background = ApplicationInstaller('CreateStagingNow', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def UpdateWPSettings(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - siteId = data['siteId'] - setting = data['setting'] - value = data['value'] - - wpsite = WPSites.objects.get(pk=siteId) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) != 1: - return ACLManager.loadError() - - # Get PHP version and path - Webobj = Websites.objects.get(pk=wpsite.owner_id) - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - # Update the appropriate setting based on the setting type - if setting == 'search-indexing': - # Update search engine indexing - command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp option update blog_public {value} --skip-plugins --skip-themes --path={wpsite.path}' - elif setting == 'debugging': - # Update debugging in wp-config.php - if value: - command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_DEBUG true --raw --skip-plugins --skip-themes --path={wpsite.path}' - else: - command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_DEBUG false --raw --skip-plugins --skip-themes --path={wpsite.path}' - elif setting == 'password-protection': - vhostName = wpsite.owner.domain - vhostPassDir = f'/home/{vhostName}' - path = f'{vhostPassDir}/{siteId}' - if value: - # Enable password protection - if not os.path.exists(path): - os.makedirs(path) - htpasswd = f'{path}/.htpasswd' - htaccess = f'{wpsite.path}/.htaccess' - password = randomPassword.generate_pass(12) - - # Create .htpasswd file - command = f"htpasswd -cb {htpasswd} admin {password}" - ProcessUtilities.executioner(command) - - # Create .htaccess file - htaccess_content = f"""AuthType Basic -AuthName "Restricted Access" -AuthUserFile {htpasswd} -Require valid-user""" - with open(htaccess, 'w') as f: - f.write(htaccess_content) - - def submitWebsiteModify(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - domain = data['domain'] - website = Websites.objects.get(domain=domain) - - if ACLManager.checkOwnership(domain, admin, currentACL) != 1: - return ACLManager.loadErrorJson('fetchStatus', 0) - - wp_sites = WPSites.objects.filter(owner=website) - sites = [] - - for site in wp_sites: - sites.append({ - 'id': site.id, - 'title': site.title, - 'url': site.FinalURL, - 'path': site.path, - 'version': site.version, - 'status': site.status - }) - - data_ret = {'status': 1, 'fetchStatus': 1, 'error_message': "None", "sites": sites} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'fetchStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def getWebsiteCron(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - self.domain = data['domain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('getWebsiteCron', 0) - - website = Websites.objects.get(domain=self.domain) - - if Websites.objects.filter(domain=self.domain).exists(): - pass - else: - dic = {'getWebsiteCron': 0, 'error_message': 'You do not own this domain'} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - CronUtil.CronPrem(1) - - crons = [] - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" - execPath = execPath + " getWebsiteCron --externalApp " + website.externalApp - - f = ProcessUtilities.outputExecutioner(execPath, website.externalApp) - - CronUtil.CronPrem(0) - - if ProcessUtilities.decideDistro() == ProcessUtilities.centos or ProcessUtilities.decideDistro() == ProcessUtilities.cent8: - cronPath = "/var/spool/cron/" + website.externalApp - else: - cronPath = "/var/spool/cron/crontabs/" + website.externalApp - - if f.find('Permission denied') > -1: - command = 'chmod 644 %s' % (cronPath) - ProcessUtilities.executioner(command) - - command = 'chown %s:%s %s' % (website.externalApp, website.externalApp, cronPath) - ProcessUtilities.executioner(command) - - f = ProcessUtilities.outputExecutioner(execPath, website.externalApp) - - if f.find("0,CyberPanel,") > -1: - data_ret = {'getWebsiteCron': 0, "user": website.externalApp, "crons": {}} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - - counter = 0 - for line in f.split("\n"): - if line: - split = line.split(" ", 5) - if len(split) == 6: - counter += 1 - crons.append({"line": counter, - "minute": split[0], - "hour": split[1], - "monthday": split[2], - "month": split[3], - "weekday": split[4], - "command": split[5]}) - - data_ret = {'getWebsiteCron': 1, "user": website.externalApp, "crons": crons} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - dic = {'getWebsiteCron': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def getCronbyLine(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - line = data['line'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('getWebsiteCron', 0) - - if Websites.objects.filter(domain=self.domain).exists(): - pass - else: - dic = {'getWebsiteCron': 0, 'error_message': 'You do not own this domain'} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - line -= 1 - website = Websites.objects.get(domain=self.domain) - - try: - CronUtil.CronPrem(1) - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" - execPath = execPath + " getWebsiteCron --externalApp " + website.externalApp - - f = ProcessUtilities.outputExecutioner(execPath, website.externalApp) - CronUtil.CronPrem(0) - except subprocess.CalledProcessError as error: - dic = {'getWebsiteCron': 0, 'error_message': 'Unable to access Cron file'} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - f = f.split("\n") - cron = f[line] - - cron = cron.split(" ", 5) - if len(cron) != 6: - dic = {'getWebsiteCron': 0, 'error_message': 'Cron line incorrect'} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - data_ret = {"getWebsiteCron": 1, - "user": website.externalApp, - "cron": { - "minute": cron[0], - "hour": cron[1], - "monthday": cron[2], - "month": cron[3], - "weekday": cron[4], - "command": cron[5], - }, - "line": line} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - except BaseException as msg: - print(msg) - dic = {'getWebsiteCron': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def saveCronChanges(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - line = data['line'] - - minute = data['minute'] - hour = data['hour'] - monthday = data['monthday'] - month = data['month'] - weekday = data['weekday'] - command = data['cronCommand'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('getWebsiteCron', 0) - - website = Websites.objects.get(domain=self.domain) - - finalCron = "%s %s %s %s %s %s" % (minute, hour, monthday, month, weekday, command) - - CronUtil.CronPrem(1) - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" - execPath = execPath + " saveCronChanges --externalApp " + website.externalApp + " --line " + str( - line) + " --finalCron '" + finalCron + "'" - output = ProcessUtilities.outputExecutioner(execPath, website.externalApp) - CronUtil.CronPrem(0) - - if output.find("1,") > -1: - data_ret = {"getWebsiteCron": 1, - "user": website.externalApp, - "cron": finalCron, - "line": line} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - else: - dic = {'getWebsiteCron': 0, 'error_message': output} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - - except BaseException as msg: - dic = {'getWebsiteCron': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def remCronbyLine(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - line = data['line'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('addNewCron', 0) - - website = Websites.objects.get(domain=self.domain) - - CronUtil.CronPrem(1) - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" - execPath = execPath + " remCronbyLine --externalApp " + website.externalApp + " --line " + str( - line) - output = ProcessUtilities.outputExecutioner(execPath, website.externalApp) - - CronUtil.CronPrem(0) - - if output.find("1,") > -1: - data_ret = {"remCronbyLine": 1, - "user": website.externalApp, - "removeLine": output.split(',')[1], - "line": line} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - else: - dic = {'remCronbyLine': 0, 'error_message': output} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - - except BaseException as msg: - dic = {'remCronbyLine': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def addNewCron(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - minute = data['minute'] - hour = data['hour'] - monthday = data['monthday'] - month = data['month'] - weekday = data['weekday'] - command = data['cronCommand'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('addNewCron', 0) - - website = Websites.objects.get(domain=self.domain) - - if ProcessUtilities.decideDistro() == ProcessUtilities.centos or ProcessUtilities.decideDistro() == ProcessUtilities.cent8: - cronPath = "/var/spool/cron/" + website.externalApp - else: - cronPath = "/var/spool/cron/crontabs/" + website.externalApp - - commandT = 'touch %s' % (cronPath) - ProcessUtilities.executioner(commandT, 'root') - commandT = 'chown %s:%s %s' % (website.externalApp, website.externalApp, cronPath) - ProcessUtilities.executioner(commandT, 'root') - - CronUtil.CronPrem(1) - - finalCron = "%s %s %s %s %s %s" % (minute, hour, monthday, month, weekday, command) - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" - execPath = execPath + " addNewCron --externalApp " + website.externalApp + " --finalCron '" + finalCron + "'" - output = ProcessUtilities.outputExecutioner(execPath, website.externalApp) - - if ProcessUtilities.decideDistro() == ProcessUtilities.ubuntu or ProcessUtilities.decideDistro() == ProcessUtilities.ubuntu20: - command = 'chmod 600 %s' % (cronPath) - ProcessUtilities.executioner(command) - - command = 'systemctl restart cron' - ProcessUtilities.executioner(command) - - CronUtil.CronPrem(0) - - if output.find("1,") > -1: - - data_ret = {"addNewCron": 1, - "user": website.externalApp, - "cron": finalCron} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - else: - dic = {'addNewCron': 0, 'error_message': output} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - - except BaseException as msg: - dic = {'addNewCron': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def submitAliasCreation(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['masterDomain'] - aliasDomain = data['aliasDomain'] - ssl = data['ssl'] - - if not validators.domain(aliasDomain): - data_ret = {'status': 0, 'createAliasStatus': 0, 'error_message': "Invalid domain."} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('createAliasStatus', 0) - - sslpath = "/home/" + self.domain + "/public_html" - - ## Create Configurations - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - - execPath = execPath + " createAlias --masterDomain " + self.domain + " --aliasDomain " + aliasDomain + " --ssl " + str( - ssl) + " --sslPath " + sslpath + " --administratorEmail " + admin.email + ' --websiteOwner ' + admin.userName - - output = ProcessUtilities.outputExecutioner(execPath) - - if output.find("1,None") > -1: - pass - else: - data_ret = {'createAliasStatus': 0, 'error_message': output, "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - ## Create Configurations ends here - - data_ret = {'createAliasStatus': 1, 'error_message': "None", "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - - except BaseException as msg: - data_ret = {'createAliasStatus': 0, 'error_message': str(msg), "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def issueAliasSSL(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['masterDomain'] - aliasDomain = data['aliasDomain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('sslStatus', 0) - - if ACLManager.AliasDomainCheck(currentACL, aliasDomain, self.domain) == 1: - pass - else: - return ACLManager.loadErrorJson('sslStatus', 0) - - sslpath = "/home/" + self.domain + "/public_html" - - ## Create Configurations - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " issueAliasSSL --masterDomain " + self.domain + " --aliasDomain " + aliasDomain + " --sslPath " + sslpath + " --administratorEmail " + admin.email - - output = ProcessUtilities.outputExecutioner(execPath) - - if output.find("1,None") > -1: - data_ret = {'sslStatus': 1, 'error_message': "None", "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - data_ret = {'sslStatus': 0, 'error_message': output, "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'sslStatus': 0, 'error_message': str(msg), "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def delateAlias(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['masterDomain'] - aliasDomain = data['aliasDomain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('deleteAlias', 0) - - if ACLManager.AliasDomainCheck(currentACL, aliasDomain, self.domain) == 1: - pass - else: - return ACLManager.loadErrorJson('deleteAlias', 0) - - ## Create Configurations - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " deleteAlias --masterDomain " + self.domain + " --aliasDomain " + aliasDomain - output = ProcessUtilities.outputExecutioner(execPath) - - if output.find("1,None") > -1: - data_ret = {'deleteAlias': 1, 'error_message': "None", "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - data_ret = {'deleteAlias': 0, 'error_message': output, "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'deleteAlias': 0, 'error_message': str(msg), "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def changeOpenBasedir(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - - self.domain = data['domainName'] - openBasedirValue = data['openBasedirValue'] - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadErrorJson('changeOpenBasedir', 0) - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " changeOpenBasedir --virtualHostName '" + self.domain + "' --openBasedirValue " + openBasedirValue - output = ProcessUtilities.popenExecutioner(execPath) - - data_ret = {'status': 1, 'changeOpenBasedir': 1, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'changeOpenBasedir': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def wordpressInstall(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - proc = httpProc(request, 'websiteFunctions/installWordPress.html', {'domainName': self.domain}) - return proc.render() - - def installWordpress(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('installStatus', 0) - - mailUtilities.checkHome() - - extraArgs = {} - extraArgs['admin'] = admin - extraArgs['domainName'] = data['domain'] - extraArgs['home'] = data['home'] - extraArgs['blogTitle'] = data['blogTitle'] - extraArgs['adminUser'] = data['adminUser'] - extraArgs['adminPassword'] = data['passwordByPass'] - extraArgs['adminEmail'] = data['adminEmail'] - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - if data['home'] == '0': - extraArgs['path'] = data['path'] - - background = ApplicationInstaller('wordpress', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def installWordpressStatus(self, userID=None, data=None): - try: - statusFile = data['statusFile'] - - if ACLManager.CheckStatusFilleLoc(statusFile): - pass - else: - data_ret = {'abort': 1, 'installStatus': 0, 'installationProgress': "100", - 'currentStatus': 'Invalid status file.'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - statusData = ProcessUtilities.outputExecutioner("cat " + statusFile).splitlines() - - lastLine = statusData[-1] - - if lastLine.find('[200]') > -1: - command = 'rm -f ' + statusFile - subprocess.call(shlex.split(command)) - data_ret = {'abort': 1, 'installStatus': 1, 'installationProgress': "100", - 'currentStatus': 'Successfully Installed.'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - elif lastLine.find('[404]') > -1: - data_ret = {'abort': 1, 'installStatus': 0, 'installationProgress': "0", - 'error_message': ProcessUtilities.outputExecutioner("cat " + statusFile).splitlines()} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - progress = lastLine.split(',') - currentStatus = progress[0] - try: - installationProgress = progress[1] - except: - installationProgress = 0 - data_ret = {'abort': 0, 'installStatus': 0, 'installationProgress': installationProgress, - 'currentStatus': currentStatus} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'abort': 0, 'installStatus': 0, 'installationProgress': "0", 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def joomlaInstall(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - proc = httpProc(request, 'websiteFunctions/installJoomla.html', {'domainName': self.domain}) - return proc.render() - - def installJoomla(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('installStatus', 0) - - extraArgs = {} - - extraArgs['password'] = data['passwordByPass'] - extraArgs['prefix'] = data['prefix'] - extraArgs['domain'] = data['domain'] - extraArgs['home'] = data['home'] - extraArgs['siteName'] = data['siteName'] - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - mailUtilities.checkHome() - - if data['home'] == '0': - extraArgs['path'] = data['path'] - - background = ApplicationInstaller('joomla', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - ## Installation ends - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def setupGit(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - website = Websites.objects.get(domain=self.domain) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson() - - path = '/home/cyberpanel/' + self.domain + '.git' - - if os.path.exists(path): - ipFile = "/etc/cyberpanel/machineIP" - f = open(ipFile) - ipData = f.read() - ipAddress = ipData.split('\n', 1)[0] - - port = ProcessUtilities.fetchCurrentPort() - - webhookURL = 'https://' + ipAddress + ':%s/websites/' % (port) + self.domain + '/gitNotify' - - proc = httpProc(request, 'websiteFunctions/setupGit.html', - {'domainName': self.domain, 'installed': 1, 'webhookURL': webhookURL}) - return proc.render() - else: - - command = "ssh-keygen -f /home/%s/.ssh/%s -t rsa -N ''" % (self.domain, website.externalApp) - ProcessUtilities.executioner(command, website.externalApp) - - ### - - configContent = """Host github.com -IdentityFile /home/%s/.ssh/%s -StrictHostKeyChecking no -""" % (self.domain, website.externalApp) - - path = "/home/cyberpanel/config" - writeToFile = open(path, 'w') - writeToFile.write(configContent) - writeToFile.close() - - command = "cp /home/cyberpanel/config /home/%s/.ssh/config" % (self.domain) - ProcessUtilities.executioner(command, website.externalApp) - - command = "chown %s:%s /home/%s/.ssh/config" % (website.externalApp, website.externalApp, self.domain) - ProcessUtilities.executioner(command) - - command = "chmod 600 /home/%s/.ssh/config" % (self.domain) - ProcessUtilities.executioner(command, website.externalApp) - - command = "rm -rf /home/cyberpanel/config" - ProcessUtilities.executioner(command) - - command = "cp /home/%s/.ssh/id_rsa.pub /home/cyberpanel/%s.pub" % (self.domain, self.domain) - ProcessUtilities.executioner(command) - - command = "chown cyberpanel:cyberpanel /home/cyberpanel/%s.pub" % (self.domain) - ProcessUtilities.executioner(command) - - ipFile = "/etc/cyberpanel/machineIP" - f = open(ipFile) - ipData = f.read() - ipAddress = ipData.split('\n', 1)[0] - - port = ProcessUtilities.fetchCurrentPort() - - webhookURL = 'https://' + ipAddress + ':%s/websites/' % (port) + self.domain + '/gitNotify' - - proc = httpProc(request, 'websiteFunctions/setupGit.html', - {'domainName': self.domain, 'installed': 0, 'webhookURL': webhookURL}) - return proc.render() - - def startCloning(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - repoURL = data['repoURL'] - branch = data['branch'] - repoName = data['repoName'] - tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('cloneStatus', 0) - - background = Cloner(self.domain, repoURL, branch, repoName, tempStatusPath) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'cloneStatus': 1, 'error_message': 'None', - 'tempStatusPath': tempStatusPath} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'cloneStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def cloneStatus(self, userID=None, data=None): - try: - statusFile = data['statusFile'] - - if ACLManager.CheckStatusFilleLoc(statusFile): - pass - else: - data_ret = {'abort': 1, 'cloneStatus': 0, 'installationProgress': "100", - 'currentStatus': 'Invalid status file.'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - statusData = ProcessUtilities.outputExecutioner("cat " + statusFile).splitlines() - - lastLine = statusData[-1] - - if lastLine.find('[200]') > -1: - command = 'rm -f ' + statusFile - subprocess.call(shlex.split(command)) - data_ret = {'abort': 1, 'cloneStatus': 1, 'installationProgress': "100", - 'currentStatus': 'Successfully Installed.'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - elif lastLine.find('[404]') > -1: - data_ret = {'abort': 1, 'cloneStatus': 0, 'installationProgress': "0", - 'error_message': ProcessUtilities.outputExecutioner("cat " + statusFile).splitlines()} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - progress = lastLine.split(',') - currentStatus = progress[0] - try: - installationProgress = progress[1] - except: - installationProgress = 0 - data_ret = {'abort': 0, 'cloneStatus': 0, 'installationProgress': installationProgress, - 'currentStatus': currentStatus} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'abort': 0, 'cloneStatus': 0, 'installationProgress': "0", 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def gitPull(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - repoURL = data['repoURL'] - branch = data['branch'] - repoName = data['repoName'] - tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('cloneStatus', 0) - - background = GitPuller(self.domain, repoURL, branch, repoName, tempStatusPath) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'cloneStatus': 1, 'error_message': 'None', - 'tempStatusPath': tempStatusPath} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'cloneStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def gitPullStatus(self, userID=None, data=None): - try: - statusFile = data['statusFile'] - - if ACLManager.CheckStatusFilleLoc(statusFile): - pass - else: - data_ret = {'abort': 1, 'cloneStatus': 0, 'installationProgress': "100", - 'currentStatus': 'Invalid status file.'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - statusData = ProcessUtilities.outputExecutioner("cat " + statusFile).splitlines() - - lastLine = statusData[-1] - - if lastLine.find('[200]') > -1: - command = 'rm -f ' + statusFile - subprocess.call(shlex.split(command)) - data_ret = {'abort': 1, 'cloneStatus': 1, 'installationProgress': "100", - 'currentStatus': 'Successfully Installed.'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - elif lastLine.find('[404]') > -1: - data_ret = {'abort': 1, 'cloneStatus': 0, 'installationProgress': "0", - 'error_message': ProcessUtilities.outputExecutioner("cat " + statusFile).splitlines()} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - progress = lastLine.split(',') - currentStatus = progress[0] - try: - installationProgress = progress[1] - except: - installationProgress = 0 - data_ret = {'abort': 0, 'cloneStatus': 0, 'installationProgress': installationProgress, - 'currentStatus': currentStatus} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'abort': 0, 'cloneStatus': 0, 'installationProgress': "0", 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def getSSHConfigs(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('getSSHConfigs', 0) - - website = Websites.objects.get(domain=self.domain) - - path = "/home/" + self.domain + "/.ssh/config" - - if os.path.exists(path): - f = open(path, 'r') - configData = f.read() - f.close() - else: - configData = "" - - data_ret = {'getSSHConfigs': 1, 'error_message': "None", "configData": configData} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'getSSHConfigs': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def saveSSHConfigs(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - configData = data['configData'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('saveSSHConfigs', 0) - - website = Websites.objects.get(domain=self.domain) - - path = "/home/" + self.domain + "/.ssh/config" - - writeToFile = open(path, 'w') - writeToFile.write(configData) - writeToFile.close() - - command = "chown %s:%s %s" % (website.externalApp, website.externalApp, path) - ProcessUtilities.executioner(command) - - command = "chmod 600 %s" % (path) - ProcessUtilities.executioner(command) - - data_ret = {'saveSSHConfigs': 1, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'saveSSHConfigs': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def fetchWPSitesForDomain(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - domain = data['domain'] - website = Websites.objects.get(domain=domain) - - if ACLManager.checkOwnership(domain, admin, currentACL) != 1: - return ACLManager.loadErrorJson('fetchStatus', 0) - - wp_sites = WPSites.objects.filter(owner=website) - sites = [] - - for site in wp_sites: - sites.append({ - 'id': site.id, - 'title': site.title, - 'url': site.FinalURL, - 'path': site.path, - 'version': site.version, - 'status': site.status - }) - - data_ret = {'status': 1, 'fetchStatus': 1, 'error_message': "None", "sites": sites} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'fetchStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - -class WebsiteManager: - apache = 1 - ols = 2 - lsws = 3 - - def __init__(self, data=None): - self.domain = data['domain'] - self.adminEmail = data['adminEmail'] - - if 'phpVersion' in data.keys(): - self.phpVersion = data['phpVersion'] - else: - self.phpVersion = None - - if 'package' in data.keys(): - self.package = data['package'] - else: - self.package = None - - if 'websiteOwner' in data.keys(): - self.websiteOwner = data['websiteOwner'] - else: - self.websiteOwner = None - - if 'externalApp' in data.keys(): - self.externalApp = data['externalApp'] - else: - self.externalApp = None - - if 'ssl' in data.keys(): - self.ssl = data['ssl'] - else: - self.ssl = None - - if 'dkimCheck' in data.keys(): - self.dkimCheck = data['dkimCheck'] - else: - self.dkimCheck = None - - if 'openBasedir' in data.keys(): - self.openBasedir = data['openBasedir'] - else: - self.openBasedir = None - - if 'sslForced' in data.keys(): - self.sslForced = data['sslForced'] - else: - self.sslForced = None - - if 'http2' in data.keys(): - self.http2 = data['http2'] - else: - self.http2 = None - - if 'waf' in data.keys(): - self.waf = data['waf'] - else: - self.waf = None - - if 'wafRules' in data.keys(): - self.wafRules = data['wafRules'] - else: - self.wafRules = None - - if 'wafMode' in data.keys(): - self.wafMode = data['wafMode'] - else: - self.wafMode = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): - self.wafExclusions = data['wafExclusions'] - else: - self.wafExclusions = None - - if 'wafExclusions' in data.keys(): -Require valid-user""" - with open(htaccess, 'w') as f: - f.write(htaccess_content) - - def submitWebsiteModify(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - domain = data['domain'] - website = Websites.objects.get(domain=domain) - - if ACLManager.checkOwnership(domain, admin, currentACL) != 1: - return ACLManager.loadErrorJson('fetchStatus', 0) - - wp_sites = WPSites.objects.filter(owner=website) - sites = [] - - for site in wp_sites: - sites.append({ - 'id': site.id, - 'title': site.title, - 'url': site.FinalURL, - 'path': site.path, - 'version': site.version, - 'status': site.status - }) - - data_ret = {'status': 1, 'fetchStatus': 1, 'error_message': "None", "sites": sites} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'fetchStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - def getWebsiteCron(self, userID=None, data=None): try: @@ -16049,3 +7053,36 @@ StrictHostKeyChecking no proc = httpProc(request, 'websiteFunctions/DockerSiteHome.html', {'dockerSite': ds}) return proc.render() + + def fetchWPSitesForDomain(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + domain = data['domain'] + website = Websites.objects.get(domain=domain) + + if ACLManager.checkOwnership(domain, admin, currentACL) != 1: + return ACLManager.loadErrorJson('fetchStatus', 0) + + wp_sites = WPSites.objects.filter(owner=website) + sites = [] + + for site in wp_sites: + sites.append({ + 'id': site.id, + 'title': site.title, + 'url': site.FinalURL, + 'path': site.path, + 'version': site.version, + 'status': site.status + }) + + data_ret = {'status': 1, 'fetchStatus': 1, 'error_message': "None", "sites": sites} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'fetchStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) From 6240437d87c6baa03bc00093730a1a7259f48d7b Mon Sep 17 00:00:00 2001 From: usmannasir Date: Fri, 4 Apr 2025 17:32:10 +0500 Subject: [PATCH 008/273] fix fetchWPSitesForDomain --- .../websiteFunctions/websiteFunctions.js | 28 +++++++++++++++++-- websiteFunctions/views.py | 4 ++- 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/websiteFunctions/static/websiteFunctions/websiteFunctions.js b/websiteFunctions/static/websiteFunctions/websiteFunctions.js index 09b210069..7664c65bd 100755 --- a/websiteFunctions/static/websiteFunctions/websiteFunctions.js +++ b/websiteFunctions/static/websiteFunctions/websiteFunctions.js @@ -2689,7 +2689,19 @@ app.controller('listWebsites', function ($scope, $http, $window) { 'X-CSRFToken': getCookie('csrftoken') } }).then(function(response) { - alert(JSON.stringify(response.data, null, 2)); + if (response.data.status === 1) { + var sites = response.data.sites; + var message = 'WordPress Sites for ' + domain + ':\n\n'; + sites.forEach(function(site) { + message += 'Title: ' + site.title + '\n'; + message += 'URL: ' + site.url + '\n'; + message += 'Version: ' + site.version + '\n'; + message += 'Status: ' + site.status + '\n\n'; + }); + alert(message); + } else { + alert('Error: ' + response.data.error_message); + } }).catch(function(error) { alert('Error fetching WordPress sites: ' + JSON.stringify(error)); }); @@ -6577,7 +6589,19 @@ app.controller('manageAliasController', function ($scope, $http, $timeout, $wind 'X-CSRFToken': getCookie('csrftoken') } }).then(function(response) { - alert(JSON.stringify(response.data, null, 2)); + if (response.data.status === 1) { + var sites = response.data.sites; + var message = 'WordPress Sites for ' + domain + ':\n\n'; + sites.forEach(function(site) { + message += 'Title: ' + site.title + '\n'; + message += 'URL: ' + site.url + '\n'; + message += 'Version: ' + site.version + '\n'; + message += 'Status: ' + site.status + '\n\n'; + }); + alert(message); + } else { + alert('Error: ' + response.data.error_message); + } }).catch(function(error) { alert('Error fetching WordPress sites: ' + JSON.stringify(error)); }); diff --git a/websiteFunctions/views.py b/websiteFunctions/views.py index 36aa3f78f..30a093ba0 100755 --- a/websiteFunctions/views.py +++ b/websiteFunctions/views.py @@ -1846,7 +1846,9 @@ def Dockersitehome(request, dockerapp): def fetchWPDetails(request): try: userID = request.session['userID'] - data = json.loads(request.body) + data = { + 'domain': request.POST.get('domain') + } wm = WebsiteManager() return wm.fetchWPSitesForDomain(userID, data) except KeyError: From e286efc4ffc9fa567702b56551c8d5c416503522 Mon Sep 17 00:00:00 2001 From: usmannasir Date: Fri, 4 Apr 2025 17:51:19 +0500 Subject: [PATCH 009/273] fix fetchWPSitesForDomain --- websiteFunctions/website.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/websiteFunctions/website.py b/websiteFunctions/website.py index d11601526..0f68926ca 100755 --- a/websiteFunctions/website.py +++ b/websiteFunctions/website.py @@ -7067,6 +7067,9 @@ StrictHostKeyChecking no wp_sites = WPSites.objects.filter(owner=website) sites = [] + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core version --skip-plugins --skip-themes --path=%s 2>/dev/null' % ( + Vhuser, FinalPHPPath, path) for site in wp_sites: sites.append({ From 8865814310a385f82a1a6bf627553911194723a7 Mon Sep 17 00:00:00 2001 From: usmannasir Date: Fri, 4 Apr 2025 17:57:49 +0500 Subject: [PATCH 010/273] fix vhuser in function --- websiteFunctions/website.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/websiteFunctions/website.py b/websiteFunctions/website.py index 0f68926ca..dd7fe2c6f 100755 --- a/websiteFunctions/website.py +++ b/websiteFunctions/website.py @@ -7067,18 +7067,27 @@ StrictHostKeyChecking no wp_sites = WPSites.objects.filter(owner=website) sites = [] + + Vhuser = website.externalApp + PHPVersion = website.phpSelection - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core version --skip-plugins --skip-themes --path=%s 2>/dev/null' % ( - Vhuser, FinalPHPPath, path) + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) for site in wp_sites: + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core version --skip-plugins --skip-themes --path=%s 2>/dev/null' % ( + Vhuser, FinalPHPPath, site.path) + version = ProcessUtilities.outputExecutioner(command, None, True) + version = html.escape(version) + + sites.append({ 'id': site.id, 'title': site.title, 'url': site.FinalURL, 'path': site.path, - 'version': site.version, - 'status': site.status + 'version': version, }) data_ret = {'status': 1, 'fetchStatus': 1, 'error_message': "None", "sites": sites} From 1d86636e26d4d56034cff28b8383a516c3b431ae Mon Sep 17 00:00:00 2001 From: usmannasir Date: Fri, 4 Apr 2025 18:23:10 +0500 Subject: [PATCH 011/273] fix vhuser in function --- .../websiteFunctions/websiteFunctions.js | 1504 ++--------------- websiteFunctions/website.py | 14 +- 2 files changed, 125 insertions(+), 1393 deletions(-) diff --git a/websiteFunctions/static/websiteFunctions/websiteFunctions.js b/websiteFunctions/static/websiteFunctions/websiteFunctions.js index 7664c65bd..7f8a1961e 100755 --- a/websiteFunctions/static/websiteFunctions/websiteFunctions.js +++ b/websiteFunctions/static/websiteFunctions/websiteFunctions.js @@ -2690,19 +2690,31 @@ app.controller('listWebsites', function ($scope, $http, $window) { } }).then(function(response) { if (response.data.status === 1) { - var sites = response.data.sites; - var message = 'WordPress Sites for ' + domain + ':\n\n'; - sites.forEach(function(site) { - message += 'Title: ' + site.title + '\n'; - message += 'URL: ' + site.url + '\n'; - message += 'Version: ' + site.version + '\n'; - message += 'Status: ' + site.status + '\n\n'; + $scope.web.showWPSites = true; + $scope.web.wp_sites = response.data.sites.map(function(site) { + return { + id: site.id, + title: site.title, + url: site.url, + version: site.version, + status: site.status, + phpVersion: site.phpVersion || 'Unknown', + theme: site.theme || 'Default', + activePlugins: site.activePlugins || '0', + searchIndex: true, + debugging: false, + passwordProtection: false, + maintenanceMode: false + }; }); - alert(message); } else { + $scope.web.showWPSites = false; + $scope.web.wp_sites = []; alert('Error: ' + response.data.error_message); } }).catch(function(error) { + $scope.web.showWPSites = false; + $scope.web.wp_sites = []; alert('Error fetching WordPress sites: ' + JSON.stringify(error)); }); }; @@ -2711,65 +2723,23 @@ app.controller('listWebsites', function ($scope, $http, $window) { window.open(url, '_blank'); }; - $scope.wpLogin = function(wpId) { - window.open('/websites/wpLogin?wpID=' + wpId, '_blank'); + $scope.wpLogin = function(siteId) { + // You'll need to implement the login URL generation + var site = $scope.web.wp_sites.find(function(s) { return s.id === siteId; }); + if (site) { + window.open(site.url + '/wp-admin', '_blank'); + } }; - $scope.manageWP = function(wpId) { - window.location.href = '/websites/listWPsites?wpID=' + wpId; + $scope.manageWP = function(siteId) { + // Implement your management page navigation + window.location.href = '/websites/WPHome?ID=' + siteId; }; $scope.updateSetting = function(wp, setting) { - var settingMap = { - 'search-indexing': 'searchIndex', - 'debugging': 'debugging', - 'password-protection': 'passwordProtection', - 'maintenance-mode': 'maintenanceMode' - }; - - var data = { - wpID: wp.id, - setting: setting, - value: wp[settingMap[setting]] ? 'enable' : 'disable' - }; - - $http({ - method: 'POST', - url: '/websites/UpdateWPSettings', - data: data, - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', - 'X-CSRFToken': getCookie('csrftoken') - }, - transformRequest: function(obj) { - var str = []; - for(var p in obj) - str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); - return str.join("&"); - } - }).then(function(response) { - if (response.data.status === 1) { - new PNotify({ - title: 'Success', - text: 'Setting updated successfully.', - type: 'success' - }); - } else { - wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change - new PNotify({ - title: 'Error', - text: 'Failed to update setting.', - type: 'error' - }); - } - }).catch(function(error) { - wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change - new PNotify({ - title: 'Error', - text: 'Connection failed while updating setting.', - type: 'error' - }); - }); + // Implement settings update logic here + console.log('Updating setting:', setting, 'for site:', wp.id); + // You would typically make an API call here to update the setting }; $scope.cyberPanelLoading = true; @@ -6590,667 +6560,64 @@ app.controller('manageAliasController', function ($scope, $http, $timeout, $wind } }).then(function(response) { if (response.data.status === 1) { - var sites = response.data.sites; - var message = 'WordPress Sites for ' + domain + ':\n\n'; - sites.forEach(function(site) { - message += 'Title: ' + site.title + '\n'; - message += 'URL: ' + site.url + '\n'; - message += 'Version: ' + site.version + '\n'; - message += 'Status: ' + site.status + '\n\n'; + $scope.web.showWPSites = true; + $scope.web.wp_sites = response.data.sites.map(function(site) { + return { + id: site.id, + title: site.title, + url: site.url, + version: site.version, + status: site.status, + phpVersion: site.phpVersion || 'Unknown', + theme: site.theme || 'Default', + activePlugins: site.activePlugins || '0', + searchIndex: true, + debugging: false, + passwordProtection: false, + maintenanceMode: false + }; }); - alert(message); } else { + $scope.web.showWPSites = false; + $scope.web.wp_sites = []; alert('Error: ' + response.data.error_message); } }).catch(function(error) { + $scope.web.showWPSites = false; + $scope.web.wp_sites = []; alert('Error fetching WordPress sites: ' + JSON.stringify(error)); }); }; - $scope.updateSetting = function(wp, setting) { - var settingMap = { - 'search-indexing': 'searchIndex', - 'debugging': 'debugging', - 'password-protection': 'passwordProtection', - 'maintenance-mode': 'maintenanceMode' - }; - - var data = { - wpID: wp.id, - setting: setting, - value: wp[settingMap[setting]] ? 'enable' : 'disable' - }; - - $http({ - method: 'POST', - url: '/websites/UpdateWPSettings', - data: data, - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', - 'X-CSRFToken': getCookie('csrftoken') - }, - transformRequest: function(obj) { - var str = []; - for(var p in obj) - str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); - return str.join("&"); - } - }).then(function(response) { - if (response.data.status === 1) { - new PNotify({ - title: 'Success', - text: 'Setting updated successfully.', - type: 'success' - }); - } else { - wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change - new PNotify({ - title: 'Error', - text: 'Failed to update setting.', - type: 'error' - }); - } - }).catch(function(error) { - wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change - new PNotify({ - title: 'Error', - text: 'Connection failed while updating setting.', - type: 'error' - }); - }); - }; - $scope.visitSite = function(url) { window.open(url, '_blank'); }; - $scope.wpLogin = function(wpId) { - window.open('/websites/wpLogin?wpID=' + wpId, '_blank'); + $scope.wpLogin = function(siteId) { + // You'll need to implement the login URL generation + var site = $scope.web.wp_sites.find(function(s) { return s.id === siteId; }); + if (site) { + window.open(site.url + '/wp-admin', '_blank'); + } }; - $scope.manageWP = function(wpId) { - window.location.href = '/websites/listWPsites?wpID=' + wpId; + $scope.manageWP = function(siteId) { + // Implement your management page navigation + window.location.href = '/websites/WPHome?ID=' + siteId; }; $scope.updateSetting = function(wp, setting) { - var settingMap = { - 'search-indexing': 'searchIndex', - 'debugging': 'debugging', - 'password-protection': 'passwordProtection', - 'maintenance-mode': 'maintenanceMode' - }; - - var data = { - wpID: wp.id, - setting: setting, - value: wp[settingMap[setting]] ? 'enable' : 'disable' - }; - - $http({ - method: 'POST', - url: '/websites/UpdateWPSettings', - data: data, - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', - 'X-CSRFToken': getCookie('csrftoken') - }, - transformRequest: function(obj) { - var str = []; - for(var p in obj) - str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); - return str.join("&"); - } - }).then(function(response) { - if (response.data.status === 1) { - new PNotify({ - title: 'Success', - text: 'Setting updated successfully.', - type: 'success' - }); - } else { - wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change - new PNotify({ - title: 'Error', - text: 'Failed to update setting.', - type: 'error' - }); - } - }).catch(function(error) { - wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change - new PNotify({ - title: 'Error', - text: 'Connection failed while updating setting.', - type: 'error' - }); - }); + // Implement settings update logic here + console.log('Updating setting:', setting, 'for site:', wp.id); + // You would typically make an API call here to update the setting }; - $scope.saveRewriteRules = function () { - - $scope.configFileLoading = false; - - - url = "/websites/saveRewriteRules"; - - var virtualHost = $("#childDomain").text(); - var rewriteRules = $scope.rewriteRules; - - - var data = { - virtualHost: virtualHost, - rewriteRules: rewriteRules, - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.rewriteStatus == 1) { - - $scope.configurationsBoxRewrite = false; - $scope.rewriteRulesFetched = true; - $scope.couldNotFetchRewriteRules = true; - $scope.rewriteRulesSaved = false; - $scope.couldNotSaveRewriteRules = true; - $scope.fetchedRewriteRules = true; - $scope.saveRewriteRulesBTN = true; - $scope.configFileLoading = true; - - - } else { - $scope.configurationsBoxRewrite = false; - $scope.rewriteRulesFetched = false; - $scope.couldNotFetchRewriteRules = true; - $scope.rewriteRulesSaved = true; - $scope.couldNotSaveRewriteRules = false; - $scope.fetchedRewriteRules = true; - $scope.saveRewriteRulesBTN = false; - - $scope.configFileLoading = true; - - - $scope.errorMessage = response.data.error_message; - - } - - - } - - function cantLoadInitialDatas(response) { - - $scope.configurationsBoxRewrite = false; - $scope.rewriteRulesFetched = false; - $scope.couldNotFetchRewriteRules = true; - $scope.rewriteRulesSaved = true; - $scope.couldNotSaveRewriteRules = true; - $scope.fetchedRewriteRules = true; - $scope.saveRewriteRulesBTN = false; - - $scope.configFileLoading = true; - - $scope.couldNotConnect = false; - - - } - - + $scope.updateSetting = function(wp, setting) { + // Implement settings update logic here + console.log('Updating setting:', setting, 'for site:', wp.id); + // You would typically make an API call here to update the setting }; - - //////// SSL Part - - $scope.sslSaved = true; - $scope.couldNotSaveSSL = true; - $scope.hidsslconfigs = true; - $scope.couldNotConnect = true; - - - $scope.hidesslbtn = function () { - $scope.hidsslconfigs = true; - }; - - $scope.addSSL = function () { - $scope.hidsslconfigs = false; - $scope.configurationsBox = true; - $scope.configurationsBoxRewrite = true; - $scope.changePHPView = true; - }; - - - $scope.saveSSL = function () { - - - $scope.configFileLoading = false; - - url = "/websites/saveSSL"; - - var virtualHost = $("#childDomain").text(); - var cert = $scope.cert; - var key = $scope.key; - - - var data = { - virtualHost: virtualHost, - cert: cert, - key: key, - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.sslStatus === 1) { - - $scope.sslSaved = false; - $scope.couldNotSaveSSL = true; - $scope.couldNotConnect = true; - $scope.configFileLoading = true; - - - } else { - - $scope.sslSaved = true; - $scope.couldNotSaveSSL = false; - $scope.couldNotConnect = true; - $scope.configFileLoading = true; - - $scope.errorMessage = response.data.error_message; - - } - - - } - - function cantLoadInitialDatas(response) { - - $scope.sslSaved = true; - $scope.couldNotSaveSSL = true; - $scope.couldNotConnect = false; - $scope.configFileLoading = true; - - - } - - }; - - - //// Change PHP Master - - $scope.failedToChangePHPMaster = true; - $scope.phpChangedMaster = true; - $scope.couldNotConnect = true; - - $scope.changePHPView = true; - - - $scope.hideChangePHPMaster = function () { - $scope.changePHPView = true; - }; - - $scope.changePHPMaster = function () { - $scope.hidsslconfigs = true; - $scope.configurationsBox = true; - $scope.configurationsBoxRewrite = true; - $scope.changePHPView = false; - }; - - - $scope.changePHPVersionMaster = function (childDomain, phpSelection) { - - // notifcations - - $scope.configFileLoading = false; - - var url = "/websites/changePHP"; - - var data = { - childDomain: $("#childDomain").text(), - phpSelection: $scope.phpSelectionMaster, - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - - if (response.data.changePHP === 1) { - - $scope.configFileLoading = true; - $scope.websiteDomain = $("#childDomain").text(); - - - // notifcations - - $scope.failedToChangePHPMaster = true; - $scope.phpChangedMaster = false; - $scope.couldNotConnect = true; - - - } else { - - $scope.configFileLoading = true; - $scope.errorMessage = response.data.error_message; - - // notifcations - - $scope.failedToChangePHPMaster = false; - $scope.phpChangedMaster = true; - $scope.couldNotConnect = true; - - } - - - } - - function cantLoadInitialDatas(response) { - - $scope.configFileLoading = true; - - // notifcations - - $scope.failedToChangePHPMaster = true; - $scope.phpChangedMaster = true; - $scope.couldNotConnect = false; - - } - - }; - - - /// Open_basedir protection - - $scope.baseDirLoading = true; - $scope.operationFailed = true; - $scope.operationSuccessfull = true; - $scope.couldNotConnect = true; - $scope.openBaseDirBox = true; - - - $scope.openBaseDirView = function () { - $scope.openBaseDirBox = false; - }; - - $scope.hideOpenBasedir = function () { - $scope.openBaseDirBox = true; - }; - - $scope.applyOpenBasedirChanges = function (childDomain, phpSelection) { - - // notifcations - - $scope.baseDirLoading = false; - $scope.operationFailed = true; - $scope.operationSuccessfull = true; - $scope.couldNotConnect = true; - $scope.openBaseDirBox = false; - - - var url = "/websites/changeOpenBasedir"; - - var data = { - domainName: $("#childDomain").text(), - openBasedirValue: $scope.openBasedirValue - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - - if (response.data.changeOpenBasedir === 1) { - - $scope.baseDirLoading = true; - $scope.operationFailed = true; - $scope.operationSuccessfull = false; - $scope.couldNotConnect = true; - $scope.openBaseDirBox = false; - - } else { - - $scope.baseDirLoading = true; - $scope.operationFailed = false; - $scope.operationSuccessfull = true; - $scope.couldNotConnect = true; - $scope.openBaseDirBox = false; - - $scope.errorMessage = response.data.error_message; - - } - - - } - - function cantLoadInitialDatas(response) { - - $scope.baseDirLoading = true; - $scope.operationFailed = true; - $scope.operationSuccessfull = true; - $scope.couldNotConnect = false; - $scope.openBaseDirBox = false; - - - } - - } - -}); - -/* Application Installer */ - -app.controller('installWordPressCTRL', function ($scope, $http, $timeout) { - - $scope.installationDetailsForm = false; - $scope.installationProgress = true; - $scope.installationFailed = true; - $scope.installationSuccessfull = true; - $scope.couldNotConnect = true; - $scope.wpInstallLoading = true; - $scope.goBackDisable = true; - - var statusFile; - var domain = $("#domainNamePage").text(); - var path; - - - $scope.goBack = function () { - $scope.installationDetailsForm = false; - $scope.installationProgress = true; - $scope.installationFailed = true; - $scope.installationSuccessfull = true; - $scope.couldNotConnect = true; - $scope.wpInstallLoading = true; - $scope.goBackDisable = true; - $("#installProgress").css("width", "0%"); - }; - - $scope.installWordPress = function () { - - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.installationFailed = true; - $scope.installationSuccessfull = true; - $scope.couldNotConnect = true; - $scope.wpInstallLoading = false; - $scope.goBackDisable = true; - $scope.currentStatus = "Starting installation.."; - - path = $scope.installPath; - - - url = "/websites/installWordpress"; - - var home = "1"; - - if (typeof path !== 'undefined') { - home = "0"; - } - - - var data = { - domain: domain, - home: home, - path: path, - blogTitle: $scope.blogTitle, - adminUser: $scope.adminUser, - passwordByPass: $scope.adminPassword, - adminEmail: $scope.adminEmail - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.installStatus === 1) { - statusFile = response.data.tempStatusPath; - getInstallStatus(); - } else { - - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.installationFailed = false; - $scope.installationSuccessfull = true; - $scope.couldNotConnect = true; - $scope.wpInstallLoading = true; - $scope.goBackDisable = false; - - $scope.errorMessage = response.data.error_message; - - } - - - } - - function cantLoadInitialDatas(response) { - - - } - - }; - - function getInstallStatus() { - - url = "/websites/installWordpressStatus"; - - var data = { - statusFile: statusFile, - domainName: domain - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - - if (response.data.abort === 1) { - - if (response.data.installStatus === 1) { - - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.installationFailed = true; - $scope.installationSuccessfull = false; - $scope.couldNotConnect = true; - $scope.wpInstallLoading = true; - $scope.goBackDisable = false; - - if (typeof path !== 'undefined') { - $scope.installationURL = "http://" + domain + "/" + path; - } else { - $scope.installationURL = domain; - } - - - $("#installProgress").css("width", "100%"); - $scope.installPercentage = "100"; - $scope.currentStatus = response.data.currentStatus; - $timeout.cancel(); - - } else { - - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.installationFailed = false; - $scope.installationSuccessfull = true; - $scope.couldNotConnect = true; - $scope.wpInstallLoading = true; - $scope.goBackDisable = false; - - $scope.errorMessage = response.data.error_message; - - $("#installProgress").css("width", "0%"); - $scope.installPercentage = "0"; - - } - - } else { - $("#installProgress").css("width", response.data.installationProgress + "%"); - $scope.installPercentage = response.data.installationProgress; - $scope.currentStatus = response.data.currentStatus; - - $timeout(getInstallStatus, 1000); - - - } - - } - - function cantLoadInitialDatas(response) { - - $scope.canNotFetch = true; - $scope.couldNotConnect = false; - - - } - - - } - - -}); - app.controller('installJoomlaCTRL', function ($scope, $http, $timeout) { $scope.installationDetailsForm = false; @@ -9437,709 +8804,74 @@ app.controller('manageGIT', function ($scope, $http, $timeout, $window) { } }; - $scope.fetchGitignore = function () { - - $scope.cyberpanelLoading = false; - - url = "/websites/fetchGitignore"; - - + $scope.showWPSites = function(domain) { + var url = '/websites/fetchWPDetails'; var data = { - domain: $("#domain").text(), - folder: $scope.folder + domain: domain }; - - var config = { + + $http({ + method: 'POST', + url: url, + data: $.param(data), headers: { + 'Content-Type': 'application/x-www-form-urlencoded', 'X-CSRFToken': getCookie('csrftoken') } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - function ListInitialDatas(response) { - $scope.cyberpanelLoading = true; + }).then(function(response) { if (response.data.status === 1) { - new PNotify({ - title: 'Success', - text: 'Successfully fetched.', - type: 'success' + $scope.web.showWPSites = true; + $scope.web.wp_sites = response.data.sites.map(function(site) { + return { + id: site.id, + title: site.title, + url: site.url, + version: site.version, + status: site.status, + phpVersion: site.phpVersion || 'Unknown', + theme: site.theme || 'Default', + activePlugins: site.activePlugins || '0', + searchIndex: true, + debugging: false, + passwordProtection: false, + maintenanceMode: false + }; }); - $scope.gitIgnoreContent = response.data.gitIgnoreContent; } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); + $scope.web.showWPSites = false; + $scope.web.wp_sites = []; + alert('Error: ' + response.data.error_message); } + }).catch(function(error) { + $scope.web.showWPSites = false; + $scope.web.wp_sites = []; + alert('Error fetching WordPress sites: ' + JSON.stringify(error)); + }); + }; + $scope.visitSite = function(url) { + window.open(url, '_blank'); + }; - } - - function cantLoadInitialDatas(response) { - $scope.cyberpanelLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: 'Could not connect to server, please refresh this page.', - type: 'error' - }); - - + $scope.wpLogin = function(siteId) { + // You'll need to implement the login URL generation + var site = $scope.web.wp_sites.find(function(s) { return s.id === siteId; }); + if (site) { + window.open(site.url + '/wp-admin', '_blank'); } }; - $scope.saveGitIgnore = function () { - - $scope.cyberpanelLoading = false; - - url = "/websites/saveGitIgnore"; - - - var data = { - domain: $("#domain").text(), - folder: $scope.folder, - gitIgnoreContent: $scope.gitIgnoreContent - - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - function ListInitialDatas(response) { - $scope.cyberpanelLoading = true; - if (response.data.status === 1) { - new PNotify({ - title: 'Success', - text: 'Successfully saved.', - type: 'success' - }); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - } - - - } - - function cantLoadInitialDatas(response) { - $scope.cyberpanelLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: 'Could not connect to server, please refresh this page.', - type: 'error' - }); - - - } + $scope.manageWP = function(siteId) { + // Implement your management page navigation + window.location.href = '/websites/WPHome?ID=' + siteId; }; - $scope.fetchCommits = function () { - - $scope.cyberpanelLoading = false; - - url = "/websites/fetchCommits"; - - - var data = { - domain: $("#domain").text(), - folder: $scope.folder - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - function ListInitialDatas(response) { - $scope.cyberpanelLoading = true; - $scope.gitCommitsTable = false; - if (response.data.status === 1) { - new PNotify({ - title: 'Success', - text: 'Successfully fetched.', - type: 'success' - }); - $scope.commits = JSON.parse(response.data.commits); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - } - - - } - - function cantLoadInitialDatas(response) { - $scope.cyberpanelLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: 'Could not connect to server, please refresh this page.', - type: 'error' - }); - - - } + $scope.updateSetting = function(wp, setting) { + // Implement settings update logic here + console.log('Updating setting:', setting, 'for site:', wp.id); + // You would typically make an API call here to update the setting }; - var currentComit; - var fetchFileCheck = 0; - var initial = 1; - - $scope.fetchFiles = function (commit) { - - currentComit = commit; - $scope.cyberpanelLoading = false; - - if (initial === 1) { - initial = 0; - } else { - fetchFileCheck = 1; - } - - url = "/websites/fetchFiles"; - - - var data = { - domain: $("#domain").text(), - folder: $scope.folder, - commit: commit - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - function ListInitialDatas(response) { - $scope.cyberpanelLoading = true; - $scope.gitCommitsTable = false; - if (response.data.status === 1) { - new PNotify({ - title: 'Success', - text: 'Successfully fetched.', - type: 'success' - }); - $scope.files = response.data.files; - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - } - - - } - - function cantLoadInitialDatas(response) { - $scope.cyberpanelLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: 'Could not connect to server, please refresh this page.', - type: 'error' - }); - - - } - }; - - $scope.fileStatus = true; - - $scope.fetchChangesInFile = function () { - $scope.fileStatus = true; - - if (fetchFileCheck === 1) { - fetchFileCheck = 0; - return 0; - } - - $scope.cyberpanelLoading = false; - $scope.currentSelectedFile = $scope.changeFile; - - url = "/websites/fetchChangesInFile"; - - var data = { - domain: $("#domain").text(), - folder: $scope.folder, - file: $scope.changeFile, - commit: currentComit - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - function ListInitialDatas(response) { - $scope.cyberpanelLoading = true; - if (response.data.status === 1) { - new PNotify({ - title: 'Success', - text: 'Successfully fetched.', - type: 'success' - }); - $scope.fileStatus = false; - document.getElementById("fileChangedContent").innerHTML = response.data.fileChangedContent; - } else { - $scope.fileStatus = true; - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - } - } - - function cantLoadInitialDatas(response) { - $scope.cyberpanelLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: 'Could not connect to server, please refresh this page.', - type: 'error' - }); - - - } - }; - - $scope.saveGitConfigurations = function () { - - $scope.cyberpanelLoading = false; - - url = "/websites/saveGitConfigurations"; - - var data = { - domain: $("#domain").text(), - folder: $scope.folder, - autoCommit: $scope.autoCommit, - autoPush: $scope.autoPush, - emailLogs: $scope.emailLogs, - commands: document.getElementById("currentCommands").value, - webhookCommand: $scope.webhookCommand - }; - - if ($scope.autoCommit === undefined) { - $scope.autoCommitCurrent = 'Never'; - } else { - $scope.autoCommitCurrent = $scope.autoCommit; - } - - if ($scope.autoPush === undefined) { - $scope.autoPushCurrent = 'Never'; - } else { - $scope.autoPushCurrent = $scope.autoPush; - } - - if ($scope.emailLogs === undefined) { - $scope.emailLogsCurrent = false; - } else { - $scope.emailLogsCurrent = $scope.emailLogs; - } - - if ($scope.webhookCommand === undefined) { - $scope.webhookCommandCurrent = false; - } else { - $scope.webhookCommandCurrent = $scope.webhookCommand; - } - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - function ListInitialDatas(response) { - $scope.cyberpanelLoading = true; - if (response.data.status === 1) { - new PNotify({ - title: 'Success', - text: 'Successfully saved.', - type: 'success' - }); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - } - } - - function cantLoadInitialDatas(response) { - $scope.cyberpanelLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: 'Could not connect to server, please refresh this page.', - type: 'error' - }); - - - } - }; - - $scope.currentPage = 1; - $scope.recordsToShow = 10; - - $scope.fetchGitLogs = function () { - $scope.cyberpanelLoading = false; - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - var data = { - domain: $("#domain").text(), - folder: $scope.folder, - page: $scope.currentPage, - recordsToShow: $scope.recordsToShow - }; - - - dataurl = "/websites/fetchGitLogs"; - - $http.post(dataurl, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - function ListInitialDatas(response) { - $scope.cyberpanelLoading = true; - if (response.data.status === 1) { - new PNotify({ - title: 'Success', - text: 'Successfully fetched.', - type: 'success' - }); - $scope.logs = JSON.parse(response.data.logs); - $scope.pagination = response.data.pagination; - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - } - } - - function cantLoadInitialDatas(response) { - $scope.cyberpanelLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: 'Could not connect to server, please refresh this page.', - type: 'error' - }); - - - } - - - }; - -}); - -/* Java script code to git tracking ends here */ - - -app.controller('ApacheManager', function ($scope, $http, $timeout) { - $scope.cyberpanelloading = true; - $scope.apacheOLS = true; - $scope.pureOLS = true; - $scope.lswsEnt = true; - - var apache = 1, ols = 2, lsws = 3; - var statusFile; - - $scope.getSwitchStatus = function () { - $scope.cyberpanelloading = false; - url = "/websites/getSwitchStatus"; - - var data = { - domainName: $("#domainNamePage").text() - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialData, cantLoadInitialData); - - - function ListInitialData(response) { - $scope.cyberpanelloading = true; - if (response.data.status === 1) { - if (response.data.server === apache) { - $scope.apacheOLS = false; - $scope.pureOLS = true; - $scope.lswsEnt = true; - $scope.configData = response.data.configData; - - $scope.pmMaxChildren = response.data.pmMaxChildren; - $scope.pmStartServers = response.data.pmStartServers; - $scope.pmMinSpareServers = response.data.pmMinSpareServers; - $scope.pmMaxSpareServers = response.data.pmMaxSpareServers; - $scope.phpPath = response.data.phpPath; - - - } else if (response.data.server === ols) { - $scope.apacheOLS = true; - $scope.pureOLS = false; - $scope.lswsEnt = true; - } else { - $scope.apacheOLS = true; - $scope.pureOLS = true; - $scope.lswsEnt = false; - } - //$scope.records = JSON.parse(response.data.data); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - } - } - - function cantLoadInitialData(response) { - $scope.cyberpanelloading = true; - new PNotify({ - title: 'Operation Failed!', - text: 'Could not connect to server, please refresh this page.', - type: 'error' - }); - } - - - }; - $scope.getSwitchStatus(); - - $scope.switchServer = function (server) { - $scope.cyberpanelloading = false; - $scope.functionProgress = {"width": "0%"}; - $scope.functionStatus = 'Starting conversion..'; - - url = "/websites/switchServer"; - - var data = { - domainName: $("#domainNamePage").text(), - phpSelection: $scope.phpSelection, - server: server - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialData, cantLoadInitialData); - - function ListInitialData(response) { - if (response.data.status === 1) { - statusFile = response.data.tempStatusPath; - statusFunc(); - - } else { - $scope.cyberpanelloading = true; - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - } - - } - - function cantLoadInitialData(response) { - $scope.cyberpanelloading = true; - new PNotify({ - title: 'Operation Failed!', - text: 'Could not connect to server, please refresh this page.', - type: 'error' - }); - } - - - }; - - function statusFunc() { - $scope.cyberpanelloading = false; - url = "/websites/statusFunc"; - - var data = { - statusFile: statusFile - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialData, cantLoadInitialData); - - - function ListInitialData(response) { - if (response.data.status === 1) { - if (response.data.abort === 1) { - $scope.functionProgress = {"width": "100%"}; - $scope.functionStatus = response.data.currentStatus; - $scope.cyberpanelloading = true; - $timeout.cancel(); - $scope.getSwitchStatus(); - } else { - $scope.functionProgress = {"width": response.data.installationProgress + "%"}; - $scope.functionStatus = response.data.currentStatus; - $timeout(statusFunc, 3000); - } - - } else { - $scope.cyberpanelloading = true; - $scope.functionStatus = response.data.error_message; - $scope.functionProgress = {"width": response.data.installationProgress + "%"}; - $timeout.cancel(); - } - - } - - function cantLoadInitialData(response) { - $scope.functionProgress = {"width": response.data.installationProgress + "%"}; - $scope.functionStatus = 'Could not connect to server, please refresh this page.'; - $timeout.cancel(); - } - - } - - - $scope.tuneSettings = function () { - $scope.cyberpanelloading = false; - - url = "/websites/tuneSettings"; - - var data = { - domainName: $("#domainNamePage").text(), - pmMaxChildren: $scope.pmMaxChildren, - pmStartServers: $scope.pmStartServers, - pmMinSpareServers: $scope.pmMinSpareServers, - pmMaxSpareServers: $scope.pmMaxSpareServers, - phpPath: $scope.phpPath - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialData, cantLoadInitialData); - - function ListInitialData(response) { - $scope.cyberpanelloading = true; - if (response.data.status === 1) { - - new PNotify({ - title: 'Success', - text: 'Changes successfully applied.', - type: 'success' - }); - - } else { - $scope.cyberpanelloading = true; - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - } - - } - - function cantLoadInitialData(response) { - $scope.cyberpanelloading = true; - new PNotify({ - title: 'Operation Failed!', - text: 'Could not connect to server, please refresh this page.', - type: 'error' - }); - } - - - }; - - $scope.saveApacheConfig = function () { - $scope.cyberpanelloading = false; - - url = "/websites/saveApacheConfigsToFile"; - - var data = { - domainName: $("#domainNamePage").text(), - configData: $scope.configData - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialData, cantLoadInitialData); - - function ListInitialData(response) { - $scope.cyberpanelloading = true; - if (response.data.status === 1) { - - new PNotify({ - title: 'Success', - text: 'Changes successfully applied.', - type: 'success' - }); - - } else { - $scope.cyberpanelloading = true; - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - } - - } - - function cantLoadInitialData(response) { - $scope.cyberpanelloading = true; - new PNotify({ - title: 'Operation Failed!', - text: 'Could not connect to server, please refresh this page.', - type: 'error' - }); - } - - - }; - -}); - app.controller('createDockerPackage', function ($scope, $http, $window) { $scope.cyberpanelLoading = true; diff --git a/websiteFunctions/website.py b/websiteFunctions/website.py index dd7fe2c6f..280191367 100755 --- a/websiteFunctions/website.py +++ b/websiteFunctions/website.py @@ -7053,7 +7053,7 @@ StrictHostKeyChecking no proc = httpProc(request, 'websiteFunctions/DockerSiteHome.html', {'dockerSite': ds}) return proc.render() - + def fetchWPSitesForDomain(self, userID=None, data=None): try: currentACL = ACLManager.loadedACL(userID) @@ -7064,7 +7064,7 @@ StrictHostKeyChecking no if ACLManager.checkOwnership(domain, admin, currentACL) != 1: return ACLManager.loadErrorJson('fetchStatus', 0) - + wp_sites = WPSites.objects.filter(owner=website) sites = [] @@ -7082,10 +7082,10 @@ StrictHostKeyChecking no version = html.escape(version) - sites.append({ - 'id': site.id, - 'title': site.title, - 'url': site.FinalURL, + sites.append({ + 'id': site.id, + 'title': site.title, + 'url': site.FinalURL, 'path': site.path, 'version': version, }) @@ -7093,7 +7093,7 @@ StrictHostKeyChecking no data_ret = {'status': 1, 'fetchStatus': 1, 'error_message': "None", "sites": sites} json_data = json.dumps(data_ret) return HttpResponse(json_data) - + except BaseException as msg: data_ret = {'status': 0, 'fetchStatus': 0, 'error_message': str(msg)} json_data = json.dumps(data_ret) From 955a5e398b9b22c4015d5b2d82ca0867a0760951 Mon Sep 17 00:00:00 2001 From: usmannasir Date: Fri, 4 Apr 2025 18:38:24 +0500 Subject: [PATCH 012/273] fix vhuser in function --- .../websiteFunctions/websiteFunctions.js | 1504 +++++++++++++++-- websiteFunctions/website.py | 4 +- 2 files changed, 1388 insertions(+), 120 deletions(-) diff --git a/websiteFunctions/static/websiteFunctions/websiteFunctions.js b/websiteFunctions/static/websiteFunctions/websiteFunctions.js index 7f8a1961e..7664c65bd 100755 --- a/websiteFunctions/static/websiteFunctions/websiteFunctions.js +++ b/websiteFunctions/static/websiteFunctions/websiteFunctions.js @@ -2690,31 +2690,19 @@ app.controller('listWebsites', function ($scope, $http, $window) { } }).then(function(response) { if (response.data.status === 1) { - $scope.web.showWPSites = true; - $scope.web.wp_sites = response.data.sites.map(function(site) { - return { - id: site.id, - title: site.title, - url: site.url, - version: site.version, - status: site.status, - phpVersion: site.phpVersion || 'Unknown', - theme: site.theme || 'Default', - activePlugins: site.activePlugins || '0', - searchIndex: true, - debugging: false, - passwordProtection: false, - maintenanceMode: false - }; + var sites = response.data.sites; + var message = 'WordPress Sites for ' + domain + ':\n\n'; + sites.forEach(function(site) { + message += 'Title: ' + site.title + '\n'; + message += 'URL: ' + site.url + '\n'; + message += 'Version: ' + site.version + '\n'; + message += 'Status: ' + site.status + '\n\n'; }); + alert(message); } else { - $scope.web.showWPSites = false; - $scope.web.wp_sites = []; alert('Error: ' + response.data.error_message); } }).catch(function(error) { - $scope.web.showWPSites = false; - $scope.web.wp_sites = []; alert('Error fetching WordPress sites: ' + JSON.stringify(error)); }); }; @@ -2723,23 +2711,65 @@ app.controller('listWebsites', function ($scope, $http, $window) { window.open(url, '_blank'); }; - $scope.wpLogin = function(siteId) { - // You'll need to implement the login URL generation - var site = $scope.web.wp_sites.find(function(s) { return s.id === siteId; }); - if (site) { - window.open(site.url + '/wp-admin', '_blank'); - } + $scope.wpLogin = function(wpId) { + window.open('/websites/wpLogin?wpID=' + wpId, '_blank'); }; - $scope.manageWP = function(siteId) { - // Implement your management page navigation - window.location.href = '/websites/WPHome?ID=' + siteId; + $scope.manageWP = function(wpId) { + window.location.href = '/websites/listWPsites?wpID=' + wpId; }; $scope.updateSetting = function(wp, setting) { - // Implement settings update logic here - console.log('Updating setting:', setting, 'for site:', wp.id); - // You would typically make an API call here to update the setting + var settingMap = { + 'search-indexing': 'searchIndex', + 'debugging': 'debugging', + 'password-protection': 'passwordProtection', + 'maintenance-mode': 'maintenanceMode' + }; + + var data = { + wpID: wp.id, + setting: setting, + value: wp[settingMap[setting]] ? 'enable' : 'disable' + }; + + $http({ + method: 'POST', + url: '/websites/UpdateWPSettings', + data: data, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'X-CSRFToken': getCookie('csrftoken') + }, + transformRequest: function(obj) { + var str = []; + for(var p in obj) + str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); + return str.join("&"); + } + }).then(function(response) { + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: 'Setting updated successfully.', + type: 'success' + }); + } else { + wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change + new PNotify({ + title: 'Error', + text: 'Failed to update setting.', + type: 'error' + }); + } + }).catch(function(error) { + wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change + new PNotify({ + title: 'Error', + text: 'Connection failed while updating setting.', + type: 'error' + }); + }); }; $scope.cyberPanelLoading = true; @@ -6560,64 +6590,667 @@ app.controller('manageAliasController', function ($scope, $http, $timeout, $wind } }).then(function(response) { if (response.data.status === 1) { - $scope.web.showWPSites = true; - $scope.web.wp_sites = response.data.sites.map(function(site) { - return { - id: site.id, - title: site.title, - url: site.url, - version: site.version, - status: site.status, - phpVersion: site.phpVersion || 'Unknown', - theme: site.theme || 'Default', - activePlugins: site.activePlugins || '0', - searchIndex: true, - debugging: false, - passwordProtection: false, - maintenanceMode: false - }; + var sites = response.data.sites; + var message = 'WordPress Sites for ' + domain + ':\n\n'; + sites.forEach(function(site) { + message += 'Title: ' + site.title + '\n'; + message += 'URL: ' + site.url + '\n'; + message += 'Version: ' + site.version + '\n'; + message += 'Status: ' + site.status + '\n\n'; }); + alert(message); } else { - $scope.web.showWPSites = false; - $scope.web.wp_sites = []; alert('Error: ' + response.data.error_message); } }).catch(function(error) { - $scope.web.showWPSites = false; - $scope.web.wp_sites = []; alert('Error fetching WordPress sites: ' + JSON.stringify(error)); }); }; + $scope.updateSetting = function(wp, setting) { + var settingMap = { + 'search-indexing': 'searchIndex', + 'debugging': 'debugging', + 'password-protection': 'passwordProtection', + 'maintenance-mode': 'maintenanceMode' + }; + + var data = { + wpID: wp.id, + setting: setting, + value: wp[settingMap[setting]] ? 'enable' : 'disable' + }; + + $http({ + method: 'POST', + url: '/websites/UpdateWPSettings', + data: data, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'X-CSRFToken': getCookie('csrftoken') + }, + transformRequest: function(obj) { + var str = []; + for(var p in obj) + str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); + return str.join("&"); + } + }).then(function(response) { + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: 'Setting updated successfully.', + type: 'success' + }); + } else { + wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change + new PNotify({ + title: 'Error', + text: 'Failed to update setting.', + type: 'error' + }); + } + }).catch(function(error) { + wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change + new PNotify({ + title: 'Error', + text: 'Connection failed while updating setting.', + type: 'error' + }); + }); + }; + $scope.visitSite = function(url) { window.open(url, '_blank'); }; - $scope.wpLogin = function(siteId) { - // You'll need to implement the login URL generation - var site = $scope.web.wp_sites.find(function(s) { return s.id === siteId; }); - if (site) { - window.open(site.url + '/wp-admin', '_blank'); + $scope.wpLogin = function(wpId) { + window.open('/websites/wpLogin?wpID=' + wpId, '_blank'); + }; + + $scope.manageWP = function(wpId) { + window.location.href = '/websites/listWPsites?wpID=' + wpId; + }; + + $scope.updateSetting = function(wp, setting) { + var settingMap = { + 'search-indexing': 'searchIndex', + 'debugging': 'debugging', + 'password-protection': 'passwordProtection', + 'maintenance-mode': 'maintenanceMode' + }; + + var data = { + wpID: wp.id, + setting: setting, + value: wp[settingMap[setting]] ? 'enable' : 'disable' + }; + + $http({ + method: 'POST', + url: '/websites/UpdateWPSettings', + data: data, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'X-CSRFToken': getCookie('csrftoken') + }, + transformRequest: function(obj) { + var str = []; + for(var p in obj) + str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); + return str.join("&"); + } + }).then(function(response) { + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: 'Setting updated successfully.', + type: 'success' + }); + } else { + wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change + new PNotify({ + title: 'Error', + text: 'Failed to update setting.', + type: 'error' + }); + } + }).catch(function(error) { + wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change + new PNotify({ + title: 'Error', + text: 'Connection failed while updating setting.', + type: 'error' + }); + }); + }; + + $scope.saveRewriteRules = function () { + + $scope.configFileLoading = false; + + + url = "/websites/saveRewriteRules"; + + var virtualHost = $("#childDomain").text(); + var rewriteRules = $scope.rewriteRules; + + + var data = { + virtualHost: virtualHost, + rewriteRules: rewriteRules, + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.rewriteStatus == 1) { + + $scope.configurationsBoxRewrite = false; + $scope.rewriteRulesFetched = true; + $scope.couldNotFetchRewriteRules = true; + $scope.rewriteRulesSaved = false; + $scope.couldNotSaveRewriteRules = true; + $scope.fetchedRewriteRules = true; + $scope.saveRewriteRulesBTN = true; + $scope.configFileLoading = true; + + + } else { + $scope.configurationsBoxRewrite = false; + $scope.rewriteRulesFetched = false; + $scope.couldNotFetchRewriteRules = true; + $scope.rewriteRulesSaved = true; + $scope.couldNotSaveRewriteRules = false; + $scope.fetchedRewriteRules = true; + $scope.saveRewriteRulesBTN = false; + + $scope.configFileLoading = true; + + + $scope.errorMessage = response.data.error_message; + + } + + } + + function cantLoadInitialDatas(response) { + + $scope.configurationsBoxRewrite = false; + $scope.rewriteRulesFetched = false; + $scope.couldNotFetchRewriteRules = true; + $scope.rewriteRulesSaved = true; + $scope.couldNotSaveRewriteRules = true; + $scope.fetchedRewriteRules = true; + $scope.saveRewriteRulesBTN = false; + + $scope.configFileLoading = true; + + $scope.couldNotConnect = false; + + + } + + }; - $scope.manageWP = function(siteId) { - // Implement your management page navigation - window.location.href = '/websites/WPHome?ID=' + siteId; + + //////// SSL Part + + $scope.sslSaved = true; + $scope.couldNotSaveSSL = true; + $scope.hidsslconfigs = true; + $scope.couldNotConnect = true; + + + $scope.hidesslbtn = function () { + $scope.hidsslconfigs = true; }; - $scope.updateSetting = function(wp, setting) { - // Implement settings update logic here - console.log('Updating setting:', setting, 'for site:', wp.id); - // You would typically make an API call here to update the setting + $scope.addSSL = function () { + $scope.hidsslconfigs = false; + $scope.configurationsBox = true; + $scope.configurationsBoxRewrite = true; + $scope.changePHPView = true; }; - $scope.updateSetting = function(wp, setting) { - // Implement settings update logic here - console.log('Updating setting:', setting, 'for site:', wp.id); - // You would typically make an API call here to update the setting + + $scope.saveSSL = function () { + + + $scope.configFileLoading = false; + + url = "/websites/saveSSL"; + + var virtualHost = $("#childDomain").text(); + var cert = $scope.cert; + var key = $scope.key; + + + var data = { + virtualHost: virtualHost, + cert: cert, + key: key, + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.sslStatus === 1) { + + $scope.sslSaved = false; + $scope.couldNotSaveSSL = true; + $scope.couldNotConnect = true; + $scope.configFileLoading = true; + + + } else { + + $scope.sslSaved = true; + $scope.couldNotSaveSSL = false; + $scope.couldNotConnect = true; + $scope.configFileLoading = true; + + $scope.errorMessage = response.data.error_message; + + } + + + } + + function cantLoadInitialDatas(response) { + + $scope.sslSaved = true; + $scope.couldNotSaveSSL = true; + $scope.couldNotConnect = false; + $scope.configFileLoading = true; + + + } + }; + + //// Change PHP Master + + $scope.failedToChangePHPMaster = true; + $scope.phpChangedMaster = true; + $scope.couldNotConnect = true; + + $scope.changePHPView = true; + + + $scope.hideChangePHPMaster = function () { + $scope.changePHPView = true; + }; + + $scope.changePHPMaster = function () { + $scope.hidsslconfigs = true; + $scope.configurationsBox = true; + $scope.configurationsBoxRewrite = true; + $scope.changePHPView = false; + }; + + + $scope.changePHPVersionMaster = function (childDomain, phpSelection) { + + // notifcations + + $scope.configFileLoading = false; + + var url = "/websites/changePHP"; + + var data = { + childDomain: $("#childDomain").text(), + phpSelection: $scope.phpSelectionMaster, + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + + if (response.data.changePHP === 1) { + + $scope.configFileLoading = true; + $scope.websiteDomain = $("#childDomain").text(); + + + // notifcations + + $scope.failedToChangePHPMaster = true; + $scope.phpChangedMaster = false; + $scope.couldNotConnect = true; + + + } else { + + $scope.configFileLoading = true; + $scope.errorMessage = response.data.error_message; + + // notifcations + + $scope.failedToChangePHPMaster = false; + $scope.phpChangedMaster = true; + $scope.couldNotConnect = true; + + } + + + } + + function cantLoadInitialDatas(response) { + + $scope.configFileLoading = true; + + // notifcations + + $scope.failedToChangePHPMaster = true; + $scope.phpChangedMaster = true; + $scope.couldNotConnect = false; + + } + + }; + + + /// Open_basedir protection + + $scope.baseDirLoading = true; + $scope.operationFailed = true; + $scope.operationSuccessfull = true; + $scope.couldNotConnect = true; + $scope.openBaseDirBox = true; + + + $scope.openBaseDirView = function () { + $scope.openBaseDirBox = false; + }; + + $scope.hideOpenBasedir = function () { + $scope.openBaseDirBox = true; + }; + + $scope.applyOpenBasedirChanges = function (childDomain, phpSelection) { + + // notifcations + + $scope.baseDirLoading = false; + $scope.operationFailed = true; + $scope.operationSuccessfull = true; + $scope.couldNotConnect = true; + $scope.openBaseDirBox = false; + + + var url = "/websites/changeOpenBasedir"; + + var data = { + domainName: $("#childDomain").text(), + openBasedirValue: $scope.openBasedirValue + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + + if (response.data.changeOpenBasedir === 1) { + + $scope.baseDirLoading = true; + $scope.operationFailed = true; + $scope.operationSuccessfull = false; + $scope.couldNotConnect = true; + $scope.openBaseDirBox = false; + + } else { + + $scope.baseDirLoading = true; + $scope.operationFailed = false; + $scope.operationSuccessfull = true; + $scope.couldNotConnect = true; + $scope.openBaseDirBox = false; + + $scope.errorMessage = response.data.error_message; + + } + + + } + + function cantLoadInitialDatas(response) { + + $scope.baseDirLoading = true; + $scope.operationFailed = true; + $scope.operationSuccessfull = true; + $scope.couldNotConnect = false; + $scope.openBaseDirBox = false; + + + } + + } + +}); + +/* Application Installer */ + +app.controller('installWordPressCTRL', function ($scope, $http, $timeout) { + + $scope.installationDetailsForm = false; + $scope.installationProgress = true; + $scope.installationFailed = true; + $scope.installationSuccessfull = true; + $scope.couldNotConnect = true; + $scope.wpInstallLoading = true; + $scope.goBackDisable = true; + + var statusFile; + var domain = $("#domainNamePage").text(); + var path; + + + $scope.goBack = function () { + $scope.installationDetailsForm = false; + $scope.installationProgress = true; + $scope.installationFailed = true; + $scope.installationSuccessfull = true; + $scope.couldNotConnect = true; + $scope.wpInstallLoading = true; + $scope.goBackDisable = true; + $("#installProgress").css("width", "0%"); + }; + + $scope.installWordPress = function () { + + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.installationFailed = true; + $scope.installationSuccessfull = true; + $scope.couldNotConnect = true; + $scope.wpInstallLoading = false; + $scope.goBackDisable = true; + $scope.currentStatus = "Starting installation.."; + + path = $scope.installPath; + + + url = "/websites/installWordpress"; + + var home = "1"; + + if (typeof path !== 'undefined') { + home = "0"; + } + + + var data = { + domain: domain, + home: home, + path: path, + blogTitle: $scope.blogTitle, + adminUser: $scope.adminUser, + passwordByPass: $scope.adminPassword, + adminEmail: $scope.adminEmail + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.installStatus === 1) { + statusFile = response.data.tempStatusPath; + getInstallStatus(); + } else { + + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.installationFailed = false; + $scope.installationSuccessfull = true; + $scope.couldNotConnect = true; + $scope.wpInstallLoading = true; + $scope.goBackDisable = false; + + $scope.errorMessage = response.data.error_message; + + } + + + } + + function cantLoadInitialDatas(response) { + + + } + + }; + + function getInstallStatus() { + + url = "/websites/installWordpressStatus"; + + var data = { + statusFile: statusFile, + domainName: domain + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + + if (response.data.abort === 1) { + + if (response.data.installStatus === 1) { + + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.installationFailed = true; + $scope.installationSuccessfull = false; + $scope.couldNotConnect = true; + $scope.wpInstallLoading = true; + $scope.goBackDisable = false; + + if (typeof path !== 'undefined') { + $scope.installationURL = "http://" + domain + "/" + path; + } else { + $scope.installationURL = domain; + } + + + $("#installProgress").css("width", "100%"); + $scope.installPercentage = "100"; + $scope.currentStatus = response.data.currentStatus; + $timeout.cancel(); + + } else { + + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.installationFailed = false; + $scope.installationSuccessfull = true; + $scope.couldNotConnect = true; + $scope.wpInstallLoading = true; + $scope.goBackDisable = false; + + $scope.errorMessage = response.data.error_message; + + $("#installProgress").css("width", "0%"); + $scope.installPercentage = "0"; + + } + + } else { + $("#installProgress").css("width", response.data.installationProgress + "%"); + $scope.installPercentage = response.data.installationProgress; + $scope.currentStatus = response.data.currentStatus; + + $timeout(getInstallStatus, 1000); + + + } + + } + + function cantLoadInitialDatas(response) { + + $scope.canNotFetch = true; + $scope.couldNotConnect = false; + + + } + + + } + + +}); + app.controller('installJoomlaCTRL', function ($scope, $http, $timeout) { $scope.installationDetailsForm = false; @@ -8804,74 +9437,709 @@ app.controller('manageGIT', function ($scope, $http, $timeout, $window) { } }; - $scope.showWPSites = function(domain) { - var url = '/websites/fetchWPDetails'; + $scope.fetchGitignore = function () { + + $scope.cyberpanelLoading = false; + + url = "/websites/fetchGitignore"; + + var data = { - domain: domain + domain: $("#domain").text(), + folder: $scope.folder }; - - $http({ - method: 'POST', - url: url, - data: $.param(data), + + var config = { headers: { - 'Content-Type': 'application/x-www-form-urlencoded', 'X-CSRFToken': getCookie('csrftoken') } - }).then(function(response) { + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + function ListInitialDatas(response) { + $scope.cyberpanelLoading = true; if (response.data.status === 1) { - $scope.web.showWPSites = true; - $scope.web.wp_sites = response.data.sites.map(function(site) { - return { - id: site.id, - title: site.title, - url: site.url, - version: site.version, - status: site.status, - phpVersion: site.phpVersion || 'Unknown', - theme: site.theme || 'Default', - activePlugins: site.activePlugins || '0', - searchIndex: true, - debugging: false, - passwordProtection: false, - maintenanceMode: false - }; + new PNotify({ + title: 'Success', + text: 'Successfully fetched.', + type: 'success' }); + $scope.gitIgnoreContent = response.data.gitIgnoreContent; } else { - $scope.web.showWPSites = false; - $scope.web.wp_sites = []; - alert('Error: ' + response.data.error_message); + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); } - }).catch(function(error) { - $scope.web.showWPSites = false; - $scope.web.wp_sites = []; - alert('Error fetching WordPress sites: ' + JSON.stringify(error)); - }); - }; - $scope.visitSite = function(url) { - window.open(url, '_blank'); - }; - $scope.wpLogin = function(siteId) { - // You'll need to implement the login URL generation - var site = $scope.web.wp_sites.find(function(s) { return s.id === siteId; }); - if (site) { - window.open(site.url + '/wp-admin', '_blank'); + } + + function cantLoadInitialDatas(response) { + $scope.cyberpanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page.', + type: 'error' + }); + + } }; - $scope.manageWP = function(siteId) { - // Implement your management page navigation - window.location.href = '/websites/WPHome?ID=' + siteId; + $scope.saveGitIgnore = function () { + + $scope.cyberpanelLoading = false; + + url = "/websites/saveGitIgnore"; + + + var data = { + domain: $("#domain").text(), + folder: $scope.folder, + gitIgnoreContent: $scope.gitIgnoreContent + + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + function ListInitialDatas(response) { + $scope.cyberpanelLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: 'Successfully saved.', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + + + } + + function cantLoadInitialDatas(response) { + $scope.cyberpanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page.', + type: 'error' + }); + + + } }; - $scope.updateSetting = function(wp, setting) { - // Implement settings update logic here - console.log('Updating setting:', setting, 'for site:', wp.id); - // You would typically make an API call here to update the setting + $scope.fetchCommits = function () { + + $scope.cyberpanelLoading = false; + + url = "/websites/fetchCommits"; + + + var data = { + domain: $("#domain").text(), + folder: $scope.folder + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + function ListInitialDatas(response) { + $scope.cyberpanelLoading = true; + $scope.gitCommitsTable = false; + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: 'Successfully fetched.', + type: 'success' + }); + $scope.commits = JSON.parse(response.data.commits); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + + + } + + function cantLoadInitialDatas(response) { + $scope.cyberpanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page.', + type: 'error' + }); + + + } }; + var currentComit; + var fetchFileCheck = 0; + var initial = 1; + + $scope.fetchFiles = function (commit) { + + currentComit = commit; + $scope.cyberpanelLoading = false; + + if (initial === 1) { + initial = 0; + } else { + fetchFileCheck = 1; + } + + url = "/websites/fetchFiles"; + + + var data = { + domain: $("#domain").text(), + folder: $scope.folder, + commit: commit + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + function ListInitialDatas(response) { + $scope.cyberpanelLoading = true; + $scope.gitCommitsTable = false; + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: 'Successfully fetched.', + type: 'success' + }); + $scope.files = response.data.files; + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + + + } + + function cantLoadInitialDatas(response) { + $scope.cyberpanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page.', + type: 'error' + }); + + + } + }; + + $scope.fileStatus = true; + + $scope.fetchChangesInFile = function () { + $scope.fileStatus = true; + + if (fetchFileCheck === 1) { + fetchFileCheck = 0; + return 0; + } + + $scope.cyberpanelLoading = false; + $scope.currentSelectedFile = $scope.changeFile; + + url = "/websites/fetchChangesInFile"; + + var data = { + domain: $("#domain").text(), + folder: $scope.folder, + file: $scope.changeFile, + commit: currentComit + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + function ListInitialDatas(response) { + $scope.cyberpanelLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: 'Successfully fetched.', + type: 'success' + }); + $scope.fileStatus = false; + document.getElementById("fileChangedContent").innerHTML = response.data.fileChangedContent; + } else { + $scope.fileStatus = true; + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialDatas(response) { + $scope.cyberpanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page.', + type: 'error' + }); + + + } + }; + + $scope.saveGitConfigurations = function () { + + $scope.cyberpanelLoading = false; + + url = "/websites/saveGitConfigurations"; + + var data = { + domain: $("#domain").text(), + folder: $scope.folder, + autoCommit: $scope.autoCommit, + autoPush: $scope.autoPush, + emailLogs: $scope.emailLogs, + commands: document.getElementById("currentCommands").value, + webhookCommand: $scope.webhookCommand + }; + + if ($scope.autoCommit === undefined) { + $scope.autoCommitCurrent = 'Never'; + } else { + $scope.autoCommitCurrent = $scope.autoCommit; + } + + if ($scope.autoPush === undefined) { + $scope.autoPushCurrent = 'Never'; + } else { + $scope.autoPushCurrent = $scope.autoPush; + } + + if ($scope.emailLogs === undefined) { + $scope.emailLogsCurrent = false; + } else { + $scope.emailLogsCurrent = $scope.emailLogs; + } + + if ($scope.webhookCommand === undefined) { + $scope.webhookCommandCurrent = false; + } else { + $scope.webhookCommandCurrent = $scope.webhookCommand; + } + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + function ListInitialDatas(response) { + $scope.cyberpanelLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: 'Successfully saved.', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialDatas(response) { + $scope.cyberpanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page.', + type: 'error' + }); + + + } + }; + + $scope.currentPage = 1; + $scope.recordsToShow = 10; + + $scope.fetchGitLogs = function () { + $scope.cyberpanelLoading = false; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + var data = { + domain: $("#domain").text(), + folder: $scope.folder, + page: $scope.currentPage, + recordsToShow: $scope.recordsToShow + }; + + + dataurl = "/websites/fetchGitLogs"; + + $http.post(dataurl, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + function ListInitialDatas(response) { + $scope.cyberpanelLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: 'Successfully fetched.', + type: 'success' + }); + $scope.logs = JSON.parse(response.data.logs); + $scope.pagination = response.data.pagination; + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialDatas(response) { + $scope.cyberpanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page.', + type: 'error' + }); + + + } + + + }; + +}); + +/* Java script code to git tracking ends here */ + + +app.controller('ApacheManager', function ($scope, $http, $timeout) { + $scope.cyberpanelloading = true; + $scope.apacheOLS = true; + $scope.pureOLS = true; + $scope.lswsEnt = true; + + var apache = 1, ols = 2, lsws = 3; + var statusFile; + + $scope.getSwitchStatus = function () { + $scope.cyberpanelloading = false; + url = "/websites/getSwitchStatus"; + + var data = { + domainName: $("#domainNamePage").text() + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialData, cantLoadInitialData); + + + function ListInitialData(response) { + $scope.cyberpanelloading = true; + if (response.data.status === 1) { + if (response.data.server === apache) { + $scope.apacheOLS = false; + $scope.pureOLS = true; + $scope.lswsEnt = true; + $scope.configData = response.data.configData; + + $scope.pmMaxChildren = response.data.pmMaxChildren; + $scope.pmStartServers = response.data.pmStartServers; + $scope.pmMinSpareServers = response.data.pmMinSpareServers; + $scope.pmMaxSpareServers = response.data.pmMaxSpareServers; + $scope.phpPath = response.data.phpPath; + + + } else if (response.data.server === ols) { + $scope.apacheOLS = true; + $scope.pureOLS = false; + $scope.lswsEnt = true; + } else { + $scope.apacheOLS = true; + $scope.pureOLS = true; + $scope.lswsEnt = false; + } + //$scope.records = JSON.parse(response.data.data); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialData(response) { + $scope.cyberpanelloading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page.', + type: 'error' + }); + } + + + }; + $scope.getSwitchStatus(); + + $scope.switchServer = function (server) { + $scope.cyberpanelloading = false; + $scope.functionProgress = {"width": "0%"}; + $scope.functionStatus = 'Starting conversion..'; + + url = "/websites/switchServer"; + + var data = { + domainName: $("#domainNamePage").text(), + phpSelection: $scope.phpSelection, + server: server + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialData, cantLoadInitialData); + + function ListInitialData(response) { + if (response.data.status === 1) { + statusFile = response.data.tempStatusPath; + statusFunc(); + + } else { + $scope.cyberpanelloading = true; + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + + } + + function cantLoadInitialData(response) { + $scope.cyberpanelloading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page.', + type: 'error' + }); + } + + + }; + + function statusFunc() { + $scope.cyberpanelloading = false; + url = "/websites/statusFunc"; + + var data = { + statusFile: statusFile + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialData, cantLoadInitialData); + + + function ListInitialData(response) { + if (response.data.status === 1) { + if (response.data.abort === 1) { + $scope.functionProgress = {"width": "100%"}; + $scope.functionStatus = response.data.currentStatus; + $scope.cyberpanelloading = true; + $timeout.cancel(); + $scope.getSwitchStatus(); + } else { + $scope.functionProgress = {"width": response.data.installationProgress + "%"}; + $scope.functionStatus = response.data.currentStatus; + $timeout(statusFunc, 3000); + } + + } else { + $scope.cyberpanelloading = true; + $scope.functionStatus = response.data.error_message; + $scope.functionProgress = {"width": response.data.installationProgress + "%"}; + $timeout.cancel(); + } + + } + + function cantLoadInitialData(response) { + $scope.functionProgress = {"width": response.data.installationProgress + "%"}; + $scope.functionStatus = 'Could not connect to server, please refresh this page.'; + $timeout.cancel(); + } + + } + + + $scope.tuneSettings = function () { + $scope.cyberpanelloading = false; + + url = "/websites/tuneSettings"; + + var data = { + domainName: $("#domainNamePage").text(), + pmMaxChildren: $scope.pmMaxChildren, + pmStartServers: $scope.pmStartServers, + pmMinSpareServers: $scope.pmMinSpareServers, + pmMaxSpareServers: $scope.pmMaxSpareServers, + phpPath: $scope.phpPath + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialData, cantLoadInitialData); + + function ListInitialData(response) { + $scope.cyberpanelloading = true; + if (response.data.status === 1) { + + new PNotify({ + title: 'Success', + text: 'Changes successfully applied.', + type: 'success' + }); + + } else { + $scope.cyberpanelloading = true; + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + + } + + function cantLoadInitialData(response) { + $scope.cyberpanelloading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page.', + type: 'error' + }); + } + + + }; + + $scope.saveApacheConfig = function () { + $scope.cyberpanelloading = false; + + url = "/websites/saveApacheConfigsToFile"; + + var data = { + domainName: $("#domainNamePage").text(), + configData: $scope.configData + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialData, cantLoadInitialData); + + function ListInitialData(response) { + $scope.cyberpanelloading = true; + if (response.data.status === 1) { + + new PNotify({ + title: 'Success', + text: 'Changes successfully applied.', + type: 'success' + }); + + } else { + $scope.cyberpanelloading = true; + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + + } + + function cantLoadInitialData(response) { + $scope.cyberpanelloading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page.', + type: 'error' + }); + } + + + }; + +}); + app.controller('createDockerPackage', function ($scope, $http, $window) { $scope.cyberpanelLoading = true; diff --git a/websiteFunctions/website.py b/websiteFunctions/website.py index 280191367..cc6a8f78c 100755 --- a/websiteFunctions/website.py +++ b/websiteFunctions/website.py @@ -7091,8 +7091,8 @@ StrictHostKeyChecking no }) data_ret = {'status': 1, 'fetchStatus': 1, 'error_message': "None", "sites": sites} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) + json_data = json.dumps(data_ret) + return HttpResponse(json_data) except BaseException as msg: data_ret = {'status': 0, 'fetchStatus': 0, 'error_message': str(msg)} From 182af8090a2285eeeb35763e25de444e0bc1c05d Mon Sep 17 00:00:00 2001 From: usmannasir Date: Fri, 4 Apr 2025 18:45:14 +0500 Subject: [PATCH 013/273] fix vhuser in function --- websiteFunctions/website.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/websiteFunctions/website.py b/websiteFunctions/website.py index cc6a8f78c..280191367 100755 --- a/websiteFunctions/website.py +++ b/websiteFunctions/website.py @@ -7091,8 +7091,8 @@ StrictHostKeyChecking no }) data_ret = {'status': 1, 'fetchStatus': 1, 'error_message': "None", "sites": sites} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) + json_data = json.dumps(data_ret) + return HttpResponse(json_data) except BaseException as msg: data_ret = {'status': 0, 'fetchStatus': 0, 'error_message': str(msg)} From 64ddabeac45772158c66e82798626f608bba51cc Mon Sep 17 00:00:00 2001 From: usmannasir Date: Fri, 4 Apr 2025 18:50:03 +0500 Subject: [PATCH 014/273] fix vhuser in function --- .../websiteFunctions/websiteFunctions.js | 40 ++++++++----------- 1 file changed, 16 insertions(+), 24 deletions(-) diff --git a/websiteFunctions/static/websiteFunctions/websiteFunctions.js b/websiteFunctions/static/websiteFunctions/websiteFunctions.js index 7664c65bd..5c3d53e41 100755 --- a/websiteFunctions/static/websiteFunctions/websiteFunctions.js +++ b/websiteFunctions/static/websiteFunctions/websiteFunctions.js @@ -2677,35 +2677,27 @@ app.controller('listWebsites', function ($scope, $http, $window) { $scope.showWPSites = function(domain) { var url = '/websites/fetchWPDetails'; var data = { - domain: domain + domain: domain }; - $http({ - method: 'POST', - url: url, - data: $.param(data), - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', - 'X-CSRFToken': getCookie('csrftoken') - } + method: 'POST', + url: url, + data: $.param(data), + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'X-CSRFToken': getCookie('csrftoken') + } }).then(function(response) { - if (response.data.status === 1) { - var sites = response.data.sites; - var message = 'WordPress Sites for ' + domain + ':\n\n'; - sites.forEach(function(site) { - message += 'Title: ' + site.title + '\n'; - message += 'URL: ' + site.url + '\n'; - message += 'Version: ' + site.version + '\n'; - message += 'Status: ' + site.status + '\n\n'; - }); - alert(message); - } else { - alert('Error: ' + response.data.error_message); - } + if (response.data.status === 1) { + $scope.web.wp_sites = response.data.sites; + $scope.web.showWPSites = true; + } else { + alert('Error: ' + response.data.error_message); + } }).catch(function(error) { - alert('Error fetching WordPress sites: ' + JSON.stringify(error)); + alert('Error fetching WordPress sites: ' + JSON.stringify(error)); }); - }; + }; $scope.visitSite = function(url) { window.open(url, '_blank'); From f2cf861069e6494772349ef8fa16d911d31999c4 Mon Sep 17 00:00:00 2001 From: usmannasir Date: Fri, 4 Apr 2025 21:00:38 +0500 Subject: [PATCH 015/273] fix showwpsites --- .../static/websiteFunctions/websiteFunctions.js | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/websiteFunctions/static/websiteFunctions/websiteFunctions.js b/websiteFunctions/static/websiteFunctions/websiteFunctions.js index 5c3d53e41..c01ff2160 100755 --- a/websiteFunctions/static/websiteFunctions/websiteFunctions.js +++ b/websiteFunctions/static/websiteFunctions/websiteFunctions.js @@ -2674,7 +2674,7 @@ app.controller('listWebsites', function ($scope, $http, $window) { // Call it immediately $scope.getFurtherWebsitesFromDB(); - $scope.showWPSites = function(domain) { + $scope.Sites = function(domain) { var url = '/websites/fetchWPDetails'; var data = { domain: domain @@ -2688,16 +2688,19 @@ app.controller('listWebsites', function ($scope, $http, $window) { 'X-CSRFToken': getCookie('csrftoken') } }).then(function(response) { - if (response.data.status === 1) { + if (response.data.status === 1 && response.data.fetchStatus === 1) { $scope.web.wp_sites = response.data.sites; $scope.web.showWPSites = true; + $("#listFail").hide(); } else { - alert('Error: ' + response.data.error_message); + $("#listFail").fadeIn(); + $scope.errorMessage = response.data.error_message || 'Failed to fetch WordPress sites'; } }).catch(function(error) { - alert('Error fetching WordPress sites: ' + JSON.stringify(error)); + $("#listFail").fadeIn(); + $scope.errorMessage = error.message || 'An error occurred while fetching WordPress sites'; }); - }; + }; $scope.visitSite = function(url) { window.open(url, '_blank'); @@ -6581,7 +6584,7 @@ app.controller('manageAliasController', function ($scope, $http, $timeout, $wind 'X-CSRFToken': getCookie('csrftoken') } }).then(function(response) { - if (response.data.status === 1) { + if (response.data.status === 1 && response.data.fetchStatus === 1) { var sites = response.data.sites; var message = 'WordPress Sites for ' + domain + ':\n\n'; sites.forEach(function(site) { From 5ca3b4d7685303362554da4b8c649a08fc7bc01d Mon Sep 17 00:00:00 2001 From: usmannasir Date: Fri, 4 Apr 2025 21:10:07 +0500 Subject: [PATCH 016/273] fix showwpsites --- .../websiteFunctions/websiteFunctions.js | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/websiteFunctions/static/websiteFunctions/websiteFunctions.js b/websiteFunctions/static/websiteFunctions/websiteFunctions.js index c01ff2160..96901f874 100755 --- a/websiteFunctions/static/websiteFunctions/websiteFunctions.js +++ b/websiteFunctions/static/websiteFunctions/websiteFunctions.js @@ -6585,20 +6585,16 @@ app.controller('manageAliasController', function ($scope, $http, $timeout, $wind } }).then(function(response) { if (response.data.status === 1 && response.data.fetchStatus === 1) { - var sites = response.data.sites; - var message = 'WordPress Sites for ' + domain + ':\n\n'; - sites.forEach(function(site) { - message += 'Title: ' + site.title + '\n'; - message += 'URL: ' + site.url + '\n'; - message += 'Version: ' + site.version + '\n'; - message += 'Status: ' + site.status + '\n\n'; - }); - alert(message); + $scope.web.wp_sites = response.data.sites; + $scope.web.showWPSites = true; + $("#listFail").hide(); } else { - alert('Error: ' + response.data.error_message); + $("#listFail").fadeIn(); + $scope.errorMessage = response.data.error_message || 'Failed to fetch WordPress sites'; } }).catch(function(error) { - alert('Error fetching WordPress sites: ' + JSON.stringify(error)); + $("#listFail").fadeIn(); + $scope.errorMessage = error.message || 'An error occurred while fetching WordPress sites'; }); }; From c2dd1cd0ae0d0caf0dc3c205f067aedabbfc8b18 Mon Sep 17 00:00:00 2001 From: usmannasir Date: Fri, 4 Apr 2025 21:16:06 +0500 Subject: [PATCH 017/273] fix showwpsites --- .../websiteFunctions/websiteFunctions.js | 4920 ++++++++++++++++- 1 file changed, 4919 insertions(+), 1 deletion(-) diff --git a/websiteFunctions/static/websiteFunctions/websiteFunctions.js b/websiteFunctions/static/websiteFunctions/websiteFunctions.js index 96901f874..ce1b6200e 100755 --- a/websiteFunctions/static/websiteFunctions/websiteFunctions.js +++ b/websiteFunctions/static/websiteFunctions/websiteFunctions.js @@ -2674,7 +2674,7 @@ app.controller('listWebsites', function ($scope, $http, $window) { // Call it immediately $scope.getFurtherWebsitesFromDB(); - $scope.Sites = function(domain) { + $scope.showWPSites = function(domain) { var url = '/websites/fetchWPDetails'; var data = { domain: domain @@ -4862,6 +4862,4924 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { $("#listDomains").hide(); + $scope.showListDomains = function () { + fetchDomains(); + $("#listDomains").fadeIn(); + }; + + $scope.hideListDomains = function () { + $("#listDomains").fadeOut(); + }; + + function fetchDomains() { + $scope.domainLoading = false; + + var url = "/websites/fetchDomains"; + + var data = { + masterDomain: $("#domainNamePage").text(), + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + + if (response.data.fetchStatus === 1) { + + $scope.childDomains = JSON.parse(response.data.data); + $scope.domainLoading = true; + + + } else { + $scope.domainError = false; + $scope.errorMessage = response.data.error_message; + $scope.domainLoading = true; + } + + + } + + function cantLoadInitialDatas(response) { + + $scope.couldNotConnect = false; + + } + + } + +/** + * Created by usman on 7/26/17. + */ +function getCookie(name) { + var cookieValue = null; + var t = document.cookie; + if (document.cookie && document.cookie !== '') { + var cookies = document.cookie.split(';'); + for (var i = 0; i < cookies.length; i++) { + var cookie = jQuery.trim(cookies[i]); + // Does this cookie string begin with the name we want? + if (cookie.substring(0, name.length + 1) === (name + '=')) { + cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); + break; + } + } + } + return cookieValue; +} + + +var arry = [] + +function selectpluginJs(val) { + $('#mysearch').hide() + arry.push(val) + + // console.log(arry) + document.getElementById('selJS').innerHTML = ""; + + for (var i = 0; i < arry.length; i++) { + $('#selJS').show() + var mlm = ' ' + arry[i] + '    ' + $('#selJS').append(mlm) + } + + +} + + +var DeletePluginURL; + +function DeletePluginBuucket(url) { + DeletePluginURL = url; +} + +function FinalDeletePluginBuucket() { + window.location.href = DeletePluginURL; +} + +var SPVal; + +app.controller('WPAddNewPlugin', function ($scope, $http, $timeout, $window, $compile) { + $scope.webSiteCreationLoading = true; + + $scope.SearchPluginName = function (val) { + $scope.webSiteCreationLoading = false; + SPVal = val; + url = "/websites/SearchOnkeyupPlugin"; + + var searchcontent = $scope.searchcontent; + + + var data = { + pluginname: searchcontent + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.webSiteCreationLoading = true; + + if (response.data.status === 1) { + if (SPVal == 'add') { + $('#mysearch').show() + document.getElementById('mysearch').innerHTML = ""; + var res = response.data.plugns.plugins + // console.log(res); + for (i = 0; i <= res.length; i++) { + // + var tml = '
    '; + $('#mysearch').append(tml); + } + } else if (SPVal == 'eidt') { + $('#mysearch').show() + document.getElementById('mysearch').innerHTML = ""; + var res = response.data.plugns.plugins + // console.log(res); + for (i = 0; i <= res.length; i++) { + // + var tml = '
    '; + var temp = $compile(tml)($scope) + angular.element(document.getElementById('mysearch')).append(temp); + } + + } + + + } else { + + // $scope.errorMessage = response.data.error_message; + alert("Status not = 1: Error..." + response.data.error_message) + } + + + } + + function cantLoadInitialDatas(response) { + + alert("Error..." + response) + + } + } + + $scope.AddNewplugin = function () { + + url = "/websites/AddNewpluginAjax"; + + var bucketname = $scope.PluginbucketName + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + var data = { + config: arry, + Name: bucketname + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + function ListInitialDatas(response) { + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Bucket created.', + type: 'success' + }); + location.reload(); + } else { + + new PNotify({ + title: 'Error!', + text: response.data.error_message, + type: 'error' + }); + } + + + } + + function cantLoadInitialDatas(response) { + + alert("Error..." + response) + + } + } + + $scope.deletesPlgin = function (val) { + + url = "/websites/deletesPlgin"; + + + var data = { + pluginname: val, + pluginbBucketID: $('#pluginbID').html() + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.status === 1) { + location.reload(); + + } else { + + // $scope.errorMessage = response.data.error_message; + alert("Status not = 1: Error..." + response.data.error_message) + } + + + } + + function cantLoadInitialDatas(response) { + + alert("Error..." + response) + + } + + } + + $scope.Addplugin = function (slug) { + $('#mysearch').hide() + + url = "/websites/Addplugineidt"; + + + var data = { + pluginname: slug, + pluginbBucketID: $('#pluginbID').html() + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.status === 1) { + location.reload(); + + } else { + + // $scope.errorMessage = response.data.error_message; + alert("Status not = 1: Error..." + response.data.error_message) + } + + + } + + function cantLoadInitialDatas(response) { + + alert("Error..." + response) + + } + + + } + +}); + +var domain_check = 0; + +function checkbox_function() { + + var checkBox = document.getElementById("myCheck"); + // Get the output text + + + // If the checkbox is checked, display the output text + if (checkBox.checked == true) { + domain_check = 0; + document.getElementById('Test_Domain').style.display = "block"; + document.getElementById('Own_Domain').style.display = "none"; + + } else { + document.getElementById('Test_Domain').style.display = "none"; + document.getElementById('Own_Domain').style.display = "block"; + domain_check = 1; + } + + // alert(domain_check); +} + +app.controller('createWordpress', function ($scope, $http, $timeout, $compile, $window) { + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = false; + $scope.installationProgress = true; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + + + var statusFile; + + $scope.createWordPresssite = function () { + + $scope.webSiteCreationLoading = false; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + + + $scope.currentStatus = "Starting creation.."; + + var apacheBackend = 0; + + if ($scope.apacheBackend === true) { + apacheBackend = 1; + } else { + apacheBackend = 0 + } + + var package = $scope.packageForWebsite; + var websiteOwner = $scope.websiteOwner; + var WPtitle = $scope.WPtitle; + + // if (domain_check == 0) { + // var Part2_domainNameCreate = document.getElementById('Part2_domainNameCreate').value; + // var domainNameCreate = document.getElementById('TestDomainNameCreate').value + Part2_domainNameCreate; + // } + // if (domain_check == 1) { + // + // var domainNameCreate = $scope.own_domainNameCreate; + // } + + var domainNameCreate = $scope.domainNameCreate; + + + var WPUsername = $scope.WPUsername; + var adminEmail = $scope.adminEmail; + var WPPassword = $scope.WPPassword; + var WPVersions = $scope.WPVersions; + var pluginbucket = $scope.pluginbucket; + var autoupdates = $scope.autoupdates; + var pluginupdates = $scope.pluginupdates; + var themeupdates = $scope.themeupdates; + + if (domain_check == 0) { + + var path = ""; + + } + if (domain_check = 1) { + + var path = $scope.installPath; + + } + + + var home = "1"; + + if (typeof path != 'undefined') { + home = "0"; + } + + //alert(domainNameCreate); + var data = { + + title: WPtitle, + domain: domainNameCreate, + WPVersion: WPVersions, + pluginbucket: pluginbucket, + adminUser: WPUsername, + Email: adminEmail, + PasswordByPass: WPPassword, + AutomaticUpdates: autoupdates, + Plugins: pluginupdates, + Themes: themeupdates, + websiteOwner: websiteOwner, + package: package, + home: home, + path: path, + apacheBackend: apacheBackend + } + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + var url = "/websites/submitWorpressCreation"; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.webSiteCreationLoading = true; + if (response.data.status === 1) { + statusFile = response.data.tempStatusPath; + getCreationStatus(); + + } else { + $scope.goBackDisable = false; + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + + } + + function cantLoadInitialDatas(response) { + + alert("Error..." + response) + + } + + }; + $scope.goBack = function () { + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = false; + $scope.installationProgress = true; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + $("#installProgress").css("width", "0%"); + }; + + function getCreationStatus() { + + url = "/websites/installWordpressStatus"; + + var data = { + statusFile: statusFile + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.abort === 1) { + + if (response.data.installStatus === 1) { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = false; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $("#installProgress").css("width", "100%"); + $scope.installPercentage = "100"; + $scope.currentStatus = response.data.currentStatus; + $timeout.cancel(); + + } else { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = false; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $scope.errorMessage = response.data.error_message; + + $("#installProgress").css("width", "0%"); + $scope.installPercentage = "0"; + $scope.goBackDisable = false; + + } + + } else { + $scope.webSiteCreationLoading = false; + $("#installProgress").css("width", response.data.installationProgress + "%"); + $scope.installPercentage = response.data.installationProgress; + $scope.currentStatus = response.data.currentStatus; + $timeout(getCreationStatus, 1000); + } + + } + + function cantLoadInitialDatas(response) { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = false; + $scope.goBackDisable = false; + + } + + + } + + +}); + + +//........... delete wp list +var FurlDeleteWP; + +function DeleteWPNow(url) { + FurlDeleteWP = url; +} + +function FinalDeleteWPNow() { + window.location.href = FurlDeleteWP; +} + +var DeploytoProductionID; + +function DeployToProductionInitial(vall) { + DeploytoProductionID = vall; +} + +var create_staging_domain_check = 0; + +function create_staging_checkbox_function() { + + try { + + var checkBox = document.getElementById("Create_Staging_Check"); + // Get the output text + + + // If the checkbox is checked, display the output text + if (checkBox.checked == true) { + create_staging_domain_check = 0; + document.getElementById('Website_Create_Test_Domain').style.display = "block"; + document.getElementById('Website_Create_Own_Domain').style.display = "none"; + + } else { + document.getElementById('Website_Create_Test_Domain').style.display = "none"; + document.getElementById('Website_Create_Own_Domain').style.display = "block"; + create_staging_domain_check = 1; + } + } catch (e) { + + } + + // alert(domain_check); +} + +create_staging_checkbox_function(); + +app.controller('WPsiteHome', function ($scope, $http, $timeout, $compile, $window) { + + var CheckBoxpasssword = 0; + + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = false; + $scope.installationProgress = true; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + $(document).ready(function () { + var checkstatus = document.getElementById("wordpresshome"); + if (checkstatus !== null) { + $scope.LoadWPdata(); + + } + }); + + + $scope.LoadWPdata = function () { + + $scope.wordpresshomeloading = false; + $('#wordpresshomeloading').show(); + + var url = "/websites/FetchWPdata"; + + var data = { + WPid: $('#WPid').html(), + } + + console.log(data); + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + wordpresshomeloading = true; + $('#wordpresshomeloading').hide(); + + if (response.data.status === 1) { + $('#WPVersion').text(response.data.ret_data.version); + if (response.data.ret_data.lscache === 1) { + $('#lscache').prop('checked', true); + } + if (response.data.ret_data.debugging === 1) { + $('#debugging').prop('checked', true); + } + if (response.data.ret_data.searchIndex === 1) { + $('#searchIndex').prop('checked', true); + } + if (response.data.ret_data.maintenanceMode === 1) { + $('#maintenanceMode').prop('checked', true); + } + if (response.data.ret_data.wpcron === 1) { + $('#wpcron').prop('checked', true); + } + if (response.data.ret_data.passwordprotection == 1) { + + var dc = '\n' + + ' ' + var mp = $compile(dc)($scope); + angular.element(document.getElementById('prsswdprodata')).append(mp); + CheckBoxpasssword = 1; + } else if (response.data.ret_data.passwordprotection == 0) { + var dc = '\n' + + ' ' + $('#prsswdprodata').append(dc); + CheckBoxpasssword = 0; + } + + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = false; + $scope.goBackDisable = false; + + } + + + }; + + $scope.UpdateWPSettings = function (setting) { + + $scope.wordpresshomeloading = false; + $('#wordpresshomeloading').show(); + + + var url = "/websites/UpdateWPSettings"; + + if (setting === "PasswordProtection") { + if (CheckBoxpasssword == 0) { + var data = { + WPid: $('#WPid').html(), + setting: setting, + PPUsername: $scope.PPUsername, + PPPassword: $scope.PPPassword, + } + + } else { + var data = { + WPid: $('#WPid').html(), + setting: setting, + PPUsername: '', + PPPassword: '', + } + + } + + } else { + var settingValue = 0; + if ($('#' + setting).is(":checked")) { + settingValue = 1; + } + var data = { + WPid: $('#WPid').html(), + setting: setting, + settingValue: settingValue + } + } + + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.wordpresshomeloading = true; + $('#wordpresshomeloading').hide(); + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Successfully Updated!.', + type: 'success' + }); + if (setting === "PasswordProtection") { + location.reload(); + } + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + if (setting === "PasswordProtection") { + location.reload(); + } + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + + + }; + + $scope.GetCurrentPlugins = function () { + $('#wordpresshomeloading').show(); + + $scope.wordpresshomeloading = false; + + var url = "/websites/GetCurrentPlugins"; + + var data = { + WPid: $('#WPid').html(), + } + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + wordpresshomeloading = true; + $('#wordpresshomeloading').hide(); + + if (response.data.status === 1) { + $('#PluginBody').html(''); + var plugins = JSON.parse(response.data.plugins); + plugins.forEach(AddPlugins); + + } else { + alert("Error:" + response.data.error_message) + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = false; + $scope.goBackDisable = false; + + } + + + }; + + $scope.GetCurrentThemes = function () { + $('#wordpresshomeloading').show(); + + $scope.wordpresshomeloading = false; + + var url = "/websites/GetCurrentThemes"; + + var data = { + WPid: $('#WPid').html(), + } + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + wordpresshomeloading = true; + $('#wordpresshomeloading').hide(); + + if (response.data.status === 1) { + + $('#ThemeBody').html(''); + var themes = JSON.parse(response.data.themes); + themes.forEach(AddThemes); + + } else { + alert("Error:" + response.data.error_message) + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = false; + $scope.goBackDisable = false; + + } + + + }; + + $scope.UpdatePlugins = function (plugin) { + $('#wordpresshomeloading').show(); + var data = { + plugin: plugin, + pluginarray: PluginsList, + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/UpdatePlugins"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Updating Plugins in Background!.', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + + + }; + + $scope.DeletePlugins = function (plugin) { + $('#wordpresshomeloading').show(); + var data = { + plugin: plugin, + pluginarray: PluginsList, + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/DeletePlugins"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Deleting Plugin in Background!', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + + } + + $scope.ChangeStatus = function (plugin) { + $('#wordpresshomeloading').show(); + var data = { + plugin: plugin, + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/ChangeStatus"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Changed Plugin state Successfully !.', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + + } + + function AddPlugins(value, index, array) { + var FinalMarkup = '' + FinalMarkup = FinalMarkup + ''; + for (let x in value) { + if (x === 'status') { + if (value[x] === 'inactive') { + FinalMarkup = FinalMarkup + '
    '; + } else { + FinalMarkup = FinalMarkup + '
    '; + } + } else if (x === 'update') { + if (value[x] === 'none') { + FinalMarkup = FinalMarkup + 'Upto Date'; + } else { + FinalMarkup = FinalMarkup + ''; + } + } else { + FinalMarkup = FinalMarkup + '' + value[x] + ""; + } + } + FinalMarkup = FinalMarkup + '' + FinalMarkup = FinalMarkup + '' + var temp = $compile(FinalMarkup)($scope) + AppendToTable('#PluginBody', temp) + } + + $scope.UpdateThemes = function (theme) { + $('#wordpresshomeloading').show(); + var data = { + Theme: theme, + Themearray: ThemesList, + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/UpdateThemes"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Updating Theme in background !.', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + + + }; + + $scope.DeleteThemes = function (theme) { + $('#wordpresshomeloading').show(); + var data = { + Theme: theme, + Themearray: ThemesList, + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/DeleteThemes"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Deleting Theme in Background!.', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + }; + + $scope.ChangeStatusThemes = function (theme) { + $('#wordpresshomeloading').show(); + var data = { + theme: theme, + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/StatusThemes"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Change Theme state in Bsckground!.', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + + }; + + function AddThemes(value, index, array) { + var FinalMarkup = '' + FinalMarkup = FinalMarkup + ''; + for (let x in value) { + if (x === 'status') { + if (value[x] === 'inactive') { + FinalMarkup = FinalMarkup + '
    '; + } else { + FinalMarkup = FinalMarkup + '
    '; + } + } else if (x === 'update') { + if (value[x] === 'none') { + FinalMarkup = FinalMarkup + 'Upto Date'; + } else { + FinalMarkup = FinalMarkup + ''; + } + } else { + FinalMarkup = FinalMarkup + '' + value[x] + ""; + } + } + FinalMarkup = FinalMarkup + '' + FinalMarkup = FinalMarkup + '' + var temp = $compile(FinalMarkup)($scope) + AppendToTable('#ThemeBody', temp) + } + + $scope.CreateStagingNow = function () { + $('#wordpresshomeloading').show(); + + $scope.wordpresshomeloading = false; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + + + $scope.currentStatus = "Starting creation Staging.."; + + //here enter domain name + if (create_staging_domain_check == 0) { + var Part2_domainNameCreate = document.getElementById('Part2_domainNameCreate').value; + var domainNameCreate = document.getElementById('TestDomainNameCreate').value + Part2_domainNameCreate; + } + if (create_staging_domain_check == 1) { + + var domainNameCreate = $scope.own_domainNameCreate; + } + var data = { + StagingName: $('#stagingName').val(), + StagingDomain: domainNameCreate, + WPid: $('#WPid').html(), + } + var url = "/websites/CreateStagingNow"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + if (response.data.status === 1) { + statusFile = response.data.tempStatusPath; + getCreationStatus(); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + }; + + function getCreationStatus() { + $('#wordpresshomeloading').show(); + + url = "/websites/installWordpressStatus"; + + var data = { + statusFile: statusFile + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + //$('#wordpresshomeloading').hide(); + + if (response.data.abort === 1) { + if (response.data.installStatus === 1) { + + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = false; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + + $("#installProgress").css("width", "100%"); + $("#installProgressbackup").css("width", "100%"); + $scope.installPercentage = "100"; + $scope.currentStatus = response.data.currentStatus; + $timeout.cancel(); + + + } else { + + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = false; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $scope.errorMessage = response.data.error_message; + + $("#installProgress").css("width", "0%"); + $("#installProgressbackup").css("width", "0%"); + $scope.installPercentage = "0"; + $scope.goBackDisable = false; + + + } + + } else { + + $("#installProgress").css("width", response.data.installationProgress + "%"); + $("#installProgressbackup").css("width", response.data.installationProgress + "%"); + $scope.installPercentage = response.data.installationProgress; + $scope.currentStatus = response.data.currentStatus; + $timeout(getCreationStatus, 1000); + + } + + } + + function cantLoadInitialDatas(response) { + //$('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = false; + $scope.goBackDisable = false; + + } + + + } + + $scope.goBack = function () { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = false; + $scope.installationProgress = true; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + $("#installProgress").css("width", "0%"); + }; + + $scope.fetchstaging = function () { + + $('#wordpresshomeloading').show(); + $scope.wordpresshomeloading = false; + + var url = "/websites/fetchstaging"; + + var data = { + WPid: $('#WPid').html(), + } + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + wordpresshomeloading = true; + $('#wordpresshomeloading').hide(); + + if (response.data.status === 1) { + + // $('#ThemeBody').html(''); + // var themes = JSON.parse(response.data.themes); + // themes.forEach(AddThemes); + + $('#StagingBody').html(''); + var staging = JSON.parse(response.data.wpsites); + staging.forEach(AddStagings); + + } else { + alert("Error data.error_message:" + response.data.error_message) + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + alert("Error" + response) + + } + + }; + + $scope.fetchDatabase = function () { + + $('#wordpresshomeloading').show(); + $scope.wordpresshomeloading = false; + + var url = "/websites/fetchDatabase"; + + var data = { + WPid: $('#WPid').html(), + } + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + wordpresshomeloading = true; + $('#wordpresshomeloading').hide(); + + if (response.data.status === 1) { + $('#DB_Name').html(response.data.DataBaseName); + $('#DB_User').html(response.data.DataBaseUser); + $('#tableprefix').html(response.data.tableprefix); + } else { + alert("Error data.error_message:" + response.data.error_message) + + } + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + alert("Error" + response) + + } + + }; + + $scope.SaveUpdateConfig = function () { + $('#wordpresshomeloading').show(); + var data = { + AutomaticUpdates: $('#AutomaticUpdates').find(":selected").text(), + Plugins: $('#Plugins').find(":selected").text(), + Themes: $('#Themes').find(":selected").text(), + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/SaveUpdateConfig"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Update Configurations Sucessfully!.', + type: 'success' + }); + $("#autoUpdateConfig").modal('hide'); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + new PNotify({ + title: 'Operation Failed!', + text: response, + type: 'error' + }); + + } + }; + + function AddStagings(value, index, array) { + var FinalMarkup = '' + for (let x in value) { + if (x === 'name') { + FinalMarkup = FinalMarkup + '' + value[x] + ''; + } else if (x !== 'url' && x !== 'deleteURL' && x !== 'id') { + FinalMarkup = FinalMarkup + '' + value[x] + ""; + } + } + FinalMarkup = FinalMarkup + '' + + ' ' + FinalMarkup = FinalMarkup + '' + AppendToTable('#StagingBody', FinalMarkup); + } + + $scope.FinalDeployToProduction = function () { + + $('#wordpresshomeloading').show(); + + $scope.wordpresshomeloading = false; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + + var data = { + WPid: $('#WPid').html(), + StagingID: DeploytoProductionID + } + + var url = "/websites/DeploytoProduction"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + function ListInitialDatas(response) { + + $('#wordpresshomeloading').hide(); + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Deploy To Production start!.', + type: 'success' + }); + statusFile = response.data.tempStatusPath; + getCreationStatus(); + + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + new PNotify({ + title: 'Operation Failed!', + text: response, + type: 'error' + }); + + } + + }; + + + $scope.CreateBackup = function () { + $('#wordpresshomeloading').show(); + + $scope.wordpresshomeloading = false; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + $scope.currentStatus = "Starting creation Backups.."; + var data = { + WPid: $('#WPid').html(), + Backuptype: $('#backuptype').val() + } + var url = "/websites/WPCreateBackup"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $('createbackupbutton').hide(); + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Creating Backups!.', + type: 'success' + }); + statusFile = response.data.tempStatusPath; + getCreationStatus(); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + alert(response) + + } + + }; + + + $scope.installwpcore = function () { + + $('#wordpresshomeloading').show(); + $('#wordpresshomeloadingsec').show(); + var data = { + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/installwpcore"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $('#wordpresshomeloadingsec').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Results fetched..', + type: 'success' + }); + $('#SecurityResult').html(response.data.result); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $('#wordpresshomeloadingsec').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + + }; + + $scope.dataintegrity = function () { + + $('#wordpresshomeloading').show(); + $('#wordpresshomeloadingsec').show(); + var data = { + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/dataintegrity"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $('#wordpresshomeloadingsec').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Results fetched', + type: 'success' + }); + $('#SecurityResult').html(response.data.result); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $('#wordpresshomeloadingsec').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + }; + +}); + + +var PluginsList = []; + + +function AddPluginToArray(cBox, name) { + if (cBox.checked) { + PluginsList.push(name); + // alert(PluginsList); + } else { + const index = PluginsList.indexOf(name); + if (index > -1) { + PluginsList.splice(index, 1); + } + // alert(PluginsList); + } +} + +var ThemesList = []; + +function AddThemeToArray(cBox, name) { + if (cBox.checked) { + ThemesList.push(name); + // alert(ThemesList); + } else { + const index = ThemesList.indexOf(name); + if (index > -1) { + ThemesList.splice(index, 1); + } + // alert(ThemesList); + } +} + + +function AppendToTable(table, markup) { + $(table).append(markup); +} + + +//..................Restore Backup Home + + +app.controller('RestoreWPBackup', function ($scope, $http, $timeout, $window) { + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = false; + $scope.installationProgress = true; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + + + $scope.checkmethode = function () { + var val = $('#RestoreMethode').children("option:selected").val(); + if (val == 1) { + $('#Newsitediv').show(); + $('#exinstingsitediv').hide(); + } else if (val == 0) { + $('#exinstingsitediv').show(); + $('#Newsitediv').hide(); + } else { + + } + }; + + + $scope.RestoreWPbackupNow = function () { + $('#wordpresshomeloading').show(); + $scope.wordpresshomeloading = false; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + $scope.currentStatus = "Start Restoring WordPress.."; + + var Domain = $('#wprestoresubdirdomain').val() + var path = $('#wprestoresubdirpath').val(); + var home = "1"; + + if (typeof path != 'undefined' || path != '') { + home = "0"; + } + if (typeof path == 'undefined') { + path = ""; + } + + + var backuptype = $('#backuptype').html(); + var data; + if (backuptype == "DataBase Backup") { + data = { + backupid: $('#backupid').html(), + DesSite: $('#DesSite').children("option:selected").val(), + Domain: '', + path: path, + home: home, + } + } else { + data = { + backupid: $('#backupid').html(), + DesSite: $('#DesSite').children("option:selected").val(), + Domain: Domain, + path: path, + home: home, + } + + } + + var url = "/websites/RestoreWPbackupNow"; + + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + // console.log(data) + + var d = $('#DesSite').children("option:selected").val(); + var c = $("input[name=Newdomain]").val(); + // if (d == -1 || c == "") { + // alert("Please Select Method of Backup Restore"); + // } else { + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + // } + + + function ListInitialDatas(response) { + wordpresshomeloading = true; + $('#wordpresshomeloading').hide(); + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Restoring process starts!.', + type: 'success' + }); + statusFile = response.data.tempStatusPath; + getCreationStatus(); + + } else { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = false; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $scope.errorMessage = response.data.error_message; + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + + } + } + + function getCreationStatus() { + $('#wordpresshomeloading').show(); + + url = "/websites/installWordpressStatus"; + + var data = { + statusFile: statusFile + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + //$('#wordpresshomeloading').hide(); + + if (response.data.abort === 1) { + + if (response.data.installStatus === 1) { + + + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = false; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + + $("#installProgress").css("width", "100%"); + $("#installProgressbackup").css("width", "100%"); + $scope.installPercentage = "100"; + $scope.currentStatus = response.data.currentStatus; + $timeout.cancel(); + + + } else { + + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = false; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $scope.errorMessage = response.data.error_message; + + $("#installProgress").css("width", "0%"); + $("#installProgressbackup").css("width", "0%"); + $scope.installPercentage = "0"; + $scope.goBackDisable = false; + + + } + + } else { + + $("#installProgress").css("width", response.data.installationProgress + "%"); + $("#installProgressbackup").css("width", response.data.installationProgress + "%"); + $scope.installPercentage = response.data.installationProgress; + $scope.currentStatus = response.data.currentStatus; + $timeout(getCreationStatus, 1000); + + } + + } + + function cantLoadInitialDatas(response) { + //$('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = false; + $scope.goBackDisable = false; + + } + + + } + + $scope.goBack = function () { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = false; + $scope.installationProgress = true; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + $("#installProgress").css("width", "0%"); + }; +}); + + +//.......................................Remote Backup + +//........... delete DeleteBackupConfigNow + +function DeleteBackupConfigNow(url) { + window.location.href = url; +} + +function DeleteRemoteBackupsiteNow(url) { + window.location.href = url; +} + +function DeleteBackupfileConfigNow(url) { + window.location.href = url; +} + + +app.controller('RemoteBackupConfig', function ($scope, $http, $timeout, $window) { + $scope.RemoteBackupLoading = true; + $scope.SFTPBackUpdiv = true; + + $scope.EndpointURLdiv = true; + $scope.Selectprovider = true; + $scope.S3keyNamediv = true; + $scope.Accesskeydiv = true; + $scope.SecretKeydiv = true; + $scope.SelectRemoteBackuptype = function () { + var val = $scope.RemoteBackuptype; + if (val == "SFTP") { + $scope.SFTPBackUpdiv = false; + $scope.EndpointURLdiv = true; + $scope.Selectprovider = true; + $scope.S3keyNamediv = true; + $scope.Accesskeydiv = true; + $scope.SecretKeydiv = true; + } else if (val == "S3") { + $scope.EndpointURLdiv = true; + $scope.Selectprovider = false; + $scope.S3keyNamediv = false; + $scope.Accesskeydiv = false; + $scope.SecretKeydiv = false; + $scope.SFTPBackUpdiv = true; + } else { + $scope.RemoteBackupLoading = true; + $scope.SFTPBackUpdiv = true; + + $scope.EndpointURLdiv = true; + $scope.Selectprovider = true; + $scope.S3keyNamediv = true; + $scope.Accesskeydiv = true; + $scope.SecretKeydiv = true; + } + } + + $scope.SelectProvidertype = function () { + $scope.EndpointURLdiv = true; + var provider = $scope.Providervalue + if (provider == 'Backblaze') { + $scope.EndpointURLdiv = false; + } else { + $scope.EndpointURLdiv = true; + } + } + + $scope.SaveBackupConfig = function () { + $scope.RemoteBackupLoading = false; + var Hname = $scope.Hostname; + var Uname = $scope.Username; + var Passwd = $scope.Password; + var path = $scope.path; + var type = $scope.RemoteBackuptype; + var Providervalue = $scope.Providervalue; + var data; + if (type == "SFTP") { + + data = { + Hname: Hname, + Uname: Uname, + Passwd: Passwd, + path: path, + type: type + } + } else if (type == "S3") { + if (Providervalue == "Backblaze") { + data = { + S3keyname: $scope.S3keyName, + Provider: Providervalue, + AccessKey: $scope.Accesskey, + SecertKey: $scope.SecretKey, + EndUrl: $scope.EndpointURL, + type: type + } + } else { + data = { + S3keyname: $scope.S3keyName, + Provider: Providervalue, + AccessKey: $scope.Accesskey, + SecertKey: $scope.SecretKey, + type: type + } + + } + + } + var url = "/websites/SaveBackupConfig"; + + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.RemoteBackupLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Successfully Saved!.', + type: 'success' + }); + location.reload(); + + + } else { + new PNotify({ + title: 'Error!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialDatas(response) { + $scope.RemoteBackupLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + + } + + + } + +}); + +var UpdatescheduleID; +app.controller('BackupSchedule', function ($scope, $http, $timeout, $window) { + $scope.BackupScheduleLoading = true; + $scope.SaveBackupSchedule = function () { + $scope.RemoteBackupLoading = false; + var FileRetention = $scope.Fretention; + var Backfrequency = $scope.Bfrequency; + + + var data = { + FileRetention: FileRetention, + Backfrequency: Backfrequency, + ScheduleName: $scope.ScheduleName, + RemoteConfigID: $('#RemoteConfigID').html(), + BackupType: $scope.BackupType + } + var url = "/websites/SaveBackupSchedule"; + + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.RemoteBackupLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Successfully Saved!.', + type: 'success' + }); + location.reload(); + + + } else { + new PNotify({ + title: 'Error!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialDatas(response) { + $scope.RemoteBackupLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + + } + + + }; + + + $scope.getupdateid = function (ID) { + UpdatescheduleID = ID; + } + + $scope.UpdateRemoteschedules = function () { + $scope.RemoteBackupLoading = false; + var Frequency = $scope.RemoteFrequency; + var fretention = $scope.RemoteFileretention; + + var data = { + ScheduleID: UpdatescheduleID, + Frequency: Frequency, + FileRetention: fretention + } + var url = "/websites/UpdateRemoteschedules"; + + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.RemoteBackupLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Successfully Updated!.', + type: 'success' + }); + location.reload(); + + + } else { + new PNotify({ + title: 'Error!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialDatas(response) { + $scope.RemoteBackupLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + + } + }; + + $scope.AddWPsiteforRemoteBackup = function () { + $scope.RemoteBackupLoading = false; + + + var data = { + WpsiteID: $('#Wpsite').val(), + RemoteScheduleID: $('#RemoteScheduleID').html() + } + var url = "/websites/AddWPsiteforRemoteBackup"; + + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.RemoteBackupLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Successfully Saved!.', + type: 'success' + }); + location.reload(); + + + } else { + new PNotify({ + title: 'Error!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialDatas(response) { + $scope.RemoteBackupLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + + } + + + }; +}); +/* Java script code to create account */ + +var website_create_domain_check = 0; + +function website_create_checkbox_function() { + + var checkBox = document.getElementById("myCheck"); + // Get the output text + + + // If the checkbox is checked, display the output text + if (checkBox.checked == true) { + website_create_domain_check = 0; + document.getElementById('Website_Create_Test_Domain').style.display = "block"; + document.getElementById('Website_Create_Own_Domain').style.display = "none"; + + } else { + document.getElementById('Website_Create_Test_Domain').style.display = "none"; + document.getElementById('Website_Create_Own_Domain').style.display = "block"; + website_create_domain_check = 1; + } + + // alert(domain_check); +} + +app.controller('createWebsite', function ($scope, $http, $timeout, $window) { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = false; + $scope.installationProgress = true; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + + var statusFile; + + $scope.createWebsite = function () { + + $scope.webSiteCreationLoading = false; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + + $scope.currentStatus = "Starting creation.."; + + var ssl, dkimCheck, openBasedir, mailDomain, apacheBackend; + + if ($scope.sslCheck === true) { + ssl = 1; + } else { + ssl = 0 + } + + if ($scope.apacheBackend === true) { + apacheBackend = 1; + } else { + apacheBackend = 0 + } + + if ($scope.dkimCheck === true) { + dkimCheck = 1; + } else { + dkimCheck = 0 + } + + if ($scope.openBasedir === true) { + openBasedir = 1; + } else { + openBasedir = 0 + } + + if ($scope.mailDomain === true) { + mailDomain = 1; + } else { + mailDomain = 0 + } + + + url = "/websites/submitWebsiteCreation"; + + var package = $scope.packageForWebsite; + + // if (website_create_domain_check == 0) { + // var Part2_domainNameCreate = document.getElementById('Part2_domainNameCreate').value; + // var domainName = document.getElementById('TestDomainNameCreate').value + Part2_domainNameCreate; + // } + // if (website_create_domain_check == 1) { + // + // var domainName = $scope.domainNameCreate; + // } + var domainName = $scope.domainNameCreate; + + // var domainName = $scope.domainNameCreate; + + var adminEmail = $scope.adminEmail; + var phpSelection = $scope.phpSelection; + var websiteOwner = $scope.websiteOwner; + + + var data = { + package: package, + domainName: domainName, + adminEmail: adminEmail, + phpSelection: phpSelection, + ssl: ssl, + websiteOwner: websiteOwner, + dkimCheck: dkimCheck, + openBasedir: openBasedir, + mailDomain: mailDomain, + apacheBackend: apacheBackend + }; + + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.createWebSiteStatus === 1) { + statusFile = response.data.tempStatusPath; + getCreationStatus(); + } else { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = false; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $scope.errorMessage = response.data.error_message; + } + + + } + + function cantLoadInitialDatas(response) { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = false; + $scope.goBackDisable = false; + + } + + + }; + $scope.goBack = function () { + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = false; + $scope.installationProgress = true; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + $("#installProgress").css("width", "0%"); + }; + + function getCreationStatus() { + + url = "/websites/installWordpressStatus"; + + var data = { + statusFile: statusFile + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + + if (response.data.abort === 1) { + + if (response.data.installStatus === 1) { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = false; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $("#installProgress").css("width", "100%"); + $scope.installPercentage = "100"; + $scope.currentStatus = response.data.currentStatus; + $timeout.cancel(); + + } else { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = false; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $scope.errorMessage = response.data.error_message; + + $("#installProgress").css("width", "0%"); + $scope.installPercentage = "0"; + $scope.goBackDisable = false; + + } + + } else { + $("#installProgress").css("width", response.data.installationProgress + "%"); + $scope.installPercentage = response.data.installationProgress; + $scope.currentStatus = response.data.currentStatus; + $timeout(getCreationStatus, 1000); + } + + } + + function cantLoadInitialDatas(response) { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = false; + $scope.goBackDisable = false; + + } + + + } + +}); +/* Java script code to create account ends here */ + +/* Java script code to list accounts */ + +$("#listFail").hide(); + + +app.controller('listWebsites', function ($scope, $http, $window) { + $scope.web = {}; + $scope.WebSitesList = []; + + $scope.currentPage = 1; + $scope.recordsToShow = 10; + + // Initial fetch of websites + $scope.getFurtherWebsitesFromDB = function () { + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + var data = { + page: $scope.currentPage, + recordsToShow: $scope.recordsToShow + }; + + var dataurl = "/websites/fetchWebsitesList"; + + $http.post(dataurl, data, config).then(function(response) { + if (response.data.listWebSiteStatus === 1) { + $scope.WebSitesList = JSON.parse(response.data.data); + $scope.pagination = response.data.pagination; + $("#listFail").hide(); + } else { + $("#listFail").fadeIn(); + $scope.errorMessage = response.data.error_message; + } + }).catch(function(error) { + $("#listFail").fadeIn(); + $scope.errorMessage = error.message || 'An error occurred while fetching websites'; + }); + }; + + // Call it immediately + $scope.getFurtherWebsitesFromDB(); + + $scope.showWPSites = function(domain) { + var url = '/websites/fetchWPDetails'; + var data = { + domain: domain + }; + + $http({ + method: 'POST', + url: url, + data: $.param(data), + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'X-CSRFToken': getCookie('csrftoken') + } + }).then(function(response) { + if (response.data.status === 1 && response.data.fetchStatus === 1) { + $scope.web.wp_sites = response.data.sites; + $scope.web.showWPSites = true; + $("#listFail").hide(); + } else { + $("#listFail").fadeIn(); + $scope.errorMessage = response.data.error_message || 'Failed to fetch WordPress sites'; + } + }).catch(function(error) { + $("#listFail").fadeIn(); + $scope.errorMessage = error.message || 'An error occurred while fetching WordPress sites'; + }); + }; + + $scope.visitSite = function(url) { + window.open(url, '_blank'); + }; + + $scope.wpLogin = function(wpId) { + window.open('/websites/wpLogin?wpID=' + wpId, '_blank'); + }; + + $scope.manageWP = function(wpId) { + window.location.href = '/websites/listWPsites?wpID=' + wpId; + }; + + $scope.updateSetting = function(wp, setting) { + var settingMap = { + 'search-indexing': 'searchIndex', + 'debugging': 'debugging', + 'password-protection': 'passwordProtection', + 'maintenance-mode': 'maintenanceMode' + }; + + var data = { + wpID: wp.id, + setting: setting, + value: wp[settingMap[setting]] ? 'enable' : 'disable' + }; + + $http({ + method: 'POST', + url: '/websites/UpdateWPSettings', + data: data, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'X-CSRFToken': getCookie('csrftoken') + }, + transformRequest: function(obj) { + var str = []; + for(var p in obj) + str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); + return str.join("&"); + } + }).then(function(response) { + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: 'Setting updated successfully.', + type: 'success' + }); + } else { + wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change + new PNotify({ + title: 'Error', + text: 'Failed to update setting.', + type: 'error' + }); + } + }).catch(function(error) { + wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change + new PNotify({ + title: 'Error', + text: 'Connection failed while updating setting.', + type: 'error' + }); + }); + }; + + $scope.cyberPanelLoading = true; + + $scope.issueSSL = function (virtualHost) { + $scope.cyberPanelLoading = false; + + var url = "/manageSSL/issueSSL"; + + + var data = { + virtualHost: virtualHost + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.cyberPanelLoading = true; + if (response.data.SSL === 1) { + new PNotify({ + title: 'Success!', + text: 'SSL successfully issued.', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + + } + + function cantLoadInitialDatas(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); + } + + + }; + + $scope.cyberPanelLoading = true; + + $scope.searchWebsites = function () { + + $scope.cyberPanelLoading = false; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + var data = { + patternAdded: $scope.patternAdded + }; + + dataurl = "/websites/searchWebsites"; + + $http.post(dataurl, data, config).then(ListInitialData, cantLoadInitialData); + + + function ListInitialData(response) { + $scope.cyberPanelLoading = true; + if (response.data.listWebSiteStatus === 1) { + + var finalData = JSON.parse(response.data.data); + $scope.WebSitesList = finalData; + $("#listFail").hide(); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + } + + function cantLoadInitialData(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Connect disrupted, refresh the page.', + type: 'error' + }); + } + + + }; + + $scope.ScanWordpressSite = function () { + + $('#cyberPanelLoading').show(); + + + var url = "/websites/ScanWordpressSite"; + + var data = {} + + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + $('#cyberPanelLoading').hide(); + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Successfully Saved!.', + type: 'success' + }); + location.reload(); + + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#cyberPanelLoading').hide(); + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + + } + + + }; + +}); + +app.controller('listChildDomainsMain', function ($scope, $http, $timeout) { + + $scope.currentPage = 1; + $scope.recordsToShow = 10; + + $scope.getFurtherWebsitesFromDB = function () { + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + var data = { + page: $scope.currentPage, + recordsToShow: $scope.recordsToShow + }; + + + dataurl = "/websites/fetchChildDomainsMain"; + + $http.post(dataurl, data, config).then(ListInitialData, cantLoadInitialData); + + + function ListInitialData(response) { + if (response.data.listWebSiteStatus === 1) { + + $scope.WebSitesList = JSON.parse(response.data.data); + $scope.pagination = response.data.pagination; + $scope.clients = JSON.parse(response.data.data); + $("#listFail").hide(); + } else { + $("#listFail").fadeIn(); + $scope.errorMessage = response.data.error_message; + + } + } + + function cantLoadInitialData(response) { + } + + + }; + $scope.getFurtherWebsitesFromDB(); + + $scope.cyberPanelLoading = true; + + $scope.issueSSL = function (virtualHost) { + $scope.cyberPanelLoading = false; + + var url = "/manageSSL/issueSSL"; + + + var data = { + virtualHost: virtualHost + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.cyberPanelLoading = true; + if (response.data.SSL === 1) { + new PNotify({ + title: 'Success!', + text: 'SSL successfully issued.', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + + } + + function cantLoadInitialDatas(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); + } + + + }; + + $scope.cyberPanelLoading = true; + + $scope.searchWebsites = function () { + + $scope.cyberPanelLoading = false; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + var data = { + patternAdded: $scope.patternAdded + }; + + dataurl = "/websites/searchChilds"; + + $http.post(dataurl, data, config).then(ListInitialData, cantLoadInitialData); + + + function ListInitialData(response) { + $scope.cyberPanelLoading = true; + if (response.data.listWebSiteStatus === 1) { + + var finalData = JSON.parse(response.data.data); + $scope.WebSitesList = finalData; + $("#listFail").hide(); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + } + + function cantLoadInitialData(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Connect disrupted, refresh the page.', + type: 'error' + }); + } + + + }; + + $scope.initConvert = function (virtualHost) { + $scope.domainName = virtualHost; + }; + + var statusFile; + + $scope.installationProgress = true; + + $scope.convert = function () { + + $scope.cyberPanelLoading = false; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.goBackDisable = true; + + $scope.currentStatus = "Starting creation.."; + + var ssl, dkimCheck, openBasedir; + + if ($scope.sslCheck === true) { + ssl = 1; + } else { + ssl = 0 + } + + if ($scope.dkimCheck === true) { + dkimCheck = 1; + } else { + dkimCheck = 0 + } + + if ($scope.openBasedir === true) { + openBasedir = 1; + } else { + openBasedir = 0 + } + + url = "/websites/convertDomainToSite"; + + + var data = { + package: $scope.packageForWebsite, + domainName: $scope.domainName, + adminEmail: $scope.adminEmail, + phpSelection: $scope.phpSelection, + websiteOwner: $scope.websiteOwner, + ssl: ssl, + dkimCheck: dkimCheck, + openBasedir: openBasedir + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.createWebSiteStatus === 1) { + statusFile = response.data.tempStatusPath; + getCreationStatus(); + } else { + + $scope.cyberPanelLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.goBackDisable = false; + + $scope.currentStatus = response.data.error_message; + } + + + } + + function cantLoadInitialDatas(response) { + + $scope.cyberPanelLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.goBackDisable = false; + + } + + + }; + $scope.goBack = function () { + $scope.cyberPanelLoading = true; + $scope.installationDetailsForm = false; + $scope.installationProgress = true; + $scope.goBackDisable = true; + $("#installProgress").css("width", "0%"); + }; + + function getCreationStatus() { + + url = "/websites/installWordpressStatus"; + + var data = { + statusFile: statusFile + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + + if (response.data.abort === 1) { + + if (response.data.installStatus === 1) { + + $scope.cyberPanelLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.goBackDisable = false; + + $("#installProgress").css("width", "100%"); + $scope.installPercentage = "100"; + $scope.currentStatus = response.data.currentStatus; + $timeout.cancel(); + + } else { + + $scope.cyberPanelLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.goBackDisable = false; + + $scope.currentStatus = response.data.error_message; + + $("#installProgress").css("width", "0%"); + $scope.installPercentage = "0"; + $scope.goBackDisable = false; + + } + + } else { + $("#installProgress").css("width", response.data.installationProgress + "%"); + $scope.installPercentage = response.data.installationProgress; + $scope.currentStatus = response.data.currentStatus; + $timeout(getCreationStatus, 1000); + } + + } + + function cantLoadInitialDatas(response) { + + $scope.cyberPanelLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.goBackDisable = false; + + } + + + } + + var DeleteDomain; + $scope.deleteDomainInit = function (childDomainForDeletion) { + DeleteDomain = childDomainForDeletion; + }; + + $scope.deleteChildDomain = function () { + $scope.cyberPanelLoading = false; + url = "/websites/submitDomainDeletion"; + + var data = { + websiteName: DeleteDomain, + DeleteDocRoot: $scope.DeleteDocRoot + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + function ListInitialDatas(response) { + $scope.cyberPanelLoading = true; + if (response.data.websiteDeleteStatus === 1) { + new PNotify({ + title: 'Success!', + text: 'Child Domain successfully deleted.', + type: 'success' + }); + $scope.getFurtherWebsitesFromDB(); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialDatas(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); + + } + + }; + +}); + +/* Java script code to list accounts ends here */ + + +/* Java script code to delete Website */ + + +$("#websiteDeleteFailure").hide(); +$("#websiteDeleteSuccess").hide(); + +$("#deleteWebsiteButton").hide(); +$("#deleteLoading").hide(); + +app.controller('deleteWebsiteControl', function ($scope, $http) { + + + $scope.deleteWebsite = function () { + + $("#deleteWebsiteButton").fadeIn(); + + + }; + + $scope.deleteWebsiteFinal = function () { + + $("#deleteLoading").show(); + + var websiteName = $scope.websiteToBeDeleted; + + + url = "/websites/submitWebsiteDeletion"; + + var data = { + websiteName: websiteName + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.websiteDeleteStatus === 0) { + $scope.errorMessage = response.data.error_message; + $("#websiteDeleteFailure").fadeIn(); + $("#websiteDeleteSuccess").hide(); + $("#deleteWebsiteButton").hide(); + + + $("#deleteLoading").hide(); + + } else { + $("#websiteDeleteFailure").hide(); + $("#websiteDeleteSuccess").fadeIn(); + $("#deleteWebsiteButton").hide(); + $scope.deletedWebsite = websiteName; + $("#deleteLoading").hide(); + + } + + + } + + function cantLoadInitialDatas(response) { + } + + + }; + +}); + + +/* Java script code to delete website ends here */ + + +/* Java script code to modify package ends here */ + +$("#canNotModify").hide(); +$("#webSiteDetailsToBeModified").hide(); +$("#websiteModifyFailure").hide(); +$("#websiteModifySuccess").hide(); +$("#websiteSuccessfullyModified").hide(); +$("#modifyWebsiteLoading").hide(); +$("#modifyWebsiteButton").hide(); + +app.controller('modifyWebsitesController', function ($scope, $http) { + + $scope.fetchWebsites = function () { + + $("#modifyWebsiteLoading").show(); + + + var websiteToBeModified = $scope.websiteToBeModified; + + url = "/websites/getWebsiteDetails"; + + var data = { + websiteToBeModified: websiteToBeModified, + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.modifyStatus === 0) { + console.log(response.data); + $scope.errorMessage = response.data.error_message; + $("#websiteModifyFailure").fadeIn(); + $("#websiteModifySuccess").hide(); + $("#modifyWebsiteButton").hide(); + $("#modifyWebsiteLoading").hide(); + $("#canNotModify").hide(); + + + } else { + console.log(response.data); + $("#modifyWebsiteButton").fadeIn(); + + $scope.adminEmail = response.data.adminEmail; + $scope.currentPack = response.data.current_pack; + $scope.webpacks = JSON.parse(response.data.packages); + $scope.adminNames = JSON.parse(response.data.adminNames); + $scope.currentAdmin = response.data.currentAdmin; + + $("#webSiteDetailsToBeModified").fadeIn(); + $("#websiteModifySuccess").fadeIn(); + $("#modifyWebsiteButton").fadeIn(); + $("#modifyWebsiteLoading").hide(); + $("#canNotModify").hide(); + + + } + + + } + + function cantLoadInitialDatas(response) { + $("#websiteModifyFailure").fadeIn(); + } + + }; + + + $scope.modifyWebsiteFunc = function () { + + var domain = $scope.websiteToBeModified; + var packForWeb = $scope.selectedPack; + var email = $scope.adminEmail; + var phpVersion = $scope.phpSelection; + var admin = $scope.selectedAdmin; + + + $("#websiteModifyFailure").hide(); + $("#websiteModifySuccess").hide(); + $("#websiteSuccessfullyModified").hide(); + $("#canNotModify").hide(); + $("#modifyWebsiteLoading").fadeIn(); + + + url = "/websites/saveWebsiteChanges"; + + var data = { + domain: domain, + packForWeb: packForWeb, + email: email, + phpVersion: phpVersion, + admin: admin + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.saveStatus === 0) { + $scope.errMessage = response.data.error_message; + + $("#canNotModify").fadeIn(); + $("#websiteModifyFailure").hide(); + $("#websiteModifySuccess").hide(); + $("#websiteSuccessfullyModified").hide(); + $("#modifyWebsiteLoading").hide(); + + + } else { + $("#modifyWebsiteButton").hide(); + $("#canNotModify").hide(); + $("#websiteModifyFailure").hide(); + $("#websiteModifySuccess").hide(); + + $("#websiteSuccessfullyModified").fadeIn(); + $("#modifyWebsiteLoading").hide(); + + $scope.websiteModified = domain; + + + } + + + } + + function cantLoadInitialDatas(response) { + $scope.errMessage = response.data.error_message; + $("#canNotModify").fadeIn(); + } + + + }; + +}); + +/* Java script code to Modify Pacakge ends here */ + + +/* Java script code to create account */ +var website_child_domain_check = 0; + +function website_child_domain_checkbox_function() { + + var checkBox = document.getElementById("myCheck"); + // Get the output text + + + // If the checkbox is checked, display the output text + if (checkBox.checked == true) { + website_child_domain_check = 0; + document.getElementById('Website_Create_Test_Domain').style.display = "block"; + document.getElementById('Website_Create_Own_Domain').style.display = "none"; + + } else { + document.getElementById('Website_Create_Test_Domain').style.display = "none"; + document.getElementById('Website_Create_Own_Domain').style.display = "block"; + website_child_domain_check = 1; + } + + // alert(domain_check); +} + +app.controller('websitePages', function ($scope, $http, $timeout, $window) { + + $scope.logFileLoading = true; + $scope.logsFeteched = true; + $scope.couldNotFetchLogs = true; + $scope.couldNotConnect = true; + $scope.fetchedData = true; + $scope.hideLogs = true; + $scope.hideErrorLogs = true; + + $scope.hidelogsbtn = function () { + $scope.hideLogs = true; + }; + + $scope.hideErrorLogsbtn = function () { + $scope.hideLogs = true; + }; + + $scope.fileManagerURL = "/filemanager/" + $("#domainNamePage").text(); + $scope.wordPressInstallURL = $("#domainNamePage").text() + "/wordpressInstall"; + $scope.joomlaInstallURL = $("#domainNamePage").text() + "/joomlaInstall"; + $scope.setupGit = $("#domainNamePage").text() + "/setupGit"; + $scope.installPrestaURL = $("#domainNamePage").text() + "/installPrestaShop"; + $scope.installMagentoURL = $("#domainNamePage").text() + "/installMagento"; + $scope.installMauticURL = $("#domainNamePage").text() + "/installMautic"; + $scope.domainAliasURL = "/websites/" + $("#domainNamePage").text() + "/domainAlias"; + $scope.previewUrl = "/preview/" + $("#domainNamePage").text() + "/"; + + var logType = 0; + $scope.pageNumber = 1; + + $scope.fetchLogs = function (type) { + + var pageNumber = $scope.pageNumber; + + + if (type == 3) { + pageNumber = $scope.pageNumber + 1; + $scope.pageNumber = pageNumber; + } else if (type == 4) { + pageNumber = $scope.pageNumber - 1; + $scope.pageNumber = pageNumber; + } else { + logType = type; + } + + + $scope.logFileLoading = false; + $scope.logsFeteched = true; + $scope.couldNotFetchLogs = true; + $scope.couldNotConnect = true; + $scope.fetchedData = false; + $scope.hideErrorLogs = true; + + + url = "/websites/getDataFromLogFile"; + + var domainNamePage = $("#domainNamePage").text(); + + + var data = { + logType: logType, + virtualHost: domainNamePage, + page: pageNumber, + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.logstatus == 1) { + + + $scope.logFileLoading = true; + $scope.logsFeteched = false; + $scope.couldNotFetchLogs = true; + $scope.couldNotConnect = true; + $scope.fetchedData = false; + $scope.hideLogs = false; + + + $scope.records = JSON.parse(response.data.data); + + } else { + + $scope.logFileLoading = true; + $scope.logsFeteched = true; + $scope.couldNotFetchLogs = false; + $scope.couldNotConnect = true; + $scope.fetchedData = true; + $scope.hideLogs = false; + + + $scope.errorMessage = response.data.error_message; + console.log(domainNamePage) + + } + + + } + + function cantLoadInitialDatas(response) { + + $scope.logFileLoading = true; + $scope.logsFeteched = true; + $scope.couldNotFetchLogs = true; + $scope.couldNotConnect = false; + $scope.fetchedData = true; + $scope.hideLogs = false; + + } + + + }; + + $scope.errorPageNumber = 1; + + + $scope.fetchErrorLogs = function (type) { + + var errorPageNumber = $scope.errorPageNumber; + + + if (type == 3) { + errorPageNumber = $scope.errorPageNumber + 1; + $scope.errorPageNumber = errorPageNumber; + } else if (type == 4) { + errorPageNumber = $scope.errorPageNumber - 1; + $scope.errorPageNumber = errorPageNumber; + } else { + logType = type; + } + + // notifications + + $scope.logFileLoading = false; + $scope.logsFeteched = true; + $scope.couldNotFetchLogs = true; + $scope.couldNotConnect = true; + $scope.fetchedData = true; + $scope.hideErrorLogs = true; + $scope.hideLogs = false; + + + url = "/websites/fetchErrorLogs"; + + var domainNamePage = $("#domainNamePage").text(); + + + var data = { + virtualHost: domainNamePage, + page: errorPageNumber, + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.logstatus === 1) { + + + // notifications + + $scope.logFileLoading = true; + $scope.logsFeteched = false; + $scope.couldNotFetchLogs = true; + $scope.couldNotConnect = true; + $scope.fetchedData = true; + $scope.hideLogs = false; + $scope.hideErrorLogs = false; + + + $scope.errorLogsData = response.data.data; + + } else { + + // notifications + + $scope.logFileLoading = true; + $scope.logsFeteched = true; + $scope.couldNotFetchLogs = false; + $scope.couldNotConnect = true; + $scope.fetchedData = true; + $scope.hideLogs = true; + $scope.hideErrorLogs = true; + + + $scope.errorMessage = response.data.error_message; + + } + + + } + + function cantLoadInitialDatas(response) { + + // notifications + + $scope.logFileLoading = true; + $scope.logsFeteched = true; + $scope.couldNotFetchLogs = true; + $scope.couldNotConnect = false; + $scope.fetchedData = true; + $scope.hideLogs = true; + $scope.hideErrorLogs = true; + + } + + + }; + + ///////// Configurations Part + + $scope.configurationsBox = true; + $scope.configsFetched = true; + $scope.couldNotFetchConfigs = true; + $scope.couldNotConnect = true; + $scope.fetchedConfigsData = true; + $scope.configFileLoading = true; + $scope.configSaved = true; + $scope.couldNotSaveConfigurations = true; + + $scope.hideconfigbtn = function () { + + $scope.configurationsBox = true; + }; + + $scope.fetchConfigurations = function () { + + + $scope.hidsslconfigs = true; + $scope.configurationsBoxRewrite = true; + $scope.changePHPView = true; + + + //Rewrite rules + $scope.configurationsBoxRewrite = true; + $scope.rewriteRulesFetched = true; + $scope.couldNotFetchRewriteRules = true; + $scope.rewriteRulesSaved = true; + $scope.couldNotSaveRewriteRules = true; + $scope.fetchedRewriteRules = true; + $scope.saveRewriteRulesBTN = true; + + /// + + $scope.configFileLoading = false; + + + url = "/websites/getDataFromConfigFile"; + + var virtualHost = $("#domainNamePage").text(); + + + var data = { + virtualHost: virtualHost, + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.configstatus === 1) { + + //Rewrite rules + + $scope.configurationsBoxRewrite = true; + $scope.rewriteRulesFetched = true; + $scope.couldNotFetchRewriteRules = true; + $scope.rewriteRulesSaved = true; + $scope.couldNotSaveRewriteRules = true; + $scope.fetchedRewriteRules = true; + $scope.saveRewriteRulesBTN = true; + + /// + + $scope.configurationsBox = false; + $scope.configsFetched = false; + $scope.couldNotFetchConfigs = true; + $scope.couldNotConnect = true; + $scope.fetchedConfigsData = false; + $scope.configFileLoading = true; + $scope.configSaved = true; + $scope.couldNotSaveConfigurations = true; + $scope.saveConfigBtn = false; + + + $scope.configData = response.data.configData; + + } else { + + //Rewrite rules + $scope.configurationsBoxRewrite = true; + $scope.rewriteRulesFetched = true; + $scope.couldNotFetchRewriteRules = true; + $scope.rewriteRulesSaved = true; + $scope.couldNotSaveRewriteRules = true; + $scope.fetchedRewriteRules = true; + $scope.saveRewriteRulesBTN = true; + + /// + $scope.configurationsBox = false; + $scope.configsFetched = true; + $scope.couldNotFetchConfigs = false; + $scope.couldNotConnect = true; + $scope.fetchedConfigsData = true; + $scope.configFileLoading = true; + $scope.configSaved = true; + $scope.couldNotSaveConfigurations = true; + + + $scope.errorMessage = response.data.error_message; + + } + + + } + + function cantLoadInitialDatas(response) { + + //Rewrite rules + $scope.configurationsBoxRewrite = true; + $scope.rewriteRulesFetched = true; + $scope.couldNotFetchRewriteRules = true; + $scope.rewriteRulesSaved = true; + $scope.couldNotSaveRewriteRules = true; + $scope.fetchedRewriteRules = true; + $scope.saveRewriteRulesBTN = true; + /// + + $scope.configurationsBox = false; + $scope.configsFetched = true; + $scope.couldNotFetchConfigs = true; + $scope.couldNotConnect = false; + $scope.fetchedConfigsData = true; + $scope.configFileLoading = true; + $scope.configSaved = true; + $scope.couldNotSaveConfigurations = true; + + + } + + + }; + + $scope.saveCongiruations = function () { + + $scope.configFileLoading = false; + + + url = "/websites/saveConfigsToFile"; + + var virtualHost = $("#domainNamePage").text(); + var configData = $scope.configData; + + + var data = { + virtualHost: virtualHost, + configData: configData, + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.configstatus === 1) { + + $scope.configurationsBox = false; + $scope.configsFetched = true; + $scope.couldNotFetchConfigs = true; + $scope.couldNotConnect = true; + $scope.fetchedConfigsData = true; + $scope.configFileLoading = true; + $scope.configSaved = false; + $scope.couldNotSaveConfigurations = true; + $scope.saveConfigBtn = true; + + + } else { + $scope.configurationsBox = false; + $scope.configsFetched = true; + $scope.couldNotFetchConfigs = true; + $scope.couldNotConnect = true; + $scope.fetchedConfigsData = false; + $scope.configFileLoading = true; + $scope.configSaved = true; + $scope.couldNotSaveConfigurations = false; + + + $scope.errorMessage = response.data.error_message; + + } + + + } + + function cantLoadInitialDatas(response) { + + $scope.configurationsBox = false; + $scope.configsFetched = true; + $scope.couldNotFetchConfigs = true; + $scope.couldNotConnect = false; + $scope.fetchedConfigsData = true; + $scope.configFileLoading = true; + $scope.configSaved = true; + $scope.couldNotSaveConfigurations = true; + + + } + + + }; + + + ///////// Rewrite Rules + + $scope.configurationsBoxRewrite = true; + $scope.rewriteRulesFetched = true; + $scope.couldNotFetchRewriteRules = true; + $scope.rewriteRulesSaved = true; + $scope.couldNotSaveRewriteRules = true; + $scope.fetchedRewriteRules = true; + $scope.saveRewriteRulesBTN = true; + + $scope.hideRewriteRulesbtn = function () { + $scope.configurationsBoxRewrite = true; + }; + + $scope.fetchRewriteFules = function () { + + $scope.hidsslconfigs = true; + $scope.configurationsBox = true; + $scope.changePHPView = true; + + + $scope.configurationsBox = true; + $scope.configsFetched = true; + $scope.couldNotFetchConfigs = true; + $scope.couldNotConnect = true; + $scope.fetchedConfigsData = true; + $scope.configFileLoading = true; + $scope.configSaved = true; + $scope.couldNotSaveConfigurations = true; + $scope.saveConfigBtn = true; + + $scope.configFileLoading = false; + + + url = "/websites/getRewriteRules"; + + var virtualHost = $("#domainNamePage").text(); + + + var data = { + virtualHost: virtualHost, + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.rewriteStatus == 1) { + + + // from main + + $scope.configurationsBox = true; + $scope.configsFetched = true; + $scope.couldNotFetchConfigs = true; + $scope.fetchedConfigsData = true; + $scope.configSaved = true; + $scope.couldNotSaveConfigurations = true; + $scope.saveConfigBtn = true; + + // main ends + + $scope.configFileLoading = true; + + // + + + $scope.configurationsBoxRewrite = false; + $scope.rewriteRulesFetched = false; + $scope.couldNotFetchRewriteRules = true; + $scope.rewriteRulesSaved = true; + $scope.couldNotSaveRewriteRules = true; + $scope.fetchedRewriteRules = false; + $scope.saveRewriteRulesBTN = false; + $scope.couldNotConnect = true; + + + $scope.rewriteRules = response.data.rewriteRules; + + } else { + // from main + $scope.configurationsBox = true; + $scope.configsFetched = true; + $scope.couldNotFetchConfigs = true; + $scope.fetchedConfigsData = true; + $scope.configFileLoading = true; + $scope.configSaved = true; + $scope.couldNotSaveConfigurations = true; + $scope.saveConfigBtn = true; + // from main + + $scope.configFileLoading = true; + + /// + + $scope.configurationsBoxRewrite = true; + $scope.rewriteRulesFetched = true; + $scope.couldNotFetchRewriteRules = false; + $scope.rewriteRulesSaved = true; + $scope.couldNotSaveRewriteRules = true; + $scope.fetchedRewriteRules = true; + $scope.saveRewriteRulesBTN = true; + $scope.couldNotConnect = true; + + + $scope.errorMessage = response.data.error_message; + + } + + + } + + function cantLoadInitialDatas(response) { + // from main + + $scope.configurationsBox = true; + $scope.configsFetched = true; + $scope.couldNotFetchConfigs = true; + $scope.fetchedConfigsData = true; + $scope.configFileLoading = true; + $scope.configSaved = true; + $scope.couldNotSaveConfigurations = true; + $scope.saveConfigBtn = true; + + // from main + + $scope.configFileLoading = true; + + /// + + $scope.configurationsBoxRewrite = true; + $scope.rewriteRulesFetched = true; + $scope.couldNotFetchRewriteRules = true; + $scope.rewriteRulesSaved = true; + $scope.couldNotSaveRewriteRules = true; + $scope.fetchedRewriteRules = true; + $scope.saveRewriteRulesBTN = true; + + $scope.couldNotConnect = false; + + + } + + + }; + + $scope.saveRewriteRules = function () { + + $scope.configFileLoading = false; + + + url = "/websites/saveRewriteRules"; + + var virtualHost = $("#domainNamePage").text(); + var rewriteRules = $scope.rewriteRules; + + + var data = { + virtualHost: virtualHost, + rewriteRules: rewriteRules, + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.rewriteStatus == 1) { + + $scope.configurationsBoxRewrite = false; + $scope.rewriteRulesFetched = true; + $scope.couldNotFetchRewriteRules = true; + $scope.rewriteRulesSaved = false; + $scope.couldNotSaveRewriteRules = true; + $scope.fetchedRewriteRules = true; + $scope.saveRewriteRulesBTN = true; + $scope.configFileLoading = true; + + + } else { + $scope.configurationsBoxRewrite = false; + $scope.rewriteRulesFetched = false; + $scope.couldNotFetchRewriteRules = true; + $scope.rewriteRulesSaved = true; + $scope.couldNotSaveRewriteRules = false; + $scope.fetchedRewriteRules = true; + $scope.saveRewriteRulesBTN = false; + + $scope.configFileLoading = true; + + + $scope.errorMessage = response.data.error_message; + + } + + + } + + function cantLoadInitialDatas(response) { + + $scope.configurationsBoxRewrite = false; + $scope.rewriteRulesFetched = false; + $scope.couldNotFetchRewriteRules = true; + $scope.rewriteRulesSaved = true; + $scope.couldNotSaveRewriteRules = true; + $scope.fetchedRewriteRules = true; + $scope.saveRewriteRulesBTN = false; + + $scope.configFileLoading = true; + + $scope.couldNotConnect = false; + + + } + + + }; + + //////// Application Installation part + + $scope.installationDetailsForm = true; + $scope.installationDetailsFormJoomla = true; + $scope.applicationInstallerLoading = true; + $scope.installationFailed = true; + $scope.installationSuccessfull = true; + $scope.couldNotConnect = true; + + + $scope.installationDetails = function () { + + $scope.installationDetailsForm = !$scope.installationDetailsForm; + $scope.installationDetailsFormJoomla = true; + + }; + + $scope.installationDetailsJoomla = function () { + + $scope.installationDetailsFormJoomla = !$scope.installationDetailsFormJoomla; + $scope.installationDetailsForm = true; + + }; + + $scope.installWordpress = function () { + + + $scope.installationDetailsForm = false; + $scope.applicationInstallerLoading = false; + $scope.installationFailed = true; + $scope.installationSuccessfull = true; + $scope.couldNotConnect = true; + + var domain = $("#domainNamePage").text(); + var path = $scope.installPath; + + url = "/websites/installWordpress"; + + var home = "1"; + + if (typeof path != 'undefined') { + home = "0"; + } + + + var data = { + domain: domain, + home: home, + path: path, + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.installStatus === 1) { + if (typeof path != 'undefined') { + $scope.installationURL = "http://" + domain + "/" + path; + } else { + $scope.installationURL = domain; + } + + $scope.installationDetailsForm = false; + $scope.applicationInstallerLoading = true; + $scope.installationFailed = true; + $scope.installationSuccessfull = false; + $scope.couldNotConnect = true; + + } else { + + $scope.installationDetailsForm = false; + $scope.applicationInstallerLoading = true; + $scope.installationFailed = false; + $scope.installationSuccessfull = true; + $scope.couldNotConnect = true; + + $scope.errorMessage = response.data.error_message; + + } + + + } + + function cantLoadInitialDatas(response) { + + $scope.installationDetailsForm = false; + $scope.applicationInstallerLoading = true; + $scope.installationFailed = true; + $scope.installationSuccessfull = true; + $scope.couldNotConnect = false; + + } + + }; + + $scope.installJoomla = function () { + + + $scope.installationDetailsFormJoomla = false; + $scope.applicationInstallerLoading = false; + $scope.installationFailed = true; + $scope.installationSuccessfull = true; + $scope.couldNotConnect = true; + + var domain = $("#domainNamePage").text(); + var path = $scope.installPath; + var username = 'admin'; + var password = $scope.password; + var prefix = $scope.prefix; + + + url = "/websites/installJoomla"; + + var home = "1"; + + if (typeof path != 'undefined') { + home = "0"; + } + + + var data = { + domain: domain, + siteName: $scope.siteName, + home: home, + path: path, + password: password, + prefix: prefix, + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.installStatus === 1) { + if (typeof path != 'undefined') { + $scope.installationURL = "http://" + domain + "/" + path; + } else { + $scope.installationURL = domain; + } + + $scope.installationDetailsFormJoomla = false; + $scope.applicationInstallerLoading = true; + $scope.installationFailed = true; + $scope.installationSuccessfull = false; + $scope.couldNotConnect = true; + + } else { + + $scope.installationDetailsFormJoomla = false; + $scope.applicationInstallerLoading = true; + $scope.installationFailed = false; + $scope.installationSuccessfull = true; + $scope.couldNotConnect = true; + + $scope.errorMessage = response.data.error_message; + + } + + + } + + function cantLoadInitialDatas(response) { + + $scope.installationDetailsFormJoomla = false; + $scope.applicationInstallerLoading = true; + $scope.installationFailed = true; + $scope.installationSuccessfull = true; + $scope.couldNotConnect = false; + + } + + }; + + + //////// SSL Part + + $scope.sslSaved = true; + $scope.couldNotSaveSSL = true; + $scope.hidsslconfigs = true; + $scope.couldNotConnect = true; + + + $scope.hidesslbtn = function () { + $scope.hidsslconfigs = true; + }; + + $scope.addSSL = function () { + $scope.hidsslconfigs = false; + $scope.configurationsBox = true; + $scope.configurationsBoxRewrite = true; + $scope.changePHPView = true; + }; + + $scope.saveSSL = function () { + + + $scope.configFileLoading = false; + + url = "/websites/saveSSL"; + + var virtualHost = $("#domainNamePage").text(); + var cert = $scope.cert; + var key = $scope.key; + + + var data = { + virtualHost: virtualHost, + cert: cert, + key: key + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.sslStatus === 1) { + + $scope.sslSaved = false; + $scope.couldNotSaveSSL = true; + $scope.couldNotConnect = true; + $scope.configFileLoading = true; + + + } else { + + $scope.sslSaved = true; + $scope.couldNotSaveSSL = false; + $scope.couldNotConnect = true; + $scope.configFileLoading = true; + + $scope.errorMessage = response.data.error_message; + + } + + + } + + function cantLoadInitialDatas(response) { + + $scope.sslSaved = true; + $scope.couldNotSaveSSL = true; + $scope.couldNotConnect = false; + $scope.configFileLoading = true; + + + } + + }; + + //// Change PHP Master + + $scope.failedToChangePHPMaster = true; + $scope.phpChangedMaster = true; + $scope.couldNotConnect = true; + + $scope.changePHPView = true; + + + $scope.hideChangePHPMaster = function () { + $scope.changePHPView = true; + }; + + $scope.changePHPMaster = function () { + $scope.hidsslconfigs = true; + $scope.configurationsBox = true; + $scope.configurationsBoxRewrite = true; + $scope.changePHPView = false; + }; + + $scope.changePHPVersionMaster = function (childDomain, phpSelection) { + + // notifcations + + $scope.configFileLoading = false; + + var url = "/websites/changePHP"; + + var data = { + childDomain: $("#domainNamePage").text(), + phpSelection: $scope.phpSelectionMaster, + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + + if (response.data.changePHP === 1) { + + $scope.configFileLoading = true; + $scope.websiteDomain = $("#domainNamePage").text(); + + + // notifcations + + $scope.failedToChangePHPMaster = true; + $scope.phpChangedMaster = false; + $scope.couldNotConnect = true; + + + } else { + + $scope.configFileLoading = true; + $scope.errorMessage = response.data.error_message; + + // notifcations + + $scope.failedToChangePHPMaster = false; + $scope.phpChangedMaster = true; + $scope.couldNotConnect = true; + + } + + + } + + function cantLoadInitialDatas(response) { + + $scope.configFileLoading = true; + + // notifcations + + $scope.failedToChangePHPMaster = true; + $scope.phpChangedMaster = true; + $scope.couldNotConnect = false; + + } + + }; + + ////// create domain part + + $("#domainCreationForm").hide(); + + $scope.showCreateDomainForm = function () { + $("#domainCreationForm").fadeIn(); + }; + + $scope.hideDomainCreationForm = function () { + $("#domainCreationForm").fadeOut(); + }; + + $scope.masterDomain = $("#domainNamePage").text(); + + // notifcations settings + $scope.domainLoading = true; + $scope.installationDetailsForm = false; + $scope.installationProgress = true; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + $scope.DomainCreateForm = true; + + var statusFile; + + + $scope.webselection = true; + $scope.WebsiteType = function () { + var type = $scope.websitetype; + if (type == 'Sub Domain') { + $scope.webselection = false; + $scope.DomainCreateForm = true; + + } else if (type == 'Addon Domain') { + $scope.DomainCreateForm = false; + $scope.webselection = true; + $scope.masterDomain = $('#defaultSite').html() + } + }; + + $scope.WebsiteSelection = function () { + $scope.DomainCreateForm = false; + }; + + $scope.createDomain = function () { + + $scope.domainLoading = false; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + $scope.currentStatus = "Starting creation.."; + $scope.DomainCreateForm = true; + + var ssl, dkimCheck, openBasedir, apacheBackend; + + if ($scope.sslCheck === true) { + ssl = 1; + } else { + ssl = 0 + } + + if ($scope.dkimCheck === true) { + dkimCheck = 1; + } else { + dkimCheck = 0 + } + + if ($scope.openBasedir === true) { + openBasedir = 1; + } else { + openBasedir = 0 + } + + + if ($scope.apacheBackend === true) { + apacheBackend = 1; + } else { + apacheBackend = 0 + } + + + url = "/websites/submitDomainCreation"; + var domainName = $scope.domainNameCreate; + var phpSelection = $scope.phpSelection; + + var path = $scope.docRootPath; + + if (typeof path === 'undefined') { + path = ""; + } + var package = $scope.packageForWebsite; + + // if (website_child_domain_check == 0) { + // var Part2_domainNameCreate = document.getElementById('Part2_domainNameCreate').value; + // var domainName = document.getElementById('TestDomainNameCreate').value + Part2_domainNameCreate; + // } + // if (website_child_domain_check == 1) { + // + // var domainName = $scope.own_domainNameCreate; + // } + var type = $scope.websitetype; + + var domainName = $scope.domainNameCreate; + + + var data = { + domainName: domainName, + phpSelection: phpSelection, + ssl: ssl, + path: path, + masterDomain: $scope.masterDomain, + dkimCheck: dkimCheck, + openBasedir: openBasedir, + apacheBackend: apacheBackend + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + // console.log(data) + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.createWebSiteStatus === 1) { + statusFile = response.data.tempStatusPath; + getCreationStatus(); + } else { + + $scope.domainLoading = true; + $scope.installationDetailsForm = true; + $scope.DomainCreateForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = false; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $scope.errorMessage = response.data.error_message; + } + + + } + + function cantLoadInitialDatas(response) { + + $scope.domainLoading = true; + $scope.installationDetailsForm = true; + $scope.DomainCreateForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = false; + $scope.goBackDisable = false; + + } + + + }; + + $scope.goBack = function () { + $scope.domainLoading = true; + $scope.installationDetailsForm = false; + $scope.DomainCreateForm = true; + $scope.installationProgress = true; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + $scope.DomainCreateForm = true; + $("#installProgress").css("width", "0%"); + }; + + function getCreationStatus() { + + url = "/websites/installWordpressStatus"; + + var data = { + statusFile: statusFile + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + + if (response.data.abort === 1) { + + if (response.data.installStatus === 1) { + + $scope.domainLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = false; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $("#installProgress").css("width", "100%"); + $scope.installPercentage = "100"; + $scope.currentStatus = response.data.currentStatus; + $timeout.cancel(); + + } else { + + $scope.domainLoading = true; + $scope.installationDetailsForm = true; + $scope.DomainCreateForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = false; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $scope.errorMessage = response.data.error_message; + + $("#installProgress").css("width", "0%"); + $scope.installPercentage = "0"; + $scope.goBackDisable = false; + + } + + } else { + $("#installProgress").css("width", response.data.installationProgress + "%"); + $scope.installPercentage = response.data.installationProgress; + $scope.currentStatus = response.data.currentStatus; + $timeout(getCreationStatus, 1000); + } + + } + + function cantLoadInitialDatas(response) { + + $scope.domainLoading = true; + $scope.installationDetailsForm = true; + $scope.DomainCreateForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = false; + $scope.goBackDisable = false; + + } + + + } + + + ////// List Domains Part + + //////////////////////// + + // notifcations + + $scope.phpChanged = true; + $scope.domainError = true; + $scope.couldNotConnect = true; + $scope.domainDeleted = true; + $scope.sslIssued = true; + $scope.childBaseDirChanged = true; + + $("#listDomains").hide(); + + $scope.showListDomains = function () { fetchDomains(); $("#listDomains").fadeIn(); From b1e2791e193e4c010e774a3f5eb1e2bdf55991e7 Mon Sep 17 00:00:00 2001 From: usmannasir Date: Fri, 4 Apr 2025 21:30:35 +0500 Subject: [PATCH 018/273] fix showwpsites --- .../websiteFunctions/websiteFunctions.js | 8308 +++++++---------- 1 file changed, 3384 insertions(+), 4924 deletions(-) diff --git a/websiteFunctions/static/websiteFunctions/websiteFunctions.js b/websiteFunctions/static/websiteFunctions/websiteFunctions.js index ce1b6200e..a12105241 100755 --- a/websiteFunctions/static/websiteFunctions/websiteFunctions.js +++ b/websiteFunctions/static/websiteFunctions/websiteFunctions.js @@ -2634,4923 +2634,6 @@ app.controller('createWebsite', function ($scope, $http, $timeout, $window) { $("#listFail").hide(); -app.controller('listWebsites', function ($scope, $http, $window) { - $scope.web = {}; - $scope.WebSitesList = []; - - $scope.currentPage = 1; - $scope.recordsToShow = 10; - - // Initial fetch of websites - $scope.getFurtherWebsitesFromDB = function () { - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - var data = { - page: $scope.currentPage, - recordsToShow: $scope.recordsToShow - }; - - var dataurl = "/websites/fetchWebsitesList"; - - $http.post(dataurl, data, config).then(function(response) { - if (response.data.listWebSiteStatus === 1) { - $scope.WebSitesList = JSON.parse(response.data.data); - $scope.pagination = response.data.pagination; - $("#listFail").hide(); - } else { - $("#listFail").fadeIn(); - $scope.errorMessage = response.data.error_message; - } - }).catch(function(error) { - $("#listFail").fadeIn(); - $scope.errorMessage = error.message || 'An error occurred while fetching websites'; - }); - }; - - // Call it immediately - $scope.getFurtherWebsitesFromDB(); - - $scope.showWPSites = function(domain) { - var url = '/websites/fetchWPDetails'; - var data = { - domain: domain - }; - $http({ - method: 'POST', - url: url, - data: $.param(data), - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', - 'X-CSRFToken': getCookie('csrftoken') - } - }).then(function(response) { - if (response.data.status === 1 && response.data.fetchStatus === 1) { - $scope.web.wp_sites = response.data.sites; - $scope.web.showWPSites = true; - $("#listFail").hide(); - } else { - $("#listFail").fadeIn(); - $scope.errorMessage = response.data.error_message || 'Failed to fetch WordPress sites'; - } - }).catch(function(error) { - $("#listFail").fadeIn(); - $scope.errorMessage = error.message || 'An error occurred while fetching WordPress sites'; - }); - }; - - $scope.visitSite = function(url) { - window.open(url, '_blank'); - }; - - $scope.wpLogin = function(wpId) { - window.open('/websites/wpLogin?wpID=' + wpId, '_blank'); - }; - - $scope.manageWP = function(wpId) { - window.location.href = '/websites/listWPsites?wpID=' + wpId; - }; - - $scope.updateSetting = function(wp, setting) { - var settingMap = { - 'search-indexing': 'searchIndex', - 'debugging': 'debugging', - 'password-protection': 'passwordProtection', - 'maintenance-mode': 'maintenanceMode' - }; - - var data = { - wpID: wp.id, - setting: setting, - value: wp[settingMap[setting]] ? 'enable' : 'disable' - }; - - $http({ - method: 'POST', - url: '/websites/UpdateWPSettings', - data: data, - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', - 'X-CSRFToken': getCookie('csrftoken') - }, - transformRequest: function(obj) { - var str = []; - for(var p in obj) - str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); - return str.join("&"); - } - }).then(function(response) { - if (response.data.status === 1) { - new PNotify({ - title: 'Success', - text: 'Setting updated successfully.', - type: 'success' - }); - } else { - wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change - new PNotify({ - title: 'Error', - text: 'Failed to update setting.', - type: 'error' - }); - } - }).catch(function(error) { - wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change - new PNotify({ - title: 'Error', - text: 'Connection failed while updating setting.', - type: 'error' - }); - }); - }; - - $scope.cyberPanelLoading = true; - - $scope.issueSSL = function (virtualHost) { - $scope.cyberPanelLoading = false; - - var url = "/manageSSL/issueSSL"; - - - var data = { - virtualHost: virtualHost - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.cyberPanelLoading = true; - if (response.data.SSL === 1) { - new PNotify({ - title: 'Success!', - text: 'SSL successfully issued.', - type: 'success' - }); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - } - - } - - function cantLoadInitialDatas(response) { - $scope.cyberPanelLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: 'Could not connect to server, please refresh this page', - type: 'error' - }); - } - - - }; - - $scope.cyberPanelLoading = true; - - $scope.searchWebsites = function () { - - $scope.cyberPanelLoading = false; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - var data = { - patternAdded: $scope.patternAdded - }; - - dataurl = "/websites/searchWebsites"; - - $http.post(dataurl, data, config).then(ListInitialData, cantLoadInitialData); - - - function ListInitialData(response) { - $scope.cyberPanelLoading = true; - if (response.data.listWebSiteStatus === 1) { - - var finalData = JSON.parse(response.data.data); - $scope.WebSitesList = finalData; - $("#listFail").hide(); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - } - - function cantLoadInitialData(response) { - $scope.cyberPanelLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: 'Connect disrupted, refresh the page.', - type: 'error' - }); - } - - - }; - - $scope.ScanWordpressSite = function () { - - $('#cyberPanelLoading').show(); - - - var url = "/websites/ScanWordpressSite"; - - var data = {} - - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - $('#cyberPanelLoading').hide(); - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Successfully Saved!.', - type: 'success' - }); - location.reload(); - - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#cyberPanelLoading').hide(); - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - - } - - - }; - -}); - -app.controller('listChildDomainsMain', function ($scope, $http, $timeout) { - - $scope.currentPage = 1; - $scope.recordsToShow = 10; - - $scope.getFurtherWebsitesFromDB = function () { - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - var data = { - page: $scope.currentPage, - recordsToShow: $scope.recordsToShow - }; - - - dataurl = "/websites/fetchChildDomainsMain"; - - $http.post(dataurl, data, config).then(ListInitialData, cantLoadInitialData); - - - function ListInitialData(response) { - if (response.data.listWebSiteStatus === 1) { - - $scope.WebSitesList = JSON.parse(response.data.data); - $scope.pagination = response.data.pagination; - $scope.clients = JSON.parse(response.data.data); - $("#listFail").hide(); - } else { - $("#listFail").fadeIn(); - $scope.errorMessage = response.data.error_message; - - } - } - - function cantLoadInitialData(response) { - } - - - }; - $scope.getFurtherWebsitesFromDB(); - - $scope.cyberPanelLoading = true; - - $scope.issueSSL = function (virtualHost) { - $scope.cyberPanelLoading = false; - - var url = "/manageSSL/issueSSL"; - - - var data = { - virtualHost: virtualHost - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.cyberPanelLoading = true; - if (response.data.SSL === 1) { - new PNotify({ - title: 'Success!', - text: 'SSL successfully issued.', - type: 'success' - }); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - } - - } - - function cantLoadInitialDatas(response) { - $scope.cyberPanelLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: 'Could not connect to server, please refresh this page', - type: 'error' - }); - } - - - }; - - $scope.cyberPanelLoading = true; - - $scope.searchWebsites = function () { - - $scope.cyberPanelLoading = false; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - var data = { - patternAdded: $scope.patternAdded - }; - - dataurl = "/websites/searchChilds"; - - $http.post(dataurl, data, config).then(ListInitialData, cantLoadInitialData); - - - function ListInitialData(response) { - $scope.cyberPanelLoading = true; - if (response.data.listWebSiteStatus === 1) { - - var finalData = JSON.parse(response.data.data); - $scope.WebSitesList = finalData; - $("#listFail").hide(); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - } - - function cantLoadInitialData(response) { - $scope.cyberPanelLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: 'Connect disrupted, refresh the page.', - type: 'error' - }); - } - - - }; - - $scope.initConvert = function (virtualHost) { - $scope.domainName = virtualHost; - }; - - var statusFile; - - $scope.installationProgress = true; - - $scope.convert = function () { - - $scope.cyberPanelLoading = false; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.goBackDisable = true; - - $scope.currentStatus = "Starting creation.."; - - var ssl, dkimCheck, openBasedir; - - if ($scope.sslCheck === true) { - ssl = 1; - } else { - ssl = 0 - } - - if ($scope.dkimCheck === true) { - dkimCheck = 1; - } else { - dkimCheck = 0 - } - - if ($scope.openBasedir === true) { - openBasedir = 1; - } else { - openBasedir = 0 - } - - url = "/websites/convertDomainToSite"; - - - var data = { - package: $scope.packageForWebsite, - domainName: $scope.domainName, - adminEmail: $scope.adminEmail, - phpSelection: $scope.phpSelection, - websiteOwner: $scope.websiteOwner, - ssl: ssl, - dkimCheck: dkimCheck, - openBasedir: openBasedir - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.createWebSiteStatus === 1) { - statusFile = response.data.tempStatusPath; - getCreationStatus(); - } else { - - $scope.cyberPanelLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.goBackDisable = false; - - $scope.currentStatus = response.data.error_message; - } - - - } - - function cantLoadInitialDatas(response) { - - $scope.cyberPanelLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.goBackDisable = false; - - } - - - }; - $scope.goBack = function () { - $scope.cyberPanelLoading = true; - $scope.installationDetailsForm = false; - $scope.installationProgress = true; - $scope.goBackDisable = true; - $("#installProgress").css("width", "0%"); - }; - - function getCreationStatus() { - - url = "/websites/installWordpressStatus"; - - var data = { - statusFile: statusFile - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - - if (response.data.abort === 1) { - - if (response.data.installStatus === 1) { - - $scope.cyberPanelLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.goBackDisable = false; - - $("#installProgress").css("width", "100%"); - $scope.installPercentage = "100"; - $scope.currentStatus = response.data.currentStatus; - $timeout.cancel(); - - } else { - - $scope.cyberPanelLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.goBackDisable = false; - - $scope.currentStatus = response.data.error_message; - - $("#installProgress").css("width", "0%"); - $scope.installPercentage = "0"; - $scope.goBackDisable = false; - - } - - } else { - $("#installProgress").css("width", response.data.installationProgress + "%"); - $scope.installPercentage = response.data.installationProgress; - $scope.currentStatus = response.data.currentStatus; - $timeout(getCreationStatus, 1000); - } - - } - - function cantLoadInitialDatas(response) { - - $scope.cyberPanelLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.goBackDisable = false; - - } - - - } - - var DeleteDomain; - $scope.deleteDomainInit = function (childDomainForDeletion) { - DeleteDomain = childDomainForDeletion; - }; - - $scope.deleteChildDomain = function () { - $scope.cyberPanelLoading = false; - url = "/websites/submitDomainDeletion"; - - var data = { - websiteName: DeleteDomain, - DeleteDocRoot: $scope.DeleteDocRoot - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - function ListInitialDatas(response) { - $scope.cyberPanelLoading = true; - if (response.data.websiteDeleteStatus === 1) { - new PNotify({ - title: 'Success!', - text: 'Child Domain successfully deleted.', - type: 'success' - }); - $scope.getFurtherWebsitesFromDB(); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - } - } - - function cantLoadInitialDatas(response) { - $scope.cyberPanelLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: 'Could not connect to server, please refresh this page', - type: 'error' - }); - - } - - }; - -}); - -/* Java script code to list accounts ends here */ - - -/* Java script code to delete Website */ - - -$("#websiteDeleteFailure").hide(); -$("#websiteDeleteSuccess").hide(); - -$("#deleteWebsiteButton").hide(); -$("#deleteLoading").hide(); - -app.controller('deleteWebsiteControl', function ($scope, $http) { - - - $scope.deleteWebsite = function () { - - $("#deleteWebsiteButton").fadeIn(); - - - }; - - $scope.deleteWebsiteFinal = function () { - - $("#deleteLoading").show(); - - var websiteName = $scope.websiteToBeDeleted; - - - url = "/websites/submitWebsiteDeletion"; - - var data = { - websiteName: websiteName - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.websiteDeleteStatus === 0) { - $scope.errorMessage = response.data.error_message; - $("#websiteDeleteFailure").fadeIn(); - $("#websiteDeleteSuccess").hide(); - $("#deleteWebsiteButton").hide(); - - - $("#deleteLoading").hide(); - - } else { - $("#websiteDeleteFailure").hide(); - $("#websiteDeleteSuccess").fadeIn(); - $("#deleteWebsiteButton").hide(); - $scope.deletedWebsite = websiteName; - $("#deleteLoading").hide(); - - } - - - } - - function cantLoadInitialDatas(response) { - } - - - }; - -}); - - -/* Java script code to delete website ends here */ - - -/* Java script code to modify package ends here */ - -$("#canNotModify").hide(); -$("#webSiteDetailsToBeModified").hide(); -$("#websiteModifyFailure").hide(); -$("#websiteModifySuccess").hide(); -$("#websiteSuccessfullyModified").hide(); -$("#modifyWebsiteLoading").hide(); -$("#modifyWebsiteButton").hide(); - -app.controller('modifyWebsitesController', function ($scope, $http) { - - $scope.fetchWebsites = function () { - - $("#modifyWebsiteLoading").show(); - - - var websiteToBeModified = $scope.websiteToBeModified; - - url = "/websites/getWebsiteDetails"; - - var data = { - websiteToBeModified: websiteToBeModified, - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.modifyStatus === 0) { - console.log(response.data); - $scope.errorMessage = response.data.error_message; - $("#websiteModifyFailure").fadeIn(); - $("#websiteModifySuccess").hide(); - $("#modifyWebsiteButton").hide(); - $("#modifyWebsiteLoading").hide(); - $("#canNotModify").hide(); - - - } else { - console.log(response.data); - $("#modifyWebsiteButton").fadeIn(); - - $scope.adminEmail = response.data.adminEmail; - $scope.currentPack = response.data.current_pack; - $scope.webpacks = JSON.parse(response.data.packages); - $scope.adminNames = JSON.parse(response.data.adminNames); - $scope.currentAdmin = response.data.currentAdmin; - - $("#webSiteDetailsToBeModified").fadeIn(); - $("#websiteModifySuccess").fadeIn(); - $("#modifyWebsiteButton").fadeIn(); - $("#modifyWebsiteLoading").hide(); - $("#canNotModify").hide(); - - - } - - - } - - function cantLoadInitialDatas(response) { - $("#websiteModifyFailure").fadeIn(); - } - - }; - - - $scope.modifyWebsiteFunc = function () { - - var domain = $scope.websiteToBeModified; - var packForWeb = $scope.selectedPack; - var email = $scope.adminEmail; - var phpVersion = $scope.phpSelection; - var admin = $scope.selectedAdmin; - - - $("#websiteModifyFailure").hide(); - $("#websiteModifySuccess").hide(); - $("#websiteSuccessfullyModified").hide(); - $("#canNotModify").hide(); - $("#modifyWebsiteLoading").fadeIn(); - - - url = "/websites/saveWebsiteChanges"; - - var data = { - domain: domain, - packForWeb: packForWeb, - email: email, - phpVersion: phpVersion, - admin: admin - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.saveStatus === 0) { - $scope.errMessage = response.data.error_message; - - $("#canNotModify").fadeIn(); - $("#websiteModifyFailure").hide(); - $("#websiteModifySuccess").hide(); - $("#websiteSuccessfullyModified").hide(); - $("#modifyWebsiteLoading").hide(); - - - } else { - $("#modifyWebsiteButton").hide(); - $("#canNotModify").hide(); - $("#websiteModifyFailure").hide(); - $("#websiteModifySuccess").hide(); - - $("#websiteSuccessfullyModified").fadeIn(); - $("#modifyWebsiteLoading").hide(); - - $scope.websiteModified = domain; - - - } - - - } - - function cantLoadInitialDatas(response) { - $scope.errMessage = response.data.error_message; - $("#canNotModify").fadeIn(); - } - - - }; - -}); - -/* Java script code to Modify Pacakge ends here */ - - -/* Java script code to create account */ -var website_child_domain_check = 0; - -function website_child_domain_checkbox_function() { - - var checkBox = document.getElementById("myCheck"); - // Get the output text - - - // If the checkbox is checked, display the output text - if (checkBox.checked == true) { - website_child_domain_check = 0; - document.getElementById('Website_Create_Test_Domain').style.display = "block"; - document.getElementById('Website_Create_Own_Domain').style.display = "none"; - - } else { - document.getElementById('Website_Create_Test_Domain').style.display = "none"; - document.getElementById('Website_Create_Own_Domain').style.display = "block"; - website_child_domain_check = 1; - } - - // alert(domain_check); -} - -app.controller('websitePages', function ($scope, $http, $timeout, $window) { - - $scope.logFileLoading = true; - $scope.logsFeteched = true; - $scope.couldNotFetchLogs = true; - $scope.couldNotConnect = true; - $scope.fetchedData = true; - $scope.hideLogs = true; - $scope.hideErrorLogs = true; - - $scope.hidelogsbtn = function () { - $scope.hideLogs = true; - }; - - $scope.hideErrorLogsbtn = function () { - $scope.hideLogs = true; - }; - - $scope.fileManagerURL = "/filemanager/" + $("#domainNamePage").text(); - $scope.wordPressInstallURL = $("#domainNamePage").text() + "/wordpressInstall"; - $scope.joomlaInstallURL = $("#domainNamePage").text() + "/joomlaInstall"; - $scope.setupGit = $("#domainNamePage").text() + "/setupGit"; - $scope.installPrestaURL = $("#domainNamePage").text() + "/installPrestaShop"; - $scope.installMagentoURL = $("#domainNamePage").text() + "/installMagento"; - $scope.installMauticURL = $("#domainNamePage").text() + "/installMautic"; - $scope.domainAliasURL = "/websites/" + $("#domainNamePage").text() + "/domainAlias"; - $scope.previewUrl = "/preview/" + $("#domainNamePage").text() + "/"; - - var logType = 0; - $scope.pageNumber = 1; - - $scope.fetchLogs = function (type) { - - var pageNumber = $scope.pageNumber; - - - if (type == 3) { - pageNumber = $scope.pageNumber + 1; - $scope.pageNumber = pageNumber; - } else if (type == 4) { - pageNumber = $scope.pageNumber - 1; - $scope.pageNumber = pageNumber; - } else { - logType = type; - } - - - $scope.logFileLoading = false; - $scope.logsFeteched = true; - $scope.couldNotFetchLogs = true; - $scope.couldNotConnect = true; - $scope.fetchedData = false; - $scope.hideErrorLogs = true; - - - url = "/websites/getDataFromLogFile"; - - var domainNamePage = $("#domainNamePage").text(); - - - var data = { - logType: logType, - virtualHost: domainNamePage, - page: pageNumber, - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.logstatus == 1) { - - - $scope.logFileLoading = true; - $scope.logsFeteched = false; - $scope.couldNotFetchLogs = true; - $scope.couldNotConnect = true; - $scope.fetchedData = false; - $scope.hideLogs = false; - - - $scope.records = JSON.parse(response.data.data); - - } else { - - $scope.logFileLoading = true; - $scope.logsFeteched = true; - $scope.couldNotFetchLogs = false; - $scope.couldNotConnect = true; - $scope.fetchedData = true; - $scope.hideLogs = false; - - - $scope.errorMessage = response.data.error_message; - console.log(domainNamePage) - - } - - - } - - function cantLoadInitialDatas(response) { - - $scope.logFileLoading = true; - $scope.logsFeteched = true; - $scope.couldNotFetchLogs = true; - $scope.couldNotConnect = false; - $scope.fetchedData = true; - $scope.hideLogs = false; - - } - - - }; - - $scope.errorPageNumber = 1; - - - $scope.fetchErrorLogs = function (type) { - - var errorPageNumber = $scope.errorPageNumber; - - - if (type == 3) { - errorPageNumber = $scope.errorPageNumber + 1; - $scope.errorPageNumber = errorPageNumber; - } else if (type == 4) { - errorPageNumber = $scope.errorPageNumber - 1; - $scope.errorPageNumber = errorPageNumber; - } else { - logType = type; - } - - // notifications - - $scope.logFileLoading = false; - $scope.logsFeteched = true; - $scope.couldNotFetchLogs = true; - $scope.couldNotConnect = true; - $scope.fetchedData = true; - $scope.hideErrorLogs = true; - $scope.hideLogs = false; - - - url = "/websites/fetchErrorLogs"; - - var domainNamePage = $("#domainNamePage").text(); - - - var data = { - virtualHost: domainNamePage, - page: errorPageNumber, - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.logstatus === 1) { - - - // notifications - - $scope.logFileLoading = true; - $scope.logsFeteched = false; - $scope.couldNotFetchLogs = true; - $scope.couldNotConnect = true; - $scope.fetchedData = true; - $scope.hideLogs = false; - $scope.hideErrorLogs = false; - - - $scope.errorLogsData = response.data.data; - - } else { - - // notifications - - $scope.logFileLoading = true; - $scope.logsFeteched = true; - $scope.couldNotFetchLogs = false; - $scope.couldNotConnect = true; - $scope.fetchedData = true; - $scope.hideLogs = true; - $scope.hideErrorLogs = true; - - - $scope.errorMessage = response.data.error_message; - - } - - - } - - function cantLoadInitialDatas(response) { - - // notifications - - $scope.logFileLoading = true; - $scope.logsFeteched = true; - $scope.couldNotFetchLogs = true; - $scope.couldNotConnect = false; - $scope.fetchedData = true; - $scope.hideLogs = true; - $scope.hideErrorLogs = true; - - } - - - }; - - ///////// Configurations Part - - $scope.configurationsBox = true; - $scope.configsFetched = true; - $scope.couldNotFetchConfigs = true; - $scope.couldNotConnect = true; - $scope.fetchedConfigsData = true; - $scope.configFileLoading = true; - $scope.configSaved = true; - $scope.couldNotSaveConfigurations = true; - - $scope.hideconfigbtn = function () { - - $scope.configurationsBox = true; - }; - - $scope.fetchConfigurations = function () { - - - $scope.hidsslconfigs = true; - $scope.configurationsBoxRewrite = true; - $scope.changePHPView = true; - - - //Rewrite rules - $scope.configurationsBoxRewrite = true; - $scope.rewriteRulesFetched = true; - $scope.couldNotFetchRewriteRules = true; - $scope.rewriteRulesSaved = true; - $scope.couldNotSaveRewriteRules = true; - $scope.fetchedRewriteRules = true; - $scope.saveRewriteRulesBTN = true; - - /// - - $scope.configFileLoading = false; - - - url = "/websites/getDataFromConfigFile"; - - var virtualHost = $("#domainNamePage").text(); - - - var data = { - virtualHost: virtualHost, - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.configstatus === 1) { - - //Rewrite rules - - $scope.configurationsBoxRewrite = true; - $scope.rewriteRulesFetched = true; - $scope.couldNotFetchRewriteRules = true; - $scope.rewriteRulesSaved = true; - $scope.couldNotSaveRewriteRules = true; - $scope.fetchedRewriteRules = true; - $scope.saveRewriteRulesBTN = true; - - /// - - $scope.configurationsBox = false; - $scope.configsFetched = false; - $scope.couldNotFetchConfigs = true; - $scope.couldNotConnect = true; - $scope.fetchedConfigsData = false; - $scope.configFileLoading = true; - $scope.configSaved = true; - $scope.couldNotSaveConfigurations = true; - $scope.saveConfigBtn = false; - - - $scope.configData = response.data.configData; - - } else { - - //Rewrite rules - $scope.configurationsBoxRewrite = true; - $scope.rewriteRulesFetched = true; - $scope.couldNotFetchRewriteRules = true; - $scope.rewriteRulesSaved = true; - $scope.couldNotSaveRewriteRules = true; - $scope.fetchedRewriteRules = true; - $scope.saveRewriteRulesBTN = true; - - /// - $scope.configurationsBox = false; - $scope.configsFetched = true; - $scope.couldNotFetchConfigs = false; - $scope.couldNotConnect = true; - $scope.fetchedConfigsData = true; - $scope.configFileLoading = true; - $scope.configSaved = true; - $scope.couldNotSaveConfigurations = true; - - - $scope.errorMessage = response.data.error_message; - - } - - - } - - function cantLoadInitialDatas(response) { - - //Rewrite rules - $scope.configurationsBoxRewrite = true; - $scope.rewriteRulesFetched = true; - $scope.couldNotFetchRewriteRules = true; - $scope.rewriteRulesSaved = true; - $scope.couldNotSaveRewriteRules = true; - $scope.fetchedRewriteRules = true; - $scope.saveRewriteRulesBTN = true; - /// - - $scope.configurationsBox = false; - $scope.configsFetched = true; - $scope.couldNotFetchConfigs = true; - $scope.couldNotConnect = false; - $scope.fetchedConfigsData = true; - $scope.configFileLoading = true; - $scope.configSaved = true; - $scope.couldNotSaveConfigurations = true; - - - } - - - }; - - $scope.saveCongiruations = function () { - - $scope.configFileLoading = false; - - - url = "/websites/saveConfigsToFile"; - - var virtualHost = $("#domainNamePage").text(); - var configData = $scope.configData; - - - var data = { - virtualHost: virtualHost, - configData: configData, - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.configstatus === 1) { - - $scope.configurationsBox = false; - $scope.configsFetched = true; - $scope.couldNotFetchConfigs = true; - $scope.couldNotConnect = true; - $scope.fetchedConfigsData = true; - $scope.configFileLoading = true; - $scope.configSaved = false; - $scope.couldNotSaveConfigurations = true; - $scope.saveConfigBtn = true; - - - } else { - $scope.configurationsBox = false; - $scope.configsFetched = true; - $scope.couldNotFetchConfigs = true; - $scope.couldNotConnect = true; - $scope.fetchedConfigsData = false; - $scope.configFileLoading = true; - $scope.configSaved = true; - $scope.couldNotSaveConfigurations = false; - - - $scope.errorMessage = response.data.error_message; - - } - - - } - - function cantLoadInitialDatas(response) { - - $scope.configurationsBox = false; - $scope.configsFetched = true; - $scope.couldNotFetchConfigs = true; - $scope.couldNotConnect = false; - $scope.fetchedConfigsData = true; - $scope.configFileLoading = true; - $scope.configSaved = true; - $scope.couldNotSaveConfigurations = true; - - - } - - - }; - - - ///////// Rewrite Rules - - $scope.configurationsBoxRewrite = true; - $scope.rewriteRulesFetched = true; - $scope.couldNotFetchRewriteRules = true; - $scope.rewriteRulesSaved = true; - $scope.couldNotSaveRewriteRules = true; - $scope.fetchedRewriteRules = true; - $scope.saveRewriteRulesBTN = true; - - $scope.hideRewriteRulesbtn = function () { - $scope.configurationsBoxRewrite = true; - }; - - $scope.fetchRewriteFules = function () { - - $scope.hidsslconfigs = true; - $scope.configurationsBox = true; - $scope.changePHPView = true; - - - $scope.configurationsBox = true; - $scope.configsFetched = true; - $scope.couldNotFetchConfigs = true; - $scope.couldNotConnect = true; - $scope.fetchedConfigsData = true; - $scope.configFileLoading = true; - $scope.configSaved = true; - $scope.couldNotSaveConfigurations = true; - $scope.saveConfigBtn = true; - - $scope.configFileLoading = false; - - - url = "/websites/getRewriteRules"; - - var virtualHost = $("#domainNamePage").text(); - - - var data = { - virtualHost: virtualHost, - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.rewriteStatus == 1) { - - - // from main - - $scope.configurationsBox = true; - $scope.configsFetched = true; - $scope.couldNotFetchConfigs = true; - $scope.fetchedConfigsData = true; - $scope.configSaved = true; - $scope.couldNotSaveConfigurations = true; - $scope.saveConfigBtn = true; - - // main ends - - $scope.configFileLoading = true; - - // - - - $scope.configurationsBoxRewrite = false; - $scope.rewriteRulesFetched = false; - $scope.couldNotFetchRewriteRules = true; - $scope.rewriteRulesSaved = true; - $scope.couldNotSaveRewriteRules = true; - $scope.fetchedRewriteRules = false; - $scope.saveRewriteRulesBTN = false; - $scope.couldNotConnect = true; - - - $scope.rewriteRules = response.data.rewriteRules; - - } else { - // from main - $scope.configurationsBox = true; - $scope.configsFetched = true; - $scope.couldNotFetchConfigs = true; - $scope.fetchedConfigsData = true; - $scope.configFileLoading = true; - $scope.configSaved = true; - $scope.couldNotSaveConfigurations = true; - $scope.saveConfigBtn = true; - // from main - - $scope.configFileLoading = true; - - /// - - $scope.configurationsBoxRewrite = true; - $scope.rewriteRulesFetched = true; - $scope.couldNotFetchRewriteRules = false; - $scope.rewriteRulesSaved = true; - $scope.couldNotSaveRewriteRules = true; - $scope.fetchedRewriteRules = true; - $scope.saveRewriteRulesBTN = true; - $scope.couldNotConnect = true; - - - $scope.errorMessage = response.data.error_message; - - } - - - } - - function cantLoadInitialDatas(response) { - // from main - - $scope.configurationsBox = true; - $scope.configsFetched = true; - $scope.couldNotFetchConfigs = true; - $scope.fetchedConfigsData = true; - $scope.configFileLoading = true; - $scope.configSaved = true; - $scope.couldNotSaveConfigurations = true; - $scope.saveConfigBtn = true; - - // from main - - $scope.configFileLoading = true; - - /// - - $scope.configurationsBoxRewrite = true; - $scope.rewriteRulesFetched = true; - $scope.couldNotFetchRewriteRules = true; - $scope.rewriteRulesSaved = true; - $scope.couldNotSaveRewriteRules = true; - $scope.fetchedRewriteRules = true; - $scope.saveRewriteRulesBTN = true; - - $scope.couldNotConnect = false; - - - } - - - }; - - $scope.saveRewriteRules = function () { - - $scope.configFileLoading = false; - - - url = "/websites/saveRewriteRules"; - - var virtualHost = $("#domainNamePage").text(); - var rewriteRules = $scope.rewriteRules; - - - var data = { - virtualHost: virtualHost, - rewriteRules: rewriteRules, - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.rewriteStatus == 1) { - - $scope.configurationsBoxRewrite = false; - $scope.rewriteRulesFetched = true; - $scope.couldNotFetchRewriteRules = true; - $scope.rewriteRulesSaved = false; - $scope.couldNotSaveRewriteRules = true; - $scope.fetchedRewriteRules = true; - $scope.saveRewriteRulesBTN = true; - $scope.configFileLoading = true; - - - } else { - $scope.configurationsBoxRewrite = false; - $scope.rewriteRulesFetched = false; - $scope.couldNotFetchRewriteRules = true; - $scope.rewriteRulesSaved = true; - $scope.couldNotSaveRewriteRules = false; - $scope.fetchedRewriteRules = true; - $scope.saveRewriteRulesBTN = false; - - $scope.configFileLoading = true; - - - $scope.errorMessage = response.data.error_message; - - } - - - } - - function cantLoadInitialDatas(response) { - - $scope.configurationsBoxRewrite = false; - $scope.rewriteRulesFetched = false; - $scope.couldNotFetchRewriteRules = true; - $scope.rewriteRulesSaved = true; - $scope.couldNotSaveRewriteRules = true; - $scope.fetchedRewriteRules = true; - $scope.saveRewriteRulesBTN = false; - - $scope.configFileLoading = true; - - $scope.couldNotConnect = false; - - - } - - - }; - - //////// Application Installation part - - $scope.installationDetailsForm = true; - $scope.installationDetailsFormJoomla = true; - $scope.applicationInstallerLoading = true; - $scope.installationFailed = true; - $scope.installationSuccessfull = true; - $scope.couldNotConnect = true; - - - $scope.installationDetails = function () { - - $scope.installationDetailsForm = !$scope.installationDetailsForm; - $scope.installationDetailsFormJoomla = true; - - }; - - $scope.installationDetailsJoomla = function () { - - $scope.installationDetailsFormJoomla = !$scope.installationDetailsFormJoomla; - $scope.installationDetailsForm = true; - - }; - - $scope.installWordpress = function () { - - - $scope.installationDetailsForm = false; - $scope.applicationInstallerLoading = false; - $scope.installationFailed = true; - $scope.installationSuccessfull = true; - $scope.couldNotConnect = true; - - var domain = $("#domainNamePage").text(); - var path = $scope.installPath; - - url = "/websites/installWordpress"; - - var home = "1"; - - if (typeof path != 'undefined') { - home = "0"; - } - - - var data = { - domain: domain, - home: home, - path: path, - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.installStatus === 1) { - if (typeof path != 'undefined') { - $scope.installationURL = "http://" + domain + "/" + path; - } else { - $scope.installationURL = domain; - } - - $scope.installationDetailsForm = false; - $scope.applicationInstallerLoading = true; - $scope.installationFailed = true; - $scope.installationSuccessfull = false; - $scope.couldNotConnect = true; - - } else { - - $scope.installationDetailsForm = false; - $scope.applicationInstallerLoading = true; - $scope.installationFailed = false; - $scope.installationSuccessfull = true; - $scope.couldNotConnect = true; - - $scope.errorMessage = response.data.error_message; - - } - - - } - - function cantLoadInitialDatas(response) { - - $scope.installationDetailsForm = false; - $scope.applicationInstallerLoading = true; - $scope.installationFailed = true; - $scope.installationSuccessfull = true; - $scope.couldNotConnect = false; - - } - - }; - - $scope.installJoomla = function () { - - - $scope.installationDetailsFormJoomla = false; - $scope.applicationInstallerLoading = false; - $scope.installationFailed = true; - $scope.installationSuccessfull = true; - $scope.couldNotConnect = true; - - var domain = $("#domainNamePage").text(); - var path = $scope.installPath; - var username = 'admin'; - var password = $scope.password; - var prefix = $scope.prefix; - - - url = "/websites/installJoomla"; - - var home = "1"; - - if (typeof path != 'undefined') { - home = "0"; - } - - - var data = { - domain: domain, - siteName: $scope.siteName, - home: home, - path: path, - password: password, - prefix: prefix, - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.installStatus === 1) { - if (typeof path != 'undefined') { - $scope.installationURL = "http://" + domain + "/" + path; - } else { - $scope.installationURL = domain; - } - - $scope.installationDetailsFormJoomla = false; - $scope.applicationInstallerLoading = true; - $scope.installationFailed = true; - $scope.installationSuccessfull = false; - $scope.couldNotConnect = true; - - } else { - - $scope.installationDetailsFormJoomla = false; - $scope.applicationInstallerLoading = true; - $scope.installationFailed = false; - $scope.installationSuccessfull = true; - $scope.couldNotConnect = true; - - $scope.errorMessage = response.data.error_message; - - } - - - } - - function cantLoadInitialDatas(response) { - - $scope.installationDetailsFormJoomla = false; - $scope.applicationInstallerLoading = true; - $scope.installationFailed = true; - $scope.installationSuccessfull = true; - $scope.couldNotConnect = false; - - } - - }; - - - //////// SSL Part - - $scope.sslSaved = true; - $scope.couldNotSaveSSL = true; - $scope.hidsslconfigs = true; - $scope.couldNotConnect = true; - - - $scope.hidesslbtn = function () { - $scope.hidsslconfigs = true; - }; - - $scope.addSSL = function () { - $scope.hidsslconfigs = false; - $scope.configurationsBox = true; - $scope.configurationsBoxRewrite = true; - $scope.changePHPView = true; - }; - - $scope.saveSSL = function () { - - - $scope.configFileLoading = false; - - url = "/websites/saveSSL"; - - var virtualHost = $("#domainNamePage").text(); - var cert = $scope.cert; - var key = $scope.key; - - - var data = { - virtualHost: virtualHost, - cert: cert, - key: key - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.sslStatus === 1) { - - $scope.sslSaved = false; - $scope.couldNotSaveSSL = true; - $scope.couldNotConnect = true; - $scope.configFileLoading = true; - - - } else { - - $scope.sslSaved = true; - $scope.couldNotSaveSSL = false; - $scope.couldNotConnect = true; - $scope.configFileLoading = true; - - $scope.errorMessage = response.data.error_message; - - } - - - } - - function cantLoadInitialDatas(response) { - - $scope.sslSaved = true; - $scope.couldNotSaveSSL = true; - $scope.couldNotConnect = false; - $scope.configFileLoading = true; - - - } - - }; - - //// Change PHP Master - - $scope.failedToChangePHPMaster = true; - $scope.phpChangedMaster = true; - $scope.couldNotConnect = true; - - $scope.changePHPView = true; - - - $scope.hideChangePHPMaster = function () { - $scope.changePHPView = true; - }; - - $scope.changePHPMaster = function () { - $scope.hidsslconfigs = true; - $scope.configurationsBox = true; - $scope.configurationsBoxRewrite = true; - $scope.changePHPView = false; - }; - - $scope.changePHPVersionMaster = function (childDomain, phpSelection) { - - // notifcations - - $scope.configFileLoading = false; - - var url = "/websites/changePHP"; - - var data = { - childDomain: $("#domainNamePage").text(), - phpSelection: $scope.phpSelectionMaster, - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - - if (response.data.changePHP === 1) { - - $scope.configFileLoading = true; - $scope.websiteDomain = $("#domainNamePage").text(); - - - // notifcations - - $scope.failedToChangePHPMaster = true; - $scope.phpChangedMaster = false; - $scope.couldNotConnect = true; - - - } else { - - $scope.configFileLoading = true; - $scope.errorMessage = response.data.error_message; - - // notifcations - - $scope.failedToChangePHPMaster = false; - $scope.phpChangedMaster = true; - $scope.couldNotConnect = true; - - } - - - } - - function cantLoadInitialDatas(response) { - - $scope.configFileLoading = true; - - // notifcations - - $scope.failedToChangePHPMaster = true; - $scope.phpChangedMaster = true; - $scope.couldNotConnect = false; - - } - - }; - - ////// create domain part - - $("#domainCreationForm").hide(); - - $scope.showCreateDomainForm = function () { - $("#domainCreationForm").fadeIn(); - }; - - $scope.hideDomainCreationForm = function () { - $("#domainCreationForm").fadeOut(); - }; - - $scope.masterDomain = $("#domainNamePage").text(); - - // notifcations settings - $scope.domainLoading = true; - $scope.installationDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - $scope.DomainCreateForm = true; - - var statusFile; - - - $scope.webselection = true; - $scope.WebsiteType = function () { - var type = $scope.websitetype; - if (type == 'Sub Domain') { - $scope.webselection = false; - $scope.DomainCreateForm = true; - - } else if (type == 'Addon Domain') { - $scope.DomainCreateForm = false; - $scope.webselection = true; - $scope.masterDomain = $('#defaultSite').html() - } - }; - - $scope.WebsiteSelection = function () { - $scope.DomainCreateForm = false; - }; - - $scope.createDomain = function () { - - $scope.domainLoading = false; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - $scope.currentStatus = "Starting creation.."; - $scope.DomainCreateForm = true; - - var ssl, dkimCheck, openBasedir, apacheBackend; - - if ($scope.sslCheck === true) { - ssl = 1; - } else { - ssl = 0 - } - - if ($scope.dkimCheck === true) { - dkimCheck = 1; - } else { - dkimCheck = 0 - } - - if ($scope.openBasedir === true) { - openBasedir = 1; - } else { - openBasedir = 0 - } - - - if ($scope.apacheBackend === true) { - apacheBackend = 1; - } else { - apacheBackend = 0 - } - - - url = "/websites/submitDomainCreation"; - var domainName = $scope.domainNameCreate; - var phpSelection = $scope.phpSelection; - - var path = $scope.docRootPath; - - if (typeof path === 'undefined') { - path = ""; - } - var package = $scope.packageForWebsite; - - // if (website_child_domain_check == 0) { - // var Part2_domainNameCreate = document.getElementById('Part2_domainNameCreate').value; - // var domainName = document.getElementById('TestDomainNameCreate').value + Part2_domainNameCreate; - // } - // if (website_child_domain_check == 1) { - // - // var domainName = $scope.own_domainNameCreate; - // } - var type = $scope.websitetype; - - var domainName = $scope.domainNameCreate; - - - var data = { - domainName: domainName, - phpSelection: phpSelection, - ssl: ssl, - path: path, - masterDomain: $scope.masterDomain, - dkimCheck: dkimCheck, - openBasedir: openBasedir, - apacheBackend: apacheBackend - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - // console.log(data) - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.createWebSiteStatus === 1) { - statusFile = response.data.tempStatusPath; - getCreationStatus(); - } else { - - $scope.domainLoading = true; - $scope.installationDetailsForm = true; - $scope.DomainCreateForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = false; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $scope.errorMessage = response.data.error_message; - } - - - } - - function cantLoadInitialDatas(response) { - - $scope.domainLoading = true; - $scope.installationDetailsForm = true; - $scope.DomainCreateForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - }; - - $scope.goBack = function () { - $scope.domainLoading = true; - $scope.installationDetailsForm = false; - $scope.DomainCreateForm = true; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - $scope.DomainCreateForm = true; - $("#installProgress").css("width", "0%"); - }; - - function getCreationStatus() { - - url = "/websites/installWordpressStatus"; - - var data = { - statusFile: statusFile - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - - if (response.data.abort === 1) { - - if (response.data.installStatus === 1) { - - $scope.domainLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = false; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $("#installProgress").css("width", "100%"); - $scope.installPercentage = "100"; - $scope.currentStatus = response.data.currentStatus; - $timeout.cancel(); - - } else { - - $scope.domainLoading = true; - $scope.installationDetailsForm = true; - $scope.DomainCreateForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = false; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $scope.errorMessage = response.data.error_message; - - $("#installProgress").css("width", "0%"); - $scope.installPercentage = "0"; - $scope.goBackDisable = false; - - } - - } else { - $("#installProgress").css("width", response.data.installationProgress + "%"); - $scope.installPercentage = response.data.installationProgress; - $scope.currentStatus = response.data.currentStatus; - $timeout(getCreationStatus, 1000); - } - - } - - function cantLoadInitialDatas(response) { - - $scope.domainLoading = true; - $scope.installationDetailsForm = true; - $scope.DomainCreateForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - } - - - ////// List Domains Part - - //////////////////////// - - // notifcations - - $scope.phpChanged = true; - $scope.domainError = true; - $scope.couldNotConnect = true; - $scope.domainDeleted = true; - $scope.sslIssued = true; - $scope.childBaseDirChanged = true; - - $("#listDomains").hide(); - - - $scope.showListDomains = function () { - fetchDomains(); - $("#listDomains").fadeIn(); - }; - - $scope.hideListDomains = function () { - $("#listDomains").fadeOut(); - }; - - function fetchDomains() { - $scope.domainLoading = false; - - var url = "/websites/fetchDomains"; - - var data = { - masterDomain: $("#domainNamePage").text(), - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - - if (response.data.fetchStatus === 1) { - - $scope.childDomains = JSON.parse(response.data.data); - $scope.domainLoading = true; - - - } else { - $scope.domainError = false; - $scope.errorMessage = response.data.error_message; - $scope.domainLoading = true; - } - - - } - - function cantLoadInitialDatas(response) { - - $scope.couldNotConnect = false; - - } - - } - -/** - * Created by usman on 7/26/17. - */ -function getCookie(name) { - var cookieValue = null; - var t = document.cookie; - if (document.cookie && document.cookie !== '') { - var cookies = document.cookie.split(';'); - for (var i = 0; i < cookies.length; i++) { - var cookie = jQuery.trim(cookies[i]); - // Does this cookie string begin with the name we want? - if (cookie.substring(0, name.length + 1) === (name + '=')) { - cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); - break; - } - } - } - return cookieValue; -} - - -var arry = [] - -function selectpluginJs(val) { - $('#mysearch').hide() - arry.push(val) - - // console.log(arry) - document.getElementById('selJS').innerHTML = ""; - - for (var i = 0; i < arry.length; i++) { - $('#selJS').show() - var mlm = ' ' + arry[i] + '    ' - $('#selJS').append(mlm) - } - - -} - - -var DeletePluginURL; - -function DeletePluginBuucket(url) { - DeletePluginURL = url; -} - -function FinalDeletePluginBuucket() { - window.location.href = DeletePluginURL; -} - -var SPVal; - -app.controller('WPAddNewPlugin', function ($scope, $http, $timeout, $window, $compile) { - $scope.webSiteCreationLoading = true; - - $scope.SearchPluginName = function (val) { - $scope.webSiteCreationLoading = false; - SPVal = val; - url = "/websites/SearchOnkeyupPlugin"; - - var searchcontent = $scope.searchcontent; - - - var data = { - pluginname: searchcontent - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.webSiteCreationLoading = true; - - if (response.data.status === 1) { - if (SPVal == 'add') { - $('#mysearch').show() - document.getElementById('mysearch').innerHTML = ""; - var res = response.data.plugns.plugins - // console.log(res); - for (i = 0; i <= res.length; i++) { - // - var tml = '
    '; - $('#mysearch').append(tml); - } - } else if (SPVal == 'eidt') { - $('#mysearch').show() - document.getElementById('mysearch').innerHTML = ""; - var res = response.data.plugns.plugins - // console.log(res); - for (i = 0; i <= res.length; i++) { - // - var tml = '
    '; - var temp = $compile(tml)($scope) - angular.element(document.getElementById('mysearch')).append(temp); - } - - } - - - } else { - - // $scope.errorMessage = response.data.error_message; - alert("Status not = 1: Error..." + response.data.error_message) - } - - - } - - function cantLoadInitialDatas(response) { - - alert("Error..." + response) - - } - } - - $scope.AddNewplugin = function () { - - url = "/websites/AddNewpluginAjax"; - - var bucketname = $scope.PluginbucketName - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - var data = { - config: arry, - Name: bucketname - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - function ListInitialDatas(response) { - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Bucket created.', - type: 'success' - }); - location.reload(); - } else { - - new PNotify({ - title: 'Error!', - text: response.data.error_message, - type: 'error' - }); - } - - - } - - function cantLoadInitialDatas(response) { - - alert("Error..." + response) - - } - } - - $scope.deletesPlgin = function (val) { - - url = "/websites/deletesPlgin"; - - - var data = { - pluginname: val, - pluginbBucketID: $('#pluginbID').html() - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.status === 1) { - location.reload(); - - } else { - - // $scope.errorMessage = response.data.error_message; - alert("Status not = 1: Error..." + response.data.error_message) - } - - - } - - function cantLoadInitialDatas(response) { - - alert("Error..." + response) - - } - - } - - $scope.Addplugin = function (slug) { - $('#mysearch').hide() - - url = "/websites/Addplugineidt"; - - - var data = { - pluginname: slug, - pluginbBucketID: $('#pluginbID').html() - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.status === 1) { - location.reload(); - - } else { - - // $scope.errorMessage = response.data.error_message; - alert("Status not = 1: Error..." + response.data.error_message) - } - - - } - - function cantLoadInitialDatas(response) { - - alert("Error..." + response) - - } - - - } - -}); - -var domain_check = 0; - -function checkbox_function() { - - var checkBox = document.getElementById("myCheck"); - // Get the output text - - - // If the checkbox is checked, display the output text - if (checkBox.checked == true) { - domain_check = 0; - document.getElementById('Test_Domain').style.display = "block"; - document.getElementById('Own_Domain').style.display = "none"; - - } else { - document.getElementById('Test_Domain').style.display = "none"; - document.getElementById('Own_Domain').style.display = "block"; - domain_check = 1; - } - - // alert(domain_check); -} - -app.controller('createWordpress', function ($scope, $http, $timeout, $compile, $window) { - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - - - var statusFile; - - $scope.createWordPresssite = function () { - - $scope.webSiteCreationLoading = false; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - - - $scope.currentStatus = "Starting creation.."; - - var apacheBackend = 0; - - if ($scope.apacheBackend === true) { - apacheBackend = 1; - } else { - apacheBackend = 0 - } - - var package = $scope.packageForWebsite; - var websiteOwner = $scope.websiteOwner; - var WPtitle = $scope.WPtitle; - - // if (domain_check == 0) { - // var Part2_domainNameCreate = document.getElementById('Part2_domainNameCreate').value; - // var domainNameCreate = document.getElementById('TestDomainNameCreate').value + Part2_domainNameCreate; - // } - // if (domain_check == 1) { - // - // var domainNameCreate = $scope.own_domainNameCreate; - // } - - var domainNameCreate = $scope.domainNameCreate; - - - var WPUsername = $scope.WPUsername; - var adminEmail = $scope.adminEmail; - var WPPassword = $scope.WPPassword; - var WPVersions = $scope.WPVersions; - var pluginbucket = $scope.pluginbucket; - var autoupdates = $scope.autoupdates; - var pluginupdates = $scope.pluginupdates; - var themeupdates = $scope.themeupdates; - - if (domain_check == 0) { - - var path = ""; - - } - if (domain_check = 1) { - - var path = $scope.installPath; - - } - - - var home = "1"; - - if (typeof path != 'undefined') { - home = "0"; - } - - //alert(domainNameCreate); - var data = { - - title: WPtitle, - domain: domainNameCreate, - WPVersion: WPVersions, - pluginbucket: pluginbucket, - adminUser: WPUsername, - Email: adminEmail, - PasswordByPass: WPPassword, - AutomaticUpdates: autoupdates, - Plugins: pluginupdates, - Themes: themeupdates, - websiteOwner: websiteOwner, - package: package, - home: home, - path: path, - apacheBackend: apacheBackend - } - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - var url = "/websites/submitWorpressCreation"; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.webSiteCreationLoading = true; - if (response.data.status === 1) { - statusFile = response.data.tempStatusPath; - getCreationStatus(); - - } else { - $scope.goBackDisable = false; - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - } - - } - - function cantLoadInitialDatas(response) { - - alert("Error..." + response) - - } - - }; - $scope.goBack = function () { - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - $("#installProgress").css("width", "0%"); - }; - - function getCreationStatus() { - - url = "/websites/installWordpressStatus"; - - var data = { - statusFile: statusFile - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.abort === 1) { - - if (response.data.installStatus === 1) { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = false; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $("#installProgress").css("width", "100%"); - $scope.installPercentage = "100"; - $scope.currentStatus = response.data.currentStatus; - $timeout.cancel(); - - } else { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = false; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $scope.errorMessage = response.data.error_message; - - $("#installProgress").css("width", "0%"); - $scope.installPercentage = "0"; - $scope.goBackDisable = false; - - } - - } else { - $scope.webSiteCreationLoading = false; - $("#installProgress").css("width", response.data.installationProgress + "%"); - $scope.installPercentage = response.data.installationProgress; - $scope.currentStatus = response.data.currentStatus; - $timeout(getCreationStatus, 1000); - } - - } - - function cantLoadInitialDatas(response) { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - } - - -}); - - -//........... delete wp list -var FurlDeleteWP; - -function DeleteWPNow(url) { - FurlDeleteWP = url; -} - -function FinalDeleteWPNow() { - window.location.href = FurlDeleteWP; -} - -var DeploytoProductionID; - -function DeployToProductionInitial(vall) { - DeploytoProductionID = vall; -} - -var create_staging_domain_check = 0; - -function create_staging_checkbox_function() { - - try { - - var checkBox = document.getElementById("Create_Staging_Check"); - // Get the output text - - - // If the checkbox is checked, display the output text - if (checkBox.checked == true) { - create_staging_domain_check = 0; - document.getElementById('Website_Create_Test_Domain').style.display = "block"; - document.getElementById('Website_Create_Own_Domain').style.display = "none"; - - } else { - document.getElementById('Website_Create_Test_Domain').style.display = "none"; - document.getElementById('Website_Create_Own_Domain').style.display = "block"; - create_staging_domain_check = 1; - } - } catch (e) { - - } - - // alert(domain_check); -} - -create_staging_checkbox_function(); - -app.controller('WPsiteHome', function ($scope, $http, $timeout, $compile, $window) { - - var CheckBoxpasssword = 0; - - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - $(document).ready(function () { - var checkstatus = document.getElementById("wordpresshome"); - if (checkstatus !== null) { - $scope.LoadWPdata(); - - } - }); - - - $scope.LoadWPdata = function () { - - $scope.wordpresshomeloading = false; - $('#wordpresshomeloading').show(); - - var url = "/websites/FetchWPdata"; - - var data = { - WPid: $('#WPid').html(), - } - - console.log(data); - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - wordpresshomeloading = true; - $('#wordpresshomeloading').hide(); - - if (response.data.status === 1) { - $('#WPVersion').text(response.data.ret_data.version); - if (response.data.ret_data.lscache === 1) { - $('#lscache').prop('checked', true); - } - if (response.data.ret_data.debugging === 1) { - $('#debugging').prop('checked', true); - } - if (response.data.ret_data.searchIndex === 1) { - $('#searchIndex').prop('checked', true); - } - if (response.data.ret_data.maintenanceMode === 1) { - $('#maintenanceMode').prop('checked', true); - } - if (response.data.ret_data.wpcron === 1) { - $('#wpcron').prop('checked', true); - } - if (response.data.ret_data.passwordprotection == 1) { - - var dc = '\n' + - ' ' - var mp = $compile(dc)($scope); - angular.element(document.getElementById('prsswdprodata')).append(mp); - CheckBoxpasssword = 1; - } else if (response.data.ret_data.passwordprotection == 0) { - var dc = '\n' + - ' ' - $('#prsswdprodata').append(dc); - CheckBoxpasssword = 0; - } - - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - }; - - $scope.UpdateWPSettings = function (setting) { - - $scope.wordpresshomeloading = false; - $('#wordpresshomeloading').show(); - - - var url = "/websites/UpdateWPSettings"; - - if (setting === "PasswordProtection") { - if (CheckBoxpasssword == 0) { - var data = { - WPid: $('#WPid').html(), - setting: setting, - PPUsername: $scope.PPUsername, - PPPassword: $scope.PPPassword, - } - - } else { - var data = { - WPid: $('#WPid').html(), - setting: setting, - PPUsername: '', - PPPassword: '', - } - - } - - } else { - var settingValue = 0; - if ($('#' + setting).is(":checked")) { - settingValue = 1; - } - var data = { - WPid: $('#WPid').html(), - setting: setting, - settingValue: settingValue - } - } - - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.wordpresshomeloading = true; - $('#wordpresshomeloading').hide(); - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Successfully Updated!.', - type: 'success' - }); - if (setting === "PasswordProtection") { - location.reload(); - } - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - if (setting === "PasswordProtection") { - location.reload(); - } - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - - - }; - - $scope.GetCurrentPlugins = function () { - $('#wordpresshomeloading').show(); - - $scope.wordpresshomeloading = false; - - var url = "/websites/GetCurrentPlugins"; - - var data = { - WPid: $('#WPid').html(), - } - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - wordpresshomeloading = true; - $('#wordpresshomeloading').hide(); - - if (response.data.status === 1) { - $('#PluginBody').html(''); - var plugins = JSON.parse(response.data.plugins); - plugins.forEach(AddPlugins); - - } else { - alert("Error:" + response.data.error_message) - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - }; - - $scope.GetCurrentThemes = function () { - $('#wordpresshomeloading').show(); - - $scope.wordpresshomeloading = false; - - var url = "/websites/GetCurrentThemes"; - - var data = { - WPid: $('#WPid').html(), - } - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - wordpresshomeloading = true; - $('#wordpresshomeloading').hide(); - - if (response.data.status === 1) { - - $('#ThemeBody').html(''); - var themes = JSON.parse(response.data.themes); - themes.forEach(AddThemes); - - } else { - alert("Error:" + response.data.error_message) - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - }; - - $scope.UpdatePlugins = function (plugin) { - $('#wordpresshomeloading').show(); - var data = { - plugin: plugin, - pluginarray: PluginsList, - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/UpdatePlugins"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Updating Plugins in Background!.', - type: 'success' - }); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - - - }; - - $scope.DeletePlugins = function (plugin) { - $('#wordpresshomeloading').show(); - var data = { - plugin: plugin, - pluginarray: PluginsList, - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/DeletePlugins"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Deleting Plugin in Background!', - type: 'success' - }); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - - } - - $scope.ChangeStatus = function (plugin) { - $('#wordpresshomeloading').show(); - var data = { - plugin: plugin, - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/ChangeStatus"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Changed Plugin state Successfully !.', - type: 'success' - }); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - - } - - function AddPlugins(value, index, array) { - var FinalMarkup = '' - FinalMarkup = FinalMarkup + ''; - for (let x in value) { - if (x === 'status') { - if (value[x] === 'inactive') { - FinalMarkup = FinalMarkup + '
    '; - } else { - FinalMarkup = FinalMarkup + '
    '; - } - } else if (x === 'update') { - if (value[x] === 'none') { - FinalMarkup = FinalMarkup + 'Upto Date'; - } else { - FinalMarkup = FinalMarkup + ''; - } - } else { - FinalMarkup = FinalMarkup + '' + value[x] + ""; - } - } - FinalMarkup = FinalMarkup + '' - FinalMarkup = FinalMarkup + '' - var temp = $compile(FinalMarkup)($scope) - AppendToTable('#PluginBody', temp) - } - - $scope.UpdateThemes = function (theme) { - $('#wordpresshomeloading').show(); - var data = { - Theme: theme, - Themearray: ThemesList, - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/UpdateThemes"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Updating Theme in background !.', - type: 'success' - }); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - - - }; - - $scope.DeleteThemes = function (theme) { - $('#wordpresshomeloading').show(); - var data = { - Theme: theme, - Themearray: ThemesList, - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/DeleteThemes"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Deleting Theme in Background!.', - type: 'success' - }); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - }; - - $scope.ChangeStatusThemes = function (theme) { - $('#wordpresshomeloading').show(); - var data = { - theme: theme, - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/StatusThemes"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Change Theme state in Bsckground!.', - type: 'success' - }); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - - }; - - function AddThemes(value, index, array) { - var FinalMarkup = '' - FinalMarkup = FinalMarkup + ''; - for (let x in value) { - if (x === 'status') { - if (value[x] === 'inactive') { - FinalMarkup = FinalMarkup + '
    '; - } else { - FinalMarkup = FinalMarkup + '
    '; - } - } else if (x === 'update') { - if (value[x] === 'none') { - FinalMarkup = FinalMarkup + 'Upto Date'; - } else { - FinalMarkup = FinalMarkup + ''; - } - } else { - FinalMarkup = FinalMarkup + '' + value[x] + ""; - } - } - FinalMarkup = FinalMarkup + '' - FinalMarkup = FinalMarkup + '' - var temp = $compile(FinalMarkup)($scope) - AppendToTable('#ThemeBody', temp) - } - - $scope.CreateStagingNow = function () { - $('#wordpresshomeloading').show(); - - $scope.wordpresshomeloading = false; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - - - $scope.currentStatus = "Starting creation Staging.."; - - //here enter domain name - if (create_staging_domain_check == 0) { - var Part2_domainNameCreate = document.getElementById('Part2_domainNameCreate').value; - var domainNameCreate = document.getElementById('TestDomainNameCreate').value + Part2_domainNameCreate; - } - if (create_staging_domain_check == 1) { - - var domainNameCreate = $scope.own_domainNameCreate; - } - var data = { - StagingName: $('#stagingName').val(), - StagingDomain: domainNameCreate, - WPid: $('#WPid').html(), - } - var url = "/websites/CreateStagingNow"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - if (response.data.status === 1) { - statusFile = response.data.tempStatusPath; - getCreationStatus(); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - }; - - function getCreationStatus() { - $('#wordpresshomeloading').show(); - - url = "/websites/installWordpressStatus"; - - var data = { - statusFile: statusFile - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - //$('#wordpresshomeloading').hide(); - - if (response.data.abort === 1) { - if (response.data.installStatus === 1) { - - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = false; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - - $("#installProgress").css("width", "100%"); - $("#installProgressbackup").css("width", "100%"); - $scope.installPercentage = "100"; - $scope.currentStatus = response.data.currentStatus; - $timeout.cancel(); - - - } else { - - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = false; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $scope.errorMessage = response.data.error_message; - - $("#installProgress").css("width", "0%"); - $("#installProgressbackup").css("width", "0%"); - $scope.installPercentage = "0"; - $scope.goBackDisable = false; - - - } - - } else { - - $("#installProgress").css("width", response.data.installationProgress + "%"); - $("#installProgressbackup").css("width", response.data.installationProgress + "%"); - $scope.installPercentage = response.data.installationProgress; - $scope.currentStatus = response.data.currentStatus; - $timeout(getCreationStatus, 1000); - - } - - } - - function cantLoadInitialDatas(response) { - //$('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - } - - $scope.goBack = function () { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - $("#installProgress").css("width", "0%"); - }; - - $scope.fetchstaging = function () { - - $('#wordpresshomeloading').show(); - $scope.wordpresshomeloading = false; - - var url = "/websites/fetchstaging"; - - var data = { - WPid: $('#WPid').html(), - } - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - wordpresshomeloading = true; - $('#wordpresshomeloading').hide(); - - if (response.data.status === 1) { - - // $('#ThemeBody').html(''); - // var themes = JSON.parse(response.data.themes); - // themes.forEach(AddThemes); - - $('#StagingBody').html(''); - var staging = JSON.parse(response.data.wpsites); - staging.forEach(AddStagings); - - } else { - alert("Error data.error_message:" + response.data.error_message) - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - alert("Error" + response) - - } - - }; - - $scope.fetchDatabase = function () { - - $('#wordpresshomeloading').show(); - $scope.wordpresshomeloading = false; - - var url = "/websites/fetchDatabase"; - - var data = { - WPid: $('#WPid').html(), - } - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - wordpresshomeloading = true; - $('#wordpresshomeloading').hide(); - - if (response.data.status === 1) { - $('#DB_Name').html(response.data.DataBaseName); - $('#DB_User').html(response.data.DataBaseUser); - $('#tableprefix').html(response.data.tableprefix); - } else { - alert("Error data.error_message:" + response.data.error_message) - - } - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - alert("Error" + response) - - } - - }; - - $scope.SaveUpdateConfig = function () { - $('#wordpresshomeloading').show(); - var data = { - AutomaticUpdates: $('#AutomaticUpdates').find(":selected").text(), - Plugins: $('#Plugins').find(":selected").text(), - Themes: $('#Themes').find(":selected").text(), - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/SaveUpdateConfig"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Update Configurations Sucessfully!.', - type: 'success' - }); - $("#autoUpdateConfig").modal('hide'); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - new PNotify({ - title: 'Operation Failed!', - text: response, - type: 'error' - }); - - } - }; - - function AddStagings(value, index, array) { - var FinalMarkup = '' - for (let x in value) { - if (x === 'name') { - FinalMarkup = FinalMarkup + '' + value[x] + ''; - } else if (x !== 'url' && x !== 'deleteURL' && x !== 'id') { - FinalMarkup = FinalMarkup + '' + value[x] + ""; - } - } - FinalMarkup = FinalMarkup + '' + - ' ' - FinalMarkup = FinalMarkup + '' - AppendToTable('#StagingBody', FinalMarkup); - } - - $scope.FinalDeployToProduction = function () { - - $('#wordpresshomeloading').show(); - - $scope.wordpresshomeloading = false; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - - var data = { - WPid: $('#WPid').html(), - StagingID: DeploytoProductionID - } - - var url = "/websites/DeploytoProduction"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - function ListInitialDatas(response) { - - $('#wordpresshomeloading').hide(); - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Deploy To Production start!.', - type: 'success' - }); - statusFile = response.data.tempStatusPath; - getCreationStatus(); - - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - new PNotify({ - title: 'Operation Failed!', - text: response, - type: 'error' - }); - - } - - }; - - - $scope.CreateBackup = function () { - $('#wordpresshomeloading').show(); - - $scope.wordpresshomeloading = false; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - $scope.currentStatus = "Starting creation Backups.."; - var data = { - WPid: $('#WPid').html(), - Backuptype: $('#backuptype').val() - } - var url = "/websites/WPCreateBackup"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $('createbackupbutton').hide(); - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Creating Backups!.', - type: 'success' - }); - statusFile = response.data.tempStatusPath; - getCreationStatus(); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - alert(response) - - } - - }; - - - $scope.installwpcore = function () { - - $('#wordpresshomeloading').show(); - $('#wordpresshomeloadingsec').show(); - var data = { - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/installwpcore"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $('#wordpresshomeloadingsec').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Results fetched..', - type: 'success' - }); - $('#SecurityResult').html(response.data.result); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $('#wordpresshomeloadingsec').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - - }; - - $scope.dataintegrity = function () { - - $('#wordpresshomeloading').show(); - $('#wordpresshomeloadingsec').show(); - var data = { - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/dataintegrity"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $('#wordpresshomeloadingsec').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Results fetched', - type: 'success' - }); - $('#SecurityResult').html(response.data.result); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $('#wordpresshomeloadingsec').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - }; - -}); - - -var PluginsList = []; - - -function AddPluginToArray(cBox, name) { - if (cBox.checked) { - PluginsList.push(name); - // alert(PluginsList); - } else { - const index = PluginsList.indexOf(name); - if (index > -1) { - PluginsList.splice(index, 1); - } - // alert(PluginsList); - } -} - -var ThemesList = []; - -function AddThemeToArray(cBox, name) { - if (cBox.checked) { - ThemesList.push(name); - // alert(ThemesList); - } else { - const index = ThemesList.indexOf(name); - if (index > -1) { - ThemesList.splice(index, 1); - } - // alert(ThemesList); - } -} - - -function AppendToTable(table, markup) { - $(table).append(markup); -} - - -//..................Restore Backup Home - - -app.controller('RestoreWPBackup', function ($scope, $http, $timeout, $window) { - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - - - $scope.checkmethode = function () { - var val = $('#RestoreMethode').children("option:selected").val(); - if (val == 1) { - $('#Newsitediv').show(); - $('#exinstingsitediv').hide(); - } else if (val == 0) { - $('#exinstingsitediv').show(); - $('#Newsitediv').hide(); - } else { - - } - }; - - - $scope.RestoreWPbackupNow = function () { - $('#wordpresshomeloading').show(); - $scope.wordpresshomeloading = false; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - $scope.currentStatus = "Start Restoring WordPress.."; - - var Domain = $('#wprestoresubdirdomain').val() - var path = $('#wprestoresubdirpath').val(); - var home = "1"; - - if (typeof path != 'undefined' || path != '') { - home = "0"; - } - if (typeof path == 'undefined') { - path = ""; - } - - - var backuptype = $('#backuptype').html(); - var data; - if (backuptype == "DataBase Backup") { - data = { - backupid: $('#backupid').html(), - DesSite: $('#DesSite').children("option:selected").val(), - Domain: '', - path: path, - home: home, - } - } else { - data = { - backupid: $('#backupid').html(), - DesSite: $('#DesSite').children("option:selected").val(), - Domain: Domain, - path: path, - home: home, - } - - } - - var url = "/websites/RestoreWPbackupNow"; - - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - // console.log(data) - - var d = $('#DesSite').children("option:selected").val(); - var c = $("input[name=Newdomain]").val(); - // if (d == -1 || c == "") { - // alert("Please Select Method of Backup Restore"); - // } else { - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - // } - - - function ListInitialDatas(response) { - wordpresshomeloading = true; - $('#wordpresshomeloading').hide(); - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Restoring process starts!.', - type: 'success' - }); - statusFile = response.data.tempStatusPath; - getCreationStatus(); - - } else { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = false; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $scope.errorMessage = response.data.error_message; - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - - } - } - - function getCreationStatus() { - $('#wordpresshomeloading').show(); - - url = "/websites/installWordpressStatus"; - - var data = { - statusFile: statusFile - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - //$('#wordpresshomeloading').hide(); - - if (response.data.abort === 1) { - - if (response.data.installStatus === 1) { - - - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = false; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - - $("#installProgress").css("width", "100%"); - $("#installProgressbackup").css("width", "100%"); - $scope.installPercentage = "100"; - $scope.currentStatus = response.data.currentStatus; - $timeout.cancel(); - - - } else { - - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = false; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $scope.errorMessage = response.data.error_message; - - $("#installProgress").css("width", "0%"); - $("#installProgressbackup").css("width", "0%"); - $scope.installPercentage = "0"; - $scope.goBackDisable = false; - - - } - - } else { - - $("#installProgress").css("width", response.data.installationProgress + "%"); - $("#installProgressbackup").css("width", response.data.installationProgress + "%"); - $scope.installPercentage = response.data.installationProgress; - $scope.currentStatus = response.data.currentStatus; - $timeout(getCreationStatus, 1000); - - } - - } - - function cantLoadInitialDatas(response) { - //$('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - } - - $scope.goBack = function () { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - $("#installProgress").css("width", "0%"); - }; -}); - - -//.......................................Remote Backup - -//........... delete DeleteBackupConfigNow - -function DeleteBackupConfigNow(url) { - window.location.href = url; -} - -function DeleteRemoteBackupsiteNow(url) { - window.location.href = url; -} - -function DeleteBackupfileConfigNow(url) { - window.location.href = url; -} - - -app.controller('RemoteBackupConfig', function ($scope, $http, $timeout, $window) { - $scope.RemoteBackupLoading = true; - $scope.SFTPBackUpdiv = true; - - $scope.EndpointURLdiv = true; - $scope.Selectprovider = true; - $scope.S3keyNamediv = true; - $scope.Accesskeydiv = true; - $scope.SecretKeydiv = true; - $scope.SelectRemoteBackuptype = function () { - var val = $scope.RemoteBackuptype; - if (val == "SFTP") { - $scope.SFTPBackUpdiv = false; - $scope.EndpointURLdiv = true; - $scope.Selectprovider = true; - $scope.S3keyNamediv = true; - $scope.Accesskeydiv = true; - $scope.SecretKeydiv = true; - } else if (val == "S3") { - $scope.EndpointURLdiv = true; - $scope.Selectprovider = false; - $scope.S3keyNamediv = false; - $scope.Accesskeydiv = false; - $scope.SecretKeydiv = false; - $scope.SFTPBackUpdiv = true; - } else { - $scope.RemoteBackupLoading = true; - $scope.SFTPBackUpdiv = true; - - $scope.EndpointURLdiv = true; - $scope.Selectprovider = true; - $scope.S3keyNamediv = true; - $scope.Accesskeydiv = true; - $scope.SecretKeydiv = true; - } - } - - $scope.SelectProvidertype = function () { - $scope.EndpointURLdiv = true; - var provider = $scope.Providervalue - if (provider == 'Backblaze') { - $scope.EndpointURLdiv = false; - } else { - $scope.EndpointURLdiv = true; - } - } - - $scope.SaveBackupConfig = function () { - $scope.RemoteBackupLoading = false; - var Hname = $scope.Hostname; - var Uname = $scope.Username; - var Passwd = $scope.Password; - var path = $scope.path; - var type = $scope.RemoteBackuptype; - var Providervalue = $scope.Providervalue; - var data; - if (type == "SFTP") { - - data = { - Hname: Hname, - Uname: Uname, - Passwd: Passwd, - path: path, - type: type - } - } else if (type == "S3") { - if (Providervalue == "Backblaze") { - data = { - S3keyname: $scope.S3keyName, - Provider: Providervalue, - AccessKey: $scope.Accesskey, - SecertKey: $scope.SecretKey, - EndUrl: $scope.EndpointURL, - type: type - } - } else { - data = { - S3keyname: $scope.S3keyName, - Provider: Providervalue, - AccessKey: $scope.Accesskey, - SecertKey: $scope.SecretKey, - type: type - } - - } - - } - var url = "/websites/SaveBackupConfig"; - - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.RemoteBackupLoading = true; - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Successfully Saved!.', - type: 'success' - }); - location.reload(); - - - } else { - new PNotify({ - title: 'Error!', - text: response.data.error_message, - type: 'error' - }); - } - } - - function cantLoadInitialDatas(response) { - $scope.RemoteBackupLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - - } - - - } - -}); - -var UpdatescheduleID; -app.controller('BackupSchedule', function ($scope, $http, $timeout, $window) { - $scope.BackupScheduleLoading = true; - $scope.SaveBackupSchedule = function () { - $scope.RemoteBackupLoading = false; - var FileRetention = $scope.Fretention; - var Backfrequency = $scope.Bfrequency; - - - var data = { - FileRetention: FileRetention, - Backfrequency: Backfrequency, - ScheduleName: $scope.ScheduleName, - RemoteConfigID: $('#RemoteConfigID').html(), - BackupType: $scope.BackupType - } - var url = "/websites/SaveBackupSchedule"; - - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.RemoteBackupLoading = true; - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Successfully Saved!.', - type: 'success' - }); - location.reload(); - - - } else { - new PNotify({ - title: 'Error!', - text: response.data.error_message, - type: 'error' - }); - } - } - - function cantLoadInitialDatas(response) { - $scope.RemoteBackupLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - - } - - - }; - - - $scope.getupdateid = function (ID) { - UpdatescheduleID = ID; - } - - $scope.UpdateRemoteschedules = function () { - $scope.RemoteBackupLoading = false; - var Frequency = $scope.RemoteFrequency; - var fretention = $scope.RemoteFileretention; - - var data = { - ScheduleID: UpdatescheduleID, - Frequency: Frequency, - FileRetention: fretention - } - var url = "/websites/UpdateRemoteschedules"; - - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.RemoteBackupLoading = true; - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Successfully Updated!.', - type: 'success' - }); - location.reload(); - - - } else { - new PNotify({ - title: 'Error!', - text: response.data.error_message, - type: 'error' - }); - } - } - - function cantLoadInitialDatas(response) { - $scope.RemoteBackupLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - - } - }; - - $scope.AddWPsiteforRemoteBackup = function () { - $scope.RemoteBackupLoading = false; - - - var data = { - WpsiteID: $('#Wpsite').val(), - RemoteScheduleID: $('#RemoteScheduleID').html() - } - var url = "/websites/AddWPsiteforRemoteBackup"; - - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.RemoteBackupLoading = true; - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Successfully Saved!.', - type: 'success' - }); - location.reload(); - - - } else { - new PNotify({ - title: 'Error!', - text: response.data.error_message, - type: 'error' - }); - } - } - - function cantLoadInitialDatas(response) { - $scope.RemoteBackupLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - - } - - - }; -}); -/* Java script code to create account */ - -var website_create_domain_check = 0; - -function website_create_checkbox_function() { - - var checkBox = document.getElementById("myCheck"); - // Get the output text - - - // If the checkbox is checked, display the output text - if (checkBox.checked == true) { - website_create_domain_check = 0; - document.getElementById('Website_Create_Test_Domain').style.display = "block"; - document.getElementById('Website_Create_Own_Domain').style.display = "none"; - - } else { - document.getElementById('Website_Create_Test_Domain').style.display = "none"; - document.getElementById('Website_Create_Own_Domain').style.display = "block"; - website_create_domain_check = 1; - } - - // alert(domain_check); -} - -app.controller('createWebsite', function ($scope, $http, $timeout, $window) { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - - var statusFile; - - $scope.createWebsite = function () { - - $scope.webSiteCreationLoading = false; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - - $scope.currentStatus = "Starting creation.."; - - var ssl, dkimCheck, openBasedir, mailDomain, apacheBackend; - - if ($scope.sslCheck === true) { - ssl = 1; - } else { - ssl = 0 - } - - if ($scope.apacheBackend === true) { - apacheBackend = 1; - } else { - apacheBackend = 0 - } - - if ($scope.dkimCheck === true) { - dkimCheck = 1; - } else { - dkimCheck = 0 - } - - if ($scope.openBasedir === true) { - openBasedir = 1; - } else { - openBasedir = 0 - } - - if ($scope.mailDomain === true) { - mailDomain = 1; - } else { - mailDomain = 0 - } - - - url = "/websites/submitWebsiteCreation"; - - var package = $scope.packageForWebsite; - - // if (website_create_domain_check == 0) { - // var Part2_domainNameCreate = document.getElementById('Part2_domainNameCreate').value; - // var domainName = document.getElementById('TestDomainNameCreate').value + Part2_domainNameCreate; - // } - // if (website_create_domain_check == 1) { - // - // var domainName = $scope.domainNameCreate; - // } - var domainName = $scope.domainNameCreate; - - // var domainName = $scope.domainNameCreate; - - var adminEmail = $scope.adminEmail; - var phpSelection = $scope.phpSelection; - var websiteOwner = $scope.websiteOwner; - - - var data = { - package: package, - domainName: domainName, - adminEmail: adminEmail, - phpSelection: phpSelection, - ssl: ssl, - websiteOwner: websiteOwner, - dkimCheck: dkimCheck, - openBasedir: openBasedir, - mailDomain: mailDomain, - apacheBackend: apacheBackend - }; - - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.createWebSiteStatus === 1) { - statusFile = response.data.tempStatusPath; - getCreationStatus(); - } else { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = false; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $scope.errorMessage = response.data.error_message; - } - - - } - - function cantLoadInitialDatas(response) { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - }; - $scope.goBack = function () { - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - $("#installProgress").css("width", "0%"); - }; - - function getCreationStatus() { - - url = "/websites/installWordpressStatus"; - - var data = { - statusFile: statusFile - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - - if (response.data.abort === 1) { - - if (response.data.installStatus === 1) { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = false; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $("#installProgress").css("width", "100%"); - $scope.installPercentage = "100"; - $scope.currentStatus = response.data.currentStatus; - $timeout.cancel(); - - } else { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = false; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $scope.errorMessage = response.data.error_message; - - $("#installProgress").css("width", "0%"); - $scope.installPercentage = "0"; - $scope.goBackDisable = false; - - } - - } else { - $("#installProgress").css("width", response.data.installationProgress + "%"); - $scope.installPercentage = response.data.installationProgress; - $scope.currentStatus = response.data.currentStatus; - $timeout(getCreationStatus, 1000); - } - - } - - function cantLoadInitialDatas(response) { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - } - -}); -/* Java script code to create account ends here */ - -/* Java script code to list accounts */ - -$("#listFail").hide(); - - app.controller('listWebsites', function ($scope, $http, $window) { $scope.web = {}; $scope.WebSitesList = []; @@ -8289,6 +3372,3379 @@ app.controller('deleteWebsiteControl', function ($scope, $http) { }); +/** + * Created by usman on 7/26/17. + */ +function getCookie(name) { + var cookieValue = null; + var t = document.cookie; + if (document.cookie && document.cookie !== '') { + var cookies = document.cookie.split(';'); + for (var i = 0; i < cookies.length; i++) { + var cookie = jQuery.trim(cookies[i]); + // Does this cookie string begin with the name we want? + if (cookie.substring(0, name.length + 1) === (name + '=')) { + cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); + break; + } + } + } + return cookieValue; +} + + +var arry = [] + +function selectpluginJs(val) { + $('#mysearch').hide() + arry.push(val) + + // console.log(arry) + document.getElementById('selJS').innerHTML = ""; + + for (var i = 0; i < arry.length; i++) { + $('#selJS').show() + var mlm = ' ' + arry[i] + '    ' + $('#selJS').append(mlm) + } + + +} + + +var DeletePluginURL; + +function DeletePluginBuucket(url) { + DeletePluginURL = url; +} + +function FinalDeletePluginBuucket() { + window.location.href = DeletePluginURL; +} + +var SPVal; + +app.controller('WPAddNewPlugin', function ($scope, $http, $timeout, $window, $compile) { + $scope.webSiteCreationLoading = true; + + $scope.SearchPluginName = function (val) { + $scope.webSiteCreationLoading = false; + SPVal = val; + url = "/websites/SearchOnkeyupPlugin"; + + var searchcontent = $scope.searchcontent; + + + var data = { + pluginname: searchcontent + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.webSiteCreationLoading = true; + + if (response.data.status === 1) { + if (SPVal == 'add') { + $('#mysearch').show() + document.getElementById('mysearch').innerHTML = ""; + var res = response.data.plugns.plugins + // console.log(res); + for (i = 0; i <= res.length; i++) { + // + var tml = '
    '; + $('#mysearch').append(tml); + } + } else if (SPVal == 'eidt') { + $('#mysearch').show() + document.getElementById('mysearch').innerHTML = ""; + var res = response.data.plugns.plugins + // console.log(res); + for (i = 0; i <= res.length; i++) { + // + var tml = '
    '; + var temp = $compile(tml)($scope) + angular.element(document.getElementById('mysearch')).append(temp); + } + + } + + + } else { + + // $scope.errorMessage = response.data.error_message; + alert("Status not = 1: Error..." + response.data.error_message) + } + + + } + + function cantLoadInitialDatas(response) { + + alert("Error..." + response) + + } + } + + $scope.AddNewplugin = function () { + + url = "/websites/AddNewpluginAjax"; + + var bucketname = $scope.PluginbucketName + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + var data = { + config: arry, + Name: bucketname + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + function ListInitialDatas(response) { + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Bucket created.', + type: 'success' + }); + location.reload(); + } else { + + new PNotify({ + title: 'Error!', + text: response.data.error_message, + type: 'error' + }); + } + + + } + + function cantLoadInitialDatas(response) { + + alert("Error..." + response) + + } + } + + $scope.deletesPlgin = function (val) { + + url = "/websites/deletesPlgin"; + + + var data = { + pluginname: val, + pluginbBucketID: $('#pluginbID').html() + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.status === 1) { + location.reload(); + + } else { + + // $scope.errorMessage = response.data.error_message; + alert("Status not = 1: Error..." + response.data.error_message) + } + + + } + + function cantLoadInitialDatas(response) { + + alert("Error..." + response) + + } + + } + + $scope.Addplugin = function (slug) { + $('#mysearch').hide() + + url = "/websites/Addplugineidt"; + + + var data = { + pluginname: slug, + pluginbBucketID: $('#pluginbID').html() + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.status === 1) { + location.reload(); + + } else { + + // $scope.errorMessage = response.data.error_message; + alert("Status not = 1: Error..." + response.data.error_message) + } + + + } + + function cantLoadInitialDatas(response) { + + alert("Error..." + response) + + } + + + } + +}); + +var domain_check = 0; + +function checkbox_function() { + + var checkBox = document.getElementById("myCheck"); + // Get the output text + + + // If the checkbox is checked, display the output text + if (checkBox.checked == true) { + domain_check = 0; + document.getElementById('Test_Domain').style.display = "block"; + document.getElementById('Own_Domain').style.display = "none"; + + } else { + document.getElementById('Test_Domain').style.display = "none"; + document.getElementById('Own_Domain').style.display = "block"; + domain_check = 1; + } + + // alert(domain_check); +} + +app.controller('createWordpress', function ($scope, $http, $timeout, $compile, $window) { + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = false; + $scope.installationProgress = true; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + + + var statusFile; + + $scope.createWordPresssite = function () { + + $scope.webSiteCreationLoading = false; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + + + $scope.currentStatus = "Starting creation.."; + + var apacheBackend = 0; + + if ($scope.apacheBackend === true) { + apacheBackend = 1; + } else { + apacheBackend = 0 + } + + var package = $scope.packageForWebsite; + var websiteOwner = $scope.websiteOwner; + var WPtitle = $scope.WPtitle; + + // if (domain_check == 0) { + // var Part2_domainNameCreate = document.getElementById('Part2_domainNameCreate').value; + // var domainNameCreate = document.getElementById('TestDomainNameCreate').value + Part2_domainNameCreate; + // } + // if (domain_check == 1) { + // + // var domainNameCreate = $scope.own_domainNameCreate; + // } + + var domainNameCreate = $scope.domainNameCreate; + + + var WPUsername = $scope.WPUsername; + var adminEmail = $scope.adminEmail; + var WPPassword = $scope.WPPassword; + var WPVersions = $scope.WPVersions; + var pluginbucket = $scope.pluginbucket; + var autoupdates = $scope.autoupdates; + var pluginupdates = $scope.pluginupdates; + var themeupdates = $scope.themeupdates; + + if (domain_check == 0) { + + var path = ""; + + } + if (domain_check = 1) { + + var path = $scope.installPath; + + } + + + var home = "1"; + + if (typeof path != 'undefined') { + home = "0"; + } + + //alert(domainNameCreate); + var data = { + + title: WPtitle, + domain: domainNameCreate, + WPVersion: WPVersions, + pluginbucket: pluginbucket, + adminUser: WPUsername, + Email: adminEmail, + PasswordByPass: WPPassword, + AutomaticUpdates: autoupdates, + Plugins: pluginupdates, + Themes: themeupdates, + websiteOwner: websiteOwner, + package: package, + home: home, + path: path, + apacheBackend: apacheBackend + } + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + var url = "/websites/submitWorpressCreation"; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.webSiteCreationLoading = true; + if (response.data.status === 1) { + statusFile = response.data.tempStatusPath; + getCreationStatus(); + + } else { + $scope.goBackDisable = false; + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + + } + + function cantLoadInitialDatas(response) { + + alert("Error..." + response) + + } + + }; + $scope.goBack = function () { + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = false; + $scope.installationProgress = true; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + $("#installProgress").css("width", "0%"); + }; + + function getCreationStatus() { + + url = "/websites/installWordpressStatus"; + + var data = { + statusFile: statusFile + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.abort === 1) { + + if (response.data.installStatus === 1) { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = false; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $("#installProgress").css("width", "100%"); + $scope.installPercentage = "100"; + $scope.currentStatus = response.data.currentStatus; + $timeout.cancel(); + + } else { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = false; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $scope.errorMessage = response.data.error_message; + + $("#installProgress").css("width", "0%"); + $scope.installPercentage = "0"; + $scope.goBackDisable = false; + + } + + } else { + $scope.webSiteCreationLoading = false; + $("#installProgress").css("width", response.data.installationProgress + "%"); + $scope.installPercentage = response.data.installationProgress; + $scope.currentStatus = response.data.currentStatus; + $timeout(getCreationStatus, 1000); + } + + } + + function cantLoadInitialDatas(response) { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = false; + $scope.goBackDisable = false; + + } + + + } + + +}); + + +//........... delete wp list +var FurlDeleteWP; + +function DeleteWPNow(url) { + FurlDeleteWP = url; +} + +function FinalDeleteWPNow() { + window.location.href = FurlDeleteWP; +} + +var DeploytoProductionID; + +function DeployToProductionInitial(vall) { + DeploytoProductionID = vall; +} + +var create_staging_domain_check = 0; + +function create_staging_checkbox_function() { + + try { + + var checkBox = document.getElementById("Create_Staging_Check"); + // Get the output text + + + // If the checkbox is checked, display the output text + if (checkBox.checked == true) { + create_staging_domain_check = 0; + document.getElementById('Website_Create_Test_Domain').style.display = "block"; + document.getElementById('Website_Create_Own_Domain').style.display = "none"; + + } else { + document.getElementById('Website_Create_Test_Domain').style.display = "none"; + document.getElementById('Website_Create_Own_Domain').style.display = "block"; + create_staging_domain_check = 1; + } + } catch (e) { + + } + + // alert(domain_check); +} + +create_staging_checkbox_function(); + +app.controller('WPsiteHome', function ($scope, $http, $timeout, $compile, $window) { + + var CheckBoxpasssword = 0; + + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = false; + $scope.installationProgress = true; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + $(document).ready(function () { + var checkstatus = document.getElementById("wordpresshome"); + if (checkstatus !== null) { + $scope.LoadWPdata(); + + } + }); + + + $scope.LoadWPdata = function () { + + $scope.wordpresshomeloading = false; + $('#wordpresshomeloading').show(); + + var url = "/websites/FetchWPdata"; + + var data = { + WPid: $('#WPid').html(), + } + + console.log(data); + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + wordpresshomeloading = true; + $('#wordpresshomeloading').hide(); + + if (response.data.status === 1) { + $('#WPVersion').text(response.data.ret_data.version); + if (response.data.ret_data.lscache === 1) { + $('#lscache').prop('checked', true); + } + if (response.data.ret_data.debugging === 1) { + $('#debugging').prop('checked', true); + } + if (response.data.ret_data.searchIndex === 1) { + $('#searchIndex').prop('checked', true); + } + if (response.data.ret_data.maintenanceMode === 1) { + $('#maintenanceMode').prop('checked', true); + } + if (response.data.ret_data.wpcron === 1) { + $('#wpcron').prop('checked', true); + } + if (response.data.ret_data.passwordprotection == 1) { + + var dc = '\n' + + ' ' + var mp = $compile(dc)($scope); + angular.element(document.getElementById('prsswdprodata')).append(mp); + CheckBoxpasssword = 1; + } else if (response.data.ret_data.passwordprotection == 0) { + var dc = '\n' + + ' ' + $('#prsswdprodata').append(dc); + CheckBoxpasssword = 0; + } + + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = false; + $scope.goBackDisable = false; + + } + + + }; + + $scope.UpdateWPSettings = function (setting) { + + $scope.wordpresshomeloading = false; + $('#wordpresshomeloading').show(); + + + var url = "/websites/UpdateWPSettings"; + + if (setting === "PasswordProtection") { + if (CheckBoxpasssword == 0) { + var data = { + WPid: $('#WPid').html(), + setting: setting, + PPUsername: $scope.PPUsername, + PPPassword: $scope.PPPassword, + } + + } else { + var data = { + WPid: $('#WPid').html(), + setting: setting, + PPUsername: '', + PPPassword: '', + } + + } + + } else { + var settingValue = 0; + if ($('#' + setting).is(":checked")) { + settingValue = 1; + } + var data = { + WPid: $('#WPid').html(), + setting: setting, + settingValue: settingValue + } + } + + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.wordpresshomeloading = true; + $('#wordpresshomeloading').hide(); + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Successfully Updated!.', + type: 'success' + }); + if (setting === "PasswordProtection") { + location.reload(); + } + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + if (setting === "PasswordProtection") { + location.reload(); + } + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + + + }; + + $scope.GetCurrentPlugins = function () { + $('#wordpresshomeloading').show(); + + $scope.wordpresshomeloading = false; + + var url = "/websites/GetCurrentPlugins"; + + var data = { + WPid: $('#WPid').html(), + } + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + wordpresshomeloading = true; + $('#wordpresshomeloading').hide(); + + if (response.data.status === 1) { + $('#PluginBody').html(''); + var plugins = JSON.parse(response.data.plugins); + plugins.forEach(AddPlugins); + + } else { + alert("Error:" + response.data.error_message) + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = false; + $scope.goBackDisable = false; + + } + + + }; + + $scope.GetCurrentThemes = function () { + $('#wordpresshomeloading').show(); + + $scope.wordpresshomeloading = false; + + var url = "/websites/GetCurrentThemes"; + + var data = { + WPid: $('#WPid').html(), + } + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + wordpresshomeloading = true; + $('#wordpresshomeloading').hide(); + + if (response.data.status === 1) { + + $('#ThemeBody').html(''); + var themes = JSON.parse(response.data.themes); + themes.forEach(AddThemes); + + } else { + alert("Error:" + response.data.error_message) + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = false; + $scope.goBackDisable = false; + + } + + + }; + + $scope.UpdatePlugins = function (plugin) { + $('#wordpresshomeloading').show(); + var data = { + plugin: plugin, + pluginarray: PluginsList, + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/UpdatePlugins"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Updating Plugins in Background!.', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + + + }; + + $scope.DeletePlugins = function (plugin) { + $('#wordpresshomeloading').show(); + var data = { + plugin: plugin, + pluginarray: PluginsList, + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/DeletePlugins"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Deleting Plugin in Background!', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + + } + + $scope.ChangeStatus = function (plugin) { + $('#wordpresshomeloading').show(); + var data = { + plugin: plugin, + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/ChangeStatus"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Changed Plugin state Successfully !.', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + + } + + function AddPlugins(value, index, array) { + var FinalMarkup = '' + FinalMarkup = FinalMarkup + ''; + for (let x in value) { + if (x === 'status') { + if (value[x] === 'inactive') { + FinalMarkup = FinalMarkup + '
    '; + } else { + FinalMarkup = FinalMarkup + '
    '; + } + } else if (x === 'update') { + if (value[x] === 'none') { + FinalMarkup = FinalMarkup + 'Upto Date'; + } else { + FinalMarkup = FinalMarkup + ''; + } + } else { + FinalMarkup = FinalMarkup + '' + value[x] + ""; + } + } + FinalMarkup = FinalMarkup + '' + FinalMarkup = FinalMarkup + '' + var temp = $compile(FinalMarkup)($scope) + AppendToTable('#PluginBody', temp) + } + + $scope.UpdateThemes = function (theme) { + $('#wordpresshomeloading').show(); + var data = { + Theme: theme, + Themearray: ThemesList, + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/UpdateThemes"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Updating Theme in background !.', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + + + }; + + $scope.DeleteThemes = function (theme) { + $('#wordpresshomeloading').show(); + var data = { + Theme: theme, + Themearray: ThemesList, + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/DeleteThemes"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Deleting Theme in Background!.', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + }; + + $scope.ChangeStatusThemes = function (theme) { + $('#wordpresshomeloading').show(); + var data = { + theme: theme, + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/StatusThemes"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Change Theme state in Bsckground!.', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + + }; + + function AddThemes(value, index, array) { + var FinalMarkup = '' + FinalMarkup = FinalMarkup + ''; + for (let x in value) { + if (x === 'status') { + if (value[x] === 'inactive') { + FinalMarkup = FinalMarkup + '
    '; + } else { + FinalMarkup = FinalMarkup + '
    '; + } + } else if (x === 'update') { + if (value[x] === 'none') { + FinalMarkup = FinalMarkup + 'Upto Date'; + } else { + FinalMarkup = FinalMarkup + ''; + } + } else { + FinalMarkup = FinalMarkup + '' + value[x] + ""; + } + } + FinalMarkup = FinalMarkup + '' + FinalMarkup = FinalMarkup + '' + var temp = $compile(FinalMarkup)($scope) + AppendToTable('#ThemeBody', temp) + } + + $scope.CreateStagingNow = function () { + $('#wordpresshomeloading').show(); + + $scope.wordpresshomeloading = false; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + + + $scope.currentStatus = "Starting creation Staging.."; + + //here enter domain name + if (create_staging_domain_check == 0) { + var Part2_domainNameCreate = document.getElementById('Part2_domainNameCreate').value; + var domainNameCreate = document.getElementById('TestDomainNameCreate').value + Part2_domainNameCreate; + } + if (create_staging_domain_check == 1) { + + var domainNameCreate = $scope.own_domainNameCreate; + } + var data = { + StagingName: $('#stagingName').val(), + StagingDomain: domainNameCreate, + WPid: $('#WPid').html(), + } + var url = "/websites/CreateStagingNow"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + if (response.data.status === 1) { + statusFile = response.data.tempStatusPath; + getCreationStatus(); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + }; + + function getCreationStatus() { + $('#wordpresshomeloading').show(); + + url = "/websites/installWordpressStatus"; + + var data = { + statusFile: statusFile + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + //$('#wordpresshomeloading').hide(); + + if (response.data.abort === 1) { + if (response.data.installStatus === 1) { + + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = false; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + + $("#installProgress").css("width", "100%"); + $("#installProgressbackup").css("width", "100%"); + $scope.installPercentage = "100"; + $scope.currentStatus = response.data.currentStatus; + $timeout.cancel(); + + + } else { + + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = false; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $scope.errorMessage = response.data.error_message; + + $("#installProgress").css("width", "0%"); + $("#installProgressbackup").css("width", "0%"); + $scope.installPercentage = "0"; + $scope.goBackDisable = false; + + + } + + } else { + + $("#installProgress").css("width", response.data.installationProgress + "%"); + $("#installProgressbackup").css("width", response.data.installationProgress + "%"); + $scope.installPercentage = response.data.installationProgress; + $scope.currentStatus = response.data.currentStatus; + $timeout(getCreationStatus, 1000); + + } + + } + + function cantLoadInitialDatas(response) { + //$('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = false; + $scope.goBackDisable = false; + + } + + + } + + $scope.goBack = function () { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = false; + $scope.installationProgress = true; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + $("#installProgress").css("width", "0%"); + }; + + $scope.fetchstaging = function () { + + $('#wordpresshomeloading').show(); + $scope.wordpresshomeloading = false; + + var url = "/websites/fetchstaging"; + + var data = { + WPid: $('#WPid').html(), + } + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + wordpresshomeloading = true; + $('#wordpresshomeloading').hide(); + + if (response.data.status === 1) { + + // $('#ThemeBody').html(''); + // var themes = JSON.parse(response.data.themes); + // themes.forEach(AddThemes); + + $('#StagingBody').html(''); + var staging = JSON.parse(response.data.wpsites); + staging.forEach(AddStagings); + + } else { + alert("Error data.error_message:" + response.data.error_message) + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + alert("Error" + response) + + } + + }; + + $scope.fetchDatabase = function () { + + $('#wordpresshomeloading').show(); + $scope.wordpresshomeloading = false; + + var url = "/websites/fetchDatabase"; + + var data = { + WPid: $('#WPid').html(), + } + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + wordpresshomeloading = true; + $('#wordpresshomeloading').hide(); + + if (response.data.status === 1) { + $('#DB_Name').html(response.data.DataBaseName); + $('#DB_User').html(response.data.DataBaseUser); + $('#tableprefix').html(response.data.tableprefix); + } else { + alert("Error data.error_message:" + response.data.error_message) + + } + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + alert("Error" + response) + + } + + }; + + $scope.SaveUpdateConfig = function () { + $('#wordpresshomeloading').show(); + var data = { + AutomaticUpdates: $('#AutomaticUpdates').find(":selected").text(), + Plugins: $('#Plugins').find(":selected").text(), + Themes: $('#Themes').find(":selected").text(), + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/SaveUpdateConfig"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Update Configurations Sucessfully!.', + type: 'success' + }); + $("#autoUpdateConfig").modal('hide'); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + new PNotify({ + title: 'Operation Failed!', + text: response, + type: 'error' + }); + + } + }; + + function AddStagings(value, index, array) { + var FinalMarkup = '' + for (let x in value) { + if (x === 'name') { + FinalMarkup = FinalMarkup + '' + value[x] + ''; + } else if (x !== 'url' && x !== 'deleteURL' && x !== 'id') { + FinalMarkup = FinalMarkup + '' + value[x] + ""; + } + } + FinalMarkup = FinalMarkup + '' + + ' ' + FinalMarkup = FinalMarkup + '' + AppendToTable('#StagingBody', FinalMarkup); + } + + $scope.FinalDeployToProduction = function () { + + $('#wordpresshomeloading').show(); + + $scope.wordpresshomeloading = false; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + + var data = { + WPid: $('#WPid').html(), + StagingID: DeploytoProductionID + } + + var url = "/websites/DeploytoProduction"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + function ListInitialDatas(response) { + + $('#wordpresshomeloading').hide(); + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Deploy To Production start!.', + type: 'success' + }); + statusFile = response.data.tempStatusPath; + getCreationStatus(); + + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + new PNotify({ + title: 'Operation Failed!', + text: response, + type: 'error' + }); + + } + + }; + + + $scope.CreateBackup = function () { + $('#wordpresshomeloading').show(); + + $scope.wordpresshomeloading = false; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + $scope.currentStatus = "Starting creation Backups.."; + var data = { + WPid: $('#WPid').html(), + Backuptype: $('#backuptype').val() + } + var url = "/websites/WPCreateBackup"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $('createbackupbutton').hide(); + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Creating Backups!.', + type: 'success' + }); + statusFile = response.data.tempStatusPath; + getCreationStatus(); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + alert(response) + + } + + }; + + + $scope.installwpcore = function () { + + $('#wordpresshomeloading').show(); + $('#wordpresshomeloadingsec').show(); + var data = { + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/installwpcore"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $('#wordpresshomeloadingsec').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Results fetched..', + type: 'success' + }); + $('#SecurityResult').html(response.data.result); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $('#wordpresshomeloadingsec').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + + }; + + $scope.dataintegrity = function () { + + $('#wordpresshomeloading').show(); + $('#wordpresshomeloadingsec').show(); + var data = { + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/dataintegrity"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $('#wordpresshomeloadingsec').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Results fetched', + type: 'success' + }); + $('#SecurityResult').html(response.data.result); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $('#wordpresshomeloadingsec').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + }; + +}); + + +var PluginsList = []; + + +function AddPluginToArray(cBox, name) { + if (cBox.checked) { + PluginsList.push(name); + // alert(PluginsList); + } else { + const index = PluginsList.indexOf(name); + if (index > -1) { + PluginsList.splice(index, 1); + } + // alert(PluginsList); + } +} + +var ThemesList = []; + +function AddThemeToArray(cBox, name) { + if (cBox.checked) { + ThemesList.push(name); + // alert(ThemesList); + } else { + const index = ThemesList.indexOf(name); + if (index > -1) { + ThemesList.splice(index, 1); + } + // alert(ThemesList); + } +} + + +function AppendToTable(table, markup) { + $(table).append(markup); +} + + +//..................Restore Backup Home + + +app.controller('RestoreWPBackup', function ($scope, $http, $timeout, $window) { + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = false; + $scope.installationProgress = true; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + + + $scope.checkmethode = function () { + var val = $('#RestoreMethode').children("option:selected").val(); + if (val == 1) { + $('#Newsitediv').show(); + $('#exinstingsitediv').hide(); + } else if (val == 0) { + $('#exinstingsitediv').show(); + $('#Newsitediv').hide(); + } else { + + } + }; + + + $scope.RestoreWPbackupNow = function () { + $('#wordpresshomeloading').show(); + $scope.wordpresshomeloading = false; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + $scope.currentStatus = "Start Restoring WordPress.."; + + var Domain = $('#wprestoresubdirdomain').val() + var path = $('#wprestoresubdirpath').val(); + var home = "1"; + + if (typeof path != 'undefined' || path != '') { + home = "0"; + } + if (typeof path == 'undefined') { + path = ""; + } + + + var backuptype = $('#backuptype').html(); + var data; + if (backuptype == "DataBase Backup") { + data = { + backupid: $('#backupid').html(), + DesSite: $('#DesSite').children("option:selected").val(), + Domain: '', + path: path, + home: home, + } + } else { + data = { + backupid: $('#backupid').html(), + DesSite: $('#DesSite').children("option:selected").val(), + Domain: Domain, + path: path, + home: home, + } + + } + + var url = "/websites/RestoreWPbackupNow"; + + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + // console.log(data) + + var d = $('#DesSite').children("option:selected").val(); + var c = $("input[name=Newdomain]").val(); + // if (d == -1 || c == "") { + // alert("Please Select Method of Backup Restore"); + // } else { + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + // } + + + function ListInitialDatas(response) { + wordpresshomeloading = true; + $('#wordpresshomeloading').hide(); + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Restoring process starts!.', + type: 'success' + }); + statusFile = response.data.tempStatusPath; + getCreationStatus(); + + } else { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = false; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $scope.errorMessage = response.data.error_message; + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + + } + } + + function getCreationStatus() { + $('#wordpresshomeloading').show(); + + url = "/websites/installWordpressStatus"; + + var data = { + statusFile: statusFile + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + //$('#wordpresshomeloading').hide(); + + if (response.data.abort === 1) { + + if (response.data.installStatus === 1) { + + + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = false; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + + $("#installProgress").css("width", "100%"); + $("#installProgressbackup").css("width", "100%"); + $scope.installPercentage = "100"; + $scope.currentStatus = response.data.currentStatus; + $timeout.cancel(); + + + } else { + + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = false; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $scope.errorMessage = response.data.error_message; + + $("#installProgress").css("width", "0%"); + $("#installProgressbackup").css("width", "0%"); + $scope.installPercentage = "0"; + $scope.goBackDisable = false; + + + } + + } else { + + $("#installProgress").css("width", response.data.installationProgress + "%"); + $("#installProgressbackup").css("width", response.data.installationProgress + "%"); + $scope.installPercentage = response.data.installationProgress; + $scope.currentStatus = response.data.currentStatus; + $timeout(getCreationStatus, 1000); + + } + + } + + function cantLoadInitialDatas(response) { + //$('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = false; + $scope.goBackDisable = false; + + } + + + } + + $scope.goBack = function () { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = false; + $scope.installationProgress = true; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + $("#installProgress").css("width", "0%"); + }; +}); + + +//.......................................Remote Backup + +//........... delete DeleteBackupConfigNow + +function DeleteBackupConfigNow(url) { + window.location.href = url; +} + +function DeleteRemoteBackupsiteNow(url) { + window.location.href = url; +} + +function DeleteBackupfileConfigNow(url) { + window.location.href = url; +} + + +app.controller('RemoteBackupConfig', function ($scope, $http, $timeout, $window) { + $scope.RemoteBackupLoading = true; + $scope.SFTPBackUpdiv = true; + + $scope.EndpointURLdiv = true; + $scope.Selectprovider = true; + $scope.S3keyNamediv = true; + $scope.Accesskeydiv = true; + $scope.SecretKeydiv = true; + $scope.SelectRemoteBackuptype = function () { + var val = $scope.RemoteBackuptype; + if (val == "SFTP") { + $scope.SFTPBackUpdiv = false; + $scope.EndpointURLdiv = true; + $scope.Selectprovider = true; + $scope.S3keyNamediv = true; + $scope.Accesskeydiv = true; + $scope.SecretKeydiv = true; + } else if (val == "S3") { + $scope.EndpointURLdiv = true; + $scope.Selectprovider = false; + $scope.S3keyNamediv = false; + $scope.Accesskeydiv = false; + $scope.SecretKeydiv = false; + $scope.SFTPBackUpdiv = true; + } else { + $scope.RemoteBackupLoading = true; + $scope.SFTPBackUpdiv = true; + + $scope.EndpointURLdiv = true; + $scope.Selectprovider = true; + $scope.S3keyNamediv = true; + $scope.Accesskeydiv = true; + $scope.SecretKeydiv = true; + } + } + + $scope.SelectProvidertype = function () { + $scope.EndpointURLdiv = true; + var provider = $scope.Providervalue + if (provider == 'Backblaze') { + $scope.EndpointURLdiv = false; + } else { + $scope.EndpointURLdiv = true; + } + } + + $scope.SaveBackupConfig = function () { + $scope.RemoteBackupLoading = false; + var Hname = $scope.Hostname; + var Uname = $scope.Username; + var Passwd = $scope.Password; + var path = $scope.path; + var type = $scope.RemoteBackuptype; + var Providervalue = $scope.Providervalue; + var data; + if (type == "SFTP") { + + data = { + Hname: Hname, + Uname: Uname, + Passwd: Passwd, + path: path, + type: type + } + } else if (type == "S3") { + if (Providervalue == "Backblaze") { + data = { + S3keyname: $scope.S3keyName, + Provider: Providervalue, + AccessKey: $scope.Accesskey, + SecertKey: $scope.SecretKey, + EndUrl: $scope.EndpointURL, + type: type + } + } else { + data = { + S3keyname: $scope.S3keyName, + Provider: Providervalue, + AccessKey: $scope.Accesskey, + SecertKey: $scope.SecretKey, + type: type + } + + } + + } + var url = "/websites/SaveBackupConfig"; + + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.RemoteBackupLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Successfully Saved!.', + type: 'success' + }); + location.reload(); + + + } else { + new PNotify({ + title: 'Error!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialDatas(response) { + $scope.RemoteBackupLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + + } + + + } + +}); + +var UpdatescheduleID; +app.controller('BackupSchedule', function ($scope, $http, $timeout, $window) { + $scope.BackupScheduleLoading = true; + $scope.SaveBackupSchedule = function () { + $scope.RemoteBackupLoading = false; + var FileRetention = $scope.Fretention; + var Backfrequency = $scope.Bfrequency; + + + var data = { + FileRetention: FileRetention, + Backfrequency: Backfrequency, + ScheduleName: $scope.ScheduleName, + RemoteConfigID: $('#RemoteConfigID').html(), + BackupType: $scope.BackupType + } + var url = "/websites/SaveBackupSchedule"; + + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.RemoteBackupLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Successfully Saved!.', + type: 'success' + }); + location.reload(); + + + } else { + new PNotify({ + title: 'Error!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialDatas(response) { + $scope.RemoteBackupLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + + } + + + }; + + + $scope.getupdateid = function (ID) { + UpdatescheduleID = ID; + } + + $scope.UpdateRemoteschedules = function () { + $scope.RemoteBackupLoading = false; + var Frequency = $scope.RemoteFrequency; + var fretention = $scope.RemoteFileretention; + + var data = { + ScheduleID: UpdatescheduleID, + Frequency: Frequency, + FileRetention: fretention + } + var url = "/websites/UpdateRemoteschedules"; + + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.RemoteBackupLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Successfully Updated!.', + type: 'success' + }); + location.reload(); + + + } else { + new PNotify({ + title: 'Error!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialDatas(response) { + $scope.RemoteBackupLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + + } + }; + + $scope.AddWPsiteforRemoteBackup = function () { + $scope.RemoteBackupLoading = false; + + + var data = { + WpsiteID: $('#Wpsite').val(), + RemoteScheduleID: $('#RemoteScheduleID').html() + } + var url = "/websites/AddWPsiteforRemoteBackup"; + + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.RemoteBackupLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Successfully Saved!.', + type: 'success' + }); + location.reload(); + + + } else { + new PNotify({ + title: 'Error!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialDatas(response) { + $scope.RemoteBackupLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + + } + + + }; +}); +/* Java script code to create account */ + +var website_create_domain_check = 0; + +function website_create_checkbox_function() { + + var checkBox = document.getElementById("myCheck"); + // Get the output text + + + // If the checkbox is checked, display the output text + if (checkBox.checked == true) { + website_create_domain_check = 0; + document.getElementById('Website_Create_Test_Domain').style.display = "block"; + document.getElementById('Website_Create_Own_Domain').style.display = "none"; + + } else { + document.getElementById('Website_Create_Test_Domain').style.display = "none"; + document.getElementById('Website_Create_Own_Domain').style.display = "block"; + website_create_domain_check = 1; + } + + // alert(domain_check); +} + +app.controller('createWebsite', function ($scope, $http, $timeout, $window) { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = false; + $scope.installationProgress = true; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + + var statusFile; + + $scope.createWebsite = function () { + + $scope.webSiteCreationLoading = false; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + + $scope.currentStatus = "Starting creation.."; + + var ssl, dkimCheck, openBasedir, mailDomain, apacheBackend; + + if ($scope.sslCheck === true) { + ssl = 1; + } else { + ssl = 0 + } + + if ($scope.apacheBackend === true) { + apacheBackend = 1; + } else { + apacheBackend = 0 + } + + if ($scope.dkimCheck === true) { + dkimCheck = 1; + } else { + dkimCheck = 0 + } + + if ($scope.openBasedir === true) { + openBasedir = 1; + } else { + openBasedir = 0 + } + + if ($scope.mailDomain === true) { + mailDomain = 1; + } else { + mailDomain = 0 + } + + + url = "/websites/submitWebsiteCreation"; + + var package = $scope.packageForWebsite; + + // if (website_create_domain_check == 0) { + // var Part2_domainNameCreate = document.getElementById('Part2_domainNameCreate').value; + // var domainName = document.getElementById('TestDomainNameCreate').value + Part2_domainNameCreate; + // } + // if (website_create_domain_check == 1) { + // + // var domainName = $scope.domainNameCreate; + // } + var domainName = $scope.domainNameCreate; + + // var domainName = $scope.domainNameCreate; + + var adminEmail = $scope.adminEmail; + var phpSelection = $scope.phpSelection; + var websiteOwner = $scope.websiteOwner; + + + var data = { + package: package, + domainName: domainName, + adminEmail: adminEmail, + phpSelection: phpSelection, + ssl: ssl, + websiteOwner: websiteOwner, + dkimCheck: dkimCheck, + openBasedir: openBasedir, + mailDomain: mailDomain, + apacheBackend: apacheBackend + }; + + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.createWebSiteStatus === 1) { + statusFile = response.data.tempStatusPath; + getCreationStatus(); + } else { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = false; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $scope.errorMessage = response.data.error_message; + } + + + } + + function cantLoadInitialDatas(response) { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = false; + $scope.goBackDisable = false; + + } + + + }; + $scope.goBack = function () { + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = false; + $scope.installationProgress = true; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + $("#installProgress").css("width", "0%"); + }; + + function getCreationStatus() { + + url = "/websites/installWordpressStatus"; + + var data = { + statusFile: statusFile + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + + if (response.data.abort === 1) { + + if (response.data.installStatus === 1) { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = false; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $("#installProgress").css("width", "100%"); + $scope.installPercentage = "100"; + $scope.currentStatus = response.data.currentStatus; + $timeout.cancel(); + + } else { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = false; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $scope.errorMessage = response.data.error_message; + + $("#installProgress").css("width", "0%"); + $scope.installPercentage = "0"; + $scope.goBackDisable = false; + + } + + } else { + $("#installProgress").css("width", response.data.installationProgress + "%"); + $scope.installPercentage = response.data.installationProgress; + $scope.currentStatus = response.data.currentStatus; + $timeout(getCreationStatus, 1000); + } + + } + + function cantLoadInitialDatas(response) { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = false; + $scope.goBackDisable = false; + + } + + + } + +}); +/* Java script code to create account ends here */ + +/* Java script code to list accounts */ + +$("#listFail").hide(); + + +app.controller('listWebsites', function ($scope, $http, $window) { + $scope.web = {}; + $scope.WebSitesList = []; + + $scope.currentPage = 1; + $scope.recordsToShow = 10; + + // Initial fetch of websites + $scope.getFurtherWebsitesFromDB = function () { + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + var data = { + page: $scope.currentPage, + recordsToShow: $scope.recordsToShow + }; + + var dataurl = "/websites/fetchWebsitesList"; + + $http.post(dataurl, data, config).then(function(response) { + if (response.data.listWebSiteStatus === 1) { + $scope.WebSitesList = JSON.parse(response.data.data); + $scope.pagination = response.data.pagination; + $("#listFail").hide(); + } else { + $("#listFail").fadeIn(); + $scope.errorMessage = response.data.error_message; + } + }).catch(function(error) { + $("#listFail").fadeIn(); + $scope.errorMessage = error.message || 'An error occurred while fetching websites'; + }); + }; + + // Call it immediately + $scope.getFurtherWebsitesFromDB(); + + $scope.Sites = function(domain) { + var url = '/websites/fetchWPDetails'; + var data = { + domain: domain + }; + $http({ + method: 'POST', + url: url, + data: $.param(data), + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'X-CSRFToken': getCookie('csrftoken') + } + }).then(function(response) { + if (response.data.status === 1 && response.data.fetchStatus === 1) { + $scope.web.wp_sites = response.data.sites; + $scope.web.showWPSites = true; + $("#listFail").hide(); + } else { + $("#listFail").fadeIn(); + $scope.errorMessage = response.data.error_message || 'Failed to fetch WordPress sites'; + } + }).catch(function(error) { + $("#listFail").fadeIn(); + $scope.errorMessage = error.message || 'An error occurred while fetching WordPress sites'; + }); + }; + + $scope.visitSite = function(url) { + window.open(url, '_blank'); + }; + + $scope.wpLogin = function(wpId) { + window.open('/websites/wpLogin?wpID=' + wpId, '_blank'); + }; + + $scope.manageWP = function(wpId) { + window.location.href = '/websites/listWPsites?wpID=' + wpId; + }; + + $scope.updateSetting = function(wp, setting) { + var settingMap = { + 'search-indexing': 'searchIndex', + 'debugging': 'debugging', + 'password-protection': 'passwordProtection', + 'maintenance-mode': 'maintenanceMode' + }; + + var data = { + wpID: wp.id, + setting: setting, + value: wp[settingMap[setting]] ? 'enable' : 'disable' + }; + + $http({ + method: 'POST', + url: '/websites/UpdateWPSettings', + data: data, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'X-CSRFToken': getCookie('csrftoken') + }, + transformRequest: function(obj) { + var str = []; + for(var p in obj) + str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); + return str.join("&"); + } + }).then(function(response) { + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: 'Setting updated successfully.', + type: 'success' + }); + } else { + wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change + new PNotify({ + title: 'Error', + text: 'Failed to update setting.', + type: 'error' + }); + } + }).catch(function(error) { + wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change + new PNotify({ + title: 'Error', + text: 'Connection failed while updating setting.', + type: 'error' + }); + }); + }; + + $scope.cyberPanelLoading = true; + + $scope.issueSSL = function (virtualHost) { + $scope.cyberPanelLoading = false; + + var url = "/manageSSL/issueSSL"; + + + var data = { + virtualHost: virtualHost + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.cyberPanelLoading = true; + if (response.data.SSL === 1) { + new PNotify({ + title: 'Success!', + text: 'SSL successfully issued.', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + + } + + function cantLoadInitialDatas(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); + } + + + }; + + $scope.cyberPanelLoading = true; + + $scope.searchWebsites = function () { + + $scope.cyberPanelLoading = false; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + var data = { + patternAdded: $scope.patternAdded + }; + + dataurl = "/websites/searchWebsites"; + + $http.post(dataurl, data, config).then(ListInitialData, cantLoadInitialData); + + + function ListInitialData(response) { + $scope.cyberPanelLoading = true; + if (response.data.listWebSiteStatus === 1) { + + var finalData = JSON.parse(response.data.data); + $scope.WebSitesList = finalData; + $("#listFail").hide(); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + } + + function cantLoadInitialData(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Connect disrupted, refresh the page.', + type: 'error' + }); + } + + + }; + + $scope.ScanWordpressSite = function () { + + $('#cyberPanelLoading').show(); + + + var url = "/websites/ScanWordpressSite"; + + var data = {} + + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + $('#cyberPanelLoading').hide(); + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Successfully Saved!.', + type: 'success' + }); + location.reload(); + + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#cyberPanelLoading').hide(); + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + + } + + + }; + +}); + +app.controller('listChildDomainsMain', function ($scope, $http, $timeout) { + + $scope.currentPage = 1; + $scope.recordsToShow = 10; + + $scope.getFurtherWebsitesFromDB = function () { + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + var data = { + page: $scope.currentPage, + recordsToShow: $scope.recordsToShow + }; + + + dataurl = "/websites/fetchChildDomainsMain"; + + $http.post(dataurl, data, config).then(ListInitialData, cantLoadInitialData); + + + function ListInitialData(response) { + if (response.data.listWebSiteStatus === 1) { + + $scope.WebSitesList = JSON.parse(response.data.data); + $scope.pagination = response.data.pagination; + $scope.clients = JSON.parse(response.data.data); + $("#listFail").hide(); + } else { + $("#listFail").fadeIn(); + $scope.errorMessage = response.data.error_message; + + } + } + + function cantLoadInitialData(response) { + } + + + }; + $scope.getFurtherWebsitesFromDB(); + + $scope.cyberPanelLoading = true; + + $scope.issueSSL = function (virtualHost) { + $scope.cyberPanelLoading = false; + + var url = "/manageSSL/issueSSL"; + + + var data = { + virtualHost: virtualHost + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.cyberPanelLoading = true; + if (response.data.SSL === 1) { + new PNotify({ + title: 'Success!', + text: 'SSL successfully issued.', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + + } + + function cantLoadInitialDatas(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); + } + + + }; + + $scope.cyberPanelLoading = true; + + $scope.searchWebsites = function () { + + $scope.cyberPanelLoading = false; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + var data = { + patternAdded: $scope.patternAdded + }; + + dataurl = "/websites/searchChilds"; + + $http.post(dataurl, data, config).then(ListInitialData, cantLoadInitialData); + + + function ListInitialData(response) { + $scope.cyberPanelLoading = true; + if (response.data.listWebSiteStatus === 1) { + + var finalData = JSON.parse(response.data.data); + $scope.WebSitesList = finalData; + $("#listFail").hide(); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + } + + function cantLoadInitialData(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Connect disrupted, refresh the page.', + type: 'error' + }); + } + + + }; + + $scope.initConvert = function (virtualHost) { + $scope.domainName = virtualHost; + }; + + var statusFile; + + $scope.installationProgress = true; + + $scope.convert = function () { + + $scope.cyberPanelLoading = false; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.goBackDisable = true; + + $scope.currentStatus = "Starting creation.."; + + var ssl, dkimCheck, openBasedir; + + if ($scope.sslCheck === true) { + ssl = 1; + } else { + ssl = 0 + } + + if ($scope.dkimCheck === true) { + dkimCheck = 1; + } else { + dkimCheck = 0 + } + + if ($scope.openBasedir === true) { + openBasedir = 1; + } else { + openBasedir = 0 + } + + url = "/websites/convertDomainToSite"; + + + var data = { + package: $scope.packageForWebsite, + domainName: $scope.domainName, + adminEmail: $scope.adminEmail, + phpSelection: $scope.phpSelection, + websiteOwner: $scope.websiteOwner, + ssl: ssl, + dkimCheck: dkimCheck, + openBasedir: openBasedir + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.createWebSiteStatus === 1) { + statusFile = response.data.tempStatusPath; + getCreationStatus(); + } else { + + $scope.cyberPanelLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.goBackDisable = false; + + $scope.currentStatus = response.data.error_message; + } + + + } + + function cantLoadInitialDatas(response) { + + $scope.cyberPanelLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.goBackDisable = false; + + } + + + }; + $scope.goBack = function () { + $scope.cyberPanelLoading = true; + $scope.installationDetailsForm = false; + $scope.installationProgress = true; + $scope.goBackDisable = true; + $("#installProgress").css("width", "0%"); + }; + + function getCreationStatus() { + + url = "/websites/installWordpressStatus"; + + var data = { + statusFile: statusFile + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + + if (response.data.abort === 1) { + + if (response.data.installStatus === 1) { + + $scope.cyberPanelLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.goBackDisable = false; + + $("#installProgress").css("width", "100%"); + $scope.installPercentage = "100"; + $scope.currentStatus = response.data.currentStatus; + $timeout.cancel(); + + } else { + + $scope.cyberPanelLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.goBackDisable = false; + + $scope.currentStatus = response.data.error_message; + + $("#installProgress").css("width", "0%"); + $scope.installPercentage = "0"; + $scope.goBackDisable = false; + + } + + } else { + $("#installProgress").css("width", response.data.installationProgress + "%"); + $scope.installPercentage = response.data.installationProgress; + $scope.currentStatus = response.data.currentStatus; + $timeout(getCreationStatus, 1000); + } + + } + + function cantLoadInitialDatas(response) { + + $scope.cyberPanelLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.goBackDisable = false; + + } + + + } + + var DeleteDomain; + $scope.deleteDomainInit = function (childDomainForDeletion) { + DeleteDomain = childDomainForDeletion; + }; + + $scope.deleteChildDomain = function () { + $scope.cyberPanelLoading = false; + url = "/websites/submitDomainDeletion"; + + var data = { + websiteName: DeleteDomain, + DeleteDocRoot: $scope.DeleteDocRoot + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + function ListInitialDatas(response) { + $scope.cyberPanelLoading = true; + if (response.data.websiteDeleteStatus === 1) { + new PNotify({ + title: 'Success!', + text: 'Child Domain successfully deleted.', + type: 'success' + }); + $scope.getFurtherWebsitesFromDB(); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialDatas(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); + + } + + }; + +}); + +/* Java script code to list accounts ends here */ + + +/* Java script code to delete Website */ + + +$("#websiteDeleteFailure").hide(); +$("#websiteDeleteSuccess").hide(); + +$("#deleteWebsiteButton").hide(); +$("#deleteLoading").hide(); + +app.controller('deleteWebsiteControl', function ($scope, $http) { + + + $scope.deleteWebsite = function () { + + $("#deleteWebsiteButton").fadeIn(); + + + }; + + $scope.deleteWebsiteFinal = function () { + + $("#deleteLoading").show(); + + var websiteName = $scope.websiteToBeDeleted; + + + url = "/websites/submitWebsiteDeletion"; + + var data = { + websiteName: websiteName + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.websiteDeleteStatus === 0) { + $scope.errorMessage = response.data.error_message; + $("#websiteDeleteFailure").fadeIn(); + $("#websiteDeleteSuccess").hide(); + $("#deleteWebsiteButton").hide(); + + + $("#deleteLoading").hide(); + + } else { + $("#websiteDeleteFailure").hide(); + $("#websiteDeleteSuccess").fadeIn(); + $("#deleteWebsiteButton").hide(); + $scope.deletedWebsite = websiteName; + $("#deleteLoading").hide(); + + } + + + } + + function cantLoadInitialDatas(response) { + } + + + }; + +}); + + /* Java script code to delete website ends here */ @@ -11503,16 +9959,20 @@ app.controller('manageAliasController', function ($scope, $http, $timeout, $wind } }).then(function(response) { if (response.data.status === 1 && response.data.fetchStatus === 1) { - $scope.web.wp_sites = response.data.sites; - $scope.web.showWPSites = true; - $("#listFail").hide(); + var sites = response.data.sites; + var message = 'WordPress Sites for ' + domain + ':\n\n'; + sites.forEach(function(site) { + message += 'Title: ' + site.title + '\n'; + message += 'URL: ' + site.url + '\n'; + message += 'Version: ' + site.version + '\n'; + message += 'Status: ' + site.status + '\n\n'; + }); + alert(message); } else { - $("#listFail").fadeIn(); - $scope.errorMessage = response.data.error_message || 'Failed to fetch WordPress sites'; + alert('Error: ' + response.data.error_message); } }).catch(function(error) { - $("#listFail").fadeIn(); - $scope.errorMessage = error.message || 'An error occurred while fetching WordPress sites'; + alert('Error fetching WordPress sites: ' + JSON.stringify(error)); }); }; From d5eb868186fd6f672aaf23a2bcd6fe8b36266986 Mon Sep 17 00:00:00 2001 From: usmannasir Date: Fri, 4 Apr 2025 21:44:18 +0500 Subject: [PATCH 019/273] fix showwpsites --- .../websiteFunctions/websiteFunctions.js | 116 +++++++++++++----- .../websiteFunctions/listWebsites.html | 12 +- 2 files changed, 92 insertions(+), 36 deletions(-) diff --git a/websiteFunctions/static/websiteFunctions/websiteFunctions.js b/websiteFunctions/static/websiteFunctions/websiteFunctions.js index a12105241..5b042f691 100755 --- a/websiteFunctions/static/websiteFunctions/websiteFunctions.js +++ b/websiteFunctions/static/websiteFunctions/websiteFunctions.js @@ -2675,11 +2675,21 @@ app.controller('listWebsites', function ($scope, $http, $window) { $scope.getFurtherWebsitesFromDB(); $scope.showWPSites = function(domain) { + console.log('showWPSites called for domain:', domain); + + // Make sure domain is defined + if (!domain) { + console.error('Domain is undefined'); + return; + } + var url = '/websites/fetchWPDetails'; var data = { domain: domain }; + console.log('Making request to:', url, 'with data:', data); + $http({ method: 'POST', url: url, @@ -2689,17 +2699,26 @@ app.controller('listWebsites', function ($scope, $http, $window) { 'X-CSRFToken': getCookie('csrftoken') } }).then(function(response) { + console.log('Response received:', response); if (response.data.status === 1 && response.data.fetchStatus === 1) { - $scope.web.wp_sites = response.data.sites; - $scope.web.showWPSites = true; + // Find the website in the list and update its properties + $scope.WebSitesList.forEach(function(website) { + if (website.domain === domain) { + website.wp_sites = response.data.sites; + website.showWPSites = true; + console.log('Updated website:', website); + } + }); $("#listFail").hide(); } else { $("#listFail").fadeIn(); $scope.errorMessage = response.data.error_message || 'Failed to fetch WordPress sites'; + console.error('Error in response:', response.data.error_message); } }).catch(function(error) { $("#listFail").fadeIn(); $scope.errorMessage = error.message || 'An error occurred while fetching WordPress sites'; + console.error('Request failed:', error); }); }; @@ -6048,31 +6067,51 @@ app.controller('listWebsites', function ($scope, $http, $window) { // Call it immediately $scope.getFurtherWebsitesFromDB(); - $scope.Sites = function(domain) { + $scope.showWPSites = function(domain) { + console.log('showWPSites called for domain:', domain); + + // Make sure domain is defined + if (!domain) { + console.error('Domain is undefined'); + return; + } + var url = '/websites/fetchWPDetails'; var data = { - domain: domain + domain: domain }; + + console.log('Making request to:', url, 'with data:', data); + $http({ - method: 'POST', - url: url, - data: $.param(data), - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', - 'X-CSRFToken': getCookie('csrftoken') - } + method: 'POST', + url: url, + data: $.param(data), + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'X-CSRFToken': getCookie('csrftoken') + } }).then(function(response) { - if (response.data.status === 1 && response.data.fetchStatus === 1) { - $scope.web.wp_sites = response.data.sites; - $scope.web.showWPSites = true; - $("#listFail").hide(); - } else { - $("#listFail").fadeIn(); - $scope.errorMessage = response.data.error_message || 'Failed to fetch WordPress sites'; - } + console.log('Response received:', response); + if (response.data.status === 1 && response.data.fetchStatus === 1) { + // Find the website in the list and update its properties + $scope.WebSitesList.forEach(function(website) { + if (website.domain === domain) { + website.wp_sites = response.data.sites; + website.showWPSites = true; + console.log('Updated website:', website); + } + }); + $("#listFail").hide(); + } else { + $("#listFail").fadeIn(); + $scope.errorMessage = response.data.error_message || 'Failed to fetch WordPress sites'; + console.error('Error in response:', response.data.error_message); + } }).catch(function(error) { - $("#listFail").fadeIn(); - $scope.errorMessage = error.message || 'An error occurred while fetching WordPress sites'; + $("#listFail").fadeIn(); + $scope.errorMessage = error.message || 'An error occurred while fetching WordPress sites'; + console.error('Request failed:', error); }); }; @@ -9944,11 +9983,21 @@ app.controller('manageAliasController', function ($scope, $http, $timeout, $wind } $scope.showWPSites = function(domain) { + console.log('showWPSites called for domain:', domain); + + // Make sure domain is defined + if (!domain) { + console.error('Domain is undefined'); + return; + } + var url = '/websites/fetchWPDetails'; var data = { domain: domain }; + console.log('Making request to:', url, 'with data:', data); + $http({ method: 'POST', url: url, @@ -9958,21 +10007,26 @@ app.controller('manageAliasController', function ($scope, $http, $timeout, $wind 'X-CSRFToken': getCookie('csrftoken') } }).then(function(response) { + console.log('Response received:', response); if (response.data.status === 1 && response.data.fetchStatus === 1) { - var sites = response.data.sites; - var message = 'WordPress Sites for ' + domain + ':\n\n'; - sites.forEach(function(site) { - message += 'Title: ' + site.title + '\n'; - message += 'URL: ' + site.url + '\n'; - message += 'Version: ' + site.version + '\n'; - message += 'Status: ' + site.status + '\n\n'; + // Find the website in the list and update its properties + $scope.WebSitesList.forEach(function(website) { + if (website.domain === domain) { + website.wp_sites = response.data.sites; + website.showWPSites = true; + console.log('Updated website:', website); + } }); - alert(message); + $("#listFail").hide(); } else { - alert('Error: ' + response.data.error_message); + $("#listFail").fadeIn(); + $scope.errorMessage = response.data.error_message || 'Failed to fetch WordPress sites'; + console.error('Error in response:', response.data.error_message); } }).catch(function(error) { - alert('Error fetching WordPress sites: ' + JSON.stringify(error)); + $("#listFail").fadeIn(); + $scope.errorMessage = error.message || 'An error occurred while fetching WordPress sites'; + console.error('Request failed:', error); }); }; diff --git a/websiteFunctions/templates/websiteFunctions/listWebsites.html b/websiteFunctions/templates/websiteFunctions/listWebsites.html index 370e2a94a..b9e58588f 100755 --- a/websiteFunctions/templates/websiteFunctions/listWebsites.html +++ b/websiteFunctions/templates/websiteFunctions/listWebsites.html @@ -101,11 +101,13 @@
    - - - {$ web.wp_sites.length $} WordPress Sites - + + + + {$ web.wp_sites.length $} WordPress Sites + +
    From 85a8fbef2776e7ed9aea0f93624c35ac3a4b24fa Mon Sep 17 00:00:00 2001 From: usmannasir Date: Sat, 5 Apr 2025 00:12:20 +0500 Subject: [PATCH 020/273] update code to add design from main wp page --- static/websiteFunctions/websiteFunctions.js | 174 +++++++++++++++- .../websiteFunctions/listWebsites.html | 193 +++++++++++++----- 2 files changed, 310 insertions(+), 57 deletions(-) diff --git a/static/websiteFunctions/websiteFunctions.js b/static/websiteFunctions/websiteFunctions.js index ddb265b42..70987a875 100644 --- a/static/websiteFunctions/websiteFunctions.js +++ b/static/websiteFunctions/websiteFunctions.js @@ -237,7 +237,7 @@ app.controller('createWebsite', function ($scope, $http, $timeout, $window) { $("#listFail").hide(); -app.controller('listWebsites', function ($scope, $http) { +app.controller('listWebsites', function ($scope, $http, $window) { $scope.currentPage = 1; @@ -384,6 +384,178 @@ app.controller('listWebsites', function ($scope, $http) { }; + $scope.getFullUrl = function(url) { + if (!url) return ''; + if (url.startsWith('http://') || url.startsWith('https://')) { + return url; + } + return 'https://' + url; + }; + + $scope.showWPSites = function(domain) { + var site = $scope.WebSitesList.find(function(site) { + return site.domain === domain; + }); + if (site) { + site.showWPSites = !site.showWPSites; + if (site.showWPSites && (!site.wp_sites || !site.wp_sites.length)) { + // Fetch WordPress sites if not already loaded + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + var data = { domain: domain }; + $http.post('/websites/getWordPressSites', data, config).then( + function(response) { + if (response.data.status === 1) { + site.wp_sites = response.data.sites; + site.wp_sites.forEach(function(wp) { + fetchWPSiteData(wp); + }); + } else { + new PNotify({ + title: 'Error!', + text: response.data.error_message || 'Could not fetch WordPress sites', + type: 'error' + }); + } + }, + function(response) { + new PNotify({ + title: 'Error!', + text: 'Could not connect to server', + type: 'error' + }); + } + ); + } + } + }; + + function fetchWPSiteData(wp) { + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + var data = { WPid: wp.id }; + + // Fetch site data + $http.post('/websites/FetchWPdata', data, config).then( + function(response) { + if (response.data.status === 1) { + var data = response.data.ret_data; + wp.version = data.version; + wp.phpVersion = data.phpVersion || 'PHP 7.4'; + wp.searchIndex = data.searchIndex === 1; + wp.debugging = data.debugging === 1; + wp.passwordProtection = data.passwordprotection === 1; + wp.maintenanceMode = data.maintenanceMode === 1; + fetchPluginData(wp); + fetchThemeData(wp); + } + } + ); + } + + function fetchPluginData(wp) { + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + var data = { WPid: wp.id }; + $http.post('/websites/GetCurrentPlugins', data, config).then( + function(response) { + if (response.data.status === 1) { + var plugins = JSON.parse(response.data.plugins); + wp.activePlugins = plugins.filter(function(p) { return p.status === 'active'; }).length; + wp.totalPlugins = plugins.length; + } + } + ); + } + + function fetchThemeData(wp) { + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + var data = { WPid: wp.id }; + $http.post('/websites/GetCurrentThemes', data, config).then( + function(response) { + if (response.data.status === 1) { + var themes = JSON.parse(response.data.themes); + wp.theme = themes.find(function(t) { return t.status === 'active'; }).name; + wp.totalThemes = themes.length; + } + } + ); + } + + $scope.updateSetting = function(wp, setting) { + var settingMap = { + 'search-indexing': 'searchIndex', + 'debugging': 'debugging', + 'password-protection': 'passwordProtection', + 'maintenance-mode': 'maintenanceMode' + }; + + var data = { + siteId: wp.id, + setting: setting, + value: wp[settingMap[setting]] ? 1 : 0 + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post('/websites/UpdateWPSettings', data, config).then( + function(response) { + if (!response.data.status) { + wp[settingMap[setting]] = !wp[settingMap[setting]]; + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message || 'Unknown error', + type: 'error' + }); + } else { + new PNotify({ + title: 'Success!', + text: 'Setting updated successfully.', + type: 'success' + }); + } + }, + function(response) { + wp[settingMap[setting]] = !wp[settingMap[setting]]; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please try again.', + type: 'error' + }); + } + ); + }; + + $scope.wpLogin = function(wpId) { + window.open('/websites/AutoLogin?id=' + wpId, '_blank'); + }; + + $scope.manageWP = function(wpId) { + window.location.href = '/websites/WPHome?ID=' + wpId; + }; + + $scope.deleteWPSite = function(wp) { + if (confirm('Are you sure you want to delete this WordPress site? This action cannot be undone.')) { + window.location.href = '/websites/ListWPSites?DeleteID=' + wp.id; + } + }; }); diff --git a/websiteFunctions/templates/websiteFunctions/listWebsites.html b/websiteFunctions/templates/websiteFunctions/listWebsites.html index b9e58588f..94ee99de8 100755 --- a/websiteFunctions/templates/websiteFunctions/listWebsites.html +++ b/websiteFunctions/templates/websiteFunctions/listWebsites.html @@ -113,70 +113,151 @@
    -
    +
    -
    - -
    -
    - - - -
    -
    - -
    -
    -
    -
    WordPress
    -
    +
    +
    +
    +
    +

    {$ wp.title $}

    +
    +
    + + +
    +
    -
    -
    -
    -
    PHP Version
    -
    -
    -
    -
    -
    -
    Theme
    -
    -
    -
    -
    -
    -
    Plugins
    -
    {$ wp.activePlugins || '0' $} active
    -
    -
    -
    - -
    -
    -
    - - Search engine indexing -
    -
    - - Debugging -
    -
    -
    -
    - - Password protection -
    -
    - - Maintenance mode +
    +
    + +
    +
    +
    +
    + + {$ wp.version || 'Unknown' $} +
    +
    +
    +
    + + {$ wp.phpVersion || 'Loading...' $} +
    +
    +
    +
    + + {$ wp.theme || 'twentytwentyfive' $} +
    +
    +
    +
    + + {$ wp.activePlugins || '0' $} active +
    +
    +
    +
    +
    +
    + +
    +
    + +
    +
    +
    +
    + +
    +
    + +
    +
    +
    +
    +
    + +

    {% trans "Cannot list websites. Error message:" %} {$ errorMessage $}

    From 722d804685b47225eac6ffe780e1ac1da015cc1c Mon Sep 17 00:00:00 2001 From: usmannasir Date: Sat, 5 Apr 2025 00:38:17 +0500 Subject: [PATCH 021/273] update code to add design from main wp page --- static/websiteFunctions/websiteFunctions.js | 8 - .../websiteFunctions/listWebsites.html | 6 +- websiteFunctions/website.py | 7864 +++++++++++++++++ 3 files changed, 7867 insertions(+), 11 deletions(-) diff --git a/static/websiteFunctions/websiteFunctions.js b/static/websiteFunctions/websiteFunctions.js index 70987a875..0520c2956 100644 --- a/static/websiteFunctions/websiteFunctions.js +++ b/static/websiteFunctions/websiteFunctions.js @@ -384,14 +384,6 @@ app.controller('listWebsites', function ($scope, $http, $window) { }; - $scope.getFullUrl = function(url) { - if (!url) return ''; - if (url.startsWith('http://') || url.startsWith('https://')) { - return url; - } - return 'https://' + url; - }; - $scope.showWPSites = function(domain) { var site = $scope.WebSitesList.find(function(site) { return site.domain === domain; diff --git a/websiteFunctions/templates/websiteFunctions/listWebsites.html b/websiteFunctions/templates/websiteFunctions/listWebsites.html index 94ee99de8..1fcf6cc33 100755 --- a/websiteFunctions/templates/websiteFunctions/listWebsites.html +++ b/websiteFunctions/templates/websiteFunctions/listWebsites.html @@ -134,16 +134,16 @@
    - {$ wp.title $} diff --git a/websiteFunctions/website.py b/websiteFunctions/website.py index 280191367..f64e7470a 100755 --- a/websiteFunctions/website.py +++ b/websiteFunctions/website.py @@ -1987,6 +1987,7870 @@ class WebsiteManager: htaccess_content = f"""AuthType Basic AuthName "Restricted Access" AuthUserFile {htpasswd} +Require valid-user""" + with open(htaccess, 'w') as f: + f.write(htaccess_content) + +#!/usr/local/CyberCP/bin/python +import html +import os +import os.path +import sys +import django + +from databases.models import Databases +from plogical.DockerSites import Docker_Sites +from plogical.httpProc import httpProc + +sys.path.append('/usr/local/CyberCP') +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings") +django.setup() +import json +from plogical.acl import ACLManager +import plogical.CyberCPLogFileWriter as logging +from websiteFunctions.models import Websites, ChildDomains, GitLogs, wpplugins, WPSites, WPStaging, WPSitesBackup, \ + RemoteBackupConfig, RemoteBackupSchedule, RemoteBackupsites, DockerPackages, PackageAssignment, DockerSites +from plogical.virtualHostUtilities import virtualHostUtilities +import subprocess +import shlex +from plogical.installUtilities import installUtilities +from django.shortcuts import HttpResponse, render, redirect +from loginSystem.models import Administrator, ACL +from packages.models import Package +from plogical.mailUtilities import mailUtilities +from random import randint +import time +import re +import boto3 +from plogical.childDomain import ChildDomainManager +from math import ceil +from plogical.alias import AliasManager +from plogical.applicationInstaller import ApplicationInstaller +from plogical import hashPassword, randomPassword +from emailMarketing.emACL import emACL +from plogical.processUtilities import ProcessUtilities +from managePHP.phpManager import PHPManager +from ApachController.ApacheVhosts import ApacheVhost +from plogical.vhostConfs import vhostConfs +from plogical.cronUtil import CronUtil +from .StagingSetup import StagingSetup +import validators +from django.http import JsonResponse + + +class WebsiteManager: + apache = 1 + ols = 2 + lsws = 3 + + def __init__(self, domain=None, childDomain=None): + self.domain = domain + self.childDomain = childDomain + + def createWebsite(self, request=None, userID=None, data=None): + + url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" + data = { + "name": "all", + "IP": ACLManager.GetServerIP() + } + + import requests + response = requests.post(url, data=json.dumps(data)) + Status = response.json()['status'] + + test_domain_status = 0 + + if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: + test_domain_status = 1 + + currentACL = ACLManager.loadedACL(userID) + adminNames = ACLManager.loadAllUsers(userID) + packagesName = ACLManager.loadPackages(userID, currentACL) + phps = PHPManager.findPHPVersions() + + rnpss = randomPassword.generate_pass(10) + + Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps, 'Randam_String': rnpss.lower(), + 'test_domain_data': test_domain_status} + proc = httpProc(request, 'websiteFunctions/createWebsite.html', + Data, 'createWebsite') + return proc.render() + + def WPCreate(self, request=None, userID=None, data=None): + url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" + data = { + "name": "wp-manager", + "IP": ACLManager.GetServerIP() + } + + import requests + response = requests.post(url, data=json.dumps(data)) + Status = response.json()['status'] + + + if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: + currentACL = ACLManager.loadedACL(userID) + adminNames = ACLManager.loadAllUsers(userID) + packagesName = ACLManager.loadPackages(userID, currentACL) + + if len(packagesName) == 0: + packagesName = ['Default'] + + FinalVersions = [] + userobj = Administrator.objects.get(pk=userID) + counter = 0 + try: + import requests + WPVersions = json.loads(requests.get('https://api.wordpress.org/core/version-check/1.7/').text)[ + 'offers'] + + for versions in WPVersions: + if counter == 7: + break + if versions['current'] not in FinalVersions: + FinalVersions.append(versions['current']) + counter = counter + 1 + except: + FinalVersions = ['5.6', '5.5.3', '5.5.2'] + + Plugins = wpplugins.objects.filter(owner=userobj) + rnpss = randomPassword.generate_pass(10) + + ## + + test_domain_status = 1 + + Data = {'packageList': packagesName, "owernList": adminNames, 'WPVersions': FinalVersions, + 'Plugins': Plugins, 'Randam_String': rnpss.lower(), 'test_domain_data': test_domain_status} + proc = httpProc(request, 'websiteFunctions/WPCreate.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def ListWPSites(self, request=None, userID=None, DeleteID=None): + import json + currentACL = ACLManager.loadedACL(userID) + + admin = Administrator.objects.get(pk=userID) + data = {} + wp_sites = ACLManager.GetALLWPObjects(currentACL, userID) + data['wp'] = wp_sites + + try: + if DeleteID != None: + WPDelete = WPSites.objects.get(pk=DeleteID) + + if ACLManager.checkOwnership(WPDelete.owner.domain, admin, currentACL) == 1: + WPDelete.delete() + except BaseException as msg: + pass + + sites = [] + for site in data['wp']: + sites.append({ + 'id': site.id, + 'title': site.title, + 'url': site.FinalURL, + 'production_status': True + }) + + context = { + "wpsite": json.dumps(sites), + "status": 1, + "total_sites": len(sites), + "debug_info": json.dumps({ + "user_id": userID, + "is_admin": bool(currentACL.get('admin', 0)), + "wp_sites_count": wp_sites.count() + }) + } + + proc = httpProc(request, 'websiteFunctions/WPsitesList.html', context) + return proc.render() + + def WPHome(self, request=None, userID=None, WPid=None, DeleteID=None): + Data = {} + currentACL = ACLManager.loadedACL(userID) + WPobj = WPSites.objects.get(pk=WPid) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(WPobj.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + try: + + url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" + data = { + "name": "wp-manager", + "IP": ACLManager.GetServerIP() + } + + import requests + response = requests.post(url, data=json.dumps(data)) + Status = response.json()['status'] + + rnpss = randomPassword.generate_pass(10) + + Data['Randam_String'] = rnpss.lower() + + if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: + Data['wpsite'] = WPobj + Data['test_domain_data'] = 1 + + try: + DeleteID = request.GET.get('DeleteID', None) + + if DeleteID != None: + wstagingDelete = WPStaging.objects.get(pk=DeleteID, owner=WPobj) + wstagingDelete.delete() + + except BaseException as msg: + da = str(msg) + + proc = httpProc(request, 'websiteFunctions/WPsiteHome.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + except: + proc = httpProc(request, 'websiteFunctions/WPsiteHome.html', + Data, 'createDatabase') + return proc.render() + + def RestoreHome(self, request=None, userID=None, BackupID=None): + Data = {} + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.CheckForPremFeature('wp-manager'): + + Data['backupobj'] = WPSitesBackup.objects.get(pk=BackupID) + + if ACLManager.CheckIPBackupObjectOwner(currentACL, Data['backupobj'], admin) == 1: + pass + else: + return ACLManager.loadError() + + config = json.loads(Data['backupobj'].config) + Data['FileName'] = config['name'] + try: + Data['Backuptype'] = config['Backuptype'] + + if Data['Backuptype'] == 'DataBase Backup' or Data['Backuptype'] == 'Website Backup': + Data['WPsites'] = [WPSites.objects.get(pk=Data['backupobj'].WPSiteID)] + else: + Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) + + except: + Data['Backuptype'] = None + Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) + + proc = httpProc(request, 'websiteFunctions/WPRestoreHome.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def RemoteBackupConfig(self, request=None, userID=None, DeleteID=None): + Data = {} + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + try: + if DeleteID != None: + BackupconfigDelete = RemoteBackupConfig.objects.get(pk=DeleteID) + BackupconfigDelete.delete() + except: + pass + + if ACLManager.CheckForPremFeature('wp-manager'): + + Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) + allcon = RemoteBackupConfig.objects.all() + Data['backupconfigs'] = [] + for i in allcon: + configr = json.loads(i.config) + if i.configtype == "SFTP": + Data['backupconfigs'].append({ + 'id': i.pk, + 'Type': i.configtype, + 'HostName': configr['Hostname'], + 'Path': configr['Path'] + }) + elif i.configtype == "S3": + Provider = configr['Provider'] + if Provider == "Backblaze": + Data['backupconfigs'].append({ + 'id': i.pk, + 'Type': i.configtype, + 'HostName': Provider, + 'Path': configr['S3keyname'] + }) + else: + Data['backupconfigs'].append({ + 'id': i.pk, + 'Type': i.configtype, + 'HostName': Provider, + 'Path': configr['S3keyname'] + }) + + proc = httpProc(request, 'websiteFunctions/RemoteBackupConfig.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def BackupfileConfig(self, request=None, userID=None, RemoteConfigID=None, DeleteID=None): + Data = {} + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + Data['RemoteConfigID'] = RemoteConfigID + RemoteConfigobj = RemoteBackupConfig.objects.get(pk=RemoteConfigID) + try: + if DeleteID != None: + RemoteBackupConfigDelete = RemoteBackupSchedule.objects.get(pk=DeleteID) + RemoteBackupConfigDelete.delete() + except: + pass + + if ACLManager.CheckForPremFeature('wp-manager'): + Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) + allsechedule = RemoteBackupSchedule.objects.filter(RemoteBackupConfig=RemoteConfigobj) + Data['Backupschedule'] = [] + for i in allsechedule: + lastrun = i.lastrun + LastRun = time.strftime('%Y-%m-%d', time.localtime(float(lastrun))) + Data['Backupschedule'].append({ + 'id': i.pk, + 'Name': i.Name, + 'RemoteConfiguration': i.RemoteBackupConfig.configtype, + 'Retention': i.fileretention, + 'Frequency': i.timeintervel, + 'LastRun': LastRun + }) + proc = httpProc(request, 'websiteFunctions/BackupfileConfig.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def AddRemoteBackupsite(self, request=None, userID=None, RemoteScheduleID=None, DeleteSiteID=None): + Data = {} + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + Data['RemoteScheduleID'] = RemoteScheduleID + RemoteBackupScheduleobj = RemoteBackupSchedule.objects.get(pk=RemoteScheduleID) + + try: + if DeleteSiteID != None: + RemoteBackupsitesDelete = RemoteBackupsites.objects.get(pk=DeleteSiteID) + RemoteBackupsitesDelete.delete() + except: + pass + + if ACLManager.CheckForPremFeature('wp-manager'): + Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) + allRemoteBackupsites = RemoteBackupsites.objects.filter(owner=RemoteBackupScheduleobj) + Data['RemoteBackupsites'] = [] + for i in allRemoteBackupsites: + try: + wpsite = WPSites.objects.get(pk=i.WPsites) + Data['RemoteBackupsites'].append({ + 'id': i.pk, + 'Title': wpsite.title, + }) + except: + pass + proc = httpProc(request, 'websiteFunctions/AddRemoteBackupSite.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def WordpressPricing(self, request=None, userID=None, ): + Data = {} + proc = httpProc(request, 'websiteFunctions/CyberpanelPricing.html', Data, 'createWebsite') + return proc.render() + + def RestoreBackups(self, request=None, userID=None, DeleteID=None): + Data = {} + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" + data = { + "name": "wp-manager", + "IP": ACLManager.GetServerIP() + } + + import requests + response = requests.post(url, data=json.dumps(data)) + Status = response.json()['status'] + + if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: + + backobj = WPSitesBackup.objects.filter(owner=admin).order_by('-id') + + # if ACLManager.CheckIPBackupObjectOwner(currentACL, backobj, admin) == 1: + # pass + # else: + # return ACLManager.loadError() + + try: + if DeleteID != None: + DeleteIDobj = WPSitesBackup.objects.get(pk=DeleteID) + + if ACLManager.CheckIPBackupObjectOwner(currentACL, DeleteIDobj, admin) == 1: + config = DeleteIDobj.config + conf = json.loads(config) + FileName = conf['name'] + command = "rm -r /home/backup/%s.tar.gz" % FileName + ProcessUtilities.executioner(command) + DeleteIDobj.delete() + + except BaseException as msg: + pass + Data['job'] = [] + + for sub in backobj: + try: + wpsite = WPSites.objects.get(pk=sub.WPSiteID) + web = wpsite.title + except: + web = "Website Not Found" + + try: + config = sub.config + conf = json.loads(config) + Backuptype = conf['Backuptype'] + BackupDestination = conf['BackupDestination'] + except: + Backuptype = "Backup type not exists" + + Data['job'].append({ + 'id': sub.id, + 'title': web, + 'Backuptype': Backuptype, + 'BackupDestination': BackupDestination + }) + + proc = httpProc(request, 'websiteFunctions/RestoreBackups.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def AutoLogin(self, request=None, userID=None): + + WPid = request.GET.get('id') + currentACL = ACLManager.loadedACL(userID) + WPobj = WPSites.objects.get(pk=WPid) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(WPobj.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + from managePHP.phpManager import PHPManager + + php = PHPManager.getPHPString(WPobj.owner.phpSelection) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" + data = { + "name": "wp-manager", + "IP": ACLManager.GetServerIP() + } + + import requests + response = requests.post(url, data=json.dumps(data)) + Status = response.json()['status'] + + if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: + + ## Get title + + password = randomPassword.generate_pass(10) + + command = f'sudo -u %s {FinalPHPPath} /usr/bin/wp user create autologin %s --role=administrator --user_pass="%s" --path=%s --skip-plugins --skip-themes' % ( + WPobj.owner.externalApp, 'autologin@cloudpages.cloud', password, WPobj.path) + ProcessUtilities.executioner(command) + + command = f'sudo -u %s {FinalPHPPath} /usr/bin/wp user update autologin --user_pass="%s" --path=%s --skip-plugins --skip-themes' % ( + WPobj.owner.externalApp, password, WPobj.path) + ProcessUtilities.executioner(command) + + data = {} + + if WPobj.FinalURL.endswith('/'): + FinalURL = WPobj.FinalURL[:-1] + else: + FinalURL = WPobj.FinalURL + + data['url'] = 'https://%s' % (FinalURL) + data['userName'] = 'autologin' + data['password'] = password + + proc = httpProc(request, 'websiteFunctions/AutoLogin.html', + data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def ConfigurePlugins(self, request=None, userID=None, data=None): + + if ACLManager.CheckForPremFeature('wp-manager'): + currentACL = ACLManager.loadedACL(userID) + userobj = Administrator.objects.get(pk=userID) + + Selectedplugins = wpplugins.objects.filter(owner=userobj) + # data['Selectedplugins'] = wpplugins.objects.filter(ProjectOwner=HostingCompany) + + Data = {'Selectedplugins': Selectedplugins, } + proc = httpProc(request, 'websiteFunctions/WPConfigurePlugins.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def Addnewplugin(self, request=None, userID=None, data=None): + from django.shortcuts import reverse + if ACLManager.CheckForPremFeature('wp-manager'): + currentACL = ACLManager.loadedACL(userID) + adminNames = ACLManager.loadAllUsers(userID) + packagesName = ACLManager.loadPackages(userID, currentACL) + phps = PHPManager.findPHPVersions() + + Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps} + proc = httpProc(request, 'websiteFunctions/WPAddNewPlugin.html', + Data, 'createDatabase') + return proc.render() + + return redirect(reverse('pricing')) + + def SearchOnkeyupPlugin(self, userID=None, data=None): + try: + if ACLManager.CheckForPremFeature('wp-manager'): + currentACL = ACLManager.loadedACL(userID) + + pluginname = data['pluginname'] + # logging.CyberCPLogFileWriter.writeToFile("Plugin Name ....... %s"%pluginname) + + url = "http://api.wordpress.org/plugins/info/1.1/?action=query_plugins&request[search]=%s" % str( + pluginname) + import requests + + res = requests.get(url) + r = res.json() + + # return proc.ajax(1, 'Done', {'plugins': r}) + + data_ret = {'status': 1, 'plugns': r, } + + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': 'Premium feature not available.'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def AddNewpluginAjax(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + + userobj = Administrator.objects.get(pk=userID) + + config = data['config'] + Name = data['Name'] + # pluginname = data['pluginname'] + # logging.CyberCPLogFileWriter.writeToFile("config ....... %s"%config) + # logging.CyberCPLogFileWriter.writeToFile(" Name ....... %s"%Name) + + addpl = wpplugins(Name=Name, config=json.dumps(config), owner=userobj) + addpl.save() + + data_ret = {'status': 1} + + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'AddNewpluginAjax': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def EidtPlugin(self, request=None, userID=None, pluginbID=None): + Data = {} + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + pluginobj = wpplugins.objects.get(pk=pluginbID) + + if ACLManager.CheckIPPluginObjectOwner(currentACL, pluginobj, admin) == 1: + pass + else: + return ACLManager.loadError() + + lmo = json.loads(pluginobj.config) + Data['Selectedplugins'] = lmo + Data['pluginbID'] = pluginbID + Data['BucketName'] = pluginobj.Name + + proc = httpProc(request, 'websiteFunctions/WPEidtPlugin.html', + Data, 'createDatabase') + return proc.render() + + def deletesPlgin(self, userID=None, data=None, ): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + userobj = Administrator.objects.get(pk=userID) + pluginname = data['pluginname'] + pluginbBucketID = data['pluginbBucketID'] + # logging.CyberCPLogFileWriter.writeToFile("pluginbID ....... %s" % pluginbBucketID) + # logging.CyberCPLogFileWriter.writeToFile("pluginname ....... %s" % pluginname) + + obj = wpplugins.objects.get(pk=pluginbBucketID, owner=userobj) + + if ACLManager.CheckIPPluginObjectOwner(currentACL, obj, admin) == 1: + pass + else: + return ACLManager.loadError() + + ab = [] + ab = json.loads(obj.config) + ab.remove(pluginname) + obj.config = json.dumps(ab) + obj.save() + + data_ret = {'status': 1} + + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + except BaseException as msg: + data_ret = {'status': 0, 'deletesPlgin': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def Addplugineidt(self, userID=None, data=None, ): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + userobj = Administrator.objects.get(pk=userID) + pluginname = data['pluginname'] + pluginbBucketID = data['pluginbBucketID'] + + # logging.CyberCPLogFileWriter.writeToFile("pluginbID ....... %s" % pluginbBucketID) + # logging.CyberCPLogFileWriter.writeToFile("pluginname ....... %s" % pluginname) + + pObj = wpplugins.objects.get(pk=pluginbBucketID, owner=userobj) + + if ACLManager.CheckIPPluginObjectOwner(currentACL, pObj, admin) == 1: + pass + else: + return ACLManager.loadError() + + listofplugin = json.loads(pObj.config) + try: + index = listofplugin.index(pluginname) + print('index.....%s' % index) + if (index >= 0): + data_ret = {'status': 0, 'deletesPlgin': 0, 'error_message': str('Already Save in your Plugin lis')} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except: + ab = [] + ab = json.loads(pObj.config) + ab.append(pluginname) + pObj.config = json.dumps(ab) + pObj.save() + + data_ret = {'status': 1} + + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + except BaseException as msg: + data_ret = {'status': 0, 'deletesPlgin': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def modifyWebsite(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + + websitesName = ACLManager.findAllSites(currentACL, userID) + phps = PHPManager.findPHPVersions() + proc = httpProc(request, 'websiteFunctions/modifyWebsite.html', + {'websiteList': websitesName, 'phps': phps}, 'modifyWebsite') + return proc.render() + + def deleteWebsite(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + websitesName = ACLManager.findAllSites(currentACL, userID) + proc = httpProc(request, 'websiteFunctions/deleteWebsite.html', + {'websiteList': websitesName}, 'deleteWebsite') + return proc.render() + + def CreateNewDomain(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + websitesName = ACLManager.findAllSites(currentACL, userID) + + try: + admin = Administrator.objects.get(pk=userID) + if admin.defaultSite == 0: + websites = ACLManager.findWebsiteObjects(currentACL, userID) + admin.defaultSite = websites[0].id + admin.save() + except: + pass + + try: + admin = Administrator.objects.get(pk=userID) + defaultDomain = Websites.objects.get(pk=admin.defaultSite).domain + except: + try: + admin = Administrator.objects.get(pk=userID) + websites = ACLManager.findWebsiteObjects(currentACL, userID) + admin.defaultSite = websites[0].id + admin.save() + defaultDomain = websites[0].domain + except: + defaultDomain='NONE' + + + url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" + data = { + "name": "all", + "IP": ACLManager.GetServerIP() + } + + import requests + response = requests.post(url, data=json.dumps(data)) + Status = response.json()['status'] + + test_domain_status = 0 + + if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: + test_domain_status = 1 + + rnpss = randomPassword.generate_pass(10) + proc = httpProc(request, 'websiteFunctions/createDomain.html', + {'websiteList': websitesName, 'phps': PHPManager.findPHPVersions(), 'Randam_String': rnpss, + 'test_domain_data': test_domain_status, 'defaultSite': defaultDomain}) + return proc.render() + + def siteState(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + + websitesName = ACLManager.findAllSites(currentACL, userID) + + proc = httpProc(request, 'websiteFunctions/suspendWebsite.html', + {'websiteList': websitesName}, 'suspendWebsite') + return proc.render() + + def listWebsites(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + pagination = self.websitePagination(currentACL, userID) + proc = httpProc(request, 'websiteFunctions/listWebsites.html', + {"pagination": pagination}) + return proc.render() + + def listChildDomains(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + adminNames = ACLManager.loadAllUsers(userID) + packagesName = ACLManager.loadPackages(userID, currentACL) + phps = PHPManager.findPHPVersions() + + Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps} + proc = httpProc(request, 'websiteFunctions/listChildDomains.html', + Data) + return proc.render() + + def listCron(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(request.GET.get('domain'), admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + proc = httpProc(request, 'websiteFunctions/listCron.html', + {'domain': request.GET.get('domain')}) + return proc.render() + + def domainAlias(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + aliasManager = AliasManager(self.domain) + noAlias, finalAlisList = aliasManager.fetchAlisForDomains() + + path = "/home/" + self.domain + "/public_html" + + proc = httpProc(request, 'websiteFunctions/domainAlias.html', { + 'masterDomain': self.domain, + 'aliases': finalAlisList, + 'path': path, + 'noAlias': noAlias + }) + return proc.render() + + def FetchWPdata(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core version --skip-plugins --skip-themes --path=%s 2>/dev/null' % ( + Vhuser, FinalPHPPath, path) + version = ProcessUtilities.outputExecutioner(command, None, True) + version = html.escape(version) + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin status litespeed-cache --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, path) + lscachee = ProcessUtilities.outputExecutioner(command) + + if lscachee.find('Status: Active') > -1: + lscache = 1 + else: + lscache = 0 + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp config list --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, path) + stdout = ProcessUtilities.outputExecutioner(command) + debugging = 0 + for items in stdout.split('\n'): + if items.find('WP_DEBUG true constant') > -1: + debugging = 1 + break + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp option get blog_public --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, path) + stdoutput = ProcessUtilities.outputExecutioner(command) + searchindex = int(stdoutput.splitlines()[-1]) + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp maintenance-mode status --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, path) + maintenanceMod = ProcessUtilities.outputExecutioner(command) + + result = maintenanceMod.splitlines()[-1] + if result.find('not active') > -1: + maintenanceMode = 0 + else: + maintenanceMode = 1 + + ##### Check passwd protection + vhostName = wpsite.owner.domain + vhostPassDir = f'/home/{vhostName}' + path = f'{vhostPassDir}/{WPManagerID}' + if os.path.exists(path): + passwd = 1 + else: + passwd = 0 + + #### Check WP cron + command = "sudo -u %s cat %s/wp-config.php" % (Vhuser, wpsite.path) + stdout = ProcessUtilities.outputExecutioner(command) + if stdout.find("'DISABLE_WP_CRON', 'true'") > -1: + wpcron = 1 + else: + wpcron = 0 + + fb = { + 'version': version.rstrip('\n'), + 'lscache': lscache, + 'debugging': debugging, + 'searchIndex': searchindex, + 'maintenanceMode': maintenanceMode, + 'passwordprotection': passwd, + 'wpcron': wpcron + + } + + data_ret = {'status': 1, 'error_message': 'None', 'ret_data': fb} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def GetCurrentPlugins(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin list --skip-plugins --skip-themes --format=json --path=%s' % ( + Vhuser, FinalPHPPath, path) + stdoutput = ProcessUtilities.outputExecutioner(command) + json_data = stdoutput.splitlines()[-1] + + data_ret = {'status': 1, 'error_message': 'None', 'plugins': json_data} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def GetCurrentThemes(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp theme list --skip-plugins --skip-themes --format=json --path=%s' % ( + Vhuser, FinalPHPPath, path) + stdoutput = ProcessUtilities.outputExecutioner(command) + json_data = stdoutput.splitlines()[-1] + + data_ret = {'status': 1, 'error_message': 'None', 'themes': json_data} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def fetchstaging(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + from plogical.phpUtilities import phpUtilities + + json_data = phpUtilities.GetStagingInJson(wpsite.wpstaging_set.all().order_by('-id')) + + data_ret = {'status': 1, 'error_message': 'None', 'wpsites': json_data} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def fetchDatabase(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + php = PHPManager.getPHPString(wpsite.owner.phpSelection) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + command = f'{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config get DB_NAME --skip-plugins --skip-themes --path={wpsite.path} 2>/dev/null' + retStatus, stdoutput = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp, True, None, 1) + + if stdoutput.find('Error:') == -1: + DataBaseName = stdoutput.rstrip("\n") + DataBaseName = html.escape(DataBaseName) + else: + data_ret = {'status': 0, 'error_message': stdoutput} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + command = f'{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config get DB_USER --skip-plugins --skip-themes --path={wpsite.path} 2>/dev/null' + retStatus, stdoutput = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp, True, None, 1) + + if stdoutput.find('Error:') == -1: + DataBaseUser = stdoutput.rstrip("\n") + DataBaseUser = html.escape(DataBaseUser) + else: + data_ret = {'status': 0, 'error_message': stdoutput} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + command = f'{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config get table_prefix --skip-plugins --skip-themes --path={wpsite.path} 2>/dev/null' + retStatus, stdoutput = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp, True, None, 1) + + if stdoutput.find('Error:') == -1: + tableprefix = stdoutput.rstrip("\n") + tableprefix = html.escape(tableprefix) + else: + data_ret = {'status': 0, 'error_message': stdoutput} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + data_ret = {'status': 1, 'error_message': 'None', "DataBaseUser": DataBaseUser, + "DataBaseName": DataBaseName, 'tableprefix': tableprefix} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def SaveUpdateConfig(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + Plugins = data['Plugins'] + Themes = data['Themes'] + AutomaticUpdates = data['AutomaticUpdates'] + + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + + php = PHPManager.getPHPString(wpsite.owner.phpSelection) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + if AutomaticUpdates == 'Disabled': + command = f"{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_AUTO_UPDATE_CORE false --raw --allow-root --path=" + wpsite.path + result = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp) + + if result.find('Success:') == -1: + raise BaseException(result) + elif AutomaticUpdates == 'Minor and Security Updates': + command = f"{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_AUTO_UPDATE_CORE minor --allow-root --path=" + wpsite.path + result = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp) + + if result.find('Success:') == -1: + raise BaseException(result) + else: + command = f"{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_AUTO_UPDATE_CORE true --raw --allow-root --path=" + wpsite.path + result = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp) + + if result.find('Success:') == -1: + raise BaseException(result) + + wpsite.AutoUpdates = AutomaticUpdates + wpsite.PluginUpdates = Plugins + wpsite.ThemeUpdates = Themes + wpsite.save() + + data_ret = {'status': 1, 'error_message': 'None', } + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def DeploytoProduction(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + statgingID = data['StagingID'] + wpsite = WPSites.objects.get(pk=WPManagerID) + StagingObj = WPSites.objects.get(pk=statgingID) + + ### + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + if ACLManager.checkOwnership(StagingObj.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + ### + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['statgingID'] = statgingID + extraArgs['WPid'] = WPManagerID + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + background = ApplicationInstaller('DeploytoProduction', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def WPCreateBackup(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + Backuptype = data['Backuptype'] + + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['WPid'] = WPManagerID + extraArgs['Backuptype'] = Backuptype + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + background = ApplicationInstaller('WPCreateBackup', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def RestoreWPbackupNow(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + backupid = data['backupid'] + DesSiteID = data['DesSite'] + + # try: + # + # bwp = WPSites.objects.get(pk=int(backupid)) + # + # if ACLManager.checkOwnership(bwp.owner.domain, admin, currentACL) == 1: + # pass + # else: + # return ACLManager.loadError() + # + # except: + # pass + # + # dwp = WPSites.objects.get(pk=int(DesSiteID)) + # if ACLManager.checkOwnership(dwp.owner.domain, admin, currentACL) == 1: + # pass + # else: + # return ACLManager.loadError() + + Domain = data['Domain'] + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['backupid'] = backupid + extraArgs['DesSiteID'] = DesSiteID + extraArgs['Domain'] = Domain + extraArgs['path'] = data['path'] + extraArgs['home'] = data['home'] + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + background = ApplicationInstaller('RestoreWPbackupNow', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def SaveBackupConfig(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + ConfigType = data['type'] + if ConfigType == 'SFTP': + Hname = data['Hname'] + Uname = data['Uname'] + Passwd = data['Passwd'] + path = data['path'] + config = { + "Hostname": Hname, + "Username": Uname, + "Password": Passwd, + "Path": path + } + elif ConfigType == "S3": + Provider = data['Provider'] + if Provider == "Backblaze": + S3keyname = data['S3keyname'] + SecertKey = data['SecertKey'] + AccessKey = data['AccessKey'] + EndUrl = data['EndUrl'] + config = { + "Provider": Provider, + "S3keyname": S3keyname, + "SecertKey": SecertKey, + "AccessKey": AccessKey, + "EndUrl": EndUrl + + } + else: + S3keyname = data['S3keyname'] + SecertKey = data['SecertKey'] + AccessKey = data['AccessKey'] + config = { + "Provider": Provider, + "S3keyname": S3keyname, + "SecertKey": SecertKey, + "AccessKey": AccessKey, + + } + + mkobj = RemoteBackupConfig(owner=admin, configtype=ConfigType, config=json.dumps(config)) + mkobj.save() + + time.sleep(1) + + data_ret = {'status': 1, 'error_message': 'None', } + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def SaveBackupSchedule(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + FileRetention = data['FileRetention'] + Backfrequency = data['Backfrequency'] + ScheduleName = data['ScheduleName'] + RemoteConfigID = data['RemoteConfigID'] + BackupType = data['BackupType'] + + RemoteBackupConfigobj = RemoteBackupConfig.objects.get(pk=RemoteConfigID) + Rconfig = json.loads(RemoteBackupConfigobj.config) + + try: + # This code is only supposed to run if backups are s3, not for SFTP + provider = Rconfig['Provider'] + if provider == "Backblaze": + EndURl = Rconfig['EndUrl'] + elif provider == "Amazon": + EndURl = "https://s3.us-east-1.amazonaws.com" + elif provider == "Wasabi": + EndURl = "https://s3.wasabisys.com" + + AccessKey = Rconfig['AccessKey'] + SecertKey = Rconfig['SecertKey'] + + session = boto3.session.Session() + + client = session.client( + 's3', + endpoint_url=EndURl, + aws_access_key_id=AccessKey, + aws_secret_access_key=SecertKey, + verify=False + ) + + ############Creating Bucket + BucketName = randomPassword.generate_pass().lower() + + try: + client.create_bucket(Bucket=BucketName) + except BaseException as msg: + logging.CyberCPLogFileWriter.writeToFile("Creating Bucket Error: %s" % str(msg)) + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + config = { + 'BackupType': BackupType, + 'BucketName': BucketName + } + except BaseException as msg: + config = {'BackupType': BackupType} + pass + + svobj = RemoteBackupSchedule(RemoteBackupConfig=RemoteBackupConfigobj, Name=ScheduleName, + timeintervel=Backfrequency, fileretention=FileRetention, + config=json.dumps(config), + lastrun=str(time.time())) + svobj.save() + + data_ret = {'status': 1, 'error_message': 'None', } + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def AddWPsiteforRemoteBackup(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + WPid = data['WpsiteID'] + RemoteScheduleID = data['RemoteScheduleID'] + + wpsiteobj = WPSites.objects.get(pk=WPid) + WPpath = wpsiteobj.path + VHuser = wpsiteobj.owner.externalApp + PhpVersion = wpsiteobj.owner.phpSelection + php = PHPManager.getPHPString(PhpVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + ####Get DB Name + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp config get DB_NAME --skip-plugins --skip-themes --path=%s' % ( + VHuser, FinalPHPPath, WPpath) + result, stdout = ProcessUtilities.outputExecutioner(command, None, None, None, 1) + + if stdout.find('Error:') > -1: + raise BaseException(stdout) + else: + Finaldbname = stdout.rstrip("\n") + + ## Get DB obj + try: + DBobj = Databases.objects.get(dbName=Finaldbname) + except: + raise BaseException(str("DataBase Not Found")) + RemoteScheduleIDobj = RemoteBackupSchedule.objects.get(pk=RemoteScheduleID) + + svobj = RemoteBackupsites(owner=RemoteScheduleIDobj, WPsites=WPid, database=DBobj.pk) + svobj.save() + + data_ret = {'status': 1, 'error_message': 'None', } + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def UpdateRemoteschedules(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + ScheduleID = data['ScheduleID'] + Frequency = data['Frequency'] + FileRetention = data['FileRetention'] + + scheduleobj = RemoteBackupSchedule.objects.get(pk=ScheduleID) + scheduleobj.timeintervel = Frequency + scheduleobj.fileretention = FileRetention + scheduleobj.save() + + data_ret = {'status': 1, 'error_message': 'None', } + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def ScanWordpressSite(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + allweb = Websites.objects.all() + + childdomain = ChildDomains.objects.all() + + for web in allweb: + webpath = "/home/%s/public_html/" % web.domain + command = "cat %swp-config.php" % webpath + result = ProcessUtilities.outputExecutioner(command, web.externalApp) + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(result) + + if result.find('No such file or directory') == -1: + try: + WPSites.objects.get(path=webpath) + except: + wpobj = WPSites(owner=web, title=web.domain, path=webpath, FinalURL=web.domain, + AutoUpdates="Enabled", PluginUpdates="Enabled", + ThemeUpdates="Enabled", ) + wpobj.save() + + for chlid in childdomain: + childPath = chlid.path.rstrip('/') + + command = "cat %s/wp-config.php" % childPath + result = ProcessUtilities.outputExecutioner(command, chlid.master.externalApp) + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(result) + + if result.find('No such file or directory') == -1: + fChildPath = f'{childPath}/' + try: + WPSites.objects.get(path=fChildPath) + except: + + wpobj = WPSites(owner=chlid.master, title=chlid.domain, path=fChildPath, FinalURL=chlid.domain, + AutoUpdates="Enabled", PluginUpdates="Enabled", + ThemeUpdates="Enabled", ) + wpobj.save() + + data_ret = {'status': 1, 'error_message': 'None', } + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def installwpcore(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + ###fetch WP version + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core version --skip-plugins --skip-themes --path=%s 2>/dev/null' % ( + Vhuser, FinalPHPPath, path) + version = ProcessUtilities.outputExecutioner(command, None, True) + version = version.rstrip("\n") + + ###install wp core + command = f"sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp core download --force --skip-content --version={version} --path={path}" + output = ProcessUtilities.outputExecutioner(command) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', 'result': output} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def dataintegrity(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + ###fetch WP version + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core verify-checksums --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, path) + result = ProcessUtilities.outputExecutioner(command) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', 'result': result} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def UpdatePlugins(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + plugin = data['plugin'] + pluginarray = data['pluginarray'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['plugin'] = plugin + extraArgs['pluginarray'] = pluginarray + extraArgs['FinalPHPPath'] = FinalPHPPath + extraArgs['path'] = path + extraArgs['Vhuser'] = Vhuser + + background = ApplicationInstaller('UpdateWPPlugin', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def UpdateThemes(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + Theme = data['Theme'] + Themearray = data['Themearray'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['Theme'] = Theme + extraArgs['Themearray'] = Themearray + extraArgs['FinalPHPPath'] = FinalPHPPath + extraArgs['path'] = path + extraArgs['Vhuser'] = Vhuser + + background = ApplicationInstaller('UpdateWPTheme', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def DeletePlugins(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + plugin = data['plugin'] + pluginarray = data['pluginarray'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['plugin'] = plugin + extraArgs['pluginarray'] = pluginarray + extraArgs['FinalPHPPath'] = FinalPHPPath + extraArgs['path'] = path + extraArgs['Vhuser'] = Vhuser + + background = ApplicationInstaller('DeletePlugins', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def DeleteThemes(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + Theme = data['Theme'] + Themearray = data['Themearray'] + wpsite = WPSites.objects.get(pk=WPManagerID) + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['Theme'] = Theme + extraArgs['Themearray'] = Themearray + extraArgs['FinalPHPPath'] = FinalPHPPath + extraArgs['path'] = path + extraArgs['Vhuser'] = Vhuser + + background = ApplicationInstaller('DeleteThemes', extraArgs) + background.start() + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def ChangeStatus(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + plugin = data['plugin'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin status %s --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, plugin, path) + stdoutput = ProcessUtilities.outputExecutioner(command) + + if stdoutput.find('Status: Active') > -1: + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin deactivate %s --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, plugin, path) + stdoutput = ProcessUtilities.outputExecutioner(command) + time.sleep(3) + + else: + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin activate %s --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, plugin, path) + stdoutput = ProcessUtilities.outputExecutioner(command) + time.sleep(3) + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def ChangeStatusThemes(self, userID=None, data=None): + try: + # logging.CyberCPLogFileWriter.writeToFile("Error WP ChangeStatusThemes ....... %s") + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + Theme = data['theme'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['Theme'] = Theme + extraArgs['FinalPHPPath'] = FinalPHPPath + extraArgs['path'] = path + extraArgs['Vhuser'] = Vhuser + + background = ApplicationInstaller('ChangeStatusThemes', extraArgs) + background.start() + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def CreateStagingNow(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['StagingDomain'] = data['StagingDomain'] + extraArgs['StagingName'] = data['StagingName'] + extraArgs['WPid'] = data['WPid'] + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + wpsite = WPSites.objects.get(pk=data['WPid']) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + background = ApplicationInstaller('CreateStagingNow', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def UpdateWPSettings(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + siteId = data['siteId'] + setting = data['setting'] + value = data['value'] + + wpsite = WPSites.objects.get(pk=siteId) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) != 1: + return ACLManager.loadError() + + # Get PHP version and path + Webobj = Websites.objects.get(pk=wpsite.owner_id) + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + # Update the appropriate setting based on the setting type + if setting == 'search-indexing': + # Update search engine indexing + command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp option update blog_public {value} --skip-plugins --skip-themes --path={wpsite.path}' + elif setting == 'debugging': + # Update debugging in wp-config.php + if value: + command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_DEBUG true --raw --skip-plugins --skip-themes --path={wpsite.path}' + else: + command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_DEBUG false --raw --skip-plugins --skip-themes --path={wpsite.path}' + elif setting == 'password-protection': + vhostName = wpsite.owner.domain + vhostPassDir = f'/home/{vhostName}' + path = f'{vhostPassDir}/{siteId}' + if value: + # Enable password protection + if not os.path.exists(path): + os.makedirs(path) + htpasswd = f'{path}/.htpasswd' + htaccess = f'{wpsite.path}/.htaccess' + password = randomPassword.generate_pass(12) + + # Create .htpasswd file + command = f"htpasswd -cb {htpasswd} admin {password}" + ProcessUtilities.executioner(command) + + # Create .htaccess file + htaccess_content = f"""AuthType Basic +AuthName "Restricted Access" +AuthUserFile {htpasswd} +Require valid-user""" + with open(htaccess, 'w') as f: + f.write(htaccess_content) + else: + # Disable password protection + if os.path.exists(path): + import shutil + shutil.rmtree(path) + htaccess = f'{wpsite.path}/.htaccess' + if os.path.exists(htaccess): + os.remove(htaccess) + return JsonResponse({'status': 1, 'error_message': 'None'}) + elif setting == 'maintenance-mode': + if value: + command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp maintenance-mode activate --skip-plugins --skip-themes --path={wpsite.path}' + else: + command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp maintenance-mode deactivate --skip-plugins --skip-themes --path={wpsite.path}' + else: + return JsonResponse({'status': 0, 'error_message': 'Invalid setting type'}) + + result = ProcessUtilities.outputExecutioner(command) + if result.find('Error:') > -1: + return JsonResponse({'status': 0, 'error_message': result}) + + return JsonResponse({'status': 1, 'error_message': 'None'}) + + except BaseException as msg: + return JsonResponse({'status': 0, 'error_message': str(msg)}) + + def submitWorpressCreation(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + extraArgs = {} + extraArgs['currentACL'] = currentACL + extraArgs['adminID'] = admin.pk + extraArgs['domainName'] = data['domain'] + extraArgs['WPVersion'] = data['WPVersion'] + extraArgs['blogTitle'] = data['title'] + try: + extraArgs['pluginbucket'] = data['pluginbucket'] + except: + extraArgs['pluginbucket'] = '-1' + extraArgs['adminUser'] = data['adminUser'] + extraArgs['PasswordByPass'] = data['PasswordByPass'] + extraArgs['adminPassword'] = data['PasswordByPass'] + extraArgs['adminEmail'] = data['Email'] + extraArgs['updates'] = data['AutomaticUpdates'] + extraArgs['Plugins'] = data['Plugins'] + extraArgs['Themes'] = data['Themes'] + extraArgs['websiteOwner'] = data['websiteOwner'] + extraArgs['package'] = data['package'] + extraArgs['home'] = data['home'] + extraArgs['apacheBackend'] = data['apacheBackend'] + try: + extraArgs['path'] = data['path'] + if extraArgs['path'] == '': + extraArgs['home'] = '1' + except: + pass + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + background = ApplicationInstaller('wordpressInstallNew', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def submitWebsiteCreation(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + + domain = data['domainName'] + adminEmail = data['adminEmail'] + phpSelection = data['phpSelection'] + packageName = data['package'] + websiteOwner = data['websiteOwner'].lower() + + if data['domainName'].find("cyberpanel.website") > -1: + url = "https://platform.cyberpersons.com/CyberpanelAdOns/CreateDomain" + + domain_data = { + "name": "test-domain", + "IP": ACLManager.GetServerIP(), + "domain": data['domainName'] + } + + import requests + response = requests.post(url, data=json.dumps(domain_data)) + domain_status = response.json()['status'] + + if domain_status == 0: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': response.json()['error_message']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + loggedUser = Administrator.objects.get(pk=userID) + newOwner = Administrator.objects.get(userName=websiteOwner) + + if ACLManager.currentContextPermission(currentACL, 'createWebsite') == 0: + return ACLManager.loadErrorJson('createWebSiteStatus', 0) + + if ACLManager.checkOwnerProtection(currentACL, loggedUser, newOwner) == 0: + return ACLManager.loadErrorJson('createWebSiteStatus', 0) + + if currentACL['admin'] == 0: + if ACLManager.CheckDomainBlackList(domain) == 0: + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Blacklisted domain."} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + if not validators.domain(domain): + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Invalid domain."} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + if not validators.email(adminEmail) or adminEmail.find('--') > -1: + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Invalid email."} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + try: + HA = data['HA'] + externalApp = 'nobody' + except: + externalApp = "".join(re.findall("[a-zA-Z]+", domain))[:5] + str(randint(1000, 9999)) + + try: + counter = 0 + while 1: + tWeb = Websites.objects.get(externalApp=externalApp) + externalApp = '%s%s' % (tWeb.externalApp, str(counter)) + counter = counter + 1 + except: + pass + + tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + + try: + apacheBackend = str(data['apacheBackend']) + except: + apacheBackend = "0" + + try: + mailDomain = str(data['mailDomain']) + except: + mailDomain = "1" + + import pwd + counter = 0 + + ## Create Configurations + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " createVirtualHost --virtualHostName " + domain + \ + " --administratorEmail " + adminEmail + " --phpVersion '" + phpSelection + \ + "' --virtualHostUser " + externalApp + " --ssl " + str(1) + " --dkimCheck " \ + + str(1) + " --openBasedir " + str(data['openBasedir']) + \ + ' --websiteOwner "' + websiteOwner + '" --package "' + packageName + '" --tempStatusPath ' + tempStatusPath + " --apache " + apacheBackend + " --mailDomain %s" % ( + mailDomain) + + ProcessUtilities.popenExecutioner(execPath) + time.sleep(2) + + data_ret = {'status': 1, 'createWebSiteStatus': 1, 'error_message': "None", + 'tempStatusPath': tempStatusPath, 'LinuxUser': externalApp} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def submitDomainCreation(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + try: + alias = data['alias'] + except: + alias = 0 + + masterDomain = data['masterDomain'] + domain = data['domainName'] + + + if alias == 0: + phpSelection = data['phpSelection'] + path = data['path'] + else: + + ### if master website have apache then create this sub-domain also as ols + apache + + apachePath = ApacheVhost.configBasePath + masterDomain + '.conf' + + if os.path.exists(apachePath): + data['apacheBackend'] = 1 + + phpSelection = Websites.objects.get(domain=masterDomain).phpSelection + + tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + + if not validators.domain(domain): + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Invalid domain."} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + if data['domainName'].find("cyberpanel.website") > -1: + url = "https://platform.cyberpersons.com/CyberpanelAdOns/CreateDomain" + + domain_data = { + "name": "test-domain", + "IP": ACLManager.GetServerIP(), + "domain": data['domainName'] + } + + import requests + response = requests.post(url, data=json.dumps(domain_data)) + domain_status = response.json()['status'] + + if domain_status == 0: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': response.json()['error_message']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + if ACLManager.checkOwnership(masterDomain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('createWebSiteStatus', 0) + + if data['path'].find('..') > -1: + return ACLManager.loadErrorJson('createWebSiteStatus', 0) + + if currentACL['admin'] != 1: + data['openBasedir'] = 1 + + if alias == 0: + + if len(path) > 0: + path = path.lstrip("/") + path = "/home/" + masterDomain + "/" + path + else: + path = "/home/" + masterDomain + "/" + domain + else: + path = f'/home/{masterDomain}/public_html' + + try: + apacheBackend = str(data['apacheBackend']) + except: + apacheBackend = "0" + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + + execPath = execPath + " createDomain --masterDomain " + masterDomain + " --virtualHostName " + domain + \ + " --phpVersion '" + phpSelection + "' --ssl " + str(1) + " --dkimCheck " + str(1) \ + + " --openBasedir " + str(data['openBasedir']) + ' --path ' + path + ' --websiteOwner ' \ + + admin.userName + ' --tempStatusPath ' + tempStatusPath + " --apache " + apacheBackend + f' --aliasDomain {str(alias)}' + + ProcessUtilities.popenExecutioner(execPath) + time.sleep(2) + + data_ret = {'status': 1, 'createWebSiteStatus': 1, 'error_message': "None", + 'tempStatusPath': tempStatusPath} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def fetchDomains(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + masterDomain = data['masterDomain'] + + try: + alias = data['alias'] + except: + alias = 0 + + if ACLManager.checkOwnership(masterDomain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('fetchStatus', 0) + + cdManager = ChildDomainManager(masterDomain) + json_data = cdManager.findChildDomainsJson(alias) + + final_json = json.dumps({'status': 1, 'fetchStatus': 1, 'error_message': "None", "data": json_data}) + return HttpResponse(final_json) + + except BaseException as msg: + final_dic = {'status': 0, 'fetchStatus': 0, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def searchWebsites(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + try: + json_data = self.searchWebsitesJson(currentACL, userID, data['patternAdded']) + except BaseException as msg: + tempData = {} + tempData['page'] = 1 + return self.getFurtherAccounts(userID, tempData) + + pagination = self.websitePagination(currentACL, userID) + final_dic = {'status': 1, 'listWebSiteStatus': 1, 'error_message': "None", "data": json_data, + 'pagination': pagination} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + except BaseException as msg: + dic = {'status': 1, 'listWebSiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def searchChilds(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + + websites = ACLManager.findWebsiteObjects(currentACL, userID) + childDomains = [] + + for web in websites: + for child in web.childdomains_set.filter(domain__istartswith=data['patternAdded']): + childDomains.append(child) + + json_data = self.findChildsListJson(childDomains) + + final_dic = {'status': 1, 'listWebSiteStatus': 1, 'error_message': "None", "data": json_data} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + except BaseException as msg: + dic = {'status': 1, 'listWebSiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def getFurtherAccounts(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + pageNumber = int(data['page']) + json_data = self.findWebsitesJson(currentACL, userID, pageNumber) + pagination = self.websitePagination(currentACL, userID) + final_dic = {'status': 1, 'listWebSiteStatus': 1, 'error_message': "None", "data": json_data, + 'pagination': pagination} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + except BaseException as msg: + dic = {'status': 1, 'listWebSiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def fetchWebsitesList(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + pageNumber = int(data['page']) + recordsToShow = int(data['recordsToShow']) + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(f'Fetch sites step 1..') + + endPageNumber, finalPageNumber = self.recordsPointer(pageNumber, recordsToShow) + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(f'Fetch sites step 2..') + + websites = ACLManager.findWebsiteObjects(currentACL, userID) + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(f'Fetch sites step 3..') + + pagination = self.getPagination(len(websites), recordsToShow) + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(f'Fetch sites step 4..') + + json_data = self.findWebsitesListJson(websites[finalPageNumber:endPageNumber]) + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(f'Fetch sites step 5..') + + final_dic = {'status': 1, 'listWebSiteStatus': 1, 'error_message': "None", "data": json_data, + 'pagination': pagination} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + except BaseException as msg: + dic = {'status': 1, 'listWebSiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def fetchChildDomainsMain(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + pageNumber = int(data['page']) + recordsToShow = int(data['recordsToShow']) + + endPageNumber, finalPageNumber = self.recordsPointer(pageNumber, recordsToShow) + websites = ACLManager.findWebsiteObjects(currentACL, userID) + childDomains = [] + + for web in websites: + for child in web.childdomains_set.filter(alais=0): + if child.domain == f'mail.{web.domain}': + pass + else: + childDomains.append(child) + + pagination = self.getPagination(len(childDomains), recordsToShow) + json_data = self.findChildsListJson(childDomains[finalPageNumber:endPageNumber]) + + final_dic = {'status': 1, 'listWebSiteStatus': 1, 'error_message': "None", "data": json_data, + 'pagination': pagination} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + except BaseException as msg: + dic = {'status': 1, 'listWebSiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def findWebsitesListJson(self, websites): + try: + ipFile = "/etc/cyberpanel/machineIP" + f = open(ipFile) + ipData = f.read() + ipAddress = ipData.split('\n', 1)[0] + except BaseException as msg: + logging.CyberCPLogFileWriter.writeToFile("Failed to read machine IP, error:" + str(msg)) + ipAddress = "192.168.100.1" + + json_data = [] + + for website in websites: + wp_sites = [] + try: + wp_sites = WPSites.objects.filter(owner=website) + wp_sites = [{ + 'id': wp.id, + 'title': wp.title, + 'url': wp.FinalURL, + 'version': wp.version if hasattr(wp, 'version') else 'Unknown', + 'phpVersion': wp.phpVersion if hasattr(wp, 'phpVersion') else 'Unknown' + } for wp in wp_sites] + except: + pass + + # Calculate disk usage + DiskUsage, DiskUsagePercentage, bwInMB, bwUsage = virtualHostUtilities.FindStats(website) + diskUsed = "%sMB" % str(DiskUsage) + + # Convert numeric state to text + state = "Active" if website.state == 1 else "Suspended" + + json_data.append({ + 'domain': website.domain, + 'adminEmail': website.adminEmail, + 'phpVersion': website.phpSelection, + 'state': state, + 'ipAddress': ipAddress, + 'package': website.package.packageName, + 'admin': website.admin.userName, + 'wp_sites': wp_sites, + 'diskUsed': diskUsed + }) + return json.dumps(json_data) + + + + def findDockersitesListJson(self, Dockersite): + + json_data = "[" + checker = 0 + + try: + ipFile = "/etc/cyberpanel/machineIP" + f = open(ipFile) + ipData = f.read() + ipAddress = ipData.split('\n', 1)[0] + except BaseException as msg: + logging.CyberCPLogFileWriter.writeToFile("Failed to read machine IP, error:" + str(msg)) + ipAddress = "192.168.100.1" + + from plogical.phpUtilities import phpUtilities + for items in Dockersite: + website = Websites.objects.get(pk=items.admin.pk) + vhFile = f'/usr/local/lsws/conf/vhosts/{website.domain}/vhost.conf' + + try: + PHPVersionActual = phpUtilities.WrapGetPHPVersionFromFileToGetVersionWithPHP(website) + except: + PHPVersionActual = 'PHP 8.1' + + + if items.state == 0: + state = "Suspended" + else: + state = "Active" + + dpkg = PackageAssignment.objects.get(user=website.admin) + + + dic = {'id':items.pk, 'domain': website.domain, 'adminEmail': website.adminEmail, 'ipAddress': ipAddress, + 'admin': website.admin.userName, 'package': dpkg.package.Name, 'state': state, + 'CPU': int(items.CPUsMySQL)+int(items.CPUsSite), 'Ram': int(items.MemorySite)+int(items.MemoryMySQL), 'phpVersion': PHPVersionActual } + + if checker == 0: + json_data = json_data + json.dumps(dic) + checker = 1 + else: + json_data = json_data + ',' + json.dumps(dic) + + json_data = json_data + ']' + + return json_data + + def findChildsListJson(self, childs): + + json_data = "[" + checker = 0 + + try: + ipFile = "/etc/cyberpanel/machineIP" + f = open(ipFile) + ipData = f.read() + ipAddress = ipData.split('\n', 1)[0] + except BaseException as msg: + logging.CyberCPLogFileWriter.writeToFile("Failed to read machine IP, error:" + str(msg)) + ipAddress = "192.168.100.1" + + for items in childs: + + dic = {'domain': items.domain, 'masterDomain': items.master.domain, 'adminEmail': items.master.adminEmail, + 'ipAddress': ipAddress, + 'admin': items.master.admin.userName, 'package': items.master.package.packageName, + 'path': items.path} + + if checker == 0: + json_data = json_data + json.dumps(dic) + checker = 1 + else: + json_data = json_data + ',' + json.dumps(dic) + + json_data = json_data + ']' + + return json_data + + def recordsPointer(self, page, toShow): + finalPageNumber = ((page * toShow)) - toShow + endPageNumber = finalPageNumber + toShow + return endPageNumber, finalPageNumber + + def getPagination(self, records, toShow): + pages = float(records) / float(toShow) + + pagination = [] + counter = 1 + + if pages <= 1.0: + pages = 1 + pagination.append(counter) + else: + pages = ceil(pages) + finalPages = int(pages) + 1 + + for i in range(1, finalPages): + pagination.append(counter) + counter = counter + 1 + + return pagination + + def submitWebsiteDeletion(self, userID=None, data=None): + try: + if data['websiteName'].find("cyberpanel.website") > -1: + url = "https://platform.cyberpersons.com/CyberpanelAdOns/DeleteDomain" + + domain_data = { + "name": "test-domain", + "IP": ACLManager.GetServerIP(), + "domain": data['websiteName'] + } + + import requests + response = requests.post(url, data=json.dumps(domain_data)) + + currentACL = ACLManager.loadedACL(userID) + if ACLManager.currentContextPermission(currentACL, 'deleteWebsite') == 0: + return ACLManager.loadErrorJson('websiteDeleteStatus', 0) + + websiteName = data['websiteName'] + + admin = Administrator.objects.get(pk=userID) + if ACLManager.checkOwnership(websiteName, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('websiteDeleteStatus', 0) + + ## Deleting master domain + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " deleteVirtualHostConfigurations --virtualHostName " + websiteName + ProcessUtilities.popenExecutioner(execPath) + + ### delete site from dgdrive backups + + try: + + from websiteFunctions.models import GDriveSites + GDriveSites.objects.filter(domain=websiteName).delete() + except: + pass + + data_ret = {'status': 1, 'websiteDeleteStatus': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'websiteDeleteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def submitDomainDeletion(self, userID=None, data=None): + try: + + if data['websiteName'].find("cyberpanel.website") > -1: + url = "https://platform.cyberpersons.com/CyberpanelAdOns/DeleteDomain" + + domain_data = { + "name": "test-domain", + "IP": ACLManager.GetServerIP(), + "domain": data['websiteName'] + } + + import requests + response = requests.post(url, data=json.dumps(domain_data)) + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + websiteName = data['websiteName'] + + try: + DeleteDocRoot = int(data['DeleteDocRoot']) + except: + DeleteDocRoot = 0 + + if ACLManager.checkOwnership(websiteName, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('websiteDeleteStatus', 0) + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " deleteDomain --virtualHostName " + websiteName + ' --DeleteDocRoot %s' % ( + str(DeleteDocRoot)) + ProcessUtilities.outputExecutioner(execPath) + + data_ret = {'status': 1, 'websiteDeleteStatus': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'websiteDeleteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def submitWebsiteStatus(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + if ACLManager.currentContextPermission(currentACL, 'suspendWebsite') == 0: + return ACLManager.loadErrorJson('websiteStatus', 0) + + websiteName = data['websiteName'] + state = data['state'] + + website = Websites.objects.get(domain=websiteName) + + admin = Administrator.objects.get(pk=userID) + if ACLManager.checkOwnership(websiteName, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('websiteStatus', 0) + + if state == "Suspend": + confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + websiteName + command = "mv " + confPath + " " + confPath + "-suspended" + ProcessUtilities.popenExecutioner(command) + + childDomains = website.childdomains_set.all() + + for items in childDomains: + confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + items.domain + command = "mv " + confPath + " " + confPath + "-suspended" + ProcessUtilities.executioner(command) + + installUtilities.reStartLiteSpeedSocket() + website.state = 0 + else: + confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + websiteName + + command = "mv " + confPath + "-suspended" + " " + confPath + ProcessUtilities.executioner(command) + + command = "chown -R " + "lsadm" + ":" + "lsadm" + " " + confPath + ProcessUtilities.popenExecutioner(command) + + childDomains = website.childdomains_set.all() + + for items in childDomains: + confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + items.domain + + command = "mv " + confPath + "-suspended" + " " + confPath + ProcessUtilities.executioner(command) + + command = "chown -R " + "lsadm" + ":" + "lsadm" + " " + confPath + ProcessUtilities.popenExecutioner(command) + + installUtilities.reStartLiteSpeedSocket() + website.state = 1 + + website.save() + + data_ret = {'websiteStatus': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + + data_ret = {'websiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def submitWebsiteModify(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + if ACLManager.currentContextPermission(currentACL, 'modifyWebsite') == 0: + return ACLManager.loadErrorJson('modifyStatus', 0) + + admin = Administrator.objects.get(pk=userID) + if ACLManager.checkOwnership(data['websiteToBeModified'], admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('websiteDeleteStatus', 0) + + packs = ACLManager.loadPackages(userID, currentACL) + admins = ACLManager.loadAllUsers(userID) + + ## Get packs name + + json_data = "[" + checker = 0 + + for items in packs: + dic = {"pack": items} + + if checker == 0: + json_data = json_data + json.dumps(dic) + checker = 1 + else: + json_data = json_data + ',' + json.dumps(dic) + + json_data = json_data + ']' + + ### Get admin names + + admin_data = "[" + checker = 0 + + for items in admins: + dic = {"adminNames": items} + + if checker == 0: + admin_data = admin_data + json.dumps(dic) + checker = 1 + else: + admin_data = admin_data + ',' + json.dumps(dic) + + admin_data = admin_data + ']' + + websiteToBeModified = data['websiteToBeModified'] + + modifyWeb = Websites.objects.get(domain=websiteToBeModified) + + email = modifyWeb.adminEmail + currentPack = modifyWeb.package.packageName + owner = modifyWeb.admin.userName + + data_ret = {'status': 1, 'modifyStatus': 1, 'error_message': "None", "adminEmail": email, + "packages": json_data, "current_pack": currentPack, "adminNames": admin_data, + 'currentAdmin': owner} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + + except BaseException as msg: + dic = {'status': 0, 'modifyStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def fetchWebsiteDataJSON(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + if ACLManager.currentContextPermission(currentACL, 'createWebsite') == 0: + return ACLManager.loadErrorJson('createWebSiteStatus', 0) + + packs = ACLManager.loadPackages(userID, currentACL) + admins = ACLManager.loadAllUsers(userID) + + ## Get packs name + + json_data = "[" + checker = 0 + + for items in packs: + dic = {"pack": items} + + if checker == 0: + json_data = json_data + json.dumps(dic) + checker = 1 + else: + json_data = json_data + ',' + json.dumps(dic) + + json_data = json_data + ']' + + ### Get admin names + + admin_data = "[" + checker = 0 + + for items in admins: + dic = {"adminNames": items} + + if checker == 0: + admin_data = admin_data + json.dumps(dic) + checker = 1 + else: + admin_data = admin_data + ',' + json.dumps(dic) + + admin_data = admin_data + ']' + + data_ret = {'status': 1, 'error_message': "None", + "packages": json_data, "adminNames": admin_data} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + + except BaseException as msg: + dic = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def saveWebsiteChanges(self, userID=None, data=None): + try: + domain = data['domain'] + package = data['packForWeb'] + email = data['email'] + phpVersion = data['phpVersion'] + newUser = data['admin'] + + currentACL = ACLManager.loadedACL(userID) + if ACLManager.currentContextPermission(currentACL, 'modifyWebsite') == 0: + return ACLManager.loadErrorJson('saveStatus', 0) + + admin = Administrator.objects.get(pk=userID) + if ACLManager.checkOwnership(domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('websiteDeleteStatus', 0) + + newOwner = Administrator.objects.get(userName=newUser) + if ACLManager.checkUserOwnerShip(currentACL, admin, newOwner) == 1: + pass + else: + return ACLManager.loadErrorJson('websiteDeleteStatus', 0) + + confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + domain + completePathToConfigFile = confPath + "/vhost.conf" + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " changePHP --phpVersion '" + phpVersion + "' --path " + completePathToConfigFile + ProcessUtilities.popenExecutioner(execPath) + + #### + + newOwner = Administrator.objects.get(userName=newUser) + + modifyWeb = Websites.objects.get(domain=domain) + webpack = Package.objects.get(packageName=package) + + modifyWeb.package = webpack + modifyWeb.adminEmail = email + modifyWeb.phpSelection = phpVersion + modifyWeb.admin = newOwner + + modifyWeb.save() + + ## Fix https://github.com/usmannasir/cyberpanel/issues/998 + + # from plogical.IncScheduler import IncScheduler + # isPU = IncScheduler('CalculateAndUpdateDiskUsage', {}) + # isPU.start() + + command = '/usr/local/CyberCP/bin/python /usr/local/CyberCP/plogical/IncScheduler.py UpdateDiskUsageForce' + ProcessUtilities.outputExecutioner(command) + + ## + + data_ret = {'status': 1, 'saveStatus': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'saveStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def loadDomainHome(self, request=None, userID=None, data=None): + + if Websites.objects.filter(domain=self.domain).exists(): + + currentACL = ACLManager.loadedACL(userID) + website = Websites.objects.get(domain=self.domain) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + Data = {} + + marketingStatus = emACL.checkIfEMEnabled(admin.userName) + + Data['marketingStatus'] = marketingStatus + Data['ftpTotal'] = website.package.ftpAccounts + Data['ftpUsed'] = website.users_set.all().count() + + Data['databasesUsed'] = website.databases_set.all().count() + Data['databasesTotal'] = website.package.dataBases + + Data['domain'] = self.domain + + DiskUsage, DiskUsagePercentage, bwInMB, bwUsage = virtualHostUtilities.FindStats(website) + + ## bw usage calculations + + Data['bwInMBTotal'] = website.package.bandwidth + Data['bwInMB'] = bwInMB + Data['bwUsage'] = bwUsage + + if DiskUsagePercentage > 100: + DiskUsagePercentage = 100 + + Data['diskUsage'] = DiskUsagePercentage + Data['diskInMB'] = DiskUsage + Data['diskInMBTotal'] = website.package.diskSpace + + Data['phps'] = PHPManager.findPHPVersions() + + servicePath = '/home/cyberpanel/postfix' + if os.path.exists(servicePath): + Data['email'] = 1 + else: + Data['email'] = 0 + + ## Getting SSL Information + try: + import OpenSSL + from datetime import datetime + filePath = '/etc/letsencrypt/live/%s/fullchain.pem' % (self.domain) + x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, + open(filePath, 'r').read()) + expireData = x509.get_notAfter().decode('ascii') + finalDate = datetime.strptime(expireData, '%Y%m%d%H%M%SZ') + + now = datetime.now() + diff = finalDate - now + Data['viewSSL'] = 1 + Data['days'] = str(diff.days) + Data['authority'] = x509.get_issuer().get_components()[1][1].decode('utf-8') + + if Data['authority'] == 'Denial': + Data['authority'] = '%s has SELF-SIGNED SSL.' % (self.domain) + else: + Data['authority'] = '%s has SSL from %s.' % (self.domain, Data['authority']) + + except BaseException as msg: + Data['viewSSL'] = 0 + logging.CyberCPLogFileWriter.writeToFile(str(msg)) + + servicePath = '/home/cyberpanel/pureftpd' + if os.path.exists(servicePath): + Data['ftp'] = 1 + else: + Data['ftp'] = 0 + + proc = httpProc(request, 'websiteFunctions/website.html', Data) + return proc.render() + else: + proc = httpProc(request, 'websiteFunctions/website.html', + {"error": 1, "domain": "This domain does not exists."}) + return proc.render() + + def launchChild(self, request=None, userID=None, data=None): + + if ChildDomains.objects.filter(domain=self.childDomain).exists(): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + website = Websites.objects.get(domain=self.domain) + + Data = {} + + Data['ftpTotal'] = website.package.ftpAccounts + Data['ftpUsed'] = website.users_set.all().count() + + Data['databasesUsed'] = website.databases_set.all().count() + Data['databasesTotal'] = website.package.dataBases + + Data['domain'] = self.domain + Data['childDomain'] = self.childDomain + + DiskUsage, DiskUsagePercentage, bwInMB, bwUsage = virtualHostUtilities.FindStats(website) + + ## bw usage calculations + + Data['bwInMBTotal'] = website.package.bandwidth + Data['bwInMB'] = bwInMB + Data['bwUsage'] = bwUsage + + if DiskUsagePercentage > 100: + DiskUsagePercentage = 100 + + Data['diskUsage'] = DiskUsagePercentage + Data['diskInMB'] = DiskUsage + Data['diskInMBTotal'] = website.package.diskSpace + + Data['phps'] = PHPManager.findPHPVersions() + + servicePath = '/home/cyberpanel/postfix' + if os.path.exists(servicePath): + Data['email'] = 1 + else: + Data['email'] = 0 + + servicePath = '/home/cyberpanel/pureftpd' + if os.path.exists(servicePath): + Data['ftp'] = 1 + else: + Data['ftp'] = 0 + + ## Getting SSL Information + try: + import OpenSSL + from datetime import datetime + filePath = '/etc/letsencrypt/live/%s/fullchain.pem' % (self.childDomain) + x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, + open(filePath, 'r').read()) + expireData = x509.get_notAfter().decode('ascii') + finalDate = datetime.strptime(expireData, '%Y%m%d%H%M%SZ') + + now = datetime.now() + diff = finalDate - now + Data['viewSSL'] = 1 + Data['days'] = str(diff.days) + Data['authority'] = x509.get_issuer().get_components()[1][1].decode('utf-8') + + if Data['authority'] == 'Denial': + Data['authority'] = '%s has SELF-SIGNED SSL.' % (self.childDomain) + else: + Data['authority'] = '%s has SSL from %s.' % (self.childDomain, Data['authority']) + + except BaseException as msg: + Data['viewSSL'] = 0 + logging.CyberCPLogFileWriter.writeToFile(str(msg)) + + proc = httpProc(request, 'websiteFunctions/launchChild.html', Data) + return proc.render() + else: + proc = httpProc(request, 'websiteFunctions/launchChild.html', + {"error": 1, "domain": "This child domain does not exists"}) + return proc.render() + + def getDataFromLogFile(self, userID=None, data=None): + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + logType = data['logType'] + self.domain = data['virtualHost'] + page = data['page'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('logstatus', 0) + + if logType == 1: + fileName = "/home/" + self.domain + "/logs/" + self.domain + ".access_log" + else: + fileName = "/home/" + self.domain + "/logs/" + self.domain + ".error_log" + + command = 'ls -la %s' % fileName + result = ProcessUtilities.outputExecutioner(command) + + if result.find('->') > -1: + final_json = json.dumps( + {'status': 0, 'logstatus': 0, + 'error_message': "Symlink attack."}) + return HttpResponse(final_json) + + ## get Logs + website = Websites.objects.get(domain=self.domain) + + output = virtualHostUtilities.getAccessLogs(fileName, page, website.externalApp) + + if output.find("1,None") > -1: + final_json = json.dumps( + {'status': 0, 'logstatus': 0, + 'error_message': "Not able to fetch logs, see CyberPanel main log file, Error: %s" % (output)}) + return HttpResponse(final_json) + + ## get log ends here. + + data = output.split("\n") + + json_data = "[" + checker = 0 + + for items in reversed(data): + if len(items) > 10: + logData = items.split(" ") + domain = logData[5].strip('"') + ipAddress = logData[0].strip('"') + time = (logData[3]).strip("[").strip("]") + resource = logData[6].strip('"') + size = logData[9].replace('"', '') + + dic = {'domain': domain, + 'ipAddress': ipAddress, + 'time': time, + 'resource': resource, + 'size': size, + } + + if checker == 0: + json_data = json_data + json.dumps(dic) + checker = 1 + else: + json_data = json_data + ',' + json.dumps(dic) + + json_data = json_data + ']' + final_json = json.dumps({'status': 1, 'logstatus': 1, 'error_message': "None", "data": json_data}) + return HttpResponse(final_json) + + def fetchErrorLogs(self, userID=None, data=None): + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['virtualHost'] + page = data['page'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('logstatus', 0) + + fileName = "/home/" + self.domain + "/logs/" + self.domain + ".error_log" + + command = 'ls -la %s' % fileName + result = ProcessUtilities.outputExecutioner(command) + + if result.find('->') > -1: + final_json = json.dumps( + {'status': 0, 'logstatus': 0, + 'error_message': "Symlink attack."}) + return HttpResponse(final_json) + + ## get Logs + website = Websites.objects.get(domain=self.domain) + + output = virtualHostUtilities.getErrorLogs(fileName, page, website.externalApp) + + if output.find("1,None") > -1: + final_json = json.dumps( + {'status': 0, 'logstatus': 0, 'error_message': "Not able to fetch logs, see CyberPanel main log file!"}) + return HttpResponse(final_json) + + ## get log ends here. + + final_json = json.dumps({'status': 1, 'logstatus': 1, 'error_message': "None", "data": output}) + return HttpResponse(final_json) + + def getDataFromConfigFile(self, userID=None, data=None): + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + self.domain = data['virtualHost'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('configstatus', 0) + + command = 'cat %s' % ('/usr/local/lsws/conf/dvhost_redis.conf') + + if ProcessUtilities.outputExecutioner(command).find('127.0.0.1') == -1: + filePath = installUtilities.Server_root_path + "/conf/vhosts/" + self.domain + "/vhost.conf" + + command = 'cat ' + filePath + configData = ProcessUtilities.outputExecutioner(command, 'lsadm') + + if len(configData) == 0: + status = {'status': 0, "configstatus": 0, "error_message": "Configuration file is currently empty!"} + + final_json = json.dumps(status) + return HttpResponse(final_json) + + else: + command = 'redis-cli get "vhost:%s"' % (self.domain) + configData = ProcessUtilities.outputExecutioner(command) + configData = '#### This configuration is fetched from redis as Redis-Mass Hosting is being used.\n%s' % ( + configData) + + status = {'status': 1, "configstatus": 1, "configData": configData} + final_json = json.dumps(status) + return HttpResponse(final_json) + + def saveConfigsToFile(self, userID=None, data=None): + + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] != 1: + return ACLManager.loadErrorJson('configstatus', 0) + + configData = data['configData'] + self.domain = data['virtualHost'] + + if len(configData) == 0: + status = {"configstatus": 0, 'error_message': 'Error: you are trying to save empty vhost file, your website will stop working.'} + + final_json = json.dumps(status) + return HttpResponse(final_json) + + + command = 'cat %s' % ('/usr/local/lsws/conf/dvhost_redis.conf') + + if ProcessUtilities.outputExecutioner(command).find('127.0.0.1') == -1: + + mailUtilities.checkHome() + + tempPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + + vhost = open(tempPath, "w") + + vhost.write(configData) + + vhost.close() + + ## writing data temporary to file + + filePath = installUtilities.Server_root_path + "/conf/vhosts/" + self.domain + "/vhost.conf" + + ## save configuration data + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " saveVHostConfigs --path " + filePath + " --tempPath " + tempPath + + output = ProcessUtilities.outputExecutioner(execPath) + + if output.find("1,None") > -1: + status = {"configstatus": 1} + + final_json = json.dumps(status) + return HttpResponse(final_json) + else: + data_ret = {'configstatus': 0, 'error_message': output} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + ## save configuration data ends + else: + command = "redis-cli set vhost:%s '%s'" % (self.domain, configData.replace( + '#### This configuration is fetched from redis as Redis-Mass Hosting is being used.\n', '')) + ProcessUtilities.executioner(command) + + status = {"configstatus": 1} + + final_json = json.dumps(status) + return HttpResponse(final_json) + + def getRewriteRules(self, userID=None, data=None): + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + self.domain = data['virtualHost'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('rewriteStatus', 0) + + try: + childDom = ChildDomains.objects.get(domain=self.domain) + filePath = childDom.path + '/.htaccess' + externalApp = childDom.master.externalApp + except: + website = Websites.objects.get(domain=self.domain) + externalApp = website.externalApp + filePath = "/home/" + self.domain + "/public_html/.htaccess" + + try: + command = 'cat %s' % (filePath) + rewriteRules = ProcessUtilities.outputExecutioner(command, externalApp) + + if len(rewriteRules) == 0: + status = {"rewriteStatus": 1, "error_message": "Rules file is currently empty"} + final_json = json.dumps(status) + return HttpResponse(final_json) + + status = {"rewriteStatus": 1, "rewriteRules": rewriteRules} + + final_json = json.dumps(status) + return HttpResponse(final_json) + + except BaseException as msg: + status = {"rewriteStatus": 1, "error_message": str(msg), "rewriteRules": ""} + final_json = json.dumps(status) + return HttpResponse(final_json) + + def saveRewriteRules(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + self.domain = data['virtualHost'] + rewriteRules = data['rewriteRules'].encode('utf-8') + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('rewriteStatus', 0) + + ## writing data temporary to file + + mailUtilities.checkHome() + tempPath = "/tmp/" + str(randint(1000, 9999)) + vhost = open(tempPath, "wb") + vhost.write(rewriteRules) + vhost.close() + + ## writing data temporary to file + + try: + childDomain = ChildDomains.objects.get(domain=self.domain) + filePath = childDomain.path + '/.htaccess' + externalApp = childDomain.master.externalApp + except: + filePath = "/home/" + self.domain + "/public_html/.htaccess" + website = Websites.objects.get(domain=self.domain) + externalApp = website.externalApp + + ## save configuration data + + command = 'cp %s %s' % (tempPath, filePath) + ProcessUtilities.executioner(command, externalApp) + + command = 'rm -f %s' % (tempPath) + ProcessUtilities.executioner(command, 'cyberpanel') + + installUtilities.reStartLiteSpeedSocket() + status = {"rewriteStatus": 1, 'error_message': 'None'} + final_json = json.dumps(status) + return HttpResponse(final_json) + except BaseException as msg: + status = {"rewriteStatus": 0, 'error_message': str(msg)} + final_json = json.dumps(status) + return HttpResponse(final_json) + + def saveSSL(self, userID=None, data=None): + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + self.domain = data['virtualHost'] + key = data['key'] + cert = data['cert'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('sslStatus', 0) + + mailUtilities.checkHome() + + ## writing data temporary to file + + tempKeyPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + vhost = open(tempKeyPath, "w") + vhost.write(key) + vhost.close() + + tempCertPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + vhost = open(tempCertPath, "w") + vhost.write(cert) + vhost.close() + + ## writing data temporary to file + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " saveSSL --virtualHostName " + self.domain + " --tempKeyPath " + tempKeyPath + " --tempCertPath " + tempCertPath + output = ProcessUtilities.outputExecutioner(execPath) + + if output.find("1,None") > -1: + data_ret = {'sslStatus': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + logging.CyberCPLogFileWriter.writeToFile( + output) + data_ret = {'sslStatus': 0, 'error_message': output} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def changePHP(self, userID=None, data=None): + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + self.domain = data['childDomain'] + phpVersion = data['phpSelection'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('changePHP', 0) + + confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + self.domain + completePathToConfigFile = confPath + "/vhost.conf" + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " changePHP --phpVersion '" + phpVersion + "' --path " + completePathToConfigFile + ProcessUtilities.popenExecutioner(execPath) + + try: + website = Websites.objects.get(domain=self.domain) + website.phpSelection = data['phpSelection'] + website.save() + + ### check if there are any alias domains under the main website and then change php for them too + + for alias in website.childdomains_set.filter(alais=1): + + try: + + confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + alias.domain + completePathToConfigFile = confPath + "/vhost.conf" + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " changePHP --phpVersion '" + phpVersion + "' --path " + completePathToConfigFile + ProcessUtilities.popenExecutioner(execPath) + except BaseException as msg: + logging.CyberCPLogFileWriter.writeToFile(f'Error changing PHP for alias: {str(msg)}') + + + except: + website = ChildDomains.objects.get(domain=self.domain) + website.phpSelection = data['phpSelection'] + website.save() + + data_ret = {'status': 1, 'changePHP': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def getWebsiteCron(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + self.domain = data['domain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('getWebsiteCron', 0) + + website = Websites.objects.get(domain=self.domain) + + if Websites.objects.filter(domain=self.domain).exists(): + pass + else: + dic = {'getWebsiteCron': 0, 'error_message': 'You do not own this domain'} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + CronUtil.CronPrem(1) + + crons = [] + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" + execPath = execPath + " getWebsiteCron --externalApp " + website.externalApp + + f = ProcessUtilities.outputExecutioner(execPath, website.externalApp) + + CronUtil.CronPrem(0) + + if ProcessUtilities.decideDistro() == ProcessUtilities.centos or ProcessUtilities.decideDistro() == ProcessUtilities.cent8: + cronPath = "/var/spool/cron/" + website.externalApp + else: + cronPath = "/var/spool/cron/crontabs/" + website.externalApp + + if f.find('Permission denied') > -1: + command = 'chmod 644 %s' % (cronPath) + ProcessUtilities.executioner(command) + + command = 'chown %s:%s %s' % (website.externalApp, website.externalApp, cronPath) + ProcessUtilities.executioner(command) + + f = ProcessUtilities.outputExecutioner(execPath, website.externalApp) + + if f.find("0,CyberPanel,") > -1: + data_ret = {'getWebsiteCron': 0, "user": website.externalApp, "crons": {}} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + + counter = 0 + for line in f.split("\n"): + if line: + split = line.split(" ", 5) + if len(split) == 6: + counter += 1 + crons.append({"line": counter, + "minute": split[0], + "hour": split[1], + "monthday": split[2], + "month": split[3], + "weekday": split[4], + "command": split[5]}) + + data_ret = {'getWebsiteCron': 1, "user": website.externalApp, "crons": crons} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + except BaseException as msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg)) + dic = {'getWebsiteCron': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def getCronbyLine(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + line = data['line'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('getWebsiteCron', 0) + + if Websites.objects.filter(domain=self.domain).exists(): + pass + else: + dic = {'getWebsiteCron': 0, 'error_message': 'You do not own this domain'} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + line -= 1 + website = Websites.objects.get(domain=self.domain) + + try: + CronUtil.CronPrem(1) + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" + execPath = execPath + " getWebsiteCron --externalApp " + website.externalApp + + f = ProcessUtilities.outputExecutioner(execPath, website.externalApp) + CronUtil.CronPrem(0) + except subprocess.CalledProcessError as error: + dic = {'getWebsiteCron': 0, 'error_message': 'Unable to access Cron file'} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + f = f.split("\n") + cron = f[line] + + cron = cron.split(" ", 5) + if len(cron) != 6: + dic = {'getWebsiteCron': 0, 'error_message': 'Cron line incorrect'} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + data_ret = {"getWebsiteCron": 1, + "user": website.externalApp, + "cron": { + "minute": cron[0], + "hour": cron[1], + "monthday": cron[2], + "month": cron[3], + "weekday": cron[4], + "command": cron[5], + }, + "line": line} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + except BaseException as msg: + print(msg) + dic = {'getWebsiteCron': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def saveCronChanges(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + line = data['line'] + + minute = data['minute'] + hour = data['hour'] + monthday = data['monthday'] + month = data['month'] + weekday = data['weekday'] + command = data['cronCommand'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('getWebsiteCron', 0) + + website = Websites.objects.get(domain=self.domain) + + finalCron = "%s %s %s %s %s %s" % (minute, hour, monthday, month, weekday, command) + + CronUtil.CronPrem(1) + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" + execPath = execPath + " saveCronChanges --externalApp " + website.externalApp + " --line " + str( + line) + " --finalCron '" + finalCron + "'" + output = ProcessUtilities.outputExecutioner(execPath, website.externalApp) + CronUtil.CronPrem(0) + + if output.find("1,") > -1: + data_ret = {"getWebsiteCron": 1, + "user": website.externalApp, + "cron": finalCron, + "line": line} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + else: + dic = {'getWebsiteCron': 0, 'error_message': output} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + except BaseException as msg: + dic = {'getWebsiteCron': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def remCronbyLine(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + line = data['line'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('addNewCron', 0) + + website = Websites.objects.get(domain=self.domain) + + CronUtil.CronPrem(1) + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" + execPath = execPath + " remCronbyLine --externalApp " + website.externalApp + " --line " + str( + line) + output = ProcessUtilities.outputExecutioner(execPath, website.externalApp) + + CronUtil.CronPrem(0) + + if output.find("1,") > -1: + data_ret = {"remCronbyLine": 1, + "user": website.externalApp, + "removeLine": output.split(',')[1], + "line": line} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + else: + dic = {'remCronbyLine': 0, 'error_message': output} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + + except BaseException as msg: + dic = {'remCronbyLine': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def addNewCron(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + minute = data['minute'] + hour = data['hour'] + monthday = data['monthday'] + month = data['month'] + weekday = data['weekday'] + command = data['cronCommand'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('addNewCron', 0) + + website = Websites.objects.get(domain=self.domain) + + if ProcessUtilities.decideDistro() == ProcessUtilities.centos or ProcessUtilities.decideDistro() == ProcessUtilities.cent8: + cronPath = "/var/spool/cron/" + website.externalApp + else: + cronPath = "/var/spool/cron/crontabs/" + website.externalApp + + commandT = 'touch %s' % (cronPath) + ProcessUtilities.executioner(commandT, 'root') + commandT = 'chown %s:%s %s' % (website.externalApp, website.externalApp, cronPath) + ProcessUtilities.executioner(commandT, 'root') + + CronUtil.CronPrem(1) + + finalCron = "%s %s %s %s %s %s" % (minute, hour, monthday, month, weekday, command) + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" + execPath = execPath + " addNewCron --externalApp " + website.externalApp + " --finalCron '" + finalCron + "'" + output = ProcessUtilities.outputExecutioner(execPath, website.externalApp) + + if ProcessUtilities.decideDistro() == ProcessUtilities.ubuntu or ProcessUtilities.decideDistro() == ProcessUtilities.ubuntu20: + command = 'chmod 600 %s' % (cronPath) + ProcessUtilities.executioner(command) + + command = 'systemctl restart cron' + ProcessUtilities.executioner(command) + + CronUtil.CronPrem(0) + + if output.find("1,") > -1: + + data_ret = {"addNewCron": 1, + "user": website.externalApp, + "cron": finalCron} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + else: + dic = {'addNewCron': 0, 'error_message': output} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + + except BaseException as msg: + dic = {'addNewCron': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def submitAliasCreation(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['masterDomain'] + aliasDomain = data['aliasDomain'] + ssl = data['ssl'] + + if not validators.domain(aliasDomain): + data_ret = {'status': 0, 'createAliasStatus': 0, 'error_message': "Invalid domain."} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('createAliasStatus', 0) + + sslpath = "/home/" + self.domain + "/public_html" + + ## Create Configurations + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + + execPath = execPath + " createAlias --masterDomain " + self.domain + " --aliasDomain " + aliasDomain + " --ssl " + str( + ssl) + " --sslPath " + sslpath + " --administratorEmail " + admin.email + ' --websiteOwner ' + admin.userName + + output = ProcessUtilities.outputExecutioner(execPath) + + if output.find("1,None") > -1: + pass + else: + data_ret = {'createAliasStatus': 0, 'error_message': output, "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + ## Create Configurations ends here + + data_ret = {'createAliasStatus': 1, 'error_message': "None", "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + + except BaseException as msg: + data_ret = {'createAliasStatus': 0, 'error_message': str(msg), "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def issueAliasSSL(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['masterDomain'] + aliasDomain = data['aliasDomain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('sslStatus', 0) + + if ACLManager.AliasDomainCheck(currentACL, aliasDomain, self.domain) == 1: + pass + else: + return ACLManager.loadErrorJson('sslStatus', 0) + + sslpath = "/home/" + self.domain + "/public_html" + + ## Create Configurations + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " issueAliasSSL --masterDomain " + self.domain + " --aliasDomain " + aliasDomain + " --sslPath " + sslpath + " --administratorEmail " + admin.email + + output = ProcessUtilities.outputExecutioner(execPath) + + if output.find("1,None") > -1: + data_ret = {'sslStatus': 1, 'error_message': "None", "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + data_ret = {'sslStatus': 0, 'error_message': output, "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'sslStatus': 0, 'error_message': str(msg), "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def delateAlias(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['masterDomain'] + aliasDomain = data['aliasDomain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('deleteAlias', 0) + + if ACLManager.AliasDomainCheck(currentACL, aliasDomain, self.domain) == 1: + pass + else: + return ACLManager.loadErrorJson('deleteAlias', 0) + + ## Create Configurations + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " deleteAlias --masterDomain " + self.domain + " --aliasDomain " + aliasDomain + output = ProcessUtilities.outputExecutioner(execPath) + + if output.find("1,None") > -1: + data_ret = {'deleteAlias': 1, 'error_message': "None", "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + data_ret = {'deleteAlias': 0, 'error_message': output, "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'deleteAlias': 0, 'error_message': str(msg), "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def changeOpenBasedir(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + + self.domain = data['domainName'] + openBasedirValue = data['openBasedirValue'] + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson('changeOpenBasedir', 0) + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " changeOpenBasedir --virtualHostName '" + self.domain + "' --openBasedirValue " + openBasedirValue + output = ProcessUtilities.popenExecutioner(execPath) + + data_ret = {'status': 1, 'changeOpenBasedir': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'changeOpenBasedir': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def wordpressInstall(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + proc = httpProc(request, 'websiteFunctions/installWordPress.html', {'domainName': self.domain}) + return proc.render() + + def installWordpress(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('installStatus', 0) + + mailUtilities.checkHome() + + extraArgs = {} + extraArgs['admin'] = admin + extraArgs['domainName'] = data['domain'] + extraArgs['home'] = data['home'] + extraArgs['blogTitle'] = data['blogTitle'] + extraArgs['adminUser'] = data['adminUser'] + extraArgs['adminPassword'] = data['passwordByPass'] + extraArgs['adminEmail'] = data['adminEmail'] + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + if data['home'] == '0': + extraArgs['path'] = data['path'] + + background = ApplicationInstaller('wordpress', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def installWordpressStatus(self, userID=None, data=None): + try: + statusFile = data['statusFile'] + + if ACLManager.CheckStatusFilleLoc(statusFile): + pass + else: + data_ret = {'abort': 1, 'installStatus': 0, 'installationProgress': "100", + 'currentStatus': 'Invalid status file.'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + statusData = ProcessUtilities.outputExecutioner("cat " + statusFile).splitlines() + + lastLine = statusData[-1] + + if lastLine.find('[200]') > -1: + command = 'rm -f ' + statusFile + subprocess.call(shlex.split(command)) + data_ret = {'abort': 1, 'installStatus': 1, 'installationProgress': "100", + 'currentStatus': 'Successfully Installed.'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + elif lastLine.find('[404]') > -1: + data_ret = {'abort': 1, 'installStatus': 0, 'installationProgress': "0", + 'error_message': ProcessUtilities.outputExecutioner("cat " + statusFile).splitlines()} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + progress = lastLine.split(',') + currentStatus = progress[0] + try: + installationProgress = progress[1] + except: + installationProgress = 0 + data_ret = {'abort': 0, 'installStatus': 0, 'installationProgress': installationProgress, + 'currentStatus': currentStatus} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'abort': 0, 'installStatus': 0, 'installationProgress': "0", 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def joomlaInstall(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + proc = httpProc(request, 'websiteFunctions/installJoomla.html', {'domainName': self.domain}) + return proc.render() + + def installJoomla(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('installStatus', 0) + + extraArgs = {} + + extraArgs['password'] = data['passwordByPass'] + extraArgs['prefix'] = data['prefix'] + extraArgs['domain'] = data['domain'] + extraArgs['home'] = data['home'] + extraArgs['siteName'] = data['siteName'] + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + mailUtilities.checkHome() + + if data['home'] == '0': + extraArgs['path'] = data['path'] + + background = ApplicationInstaller('joomla', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + ## Installation ends + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def setupGit(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + website = Websites.objects.get(domain=self.domain) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson() + + path = '/home/cyberpanel/' + self.domain + '.git' + + if os.path.exists(path): + ipFile = "/etc/cyberpanel/machineIP" + f = open(ipFile) + ipData = f.read() + ipAddress = ipData.split('\n', 1)[0] + + port = ProcessUtilities.fetchCurrentPort() + + webhookURL = 'https://' + ipAddress + ':%s/websites/' % (port) + self.domain + '/gitNotify' + + proc = httpProc(request, 'websiteFunctions/setupGit.html', + {'domainName': self.domain, 'installed': 1, 'webhookURL': webhookURL}) + return proc.render() + else: + + command = "ssh-keygen -f /home/%s/.ssh/%s -t rsa -N ''" % (self.domain, website.externalApp) + ProcessUtilities.executioner(command, website.externalApp) + + ### + + configContent = """Host github.com +IdentityFile /home/%s/.ssh/%s +StrictHostKeyChecking no +""" % (self.domain, website.externalApp) + + path = "/home/cyberpanel/config" + writeToFile = open(path, 'w') + writeToFile.writelines(configContent) + writeToFile.close() + + command = 'mv %s /home/%s/.ssh/config' % (path, self.domain) + ProcessUtilities.executioner(command) + + command = 'chown %s:%s /home/%s/.ssh/config' % (website.externalApp, website.externalApp, self.domain) + ProcessUtilities.executioner(command) + + command = 'cat /home/%s/.ssh/%s.pub' % (self.domain, website.externalApp) + deploymentKey = ProcessUtilities.outputExecutioner(command, website.externalApp) + + proc = httpProc(request, 'websiteFunctions/setupGit.html', + {'domainName': self.domain, 'deploymentKey': deploymentKey, 'installed': 0}) + return proc.render() + + def setupGitRepo(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('installStatus', 0) + + mailUtilities.checkHome() + + extraArgs = {} + extraArgs['admin'] = admin + extraArgs['domainName'] = data['domain'] + extraArgs['username'] = data['username'] + extraArgs['reponame'] = data['reponame'] + extraArgs['branch'] = data['branch'] + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + extraArgs['defaultProvider'] = data['defaultProvider'] + + background = ApplicationInstaller('git', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def gitNotify(self, userID=None, data=None): + try: + + extraArgs = {} + extraArgs['domain'] = self.domain + + background = ApplicationInstaller('pull', extraArgs) + background.start() + + data_ret = {'pulled': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'pulled': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def detachRepo(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson() + + mailUtilities.checkHome() + + extraArgs = {} + extraArgs['domainName'] = data['domain'] + extraArgs['admin'] = admin + + background = ApplicationInstaller('detach', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def changeBranch(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson() + + mailUtilities.checkHome() + + extraArgs = {} + extraArgs['domainName'] = data['domain'] + extraArgs['githubBranch'] = data['githubBranch'] + extraArgs['admin'] = admin + + background = ApplicationInstaller('changeBranch', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def installPrestaShop(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + proc = httpProc(request, 'websiteFunctions/installPrestaShop.html', {'domainName': self.domain}) + return proc.render() + + def installMagento(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + proc = httpProc(request, 'websiteFunctions/installMagento.html', {'domainName': self.domain}) + return proc.render() + + def magentoInstall(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('installStatus', 0) + + mailUtilities.checkHome() + + extraArgs = {} + extraArgs['admin'] = admin + extraArgs['domainName'] = data['domain'] + extraArgs['home'] = data['home'] + extraArgs['firstName'] = data['firstName'] + extraArgs['lastName'] = data['lastName'] + extraArgs['username'] = data['username'] + extraArgs['email'] = data['email'] + extraArgs['password'] = data['passwordByPass'] + extraArgs['sampleData'] = data['sampleData'] + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + if data['home'] == '0': + extraArgs['path'] = data['path'] + + background = ApplicationInstaller('magento', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + ## Installation ends + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def installMautic(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + proc = httpProc(request, 'websiteFunctions/installMautic.html', {'domainName': self.domain}) + return proc.render() + + def mauticInstall(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('installStatus', 0) + + #### Before installing mautic change php to 8.1 + + completePathToConfigFile = f'/usr/local/lsws/conf/vhosts/{self.domain}/vhost.conf' + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " changePHP --phpVersion 'PHP 8.1' --path " + completePathToConfigFile + ProcessUtilities.executioner(execPath) + + mailUtilities.checkHome() + + extraArgs = {} + extraArgs['admin'] = admin + extraArgs['domainName'] = data['domain'] + extraArgs['home'] = data['home'] + extraArgs['username'] = data['username'] + extraArgs['email'] = data['email'] + extraArgs['password'] = data['passwordByPass'] + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + if data['home'] == '0': + extraArgs['path'] = data['path'] + + background = ApplicationInstaller('mautic', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + ## Installation ends + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def prestaShopInstall(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('installStatus', 0) + + mailUtilities.checkHome() + + extraArgs = {} + extraArgs['admin'] = admin + extraArgs['domainName'] = data['domain'] + extraArgs['home'] = data['home'] + extraArgs['shopName'] = data['shopName'] + extraArgs['firstName'] = data['firstName'] + extraArgs['lastName'] = data['lastName'] + extraArgs['databasePrefix'] = data['databasePrefix'] + extraArgs['email'] = data['email'] + extraArgs['password'] = data['passwordByPass'] + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + if data['home'] == '0': + extraArgs['path'] = data['path'] + + #### Before installing Prestashop change php to 8.3 + + completePathToConfigFile = f'/usr/local/lsws/conf/vhosts/{self.domain}/vhost.conf' + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " changePHP --phpVersion 'PHP 8.3' --path " + completePathToConfigFile + ProcessUtilities.executioner(execPath) + + background = ApplicationInstaller('prestashop', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + ## Installation ends + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def createWebsiteAPI(self, data=None): + try: + + adminUser = data['adminUser'] + adminPass = data['adminPass'] + adminEmail = data['ownerEmail'] + websiteOwner = data['websiteOwner'] + ownerPassword = data['ownerPassword'] + data['ssl'] = 1 + data['dkimCheck'] = 1 + data['openBasedir'] = 1 + data['adminEmail'] = data['ownerEmail'] + + try: + data['phpSelection'] = data['phpSelection'] + except: + data['phpSelection'] = "PHP 7.4" + + data['package'] = data['packageName'] + try: + websitesLimit = data['websitesLimit'] + except: + websitesLimit = 1 + + try: + apiACL = data['acl'] + except: + apiACL = 'user' + + admin = Administrator.objects.get(userName=adminUser) + + if hashPassword.check_password(admin.password, adminPass): + + if adminEmail is None: + data['adminEmail'] = "example@example.org" + + try: + acl = ACL.objects.get(name=apiACL) + websiteOwn = Administrator(userName=websiteOwner, + password=hashPassword.hash_password(ownerPassword), + email=adminEmail, type=3, owner=admin.pk, + initWebsitesLimit=websitesLimit, acl=acl, api=1) + websiteOwn.save() + except BaseException: + pass + + else: + data_ret = {"existsStatus": 0, 'createWebSiteStatus': 0, + 'error_message': "Could not authorize access to API"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + return self.submitWebsiteCreation(admin.pk, data) + + except BaseException as msg: + data_ret = {'createWebSiteStatus': 0, 'error_message': str(msg), "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def searchWebsitesJson(self, currentlACL, userID, searchTerm): + + websites = ACLManager.searchWebsiteObjects(currentlACL, userID, searchTerm) + + json_data = "[" + checker = 0 + + try: + ipFile = "/etc/cyberpanel/machineIP" + f = open(ipFile) + ipData = f.read() + ipAddress = ipData.split('\n', 1)[0] + except BaseException as msg: + logging.CyberCPLogFileWriter.writeToFile("Failed to read machine IP, error:" + str(msg)) + ipAddress = "192.168.100.1" + + for items in websites: + if items.state == 0: + state = "Suspended" + else: + state = "Active" + + DiskUsage, DiskUsagePercentage, bwInMB, bwUsage = virtualHostUtilities.FindStats(items) + + vhFile = f'/usr/local/lsws/conf/vhosts/{items.domain}/vhost.conf' + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(vhFile) + + try: + from plogical.phpUtilities import phpUtilities + PHPVersionActual = phpUtilities.WrapGetPHPVersionFromFileToGetVersionWithPHP(vhFile) + except: + PHPVersionActual = 'PHP 8.1' + + diskUsed = "%sMB" % str(DiskUsage) + dic = {'domain': items.domain, 'adminEmail': items.adminEmail, 'ipAddress': ipAddress, + 'admin': items.admin.userName, 'package': items.package.packageName, 'state': state, + 'diskUsed': diskUsed, 'phpVersion': PHPVersionActual} + + if checker == 0: + json_data = json_data + json.dumps(dic) + checker = 1 + else: + json_data = json_data + ',' + json.dumps(dic) + + json_data = json_data + ']' + + return json_data + + def findWebsitesJson(self, currentACL, userID, pageNumber): + finalPageNumber = ((pageNumber * 10)) - 10 + endPageNumber = finalPageNumber + 10 + websites = ACLManager.findWebsiteObjects(currentACL, userID)[finalPageNumber:endPageNumber] + + json_data = "[" + checker = 0 + + try: + ipFile = "/etc/cyberpanel/machineIP" + f = open(ipFile) + ipData = f.read() + ipAddress = ipData.split('\n', 1)[0] + except BaseException as msg: + logging.CyberCPLogFileWriter.writeToFile("Failed to read machine IP, error:" + str(msg)) + ipAddress = "192.168.100.1" + + for items in websites: + if items.state == 0: + state = "Suspended" + else: + state = "Active" + + DiskUsage, DiskUsagePercentage, bwInMB, bwUsage = virtualHostUtilities.FindStats(items) + + diskUsed = "%sMB" % str(DiskUsage) + + dic = {'domain': items.domain, 'adminEmail': items.adminEmail, 'ipAddress': ipAddress, + 'admin': items.admin.userName, 'package': items.package.packageName, 'state': state, + 'diskUsed': diskUsed} + + if checker == 0: + json_data = json_data + json.dumps(dic) + checker = 1 + else: + json_data = json_data + ',' + json.dumps(dic) + + json_data = json_data + ']' + + return json_data + + def websitePagination(self, currentACL, userID): + websites = ACLManager.findAllSites(currentACL, userID) + + pages = float(len(websites)) / float(10) + pagination = [] + + if pages <= 1.0: + pages = 1 + pagination.append('
  • ') + else: + pages = ceil(pages) + finalPages = int(pages) + 1 + + for i in range(1, finalPages): + pagination.append('
  • ' + str(i) + '
  • ') + + return pagination + + def DockersitePagination(self, currentACL, userID): + websites = DockerSites.objects.all() + + pages = float(len(websites)) / float(10) + pagination = [] + + if pages <= 1.0: + pages = 1 + pagination.append('
  • ') + else: + pages = ceil(pages) + finalPages = int(pages) + 1 + + for i in range(1, finalPages): + pagination.append('
  • ' + str(i) + '
  • ') + + return pagination + + def getSwitchStatus(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + try: + globalData = data['global'] + + data = {} + data['status'] = 1 + + if os.path.exists('/etc/httpd'): + data['server'] = 1 + else: + data['server'] = 0 + + json_data = json.dumps(data) + return HttpResponse(json_data) + except: + pass + + self.domain = data['domainName'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + if ProcessUtilities.decideServer() == ProcessUtilities.OLS: + finalConfPath = ApacheVhost.configBasePath + self.domain + '.conf' + + if os.path.exists(finalConfPath): + + phpPath = ApacheVhost.whichPHPExists(self.domain) + command = 'sudo cat ' + phpPath + phpConf = ProcessUtilities.outputExecutioner(command).splitlines() + pmMaxChildren = phpConf[8].split(' ')[2] + pmStartServers = phpConf[9].split(' ')[2] + pmMinSpareServers = phpConf[10].split(' ')[2] + pmMaxSpareServers = phpConf[11].split(' ')[2] + + data = {} + data['status'] = 1 + + data['server'] = WebsiteManager.apache + data['pmMaxChildren'] = pmMaxChildren + data['pmStartServers'] = pmStartServers + data['pmMinSpareServers'] = pmMinSpareServers + data['pmMaxSpareServers'] = pmMaxSpareServers + data['phpPath'] = phpPath + data['configData'] = ProcessUtilities.outputExecutioner(f'cat {finalConfPath}') + else: + data = {} + data['status'] = 1 + data['server'] = WebsiteManager.ols + + else: + data = {} + data['status'] = 1 + data['server'] = WebsiteManager.lsws + + json_data = json.dumps(data) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'saveStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def switchServer(self, userID=None, data=None): + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + domainName = data['domainName'] + phpVersion = data['phpSelection'] + server = data['server'] + + if ACLManager.checkOwnership(domainName, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson() + + tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + + execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " switchServer --phpVersion '" + phpVersion + "' --server " + str( + server) + " --virtualHostName " + domainName + " --tempStatusPath " + tempStatusPath + ProcessUtilities.popenExecutioner(execPath) + + time.sleep(3) + + data_ret = {'status': 1, 'tempStatusPath': tempStatusPath} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def tuneSettings(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + domainName = data['domainName'] + pmMaxChildren = data['pmMaxChildren'] + pmStartServers = data['pmStartServers'] + pmMinSpareServers = data['pmMinSpareServers'] + pmMaxSpareServers = data['pmMaxSpareServers'] + phpPath = data['phpPath'] + + if ACLManager.checkOwnership(domainName, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson() + + if int(pmStartServers) < int(pmMinSpareServers) or int(pmStartServers) > int(pmMinSpareServers): + data_ret = {'status': 0, + 'error_message': 'pm.start_servers must not be less than pm.min_spare_servers and not greater than pm.max_spare_servers.'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + if int(pmMinSpareServers) > int(pmMaxSpareServers): + data_ret = {'status': 0, + 'error_message': 'pm.max_spare_servers must not be less than pm.min_spare_servers'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + try: + website = Websites.objects.get(domain=domainName) + externalApp = website.externalApp + except: + website = ChildDomains.objects.get(domain=domainName) + externalApp = website.master.externalApp + + tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + + if ProcessUtilities.decideDistro() == ProcessUtilities.centos or ProcessUtilities.decideDistro() == ProcessUtilities.cent8: + sockPath = '/var/run/php-fpm/' + group = 'nobody' + else: + sockPath = '/var/run/php/' + group = 'nogroup' + + phpFPMConf = vhostConfs.phpFpmPoolReplace + phpFPMConf = phpFPMConf.replace('{externalApp}', externalApp) + phpFPMConf = phpFPMConf.replace('{pmMaxChildren}', pmMaxChildren) + phpFPMConf = phpFPMConf.replace('{pmStartServers}', pmStartServers) + phpFPMConf = phpFPMConf.replace('{pmMinSpareServers}', pmMinSpareServers) + phpFPMConf = phpFPMConf.replace('{pmMaxSpareServers}', pmMaxSpareServers) + phpFPMConf = phpFPMConf.replace('{www}', "".join(re.findall("[a-zA-Z]+", domainName))[:7]) + phpFPMConf = phpFPMConf.replace('{Sock}', domainName) + phpFPMConf = phpFPMConf.replace('{sockPath}', sockPath) + phpFPMConf = phpFPMConf.replace('{group}', group) + + writeToFile = open(tempStatusPath, 'w') + writeToFile.writelines(phpFPMConf) + writeToFile.close() + + command = 'sudo mv %s %s' % (tempStatusPath, phpPath) + ProcessUtilities.executioner(command) + + phpPath = phpPath.split('/') + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(f'PHP path in tune settings {phpPath}') + + if ProcessUtilities.decideDistro() == ProcessUtilities.centos or ProcessUtilities.decideDistro() == ProcessUtilities.cent8: + if phpPath[1] == 'etc': + phpVersion = phpPath[4][3] + phpPath[4][4] + phpVersion = f'PHP {phpPath[4][3]}.{phpPath[4][4]}' + else: + phpVersion = phpPath[3][3] + phpPath[3][4] + phpVersion = f'PHP {phpPath[3][3]}.{phpPath[3][4]}' + else: + phpVersion = f'PHP {phpPath[2]}' + + # php = PHPManager.getPHPString(phpVersion) + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(f'PHP Version in tune settings {phpVersion}') + + phpService = ApacheVhost.DecideFPMServiceName(phpVersion) + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(f'PHP service in tune settings {phpService}') + + command = f"systemctl stop {phpService}" + ProcessUtilities.normalExecutioner(command) + + command = f"systemctl restart {phpService}" + ProcessUtilities.normalExecutioner(command) + + data_ret = {'status': 1} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def sshAccess(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + website = Websites.objects.get(domain=self.domain) + externalApp = website.externalApp + + proc = httpProc(request, 'websiteFunctions/sshAccess.html', + {'domainName': self.domain, 'externalApp': externalApp}) + return proc.render() + + def saveSSHAccessChanges(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + website = Websites.objects.get(domain=self.domain) + + # if website.externalApp != data['externalApp']: + # data_ret = {'status': 0, 'error_message': 'External app mis-match.'} + # json_data = json.dumps(data_ret) + # return HttpResponse(json_data) + + uBuntuPath = '/etc/lsb-release' + + if os.path.exists(uBuntuPath): + command = "echo '%s:%s' | chpasswd" % (website.externalApp, data['password']) + else: + command = 'echo "%s" | passwd --stdin %s' % (data['password'], website.externalApp) + + ProcessUtilities.executioner(command) + + data_ret = {'status': 1, 'error_message': 'None', 'LinuxUser': website.externalApp} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def setupStaging(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + website = Websites.objects.get(domain=self.domain) + externalApp = website.externalApp + + proc = httpProc(request, 'websiteFunctions/setupStaging.html', + {'domainName': self.domain, 'externalApp': externalApp}) + return proc.render() + + def startCloning(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['masterDomain'] + + if not validators.domain(self.domain): + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Invalid domain."} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + if not validators.domain(data['domainName']): + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Invalid domain."} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + extraArgs = {} + extraArgs['domain'] = data['domainName'] + extraArgs['masterDomain'] = data['masterDomain'] + extraArgs['admin'] = admin + + tempStatusPath = "/tmp/" + str(randint(1000, 9999)) + writeToFile = open(tempStatusPath, 'a') + message = 'Cloning process has started..,5' + writeToFile.write(message) + writeToFile.close() + + extraArgs['tempStatusPath'] = tempStatusPath + + st = StagingSetup('startCloning', extraArgs) + st.start() + + data_ret = {'status': 1, 'error_message': 'None', 'tempStatusPath': tempStatusPath} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def syncToMaster(self, request=None, userID=None, data=None, childDomain=None): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + website = Websites.objects.get(domain=self.domain) + externalApp = website.externalApp + + proc = httpProc(request, 'websiteFunctions/syncMaster.html', + {'domainName': self.domain, 'externalApp': externalApp, 'childDomain': childDomain}) + return proc.render() + + def startSync(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if not validators.domain(data['childDomain']): + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Invalid domain."} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + self.domain = data['childDomain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + extraArgs = {} + extraArgs['childDomain'] = data['childDomain'] + try: + extraArgs['eraseCheck'] = data['eraseCheck'] + except: + extraArgs['eraseCheck'] = False + try: + extraArgs['dbCheck'] = data['dbCheck'] + except: + extraArgs['dbCheck'] = False + try: + extraArgs['copyChanged'] = data['copyChanged'] + except: + extraArgs['copyChanged'] = False + + extraArgs['admin'] = admin + + tempStatusPath = "/tmp/" + str(randint(1000, 9999)) + writeToFile = open(tempStatusPath, 'a') + message = 'Syncing process has started..,5' + writeToFile.write(message) + writeToFile.close() + + extraArgs['tempStatusPath'] = tempStatusPath + + st = StagingSetup('startSyncing', extraArgs) + st.start() + + data_ret = {'status': 1, 'error_message': 'None', 'tempStatusPath': tempStatusPath} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def convertDomainToSite(self, userID=None, request=None): + try: + + extraArgs = {} + extraArgs['request'] = request + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + background = ApplicationInstaller('convertDomainToSite', extraArgs) + background.start() + + data_ret = {'status': 1, 'createWebSiteStatus': 1, 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def manageGIT(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + try: + website = Websites.objects.get(domain=self.domain) + folders = ['/home/%s/public_html' % (self.domain)] + + databases = website.databases_set.all() + + # for database in databases: + # basePath = '/var/lib/mysql/' + # folders.append('%s%s' % (basePath, database.dbName)) + except: + + self.childWebsite = ChildDomains.objects.get(domain=self.domain) + + folders = [self.childWebsite.path] + + databases = self.childWebsite.master.databases_set.all() + + # for database in databases: + # basePath = '/var/lib/mysql/' + # folders.append('%s%s' % (basePath, database.dbName)) + + proc = httpProc(request, 'websiteFunctions/manageGIT.html', + {'domainName': self.domain, 'folders': folders}) + return proc.render() + + def folderCheck(self): + + try: + + ### + + domainPath = '/home/%s/public_html' % (self.domain) + vhRoot = '/home/%s' % (self.domain) + vmailPath = '/home/vmail/%s' % (self.domain) + + ## + + try: + + website = Websites.objects.get(domain=self.domain) + + self.masterWebsite = website + self.masterDomain = website.domain + externalApp = website.externalApp + self.externalAppLocal = website.externalApp + self.adminEmail = website.adminEmail + self.firstName = website.admin.firstName + self.lastName = website.admin.lastName + + self.home = 0 + if self.folder == '/home/%s/public_html' % (self.domain): + self.home = 1 + + except: + + website = ChildDomains.objects.get(domain=self.domain) + self.masterWebsite = website.master + self.masterDomain = website.master.domain + externalApp = website.master.externalApp + self.externalAppLocal = website.master.externalApp + self.adminEmail = website.master.adminEmail + self.firstName = website.master.admin.firstName + self.lastName = website.master.admin.lastName + + self.home = 0 + if self.folder == website.path: + self.home = 1 + + ### Fetch git configurations + + self.confCheck = 1 + + gitConfFolder = '/home/cyberpanel/git' + gitConFile = '%s/%s' % (gitConfFolder, self.masterDomain) + + if not os.path.exists(gitConfFolder): + os.mkdir(gitConfFolder) + + if not os.path.exists(gitConFile): + os.mkdir(gitConFile) + + if os.path.exists(gitConFile): + files = os.listdir(gitConFile) + + if len(files) >= 1: + for file in files: + self.finalFile = '%s/%s' % (gitConFile, file) + + gitConf = json.loads(open(self.finalFile, 'r').read()) + + if gitConf['folder'] == self.folder: + + self.autoCommitCurrent = gitConf['autoCommit'] + self.autoPushCurrent = gitConf['autoPush'] + self.emailLogsCurrent = gitConf['emailLogs'] + try: + self.commands = gitConf['commands'] + except: + self.commands = "Add Commands to run after every commit, separate commands using comma." + + try: + self.webhookCommandCurrent = gitConf['webhookCommand'] + except: + self.webhookCommandCurrent = "False" + + self.confCheck = 0 + break + + if self.confCheck: + self.autoCommitCurrent = 'Never' + self.autoPushCurrent = 'Never' + self.emailLogsCurrent = 'False' + self.webhookCommandCurrent = 'False' + self.commands = "Add Commands to run after every commit, separate commands using comma." + + ## + + if self.folder == domainPath: + self.externalApp = externalApp + return 1 + + ## + + if self.folder == vhRoot: + self.externalApp = externalApp + return 1 + + ## + + try: + childDomain = ChildDomains.objects.get(domain=self.domain) + + if self.folder == childDomain.path: + self.externalApp = externalApp + return 1 + + except: + pass + + ## + + if self.folder == vmailPath: + self.externalApp = 'vmail' + return 1 + + try: + + for database in website.databases_set.all(): + self.externalApp = 'mysql' + basePath = '/var/lib/mysql/' + dbPath = '%s%s' % (basePath, database.dbName) + + if self.folder == dbPath: + return 1 + except: + for database in website.master.databases_set.all(): + self.externalApp = 'mysql' + basePath = '/var/lib/mysql/' + dbPath = '%s%s' % (basePath, database.dbName) + + if self.folder == dbPath: + return 1 + + return 0 + + + except BaseException as msg: + logging.CyberCPLogFileWriter.writeToFile('%s. [folderCheck:3002]' % (str(msg))) + + return 0 + + def fetchFolderDetails(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + self.folder = data['folder'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + if self.folderCheck(): + pass + else: + return ACLManager.loadErrorJson() + + gitPath = '%s/.git' % (self.folder) + command = 'ls -la %s' % (gitPath) + + if ProcessUtilities.outputExecutioner(command, self.externalAppLocal).find( + 'No such file or directory') > -1: + + command = 'cat /home/%s/.ssh/%s.pub' % (self.masterDomain, self.externalAppLocal) + deploymentKey = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) + + if deploymentKey.find('No such file or directory') > -1: + command = "ssh-keygen -f /home/%s/.ssh/%s -t rsa -N ''" % (self.masterDomain, self.externalAppLocal) + ProcessUtilities.executioner(command, self.externalAppLocal) + + command = 'cat /home/%s/.ssh/%s.pub' % (self.masterDomain, self.externalAppLocal) + deploymentKey = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) + + data_ret = {'status': 1, 'repo': 0, 'deploymentKey': deploymentKey, 'home': self.home} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + + ## Find git branches + + command = 'git -C %s branch' % (self.folder) + branches = ProcessUtilities.outputExecutioner(command, self.externalAppLocal).split('\n')[:-1] + + ## Fetch key + + command = 'cat /home/%s/.ssh/%s.pub' % (self.domain, self.externalAppLocal) + deploymentKey = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) + + if deploymentKey.find('No such file or directory') > -1: + command = "ssh-keygen -f /home/%s/.ssh/%s -t rsa -N ''" % (self.masterDomain, self.externalAppLocal) + ProcessUtilities.executioner(command, self.externalAppLocal) + + command = 'cat /home/%s/.ssh/%s.pub' % (self.masterDomain, self.externalAppLocal) + deploymentKey = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) + + ## Find Remote if any + + command = 'git -C %s remote -v' % (self.folder) + remoteResult = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) + + remote = 1 + if remoteResult.find('origin') == -1: + remote = 0 + remoteResult = 'Remote currently not set.' + + ## Find Total commits on current branch + + command = 'git -C %s rev-list --count HEAD' % (self.folder) + totalCommits = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) + + if totalCommits.find('fatal') > -1: + totalCommits = '0' + + ## + + port = ProcessUtilities.fetchCurrentPort() + + webHookURL = 'https://%s:%s/websites/%s/webhook' % (ACLManager.fetchIP(), port, self.domain) + + data_ret = {'status': 1, 'repo': 1, 'finalBranches': branches, 'deploymentKey': deploymentKey, + 'remote': remote, 'remoteResult': remoteResult, 'totalCommits': totalCommits, + 'home': self.home, + 'webHookURL': webHookURL, 'autoCommitCurrent': self.autoCommitCurrent, + 'autoPushCurrent': self.autoPushCurrent, 'emailLogsCurrent': self.emailLogsCurrent, + 'commands': self.commands, "webhookCommandCurrent": self.webhookCommandCurrent} + + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def initRepo(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + self.folder = data['folder'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + if self.folderCheck(): + pass + else: + return ACLManager.loadErrorJson() + + website = Websites.objects.get(domain=self.masterDomain) + + command = 'git -C %s init' % (self.folder) + result = ProcessUtilities.outputExecutioner(command, website.externalApp) + + if result.find('Initialized empty Git repository in') > -1: + + command = 'git -C %s config --local user.email %s' % (self.folder, self.adminEmail) + ProcessUtilities.executioner(command, website.externalApp) + + command = 'git -C %s config --local user.name "%s %s"' % ( + self.folder, self.firstName, self.lastName) + ProcessUtilities.executioner(command, website.externalApp) + + ## Fix permissions + + # from filemanager.filemanager import FileManager + # + # fm = FileManager(None, None) + # fm.fixPermissions(self.masterDomain) + + data_ret = {'status': 1} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + data_ret = {'status': 0, 'error_message': result} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def setupRemote(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + self.folder = data['folder'] + self.gitHost = data['gitHost'] + self.gitUsername = data['gitUsername'] + self.gitReponame = data['gitReponame'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + ## Security checks + + if self.folderCheck(): + pass + else: + return ACLManager.loadErrorJson() + + if self.gitHost.find(':') > -1: + gitHostDomain = self.gitHost.split(':')[0] + gitHostPort = self.gitHost.split(':')[1] + + if not validators.domain(gitHostDomain): + return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') + + try: + gitHostPort = int(gitHostPort) + except: + return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') + + else: + if not validators.domain(self.gitHost): + return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') + + if ACLManager.validateInput(self.gitUsername) and ACLManager.validateInput(self.gitReponame): + pass + else: + return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') + + ### set default ssh key + + command = 'git -C %s config --local core.sshCommand "ssh -i /home/%s/.ssh/%s -o "StrictHostKeyChecking=no""' % ( + self.folder, self.masterDomain, self.externalAppLocal) + ProcessUtilities.executioner(command, self.externalAppLocal) + + ## Check if remote exists + + command = 'git -C %s remote -v' % (self.folder) + remoteResult = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) + + ## Set new remote + + if remoteResult.find('origin') == -1: + command = 'git -C %s remote add origin git@%s:%s/%s.git' % ( + self.folder, self.gitHost, self.gitUsername, self.gitReponame) + else: + command = 'git -C %s remote set-url origin git@%s:%s/%s.git' % ( + self.folder, self.gitHost, self.gitUsername, self.gitReponame) + + possibleError = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) + + ## Check if set correctly. + + command = 'git -C %s remote -v' % (self.folder) + remoteResult = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) + + if remoteResult.find(self.gitUsername) > -1: + + # ## Fix permissions + # + # from filemanager.filemanager import FileManager + # + # fm = FileManager(None, None) + # fm.fixPermissions(self.masterDomain) + + data_ret = {'status': 1} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + data_ret = {'status': 0, 'error_message': possibleError} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def changeGitBranch(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + self.folder = data['folder'] + self.branchName = data['branchName'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + if self.folderCheck(): + pass + else: + return ACLManager.loadErrorJson() + + ## Security check + + if ACLManager.validateInput(self.branchName): + pass + else: + return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') + + if self.branchName.find('*') > -1: + data_ret = {'status': 0, 'commandStatus': 'Already on this branch.', + 'error_message': 'Already on this branch.'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + self.externalApp = ACLManager.FetchExternalApp(self.domain) + + command = 'git -C %s checkout %s' % (self.folder, self.branchName.strip(' ')) + commandStatus = ProcessUtilities.outputExecutioner(command, self.externalApp) + + if commandStatus.find('Switched to branch') > -1: + + # ## Fix permissions + # + # from filemanager.filemanager import FileManager + # + # fm = FileManager(None, None) + # fm.fixPermissions(self.masterDomain) + + data_ret = {'status': 1, 'commandStatus': commandStatus + 'Refreshing page in 3 seconds..'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + data_ret = {'status': 0, 'error_message': 'Failed to change branch', 'commandStatus': commandStatus} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def createNewBranch(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + self.folder = data['folder'] + self.newBranchName = data['newBranchName'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + if self.folderCheck(): + pass + else: + return ACLManager.loadErrorJson() + + ## Security check + + if ACLManager.validateInput(self.newBranchName): + pass + else: + return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') + + ## + + self.externalApp = ACLManager.FetchExternalApp(self.domain) + + command = 'git -C %s checkout -b "%s"' % (self.folder, self.newBranchName) + commandStatus = ProcessUtilities.outputExecutioner(command, self.externalApp) + + if commandStatus.find(self.newBranchName) > -1: + + # ## Fix permissions + # + # from filemanager.filemanager import FileManager + # + # fm = FileManager(None, None) + # fm.fixPermissions(self.masterDomain) + + data_ret = {'status': 1, 'commandStatus': commandStatus} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + data_ret = {'status': 0, 'error_message': 'Failed to create branch', 'commandStatus': commandStatus} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def commitChanges(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + self.folder = data['folder'] + self.commitMessage = data['commitMessage'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + if self.folderCheck(): + pass + else: + return ACLManager.loadErrorJson('status', 0) + + # security check + + if ACLManager.validateInput(self.commitMessage): + pass + else: + return ACLManager.loadErrorJson() + + self.externalApp = ACLManager.FetchExternalApp(self.domain) + + ## Check if remote exists + + command = 'git -C %s add -A' % (self.folder) + ProcessUtilities.outputExecutioner(command, self.externalApp) + + command = 'git -C %s commit -m "%s"' % (self.folder, self.commitMessage.replace('"', '')) + commandStatus = ProcessUtilities.outputExecutioner(command, self.externalApp) + + if commandStatus.find('nothing to commit') == -1: + + try: + if self.commands != 'NONE': + + GitLogs(owner=self.masterWebsite, type='INFO', + message='Running commands after successful git commit..').save() + + if self.commands.find('\n') > -1: + commands = self.commands.split('\n') + + for command in commands: + GitLogs(owner=self.masterWebsite, type='INFO', + message='Running: %s' % (command)).save() + + result = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) + GitLogs(owner=self.masterWebsite, type='INFO', + message='Result: %s' % (result)).save() + else: + GitLogs(owner=self.masterWebsite, type='INFO', + message='Running: %s' % (self.commands)).save() + + result = ProcessUtilities.outputExecutioner(self.commands, self.externalAppLocal) + GitLogs(owner=self.masterWebsite, type='INFO', + message='Result: %s' % (result)).save() + + GitLogs(owner=self.masterWebsite, type='INFO', + message='Finished running commands.').save() + except: + pass + + ## Fix permissions + + # from filemanager.filemanager import FileManager + # + # fm = FileManager(None, None) + # fm.fixPermissions(self.masterDomain) + + data_ret = {'status': 1, 'commandStatus': commandStatus} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + data_ret = {'status': 0, 'error_message': 'Nothing to commit.', 'commandStatus': commandStatus} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg), 'commandStatus': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def gitPull(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + self.folder = data['folder'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + if self.folderCheck(): + pass + else: + return ACLManager.loadErrorJson() + + self.externalApp = ACLManager.FetchExternalApp(self.domain) + + ### set default ssh key + + command = 'git -C %s config --local core.sshCommand "ssh -i /home/%s/.ssh/%s -o "StrictHostKeyChecking=no""' % ( + self.folder, self.masterDomain, self.externalAppLocal) + ProcessUtilities.executioner(command, self.externalApp) + + ## Check if remote exists + + command = 'git -C %s pull' % (self.folder) + commandStatus = ProcessUtilities.outputExecutioner(command, self.externalApp) + + if commandStatus.find('Already up to date') == -1: + + ## Fix permissions + + # from filemanager.filemanager import FileManager + # + # fm = FileManager(None, None) + # fm.fixPermissions(self.masterDomain) + + data_ret = {'status': 1, 'commandStatus': commandStatus} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + data_ret = {'status': 0, 'error_message': 'Pull not required.', 'commandStatus': commandStatus} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def gitPush(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + self.folder = data['folder'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + if self.folderCheck(): + pass + else: + return ACLManager.loadErrorJson() + + self.externalApp = ACLManager.FetchExternalApp(self.domain) + + ### set default ssh key + + command = 'git -C %s config --local core.sshCommand "ssh -i /home/%s/.ssh/%s -o "StrictHostKeyChecking=no""' % ( + self.folder, self.masterDomain, self.externalAppLocal) + ProcessUtilities.executioner(command, self.externalApp) + + ## + + command = 'git -C %s push' % (self.folder) + commandStatus = ProcessUtilities.outputExecutioner(command, self.externalApp, False) + + if commandStatus.find('has no upstream branch') > -1: + command = 'git -C %s rev-parse --abbrev-ref HEAD' % (self.folder) + currentBranch = ProcessUtilities.outputExecutioner(command, self.externalApp, False).rstrip('\n') + + if currentBranch.find('fatal: ambiguous argument') > -1: + data_ret = {'status': 0, 'error_message': 'You need to commit first.', + 'commandStatus': 'You need to commit first.'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + command = 'git -C %s push --set-upstream origin %s' % (self.folder, currentBranch) + commandStatus = ProcessUtilities.outputExecutioner(command, self.externalApp, False) + + if commandStatus.find('Everything up-to-date') == -1 and commandStatus.find( + 'rejected') == -1 and commandStatus.find('Permission denied') == -1: + data_ret = {'status': 1, 'commandStatus': commandStatus} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + data_ret = {'status': 0, 'error_message': 'Push failed.', 'commandStatus': commandStatus} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg), 'commandStatus': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def attachRepoGIT(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + self.folder = data['folder'] + self.gitHost = data['gitHost'] + self.gitUsername = data['gitUsername'] + self.gitReponame = data['gitReponame'] + + try: + self.overrideData = data['overrideData'] + except: + self.overrideData = False + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('status', 0) + + if self.folderCheck(): + pass + else: + return ACLManager.loadErrorJson() + + if self.gitHost.find(':') > -1: + gitHostDomain = self.gitHost.split(':')[0] + gitHostPort = self.gitHost.split(':')[1] + + if not validators.domain(gitHostDomain): + return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') + + try: + gitHostPort = int(gitHostPort) + except: + return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') + else: + if not validators.domain(self.gitHost): + return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') + + ## Security check + + if ACLManager.validateInput(self.gitUsername) and ACLManager.validateInput(self.gitReponame): + pass + else: + return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') + + ## + + self.externalApp = ACLManager.FetchExternalApp(self.domain) + + if self.overrideData: + command = 'rm -rf %s' % (self.folder) + ProcessUtilities.executioner(command, self.externalApp) + + ## Set defauly key + + command = 'git config --global core.sshCommand "ssh -i /home/%s/.ssh/%s -o "StrictHostKeyChecking=no""' % ( + self.masterDomain, self.externalAppLocal) + ProcessUtilities.executioner(command, self.externalApp) + + ## + + command = 'git clone git@%s:%s/%s.git %s' % (self.gitHost, self.gitUsername, self.gitReponame, self.folder) + commandStatus = ProcessUtilities.outputExecutioner(command, self.externalApp) + + if commandStatus.find('already exists') == -1 and commandStatus.find('Permission denied') == -1: + + # from filemanager.filemanager import FileManager + # + # fm = FileManager(None, None) + # fm.fixPermissions(self.masterDomain) + + command = 'git -C %s config --local user.email %s' % (self.folder, self.adminEmail) + ProcessUtilities.executioner(command, self.externalApp) + + command = 'git -C %s config --local user.name "%s %s"' % (self.folder, self.firstName, self.lastName) +#!/usr/local/CyberCP/bin/python +import html +import os +import os.path +import sys +import django + +from databases.models import Databases +from plogical.DockerSites import Docker_Sites +from plogical.httpProc import httpProc + +sys.path.append('/usr/local/CyberCP') +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings") +django.setup() +import json +from plogical.acl import ACLManager +import plogical.CyberCPLogFileWriter as logging +from websiteFunctions.models import Websites, ChildDomains, GitLogs, wpplugins, WPSites, WPStaging, WPSitesBackup, \ + RemoteBackupConfig, RemoteBackupSchedule, RemoteBackupsites, DockerPackages, PackageAssignment, DockerSites +from plogical.virtualHostUtilities import virtualHostUtilities +import subprocess +import shlex +from plogical.installUtilities import installUtilities +from django.shortcuts import HttpResponse, render, redirect +from loginSystem.models import Administrator, ACL +from packages.models import Package +from plogical.mailUtilities import mailUtilities +from random import randint +import time +import re +import boto3 +from plogical.childDomain import ChildDomainManager +from math import ceil +from plogical.alias import AliasManager +from plogical.applicationInstaller import ApplicationInstaller +from plogical import hashPassword, randomPassword +from emailMarketing.emACL import emACL +from plogical.processUtilities import ProcessUtilities +from managePHP.phpManager import PHPManager +from ApachController.ApacheVhosts import ApacheVhost +from plogical.vhostConfs import vhostConfs +from plogical.cronUtil import CronUtil +from .StagingSetup import StagingSetup +import validators +from django.http import JsonResponse + + +class WebsiteManager: + apache = 1 + ols = 2 + lsws = 3 + + def __init__(self, domain=None, childDomain=None): + self.domain = domain + self.childDomain = childDomain + + def createWebsite(self, request=None, userID=None, data=None): + + url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" + data = { + "name": "all", + "IP": ACLManager.GetServerIP() + } + + import requests + response = requests.post(url, data=json.dumps(data)) + Status = response.json()['status'] + + test_domain_status = 0 + + if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: + test_domain_status = 1 + + currentACL = ACLManager.loadedACL(userID) + adminNames = ACLManager.loadAllUsers(userID) + packagesName = ACLManager.loadPackages(userID, currentACL) + phps = PHPManager.findPHPVersions() + + rnpss = randomPassword.generate_pass(10) + + Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps, 'Randam_String': rnpss.lower(), + 'test_domain_data': test_domain_status} + proc = httpProc(request, 'websiteFunctions/createWebsite.html', + Data, 'createWebsite') + return proc.render() + + def WPCreate(self, request=None, userID=None, data=None): + url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" + data = { + "name": "wp-manager", + "IP": ACLManager.GetServerIP() + } + + import requests + response = requests.post(url, data=json.dumps(data)) + Status = response.json()['status'] + + + if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: + currentACL = ACLManager.loadedACL(userID) + adminNames = ACLManager.loadAllUsers(userID) + packagesName = ACLManager.loadPackages(userID, currentACL) + + if len(packagesName) == 0: + packagesName = ['Default'] + + FinalVersions = [] + userobj = Administrator.objects.get(pk=userID) + counter = 0 + try: + import requests + WPVersions = json.loads(requests.get('https://api.wordpress.org/core/version-check/1.7/').text)[ + 'offers'] + + for versions in WPVersions: + if counter == 7: + break + if versions['current'] not in FinalVersions: + FinalVersions.append(versions['current']) + counter = counter + 1 + except: + FinalVersions = ['5.6', '5.5.3', '5.5.2'] + + Plugins = wpplugins.objects.filter(owner=userobj) + rnpss = randomPassword.generate_pass(10) + + ## + + test_domain_status = 1 + + Data = {'packageList': packagesName, "owernList": adminNames, 'WPVersions': FinalVersions, + 'Plugins': Plugins, 'Randam_String': rnpss.lower(), 'test_domain_data': test_domain_status} + proc = httpProc(request, 'websiteFunctions/WPCreate.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def ListWPSites(self, request=None, userID=None, DeleteID=None): + import json + currentACL = ACLManager.loadedACL(userID) + + admin = Administrator.objects.get(pk=userID) + data = {} + wp_sites = ACLManager.GetALLWPObjects(currentACL, userID) + data['wp'] = wp_sites + + try: + if DeleteID != None: + WPDelete = WPSites.objects.get(pk=DeleteID) + + if ACLManager.checkOwnership(WPDelete.owner.domain, admin, currentACL) == 1: + WPDelete.delete() + except BaseException as msg: + pass + + sites = [] + for site in data['wp']: + sites.append({ + 'id': site.id, + 'title': site.title, + 'url': site.FinalURL, + 'production_status': True + }) + + context = { + "wpsite": json.dumps(sites), + "status": 1, + "total_sites": len(sites), + "debug_info": json.dumps({ + "user_id": userID, + "is_admin": bool(currentACL.get('admin', 0)), + "wp_sites_count": wp_sites.count() + }) + } + + proc = httpProc(request, 'websiteFunctions/WPsitesList.html', context) + return proc.render() + + def WPHome(self, request=None, userID=None, WPid=None, DeleteID=None): + Data = {} + currentACL = ACLManager.loadedACL(userID) + WPobj = WPSites.objects.get(pk=WPid) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(WPobj.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + try: + + url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" + data = { + "name": "wp-manager", + "IP": ACLManager.GetServerIP() + } + + import requests + response = requests.post(url, data=json.dumps(data)) + Status = response.json()['status'] + + rnpss = randomPassword.generate_pass(10) + + Data['Randam_String'] = rnpss.lower() + + if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: + Data['wpsite'] = WPobj + Data['test_domain_data'] = 1 + + try: + DeleteID = request.GET.get('DeleteID', None) + + if DeleteID != None: + wstagingDelete = WPStaging.objects.get(pk=DeleteID, owner=WPobj) + wstagingDelete.delete() + + except BaseException as msg: + da = str(msg) + + proc = httpProc(request, 'websiteFunctions/WPsiteHome.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + except: + proc = httpProc(request, 'websiteFunctions/WPsiteHome.html', + Data, 'createDatabase') + return proc.render() + + def RestoreHome(self, request=None, userID=None, BackupID=None): + Data = {} + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.CheckForPremFeature('wp-manager'): + + Data['backupobj'] = WPSitesBackup.objects.get(pk=BackupID) + + if ACLManager.CheckIPBackupObjectOwner(currentACL, Data['backupobj'], admin) == 1: + pass + else: + return ACLManager.loadError() + + config = json.loads(Data['backupobj'].config) + Data['FileName'] = config['name'] + try: + Data['Backuptype'] = config['Backuptype'] + + if Data['Backuptype'] == 'DataBase Backup' or Data['Backuptype'] == 'Website Backup': + Data['WPsites'] = [WPSites.objects.get(pk=Data['backupobj'].WPSiteID)] + else: + Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) + + except: + Data['Backuptype'] = None + Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) + + proc = httpProc(request, 'websiteFunctions/WPRestoreHome.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def RemoteBackupConfig(self, request=None, userID=None, DeleteID=None): + Data = {} + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + try: + if DeleteID != None: + BackupconfigDelete = RemoteBackupConfig.objects.get(pk=DeleteID) + BackupconfigDelete.delete() + except: + pass + + if ACLManager.CheckForPremFeature('wp-manager'): + + Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) + allcon = RemoteBackupConfig.objects.all() + Data['backupconfigs'] = [] + for i in allcon: + configr = json.loads(i.config) + if i.configtype == "SFTP": + Data['backupconfigs'].append({ + 'id': i.pk, + 'Type': i.configtype, + 'HostName': configr['Hostname'], + 'Path': configr['Path'] + }) + elif i.configtype == "S3": + Provider = configr['Provider'] + if Provider == "Backblaze": + Data['backupconfigs'].append({ + 'id': i.pk, + 'Type': i.configtype, + 'HostName': Provider, + 'Path': configr['S3keyname'] + }) + else: + Data['backupconfigs'].append({ + 'id': i.pk, + 'Type': i.configtype, + 'HostName': Provider, + 'Path': configr['S3keyname'] + }) + + proc = httpProc(request, 'websiteFunctions/RemoteBackupConfig.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def BackupfileConfig(self, request=None, userID=None, RemoteConfigID=None, DeleteID=None): + Data = {} + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + Data['RemoteConfigID'] = RemoteConfigID + RemoteConfigobj = RemoteBackupConfig.objects.get(pk=RemoteConfigID) + try: + if DeleteID != None: + RemoteBackupConfigDelete = RemoteBackupSchedule.objects.get(pk=DeleteID) + RemoteBackupConfigDelete.delete() + except: + pass + + if ACLManager.CheckForPremFeature('wp-manager'): + Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) + allsechedule = RemoteBackupSchedule.objects.filter(RemoteBackupConfig=RemoteConfigobj) + Data['Backupschedule'] = [] + for i in allsechedule: + lastrun = i.lastrun + LastRun = time.strftime('%Y-%m-%d', time.localtime(float(lastrun))) + Data['Backupschedule'].append({ + 'id': i.pk, + 'Name': i.Name, + 'RemoteConfiguration': i.RemoteBackupConfig.configtype, + 'Retention': i.fileretention, + 'Frequency': i.timeintervel, + 'LastRun': LastRun + }) + proc = httpProc(request, 'websiteFunctions/BackupfileConfig.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def AddRemoteBackupsite(self, request=None, userID=None, RemoteScheduleID=None, DeleteSiteID=None): + Data = {} + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + Data['RemoteScheduleID'] = RemoteScheduleID + RemoteBackupScheduleobj = RemoteBackupSchedule.objects.get(pk=RemoteScheduleID) + + try: + if DeleteSiteID != None: + RemoteBackupsitesDelete = RemoteBackupsites.objects.get(pk=DeleteSiteID) + RemoteBackupsitesDelete.delete() + except: + pass + + if ACLManager.CheckForPremFeature('wp-manager'): + Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) + allRemoteBackupsites = RemoteBackupsites.objects.filter(owner=RemoteBackupScheduleobj) + Data['RemoteBackupsites'] = [] + for i in allRemoteBackupsites: + try: + wpsite = WPSites.objects.get(pk=i.WPsites) + Data['RemoteBackupsites'].append({ + 'id': i.pk, + 'Title': wpsite.title, + }) + except: + pass + proc = httpProc(request, 'websiteFunctions/AddRemoteBackupSite.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def WordpressPricing(self, request=None, userID=None, ): + Data = {} + proc = httpProc(request, 'websiteFunctions/CyberpanelPricing.html', Data, 'createWebsite') + return proc.render() + + def RestoreBackups(self, request=None, userID=None, DeleteID=None): + Data = {} + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" + data = { + "name": "wp-manager", + "IP": ACLManager.GetServerIP() + } + + import requests + response = requests.post(url, data=json.dumps(data)) + Status = response.json()['status'] + + if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: + + backobj = WPSitesBackup.objects.filter(owner=admin).order_by('-id') + + # if ACLManager.CheckIPBackupObjectOwner(currentACL, backobj, admin) == 1: + # pass + # else: + # return ACLManager.loadError() + + try: + if DeleteID != None: + DeleteIDobj = WPSitesBackup.objects.get(pk=DeleteID) + + if ACLManager.CheckIPBackupObjectOwner(currentACL, DeleteIDobj, admin) == 1: + config = DeleteIDobj.config + conf = json.loads(config) + FileName = conf['name'] + command = "rm -r /home/backup/%s.tar.gz" % FileName + ProcessUtilities.executioner(command) + DeleteIDobj.delete() + + except BaseException as msg: + pass + Data['job'] = [] + + for sub in backobj: + try: + wpsite = WPSites.objects.get(pk=sub.WPSiteID) + web = wpsite.title + except: + web = "Website Not Found" + + try: + config = sub.config + conf = json.loads(config) + Backuptype = conf['Backuptype'] + BackupDestination = conf['BackupDestination'] + except: + Backuptype = "Backup type not exists" + + Data['job'].append({ + 'id': sub.id, + 'title': web, + 'Backuptype': Backuptype, + 'BackupDestination': BackupDestination + }) + + proc = httpProc(request, 'websiteFunctions/RestoreBackups.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def AutoLogin(self, request=None, userID=None): + + WPid = request.GET.get('id') + currentACL = ACLManager.loadedACL(userID) + WPobj = WPSites.objects.get(pk=WPid) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(WPobj.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + from managePHP.phpManager import PHPManager + + php = PHPManager.getPHPString(WPobj.owner.phpSelection) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" + data = { + "name": "wp-manager", + "IP": ACLManager.GetServerIP() + } + + import requests + response = requests.post(url, data=json.dumps(data)) + Status = response.json()['status'] + + if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: + + ## Get title + + password = randomPassword.generate_pass(10) + + command = f'sudo -u %s {FinalPHPPath} /usr/bin/wp user create autologin %s --role=administrator --user_pass="%s" --path=%s --skip-plugins --skip-themes' % ( + WPobj.owner.externalApp, 'autologin@cloudpages.cloud', password, WPobj.path) + ProcessUtilities.executioner(command) + + command = f'sudo -u %s {FinalPHPPath} /usr/bin/wp user update autologin --user_pass="%s" --path=%s --skip-plugins --skip-themes' % ( + WPobj.owner.externalApp, password, WPobj.path) + ProcessUtilities.executioner(command) + + data = {} + + if WPobj.FinalURL.endswith('/'): + FinalURL = WPobj.FinalURL[:-1] + else: + FinalURL = WPobj.FinalURL + + data['url'] = 'https://%s' % (FinalURL) + data['userName'] = 'autologin' + data['password'] = password + + proc = httpProc(request, 'websiteFunctions/AutoLogin.html', + data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def ConfigurePlugins(self, request=None, userID=None, data=None): + + if ACLManager.CheckForPremFeature('wp-manager'): + currentACL = ACLManager.loadedACL(userID) + userobj = Administrator.objects.get(pk=userID) + + Selectedplugins = wpplugins.objects.filter(owner=userobj) + # data['Selectedplugins'] = wpplugins.objects.filter(ProjectOwner=HostingCompany) + + Data = {'Selectedplugins': Selectedplugins, } + proc = httpProc(request, 'websiteFunctions/WPConfigurePlugins.html', + Data, 'createDatabase') + return proc.render() + else: + from django.shortcuts import reverse + return redirect(reverse('pricing')) + + def Addnewplugin(self, request=None, userID=None, data=None): + from django.shortcuts import reverse + if ACLManager.CheckForPremFeature('wp-manager'): + currentACL = ACLManager.loadedACL(userID) + adminNames = ACLManager.loadAllUsers(userID) + packagesName = ACLManager.loadPackages(userID, currentACL) + phps = PHPManager.findPHPVersions() + + Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps} + proc = httpProc(request, 'websiteFunctions/WPAddNewPlugin.html', + Data, 'createDatabase') + return proc.render() + + return redirect(reverse('pricing')) + + def SearchOnkeyupPlugin(self, userID=None, data=None): + try: + if ACLManager.CheckForPremFeature('wp-manager'): + currentACL = ACLManager.loadedACL(userID) + + pluginname = data['pluginname'] + # logging.CyberCPLogFileWriter.writeToFile("Plugin Name ....... %s"%pluginname) + + url = "http://api.wordpress.org/plugins/info/1.1/?action=query_plugins&request[search]=%s" % str( + pluginname) + import requests + + res = requests.get(url) + r = res.json() + + # return proc.ajax(1, 'Done', {'plugins': r}) + + data_ret = {'status': 1, 'plugns': r, } + + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': 'Premium feature not available.'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def AddNewpluginAjax(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + + userobj = Administrator.objects.get(pk=userID) + + config = data['config'] + Name = data['Name'] + # pluginname = data['pluginname'] + # logging.CyberCPLogFileWriter.writeToFile("config ....... %s"%config) + # logging.CyberCPLogFileWriter.writeToFile(" Name ....... %s"%Name) + + addpl = wpplugins(Name=Name, config=json.dumps(config), owner=userobj) + addpl.save() + + data_ret = {'status': 1} + + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'AddNewpluginAjax': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def EidtPlugin(self, request=None, userID=None, pluginbID=None): + Data = {} + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + pluginobj = wpplugins.objects.get(pk=pluginbID) + + if ACLManager.CheckIPPluginObjectOwner(currentACL, pluginobj, admin) == 1: + pass + else: + return ACLManager.loadError() + + lmo = json.loads(pluginobj.config) + Data['Selectedplugins'] = lmo + Data['pluginbID'] = pluginbID + Data['BucketName'] = pluginobj.Name + + proc = httpProc(request, 'websiteFunctions/WPEidtPlugin.html', + Data, 'createDatabase') + return proc.render() + + def deletesPlgin(self, userID=None, data=None, ): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + userobj = Administrator.objects.get(pk=userID) + pluginname = data['pluginname'] + pluginbBucketID = data['pluginbBucketID'] + # logging.CyberCPLogFileWriter.writeToFile("pluginbID ....... %s" % pluginbBucketID) + # logging.CyberCPLogFileWriter.writeToFile("pluginname ....... %s" % pluginname) + + obj = wpplugins.objects.get(pk=pluginbBucketID, owner=userobj) + + if ACLManager.CheckIPPluginObjectOwner(currentACL, obj, admin) == 1: + pass + else: + return ACLManager.loadError() + + ab = [] + ab = json.loads(obj.config) + ab.remove(pluginname) + obj.config = json.dumps(ab) + obj.save() + + data_ret = {'status': 1} + + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + except BaseException as msg: + data_ret = {'status': 0, 'deletesPlgin': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def Addplugineidt(self, userID=None, data=None, ): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + userobj = Administrator.objects.get(pk=userID) + pluginname = data['pluginname'] + pluginbBucketID = data['pluginbBucketID'] + + # logging.CyberCPLogFileWriter.writeToFile("pluginbID ....... %s" % pluginbBucketID) + # logging.CyberCPLogFileWriter.writeToFile("pluginname ....... %s" % pluginname) + + pObj = wpplugins.objects.get(pk=pluginbBucketID, owner=userobj) + + if ACLManager.CheckIPPluginObjectOwner(currentACL, pObj, admin) == 1: + pass + else: + return ACLManager.loadError() + + listofplugin = json.loads(pObj.config) + try: + index = listofplugin.index(pluginname) + print('index.....%s' % index) + if (index >= 0): + data_ret = {'status': 0, 'deletesPlgin': 0, 'error_message': str('Already Save in your Plugin lis')} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except: + ab = [] + ab = json.loads(pObj.config) + ab.append(pluginname) + pObj.config = json.dumps(ab) + pObj.save() + + data_ret = {'status': 1} + + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + except BaseException as msg: + data_ret = {'status': 0, 'deletesPlgin': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def modifyWebsite(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + + websitesName = ACLManager.findAllSites(currentACL, userID) + phps = PHPManager.findPHPVersions() + proc = httpProc(request, 'websiteFunctions/modifyWebsite.html', + {'websiteList': websitesName, 'phps': phps}, 'modifyWebsite') + return proc.render() + + def deleteWebsite(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + websitesName = ACLManager.findAllSites(currentACL, userID) + proc = httpProc(request, 'websiteFunctions/deleteWebsite.html', + {'websiteList': websitesName}, 'deleteWebsite') + return proc.render() + + def CreateNewDomain(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + websitesName = ACLManager.findAllSites(currentACL, userID) + + try: + admin = Administrator.objects.get(pk=userID) + if admin.defaultSite == 0: + websites = ACLManager.findWebsiteObjects(currentACL, userID) + admin.defaultSite = websites[0].id + admin.save() + except: + pass + + try: + admin = Administrator.objects.get(pk=userID) + defaultDomain = Websites.objects.get(pk=admin.defaultSite).domain + except: + try: + admin = Administrator.objects.get(pk=userID) + websites = ACLManager.findWebsiteObjects(currentACL, userID) + admin.defaultSite = websites[0].id + admin.save() + defaultDomain = websites[0].domain + except: + defaultDomain='NONE' + + + url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" + data = { + "name": "all", + "IP": ACLManager.GetServerIP() + } + + import requests + response = requests.post(url, data=json.dumps(data)) + Status = response.json()['status'] + + test_domain_status = 0 + + if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: + test_domain_status = 1 + + rnpss = randomPassword.generate_pass(10) + proc = httpProc(request, 'websiteFunctions/createDomain.html', + {'websiteList': websitesName, 'phps': PHPManager.findPHPVersions(), 'Randam_String': rnpss, + 'test_domain_data': test_domain_status, 'defaultSite': defaultDomain}) + return proc.render() + + def siteState(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + + websitesName = ACLManager.findAllSites(currentACL, userID) + + proc = httpProc(request, 'websiteFunctions/suspendWebsite.html', + {'websiteList': websitesName}, 'suspendWebsite') + return proc.render() + + def listWebsites(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + pagination = self.websitePagination(currentACL, userID) + proc = httpProc(request, 'websiteFunctions/listWebsites.html', + {"pagination": pagination}) + return proc.render() + + def listChildDomains(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + adminNames = ACLManager.loadAllUsers(userID) + packagesName = ACLManager.loadPackages(userID, currentACL) + phps = PHPManager.findPHPVersions() + + Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps} + proc = httpProc(request, 'websiteFunctions/listChildDomains.html', + Data) + return proc.render() + + def listCron(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(request.GET.get('domain'), admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + proc = httpProc(request, 'websiteFunctions/listCron.html', + {'domain': request.GET.get('domain')}) + return proc.render() + + def domainAlias(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + aliasManager = AliasManager(self.domain) + noAlias, finalAlisList = aliasManager.fetchAlisForDomains() + + path = "/home/" + self.domain + "/public_html" + + proc = httpProc(request, 'websiteFunctions/domainAlias.html', { + 'masterDomain': self.domain, + 'aliases': finalAlisList, + 'path': path, + 'noAlias': noAlias + }) + return proc.render() + + def FetchWPdata(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core version --skip-plugins --skip-themes --path=%s 2>/dev/null' % ( + Vhuser, FinalPHPPath, path) + version = ProcessUtilities.outputExecutioner(command, None, True) + version = html.escape(version) + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin status litespeed-cache --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, path) + lscachee = ProcessUtilities.outputExecutioner(command) + + if lscachee.find('Status: Active') > -1: + lscache = 1 + else: + lscache = 0 + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp config list --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, path) + stdout = ProcessUtilities.outputExecutioner(command) + debugging = 0 + for items in stdout.split('\n'): + if items.find('WP_DEBUG true constant') > -1: + debugging = 1 + break + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp option get blog_public --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, path) + stdoutput = ProcessUtilities.outputExecutioner(command) + searchindex = int(stdoutput.splitlines()[-1]) + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp maintenance-mode status --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, path) + maintenanceMod = ProcessUtilities.outputExecutioner(command) + + result = maintenanceMod.splitlines()[-1] + if result.find('not active') > -1: + maintenanceMode = 0 + else: + maintenanceMode = 1 + + ##### Check passwd protection + vhostName = wpsite.owner.domain + vhostPassDir = f'/home/{vhostName}' + path = f'{vhostPassDir}/{WPManagerID}' + if os.path.exists(path): + passwd = 1 + else: + passwd = 0 + + #### Check WP cron + command = "sudo -u %s cat %s/wp-config.php" % (Vhuser, wpsite.path) + stdout = ProcessUtilities.outputExecutioner(command) + if stdout.find("'DISABLE_WP_CRON', 'true'") > -1: + wpcron = 1 + else: + wpcron = 0 + + fb = { + 'version': version.rstrip('\n'), + 'lscache': lscache, + 'debugging': debugging, + 'searchIndex': searchindex, + 'maintenanceMode': maintenanceMode, + 'passwordprotection': passwd, + 'wpcron': wpcron + + } + + data_ret = {'status': 1, 'error_message': 'None', 'ret_data': fb} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def GetCurrentPlugins(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin list --skip-plugins --skip-themes --format=json --path=%s' % ( + Vhuser, FinalPHPPath, path) + stdoutput = ProcessUtilities.outputExecutioner(command) + json_data = stdoutput.splitlines()[-1] + + data_ret = {'status': 1, 'error_message': 'None', 'plugins': json_data} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def GetCurrentThemes(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp theme list --skip-plugins --skip-themes --format=json --path=%s' % ( + Vhuser, FinalPHPPath, path) + stdoutput = ProcessUtilities.outputExecutioner(command) + json_data = stdoutput.splitlines()[-1] + + data_ret = {'status': 1, 'error_message': 'None', 'themes': json_data} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def fetchstaging(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + from plogical.phpUtilities import phpUtilities + + json_data = phpUtilities.GetStagingInJson(wpsite.wpstaging_set.all().order_by('-id')) + + data_ret = {'status': 1, 'error_message': 'None', 'wpsites': json_data} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def fetchDatabase(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + php = PHPManager.getPHPString(wpsite.owner.phpSelection) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + command = f'{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config get DB_NAME --skip-plugins --skip-themes --path={wpsite.path} 2>/dev/null' + retStatus, stdoutput = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp, True, None, 1) + + if stdoutput.find('Error:') == -1: + DataBaseName = stdoutput.rstrip("\n") + DataBaseName = html.escape(DataBaseName) + else: + data_ret = {'status': 0, 'error_message': stdoutput} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + command = f'{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config get DB_USER --skip-plugins --skip-themes --path={wpsite.path} 2>/dev/null' + retStatus, stdoutput = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp, True, None, 1) + + if stdoutput.find('Error:') == -1: + DataBaseUser = stdoutput.rstrip("\n") + DataBaseUser = html.escape(DataBaseUser) + else: + data_ret = {'status': 0, 'error_message': stdoutput} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + command = f'{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config get table_prefix --skip-plugins --skip-themes --path={wpsite.path} 2>/dev/null' + retStatus, stdoutput = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp, True, None, 1) + + if stdoutput.find('Error:') == -1: + tableprefix = stdoutput.rstrip("\n") + tableprefix = html.escape(tableprefix) + else: + data_ret = {'status': 0, 'error_message': stdoutput} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + data_ret = {'status': 1, 'error_message': 'None', "DataBaseUser": DataBaseUser, + "DataBaseName": DataBaseName, 'tableprefix': tableprefix} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def SaveUpdateConfig(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + Plugins = data['Plugins'] + Themes = data['Themes'] + AutomaticUpdates = data['AutomaticUpdates'] + + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + + php = PHPManager.getPHPString(wpsite.owner.phpSelection) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + if AutomaticUpdates == 'Disabled': + command = f"{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_AUTO_UPDATE_CORE false --raw --allow-root --path=" + wpsite.path + result = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp) + + if result.find('Success:') == -1: + raise BaseException(result) + elif AutomaticUpdates == 'Minor and Security Updates': + command = f"{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_AUTO_UPDATE_CORE minor --allow-root --path=" + wpsite.path + result = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp) + + if result.find('Success:') == -1: + raise BaseException(result) + else: + command = f"{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_AUTO_UPDATE_CORE true --raw --allow-root --path=" + wpsite.path + result = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp) + + if result.find('Success:') == -1: + raise BaseException(result) + + wpsite.AutoUpdates = AutomaticUpdates + wpsite.PluginUpdates = Plugins + wpsite.ThemeUpdates = Themes + wpsite.save() + + data_ret = {'status': 1, 'error_message': 'None', } + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def DeploytoProduction(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + statgingID = data['StagingID'] + wpsite = WPSites.objects.get(pk=WPManagerID) + StagingObj = WPSites.objects.get(pk=statgingID) + + ### + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + if ACLManager.checkOwnership(StagingObj.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + ### + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['statgingID'] = statgingID + extraArgs['WPid'] = WPManagerID + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + background = ApplicationInstaller('DeploytoProduction', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def WPCreateBackup(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + Backuptype = data['Backuptype'] + + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['WPid'] = WPManagerID + extraArgs['Backuptype'] = Backuptype + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + background = ApplicationInstaller('WPCreateBackup', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def RestoreWPbackupNow(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + backupid = data['backupid'] + DesSiteID = data['DesSite'] + + # try: + # + # bwp = WPSites.objects.get(pk=int(backupid)) + # + # if ACLManager.checkOwnership(bwp.owner.domain, admin, currentACL) == 1: + # pass + # else: + # return ACLManager.loadError() + # + # except: + # pass + # + # dwp = WPSites.objects.get(pk=int(DesSiteID)) + # if ACLManager.checkOwnership(dwp.owner.domain, admin, currentACL) == 1: + # pass + # else: + # return ACLManager.loadError() + + Domain = data['Domain'] + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['backupid'] = backupid + extraArgs['DesSiteID'] = DesSiteID + extraArgs['Domain'] = Domain + extraArgs['path'] = data['path'] + extraArgs['home'] = data['home'] + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + background = ApplicationInstaller('RestoreWPbackupNow', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def SaveBackupConfig(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + ConfigType = data['type'] + if ConfigType == 'SFTP': + Hname = data['Hname'] + Uname = data['Uname'] + Passwd = data['Passwd'] + path = data['path'] + config = { + "Hostname": Hname, + "Username": Uname, + "Password": Passwd, + "Path": path + } + elif ConfigType == "S3": + Provider = data['Provider'] + if Provider == "Backblaze": + S3keyname = data['S3keyname'] + SecertKey = data['SecertKey'] + AccessKey = data['AccessKey'] + EndUrl = data['EndUrl'] + config = { + "Provider": Provider, + "S3keyname": S3keyname, + "SecertKey": SecertKey, + "AccessKey": AccessKey, + "EndUrl": EndUrl + + } + else: + S3keyname = data['S3keyname'] + SecertKey = data['SecertKey'] + AccessKey = data['AccessKey'] + config = { + "Provider": Provider, + "S3keyname": S3keyname, + "SecertKey": SecertKey, + "AccessKey": AccessKey, + + } + + mkobj = RemoteBackupConfig(owner=admin, configtype=ConfigType, config=json.dumps(config)) + mkobj.save() + + time.sleep(1) + + data_ret = {'status': 1, 'error_message': 'None', } + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def SaveBackupSchedule(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + FileRetention = data['FileRetention'] + Backfrequency = data['Backfrequency'] + ScheduleName = data['ScheduleName'] + RemoteConfigID = data['RemoteConfigID'] + BackupType = data['BackupType'] + + RemoteBackupConfigobj = RemoteBackupConfig.objects.get(pk=RemoteConfigID) + Rconfig = json.loads(RemoteBackupConfigobj.config) + + try: + # This code is only supposed to run if backups are s3, not for SFTP + provider = Rconfig['Provider'] + if provider == "Backblaze": + EndURl = Rconfig['EndUrl'] + elif provider == "Amazon": + EndURl = "https://s3.us-east-1.amazonaws.com" + elif provider == "Wasabi": + EndURl = "https://s3.wasabisys.com" + + AccessKey = Rconfig['AccessKey'] + SecertKey = Rconfig['SecertKey'] + + session = boto3.session.Session() + + client = session.client( + 's3', + endpoint_url=EndURl, + aws_access_key_id=AccessKey, + aws_secret_access_key=SecertKey, + verify=False + ) + + ############Creating Bucket + BucketName = randomPassword.generate_pass().lower() + + try: + client.create_bucket(Bucket=BucketName) + except BaseException as msg: + logging.CyberCPLogFileWriter.writeToFile("Creating Bucket Error: %s" % str(msg)) + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + config = { + 'BackupType': BackupType, + 'BucketName': BucketName + } + except BaseException as msg: + config = {'BackupType': BackupType} + pass + + svobj = RemoteBackupSchedule(RemoteBackupConfig=RemoteBackupConfigobj, Name=ScheduleName, + timeintervel=Backfrequency, fileretention=FileRetention, + config=json.dumps(config), + lastrun=str(time.time())) + svobj.save() + + data_ret = {'status': 1, 'error_message': 'None', } + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def AddWPsiteforRemoteBackup(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + WPid = data['WpsiteID'] + RemoteScheduleID = data['RemoteScheduleID'] + + wpsiteobj = WPSites.objects.get(pk=WPid) + WPpath = wpsiteobj.path + VHuser = wpsiteobj.owner.externalApp + PhpVersion = wpsiteobj.owner.phpSelection + php = PHPManager.getPHPString(PhpVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + ####Get DB Name + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp config get DB_NAME --skip-plugins --skip-themes --path=%s' % ( + VHuser, FinalPHPPath, WPpath) + result, stdout = ProcessUtilities.outputExecutioner(command, None, None, None, 1) + + if stdout.find('Error:') > -1: + raise BaseException(stdout) + else: + Finaldbname = stdout.rstrip("\n") + + ## Get DB obj + try: + DBobj = Databases.objects.get(dbName=Finaldbname) + except: + raise BaseException(str("DataBase Not Found")) + RemoteScheduleIDobj = RemoteBackupSchedule.objects.get(pk=RemoteScheduleID) + + svobj = RemoteBackupsites(owner=RemoteScheduleIDobj, WPsites=WPid, database=DBobj.pk) + svobj.save() + + data_ret = {'status': 1, 'error_message': 'None', } + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def UpdateRemoteschedules(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + ScheduleID = data['ScheduleID'] + Frequency = data['Frequency'] + FileRetention = data['FileRetention'] + + scheduleobj = RemoteBackupSchedule.objects.get(pk=ScheduleID) + scheduleobj.timeintervel = Frequency + scheduleobj.fileretention = FileRetention + scheduleobj.save() + + data_ret = {'status': 1, 'error_message': 'None', } + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def ScanWordpressSite(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + allweb = Websites.objects.all() + + childdomain = ChildDomains.objects.all() + + for web in allweb: + webpath = "/home/%s/public_html/" % web.domain + command = "cat %swp-config.php" % webpath + result = ProcessUtilities.outputExecutioner(command, web.externalApp) + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(result) + + if result.find('No such file or directory') == -1: + try: + WPSites.objects.get(path=webpath) + except: + wpobj = WPSites(owner=web, title=web.domain, path=webpath, FinalURL=web.domain, + AutoUpdates="Enabled", PluginUpdates="Enabled", + ThemeUpdates="Enabled", ) + wpobj.save() + + for chlid in childdomain: + childPath = chlid.path.rstrip('/') + + command = "cat %s/wp-config.php" % childPath + result = ProcessUtilities.outputExecutioner(command, chlid.master.externalApp) + + if os.path.exists(ProcessUtilities.debugPath): + logging.CyberCPLogFileWriter.writeToFile(result) + + if result.find('No such file or directory') == -1: + fChildPath = f'{childPath}/' + try: + WPSites.objects.get(path=fChildPath) + except: + + wpobj = WPSites(owner=chlid.master, title=chlid.domain, path=fChildPath, FinalURL=chlid.domain, + AutoUpdates="Enabled", PluginUpdates="Enabled", + ThemeUpdates="Enabled", ) + wpobj.save() + + data_ret = {'status': 1, 'error_message': 'None', } + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def installwpcore(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + ###fetch WP version + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core version --skip-plugins --skip-themes --path=%s 2>/dev/null' % ( + Vhuser, FinalPHPPath, path) + version = ProcessUtilities.outputExecutioner(command, None, True) + version = version.rstrip("\n") + + ###install wp core + command = f"sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp core download --force --skip-content --version={version} --path={path}" + output = ProcessUtilities.outputExecutioner(command) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', 'result': output} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def dataintegrity(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + ###fetch WP version + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core verify-checksums --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, path) + result = ProcessUtilities.outputExecutioner(command) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', 'result': result} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def UpdatePlugins(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + plugin = data['plugin'] + pluginarray = data['pluginarray'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['plugin'] = plugin + extraArgs['pluginarray'] = pluginarray + extraArgs['FinalPHPPath'] = FinalPHPPath + extraArgs['path'] = path + extraArgs['Vhuser'] = Vhuser + + background = ApplicationInstaller('UpdateWPPlugin', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def UpdateThemes(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + Theme = data['Theme'] + Themearray = data['Themearray'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['Theme'] = Theme + extraArgs['Themearray'] = Themearray + extraArgs['FinalPHPPath'] = FinalPHPPath + extraArgs['path'] = path + extraArgs['Vhuser'] = Vhuser + + background = ApplicationInstaller('UpdateWPTheme', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def DeletePlugins(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + plugin = data['plugin'] + pluginarray = data['pluginarray'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['plugin'] = plugin + extraArgs['pluginarray'] = pluginarray + extraArgs['FinalPHPPath'] = FinalPHPPath + extraArgs['path'] = path + extraArgs['Vhuser'] = Vhuser + + background = ApplicationInstaller('DeletePlugins', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def DeleteThemes(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + Theme = data['Theme'] + Themearray = data['Themearray'] + wpsite = WPSites.objects.get(pk=WPManagerID) + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['Theme'] = Theme + extraArgs['Themearray'] = Themearray + extraArgs['FinalPHPPath'] = FinalPHPPath + extraArgs['path'] = path + extraArgs['Vhuser'] = Vhuser + + background = ApplicationInstaller('DeleteThemes', extraArgs) + background.start() + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def ChangeStatus(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + plugin = data['plugin'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin status %s --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, plugin, path) + stdoutput = ProcessUtilities.outputExecutioner(command) + + if stdoutput.find('Status: Active') > -1: + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin deactivate %s --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, plugin, path) + stdoutput = ProcessUtilities.outputExecutioner(command) + time.sleep(3) + + else: + + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin activate %s --skip-plugins --skip-themes --path=%s' % ( + Vhuser, FinalPHPPath, plugin, path) + stdoutput = ProcessUtilities.outputExecutioner(command) + time.sleep(3) + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def ChangeStatusThemes(self, userID=None, data=None): + try: + # logging.CyberCPLogFileWriter.writeToFile("Error WP ChangeStatusThemes ....... %s") + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + WPManagerID = data['WPid'] + Theme = data['theme'] + wpsite = WPSites.objects.get(pk=WPManagerID) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = wpsite.path + + Webobj = Websites.objects.get(pk=wpsite.owner_id) + + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['Theme'] = Theme + extraArgs['FinalPHPPath'] = FinalPHPPath + extraArgs['path'] = path + extraArgs['Vhuser'] = Vhuser + + background = ApplicationInstaller('ChangeStatusThemes', extraArgs) + background.start() + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def CreateStagingNow(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + extraArgs = {} + extraArgs['adminID'] = admin.pk + extraArgs['StagingDomain'] = data['StagingDomain'] + extraArgs['StagingName'] = data['StagingName'] + extraArgs['WPid'] = data['WPid'] + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + wpsite = WPSites.objects.get(pk=data['WPid']) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + background = ApplicationInstaller('CreateStagingNow', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException as msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def UpdateWPSettings(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + siteId = data['siteId'] + setting = data['setting'] + value = data['value'] + + wpsite = WPSites.objects.get(pk=siteId) + + if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) != 1: + return ACLManager.loadError() + + # Get PHP version and path + Webobj = Websites.objects.get(pk=wpsite.owner_id) + Vhuser = Webobj.externalApp + PHPVersion = Webobj.phpSelection + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + # Update the appropriate setting based on the setting type + if setting == 'search-indexing': + # Update search engine indexing + command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp option update blog_public {value} --skip-plugins --skip-themes --path={wpsite.path}' + elif setting == 'debugging': + # Update debugging in wp-config.php + if value: + command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_DEBUG true --raw --skip-plugins --skip-themes --path={wpsite.path}' + else: + command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_DEBUG false --raw --skip-plugins --skip-themes --path={wpsite.path}' + elif setting == 'password-protection': + vhostName = wpsite.owner.domain + vhostPassDir = f'/home/{vhostName}' + path = f'{vhostPassDir}/{siteId}' + if value: + # Enable password protection + if not os.path.exists(path): + os.makedirs(path) + htpasswd = f'{path}/.htpasswd' + htaccess = f'{wpsite.path}/.htaccess' + password = randomPassword.generate_pass(12) + + # Create .htpasswd file + command = f"htpasswd -cb {htpasswd} admin {password}" + ProcessUtilities.executioner(command) + + # Create .htaccess file + htaccess_content = f"""AuthType Basic +AuthName "Restricted Access" +AuthUserFile {htpasswd} Require valid-user""" with open(htaccess, 'w') as f: f.write(htaccess_content) From 80c67ac079083a1afa94b8ac57f614f9ba08acb7 Mon Sep 17 00:00:00 2001 From: usmannasir Date: Sat, 5 Apr 2025 00:39:03 +0500 Subject: [PATCH 022/273] update code to add design from main wp page --- websiteFunctions/website.py | 47 +++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/websiteFunctions/website.py b/websiteFunctions/website.py index f64e7470a..6aaf67cd7 100755 --- a/websiteFunctions/website.py +++ b/websiteFunctions/website.py @@ -14938,6 +14938,53 @@ StrictHostKeyChecking no php = ACLManager.getPHPString(PHPVersion) FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + for site in wp_sites: + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core version --skip-plugins --skip-themes --path=%s 2>/dev/null' % ( + Vhuser, FinalPHPPath, site.path) + version = ProcessUtilities.outputExecutioner(command, None, True) + version = html.escape(version) + + # Generate screenshot URL + site_url = site.FinalURL + if not site_url.startswith(('http://', 'https://')): + site_url = f'https://{site_url}' + + sites.append({ + 'id': site.id, + 'title': site.title, + 'url': site.FinalURL, + 'path': site.path, + 'version': version, + 'screenshot': f'https://api.microlink.io/?url={site_url}&screenshot=true&meta=false&embed=screenshot.url' + }) + + data_ret = {'status': 1, 'fetchStatus': 1, 'error_message': "None", "sites": sites} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'fetchStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + domain = data['domain'] + website = Websites.objects.get(domain=domain) + + if ACLManager.checkOwnership(domain, admin, currentACL) != 1: + return ACLManager.loadErrorJson('fetchStatus', 0) + + wp_sites = WPSites.objects.filter(owner=website) + sites = [] + + Vhuser = website.externalApp + PHPVersion = website.phpSelection + + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + for site in wp_sites: command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core version --skip-plugins --skip-themes --path=%s 2>/dev/null' % ( From 87cb7eb65a842515843607f85babb7afe00373f9 Mon Sep 17 00:00:00 2001 From: usmannasir Date: Sat, 5 Apr 2025 00:46:04 +0500 Subject: [PATCH 023/273] update code to add design from main wp page --- static/websiteFunctions/websiteFunctions.js | 8 + .../websiteFunctions/listWebsites.html | 4 +- websiteFunctions/website.py | 7911 ----------------- 3 files changed, 10 insertions(+), 7913 deletions(-) diff --git a/static/websiteFunctions/websiteFunctions.js b/static/websiteFunctions/websiteFunctions.js index 0520c2956..70987a875 100644 --- a/static/websiteFunctions/websiteFunctions.js +++ b/static/websiteFunctions/websiteFunctions.js @@ -384,6 +384,14 @@ app.controller('listWebsites', function ($scope, $http, $window) { }; + $scope.getFullUrl = function(url) { + if (!url) return ''; + if (url.startsWith('http://') || url.startsWith('https://')) { + return url; + } + return 'https://' + url; + }; + $scope.showWPSites = function(domain) { var site = $scope.WebSitesList.find(function(site) { return site.domain === domain; diff --git a/websiteFunctions/templates/websiteFunctions/listWebsites.html b/websiteFunctions/templates/websiteFunctions/listWebsites.html index 1fcf6cc33..60cfa4866 100755 --- a/websiteFunctions/templates/websiteFunctions/listWebsites.html +++ b/websiteFunctions/templates/websiteFunctions/listWebsites.html @@ -134,13 +134,13 @@
    - {$ wp.title $}
    - + Visit Site diff --git a/websiteFunctions/website.py b/websiteFunctions/website.py index 6aaf67cd7..280191367 100755 --- a/websiteFunctions/website.py +++ b/websiteFunctions/website.py @@ -1987,7870 +1987,6 @@ class WebsiteManager: htaccess_content = f"""AuthType Basic AuthName "Restricted Access" AuthUserFile {htpasswd} -Require valid-user""" - with open(htaccess, 'w') as f: - f.write(htaccess_content) - -#!/usr/local/CyberCP/bin/python -import html -import os -import os.path -import sys -import django - -from databases.models import Databases -from plogical.DockerSites import Docker_Sites -from plogical.httpProc import httpProc - -sys.path.append('/usr/local/CyberCP') -os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings") -django.setup() -import json -from plogical.acl import ACLManager -import plogical.CyberCPLogFileWriter as logging -from websiteFunctions.models import Websites, ChildDomains, GitLogs, wpplugins, WPSites, WPStaging, WPSitesBackup, \ - RemoteBackupConfig, RemoteBackupSchedule, RemoteBackupsites, DockerPackages, PackageAssignment, DockerSites -from plogical.virtualHostUtilities import virtualHostUtilities -import subprocess -import shlex -from plogical.installUtilities import installUtilities -from django.shortcuts import HttpResponse, render, redirect -from loginSystem.models import Administrator, ACL -from packages.models import Package -from plogical.mailUtilities import mailUtilities -from random import randint -import time -import re -import boto3 -from plogical.childDomain import ChildDomainManager -from math import ceil -from plogical.alias import AliasManager -from plogical.applicationInstaller import ApplicationInstaller -from plogical import hashPassword, randomPassword -from emailMarketing.emACL import emACL -from plogical.processUtilities import ProcessUtilities -from managePHP.phpManager import PHPManager -from ApachController.ApacheVhosts import ApacheVhost -from plogical.vhostConfs import vhostConfs -from plogical.cronUtil import CronUtil -from .StagingSetup import StagingSetup -import validators -from django.http import JsonResponse - - -class WebsiteManager: - apache = 1 - ols = 2 - lsws = 3 - - def __init__(self, domain=None, childDomain=None): - self.domain = domain - self.childDomain = childDomain - - def createWebsite(self, request=None, userID=None, data=None): - - url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" - data = { - "name": "all", - "IP": ACLManager.GetServerIP() - } - - import requests - response = requests.post(url, data=json.dumps(data)) - Status = response.json()['status'] - - test_domain_status = 0 - - if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: - test_domain_status = 1 - - currentACL = ACLManager.loadedACL(userID) - adminNames = ACLManager.loadAllUsers(userID) - packagesName = ACLManager.loadPackages(userID, currentACL) - phps = PHPManager.findPHPVersions() - - rnpss = randomPassword.generate_pass(10) - - Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps, 'Randam_String': rnpss.lower(), - 'test_domain_data': test_domain_status} - proc = httpProc(request, 'websiteFunctions/createWebsite.html', - Data, 'createWebsite') - return proc.render() - - def WPCreate(self, request=None, userID=None, data=None): - url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" - data = { - "name": "wp-manager", - "IP": ACLManager.GetServerIP() - } - - import requests - response = requests.post(url, data=json.dumps(data)) - Status = response.json()['status'] - - - if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: - currentACL = ACLManager.loadedACL(userID) - adminNames = ACLManager.loadAllUsers(userID) - packagesName = ACLManager.loadPackages(userID, currentACL) - - if len(packagesName) == 0: - packagesName = ['Default'] - - FinalVersions = [] - userobj = Administrator.objects.get(pk=userID) - counter = 0 - try: - import requests - WPVersions = json.loads(requests.get('https://api.wordpress.org/core/version-check/1.7/').text)[ - 'offers'] - - for versions in WPVersions: - if counter == 7: - break - if versions['current'] not in FinalVersions: - FinalVersions.append(versions['current']) - counter = counter + 1 - except: - FinalVersions = ['5.6', '5.5.3', '5.5.2'] - - Plugins = wpplugins.objects.filter(owner=userobj) - rnpss = randomPassword.generate_pass(10) - - ## - - test_domain_status = 1 - - Data = {'packageList': packagesName, "owernList": adminNames, 'WPVersions': FinalVersions, - 'Plugins': Plugins, 'Randam_String': rnpss.lower(), 'test_domain_data': test_domain_status} - proc = httpProc(request, 'websiteFunctions/WPCreate.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def ListWPSites(self, request=None, userID=None, DeleteID=None): - import json - currentACL = ACLManager.loadedACL(userID) - - admin = Administrator.objects.get(pk=userID) - data = {} - wp_sites = ACLManager.GetALLWPObjects(currentACL, userID) - data['wp'] = wp_sites - - try: - if DeleteID != None: - WPDelete = WPSites.objects.get(pk=DeleteID) - - if ACLManager.checkOwnership(WPDelete.owner.domain, admin, currentACL) == 1: - WPDelete.delete() - except BaseException as msg: - pass - - sites = [] - for site in data['wp']: - sites.append({ - 'id': site.id, - 'title': site.title, - 'url': site.FinalURL, - 'production_status': True - }) - - context = { - "wpsite": json.dumps(sites), - "status": 1, - "total_sites": len(sites), - "debug_info": json.dumps({ - "user_id": userID, - "is_admin": bool(currentACL.get('admin', 0)), - "wp_sites_count": wp_sites.count() - }) - } - - proc = httpProc(request, 'websiteFunctions/WPsitesList.html', context) - return proc.render() - - def WPHome(self, request=None, userID=None, WPid=None, DeleteID=None): - Data = {} - currentACL = ACLManager.loadedACL(userID) - WPobj = WPSites.objects.get(pk=WPid) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(WPobj.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - try: - - url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" - data = { - "name": "wp-manager", - "IP": ACLManager.GetServerIP() - } - - import requests - response = requests.post(url, data=json.dumps(data)) - Status = response.json()['status'] - - rnpss = randomPassword.generate_pass(10) - - Data['Randam_String'] = rnpss.lower() - - if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: - Data['wpsite'] = WPobj - Data['test_domain_data'] = 1 - - try: - DeleteID = request.GET.get('DeleteID', None) - - if DeleteID != None: - wstagingDelete = WPStaging.objects.get(pk=DeleteID, owner=WPobj) - wstagingDelete.delete() - - except BaseException as msg: - da = str(msg) - - proc = httpProc(request, 'websiteFunctions/WPsiteHome.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - except: - proc = httpProc(request, 'websiteFunctions/WPsiteHome.html', - Data, 'createDatabase') - return proc.render() - - def RestoreHome(self, request=None, userID=None, BackupID=None): - Data = {} - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.CheckForPremFeature('wp-manager'): - - Data['backupobj'] = WPSitesBackup.objects.get(pk=BackupID) - - if ACLManager.CheckIPBackupObjectOwner(currentACL, Data['backupobj'], admin) == 1: - pass - else: - return ACLManager.loadError() - - config = json.loads(Data['backupobj'].config) - Data['FileName'] = config['name'] - try: - Data['Backuptype'] = config['Backuptype'] - - if Data['Backuptype'] == 'DataBase Backup' or Data['Backuptype'] == 'Website Backup': - Data['WPsites'] = [WPSites.objects.get(pk=Data['backupobj'].WPSiteID)] - else: - Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) - - except: - Data['Backuptype'] = None - Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) - - proc = httpProc(request, 'websiteFunctions/WPRestoreHome.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def RemoteBackupConfig(self, request=None, userID=None, DeleteID=None): - Data = {} - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - try: - if DeleteID != None: - BackupconfigDelete = RemoteBackupConfig.objects.get(pk=DeleteID) - BackupconfigDelete.delete() - except: - pass - - if ACLManager.CheckForPremFeature('wp-manager'): - - Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) - allcon = RemoteBackupConfig.objects.all() - Data['backupconfigs'] = [] - for i in allcon: - configr = json.loads(i.config) - if i.configtype == "SFTP": - Data['backupconfigs'].append({ - 'id': i.pk, - 'Type': i.configtype, - 'HostName': configr['Hostname'], - 'Path': configr['Path'] - }) - elif i.configtype == "S3": - Provider = configr['Provider'] - if Provider == "Backblaze": - Data['backupconfigs'].append({ - 'id': i.pk, - 'Type': i.configtype, - 'HostName': Provider, - 'Path': configr['S3keyname'] - }) - else: - Data['backupconfigs'].append({ - 'id': i.pk, - 'Type': i.configtype, - 'HostName': Provider, - 'Path': configr['S3keyname'] - }) - - proc = httpProc(request, 'websiteFunctions/RemoteBackupConfig.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def BackupfileConfig(self, request=None, userID=None, RemoteConfigID=None, DeleteID=None): - Data = {} - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - Data['RemoteConfigID'] = RemoteConfigID - RemoteConfigobj = RemoteBackupConfig.objects.get(pk=RemoteConfigID) - try: - if DeleteID != None: - RemoteBackupConfigDelete = RemoteBackupSchedule.objects.get(pk=DeleteID) - RemoteBackupConfigDelete.delete() - except: - pass - - if ACLManager.CheckForPremFeature('wp-manager'): - Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) - allsechedule = RemoteBackupSchedule.objects.filter(RemoteBackupConfig=RemoteConfigobj) - Data['Backupschedule'] = [] - for i in allsechedule: - lastrun = i.lastrun - LastRun = time.strftime('%Y-%m-%d', time.localtime(float(lastrun))) - Data['Backupschedule'].append({ - 'id': i.pk, - 'Name': i.Name, - 'RemoteConfiguration': i.RemoteBackupConfig.configtype, - 'Retention': i.fileretention, - 'Frequency': i.timeintervel, - 'LastRun': LastRun - }) - proc = httpProc(request, 'websiteFunctions/BackupfileConfig.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def AddRemoteBackupsite(self, request=None, userID=None, RemoteScheduleID=None, DeleteSiteID=None): - Data = {} - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - Data['RemoteScheduleID'] = RemoteScheduleID - RemoteBackupScheduleobj = RemoteBackupSchedule.objects.get(pk=RemoteScheduleID) - - try: - if DeleteSiteID != None: - RemoteBackupsitesDelete = RemoteBackupsites.objects.get(pk=DeleteSiteID) - RemoteBackupsitesDelete.delete() - except: - pass - - if ACLManager.CheckForPremFeature('wp-manager'): - Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) - allRemoteBackupsites = RemoteBackupsites.objects.filter(owner=RemoteBackupScheduleobj) - Data['RemoteBackupsites'] = [] - for i in allRemoteBackupsites: - try: - wpsite = WPSites.objects.get(pk=i.WPsites) - Data['RemoteBackupsites'].append({ - 'id': i.pk, - 'Title': wpsite.title, - }) - except: - pass - proc = httpProc(request, 'websiteFunctions/AddRemoteBackupSite.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def WordpressPricing(self, request=None, userID=None, ): - Data = {} - proc = httpProc(request, 'websiteFunctions/CyberpanelPricing.html', Data, 'createWebsite') - return proc.render() - - def RestoreBackups(self, request=None, userID=None, DeleteID=None): - Data = {} - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" - data = { - "name": "wp-manager", - "IP": ACLManager.GetServerIP() - } - - import requests - response = requests.post(url, data=json.dumps(data)) - Status = response.json()['status'] - - if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: - - backobj = WPSitesBackup.objects.filter(owner=admin).order_by('-id') - - # if ACLManager.CheckIPBackupObjectOwner(currentACL, backobj, admin) == 1: - # pass - # else: - # return ACLManager.loadError() - - try: - if DeleteID != None: - DeleteIDobj = WPSitesBackup.objects.get(pk=DeleteID) - - if ACLManager.CheckIPBackupObjectOwner(currentACL, DeleteIDobj, admin) == 1: - config = DeleteIDobj.config - conf = json.loads(config) - FileName = conf['name'] - command = "rm -r /home/backup/%s.tar.gz" % FileName - ProcessUtilities.executioner(command) - DeleteIDobj.delete() - - except BaseException as msg: - pass - Data['job'] = [] - - for sub in backobj: - try: - wpsite = WPSites.objects.get(pk=sub.WPSiteID) - web = wpsite.title - except: - web = "Website Not Found" - - try: - config = sub.config - conf = json.loads(config) - Backuptype = conf['Backuptype'] - BackupDestination = conf['BackupDestination'] - except: - Backuptype = "Backup type not exists" - - Data['job'].append({ - 'id': sub.id, - 'title': web, - 'Backuptype': Backuptype, - 'BackupDestination': BackupDestination - }) - - proc = httpProc(request, 'websiteFunctions/RestoreBackups.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def AutoLogin(self, request=None, userID=None): - - WPid = request.GET.get('id') - currentACL = ACLManager.loadedACL(userID) - WPobj = WPSites.objects.get(pk=WPid) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(WPobj.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - from managePHP.phpManager import PHPManager - - php = PHPManager.getPHPString(WPobj.owner.phpSelection) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" - data = { - "name": "wp-manager", - "IP": ACLManager.GetServerIP() - } - - import requests - response = requests.post(url, data=json.dumps(data)) - Status = response.json()['status'] - - if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: - - ## Get title - - password = randomPassword.generate_pass(10) - - command = f'sudo -u %s {FinalPHPPath} /usr/bin/wp user create autologin %s --role=administrator --user_pass="%s" --path=%s --skip-plugins --skip-themes' % ( - WPobj.owner.externalApp, 'autologin@cloudpages.cloud', password, WPobj.path) - ProcessUtilities.executioner(command) - - command = f'sudo -u %s {FinalPHPPath} /usr/bin/wp user update autologin --user_pass="%s" --path=%s --skip-plugins --skip-themes' % ( - WPobj.owner.externalApp, password, WPobj.path) - ProcessUtilities.executioner(command) - - data = {} - - if WPobj.FinalURL.endswith('/'): - FinalURL = WPobj.FinalURL[:-1] - else: - FinalURL = WPobj.FinalURL - - data['url'] = 'https://%s' % (FinalURL) - data['userName'] = 'autologin' - data['password'] = password - - proc = httpProc(request, 'websiteFunctions/AutoLogin.html', - data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def ConfigurePlugins(self, request=None, userID=None, data=None): - - if ACLManager.CheckForPremFeature('wp-manager'): - currentACL = ACLManager.loadedACL(userID) - userobj = Administrator.objects.get(pk=userID) - - Selectedplugins = wpplugins.objects.filter(owner=userobj) - # data['Selectedplugins'] = wpplugins.objects.filter(ProjectOwner=HostingCompany) - - Data = {'Selectedplugins': Selectedplugins, } - proc = httpProc(request, 'websiteFunctions/WPConfigurePlugins.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def Addnewplugin(self, request=None, userID=None, data=None): - from django.shortcuts import reverse - if ACLManager.CheckForPremFeature('wp-manager'): - currentACL = ACLManager.loadedACL(userID) - adminNames = ACLManager.loadAllUsers(userID) - packagesName = ACLManager.loadPackages(userID, currentACL) - phps = PHPManager.findPHPVersions() - - Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps} - proc = httpProc(request, 'websiteFunctions/WPAddNewPlugin.html', - Data, 'createDatabase') - return proc.render() - - return redirect(reverse('pricing')) - - def SearchOnkeyupPlugin(self, userID=None, data=None): - try: - if ACLManager.CheckForPremFeature('wp-manager'): - currentACL = ACLManager.loadedACL(userID) - - pluginname = data['pluginname'] - # logging.CyberCPLogFileWriter.writeToFile("Plugin Name ....... %s"%pluginname) - - url = "http://api.wordpress.org/plugins/info/1.1/?action=query_plugins&request[search]=%s" % str( - pluginname) - import requests - - res = requests.get(url) - r = res.json() - - # return proc.ajax(1, 'Done', {'plugins': r}) - - data_ret = {'status': 1, 'plugns': r, } - - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': 'Premium feature not available.'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def AddNewpluginAjax(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - - userobj = Administrator.objects.get(pk=userID) - - config = data['config'] - Name = data['Name'] - # pluginname = data['pluginname'] - # logging.CyberCPLogFileWriter.writeToFile("config ....... %s"%config) - # logging.CyberCPLogFileWriter.writeToFile(" Name ....... %s"%Name) - - addpl = wpplugins(Name=Name, config=json.dumps(config), owner=userobj) - addpl.save() - - data_ret = {'status': 1} - - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'AddNewpluginAjax': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def EidtPlugin(self, request=None, userID=None, pluginbID=None): - Data = {} - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - pluginobj = wpplugins.objects.get(pk=pluginbID) - - if ACLManager.CheckIPPluginObjectOwner(currentACL, pluginobj, admin) == 1: - pass - else: - return ACLManager.loadError() - - lmo = json.loads(pluginobj.config) - Data['Selectedplugins'] = lmo - Data['pluginbID'] = pluginbID - Data['BucketName'] = pluginobj.Name - - proc = httpProc(request, 'websiteFunctions/WPEidtPlugin.html', - Data, 'createDatabase') - return proc.render() - - def deletesPlgin(self, userID=None, data=None, ): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - userobj = Administrator.objects.get(pk=userID) - pluginname = data['pluginname'] - pluginbBucketID = data['pluginbBucketID'] - # logging.CyberCPLogFileWriter.writeToFile("pluginbID ....... %s" % pluginbBucketID) - # logging.CyberCPLogFileWriter.writeToFile("pluginname ....... %s" % pluginname) - - obj = wpplugins.objects.get(pk=pluginbBucketID, owner=userobj) - - if ACLManager.CheckIPPluginObjectOwner(currentACL, obj, admin) == 1: - pass - else: - return ACLManager.loadError() - - ab = [] - ab = json.loads(obj.config) - ab.remove(pluginname) - obj.config = json.dumps(ab) - obj.save() - - data_ret = {'status': 1} - - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except BaseException as msg: - data_ret = {'status': 0, 'deletesPlgin': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def Addplugineidt(self, userID=None, data=None, ): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - userobj = Administrator.objects.get(pk=userID) - pluginname = data['pluginname'] - pluginbBucketID = data['pluginbBucketID'] - - # logging.CyberCPLogFileWriter.writeToFile("pluginbID ....... %s" % pluginbBucketID) - # logging.CyberCPLogFileWriter.writeToFile("pluginname ....... %s" % pluginname) - - pObj = wpplugins.objects.get(pk=pluginbBucketID, owner=userobj) - - if ACLManager.CheckIPPluginObjectOwner(currentACL, pObj, admin) == 1: - pass - else: - return ACLManager.loadError() - - listofplugin = json.loads(pObj.config) - try: - index = listofplugin.index(pluginname) - print('index.....%s' % index) - if (index >= 0): - data_ret = {'status': 0, 'deletesPlgin': 0, 'error_message': str('Already Save in your Plugin lis')} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except: - ab = [] - ab = json.loads(pObj.config) - ab.append(pluginname) - pObj.config = json.dumps(ab) - pObj.save() - - data_ret = {'status': 1} - - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except BaseException as msg: - data_ret = {'status': 0, 'deletesPlgin': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def modifyWebsite(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - - websitesName = ACLManager.findAllSites(currentACL, userID) - phps = PHPManager.findPHPVersions() - proc = httpProc(request, 'websiteFunctions/modifyWebsite.html', - {'websiteList': websitesName, 'phps': phps}, 'modifyWebsite') - return proc.render() - - def deleteWebsite(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - websitesName = ACLManager.findAllSites(currentACL, userID) - proc = httpProc(request, 'websiteFunctions/deleteWebsite.html', - {'websiteList': websitesName}, 'deleteWebsite') - return proc.render() - - def CreateNewDomain(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - websitesName = ACLManager.findAllSites(currentACL, userID) - - try: - admin = Administrator.objects.get(pk=userID) - if admin.defaultSite == 0: - websites = ACLManager.findWebsiteObjects(currentACL, userID) - admin.defaultSite = websites[0].id - admin.save() - except: - pass - - try: - admin = Administrator.objects.get(pk=userID) - defaultDomain = Websites.objects.get(pk=admin.defaultSite).domain - except: - try: - admin = Administrator.objects.get(pk=userID) - websites = ACLManager.findWebsiteObjects(currentACL, userID) - admin.defaultSite = websites[0].id - admin.save() - defaultDomain = websites[0].domain - except: - defaultDomain='NONE' - - - url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" - data = { - "name": "all", - "IP": ACLManager.GetServerIP() - } - - import requests - response = requests.post(url, data=json.dumps(data)) - Status = response.json()['status'] - - test_domain_status = 0 - - if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: - test_domain_status = 1 - - rnpss = randomPassword.generate_pass(10) - proc = httpProc(request, 'websiteFunctions/createDomain.html', - {'websiteList': websitesName, 'phps': PHPManager.findPHPVersions(), 'Randam_String': rnpss, - 'test_domain_data': test_domain_status, 'defaultSite': defaultDomain}) - return proc.render() - - def siteState(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - - websitesName = ACLManager.findAllSites(currentACL, userID) - - proc = httpProc(request, 'websiteFunctions/suspendWebsite.html', - {'websiteList': websitesName}, 'suspendWebsite') - return proc.render() - - def listWebsites(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - pagination = self.websitePagination(currentACL, userID) - proc = httpProc(request, 'websiteFunctions/listWebsites.html', - {"pagination": pagination}) - return proc.render() - - def listChildDomains(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - adminNames = ACLManager.loadAllUsers(userID) - packagesName = ACLManager.loadPackages(userID, currentACL) - phps = PHPManager.findPHPVersions() - - Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps} - proc = httpProc(request, 'websiteFunctions/listChildDomains.html', - Data) - return proc.render() - - def listCron(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(request.GET.get('domain'), admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - proc = httpProc(request, 'websiteFunctions/listCron.html', - {'domain': request.GET.get('domain')}) - return proc.render() - - def domainAlias(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - aliasManager = AliasManager(self.domain) - noAlias, finalAlisList = aliasManager.fetchAlisForDomains() - - path = "/home/" + self.domain + "/public_html" - - proc = httpProc(request, 'websiteFunctions/domainAlias.html', { - 'masterDomain': self.domain, - 'aliases': finalAlisList, - 'path': path, - 'noAlias': noAlias - }) - return proc.render() - - def FetchWPdata(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core version --skip-plugins --skip-themes --path=%s 2>/dev/null' % ( - Vhuser, FinalPHPPath, path) - version = ProcessUtilities.outputExecutioner(command, None, True) - version = html.escape(version) - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin status litespeed-cache --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, path) - lscachee = ProcessUtilities.outputExecutioner(command) - - if lscachee.find('Status: Active') > -1: - lscache = 1 - else: - lscache = 0 - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp config list --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, path) - stdout = ProcessUtilities.outputExecutioner(command) - debugging = 0 - for items in stdout.split('\n'): - if items.find('WP_DEBUG true constant') > -1: - debugging = 1 - break - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp option get blog_public --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, path) - stdoutput = ProcessUtilities.outputExecutioner(command) - searchindex = int(stdoutput.splitlines()[-1]) - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp maintenance-mode status --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, path) - maintenanceMod = ProcessUtilities.outputExecutioner(command) - - result = maintenanceMod.splitlines()[-1] - if result.find('not active') > -1: - maintenanceMode = 0 - else: - maintenanceMode = 1 - - ##### Check passwd protection - vhostName = wpsite.owner.domain - vhostPassDir = f'/home/{vhostName}' - path = f'{vhostPassDir}/{WPManagerID}' - if os.path.exists(path): - passwd = 1 - else: - passwd = 0 - - #### Check WP cron - command = "sudo -u %s cat %s/wp-config.php" % (Vhuser, wpsite.path) - stdout = ProcessUtilities.outputExecutioner(command) - if stdout.find("'DISABLE_WP_CRON', 'true'") > -1: - wpcron = 1 - else: - wpcron = 0 - - fb = { - 'version': version.rstrip('\n'), - 'lscache': lscache, - 'debugging': debugging, - 'searchIndex': searchindex, - 'maintenanceMode': maintenanceMode, - 'passwordprotection': passwd, - 'wpcron': wpcron - - } - - data_ret = {'status': 1, 'error_message': 'None', 'ret_data': fb} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def GetCurrentPlugins(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin list --skip-plugins --skip-themes --format=json --path=%s' % ( - Vhuser, FinalPHPPath, path) - stdoutput = ProcessUtilities.outputExecutioner(command) - json_data = stdoutput.splitlines()[-1] - - data_ret = {'status': 1, 'error_message': 'None', 'plugins': json_data} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def GetCurrentThemes(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp theme list --skip-plugins --skip-themes --format=json --path=%s' % ( - Vhuser, FinalPHPPath, path) - stdoutput = ProcessUtilities.outputExecutioner(command) - json_data = stdoutput.splitlines()[-1] - - data_ret = {'status': 1, 'error_message': 'None', 'themes': json_data} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def fetchstaging(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - from plogical.phpUtilities import phpUtilities - - json_data = phpUtilities.GetStagingInJson(wpsite.wpstaging_set.all().order_by('-id')) - - data_ret = {'status': 1, 'error_message': 'None', 'wpsites': json_data} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def fetchDatabase(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - php = PHPManager.getPHPString(wpsite.owner.phpSelection) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - command = f'{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config get DB_NAME --skip-plugins --skip-themes --path={wpsite.path} 2>/dev/null' - retStatus, stdoutput = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp, True, None, 1) - - if stdoutput.find('Error:') == -1: - DataBaseName = stdoutput.rstrip("\n") - DataBaseName = html.escape(DataBaseName) - else: - data_ret = {'status': 0, 'error_message': stdoutput} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - command = f'{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config get DB_USER --skip-plugins --skip-themes --path={wpsite.path} 2>/dev/null' - retStatus, stdoutput = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp, True, None, 1) - - if stdoutput.find('Error:') == -1: - DataBaseUser = stdoutput.rstrip("\n") - DataBaseUser = html.escape(DataBaseUser) - else: - data_ret = {'status': 0, 'error_message': stdoutput} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - command = f'{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config get table_prefix --skip-plugins --skip-themes --path={wpsite.path} 2>/dev/null' - retStatus, stdoutput = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp, True, None, 1) - - if stdoutput.find('Error:') == -1: - tableprefix = stdoutput.rstrip("\n") - tableprefix = html.escape(tableprefix) - else: - data_ret = {'status': 0, 'error_message': stdoutput} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - data_ret = {'status': 1, 'error_message': 'None', "DataBaseUser": DataBaseUser, - "DataBaseName": DataBaseName, 'tableprefix': tableprefix} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def SaveUpdateConfig(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - Plugins = data['Plugins'] - Themes = data['Themes'] - AutomaticUpdates = data['AutomaticUpdates'] - - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - - php = PHPManager.getPHPString(wpsite.owner.phpSelection) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - if AutomaticUpdates == 'Disabled': - command = f"{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_AUTO_UPDATE_CORE false --raw --allow-root --path=" + wpsite.path - result = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp) - - if result.find('Success:') == -1: - raise BaseException(result) - elif AutomaticUpdates == 'Minor and Security Updates': - command = f"{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_AUTO_UPDATE_CORE minor --allow-root --path=" + wpsite.path - result = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp) - - if result.find('Success:') == -1: - raise BaseException(result) - else: - command = f"{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_AUTO_UPDATE_CORE true --raw --allow-root --path=" + wpsite.path - result = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp) - - if result.find('Success:') == -1: - raise BaseException(result) - - wpsite.AutoUpdates = AutomaticUpdates - wpsite.PluginUpdates = Plugins - wpsite.ThemeUpdates = Themes - wpsite.save() - - data_ret = {'status': 1, 'error_message': 'None', } - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def DeploytoProduction(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - statgingID = data['StagingID'] - wpsite = WPSites.objects.get(pk=WPManagerID) - StagingObj = WPSites.objects.get(pk=statgingID) - - ### - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - if ACLManager.checkOwnership(StagingObj.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - ### - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['statgingID'] = statgingID - extraArgs['WPid'] = WPManagerID - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - background = ApplicationInstaller('DeploytoProduction', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def WPCreateBackup(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - Backuptype = data['Backuptype'] - - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['WPid'] = WPManagerID - extraArgs['Backuptype'] = Backuptype - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - background = ApplicationInstaller('WPCreateBackup', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def RestoreWPbackupNow(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - backupid = data['backupid'] - DesSiteID = data['DesSite'] - - # try: - # - # bwp = WPSites.objects.get(pk=int(backupid)) - # - # if ACLManager.checkOwnership(bwp.owner.domain, admin, currentACL) == 1: - # pass - # else: - # return ACLManager.loadError() - # - # except: - # pass - # - # dwp = WPSites.objects.get(pk=int(DesSiteID)) - # if ACLManager.checkOwnership(dwp.owner.domain, admin, currentACL) == 1: - # pass - # else: - # return ACLManager.loadError() - - Domain = data['Domain'] - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['backupid'] = backupid - extraArgs['DesSiteID'] = DesSiteID - extraArgs['Domain'] = Domain - extraArgs['path'] = data['path'] - extraArgs['home'] = data['home'] - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - background = ApplicationInstaller('RestoreWPbackupNow', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def SaveBackupConfig(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - ConfigType = data['type'] - if ConfigType == 'SFTP': - Hname = data['Hname'] - Uname = data['Uname'] - Passwd = data['Passwd'] - path = data['path'] - config = { - "Hostname": Hname, - "Username": Uname, - "Password": Passwd, - "Path": path - } - elif ConfigType == "S3": - Provider = data['Provider'] - if Provider == "Backblaze": - S3keyname = data['S3keyname'] - SecertKey = data['SecertKey'] - AccessKey = data['AccessKey'] - EndUrl = data['EndUrl'] - config = { - "Provider": Provider, - "S3keyname": S3keyname, - "SecertKey": SecertKey, - "AccessKey": AccessKey, - "EndUrl": EndUrl - - } - else: - S3keyname = data['S3keyname'] - SecertKey = data['SecertKey'] - AccessKey = data['AccessKey'] - config = { - "Provider": Provider, - "S3keyname": S3keyname, - "SecertKey": SecertKey, - "AccessKey": AccessKey, - - } - - mkobj = RemoteBackupConfig(owner=admin, configtype=ConfigType, config=json.dumps(config)) - mkobj.save() - - time.sleep(1) - - data_ret = {'status': 1, 'error_message': 'None', } - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def SaveBackupSchedule(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - FileRetention = data['FileRetention'] - Backfrequency = data['Backfrequency'] - ScheduleName = data['ScheduleName'] - RemoteConfigID = data['RemoteConfigID'] - BackupType = data['BackupType'] - - RemoteBackupConfigobj = RemoteBackupConfig.objects.get(pk=RemoteConfigID) - Rconfig = json.loads(RemoteBackupConfigobj.config) - - try: - # This code is only supposed to run if backups are s3, not for SFTP - provider = Rconfig['Provider'] - if provider == "Backblaze": - EndURl = Rconfig['EndUrl'] - elif provider == "Amazon": - EndURl = "https://s3.us-east-1.amazonaws.com" - elif provider == "Wasabi": - EndURl = "https://s3.wasabisys.com" - - AccessKey = Rconfig['AccessKey'] - SecertKey = Rconfig['SecertKey'] - - session = boto3.session.Session() - - client = session.client( - 's3', - endpoint_url=EndURl, - aws_access_key_id=AccessKey, - aws_secret_access_key=SecertKey, - verify=False - ) - - ############Creating Bucket - BucketName = randomPassword.generate_pass().lower() - - try: - client.create_bucket(Bucket=BucketName) - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile("Creating Bucket Error: %s" % str(msg)) - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - config = { - 'BackupType': BackupType, - 'BucketName': BucketName - } - except BaseException as msg: - config = {'BackupType': BackupType} - pass - - svobj = RemoteBackupSchedule(RemoteBackupConfig=RemoteBackupConfigobj, Name=ScheduleName, - timeintervel=Backfrequency, fileretention=FileRetention, - config=json.dumps(config), - lastrun=str(time.time())) - svobj.save() - - data_ret = {'status': 1, 'error_message': 'None', } - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def AddWPsiteforRemoteBackup(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - WPid = data['WpsiteID'] - RemoteScheduleID = data['RemoteScheduleID'] - - wpsiteobj = WPSites.objects.get(pk=WPid) - WPpath = wpsiteobj.path - VHuser = wpsiteobj.owner.externalApp - PhpVersion = wpsiteobj.owner.phpSelection - php = PHPManager.getPHPString(PhpVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - ####Get DB Name - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp config get DB_NAME --skip-plugins --skip-themes --path=%s' % ( - VHuser, FinalPHPPath, WPpath) - result, stdout = ProcessUtilities.outputExecutioner(command, None, None, None, 1) - - if stdout.find('Error:') > -1: - raise BaseException(stdout) - else: - Finaldbname = stdout.rstrip("\n") - - ## Get DB obj - try: - DBobj = Databases.objects.get(dbName=Finaldbname) - except: - raise BaseException(str("DataBase Not Found")) - RemoteScheduleIDobj = RemoteBackupSchedule.objects.get(pk=RemoteScheduleID) - - svobj = RemoteBackupsites(owner=RemoteScheduleIDobj, WPsites=WPid, database=DBobj.pk) - svobj.save() - - data_ret = {'status': 1, 'error_message': 'None', } - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def UpdateRemoteschedules(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - ScheduleID = data['ScheduleID'] - Frequency = data['Frequency'] - FileRetention = data['FileRetention'] - - scheduleobj = RemoteBackupSchedule.objects.get(pk=ScheduleID) - scheduleobj.timeintervel = Frequency - scheduleobj.fileretention = FileRetention - scheduleobj.save() - - data_ret = {'status': 1, 'error_message': 'None', } - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def ScanWordpressSite(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - allweb = Websites.objects.all() - - childdomain = ChildDomains.objects.all() - - for web in allweb: - webpath = "/home/%s/public_html/" % web.domain - command = "cat %swp-config.php" % webpath - result = ProcessUtilities.outputExecutioner(command, web.externalApp) - - if os.path.exists(ProcessUtilities.debugPath): - logging.CyberCPLogFileWriter.writeToFile(result) - - if result.find('No such file or directory') == -1: - try: - WPSites.objects.get(path=webpath) - except: - wpobj = WPSites(owner=web, title=web.domain, path=webpath, FinalURL=web.domain, - AutoUpdates="Enabled", PluginUpdates="Enabled", - ThemeUpdates="Enabled", ) - wpobj.save() - - for chlid in childdomain: - childPath = chlid.path.rstrip('/') - - command = "cat %s/wp-config.php" % childPath - result = ProcessUtilities.outputExecutioner(command, chlid.master.externalApp) - - if os.path.exists(ProcessUtilities.debugPath): - logging.CyberCPLogFileWriter.writeToFile(result) - - if result.find('No such file or directory') == -1: - fChildPath = f'{childPath}/' - try: - WPSites.objects.get(path=fChildPath) - except: - - wpobj = WPSites(owner=chlid.master, title=chlid.domain, path=fChildPath, FinalURL=chlid.domain, - AutoUpdates="Enabled", PluginUpdates="Enabled", - ThemeUpdates="Enabled", ) - wpobj.save() - - data_ret = {'status': 1, 'error_message': 'None', } - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def installwpcore(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - ###fetch WP version - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core version --skip-plugins --skip-themes --path=%s 2>/dev/null' % ( - Vhuser, FinalPHPPath, path) - version = ProcessUtilities.outputExecutioner(command, None, True) - version = version.rstrip("\n") - - ###install wp core - command = f"sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp core download --force --skip-content --version={version} --path={path}" - output = ProcessUtilities.outputExecutioner(command) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', 'result': output} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def dataintegrity(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - ###fetch WP version - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core verify-checksums --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, path) - result = ProcessUtilities.outputExecutioner(command) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', 'result': result} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def UpdatePlugins(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - plugin = data['plugin'] - pluginarray = data['pluginarray'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['plugin'] = plugin - extraArgs['pluginarray'] = pluginarray - extraArgs['FinalPHPPath'] = FinalPHPPath - extraArgs['path'] = path - extraArgs['Vhuser'] = Vhuser - - background = ApplicationInstaller('UpdateWPPlugin', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def UpdateThemes(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - Theme = data['Theme'] - Themearray = data['Themearray'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['Theme'] = Theme - extraArgs['Themearray'] = Themearray - extraArgs['FinalPHPPath'] = FinalPHPPath - extraArgs['path'] = path - extraArgs['Vhuser'] = Vhuser - - background = ApplicationInstaller('UpdateWPTheme', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def DeletePlugins(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - plugin = data['plugin'] - pluginarray = data['pluginarray'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['plugin'] = plugin - extraArgs['pluginarray'] = pluginarray - extraArgs['FinalPHPPath'] = FinalPHPPath - extraArgs['path'] = path - extraArgs['Vhuser'] = Vhuser - - background = ApplicationInstaller('DeletePlugins', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def DeleteThemes(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - Theme = data['Theme'] - Themearray = data['Themearray'] - wpsite = WPSites.objects.get(pk=WPManagerID) - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['Theme'] = Theme - extraArgs['Themearray'] = Themearray - extraArgs['FinalPHPPath'] = FinalPHPPath - extraArgs['path'] = path - extraArgs['Vhuser'] = Vhuser - - background = ApplicationInstaller('DeleteThemes', extraArgs) - background.start() - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def ChangeStatus(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - plugin = data['plugin'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin status %s --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, plugin, path) - stdoutput = ProcessUtilities.outputExecutioner(command) - - if stdoutput.find('Status: Active') > -1: - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin deactivate %s --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, plugin, path) - stdoutput = ProcessUtilities.outputExecutioner(command) - time.sleep(3) - - else: - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin activate %s --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, plugin, path) - stdoutput = ProcessUtilities.outputExecutioner(command) - time.sleep(3) - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def ChangeStatusThemes(self, userID=None, data=None): - try: - # logging.CyberCPLogFileWriter.writeToFile("Error WP ChangeStatusThemes ....... %s") - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - Theme = data['theme'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['Theme'] = Theme - extraArgs['FinalPHPPath'] = FinalPHPPath - extraArgs['path'] = path - extraArgs['Vhuser'] = Vhuser - - background = ApplicationInstaller('ChangeStatusThemes', extraArgs) - background.start() - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def CreateStagingNow(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['StagingDomain'] = data['StagingDomain'] - extraArgs['StagingName'] = data['StagingName'] - extraArgs['WPid'] = data['WPid'] - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - wpsite = WPSites.objects.get(pk=data['WPid']) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - background = ApplicationInstaller('CreateStagingNow', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def UpdateWPSettings(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - siteId = data['siteId'] - setting = data['setting'] - value = data['value'] - - wpsite = WPSites.objects.get(pk=siteId) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) != 1: - return ACLManager.loadError() - - # Get PHP version and path - Webobj = Websites.objects.get(pk=wpsite.owner_id) - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - # Update the appropriate setting based on the setting type - if setting == 'search-indexing': - # Update search engine indexing - command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp option update blog_public {value} --skip-plugins --skip-themes --path={wpsite.path}' - elif setting == 'debugging': - # Update debugging in wp-config.php - if value: - command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_DEBUG true --raw --skip-plugins --skip-themes --path={wpsite.path}' - else: - command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_DEBUG false --raw --skip-plugins --skip-themes --path={wpsite.path}' - elif setting == 'password-protection': - vhostName = wpsite.owner.domain - vhostPassDir = f'/home/{vhostName}' - path = f'{vhostPassDir}/{siteId}' - if value: - # Enable password protection - if not os.path.exists(path): - os.makedirs(path) - htpasswd = f'{path}/.htpasswd' - htaccess = f'{wpsite.path}/.htaccess' - password = randomPassword.generate_pass(12) - - # Create .htpasswd file - command = f"htpasswd -cb {htpasswd} admin {password}" - ProcessUtilities.executioner(command) - - # Create .htaccess file - htaccess_content = f"""AuthType Basic -AuthName "Restricted Access" -AuthUserFile {htpasswd} -Require valid-user""" - with open(htaccess, 'w') as f: - f.write(htaccess_content) - else: - # Disable password protection - if os.path.exists(path): - import shutil - shutil.rmtree(path) - htaccess = f'{wpsite.path}/.htaccess' - if os.path.exists(htaccess): - os.remove(htaccess) - return JsonResponse({'status': 1, 'error_message': 'None'}) - elif setting == 'maintenance-mode': - if value: - command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp maintenance-mode activate --skip-plugins --skip-themes --path={wpsite.path}' - else: - command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp maintenance-mode deactivate --skip-plugins --skip-themes --path={wpsite.path}' - else: - return JsonResponse({'status': 0, 'error_message': 'Invalid setting type'}) - - result = ProcessUtilities.outputExecutioner(command) - if result.find('Error:') > -1: - return JsonResponse({'status': 0, 'error_message': result}) - - return JsonResponse({'status': 1, 'error_message': 'None'}) - - except BaseException as msg: - return JsonResponse({'status': 0, 'error_message': str(msg)}) - - def submitWorpressCreation(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - extraArgs = {} - extraArgs['currentACL'] = currentACL - extraArgs['adminID'] = admin.pk - extraArgs['domainName'] = data['domain'] - extraArgs['WPVersion'] = data['WPVersion'] - extraArgs['blogTitle'] = data['title'] - try: - extraArgs['pluginbucket'] = data['pluginbucket'] - except: - extraArgs['pluginbucket'] = '-1' - extraArgs['adminUser'] = data['adminUser'] - extraArgs['PasswordByPass'] = data['PasswordByPass'] - extraArgs['adminPassword'] = data['PasswordByPass'] - extraArgs['adminEmail'] = data['Email'] - extraArgs['updates'] = data['AutomaticUpdates'] - extraArgs['Plugins'] = data['Plugins'] - extraArgs['Themes'] = data['Themes'] - extraArgs['websiteOwner'] = data['websiteOwner'] - extraArgs['package'] = data['package'] - extraArgs['home'] = data['home'] - extraArgs['apacheBackend'] = data['apacheBackend'] - try: - extraArgs['path'] = data['path'] - if extraArgs['path'] == '': - extraArgs['home'] = '1' - except: - pass - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - background = ApplicationInstaller('wordpressInstallNew', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def submitWebsiteCreation(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - - domain = data['domainName'] - adminEmail = data['adminEmail'] - phpSelection = data['phpSelection'] - packageName = data['package'] - websiteOwner = data['websiteOwner'].lower() - - if data['domainName'].find("cyberpanel.website") > -1: - url = "https://platform.cyberpersons.com/CyberpanelAdOns/CreateDomain" - - domain_data = { - "name": "test-domain", - "IP": ACLManager.GetServerIP(), - "domain": data['domainName'] - } - - import requests - response = requests.post(url, data=json.dumps(domain_data)) - domain_status = response.json()['status'] - - if domain_status == 0: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': response.json()['error_message']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - loggedUser = Administrator.objects.get(pk=userID) - newOwner = Administrator.objects.get(userName=websiteOwner) - - if ACLManager.currentContextPermission(currentACL, 'createWebsite') == 0: - return ACLManager.loadErrorJson('createWebSiteStatus', 0) - - if ACLManager.checkOwnerProtection(currentACL, loggedUser, newOwner) == 0: - return ACLManager.loadErrorJson('createWebSiteStatus', 0) - - if currentACL['admin'] == 0: - if ACLManager.CheckDomainBlackList(domain) == 0: - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Blacklisted domain."} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - if not validators.domain(domain): - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Invalid domain."} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - if not validators.email(adminEmail) or adminEmail.find('--') > -1: - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Invalid email."} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - try: - HA = data['HA'] - externalApp = 'nobody' - except: - externalApp = "".join(re.findall("[a-zA-Z]+", domain))[:5] + str(randint(1000, 9999)) - - try: - counter = 0 - while 1: - tWeb = Websites.objects.get(externalApp=externalApp) - externalApp = '%s%s' % (tWeb.externalApp, str(counter)) - counter = counter + 1 - except: - pass - - tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - - try: - apacheBackend = str(data['apacheBackend']) - except: - apacheBackend = "0" - - try: - mailDomain = str(data['mailDomain']) - except: - mailDomain = "1" - - import pwd - counter = 0 - - ## Create Configurations - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " createVirtualHost --virtualHostName " + domain + \ - " --administratorEmail " + adminEmail + " --phpVersion '" + phpSelection + \ - "' --virtualHostUser " + externalApp + " --ssl " + str(1) + " --dkimCheck " \ - + str(1) + " --openBasedir " + str(data['openBasedir']) + \ - ' --websiteOwner "' + websiteOwner + '" --package "' + packageName + '" --tempStatusPath ' + tempStatusPath + " --apache " + apacheBackend + " --mailDomain %s" % ( - mailDomain) - - ProcessUtilities.popenExecutioner(execPath) - time.sleep(2) - - data_ret = {'status': 1, 'createWebSiteStatus': 1, 'error_message': "None", - 'tempStatusPath': tempStatusPath, 'LinuxUser': externalApp} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def submitDomainCreation(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - try: - alias = data['alias'] - except: - alias = 0 - - masterDomain = data['masterDomain'] - domain = data['domainName'] - - - if alias == 0: - phpSelection = data['phpSelection'] - path = data['path'] - else: - - ### if master website have apache then create this sub-domain also as ols + apache - - apachePath = ApacheVhost.configBasePath + masterDomain + '.conf' - - if os.path.exists(apachePath): - data['apacheBackend'] = 1 - - phpSelection = Websites.objects.get(domain=masterDomain).phpSelection - - tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - - if not validators.domain(domain): - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Invalid domain."} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - if data['domainName'].find("cyberpanel.website") > -1: - url = "https://platform.cyberpersons.com/CyberpanelAdOns/CreateDomain" - - domain_data = { - "name": "test-domain", - "IP": ACLManager.GetServerIP(), - "domain": data['domainName'] - } - - import requests - response = requests.post(url, data=json.dumps(domain_data)) - domain_status = response.json()['status'] - - if domain_status == 0: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': response.json()['error_message']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - if ACLManager.checkOwnership(masterDomain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('createWebSiteStatus', 0) - - if data['path'].find('..') > -1: - return ACLManager.loadErrorJson('createWebSiteStatus', 0) - - if currentACL['admin'] != 1: - data['openBasedir'] = 1 - - if alias == 0: - - if len(path) > 0: - path = path.lstrip("/") - path = "/home/" + masterDomain + "/" + path - else: - path = "/home/" + masterDomain + "/" + domain - else: - path = f'/home/{masterDomain}/public_html' - - try: - apacheBackend = str(data['apacheBackend']) - except: - apacheBackend = "0" - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - - execPath = execPath + " createDomain --masterDomain " + masterDomain + " --virtualHostName " + domain + \ - " --phpVersion '" + phpSelection + "' --ssl " + str(1) + " --dkimCheck " + str(1) \ - + " --openBasedir " + str(data['openBasedir']) + ' --path ' + path + ' --websiteOwner ' \ - + admin.userName + ' --tempStatusPath ' + tempStatusPath + " --apache " + apacheBackend + f' --aliasDomain {str(alias)}' - - ProcessUtilities.popenExecutioner(execPath) - time.sleep(2) - - data_ret = {'status': 1, 'createWebSiteStatus': 1, 'error_message': "None", - 'tempStatusPath': tempStatusPath} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def fetchDomains(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - masterDomain = data['masterDomain'] - - try: - alias = data['alias'] - except: - alias = 0 - - if ACLManager.checkOwnership(masterDomain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('fetchStatus', 0) - - cdManager = ChildDomainManager(masterDomain) - json_data = cdManager.findChildDomainsJson(alias) - - final_json = json.dumps({'status': 1, 'fetchStatus': 1, 'error_message': "None", "data": json_data}) - return HttpResponse(final_json) - - except BaseException as msg: - final_dic = {'status': 0, 'fetchStatus': 0, 'error_message': str(msg)} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - def searchWebsites(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - try: - json_data = self.searchWebsitesJson(currentACL, userID, data['patternAdded']) - except BaseException as msg: - tempData = {} - tempData['page'] = 1 - return self.getFurtherAccounts(userID, tempData) - - pagination = self.websitePagination(currentACL, userID) - final_dic = {'status': 1, 'listWebSiteStatus': 1, 'error_message': "None", "data": json_data, - 'pagination': pagination} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - except BaseException as msg: - dic = {'status': 1, 'listWebSiteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def searchChilds(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - - websites = ACLManager.findWebsiteObjects(currentACL, userID) - childDomains = [] - - for web in websites: - for child in web.childdomains_set.filter(domain__istartswith=data['patternAdded']): - childDomains.append(child) - - json_data = self.findChildsListJson(childDomains) - - final_dic = {'status': 1, 'listWebSiteStatus': 1, 'error_message': "None", "data": json_data} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - except BaseException as msg: - dic = {'status': 1, 'listWebSiteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def getFurtherAccounts(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - pageNumber = int(data['page']) - json_data = self.findWebsitesJson(currentACL, userID, pageNumber) - pagination = self.websitePagination(currentACL, userID) - final_dic = {'status': 1, 'listWebSiteStatus': 1, 'error_message': "None", "data": json_data, - 'pagination': pagination} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - except BaseException as msg: - dic = {'status': 1, 'listWebSiteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def fetchWebsitesList(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - pageNumber = int(data['page']) - recordsToShow = int(data['recordsToShow']) - - if os.path.exists(ProcessUtilities.debugPath): - logging.CyberCPLogFileWriter.writeToFile(f'Fetch sites step 1..') - - endPageNumber, finalPageNumber = self.recordsPointer(pageNumber, recordsToShow) - - if os.path.exists(ProcessUtilities.debugPath): - logging.CyberCPLogFileWriter.writeToFile(f'Fetch sites step 2..') - - websites = ACLManager.findWebsiteObjects(currentACL, userID) - - if os.path.exists(ProcessUtilities.debugPath): - logging.CyberCPLogFileWriter.writeToFile(f'Fetch sites step 3..') - - pagination = self.getPagination(len(websites), recordsToShow) - - if os.path.exists(ProcessUtilities.debugPath): - logging.CyberCPLogFileWriter.writeToFile(f'Fetch sites step 4..') - - json_data = self.findWebsitesListJson(websites[finalPageNumber:endPageNumber]) - - if os.path.exists(ProcessUtilities.debugPath): - logging.CyberCPLogFileWriter.writeToFile(f'Fetch sites step 5..') - - final_dic = {'status': 1, 'listWebSiteStatus': 1, 'error_message': "None", "data": json_data, - 'pagination': pagination} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - except BaseException as msg: - dic = {'status': 1, 'listWebSiteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def fetchChildDomainsMain(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - pageNumber = int(data['page']) - recordsToShow = int(data['recordsToShow']) - - endPageNumber, finalPageNumber = self.recordsPointer(pageNumber, recordsToShow) - websites = ACLManager.findWebsiteObjects(currentACL, userID) - childDomains = [] - - for web in websites: - for child in web.childdomains_set.filter(alais=0): - if child.domain == f'mail.{web.domain}': - pass - else: - childDomains.append(child) - - pagination = self.getPagination(len(childDomains), recordsToShow) - json_data = self.findChildsListJson(childDomains[finalPageNumber:endPageNumber]) - - final_dic = {'status': 1, 'listWebSiteStatus': 1, 'error_message': "None", "data": json_data, - 'pagination': pagination} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - except BaseException as msg: - dic = {'status': 1, 'listWebSiteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def findWebsitesListJson(self, websites): - try: - ipFile = "/etc/cyberpanel/machineIP" - f = open(ipFile) - ipData = f.read() - ipAddress = ipData.split('\n', 1)[0] - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile("Failed to read machine IP, error:" + str(msg)) - ipAddress = "192.168.100.1" - - json_data = [] - - for website in websites: - wp_sites = [] - try: - wp_sites = WPSites.objects.filter(owner=website) - wp_sites = [{ - 'id': wp.id, - 'title': wp.title, - 'url': wp.FinalURL, - 'version': wp.version if hasattr(wp, 'version') else 'Unknown', - 'phpVersion': wp.phpVersion if hasattr(wp, 'phpVersion') else 'Unknown' - } for wp in wp_sites] - except: - pass - - # Calculate disk usage - DiskUsage, DiskUsagePercentage, bwInMB, bwUsage = virtualHostUtilities.FindStats(website) - diskUsed = "%sMB" % str(DiskUsage) - - # Convert numeric state to text - state = "Active" if website.state == 1 else "Suspended" - - json_data.append({ - 'domain': website.domain, - 'adminEmail': website.adminEmail, - 'phpVersion': website.phpSelection, - 'state': state, - 'ipAddress': ipAddress, - 'package': website.package.packageName, - 'admin': website.admin.userName, - 'wp_sites': wp_sites, - 'diskUsed': diskUsed - }) - return json.dumps(json_data) - - - - def findDockersitesListJson(self, Dockersite): - - json_data = "[" - checker = 0 - - try: - ipFile = "/etc/cyberpanel/machineIP" - f = open(ipFile) - ipData = f.read() - ipAddress = ipData.split('\n', 1)[0] - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile("Failed to read machine IP, error:" + str(msg)) - ipAddress = "192.168.100.1" - - from plogical.phpUtilities import phpUtilities - for items in Dockersite: - website = Websites.objects.get(pk=items.admin.pk) - vhFile = f'/usr/local/lsws/conf/vhosts/{website.domain}/vhost.conf' - - try: - PHPVersionActual = phpUtilities.WrapGetPHPVersionFromFileToGetVersionWithPHP(website) - except: - PHPVersionActual = 'PHP 8.1' - - - if items.state == 0: - state = "Suspended" - else: - state = "Active" - - dpkg = PackageAssignment.objects.get(user=website.admin) - - - dic = {'id':items.pk, 'domain': website.domain, 'adminEmail': website.adminEmail, 'ipAddress': ipAddress, - 'admin': website.admin.userName, 'package': dpkg.package.Name, 'state': state, - 'CPU': int(items.CPUsMySQL)+int(items.CPUsSite), 'Ram': int(items.MemorySite)+int(items.MemoryMySQL), 'phpVersion': PHPVersionActual } - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - - json_data = json_data + ']' - - return json_data - - def findChildsListJson(self, childs): - - json_data = "[" - checker = 0 - - try: - ipFile = "/etc/cyberpanel/machineIP" - f = open(ipFile) - ipData = f.read() - ipAddress = ipData.split('\n', 1)[0] - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile("Failed to read machine IP, error:" + str(msg)) - ipAddress = "192.168.100.1" - - for items in childs: - - dic = {'domain': items.domain, 'masterDomain': items.master.domain, 'adminEmail': items.master.adminEmail, - 'ipAddress': ipAddress, - 'admin': items.master.admin.userName, 'package': items.master.package.packageName, - 'path': items.path} - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - - json_data = json_data + ']' - - return json_data - - def recordsPointer(self, page, toShow): - finalPageNumber = ((page * toShow)) - toShow - endPageNumber = finalPageNumber + toShow - return endPageNumber, finalPageNumber - - def getPagination(self, records, toShow): - pages = float(records) / float(toShow) - - pagination = [] - counter = 1 - - if pages <= 1.0: - pages = 1 - pagination.append(counter) - else: - pages = ceil(pages) - finalPages = int(pages) + 1 - - for i in range(1, finalPages): - pagination.append(counter) - counter = counter + 1 - - return pagination - - def submitWebsiteDeletion(self, userID=None, data=None): - try: - if data['websiteName'].find("cyberpanel.website") > -1: - url = "https://platform.cyberpersons.com/CyberpanelAdOns/DeleteDomain" - - domain_data = { - "name": "test-domain", - "IP": ACLManager.GetServerIP(), - "domain": data['websiteName'] - } - - import requests - response = requests.post(url, data=json.dumps(domain_data)) - - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'deleteWebsite') == 0: - return ACLManager.loadErrorJson('websiteDeleteStatus', 0) - - websiteName = data['websiteName'] - - admin = Administrator.objects.get(pk=userID) - if ACLManager.checkOwnership(websiteName, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('websiteDeleteStatus', 0) - - ## Deleting master domain - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " deleteVirtualHostConfigurations --virtualHostName " + websiteName - ProcessUtilities.popenExecutioner(execPath) - - ### delete site from dgdrive backups - - try: - - from websiteFunctions.models import GDriveSites - GDriveSites.objects.filter(domain=websiteName).delete() - except: - pass - - data_ret = {'status': 1, 'websiteDeleteStatus': 1, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'websiteDeleteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def submitDomainDeletion(self, userID=None, data=None): - try: - - if data['websiteName'].find("cyberpanel.website") > -1: - url = "https://platform.cyberpersons.com/CyberpanelAdOns/DeleteDomain" - - domain_data = { - "name": "test-domain", - "IP": ACLManager.GetServerIP(), - "domain": data['websiteName'] - } - - import requests - response = requests.post(url, data=json.dumps(domain_data)) - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - websiteName = data['websiteName'] - - try: - DeleteDocRoot = int(data['DeleteDocRoot']) - except: - DeleteDocRoot = 0 - - if ACLManager.checkOwnership(websiteName, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('websiteDeleteStatus', 0) - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " deleteDomain --virtualHostName " + websiteName + ' --DeleteDocRoot %s' % ( - str(DeleteDocRoot)) - ProcessUtilities.outputExecutioner(execPath) - - data_ret = {'status': 1, 'websiteDeleteStatus': 1, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'websiteDeleteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def submitWebsiteStatus(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'suspendWebsite') == 0: - return ACLManager.loadErrorJson('websiteStatus', 0) - - websiteName = data['websiteName'] - state = data['state'] - - website = Websites.objects.get(domain=websiteName) - - admin = Administrator.objects.get(pk=userID) - if ACLManager.checkOwnership(websiteName, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('websiteStatus', 0) - - if state == "Suspend": - confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + websiteName - command = "mv " + confPath + " " + confPath + "-suspended" - ProcessUtilities.popenExecutioner(command) - - childDomains = website.childdomains_set.all() - - for items in childDomains: - confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + items.domain - command = "mv " + confPath + " " + confPath + "-suspended" - ProcessUtilities.executioner(command) - - installUtilities.reStartLiteSpeedSocket() - website.state = 0 - else: - confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + websiteName - - command = "mv " + confPath + "-suspended" + " " + confPath - ProcessUtilities.executioner(command) - - command = "chown -R " + "lsadm" + ":" + "lsadm" + " " + confPath - ProcessUtilities.popenExecutioner(command) - - childDomains = website.childdomains_set.all() - - for items in childDomains: - confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + items.domain - - command = "mv " + confPath + "-suspended" + " " + confPath - ProcessUtilities.executioner(command) - - command = "chown -R " + "lsadm" + ":" + "lsadm" + " " + confPath - ProcessUtilities.popenExecutioner(command) - - installUtilities.reStartLiteSpeedSocket() - website.state = 1 - - website.save() - - data_ret = {'websiteStatus': 1, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - - data_ret = {'websiteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def submitWebsiteModify(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'modifyWebsite') == 0: - return ACLManager.loadErrorJson('modifyStatus', 0) - - admin = Administrator.objects.get(pk=userID) - if ACLManager.checkOwnership(data['websiteToBeModified'], admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('websiteDeleteStatus', 0) - - packs = ACLManager.loadPackages(userID, currentACL) - admins = ACLManager.loadAllUsers(userID) - - ## Get packs name - - json_data = "[" - checker = 0 - - for items in packs: - dic = {"pack": items} - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - - json_data = json_data + ']' - - ### Get admin names - - admin_data = "[" - checker = 0 - - for items in admins: - dic = {"adminNames": items} - - if checker == 0: - admin_data = admin_data + json.dumps(dic) - checker = 1 - else: - admin_data = admin_data + ',' + json.dumps(dic) - - admin_data = admin_data + ']' - - websiteToBeModified = data['websiteToBeModified'] - - modifyWeb = Websites.objects.get(domain=websiteToBeModified) - - email = modifyWeb.adminEmail - currentPack = modifyWeb.package.packageName - owner = modifyWeb.admin.userName - - data_ret = {'status': 1, 'modifyStatus': 1, 'error_message': "None", "adminEmail": email, - "packages": json_data, "current_pack": currentPack, "adminNames": admin_data, - 'currentAdmin': owner} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - - except BaseException as msg: - dic = {'status': 0, 'modifyStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def fetchWebsiteDataJSON(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'createWebsite') == 0: - return ACLManager.loadErrorJson('createWebSiteStatus', 0) - - packs = ACLManager.loadPackages(userID, currentACL) - admins = ACLManager.loadAllUsers(userID) - - ## Get packs name - - json_data = "[" - checker = 0 - - for items in packs: - dic = {"pack": items} - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - - json_data = json_data + ']' - - ### Get admin names - - admin_data = "[" - checker = 0 - - for items in admins: - dic = {"adminNames": items} - - if checker == 0: - admin_data = admin_data + json.dumps(dic) - checker = 1 - else: - admin_data = admin_data + ',' + json.dumps(dic) - - admin_data = admin_data + ']' - - data_ret = {'status': 1, 'error_message': "None", - "packages": json_data, "adminNames": admin_data} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - - except BaseException as msg: - dic = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def saveWebsiteChanges(self, userID=None, data=None): - try: - domain = data['domain'] - package = data['packForWeb'] - email = data['email'] - phpVersion = data['phpVersion'] - newUser = data['admin'] - - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'modifyWebsite') == 0: - return ACLManager.loadErrorJson('saveStatus', 0) - - admin = Administrator.objects.get(pk=userID) - if ACLManager.checkOwnership(domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('websiteDeleteStatus', 0) - - newOwner = Administrator.objects.get(userName=newUser) - if ACLManager.checkUserOwnerShip(currentACL, admin, newOwner) == 1: - pass - else: - return ACLManager.loadErrorJson('websiteDeleteStatus', 0) - - confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + domain - completePathToConfigFile = confPath + "/vhost.conf" - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " changePHP --phpVersion '" + phpVersion + "' --path " + completePathToConfigFile - ProcessUtilities.popenExecutioner(execPath) - - #### - - newOwner = Administrator.objects.get(userName=newUser) - - modifyWeb = Websites.objects.get(domain=domain) - webpack = Package.objects.get(packageName=package) - - modifyWeb.package = webpack - modifyWeb.adminEmail = email - modifyWeb.phpSelection = phpVersion - modifyWeb.admin = newOwner - - modifyWeb.save() - - ## Fix https://github.com/usmannasir/cyberpanel/issues/998 - - # from plogical.IncScheduler import IncScheduler - # isPU = IncScheduler('CalculateAndUpdateDiskUsage', {}) - # isPU.start() - - command = '/usr/local/CyberCP/bin/python /usr/local/CyberCP/plogical/IncScheduler.py UpdateDiskUsageForce' - ProcessUtilities.outputExecutioner(command) - - ## - - data_ret = {'status': 1, 'saveStatus': 1, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'saveStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def loadDomainHome(self, request=None, userID=None, data=None): - - if Websites.objects.filter(domain=self.domain).exists(): - - currentACL = ACLManager.loadedACL(userID) - website = Websites.objects.get(domain=self.domain) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - Data = {} - - marketingStatus = emACL.checkIfEMEnabled(admin.userName) - - Data['marketingStatus'] = marketingStatus - Data['ftpTotal'] = website.package.ftpAccounts - Data['ftpUsed'] = website.users_set.all().count() - - Data['databasesUsed'] = website.databases_set.all().count() - Data['databasesTotal'] = website.package.dataBases - - Data['domain'] = self.domain - - DiskUsage, DiskUsagePercentage, bwInMB, bwUsage = virtualHostUtilities.FindStats(website) - - ## bw usage calculations - - Data['bwInMBTotal'] = website.package.bandwidth - Data['bwInMB'] = bwInMB - Data['bwUsage'] = bwUsage - - if DiskUsagePercentage > 100: - DiskUsagePercentage = 100 - - Data['diskUsage'] = DiskUsagePercentage - Data['diskInMB'] = DiskUsage - Data['diskInMBTotal'] = website.package.diskSpace - - Data['phps'] = PHPManager.findPHPVersions() - - servicePath = '/home/cyberpanel/postfix' - if os.path.exists(servicePath): - Data['email'] = 1 - else: - Data['email'] = 0 - - ## Getting SSL Information - try: - import OpenSSL - from datetime import datetime - filePath = '/etc/letsencrypt/live/%s/fullchain.pem' % (self.domain) - x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, - open(filePath, 'r').read()) - expireData = x509.get_notAfter().decode('ascii') - finalDate = datetime.strptime(expireData, '%Y%m%d%H%M%SZ') - - now = datetime.now() - diff = finalDate - now - Data['viewSSL'] = 1 - Data['days'] = str(diff.days) - Data['authority'] = x509.get_issuer().get_components()[1][1].decode('utf-8') - - if Data['authority'] == 'Denial': - Data['authority'] = '%s has SELF-SIGNED SSL.' % (self.domain) - else: - Data['authority'] = '%s has SSL from %s.' % (self.domain, Data['authority']) - - except BaseException as msg: - Data['viewSSL'] = 0 - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - - servicePath = '/home/cyberpanel/pureftpd' - if os.path.exists(servicePath): - Data['ftp'] = 1 - else: - Data['ftp'] = 0 - - proc = httpProc(request, 'websiteFunctions/website.html', Data) - return proc.render() - else: - proc = httpProc(request, 'websiteFunctions/website.html', - {"error": 1, "domain": "This domain does not exists."}) - return proc.render() - - def launchChild(self, request=None, userID=None, data=None): - - if ChildDomains.objects.filter(domain=self.childDomain).exists(): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - website = Websites.objects.get(domain=self.domain) - - Data = {} - - Data['ftpTotal'] = website.package.ftpAccounts - Data['ftpUsed'] = website.users_set.all().count() - - Data['databasesUsed'] = website.databases_set.all().count() - Data['databasesTotal'] = website.package.dataBases - - Data['domain'] = self.domain - Data['childDomain'] = self.childDomain - - DiskUsage, DiskUsagePercentage, bwInMB, bwUsage = virtualHostUtilities.FindStats(website) - - ## bw usage calculations - - Data['bwInMBTotal'] = website.package.bandwidth - Data['bwInMB'] = bwInMB - Data['bwUsage'] = bwUsage - - if DiskUsagePercentage > 100: - DiskUsagePercentage = 100 - - Data['diskUsage'] = DiskUsagePercentage - Data['diskInMB'] = DiskUsage - Data['diskInMBTotal'] = website.package.diskSpace - - Data['phps'] = PHPManager.findPHPVersions() - - servicePath = '/home/cyberpanel/postfix' - if os.path.exists(servicePath): - Data['email'] = 1 - else: - Data['email'] = 0 - - servicePath = '/home/cyberpanel/pureftpd' - if os.path.exists(servicePath): - Data['ftp'] = 1 - else: - Data['ftp'] = 0 - - ## Getting SSL Information - try: - import OpenSSL - from datetime import datetime - filePath = '/etc/letsencrypt/live/%s/fullchain.pem' % (self.childDomain) - x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, - open(filePath, 'r').read()) - expireData = x509.get_notAfter().decode('ascii') - finalDate = datetime.strptime(expireData, '%Y%m%d%H%M%SZ') - - now = datetime.now() - diff = finalDate - now - Data['viewSSL'] = 1 - Data['days'] = str(diff.days) - Data['authority'] = x509.get_issuer().get_components()[1][1].decode('utf-8') - - if Data['authority'] == 'Denial': - Data['authority'] = '%s has SELF-SIGNED SSL.' % (self.childDomain) - else: - Data['authority'] = '%s has SSL from %s.' % (self.childDomain, Data['authority']) - - except BaseException as msg: - Data['viewSSL'] = 0 - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - - proc = httpProc(request, 'websiteFunctions/launchChild.html', Data) - return proc.render() - else: - proc = httpProc(request, 'websiteFunctions/launchChild.html', - {"error": 1, "domain": "This child domain does not exists"}) - return proc.render() - - def getDataFromLogFile(self, userID=None, data=None): - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - logType = data['logType'] - self.domain = data['virtualHost'] - page = data['page'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('logstatus', 0) - - if logType == 1: - fileName = "/home/" + self.domain + "/logs/" + self.domain + ".access_log" - else: - fileName = "/home/" + self.domain + "/logs/" + self.domain + ".error_log" - - command = 'ls -la %s' % fileName - result = ProcessUtilities.outputExecutioner(command) - - if result.find('->') > -1: - final_json = json.dumps( - {'status': 0, 'logstatus': 0, - 'error_message': "Symlink attack."}) - return HttpResponse(final_json) - - ## get Logs - website = Websites.objects.get(domain=self.domain) - - output = virtualHostUtilities.getAccessLogs(fileName, page, website.externalApp) - - if output.find("1,None") > -1: - final_json = json.dumps( - {'status': 0, 'logstatus': 0, - 'error_message': "Not able to fetch logs, see CyberPanel main log file, Error: %s" % (output)}) - return HttpResponse(final_json) - - ## get log ends here. - - data = output.split("\n") - - json_data = "[" - checker = 0 - - for items in reversed(data): - if len(items) > 10: - logData = items.split(" ") - domain = logData[5].strip('"') - ipAddress = logData[0].strip('"') - time = (logData[3]).strip("[").strip("]") - resource = logData[6].strip('"') - size = logData[9].replace('"', '') - - dic = {'domain': domain, - 'ipAddress': ipAddress, - 'time': time, - 'resource': resource, - 'size': size, - } - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - - json_data = json_data + ']' - final_json = json.dumps({'status': 1, 'logstatus': 1, 'error_message': "None", "data": json_data}) - return HttpResponse(final_json) - - def fetchErrorLogs(self, userID=None, data=None): - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['virtualHost'] - page = data['page'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('logstatus', 0) - - fileName = "/home/" + self.domain + "/logs/" + self.domain + ".error_log" - - command = 'ls -la %s' % fileName - result = ProcessUtilities.outputExecutioner(command) - - if result.find('->') > -1: - final_json = json.dumps( - {'status': 0, 'logstatus': 0, - 'error_message': "Symlink attack."}) - return HttpResponse(final_json) - - ## get Logs - website = Websites.objects.get(domain=self.domain) - - output = virtualHostUtilities.getErrorLogs(fileName, page, website.externalApp) - - if output.find("1,None") > -1: - final_json = json.dumps( - {'status': 0, 'logstatus': 0, 'error_message': "Not able to fetch logs, see CyberPanel main log file!"}) - return HttpResponse(final_json) - - ## get log ends here. - - final_json = json.dumps({'status': 1, 'logstatus': 1, 'error_message': "None", "data": output}) - return HttpResponse(final_json) - - def getDataFromConfigFile(self, userID=None, data=None): - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - self.domain = data['virtualHost'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('configstatus', 0) - - command = 'cat %s' % ('/usr/local/lsws/conf/dvhost_redis.conf') - - if ProcessUtilities.outputExecutioner(command).find('127.0.0.1') == -1: - filePath = installUtilities.Server_root_path + "/conf/vhosts/" + self.domain + "/vhost.conf" - - command = 'cat ' + filePath - configData = ProcessUtilities.outputExecutioner(command, 'lsadm') - - if len(configData) == 0: - status = {'status': 0, "configstatus": 0, "error_message": "Configuration file is currently empty!"} - - final_json = json.dumps(status) - return HttpResponse(final_json) - - else: - command = 'redis-cli get "vhost:%s"' % (self.domain) - configData = ProcessUtilities.outputExecutioner(command) - configData = '#### This configuration is fetched from redis as Redis-Mass Hosting is being used.\n%s' % ( - configData) - - status = {'status': 1, "configstatus": 1, "configData": configData} - final_json = json.dumps(status) - return HttpResponse(final_json) - - def saveConfigsToFile(self, userID=None, data=None): - - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] != 1: - return ACLManager.loadErrorJson('configstatus', 0) - - configData = data['configData'] - self.domain = data['virtualHost'] - - if len(configData) == 0: - status = {"configstatus": 0, 'error_message': 'Error: you are trying to save empty vhost file, your website will stop working.'} - - final_json = json.dumps(status) - return HttpResponse(final_json) - - - command = 'cat %s' % ('/usr/local/lsws/conf/dvhost_redis.conf') - - if ProcessUtilities.outputExecutioner(command).find('127.0.0.1') == -1: - - mailUtilities.checkHome() - - tempPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - - vhost = open(tempPath, "w") - - vhost.write(configData) - - vhost.close() - - ## writing data temporary to file - - filePath = installUtilities.Server_root_path + "/conf/vhosts/" + self.domain + "/vhost.conf" - - ## save configuration data - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " saveVHostConfigs --path " + filePath + " --tempPath " + tempPath - - output = ProcessUtilities.outputExecutioner(execPath) - - if output.find("1,None") > -1: - status = {"configstatus": 1} - - final_json = json.dumps(status) - return HttpResponse(final_json) - else: - data_ret = {'configstatus': 0, 'error_message': output} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - ## save configuration data ends - else: - command = "redis-cli set vhost:%s '%s'" % (self.domain, configData.replace( - '#### This configuration is fetched from redis as Redis-Mass Hosting is being used.\n', '')) - ProcessUtilities.executioner(command) - - status = {"configstatus": 1} - - final_json = json.dumps(status) - return HttpResponse(final_json) - - def getRewriteRules(self, userID=None, data=None): - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - self.domain = data['virtualHost'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('rewriteStatus', 0) - - try: - childDom = ChildDomains.objects.get(domain=self.domain) - filePath = childDom.path + '/.htaccess' - externalApp = childDom.master.externalApp - except: - website = Websites.objects.get(domain=self.domain) - externalApp = website.externalApp - filePath = "/home/" + self.domain + "/public_html/.htaccess" - - try: - command = 'cat %s' % (filePath) - rewriteRules = ProcessUtilities.outputExecutioner(command, externalApp) - - if len(rewriteRules) == 0: - status = {"rewriteStatus": 1, "error_message": "Rules file is currently empty"} - final_json = json.dumps(status) - return HttpResponse(final_json) - - status = {"rewriteStatus": 1, "rewriteRules": rewriteRules} - - final_json = json.dumps(status) - return HttpResponse(final_json) - - except BaseException as msg: - status = {"rewriteStatus": 1, "error_message": str(msg), "rewriteRules": ""} - final_json = json.dumps(status) - return HttpResponse(final_json) - - def saveRewriteRules(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - self.domain = data['virtualHost'] - rewriteRules = data['rewriteRules'].encode('utf-8') - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('rewriteStatus', 0) - - ## writing data temporary to file - - mailUtilities.checkHome() - tempPath = "/tmp/" + str(randint(1000, 9999)) - vhost = open(tempPath, "wb") - vhost.write(rewriteRules) - vhost.close() - - ## writing data temporary to file - - try: - childDomain = ChildDomains.objects.get(domain=self.domain) - filePath = childDomain.path + '/.htaccess' - externalApp = childDomain.master.externalApp - except: - filePath = "/home/" + self.domain + "/public_html/.htaccess" - website = Websites.objects.get(domain=self.domain) - externalApp = website.externalApp - - ## save configuration data - - command = 'cp %s %s' % (tempPath, filePath) - ProcessUtilities.executioner(command, externalApp) - - command = 'rm -f %s' % (tempPath) - ProcessUtilities.executioner(command, 'cyberpanel') - - installUtilities.reStartLiteSpeedSocket() - status = {"rewriteStatus": 1, 'error_message': 'None'} - final_json = json.dumps(status) - return HttpResponse(final_json) - except BaseException as msg: - status = {"rewriteStatus": 0, 'error_message': str(msg)} - final_json = json.dumps(status) - return HttpResponse(final_json) - - def saveSSL(self, userID=None, data=None): - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - self.domain = data['virtualHost'] - key = data['key'] - cert = data['cert'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('sslStatus', 0) - - mailUtilities.checkHome() - - ## writing data temporary to file - - tempKeyPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - vhost = open(tempKeyPath, "w") - vhost.write(key) - vhost.close() - - tempCertPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - vhost = open(tempCertPath, "w") - vhost.write(cert) - vhost.close() - - ## writing data temporary to file - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " saveSSL --virtualHostName " + self.domain + " --tempKeyPath " + tempKeyPath + " --tempCertPath " + tempCertPath - output = ProcessUtilities.outputExecutioner(execPath) - - if output.find("1,None") > -1: - data_ret = {'sslStatus': 1, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - logging.CyberCPLogFileWriter.writeToFile( - output) - data_ret = {'sslStatus': 0, 'error_message': output} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def changePHP(self, userID=None, data=None): - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - self.domain = data['childDomain'] - phpVersion = data['phpSelection'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('changePHP', 0) - - confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + self.domain - completePathToConfigFile = confPath + "/vhost.conf" - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " changePHP --phpVersion '" + phpVersion + "' --path " + completePathToConfigFile - ProcessUtilities.popenExecutioner(execPath) - - try: - website = Websites.objects.get(domain=self.domain) - website.phpSelection = data['phpSelection'] - website.save() - - ### check if there are any alias domains under the main website and then change php for them too - - for alias in website.childdomains_set.filter(alais=1): - - try: - - confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + alias.domain - completePathToConfigFile = confPath + "/vhost.conf" - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " changePHP --phpVersion '" + phpVersion + "' --path " + completePathToConfigFile - ProcessUtilities.popenExecutioner(execPath) - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile(f'Error changing PHP for alias: {str(msg)}') - - - except: - website = ChildDomains.objects.get(domain=self.domain) - website.phpSelection = data['phpSelection'] - website.save() - - data_ret = {'status': 1, 'changePHP': 1, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def getWebsiteCron(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - self.domain = data['domain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('getWebsiteCron', 0) - - website = Websites.objects.get(domain=self.domain) - - if Websites.objects.filter(domain=self.domain).exists(): - pass - else: - dic = {'getWebsiteCron': 0, 'error_message': 'You do not own this domain'} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - CronUtil.CronPrem(1) - - crons = [] - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" - execPath = execPath + " getWebsiteCron --externalApp " + website.externalApp - - f = ProcessUtilities.outputExecutioner(execPath, website.externalApp) - - CronUtil.CronPrem(0) - - if ProcessUtilities.decideDistro() == ProcessUtilities.centos or ProcessUtilities.decideDistro() == ProcessUtilities.cent8: - cronPath = "/var/spool/cron/" + website.externalApp - else: - cronPath = "/var/spool/cron/crontabs/" + website.externalApp - - if f.find('Permission denied') > -1: - command = 'chmod 644 %s' % (cronPath) - ProcessUtilities.executioner(command) - - command = 'chown %s:%s %s' % (website.externalApp, website.externalApp, cronPath) - ProcessUtilities.executioner(command) - - f = ProcessUtilities.outputExecutioner(execPath, website.externalApp) - - if f.find("0,CyberPanel,") > -1: - data_ret = {'getWebsiteCron': 0, "user": website.externalApp, "crons": {}} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - - counter = 0 - for line in f.split("\n"): - if line: - split = line.split(" ", 5) - if len(split) == 6: - counter += 1 - crons.append({"line": counter, - "minute": split[0], - "hour": split[1], - "monthday": split[2], - "month": split[3], - "weekday": split[4], - "command": split[5]}) - - data_ret = {'getWebsiteCron': 1, "user": website.externalApp, "crons": crons} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - dic = {'getWebsiteCron': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def getCronbyLine(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - line = data['line'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('getWebsiteCron', 0) - - if Websites.objects.filter(domain=self.domain).exists(): - pass - else: - dic = {'getWebsiteCron': 0, 'error_message': 'You do not own this domain'} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - line -= 1 - website = Websites.objects.get(domain=self.domain) - - try: - CronUtil.CronPrem(1) - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" - execPath = execPath + " getWebsiteCron --externalApp " + website.externalApp - - f = ProcessUtilities.outputExecutioner(execPath, website.externalApp) - CronUtil.CronPrem(0) - except subprocess.CalledProcessError as error: - dic = {'getWebsiteCron': 0, 'error_message': 'Unable to access Cron file'} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - f = f.split("\n") - cron = f[line] - - cron = cron.split(" ", 5) - if len(cron) != 6: - dic = {'getWebsiteCron': 0, 'error_message': 'Cron line incorrect'} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - data_ret = {"getWebsiteCron": 1, - "user": website.externalApp, - "cron": { - "minute": cron[0], - "hour": cron[1], - "monthday": cron[2], - "month": cron[3], - "weekday": cron[4], - "command": cron[5], - }, - "line": line} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - except BaseException as msg: - print(msg) - dic = {'getWebsiteCron': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def saveCronChanges(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - line = data['line'] - - minute = data['minute'] - hour = data['hour'] - monthday = data['monthday'] - month = data['month'] - weekday = data['weekday'] - command = data['cronCommand'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('getWebsiteCron', 0) - - website = Websites.objects.get(domain=self.domain) - - finalCron = "%s %s %s %s %s %s" % (minute, hour, monthday, month, weekday, command) - - CronUtil.CronPrem(1) - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" - execPath = execPath + " saveCronChanges --externalApp " + website.externalApp + " --line " + str( - line) + " --finalCron '" + finalCron + "'" - output = ProcessUtilities.outputExecutioner(execPath, website.externalApp) - CronUtil.CronPrem(0) - - if output.find("1,") > -1: - data_ret = {"getWebsiteCron": 1, - "user": website.externalApp, - "cron": finalCron, - "line": line} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - else: - dic = {'getWebsiteCron': 0, 'error_message': output} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - except BaseException as msg: - dic = {'getWebsiteCron': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def remCronbyLine(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - line = data['line'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('addNewCron', 0) - - website = Websites.objects.get(domain=self.domain) - - CronUtil.CronPrem(1) - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" - execPath = execPath + " remCronbyLine --externalApp " + website.externalApp + " --line " + str( - line) - output = ProcessUtilities.outputExecutioner(execPath, website.externalApp) - - CronUtil.CronPrem(0) - - if output.find("1,") > -1: - data_ret = {"remCronbyLine": 1, - "user": website.externalApp, - "removeLine": output.split(',')[1], - "line": line} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - else: - dic = {'remCronbyLine': 0, 'error_message': output} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - - except BaseException as msg: - dic = {'remCronbyLine': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def addNewCron(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - minute = data['minute'] - hour = data['hour'] - monthday = data['monthday'] - month = data['month'] - weekday = data['weekday'] - command = data['cronCommand'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('addNewCron', 0) - - website = Websites.objects.get(domain=self.domain) - - if ProcessUtilities.decideDistro() == ProcessUtilities.centos or ProcessUtilities.decideDistro() == ProcessUtilities.cent8: - cronPath = "/var/spool/cron/" + website.externalApp - else: - cronPath = "/var/spool/cron/crontabs/" + website.externalApp - - commandT = 'touch %s' % (cronPath) - ProcessUtilities.executioner(commandT, 'root') - commandT = 'chown %s:%s %s' % (website.externalApp, website.externalApp, cronPath) - ProcessUtilities.executioner(commandT, 'root') - - CronUtil.CronPrem(1) - - finalCron = "%s %s %s %s %s %s" % (minute, hour, monthday, month, weekday, command) - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" - execPath = execPath + " addNewCron --externalApp " + website.externalApp + " --finalCron '" + finalCron + "'" - output = ProcessUtilities.outputExecutioner(execPath, website.externalApp) - - if ProcessUtilities.decideDistro() == ProcessUtilities.ubuntu or ProcessUtilities.decideDistro() == ProcessUtilities.ubuntu20: - command = 'chmod 600 %s' % (cronPath) - ProcessUtilities.executioner(command) - - command = 'systemctl restart cron' - ProcessUtilities.executioner(command) - - CronUtil.CronPrem(0) - - if output.find("1,") > -1: - - data_ret = {"addNewCron": 1, - "user": website.externalApp, - "cron": finalCron} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - else: - dic = {'addNewCron': 0, 'error_message': output} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - - except BaseException as msg: - dic = {'addNewCron': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def submitAliasCreation(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['masterDomain'] - aliasDomain = data['aliasDomain'] - ssl = data['ssl'] - - if not validators.domain(aliasDomain): - data_ret = {'status': 0, 'createAliasStatus': 0, 'error_message': "Invalid domain."} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('createAliasStatus', 0) - - sslpath = "/home/" + self.domain + "/public_html" - - ## Create Configurations - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - - execPath = execPath + " createAlias --masterDomain " + self.domain + " --aliasDomain " + aliasDomain + " --ssl " + str( - ssl) + " --sslPath " + sslpath + " --administratorEmail " + admin.email + ' --websiteOwner ' + admin.userName - - output = ProcessUtilities.outputExecutioner(execPath) - - if output.find("1,None") > -1: - pass - else: - data_ret = {'createAliasStatus': 0, 'error_message': output, "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - ## Create Configurations ends here - - data_ret = {'createAliasStatus': 1, 'error_message': "None", "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - - except BaseException as msg: - data_ret = {'createAliasStatus': 0, 'error_message': str(msg), "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def issueAliasSSL(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['masterDomain'] - aliasDomain = data['aliasDomain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('sslStatus', 0) - - if ACLManager.AliasDomainCheck(currentACL, aliasDomain, self.domain) == 1: - pass - else: - return ACLManager.loadErrorJson('sslStatus', 0) - - sslpath = "/home/" + self.domain + "/public_html" - - ## Create Configurations - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " issueAliasSSL --masterDomain " + self.domain + " --aliasDomain " + aliasDomain + " --sslPath " + sslpath + " --administratorEmail " + admin.email - - output = ProcessUtilities.outputExecutioner(execPath) - - if output.find("1,None") > -1: - data_ret = {'sslStatus': 1, 'error_message': "None", "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - data_ret = {'sslStatus': 0, 'error_message': output, "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'sslStatus': 0, 'error_message': str(msg), "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def delateAlias(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['masterDomain'] - aliasDomain = data['aliasDomain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('deleteAlias', 0) - - if ACLManager.AliasDomainCheck(currentACL, aliasDomain, self.domain) == 1: - pass - else: - return ACLManager.loadErrorJson('deleteAlias', 0) - - ## Create Configurations - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " deleteAlias --masterDomain " + self.domain + " --aliasDomain " + aliasDomain - output = ProcessUtilities.outputExecutioner(execPath) - - if output.find("1,None") > -1: - data_ret = {'deleteAlias': 1, 'error_message': "None", "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - data_ret = {'deleteAlias': 0, 'error_message': output, "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'deleteAlias': 0, 'error_message': str(msg), "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def changeOpenBasedir(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - - self.domain = data['domainName'] - openBasedirValue = data['openBasedirValue'] - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadErrorJson('changeOpenBasedir', 0) - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " changeOpenBasedir --virtualHostName '" + self.domain + "' --openBasedirValue " + openBasedirValue - output = ProcessUtilities.popenExecutioner(execPath) - - data_ret = {'status': 1, 'changeOpenBasedir': 1, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'changeOpenBasedir': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def wordpressInstall(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - proc = httpProc(request, 'websiteFunctions/installWordPress.html', {'domainName': self.domain}) - return proc.render() - - def installWordpress(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('installStatus', 0) - - mailUtilities.checkHome() - - extraArgs = {} - extraArgs['admin'] = admin - extraArgs['domainName'] = data['domain'] - extraArgs['home'] = data['home'] - extraArgs['blogTitle'] = data['blogTitle'] - extraArgs['adminUser'] = data['adminUser'] - extraArgs['adminPassword'] = data['passwordByPass'] - extraArgs['adminEmail'] = data['adminEmail'] - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - if data['home'] == '0': - extraArgs['path'] = data['path'] - - background = ApplicationInstaller('wordpress', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def installWordpressStatus(self, userID=None, data=None): - try: - statusFile = data['statusFile'] - - if ACLManager.CheckStatusFilleLoc(statusFile): - pass - else: - data_ret = {'abort': 1, 'installStatus': 0, 'installationProgress': "100", - 'currentStatus': 'Invalid status file.'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - statusData = ProcessUtilities.outputExecutioner("cat " + statusFile).splitlines() - - lastLine = statusData[-1] - - if lastLine.find('[200]') > -1: - command = 'rm -f ' + statusFile - subprocess.call(shlex.split(command)) - data_ret = {'abort': 1, 'installStatus': 1, 'installationProgress': "100", - 'currentStatus': 'Successfully Installed.'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - elif lastLine.find('[404]') > -1: - data_ret = {'abort': 1, 'installStatus': 0, 'installationProgress': "0", - 'error_message': ProcessUtilities.outputExecutioner("cat " + statusFile).splitlines()} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - progress = lastLine.split(',') - currentStatus = progress[0] - try: - installationProgress = progress[1] - except: - installationProgress = 0 - data_ret = {'abort': 0, 'installStatus': 0, 'installationProgress': installationProgress, - 'currentStatus': currentStatus} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'abort': 0, 'installStatus': 0, 'installationProgress': "0", 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def joomlaInstall(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - proc = httpProc(request, 'websiteFunctions/installJoomla.html', {'domainName': self.domain}) - return proc.render() - - def installJoomla(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('installStatus', 0) - - extraArgs = {} - - extraArgs['password'] = data['passwordByPass'] - extraArgs['prefix'] = data['prefix'] - extraArgs['domain'] = data['domain'] - extraArgs['home'] = data['home'] - extraArgs['siteName'] = data['siteName'] - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - mailUtilities.checkHome() - - if data['home'] == '0': - extraArgs['path'] = data['path'] - - background = ApplicationInstaller('joomla', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - ## Installation ends - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def setupGit(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - website = Websites.objects.get(domain=self.domain) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson() - - path = '/home/cyberpanel/' + self.domain + '.git' - - if os.path.exists(path): - ipFile = "/etc/cyberpanel/machineIP" - f = open(ipFile) - ipData = f.read() - ipAddress = ipData.split('\n', 1)[0] - - port = ProcessUtilities.fetchCurrentPort() - - webhookURL = 'https://' + ipAddress + ':%s/websites/' % (port) + self.domain + '/gitNotify' - - proc = httpProc(request, 'websiteFunctions/setupGit.html', - {'domainName': self.domain, 'installed': 1, 'webhookURL': webhookURL}) - return proc.render() - else: - - command = "ssh-keygen -f /home/%s/.ssh/%s -t rsa -N ''" % (self.domain, website.externalApp) - ProcessUtilities.executioner(command, website.externalApp) - - ### - - configContent = """Host github.com -IdentityFile /home/%s/.ssh/%s -StrictHostKeyChecking no -""" % (self.domain, website.externalApp) - - path = "/home/cyberpanel/config" - writeToFile = open(path, 'w') - writeToFile.writelines(configContent) - writeToFile.close() - - command = 'mv %s /home/%s/.ssh/config' % (path, self.domain) - ProcessUtilities.executioner(command) - - command = 'chown %s:%s /home/%s/.ssh/config' % (website.externalApp, website.externalApp, self.domain) - ProcessUtilities.executioner(command) - - command = 'cat /home/%s/.ssh/%s.pub' % (self.domain, website.externalApp) - deploymentKey = ProcessUtilities.outputExecutioner(command, website.externalApp) - - proc = httpProc(request, 'websiteFunctions/setupGit.html', - {'domainName': self.domain, 'deploymentKey': deploymentKey, 'installed': 0}) - return proc.render() - - def setupGitRepo(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('installStatus', 0) - - mailUtilities.checkHome() - - extraArgs = {} - extraArgs['admin'] = admin - extraArgs['domainName'] = data['domain'] - extraArgs['username'] = data['username'] - extraArgs['reponame'] = data['reponame'] - extraArgs['branch'] = data['branch'] - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - extraArgs['defaultProvider'] = data['defaultProvider'] - - background = ApplicationInstaller('git', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def gitNotify(self, userID=None, data=None): - try: - - extraArgs = {} - extraArgs['domain'] = self.domain - - background = ApplicationInstaller('pull', extraArgs) - background.start() - - data_ret = {'pulled': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'pulled': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def detachRepo(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson() - - mailUtilities.checkHome() - - extraArgs = {} - extraArgs['domainName'] = data['domain'] - extraArgs['admin'] = admin - - background = ApplicationInstaller('detach', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def changeBranch(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson() - - mailUtilities.checkHome() - - extraArgs = {} - extraArgs['domainName'] = data['domain'] - extraArgs['githubBranch'] = data['githubBranch'] - extraArgs['admin'] = admin - - background = ApplicationInstaller('changeBranch', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def installPrestaShop(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - proc = httpProc(request, 'websiteFunctions/installPrestaShop.html', {'domainName': self.domain}) - return proc.render() - - def installMagento(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - proc = httpProc(request, 'websiteFunctions/installMagento.html', {'domainName': self.domain}) - return proc.render() - - def magentoInstall(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('installStatus', 0) - - mailUtilities.checkHome() - - extraArgs = {} - extraArgs['admin'] = admin - extraArgs['domainName'] = data['domain'] - extraArgs['home'] = data['home'] - extraArgs['firstName'] = data['firstName'] - extraArgs['lastName'] = data['lastName'] - extraArgs['username'] = data['username'] - extraArgs['email'] = data['email'] - extraArgs['password'] = data['passwordByPass'] - extraArgs['sampleData'] = data['sampleData'] - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - if data['home'] == '0': - extraArgs['path'] = data['path'] - - background = ApplicationInstaller('magento', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - ## Installation ends - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def installMautic(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - proc = httpProc(request, 'websiteFunctions/installMautic.html', {'domainName': self.domain}) - return proc.render() - - def mauticInstall(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('installStatus', 0) - - #### Before installing mautic change php to 8.1 - - completePathToConfigFile = f'/usr/local/lsws/conf/vhosts/{self.domain}/vhost.conf' - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " changePHP --phpVersion 'PHP 8.1' --path " + completePathToConfigFile - ProcessUtilities.executioner(execPath) - - mailUtilities.checkHome() - - extraArgs = {} - extraArgs['admin'] = admin - extraArgs['domainName'] = data['domain'] - extraArgs['home'] = data['home'] - extraArgs['username'] = data['username'] - extraArgs['email'] = data['email'] - extraArgs['password'] = data['passwordByPass'] - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - if data['home'] == '0': - extraArgs['path'] = data['path'] - - background = ApplicationInstaller('mautic', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - ## Installation ends - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def prestaShopInstall(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('installStatus', 0) - - mailUtilities.checkHome() - - extraArgs = {} - extraArgs['admin'] = admin - extraArgs['domainName'] = data['domain'] - extraArgs['home'] = data['home'] - extraArgs['shopName'] = data['shopName'] - extraArgs['firstName'] = data['firstName'] - extraArgs['lastName'] = data['lastName'] - extraArgs['databasePrefix'] = data['databasePrefix'] - extraArgs['email'] = data['email'] - extraArgs['password'] = data['passwordByPass'] - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - if data['home'] == '0': - extraArgs['path'] = data['path'] - - #### Before installing Prestashop change php to 8.3 - - completePathToConfigFile = f'/usr/local/lsws/conf/vhosts/{self.domain}/vhost.conf' - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " changePHP --phpVersion 'PHP 8.3' --path " + completePathToConfigFile - ProcessUtilities.executioner(execPath) - - background = ApplicationInstaller('prestashop', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - ## Installation ends - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def createWebsiteAPI(self, data=None): - try: - - adminUser = data['adminUser'] - adminPass = data['adminPass'] - adminEmail = data['ownerEmail'] - websiteOwner = data['websiteOwner'] - ownerPassword = data['ownerPassword'] - data['ssl'] = 1 - data['dkimCheck'] = 1 - data['openBasedir'] = 1 - data['adminEmail'] = data['ownerEmail'] - - try: - data['phpSelection'] = data['phpSelection'] - except: - data['phpSelection'] = "PHP 7.4" - - data['package'] = data['packageName'] - try: - websitesLimit = data['websitesLimit'] - except: - websitesLimit = 1 - - try: - apiACL = data['acl'] - except: - apiACL = 'user' - - admin = Administrator.objects.get(userName=adminUser) - - if hashPassword.check_password(admin.password, adminPass): - - if adminEmail is None: - data['adminEmail'] = "example@example.org" - - try: - acl = ACL.objects.get(name=apiACL) - websiteOwn = Administrator(userName=websiteOwner, - password=hashPassword.hash_password(ownerPassword), - email=adminEmail, type=3, owner=admin.pk, - initWebsitesLimit=websitesLimit, acl=acl, api=1) - websiteOwn.save() - except BaseException: - pass - - else: - data_ret = {"existsStatus": 0, 'createWebSiteStatus': 0, - 'error_message': "Could not authorize access to API"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - return self.submitWebsiteCreation(admin.pk, data) - - except BaseException as msg: - data_ret = {'createWebSiteStatus': 0, 'error_message': str(msg), "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def searchWebsitesJson(self, currentlACL, userID, searchTerm): - - websites = ACLManager.searchWebsiteObjects(currentlACL, userID, searchTerm) - - json_data = "[" - checker = 0 - - try: - ipFile = "/etc/cyberpanel/machineIP" - f = open(ipFile) - ipData = f.read() - ipAddress = ipData.split('\n', 1)[0] - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile("Failed to read machine IP, error:" + str(msg)) - ipAddress = "192.168.100.1" - - for items in websites: - if items.state == 0: - state = "Suspended" - else: - state = "Active" - - DiskUsage, DiskUsagePercentage, bwInMB, bwUsage = virtualHostUtilities.FindStats(items) - - vhFile = f'/usr/local/lsws/conf/vhosts/{items.domain}/vhost.conf' - - if os.path.exists(ProcessUtilities.debugPath): - logging.CyberCPLogFileWriter.writeToFile(vhFile) - - try: - from plogical.phpUtilities import phpUtilities - PHPVersionActual = phpUtilities.WrapGetPHPVersionFromFileToGetVersionWithPHP(vhFile) - except: - PHPVersionActual = 'PHP 8.1' - - diskUsed = "%sMB" % str(DiskUsage) - dic = {'domain': items.domain, 'adminEmail': items.adminEmail, 'ipAddress': ipAddress, - 'admin': items.admin.userName, 'package': items.package.packageName, 'state': state, - 'diskUsed': diskUsed, 'phpVersion': PHPVersionActual} - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - - json_data = json_data + ']' - - return json_data - - def findWebsitesJson(self, currentACL, userID, pageNumber): - finalPageNumber = ((pageNumber * 10)) - 10 - endPageNumber = finalPageNumber + 10 - websites = ACLManager.findWebsiteObjects(currentACL, userID)[finalPageNumber:endPageNumber] - - json_data = "[" - checker = 0 - - try: - ipFile = "/etc/cyberpanel/machineIP" - f = open(ipFile) - ipData = f.read() - ipAddress = ipData.split('\n', 1)[0] - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile("Failed to read machine IP, error:" + str(msg)) - ipAddress = "192.168.100.1" - - for items in websites: - if items.state == 0: - state = "Suspended" - else: - state = "Active" - - DiskUsage, DiskUsagePercentage, bwInMB, bwUsage = virtualHostUtilities.FindStats(items) - - diskUsed = "%sMB" % str(DiskUsage) - - dic = {'domain': items.domain, 'adminEmail': items.adminEmail, 'ipAddress': ipAddress, - 'admin': items.admin.userName, 'package': items.package.packageName, 'state': state, - 'diskUsed': diskUsed} - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - - json_data = json_data + ']' - - return json_data - - def websitePagination(self, currentACL, userID): - websites = ACLManager.findAllSites(currentACL, userID) - - pages = float(len(websites)) / float(10) - pagination = [] - - if pages <= 1.0: - pages = 1 - pagination.append('
  • ') - else: - pages = ceil(pages) - finalPages = int(pages) + 1 - - for i in range(1, finalPages): - pagination.append('
  • ' + str(i) + '
  • ') - - return pagination - - def DockersitePagination(self, currentACL, userID): - websites = DockerSites.objects.all() - - pages = float(len(websites)) / float(10) - pagination = [] - - if pages <= 1.0: - pages = 1 - pagination.append('
  • ') - else: - pages = ceil(pages) - finalPages = int(pages) + 1 - - for i in range(1, finalPages): - pagination.append('
  • ' + str(i) + '
  • ') - - return pagination - - def getSwitchStatus(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - try: - globalData = data['global'] - - data = {} - data['status'] = 1 - - if os.path.exists('/etc/httpd'): - data['server'] = 1 - else: - data['server'] = 0 - - json_data = json.dumps(data) - return HttpResponse(json_data) - except: - pass - - self.domain = data['domainName'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - if ProcessUtilities.decideServer() == ProcessUtilities.OLS: - finalConfPath = ApacheVhost.configBasePath + self.domain + '.conf' - - if os.path.exists(finalConfPath): - - phpPath = ApacheVhost.whichPHPExists(self.domain) - command = 'sudo cat ' + phpPath - phpConf = ProcessUtilities.outputExecutioner(command).splitlines() - pmMaxChildren = phpConf[8].split(' ')[2] - pmStartServers = phpConf[9].split(' ')[2] - pmMinSpareServers = phpConf[10].split(' ')[2] - pmMaxSpareServers = phpConf[11].split(' ')[2] - - data = {} - data['status'] = 1 - - data['server'] = WebsiteManager.apache - data['pmMaxChildren'] = pmMaxChildren - data['pmStartServers'] = pmStartServers - data['pmMinSpareServers'] = pmMinSpareServers - data['pmMaxSpareServers'] = pmMaxSpareServers - data['phpPath'] = phpPath - data['configData'] = ProcessUtilities.outputExecutioner(f'cat {finalConfPath}') - else: - data = {} - data['status'] = 1 - data['server'] = WebsiteManager.ols - - else: - data = {} - data['status'] = 1 - data['server'] = WebsiteManager.lsws - - json_data = json.dumps(data) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'saveStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def switchServer(self, userID=None, data=None): - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - domainName = data['domainName'] - phpVersion = data['phpSelection'] - server = data['server'] - - if ACLManager.checkOwnership(domainName, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson() - - tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " switchServer --phpVersion '" + phpVersion + "' --server " + str( - server) + " --virtualHostName " + domainName + " --tempStatusPath " + tempStatusPath - ProcessUtilities.popenExecutioner(execPath) - - time.sleep(3) - - data_ret = {'status': 1, 'tempStatusPath': tempStatusPath} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def tuneSettings(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - domainName = data['domainName'] - pmMaxChildren = data['pmMaxChildren'] - pmStartServers = data['pmStartServers'] - pmMinSpareServers = data['pmMinSpareServers'] - pmMaxSpareServers = data['pmMaxSpareServers'] - phpPath = data['phpPath'] - - if ACLManager.checkOwnership(domainName, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson() - - if int(pmStartServers) < int(pmMinSpareServers) or int(pmStartServers) > int(pmMinSpareServers): - data_ret = {'status': 0, - 'error_message': 'pm.start_servers must not be less than pm.min_spare_servers and not greater than pm.max_spare_servers.'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - if int(pmMinSpareServers) > int(pmMaxSpareServers): - data_ret = {'status': 0, - 'error_message': 'pm.max_spare_servers must not be less than pm.min_spare_servers'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - try: - website = Websites.objects.get(domain=domainName) - externalApp = website.externalApp - except: - website = ChildDomains.objects.get(domain=domainName) - externalApp = website.master.externalApp - - tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - - if ProcessUtilities.decideDistro() == ProcessUtilities.centos or ProcessUtilities.decideDistro() == ProcessUtilities.cent8: - sockPath = '/var/run/php-fpm/' - group = 'nobody' - else: - sockPath = '/var/run/php/' - group = 'nogroup' - - phpFPMConf = vhostConfs.phpFpmPoolReplace - phpFPMConf = phpFPMConf.replace('{externalApp}', externalApp) - phpFPMConf = phpFPMConf.replace('{pmMaxChildren}', pmMaxChildren) - phpFPMConf = phpFPMConf.replace('{pmStartServers}', pmStartServers) - phpFPMConf = phpFPMConf.replace('{pmMinSpareServers}', pmMinSpareServers) - phpFPMConf = phpFPMConf.replace('{pmMaxSpareServers}', pmMaxSpareServers) - phpFPMConf = phpFPMConf.replace('{www}', "".join(re.findall("[a-zA-Z]+", domainName))[:7]) - phpFPMConf = phpFPMConf.replace('{Sock}', domainName) - phpFPMConf = phpFPMConf.replace('{sockPath}', sockPath) - phpFPMConf = phpFPMConf.replace('{group}', group) - - writeToFile = open(tempStatusPath, 'w') - writeToFile.writelines(phpFPMConf) - writeToFile.close() - - command = 'sudo mv %s %s' % (tempStatusPath, phpPath) - ProcessUtilities.executioner(command) - - phpPath = phpPath.split('/') - - if os.path.exists(ProcessUtilities.debugPath): - logging.CyberCPLogFileWriter.writeToFile(f'PHP path in tune settings {phpPath}') - - if ProcessUtilities.decideDistro() == ProcessUtilities.centos or ProcessUtilities.decideDistro() == ProcessUtilities.cent8: - if phpPath[1] == 'etc': - phpVersion = phpPath[4][3] + phpPath[4][4] - phpVersion = f'PHP {phpPath[4][3]}.{phpPath[4][4]}' - else: - phpVersion = phpPath[3][3] + phpPath[3][4] - phpVersion = f'PHP {phpPath[3][3]}.{phpPath[3][4]}' - else: - phpVersion = f'PHP {phpPath[2]}' - - # php = PHPManager.getPHPString(phpVersion) - - if os.path.exists(ProcessUtilities.debugPath): - logging.CyberCPLogFileWriter.writeToFile(f'PHP Version in tune settings {phpVersion}') - - phpService = ApacheVhost.DecideFPMServiceName(phpVersion) - - if os.path.exists(ProcessUtilities.debugPath): - logging.CyberCPLogFileWriter.writeToFile(f'PHP service in tune settings {phpService}') - - command = f"systemctl stop {phpService}" - ProcessUtilities.normalExecutioner(command) - - command = f"systemctl restart {phpService}" - ProcessUtilities.normalExecutioner(command) - - data_ret = {'status': 1} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def sshAccess(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - website = Websites.objects.get(domain=self.domain) - externalApp = website.externalApp - - proc = httpProc(request, 'websiteFunctions/sshAccess.html', - {'domainName': self.domain, 'externalApp': externalApp}) - return proc.render() - - def saveSSHAccessChanges(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - website = Websites.objects.get(domain=self.domain) - - # if website.externalApp != data['externalApp']: - # data_ret = {'status': 0, 'error_message': 'External app mis-match.'} - # json_data = json.dumps(data_ret) - # return HttpResponse(json_data) - - uBuntuPath = '/etc/lsb-release' - - if os.path.exists(uBuntuPath): - command = "echo '%s:%s' | chpasswd" % (website.externalApp, data['password']) - else: - command = 'echo "%s" | passwd --stdin %s' % (data['password'], website.externalApp) - - ProcessUtilities.executioner(command) - - data_ret = {'status': 1, 'error_message': 'None', 'LinuxUser': website.externalApp} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def setupStaging(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - website = Websites.objects.get(domain=self.domain) - externalApp = website.externalApp - - proc = httpProc(request, 'websiteFunctions/setupStaging.html', - {'domainName': self.domain, 'externalApp': externalApp}) - return proc.render() - - def startCloning(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['masterDomain'] - - if not validators.domain(self.domain): - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Invalid domain."} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - if not validators.domain(data['domainName']): - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Invalid domain."} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - extraArgs = {} - extraArgs['domain'] = data['domainName'] - extraArgs['masterDomain'] = data['masterDomain'] - extraArgs['admin'] = admin - - tempStatusPath = "/tmp/" + str(randint(1000, 9999)) - writeToFile = open(tempStatusPath, 'a') - message = 'Cloning process has started..,5' - writeToFile.write(message) - writeToFile.close() - - extraArgs['tempStatusPath'] = tempStatusPath - - st = StagingSetup('startCloning', extraArgs) - st.start() - - data_ret = {'status': 1, 'error_message': 'None', 'tempStatusPath': tempStatusPath} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def syncToMaster(self, request=None, userID=None, data=None, childDomain=None): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - website = Websites.objects.get(domain=self.domain) - externalApp = website.externalApp - - proc = httpProc(request, 'websiteFunctions/syncMaster.html', - {'domainName': self.domain, 'externalApp': externalApp, 'childDomain': childDomain}) - return proc.render() - - def startSync(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if not validators.domain(data['childDomain']): - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Invalid domain."} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - self.domain = data['childDomain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - extraArgs = {} - extraArgs['childDomain'] = data['childDomain'] - try: - extraArgs['eraseCheck'] = data['eraseCheck'] - except: - extraArgs['eraseCheck'] = False - try: - extraArgs['dbCheck'] = data['dbCheck'] - except: - extraArgs['dbCheck'] = False - try: - extraArgs['copyChanged'] = data['copyChanged'] - except: - extraArgs['copyChanged'] = False - - extraArgs['admin'] = admin - - tempStatusPath = "/tmp/" + str(randint(1000, 9999)) - writeToFile = open(tempStatusPath, 'a') - message = 'Syncing process has started..,5' - writeToFile.write(message) - writeToFile.close() - - extraArgs['tempStatusPath'] = tempStatusPath - - st = StagingSetup('startSyncing', extraArgs) - st.start() - - data_ret = {'status': 1, 'error_message': 'None', 'tempStatusPath': tempStatusPath} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def convertDomainToSite(self, userID=None, request=None): - try: - - extraArgs = {} - extraArgs['request'] = request - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - background = ApplicationInstaller('convertDomainToSite', extraArgs) - background.start() - - data_ret = {'status': 1, 'createWebSiteStatus': 1, 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def manageGIT(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - try: - website = Websites.objects.get(domain=self.domain) - folders = ['/home/%s/public_html' % (self.domain)] - - databases = website.databases_set.all() - - # for database in databases: - # basePath = '/var/lib/mysql/' - # folders.append('%s%s' % (basePath, database.dbName)) - except: - - self.childWebsite = ChildDomains.objects.get(domain=self.domain) - - folders = [self.childWebsite.path] - - databases = self.childWebsite.master.databases_set.all() - - # for database in databases: - # basePath = '/var/lib/mysql/' - # folders.append('%s%s' % (basePath, database.dbName)) - - proc = httpProc(request, 'websiteFunctions/manageGIT.html', - {'domainName': self.domain, 'folders': folders}) - return proc.render() - - def folderCheck(self): - - try: - - ### - - domainPath = '/home/%s/public_html' % (self.domain) - vhRoot = '/home/%s' % (self.domain) - vmailPath = '/home/vmail/%s' % (self.domain) - - ## - - try: - - website = Websites.objects.get(domain=self.domain) - - self.masterWebsite = website - self.masterDomain = website.domain - externalApp = website.externalApp - self.externalAppLocal = website.externalApp - self.adminEmail = website.adminEmail - self.firstName = website.admin.firstName - self.lastName = website.admin.lastName - - self.home = 0 - if self.folder == '/home/%s/public_html' % (self.domain): - self.home = 1 - - except: - - website = ChildDomains.objects.get(domain=self.domain) - self.masterWebsite = website.master - self.masterDomain = website.master.domain - externalApp = website.master.externalApp - self.externalAppLocal = website.master.externalApp - self.adminEmail = website.master.adminEmail - self.firstName = website.master.admin.firstName - self.lastName = website.master.admin.lastName - - self.home = 0 - if self.folder == website.path: - self.home = 1 - - ### Fetch git configurations - - self.confCheck = 1 - - gitConfFolder = '/home/cyberpanel/git' - gitConFile = '%s/%s' % (gitConfFolder, self.masterDomain) - - if not os.path.exists(gitConfFolder): - os.mkdir(gitConfFolder) - - if not os.path.exists(gitConFile): - os.mkdir(gitConFile) - - if os.path.exists(gitConFile): - files = os.listdir(gitConFile) - - if len(files) >= 1: - for file in files: - self.finalFile = '%s/%s' % (gitConFile, file) - - gitConf = json.loads(open(self.finalFile, 'r').read()) - - if gitConf['folder'] == self.folder: - - self.autoCommitCurrent = gitConf['autoCommit'] - self.autoPushCurrent = gitConf['autoPush'] - self.emailLogsCurrent = gitConf['emailLogs'] - try: - self.commands = gitConf['commands'] - except: - self.commands = "Add Commands to run after every commit, separate commands using comma." - - try: - self.webhookCommandCurrent = gitConf['webhookCommand'] - except: - self.webhookCommandCurrent = "False" - - self.confCheck = 0 - break - - if self.confCheck: - self.autoCommitCurrent = 'Never' - self.autoPushCurrent = 'Never' - self.emailLogsCurrent = 'False' - self.webhookCommandCurrent = 'False' - self.commands = "Add Commands to run after every commit, separate commands using comma." - - ## - - if self.folder == domainPath: - self.externalApp = externalApp - return 1 - - ## - - if self.folder == vhRoot: - self.externalApp = externalApp - return 1 - - ## - - try: - childDomain = ChildDomains.objects.get(domain=self.domain) - - if self.folder == childDomain.path: - self.externalApp = externalApp - return 1 - - except: - pass - - ## - - if self.folder == vmailPath: - self.externalApp = 'vmail' - return 1 - - try: - - for database in website.databases_set.all(): - self.externalApp = 'mysql' - basePath = '/var/lib/mysql/' - dbPath = '%s%s' % (basePath, database.dbName) - - if self.folder == dbPath: - return 1 - except: - for database in website.master.databases_set.all(): - self.externalApp = 'mysql' - basePath = '/var/lib/mysql/' - dbPath = '%s%s' % (basePath, database.dbName) - - if self.folder == dbPath: - return 1 - - return 0 - - - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile('%s. [folderCheck:3002]' % (str(msg))) - - return 0 - - def fetchFolderDetails(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - self.folder = data['folder'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - if self.folderCheck(): - pass - else: - return ACLManager.loadErrorJson() - - gitPath = '%s/.git' % (self.folder) - command = 'ls -la %s' % (gitPath) - - if ProcessUtilities.outputExecutioner(command, self.externalAppLocal).find( - 'No such file or directory') > -1: - - command = 'cat /home/%s/.ssh/%s.pub' % (self.masterDomain, self.externalAppLocal) - deploymentKey = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) - - if deploymentKey.find('No such file or directory') > -1: - command = "ssh-keygen -f /home/%s/.ssh/%s -t rsa -N ''" % (self.masterDomain, self.externalAppLocal) - ProcessUtilities.executioner(command, self.externalAppLocal) - - command = 'cat /home/%s/.ssh/%s.pub' % (self.masterDomain, self.externalAppLocal) - deploymentKey = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) - - data_ret = {'status': 1, 'repo': 0, 'deploymentKey': deploymentKey, 'home': self.home} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - - ## Find git branches - - command = 'git -C %s branch' % (self.folder) - branches = ProcessUtilities.outputExecutioner(command, self.externalAppLocal).split('\n')[:-1] - - ## Fetch key - - command = 'cat /home/%s/.ssh/%s.pub' % (self.domain, self.externalAppLocal) - deploymentKey = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) - - if deploymentKey.find('No such file or directory') > -1: - command = "ssh-keygen -f /home/%s/.ssh/%s -t rsa -N ''" % (self.masterDomain, self.externalAppLocal) - ProcessUtilities.executioner(command, self.externalAppLocal) - - command = 'cat /home/%s/.ssh/%s.pub' % (self.masterDomain, self.externalAppLocal) - deploymentKey = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) - - ## Find Remote if any - - command = 'git -C %s remote -v' % (self.folder) - remoteResult = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) - - remote = 1 - if remoteResult.find('origin') == -1: - remote = 0 - remoteResult = 'Remote currently not set.' - - ## Find Total commits on current branch - - command = 'git -C %s rev-list --count HEAD' % (self.folder) - totalCommits = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) - - if totalCommits.find('fatal') > -1: - totalCommits = '0' - - ## - - port = ProcessUtilities.fetchCurrentPort() - - webHookURL = 'https://%s:%s/websites/%s/webhook' % (ACLManager.fetchIP(), port, self.domain) - - data_ret = {'status': 1, 'repo': 1, 'finalBranches': branches, 'deploymentKey': deploymentKey, - 'remote': remote, 'remoteResult': remoteResult, 'totalCommits': totalCommits, - 'home': self.home, - 'webHookURL': webHookURL, 'autoCommitCurrent': self.autoCommitCurrent, - 'autoPushCurrent': self.autoPushCurrent, 'emailLogsCurrent': self.emailLogsCurrent, - 'commands': self.commands, "webhookCommandCurrent": self.webhookCommandCurrent} - - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def initRepo(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - self.folder = data['folder'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - if self.folderCheck(): - pass - else: - return ACLManager.loadErrorJson() - - website = Websites.objects.get(domain=self.masterDomain) - - command = 'git -C %s init' % (self.folder) - result = ProcessUtilities.outputExecutioner(command, website.externalApp) - - if result.find('Initialized empty Git repository in') > -1: - - command = 'git -C %s config --local user.email %s' % (self.folder, self.adminEmail) - ProcessUtilities.executioner(command, website.externalApp) - - command = 'git -C %s config --local user.name "%s %s"' % ( - self.folder, self.firstName, self.lastName) - ProcessUtilities.executioner(command, website.externalApp) - - ## Fix permissions - - # from filemanager.filemanager import FileManager - # - # fm = FileManager(None, None) - # fm.fixPermissions(self.masterDomain) - - data_ret = {'status': 1} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - data_ret = {'status': 0, 'error_message': result} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def setupRemote(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - self.folder = data['folder'] - self.gitHost = data['gitHost'] - self.gitUsername = data['gitUsername'] - self.gitReponame = data['gitReponame'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - ## Security checks - - if self.folderCheck(): - pass - else: - return ACLManager.loadErrorJson() - - if self.gitHost.find(':') > -1: - gitHostDomain = self.gitHost.split(':')[0] - gitHostPort = self.gitHost.split(':')[1] - - if not validators.domain(gitHostDomain): - return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') - - try: - gitHostPort = int(gitHostPort) - except: - return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') - - else: - if not validators.domain(self.gitHost): - return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') - - if ACLManager.validateInput(self.gitUsername) and ACLManager.validateInput(self.gitReponame): - pass - else: - return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') - - ### set default ssh key - - command = 'git -C %s config --local core.sshCommand "ssh -i /home/%s/.ssh/%s -o "StrictHostKeyChecking=no""' % ( - self.folder, self.masterDomain, self.externalAppLocal) - ProcessUtilities.executioner(command, self.externalAppLocal) - - ## Check if remote exists - - command = 'git -C %s remote -v' % (self.folder) - remoteResult = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) - - ## Set new remote - - if remoteResult.find('origin') == -1: - command = 'git -C %s remote add origin git@%s:%s/%s.git' % ( - self.folder, self.gitHost, self.gitUsername, self.gitReponame) - else: - command = 'git -C %s remote set-url origin git@%s:%s/%s.git' % ( - self.folder, self.gitHost, self.gitUsername, self.gitReponame) - - possibleError = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) - - ## Check if set correctly. - - command = 'git -C %s remote -v' % (self.folder) - remoteResult = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) - - if remoteResult.find(self.gitUsername) > -1: - - # ## Fix permissions - # - # from filemanager.filemanager import FileManager - # - # fm = FileManager(None, None) - # fm.fixPermissions(self.masterDomain) - - data_ret = {'status': 1} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - data_ret = {'status': 0, 'error_message': possibleError} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def changeGitBranch(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - self.folder = data['folder'] - self.branchName = data['branchName'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - if self.folderCheck(): - pass - else: - return ACLManager.loadErrorJson() - - ## Security check - - if ACLManager.validateInput(self.branchName): - pass - else: - return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') - - if self.branchName.find('*') > -1: - data_ret = {'status': 0, 'commandStatus': 'Already on this branch.', - 'error_message': 'Already on this branch.'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - self.externalApp = ACLManager.FetchExternalApp(self.domain) - - command = 'git -C %s checkout %s' % (self.folder, self.branchName.strip(' ')) - commandStatus = ProcessUtilities.outputExecutioner(command, self.externalApp) - - if commandStatus.find('Switched to branch') > -1: - - # ## Fix permissions - # - # from filemanager.filemanager import FileManager - # - # fm = FileManager(None, None) - # fm.fixPermissions(self.masterDomain) - - data_ret = {'status': 1, 'commandStatus': commandStatus + 'Refreshing page in 3 seconds..'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - data_ret = {'status': 0, 'error_message': 'Failed to change branch', 'commandStatus': commandStatus} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def createNewBranch(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - self.folder = data['folder'] - self.newBranchName = data['newBranchName'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - if self.folderCheck(): - pass - else: - return ACLManager.loadErrorJson() - - ## Security check - - if ACLManager.validateInput(self.newBranchName): - pass - else: - return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') - - ## - - self.externalApp = ACLManager.FetchExternalApp(self.domain) - - command = 'git -C %s checkout -b "%s"' % (self.folder, self.newBranchName) - commandStatus = ProcessUtilities.outputExecutioner(command, self.externalApp) - - if commandStatus.find(self.newBranchName) > -1: - - # ## Fix permissions - # - # from filemanager.filemanager import FileManager - # - # fm = FileManager(None, None) - # fm.fixPermissions(self.masterDomain) - - data_ret = {'status': 1, 'commandStatus': commandStatus} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - data_ret = {'status': 0, 'error_message': 'Failed to create branch', 'commandStatus': commandStatus} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def commitChanges(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - self.folder = data['folder'] - self.commitMessage = data['commitMessage'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - if self.folderCheck(): - pass - else: - return ACLManager.loadErrorJson('status', 0) - - # security check - - if ACLManager.validateInput(self.commitMessage): - pass - else: - return ACLManager.loadErrorJson() - - self.externalApp = ACLManager.FetchExternalApp(self.domain) - - ## Check if remote exists - - command = 'git -C %s add -A' % (self.folder) - ProcessUtilities.outputExecutioner(command, self.externalApp) - - command = 'git -C %s commit -m "%s"' % (self.folder, self.commitMessage.replace('"', '')) - commandStatus = ProcessUtilities.outputExecutioner(command, self.externalApp) - - if commandStatus.find('nothing to commit') == -1: - - try: - if self.commands != 'NONE': - - GitLogs(owner=self.masterWebsite, type='INFO', - message='Running commands after successful git commit..').save() - - if self.commands.find('\n') > -1: - commands = self.commands.split('\n') - - for command in commands: - GitLogs(owner=self.masterWebsite, type='INFO', - message='Running: %s' % (command)).save() - - result = ProcessUtilities.outputExecutioner(command, self.externalAppLocal) - GitLogs(owner=self.masterWebsite, type='INFO', - message='Result: %s' % (result)).save() - else: - GitLogs(owner=self.masterWebsite, type='INFO', - message='Running: %s' % (self.commands)).save() - - result = ProcessUtilities.outputExecutioner(self.commands, self.externalAppLocal) - GitLogs(owner=self.masterWebsite, type='INFO', - message='Result: %s' % (result)).save() - - GitLogs(owner=self.masterWebsite, type='INFO', - message='Finished running commands.').save() - except: - pass - - ## Fix permissions - - # from filemanager.filemanager import FileManager - # - # fm = FileManager(None, None) - # fm.fixPermissions(self.masterDomain) - - data_ret = {'status': 1, 'commandStatus': commandStatus} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - data_ret = {'status': 0, 'error_message': 'Nothing to commit.', 'commandStatus': commandStatus} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg), 'commandStatus': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def gitPull(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - self.folder = data['folder'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - if self.folderCheck(): - pass - else: - return ACLManager.loadErrorJson() - - self.externalApp = ACLManager.FetchExternalApp(self.domain) - - ### set default ssh key - - command = 'git -C %s config --local core.sshCommand "ssh -i /home/%s/.ssh/%s -o "StrictHostKeyChecking=no""' % ( - self.folder, self.masterDomain, self.externalAppLocal) - ProcessUtilities.executioner(command, self.externalApp) - - ## Check if remote exists - - command = 'git -C %s pull' % (self.folder) - commandStatus = ProcessUtilities.outputExecutioner(command, self.externalApp) - - if commandStatus.find('Already up to date') == -1: - - ## Fix permissions - - # from filemanager.filemanager import FileManager - # - # fm = FileManager(None, None) - # fm.fixPermissions(self.masterDomain) - - data_ret = {'status': 1, 'commandStatus': commandStatus} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - data_ret = {'status': 0, 'error_message': 'Pull not required.', 'commandStatus': commandStatus} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def gitPush(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - self.folder = data['folder'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - if self.folderCheck(): - pass - else: - return ACLManager.loadErrorJson() - - self.externalApp = ACLManager.FetchExternalApp(self.domain) - - ### set default ssh key - - command = 'git -C %s config --local core.sshCommand "ssh -i /home/%s/.ssh/%s -o "StrictHostKeyChecking=no""' % ( - self.folder, self.masterDomain, self.externalAppLocal) - ProcessUtilities.executioner(command, self.externalApp) - - ## - - command = 'git -C %s push' % (self.folder) - commandStatus = ProcessUtilities.outputExecutioner(command, self.externalApp, False) - - if commandStatus.find('has no upstream branch') > -1: - command = 'git -C %s rev-parse --abbrev-ref HEAD' % (self.folder) - currentBranch = ProcessUtilities.outputExecutioner(command, self.externalApp, False).rstrip('\n') - - if currentBranch.find('fatal: ambiguous argument') > -1: - data_ret = {'status': 0, 'error_message': 'You need to commit first.', - 'commandStatus': 'You need to commit first.'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - command = 'git -C %s push --set-upstream origin %s' % (self.folder, currentBranch) - commandStatus = ProcessUtilities.outputExecutioner(command, self.externalApp, False) - - if commandStatus.find('Everything up-to-date') == -1 and commandStatus.find( - 'rejected') == -1 and commandStatus.find('Permission denied') == -1: - data_ret = {'status': 1, 'commandStatus': commandStatus} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - data_ret = {'status': 0, 'error_message': 'Push failed.', 'commandStatus': commandStatus} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg), 'commandStatus': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def attachRepoGIT(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - self.folder = data['folder'] - self.gitHost = data['gitHost'] - self.gitUsername = data['gitUsername'] - self.gitReponame = data['gitReponame'] - - try: - self.overrideData = data['overrideData'] - except: - self.overrideData = False - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - if self.folderCheck(): - pass - else: - return ACLManager.loadErrorJson() - - if self.gitHost.find(':') > -1: - gitHostDomain = self.gitHost.split(':')[0] - gitHostPort = self.gitHost.split(':')[1] - - if not validators.domain(gitHostDomain): - return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') - - try: - gitHostPort = int(gitHostPort) - except: - return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') - else: - if not validators.domain(self.gitHost): - return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') - - ## Security check - - if ACLManager.validateInput(self.gitUsername) and ACLManager.validateInput(self.gitReponame): - pass - else: - return ACLManager.loadErrorJson('status', 'Invalid characters in your input.') - - ## - - self.externalApp = ACLManager.FetchExternalApp(self.domain) - - if self.overrideData: - command = 'rm -rf %s' % (self.folder) - ProcessUtilities.executioner(command, self.externalApp) - - ## Set defauly key - - command = 'git config --global core.sshCommand "ssh -i /home/%s/.ssh/%s -o "StrictHostKeyChecking=no""' % ( - self.masterDomain, self.externalAppLocal) - ProcessUtilities.executioner(command, self.externalApp) - - ## - - command = 'git clone git@%s:%s/%s.git %s' % (self.gitHost, self.gitUsername, self.gitReponame, self.folder) - commandStatus = ProcessUtilities.outputExecutioner(command, self.externalApp) - - if commandStatus.find('already exists') == -1 and commandStatus.find('Permission denied') == -1: - - # from filemanager.filemanager import FileManager - # - # fm = FileManager(None, None) - # fm.fixPermissions(self.masterDomain) - - command = 'git -C %s config --local user.email %s' % (self.folder, self.adminEmail) - ProcessUtilities.executioner(command, self.externalApp) - - command = 'git -C %s config --local user.name "%s %s"' % (self.folder, self.firstName, self.lastName) -#!/usr/local/CyberCP/bin/python -import html -import os -import os.path -import sys -import django - -from databases.models import Databases -from plogical.DockerSites import Docker_Sites -from plogical.httpProc import httpProc - -sys.path.append('/usr/local/CyberCP') -os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings") -django.setup() -import json -from plogical.acl import ACLManager -import plogical.CyberCPLogFileWriter as logging -from websiteFunctions.models import Websites, ChildDomains, GitLogs, wpplugins, WPSites, WPStaging, WPSitesBackup, \ - RemoteBackupConfig, RemoteBackupSchedule, RemoteBackupsites, DockerPackages, PackageAssignment, DockerSites -from plogical.virtualHostUtilities import virtualHostUtilities -import subprocess -import shlex -from plogical.installUtilities import installUtilities -from django.shortcuts import HttpResponse, render, redirect -from loginSystem.models import Administrator, ACL -from packages.models import Package -from plogical.mailUtilities import mailUtilities -from random import randint -import time -import re -import boto3 -from plogical.childDomain import ChildDomainManager -from math import ceil -from plogical.alias import AliasManager -from plogical.applicationInstaller import ApplicationInstaller -from plogical import hashPassword, randomPassword -from emailMarketing.emACL import emACL -from plogical.processUtilities import ProcessUtilities -from managePHP.phpManager import PHPManager -from ApachController.ApacheVhosts import ApacheVhost -from plogical.vhostConfs import vhostConfs -from plogical.cronUtil import CronUtil -from .StagingSetup import StagingSetup -import validators -from django.http import JsonResponse - - -class WebsiteManager: - apache = 1 - ols = 2 - lsws = 3 - - def __init__(self, domain=None, childDomain=None): - self.domain = domain - self.childDomain = childDomain - - def createWebsite(self, request=None, userID=None, data=None): - - url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" - data = { - "name": "all", - "IP": ACLManager.GetServerIP() - } - - import requests - response = requests.post(url, data=json.dumps(data)) - Status = response.json()['status'] - - test_domain_status = 0 - - if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: - test_domain_status = 1 - - currentACL = ACLManager.loadedACL(userID) - adminNames = ACLManager.loadAllUsers(userID) - packagesName = ACLManager.loadPackages(userID, currentACL) - phps = PHPManager.findPHPVersions() - - rnpss = randomPassword.generate_pass(10) - - Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps, 'Randam_String': rnpss.lower(), - 'test_domain_data': test_domain_status} - proc = httpProc(request, 'websiteFunctions/createWebsite.html', - Data, 'createWebsite') - return proc.render() - - def WPCreate(self, request=None, userID=None, data=None): - url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" - data = { - "name": "wp-manager", - "IP": ACLManager.GetServerIP() - } - - import requests - response = requests.post(url, data=json.dumps(data)) - Status = response.json()['status'] - - - if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: - currentACL = ACLManager.loadedACL(userID) - adminNames = ACLManager.loadAllUsers(userID) - packagesName = ACLManager.loadPackages(userID, currentACL) - - if len(packagesName) == 0: - packagesName = ['Default'] - - FinalVersions = [] - userobj = Administrator.objects.get(pk=userID) - counter = 0 - try: - import requests - WPVersions = json.loads(requests.get('https://api.wordpress.org/core/version-check/1.7/').text)[ - 'offers'] - - for versions in WPVersions: - if counter == 7: - break - if versions['current'] not in FinalVersions: - FinalVersions.append(versions['current']) - counter = counter + 1 - except: - FinalVersions = ['5.6', '5.5.3', '5.5.2'] - - Plugins = wpplugins.objects.filter(owner=userobj) - rnpss = randomPassword.generate_pass(10) - - ## - - test_domain_status = 1 - - Data = {'packageList': packagesName, "owernList": adminNames, 'WPVersions': FinalVersions, - 'Plugins': Plugins, 'Randam_String': rnpss.lower(), 'test_domain_data': test_domain_status} - proc = httpProc(request, 'websiteFunctions/WPCreate.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def ListWPSites(self, request=None, userID=None, DeleteID=None): - import json - currentACL = ACLManager.loadedACL(userID) - - admin = Administrator.objects.get(pk=userID) - data = {} - wp_sites = ACLManager.GetALLWPObjects(currentACL, userID) - data['wp'] = wp_sites - - try: - if DeleteID != None: - WPDelete = WPSites.objects.get(pk=DeleteID) - - if ACLManager.checkOwnership(WPDelete.owner.domain, admin, currentACL) == 1: - WPDelete.delete() - except BaseException as msg: - pass - - sites = [] - for site in data['wp']: - sites.append({ - 'id': site.id, - 'title': site.title, - 'url': site.FinalURL, - 'production_status': True - }) - - context = { - "wpsite": json.dumps(sites), - "status": 1, - "total_sites": len(sites), - "debug_info": json.dumps({ - "user_id": userID, - "is_admin": bool(currentACL.get('admin', 0)), - "wp_sites_count": wp_sites.count() - }) - } - - proc = httpProc(request, 'websiteFunctions/WPsitesList.html', context) - return proc.render() - - def WPHome(self, request=None, userID=None, WPid=None, DeleteID=None): - Data = {} - currentACL = ACLManager.loadedACL(userID) - WPobj = WPSites.objects.get(pk=WPid) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(WPobj.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - try: - - url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" - data = { - "name": "wp-manager", - "IP": ACLManager.GetServerIP() - } - - import requests - response = requests.post(url, data=json.dumps(data)) - Status = response.json()['status'] - - rnpss = randomPassword.generate_pass(10) - - Data['Randam_String'] = rnpss.lower() - - if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: - Data['wpsite'] = WPobj - Data['test_domain_data'] = 1 - - try: - DeleteID = request.GET.get('DeleteID', None) - - if DeleteID != None: - wstagingDelete = WPStaging.objects.get(pk=DeleteID, owner=WPobj) - wstagingDelete.delete() - - except BaseException as msg: - da = str(msg) - - proc = httpProc(request, 'websiteFunctions/WPsiteHome.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - except: - proc = httpProc(request, 'websiteFunctions/WPsiteHome.html', - Data, 'createDatabase') - return proc.render() - - def RestoreHome(self, request=None, userID=None, BackupID=None): - Data = {} - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.CheckForPremFeature('wp-manager'): - - Data['backupobj'] = WPSitesBackup.objects.get(pk=BackupID) - - if ACLManager.CheckIPBackupObjectOwner(currentACL, Data['backupobj'], admin) == 1: - pass - else: - return ACLManager.loadError() - - config = json.loads(Data['backupobj'].config) - Data['FileName'] = config['name'] - try: - Data['Backuptype'] = config['Backuptype'] - - if Data['Backuptype'] == 'DataBase Backup' or Data['Backuptype'] == 'Website Backup': - Data['WPsites'] = [WPSites.objects.get(pk=Data['backupobj'].WPSiteID)] - else: - Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) - - except: - Data['Backuptype'] = None - Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) - - proc = httpProc(request, 'websiteFunctions/WPRestoreHome.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def RemoteBackupConfig(self, request=None, userID=None, DeleteID=None): - Data = {} - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - try: - if DeleteID != None: - BackupconfigDelete = RemoteBackupConfig.objects.get(pk=DeleteID) - BackupconfigDelete.delete() - except: - pass - - if ACLManager.CheckForPremFeature('wp-manager'): - - Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) - allcon = RemoteBackupConfig.objects.all() - Data['backupconfigs'] = [] - for i in allcon: - configr = json.loads(i.config) - if i.configtype == "SFTP": - Data['backupconfigs'].append({ - 'id': i.pk, - 'Type': i.configtype, - 'HostName': configr['Hostname'], - 'Path': configr['Path'] - }) - elif i.configtype == "S3": - Provider = configr['Provider'] - if Provider == "Backblaze": - Data['backupconfigs'].append({ - 'id': i.pk, - 'Type': i.configtype, - 'HostName': Provider, - 'Path': configr['S3keyname'] - }) - else: - Data['backupconfigs'].append({ - 'id': i.pk, - 'Type': i.configtype, - 'HostName': Provider, - 'Path': configr['S3keyname'] - }) - - proc = httpProc(request, 'websiteFunctions/RemoteBackupConfig.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def BackupfileConfig(self, request=None, userID=None, RemoteConfigID=None, DeleteID=None): - Data = {} - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - Data['RemoteConfigID'] = RemoteConfigID - RemoteConfigobj = RemoteBackupConfig.objects.get(pk=RemoteConfigID) - try: - if DeleteID != None: - RemoteBackupConfigDelete = RemoteBackupSchedule.objects.get(pk=DeleteID) - RemoteBackupConfigDelete.delete() - except: - pass - - if ACLManager.CheckForPremFeature('wp-manager'): - Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) - allsechedule = RemoteBackupSchedule.objects.filter(RemoteBackupConfig=RemoteConfigobj) - Data['Backupschedule'] = [] - for i in allsechedule: - lastrun = i.lastrun - LastRun = time.strftime('%Y-%m-%d', time.localtime(float(lastrun))) - Data['Backupschedule'].append({ - 'id': i.pk, - 'Name': i.Name, - 'RemoteConfiguration': i.RemoteBackupConfig.configtype, - 'Retention': i.fileretention, - 'Frequency': i.timeintervel, - 'LastRun': LastRun - }) - proc = httpProc(request, 'websiteFunctions/BackupfileConfig.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def AddRemoteBackupsite(self, request=None, userID=None, RemoteScheduleID=None, DeleteSiteID=None): - Data = {} - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - Data['RemoteScheduleID'] = RemoteScheduleID - RemoteBackupScheduleobj = RemoteBackupSchedule.objects.get(pk=RemoteScheduleID) - - try: - if DeleteSiteID != None: - RemoteBackupsitesDelete = RemoteBackupsites.objects.get(pk=DeleteSiteID) - RemoteBackupsitesDelete.delete() - except: - pass - - if ACLManager.CheckForPremFeature('wp-manager'): - Data['WPsites'] = ACLManager.GetALLWPObjects(currentACL, userID) - allRemoteBackupsites = RemoteBackupsites.objects.filter(owner=RemoteBackupScheduleobj) - Data['RemoteBackupsites'] = [] - for i in allRemoteBackupsites: - try: - wpsite = WPSites.objects.get(pk=i.WPsites) - Data['RemoteBackupsites'].append({ - 'id': i.pk, - 'Title': wpsite.title, - }) - except: - pass - proc = httpProc(request, 'websiteFunctions/AddRemoteBackupSite.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def WordpressPricing(self, request=None, userID=None, ): - Data = {} - proc = httpProc(request, 'websiteFunctions/CyberpanelPricing.html', Data, 'createWebsite') - return proc.render() - - def RestoreBackups(self, request=None, userID=None, DeleteID=None): - Data = {} - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" - data = { - "name": "wp-manager", - "IP": ACLManager.GetServerIP() - } - - import requests - response = requests.post(url, data=json.dumps(data)) - Status = response.json()['status'] - - if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: - - backobj = WPSitesBackup.objects.filter(owner=admin).order_by('-id') - - # if ACLManager.CheckIPBackupObjectOwner(currentACL, backobj, admin) == 1: - # pass - # else: - # return ACLManager.loadError() - - try: - if DeleteID != None: - DeleteIDobj = WPSitesBackup.objects.get(pk=DeleteID) - - if ACLManager.CheckIPBackupObjectOwner(currentACL, DeleteIDobj, admin) == 1: - config = DeleteIDobj.config - conf = json.loads(config) - FileName = conf['name'] - command = "rm -r /home/backup/%s.tar.gz" % FileName - ProcessUtilities.executioner(command) - DeleteIDobj.delete() - - except BaseException as msg: - pass - Data['job'] = [] - - for sub in backobj: - try: - wpsite = WPSites.objects.get(pk=sub.WPSiteID) - web = wpsite.title - except: - web = "Website Not Found" - - try: - config = sub.config - conf = json.loads(config) - Backuptype = conf['Backuptype'] - BackupDestination = conf['BackupDestination'] - except: - Backuptype = "Backup type not exists" - - Data['job'].append({ - 'id': sub.id, - 'title': web, - 'Backuptype': Backuptype, - 'BackupDestination': BackupDestination - }) - - proc = httpProc(request, 'websiteFunctions/RestoreBackups.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def AutoLogin(self, request=None, userID=None): - - WPid = request.GET.get('id') - currentACL = ACLManager.loadedACL(userID) - WPobj = WPSites.objects.get(pk=WPid) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(WPobj.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - from managePHP.phpManager import PHPManager - - php = PHPManager.getPHPString(WPobj.owner.phpSelection) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" - data = { - "name": "wp-manager", - "IP": ACLManager.GetServerIP() - } - - import requests - response = requests.post(url, data=json.dumps(data)) - Status = response.json()['status'] - - if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: - - ## Get title - - password = randomPassword.generate_pass(10) - - command = f'sudo -u %s {FinalPHPPath} /usr/bin/wp user create autologin %s --role=administrator --user_pass="%s" --path=%s --skip-plugins --skip-themes' % ( - WPobj.owner.externalApp, 'autologin@cloudpages.cloud', password, WPobj.path) - ProcessUtilities.executioner(command) - - command = f'sudo -u %s {FinalPHPPath} /usr/bin/wp user update autologin --user_pass="%s" --path=%s --skip-plugins --skip-themes' % ( - WPobj.owner.externalApp, password, WPobj.path) - ProcessUtilities.executioner(command) - - data = {} - - if WPobj.FinalURL.endswith('/'): - FinalURL = WPobj.FinalURL[:-1] - else: - FinalURL = WPobj.FinalURL - - data['url'] = 'https://%s' % (FinalURL) - data['userName'] = 'autologin' - data['password'] = password - - proc = httpProc(request, 'websiteFunctions/AutoLogin.html', - data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def ConfigurePlugins(self, request=None, userID=None, data=None): - - if ACLManager.CheckForPremFeature('wp-manager'): - currentACL = ACLManager.loadedACL(userID) - userobj = Administrator.objects.get(pk=userID) - - Selectedplugins = wpplugins.objects.filter(owner=userobj) - # data['Selectedplugins'] = wpplugins.objects.filter(ProjectOwner=HostingCompany) - - Data = {'Selectedplugins': Selectedplugins, } - proc = httpProc(request, 'websiteFunctions/WPConfigurePlugins.html', - Data, 'createDatabase') - return proc.render() - else: - from django.shortcuts import reverse - return redirect(reverse('pricing')) - - def Addnewplugin(self, request=None, userID=None, data=None): - from django.shortcuts import reverse - if ACLManager.CheckForPremFeature('wp-manager'): - currentACL = ACLManager.loadedACL(userID) - adminNames = ACLManager.loadAllUsers(userID) - packagesName = ACLManager.loadPackages(userID, currentACL) - phps = PHPManager.findPHPVersions() - - Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps} - proc = httpProc(request, 'websiteFunctions/WPAddNewPlugin.html', - Data, 'createDatabase') - return proc.render() - - return redirect(reverse('pricing')) - - def SearchOnkeyupPlugin(self, userID=None, data=None): - try: - if ACLManager.CheckForPremFeature('wp-manager'): - currentACL = ACLManager.loadedACL(userID) - - pluginname = data['pluginname'] - # logging.CyberCPLogFileWriter.writeToFile("Plugin Name ....... %s"%pluginname) - - url = "http://api.wordpress.org/plugins/info/1.1/?action=query_plugins&request[search]=%s" % str( - pluginname) - import requests - - res = requests.get(url) - r = res.json() - - # return proc.ajax(1, 'Done', {'plugins': r}) - - data_ret = {'status': 1, 'plugns': r, } - - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': 'Premium feature not available.'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def AddNewpluginAjax(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - - userobj = Administrator.objects.get(pk=userID) - - config = data['config'] - Name = data['Name'] - # pluginname = data['pluginname'] - # logging.CyberCPLogFileWriter.writeToFile("config ....... %s"%config) - # logging.CyberCPLogFileWriter.writeToFile(" Name ....... %s"%Name) - - addpl = wpplugins(Name=Name, config=json.dumps(config), owner=userobj) - addpl.save() - - data_ret = {'status': 1} - - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'AddNewpluginAjax': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def EidtPlugin(self, request=None, userID=None, pluginbID=None): - Data = {} - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - pluginobj = wpplugins.objects.get(pk=pluginbID) - - if ACLManager.CheckIPPluginObjectOwner(currentACL, pluginobj, admin) == 1: - pass - else: - return ACLManager.loadError() - - lmo = json.loads(pluginobj.config) - Data['Selectedplugins'] = lmo - Data['pluginbID'] = pluginbID - Data['BucketName'] = pluginobj.Name - - proc = httpProc(request, 'websiteFunctions/WPEidtPlugin.html', - Data, 'createDatabase') - return proc.render() - - def deletesPlgin(self, userID=None, data=None, ): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - userobj = Administrator.objects.get(pk=userID) - pluginname = data['pluginname'] - pluginbBucketID = data['pluginbBucketID'] - # logging.CyberCPLogFileWriter.writeToFile("pluginbID ....... %s" % pluginbBucketID) - # logging.CyberCPLogFileWriter.writeToFile("pluginname ....... %s" % pluginname) - - obj = wpplugins.objects.get(pk=pluginbBucketID, owner=userobj) - - if ACLManager.CheckIPPluginObjectOwner(currentACL, obj, admin) == 1: - pass - else: - return ACLManager.loadError() - - ab = [] - ab = json.loads(obj.config) - ab.remove(pluginname) - obj.config = json.dumps(ab) - obj.save() - - data_ret = {'status': 1} - - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except BaseException as msg: - data_ret = {'status': 0, 'deletesPlgin': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def Addplugineidt(self, userID=None, data=None, ): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - userobj = Administrator.objects.get(pk=userID) - pluginname = data['pluginname'] - pluginbBucketID = data['pluginbBucketID'] - - # logging.CyberCPLogFileWriter.writeToFile("pluginbID ....... %s" % pluginbBucketID) - # logging.CyberCPLogFileWriter.writeToFile("pluginname ....... %s" % pluginname) - - pObj = wpplugins.objects.get(pk=pluginbBucketID, owner=userobj) - - if ACLManager.CheckIPPluginObjectOwner(currentACL, pObj, admin) == 1: - pass - else: - return ACLManager.loadError() - - listofplugin = json.loads(pObj.config) - try: - index = listofplugin.index(pluginname) - print('index.....%s' % index) - if (index >= 0): - data_ret = {'status': 0, 'deletesPlgin': 0, 'error_message': str('Already Save in your Plugin lis')} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except: - ab = [] - ab = json.loads(pObj.config) - ab.append(pluginname) - pObj.config = json.dumps(ab) - pObj.save() - - data_ret = {'status': 1} - - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except BaseException as msg: - data_ret = {'status': 0, 'deletesPlgin': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def modifyWebsite(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - - websitesName = ACLManager.findAllSites(currentACL, userID) - phps = PHPManager.findPHPVersions() - proc = httpProc(request, 'websiteFunctions/modifyWebsite.html', - {'websiteList': websitesName, 'phps': phps}, 'modifyWebsite') - return proc.render() - - def deleteWebsite(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - websitesName = ACLManager.findAllSites(currentACL, userID) - proc = httpProc(request, 'websiteFunctions/deleteWebsite.html', - {'websiteList': websitesName}, 'deleteWebsite') - return proc.render() - - def CreateNewDomain(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - websitesName = ACLManager.findAllSites(currentACL, userID) - - try: - admin = Administrator.objects.get(pk=userID) - if admin.defaultSite == 0: - websites = ACLManager.findWebsiteObjects(currentACL, userID) - admin.defaultSite = websites[0].id - admin.save() - except: - pass - - try: - admin = Administrator.objects.get(pk=userID) - defaultDomain = Websites.objects.get(pk=admin.defaultSite).domain - except: - try: - admin = Administrator.objects.get(pk=userID) - websites = ACLManager.findWebsiteObjects(currentACL, userID) - admin.defaultSite = websites[0].id - admin.save() - defaultDomain = websites[0].domain - except: - defaultDomain='NONE' - - - url = "https://platform.cyberpersons.com/CyberpanelAdOns/Adonpermission" - data = { - "name": "all", - "IP": ACLManager.GetServerIP() - } - - import requests - response = requests.post(url, data=json.dumps(data)) - Status = response.json()['status'] - - test_domain_status = 0 - - if (Status == 1) or ProcessUtilities.decideServer() == ProcessUtilities.ent: - test_domain_status = 1 - - rnpss = randomPassword.generate_pass(10) - proc = httpProc(request, 'websiteFunctions/createDomain.html', - {'websiteList': websitesName, 'phps': PHPManager.findPHPVersions(), 'Randam_String': rnpss, - 'test_domain_data': test_domain_status, 'defaultSite': defaultDomain}) - return proc.render() - - def siteState(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - - websitesName = ACLManager.findAllSites(currentACL, userID) - - proc = httpProc(request, 'websiteFunctions/suspendWebsite.html', - {'websiteList': websitesName}, 'suspendWebsite') - return proc.render() - - def listWebsites(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - pagination = self.websitePagination(currentACL, userID) - proc = httpProc(request, 'websiteFunctions/listWebsites.html', - {"pagination": pagination}) - return proc.render() - - def listChildDomains(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - adminNames = ACLManager.loadAllUsers(userID) - packagesName = ACLManager.loadPackages(userID, currentACL) - phps = PHPManager.findPHPVersions() - - Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps} - proc = httpProc(request, 'websiteFunctions/listChildDomains.html', - Data) - return proc.render() - - def listCron(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(request.GET.get('domain'), admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - proc = httpProc(request, 'websiteFunctions/listCron.html', - {'domain': request.GET.get('domain')}) - return proc.render() - - def domainAlias(self, request=None, userID=None, data=None): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - aliasManager = AliasManager(self.domain) - noAlias, finalAlisList = aliasManager.fetchAlisForDomains() - - path = "/home/" + self.domain + "/public_html" - - proc = httpProc(request, 'websiteFunctions/domainAlias.html', { - 'masterDomain': self.domain, - 'aliases': finalAlisList, - 'path': path, - 'noAlias': noAlias - }) - return proc.render() - - def FetchWPdata(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core version --skip-plugins --skip-themes --path=%s 2>/dev/null' % ( - Vhuser, FinalPHPPath, path) - version = ProcessUtilities.outputExecutioner(command, None, True) - version = html.escape(version) - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin status litespeed-cache --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, path) - lscachee = ProcessUtilities.outputExecutioner(command) - - if lscachee.find('Status: Active') > -1: - lscache = 1 - else: - lscache = 0 - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp config list --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, path) - stdout = ProcessUtilities.outputExecutioner(command) - debugging = 0 - for items in stdout.split('\n'): - if items.find('WP_DEBUG true constant') > -1: - debugging = 1 - break - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp option get blog_public --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, path) - stdoutput = ProcessUtilities.outputExecutioner(command) - searchindex = int(stdoutput.splitlines()[-1]) - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp maintenance-mode status --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, path) - maintenanceMod = ProcessUtilities.outputExecutioner(command) - - result = maintenanceMod.splitlines()[-1] - if result.find('not active') > -1: - maintenanceMode = 0 - else: - maintenanceMode = 1 - - ##### Check passwd protection - vhostName = wpsite.owner.domain - vhostPassDir = f'/home/{vhostName}' - path = f'{vhostPassDir}/{WPManagerID}' - if os.path.exists(path): - passwd = 1 - else: - passwd = 0 - - #### Check WP cron - command = "sudo -u %s cat %s/wp-config.php" % (Vhuser, wpsite.path) - stdout = ProcessUtilities.outputExecutioner(command) - if stdout.find("'DISABLE_WP_CRON', 'true'") > -1: - wpcron = 1 - else: - wpcron = 0 - - fb = { - 'version': version.rstrip('\n'), - 'lscache': lscache, - 'debugging': debugging, - 'searchIndex': searchindex, - 'maintenanceMode': maintenanceMode, - 'passwordprotection': passwd, - 'wpcron': wpcron - - } - - data_ret = {'status': 1, 'error_message': 'None', 'ret_data': fb} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def GetCurrentPlugins(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin list --skip-plugins --skip-themes --format=json --path=%s' % ( - Vhuser, FinalPHPPath, path) - stdoutput = ProcessUtilities.outputExecutioner(command) - json_data = stdoutput.splitlines()[-1] - - data_ret = {'status': 1, 'error_message': 'None', 'plugins': json_data} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def GetCurrentThemes(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp theme list --skip-plugins --skip-themes --format=json --path=%s' % ( - Vhuser, FinalPHPPath, path) - stdoutput = ProcessUtilities.outputExecutioner(command) - json_data = stdoutput.splitlines()[-1] - - data_ret = {'status': 1, 'error_message': 'None', 'themes': json_data} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def fetchstaging(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - from plogical.phpUtilities import phpUtilities - - json_data = phpUtilities.GetStagingInJson(wpsite.wpstaging_set.all().order_by('-id')) - - data_ret = {'status': 1, 'error_message': 'None', 'wpsites': json_data} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def fetchDatabase(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - php = PHPManager.getPHPString(wpsite.owner.phpSelection) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - command = f'{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config get DB_NAME --skip-plugins --skip-themes --path={wpsite.path} 2>/dev/null' - retStatus, stdoutput = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp, True, None, 1) - - if stdoutput.find('Error:') == -1: - DataBaseName = stdoutput.rstrip("\n") - DataBaseName = html.escape(DataBaseName) - else: - data_ret = {'status': 0, 'error_message': stdoutput} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - command = f'{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config get DB_USER --skip-plugins --skip-themes --path={wpsite.path} 2>/dev/null' - retStatus, stdoutput = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp, True, None, 1) - - if stdoutput.find('Error:') == -1: - DataBaseUser = stdoutput.rstrip("\n") - DataBaseUser = html.escape(DataBaseUser) - else: - data_ret = {'status': 0, 'error_message': stdoutput} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - command = f'{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config get table_prefix --skip-plugins --skip-themes --path={wpsite.path} 2>/dev/null' - retStatus, stdoutput = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp, True, None, 1) - - if stdoutput.find('Error:') == -1: - tableprefix = stdoutput.rstrip("\n") - tableprefix = html.escape(tableprefix) - else: - data_ret = {'status': 0, 'error_message': stdoutput} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - data_ret = {'status': 1, 'error_message': 'None', "DataBaseUser": DataBaseUser, - "DataBaseName": DataBaseName, 'tableprefix': tableprefix} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def SaveUpdateConfig(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - Plugins = data['Plugins'] - Themes = data['Themes'] - AutomaticUpdates = data['AutomaticUpdates'] - - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - - php = PHPManager.getPHPString(wpsite.owner.phpSelection) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - if AutomaticUpdates == 'Disabled': - command = f"{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_AUTO_UPDATE_CORE false --raw --allow-root --path=" + wpsite.path - result = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp) - - if result.find('Success:') == -1: - raise BaseException(result) - elif AutomaticUpdates == 'Minor and Security Updates': - command = f"{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_AUTO_UPDATE_CORE minor --allow-root --path=" + wpsite.path - result = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp) - - if result.find('Success:') == -1: - raise BaseException(result) - else: - command = f"{FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_AUTO_UPDATE_CORE true --raw --allow-root --path=" + wpsite.path - result = ProcessUtilities.outputExecutioner(command, wpsite.owner.externalApp) - - if result.find('Success:') == -1: - raise BaseException(result) - - wpsite.AutoUpdates = AutomaticUpdates - wpsite.PluginUpdates = Plugins - wpsite.ThemeUpdates = Themes - wpsite.save() - - data_ret = {'status': 1, 'error_message': 'None', } - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def DeploytoProduction(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - statgingID = data['StagingID'] - wpsite = WPSites.objects.get(pk=WPManagerID) - StagingObj = WPSites.objects.get(pk=statgingID) - - ### - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - if ACLManager.checkOwnership(StagingObj.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - ### - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['statgingID'] = statgingID - extraArgs['WPid'] = WPManagerID - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - background = ApplicationInstaller('DeploytoProduction', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def WPCreateBackup(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - Backuptype = data['Backuptype'] - - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['WPid'] = WPManagerID - extraArgs['Backuptype'] = Backuptype - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - background = ApplicationInstaller('WPCreateBackup', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def RestoreWPbackupNow(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - backupid = data['backupid'] - DesSiteID = data['DesSite'] - - # try: - # - # bwp = WPSites.objects.get(pk=int(backupid)) - # - # if ACLManager.checkOwnership(bwp.owner.domain, admin, currentACL) == 1: - # pass - # else: - # return ACLManager.loadError() - # - # except: - # pass - # - # dwp = WPSites.objects.get(pk=int(DesSiteID)) - # if ACLManager.checkOwnership(dwp.owner.domain, admin, currentACL) == 1: - # pass - # else: - # return ACLManager.loadError() - - Domain = data['Domain'] - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['backupid'] = backupid - extraArgs['DesSiteID'] = DesSiteID - extraArgs['Domain'] = Domain - extraArgs['path'] = data['path'] - extraArgs['home'] = data['home'] - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - background = ApplicationInstaller('RestoreWPbackupNow', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def SaveBackupConfig(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - ConfigType = data['type'] - if ConfigType == 'SFTP': - Hname = data['Hname'] - Uname = data['Uname'] - Passwd = data['Passwd'] - path = data['path'] - config = { - "Hostname": Hname, - "Username": Uname, - "Password": Passwd, - "Path": path - } - elif ConfigType == "S3": - Provider = data['Provider'] - if Provider == "Backblaze": - S3keyname = data['S3keyname'] - SecertKey = data['SecertKey'] - AccessKey = data['AccessKey'] - EndUrl = data['EndUrl'] - config = { - "Provider": Provider, - "S3keyname": S3keyname, - "SecertKey": SecertKey, - "AccessKey": AccessKey, - "EndUrl": EndUrl - - } - else: - S3keyname = data['S3keyname'] - SecertKey = data['SecertKey'] - AccessKey = data['AccessKey'] - config = { - "Provider": Provider, - "S3keyname": S3keyname, - "SecertKey": SecertKey, - "AccessKey": AccessKey, - - } - - mkobj = RemoteBackupConfig(owner=admin, configtype=ConfigType, config=json.dumps(config)) - mkobj.save() - - time.sleep(1) - - data_ret = {'status': 1, 'error_message': 'None', } - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def SaveBackupSchedule(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - FileRetention = data['FileRetention'] - Backfrequency = data['Backfrequency'] - ScheduleName = data['ScheduleName'] - RemoteConfigID = data['RemoteConfigID'] - BackupType = data['BackupType'] - - RemoteBackupConfigobj = RemoteBackupConfig.objects.get(pk=RemoteConfigID) - Rconfig = json.loads(RemoteBackupConfigobj.config) - - try: - # This code is only supposed to run if backups are s3, not for SFTP - provider = Rconfig['Provider'] - if provider == "Backblaze": - EndURl = Rconfig['EndUrl'] - elif provider == "Amazon": - EndURl = "https://s3.us-east-1.amazonaws.com" - elif provider == "Wasabi": - EndURl = "https://s3.wasabisys.com" - - AccessKey = Rconfig['AccessKey'] - SecertKey = Rconfig['SecertKey'] - - session = boto3.session.Session() - - client = session.client( - 's3', - endpoint_url=EndURl, - aws_access_key_id=AccessKey, - aws_secret_access_key=SecertKey, - verify=False - ) - - ############Creating Bucket - BucketName = randomPassword.generate_pass().lower() - - try: - client.create_bucket(Bucket=BucketName) - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile("Creating Bucket Error: %s" % str(msg)) - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - config = { - 'BackupType': BackupType, - 'BucketName': BucketName - } - except BaseException as msg: - config = {'BackupType': BackupType} - pass - - svobj = RemoteBackupSchedule(RemoteBackupConfig=RemoteBackupConfigobj, Name=ScheduleName, - timeintervel=Backfrequency, fileretention=FileRetention, - config=json.dumps(config), - lastrun=str(time.time())) - svobj.save() - - data_ret = {'status': 1, 'error_message': 'None', } - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def AddWPsiteforRemoteBackup(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - WPid = data['WpsiteID'] - RemoteScheduleID = data['RemoteScheduleID'] - - wpsiteobj = WPSites.objects.get(pk=WPid) - WPpath = wpsiteobj.path - VHuser = wpsiteobj.owner.externalApp - PhpVersion = wpsiteobj.owner.phpSelection - php = PHPManager.getPHPString(PhpVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - ####Get DB Name - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp config get DB_NAME --skip-plugins --skip-themes --path=%s' % ( - VHuser, FinalPHPPath, WPpath) - result, stdout = ProcessUtilities.outputExecutioner(command, None, None, None, 1) - - if stdout.find('Error:') > -1: - raise BaseException(stdout) - else: - Finaldbname = stdout.rstrip("\n") - - ## Get DB obj - try: - DBobj = Databases.objects.get(dbName=Finaldbname) - except: - raise BaseException(str("DataBase Not Found")) - RemoteScheduleIDobj = RemoteBackupSchedule.objects.get(pk=RemoteScheduleID) - - svobj = RemoteBackupsites(owner=RemoteScheduleIDobj, WPsites=WPid, database=DBobj.pk) - svobj.save() - - data_ret = {'status': 1, 'error_message': 'None', } - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def UpdateRemoteschedules(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - ScheduleID = data['ScheduleID'] - Frequency = data['Frequency'] - FileRetention = data['FileRetention'] - - scheduleobj = RemoteBackupSchedule.objects.get(pk=ScheduleID) - scheduleobj.timeintervel = Frequency - scheduleobj.fileretention = FileRetention - scheduleobj.save() - - data_ret = {'status': 1, 'error_message': 'None', } - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def ScanWordpressSite(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - allweb = Websites.objects.all() - - childdomain = ChildDomains.objects.all() - - for web in allweb: - webpath = "/home/%s/public_html/" % web.domain - command = "cat %swp-config.php" % webpath - result = ProcessUtilities.outputExecutioner(command, web.externalApp) - - if os.path.exists(ProcessUtilities.debugPath): - logging.CyberCPLogFileWriter.writeToFile(result) - - if result.find('No such file or directory') == -1: - try: - WPSites.objects.get(path=webpath) - except: - wpobj = WPSites(owner=web, title=web.domain, path=webpath, FinalURL=web.domain, - AutoUpdates="Enabled", PluginUpdates="Enabled", - ThemeUpdates="Enabled", ) - wpobj.save() - - for chlid in childdomain: - childPath = chlid.path.rstrip('/') - - command = "cat %s/wp-config.php" % childPath - result = ProcessUtilities.outputExecutioner(command, chlid.master.externalApp) - - if os.path.exists(ProcessUtilities.debugPath): - logging.CyberCPLogFileWriter.writeToFile(result) - - if result.find('No such file or directory') == -1: - fChildPath = f'{childPath}/' - try: - WPSites.objects.get(path=fChildPath) - except: - - wpobj = WPSites(owner=chlid.master, title=chlid.domain, path=fChildPath, FinalURL=chlid.domain, - AutoUpdates="Enabled", PluginUpdates="Enabled", - ThemeUpdates="Enabled", ) - wpobj.save() - - data_ret = {'status': 1, 'error_message': 'None', } - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def installwpcore(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - ###fetch WP version - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core version --skip-plugins --skip-themes --path=%s 2>/dev/null' % ( - Vhuser, FinalPHPPath, path) - version = ProcessUtilities.outputExecutioner(command, None, True) - version = version.rstrip("\n") - - ###install wp core - command = f"sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp core download --force --skip-content --version={version} --path={path}" - output = ProcessUtilities.outputExecutioner(command) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', 'result': output} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def dataintegrity(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - ###fetch WP version - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core verify-checksums --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, path) - result = ProcessUtilities.outputExecutioner(command) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', 'result': result} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def UpdatePlugins(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - plugin = data['plugin'] - pluginarray = data['pluginarray'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['plugin'] = plugin - extraArgs['pluginarray'] = pluginarray - extraArgs['FinalPHPPath'] = FinalPHPPath - extraArgs['path'] = path - extraArgs['Vhuser'] = Vhuser - - background = ApplicationInstaller('UpdateWPPlugin', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def UpdateThemes(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - Theme = data['Theme'] - Themearray = data['Themearray'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['Theme'] = Theme - extraArgs['Themearray'] = Themearray - extraArgs['FinalPHPPath'] = FinalPHPPath - extraArgs['path'] = path - extraArgs['Vhuser'] = Vhuser - - background = ApplicationInstaller('UpdateWPTheme', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def DeletePlugins(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - plugin = data['plugin'] - pluginarray = data['pluginarray'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['plugin'] = plugin - extraArgs['pluginarray'] = pluginarray - extraArgs['FinalPHPPath'] = FinalPHPPath - extraArgs['path'] = path - extraArgs['Vhuser'] = Vhuser - - background = ApplicationInstaller('DeletePlugins', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def DeleteThemes(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - Theme = data['Theme'] - Themearray = data['Themearray'] - wpsite = WPSites.objects.get(pk=WPManagerID) - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['Theme'] = Theme - extraArgs['Themearray'] = Themearray - extraArgs['FinalPHPPath'] = FinalPHPPath - extraArgs['path'] = path - extraArgs['Vhuser'] = Vhuser - - background = ApplicationInstaller('DeleteThemes', extraArgs) - background.start() - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def ChangeStatus(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - plugin = data['plugin'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin status %s --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, plugin, path) - stdoutput = ProcessUtilities.outputExecutioner(command) - - if stdoutput.find('Status: Active') > -1: - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin deactivate %s --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, plugin, path) - stdoutput = ProcessUtilities.outputExecutioner(command) - time.sleep(3) - - else: - - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp plugin activate %s --skip-plugins --skip-themes --path=%s' % ( - Vhuser, FinalPHPPath, plugin, path) - stdoutput = ProcessUtilities.outputExecutioner(command) - time.sleep(3) - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def ChangeStatusThemes(self, userID=None, data=None): - try: - # logging.CyberCPLogFileWriter.writeToFile("Error WP ChangeStatusThemes ....... %s") - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - WPManagerID = data['WPid'] - Theme = data['theme'] - wpsite = WPSites.objects.get(pk=WPManagerID) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - path = wpsite.path - - Webobj = Websites.objects.get(pk=wpsite.owner_id) - - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['Theme'] = Theme - extraArgs['FinalPHPPath'] = FinalPHPPath - extraArgs['path'] = path - extraArgs['Vhuser'] = Vhuser - - background = ApplicationInstaller('ChangeStatusThemes', extraArgs) - background.start() - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def CreateStagingNow(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - extraArgs = {} - extraArgs['adminID'] = admin.pk - extraArgs['StagingDomain'] = data['StagingDomain'] - extraArgs['StagingName'] = data['StagingName'] - extraArgs['WPid'] = data['WPid'] - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - wpsite = WPSites.objects.get(pk=data['WPid']) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - background = ApplicationInstaller('CreateStagingNow', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def UpdateWPSettings(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - siteId = data['siteId'] - setting = data['setting'] - value = data['value'] - - wpsite = WPSites.objects.get(pk=siteId) - - if ACLManager.checkOwnership(wpsite.owner.domain, admin, currentACL) != 1: - return ACLManager.loadError() - - # Get PHP version and path - Webobj = Websites.objects.get(pk=wpsite.owner_id) - Vhuser = Webobj.externalApp - PHPVersion = Webobj.phpSelection - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - - # Update the appropriate setting based on the setting type - if setting == 'search-indexing': - # Update search engine indexing - command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp option update blog_public {value} --skip-plugins --skip-themes --path={wpsite.path}' - elif setting == 'debugging': - # Update debugging in wp-config.php - if value: - command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_DEBUG true --raw --skip-plugins --skip-themes --path={wpsite.path}' - else: - command = f'sudo -u {Vhuser} {FinalPHPPath} -d error_reporting=0 /usr/bin/wp config set WP_DEBUG false --raw --skip-plugins --skip-themes --path={wpsite.path}' - elif setting == 'password-protection': - vhostName = wpsite.owner.domain - vhostPassDir = f'/home/{vhostName}' - path = f'{vhostPassDir}/{siteId}' - if value: - # Enable password protection - if not os.path.exists(path): - os.makedirs(path) - htpasswd = f'{path}/.htpasswd' - htaccess = f'{wpsite.path}/.htaccess' - password = randomPassword.generate_pass(12) - - # Create .htpasswd file - command = f"htpasswd -cb {htpasswd} admin {password}" - ProcessUtilities.executioner(command) - - # Create .htaccess file - htaccess_content = f"""AuthType Basic -AuthName "Restricted Access" -AuthUserFile {htpasswd} Require valid-user""" with open(htaccess, 'w') as f: f.write(htaccess_content) @@ -14938,53 +7074,6 @@ StrictHostKeyChecking no php = ACLManager.getPHPString(PHPVersion) FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - for site in wp_sites: - command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core version --skip-plugins --skip-themes --path=%s 2>/dev/null' % ( - Vhuser, FinalPHPPath, site.path) - version = ProcessUtilities.outputExecutioner(command, None, True) - version = html.escape(version) - - # Generate screenshot URL - site_url = site.FinalURL - if not site_url.startswith(('http://', 'https://')): - site_url = f'https://{site_url}' - - sites.append({ - 'id': site.id, - 'title': site.title, - 'url': site.FinalURL, - 'path': site.path, - 'version': version, - 'screenshot': f'https://api.microlink.io/?url={site_url}&screenshot=true&meta=false&embed=screenshot.url' - }) - - data_ret = {'status': 1, 'fetchStatus': 1, 'error_message': "None", "sites": sites} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'fetchStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - domain = data['domain'] - website = Websites.objects.get(domain=domain) - - if ACLManager.checkOwnership(domain, admin, currentACL) != 1: - return ACLManager.loadErrorJson('fetchStatus', 0) - - wp_sites = WPSites.objects.filter(owner=website) - sites = [] - - Vhuser = website.externalApp - PHPVersion = website.phpSelection - - php = ACLManager.getPHPString(PHPVersion) - FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) - for site in wp_sites: command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core version --skip-plugins --skip-themes --path=%s 2>/dev/null' % ( From 22141dc4573cdaa8e91126a88e2bfaa255b0bb88 Mon Sep 17 00:00:00 2001 From: usmannasir Date: Sat, 5 Apr 2025 00:52:33 +0500 Subject: [PATCH 024/273] update code to add design from main wp page --- websiteFunctions/website.py | 51 +++++++++++++++++++++++++++++++++++-- 1 file changed, 49 insertions(+), 2 deletions(-) diff --git a/websiteFunctions/website.py b/websiteFunctions/website.py index 280191367..d023fa1e6 100755 --- a/websiteFunctions/website.py +++ b/websiteFunctions/website.py @@ -7053,8 +7053,6 @@ StrictHostKeyChecking no proc = httpProc(request, 'websiteFunctions/DockerSiteHome.html', {'dockerSite': ds}) return proc.render() - - def fetchWPSitesForDomain(self, userID=None, data=None): try: currentACL = ACLManager.loadedACL(userID) admin = Administrator.objects.get(pk=userID) @@ -7098,3 +7096,52 @@ StrictHostKeyChecking no data_ret = {'status': 0, 'fetchStatus': 0, 'error_message': str(msg)} json_data = json.dumps(data_ret) return HttpResponse(json_data) + + def fetchWPSitesForDomain(self, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + domain = data['domain'] + website = Websites.objects.get(domain=domain) + + if ACLManager.checkOwnership(domain, admin, currentACL) != 1: + return ACLManager.loadErrorJson('fetchStatus', 0) + + wp_sites = WPSites.objects.filter(owner=website) + sites = [] + + Vhuser = website.externalApp + PHPVersion = website.phpSelection + + php = ACLManager.getPHPString(PHPVersion) + FinalPHPPath = '/usr/local/lsws/lsphp%s/bin/php' % (php) + + for site in wp_sites: + command = 'sudo -u %s %s -d error_reporting=0 /usr/bin/wp core version --skip-plugins --skip-themes --path=%s 2>/dev/null' % ( + Vhuser, FinalPHPPath, site.path) + version = ProcessUtilities.outputExecutioner(command, None, True) + version = html.escape(version) + + # Generate screenshot URL + site_url = site.FinalURL + if not site_url.startswith(('http://', 'https://')): + site_url = f'https://{site_url}' + + sites.append({ + 'id': site.id, + 'title': site.title, + 'url': site.FinalURL, + 'path': site.path, + 'version': version, + 'screenshot': f'https://api.microlink.io/?url={site_url}&screenshot=true&meta=false&embed=screenshot.url' + }) + + data_ret = {'status': 1, 'fetchStatus': 1, 'error_message': "None", "sites": sites} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException as msg: + data_ret = {'status': 0, 'fetchStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) From 900aadeec2c8dbf85192594be2a9a4858dd543c0 Mon Sep 17 00:00:00 2001 From: usmannasir Date: Sat, 5 Apr 2025 00:59:17 +0500 Subject: [PATCH 025/273] update code to add design from main wp page --- websiteFunctions/templates/websiteFunctions/listWebsites.html | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/websiteFunctions/templates/websiteFunctions/listWebsites.html b/websiteFunctions/templates/websiteFunctions/listWebsites.html index 60cfa4866..353320276 100755 --- a/websiteFunctions/templates/websiteFunctions/listWebsites.html +++ b/websiteFunctions/templates/websiteFunctions/listWebsites.html @@ -134,10 +134,10 @@
    - {$ wp.title $} -
    +
    -

    {$ wp.title $}

    +

    {$ wp.title $}

    + +
    + + +
    +
    +
    +
    @@ -196,7 +227,7 @@
    From a25f04b42b1e098422d60cad4ee34c278407f3b0 Mon Sep 17 00:00:00 2001 From: usmannasir Date: Sat, 5 Apr 2025 21:15:17 +0500 Subject: [PATCH 033/273] fix some issues with pp --- .../websiteFunctions/websiteFunctions.js | 6617 ++++++++++++++++- 1 file changed, 6441 insertions(+), 176 deletions(-) diff --git a/websiteFunctions/static/websiteFunctions/websiteFunctions.js b/websiteFunctions/static/websiteFunctions/websiteFunctions.js index d8e82a0a0..35e3fcb4a 100755 --- a/websiteFunctions/static/websiteFunctions/websiteFunctions.js +++ b/websiteFunctions/static/websiteFunctions/websiteFunctions.js @@ -2455,7 +2455,6 @@ app.controller('createWebsite', function ($scope, $http, $timeout, $window) { mailDomain = 0 } - url = "/websites/submitWebsiteCreation"; var package = $scope.packageForWebsite; @@ -2734,56 +2733,81 @@ app.controller('listWebsites', function ($scope, $http, $window) { window.location.href = '/websites/listWPsites?wpID=' + wpId; }; - $scope.updateSetting = function(wp, setting) { - var settingMap = { - 'search-indexing': 'searchIndex', - 'debugging': 'debugging', - 'password-protection': 'passwordProtection', - 'maintenance-mode': 'maintenanceMode' - }; + $scope.currentWP = null; + $scope.PPUsername = ''; + $scope.PPPassword = ''; + $scope.togglePasswordProtection = function(wp) { + if (!wp.passwordProtection) { + // Show password protection modal + $('#Passwordprotection').modal('show'); + $scope.currentWP = wp; + } else { + // Disable password protection + $scope.updateSetting(wp, 'password-protection', 0); + } + }; + + $scope.enablePasswordProtection = function() { + if (!$scope.PPUsername || !$scope.PPPassword) { + new PNotify({ + title: 'Error!', + text: 'Username and password are required.', + type: 'error' + }); + return; + } + + $scope.updateSetting($scope.currentWP, 'password-protection', 1); + $('#Passwordprotection').modal('hide'); + }; + + $scope.updateSetting = function(wp, setting, value) { var data = { - wpID: wp.id, + WPid: wp.id, setting: setting, - value: wp[settingMap[setting]] ? 'enable' : 'disable' + value: value }; - $http({ - method: 'POST', - url: '/websites/UpdateWPSettings', - data: data, + if (setting === 'password-protection' && value === 1) { + data.PPUsername = $scope.PPUsername; + data.PPPassword = $scope.PPPassword; + } + + var config = { headers: { - 'Content-Type': 'application/x-www-form-urlencoded', 'X-CSRFToken': getCookie('csrftoken') - }, - transformRequest: function(obj) { - var str = []; - for(var p in obj) - str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); - return str.join("&"); } - }).then(function(response) { + }; + + $http.post('/websites/UpdateWPSettings', data, config).then(function(response) { if (response.data.status === 1) { new PNotify({ - title: 'Success', + title: 'Success!', text: 'Setting updated successfully.', type: 'success' }); + if (setting === 'password-protection') { + wp.passwordProtection = value; + // Reset form + $scope.PPUsername = ''; + $scope.PPPassword = ''; + $scope.currentWP = null; + } } else { - wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change new PNotify({ - title: 'Error', - text: 'Failed to update setting.', + title: 'Error!', + text: response.data.error_message, type: 'error' }); } - }).catch(function(error) { - wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change + }, function(error) { new PNotify({ - title: 'Error', - text: 'Connection failed while updating setting.', + title: 'Error!', + text: 'An error occurred while updating the setting.', type: 'error' }); + console.error(error); }); }; @@ -2945,73 +2969,6 @@ app.controller('listWebsites', function ($scope, $http, $window) { }; - $scope.togglePasswordProtection = function(wp) { - if (wp.passwordProtection) { - // Show modal for credentials - $('#Passwordprotection').modal('show'); - // Store the current WordPress site for later use - $scope.currentWPSite = wp; - } else { - // Disable password protection - $scope.updateSetting(wp, 'password-protection'); - } - }; - - $scope.enablePasswordProtection = function() { - if (!$scope.PPUsername || !$scope.PPPassword) { - new PNotify({ - title: 'Error!', - text: 'Please provide both username and password', - type: 'error' - }); - return; - } - - var data = { - siteId: $scope.currentWPSite.id, - setting: 'password-protection', - PPUsername: $scope.PPUsername, - PPPassword: $scope.PPPassword - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post('/websites/UpdateWPSettings', data, config).then( - function(response) { - if (response.data.status) { - new PNotify({ - title: 'Success!', - text: 'Password protection enabled successfully', - type: 'success' - }); - $('#Passwordprotection').modal('hide'); - // Clear the credentials - $scope.PPUsername = ''; - $scope.PPPassword = ''; - } else { - $scope.currentWPSite.passwordProtection = false; - new PNotify({ - title: 'Error!', - text: response.data.error_message || 'Failed to enable password protection', - type: 'error' - }); - } - }, - function(response) { - $scope.currentWPSite.passwordProtection = false; - new PNotify({ - title: 'Error!', - text: 'Could not connect to server', - type: 'error' - }); - } - ); - }; - }); app.controller('listChildDomainsMain', function ($scope, $http, $timeout) { @@ -6194,56 +6151,3013 @@ app.controller('listWebsites', function ($scope, $http, $window) { window.location.href = '/websites/listWPsites?wpID=' + wpId; }; - $scope.updateSetting = function(wp, setting) { - var settingMap = { - 'search-indexing': 'searchIndex', - 'debugging': 'debugging', - 'password-protection': 'passwordProtection', - 'maintenance-mode': 'maintenanceMode' - }; + $scope.currentWP = null; + $scope.PPUsername = ''; + $scope.PPPassword = ''; + $scope.togglePasswordProtection = function(wp) { + if (!wp.passwordProtection) { + // Show password protection modal + $('#Passwordprotection').modal('show'); + $scope.currentWP = wp; + } else { + // Disable password protection + $scope.updateSetting(wp, 'password-protection', 0); + } + }; + + $scope.enablePasswordProtection = function() { + if (!$scope.PPUsername || !$scope.PPPassword) { + new PNotify({ + title: 'Error!', + text: 'Username and password are required.', + type: 'error' + }); + return; + } + + $scope.updateSetting($scope.currentWP, 'password-protection', 1); + $('#Passwordprotection').modal('hide'); + }; + + $scope.updateSetting = function(wp, setting, value) { var data = { - wpID: wp.id, + WPid: wp.id, setting: setting, - value: wp[settingMap[setting]] ? 'enable' : 'disable' + value: value }; - $http({ - method: 'POST', - url: '/websites/UpdateWPSettings', - data: data, + if (setting === 'password-protection' && value === 1) { + data.PPUsername = $scope.PPUsername; + data.PPPassword = $scope.PPPassword; + } + + var config = { headers: { - 'Content-Type': 'application/x-www-form-urlencoded', 'X-CSRFToken': getCookie('csrftoken') - }, - transformRequest: function(obj) { - var str = []; - for(var p in obj) - str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); - return str.join("&"); } - }).then(function(response) { + }; + + $http.post('/websites/UpdateWPSettings', data, config).then(function(response) { if (response.data.status === 1) { new PNotify({ - title: 'Success', + title: 'Success!', text: 'Setting updated successfully.', type: 'success' }); + if (setting === 'password-protection') { + wp.passwordProtection = value; + // Reset form + $scope.PPUsername = ''; + $scope.PPPassword = ''; + $scope.currentWP = null; + } } else { - wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change new PNotify({ - title: 'Error', - text: 'Failed to update setting.', + title: 'Error!', + text: response.data.error_message, type: 'error' }); } - }).catch(function(error) { - wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change + }, function(error) { new PNotify({ - title: 'Error', - text: 'Connection failed while updating setting.', + title: 'Error!', + text: 'An error occurred while updating the setting.', type: 'error' }); + console.error(error); + }); + }; + + $scope.cyberPanelLoading = true; + + $scope.issueSSL = function (virtualHost) { + $scope.cyberPanelLoading = false; + + var url = "/manageSSL/issueSSL"; + + + var data = { + virtualHost: virtualHost + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.cyberPanelLoading = true; + if (response.data.SSL === 1) { + new PNotify({ + title: 'Success!', + text: 'SSL successfully issued.', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + + } + + function cantLoadInitialDatas(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); + } + + + }; + + $scope.cyberPanelLoading = true; + + $scope.searchWebsites = function () { + + $scope.cyberPanelLoading = false; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + var data = { + patternAdded: $scope.patternAdded + }; + + dataurl = "/websites/searchWebsites"; + + $http.post(dataurl, data, config).then(ListInitialData, cantLoadInitialData); + + + function ListInitialData(response) { + $scope.cyberPanelLoading = true; + if (response.data.listWebSiteStatus === 1) { + + var finalData = JSON.parse(response.data.data); + $scope.WebSitesList = finalData; + $("#listFail").hide(); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + } + + function cantLoadInitialData(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Connect disrupted, refresh the page.', + type: 'error' + }); + } + + + }; + + $scope.ScanWordpressSite = function () { + + $('#cyberPanelLoading').show(); + + + var url = "/websites/ScanWordpressSite"; + + var data = {} + + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + +/** + * Created by usman on 7/26/17. + */ +function getCookie(name) { + var cookieValue = null; + var t = document.cookie; + if (document.cookie && document.cookie !== '') { + var cookies = document.cookie.split(';'); + for (var i = 0; i < cookies.length; i++) { + var cookie = jQuery.trim(cookies[i]); + // Does this cookie string begin with the name we want? + if (cookie.substring(0, name.length + 1) === (name + '=')) { + cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); + break; + } + } + } + return cookieValue; +} + + +var arry = [] + +function selectpluginJs(val) { + $('#mysearch').hide() + arry.push(val) + + // console.log(arry) + document.getElementById('selJS').innerHTML = ""; + + for (var i = 0; i < arry.length; i++) { + $('#selJS').show() + var mlm = ' ' + arry[i] + '    ' + $('#selJS').append(mlm) + } + + +} + + +var DeletePluginURL; + +function DeletePluginBuucket(url) { + DeletePluginURL = url; +} + +function FinalDeletePluginBuucket() { + window.location.href = DeletePluginURL; +} + +var SPVal; + +app.controller('WPAddNewPlugin', function ($scope, $http, $timeout, $window, $compile) { + $scope.webSiteCreationLoading = true; + + $scope.SearchPluginName = function (val) { + $scope.webSiteCreationLoading = false; + SPVal = val; + url = "/websites/SearchOnkeyupPlugin"; + + var searchcontent = $scope.searchcontent; + + + var data = { + pluginname: searchcontent + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.webSiteCreationLoading = true; + + if (response.data.status === 1) { + if (SPVal == 'add') { + $('#mysearch').show() + document.getElementById('mysearch').innerHTML = ""; + var res = response.data.plugns.plugins + // console.log(res); + for (i = 0; i <= res.length; i++) { + // + var tml = '
    '; + $('#mysearch').append(tml); + } + } else if (SPVal == 'eidt') { + $('#mysearch').show() + document.getElementById('mysearch').innerHTML = ""; + var res = response.data.plugns.plugins + // console.log(res); + for (i = 0; i <= res.length; i++) { + // + var tml = '
    '; + var temp = $compile(tml)($scope) + angular.element(document.getElementById('mysearch')).append(temp); + } + + } + + + } else { + + // $scope.errorMessage = response.data.error_message; + alert("Status not = 1: Error..." + response.data.error_message) + } + + + } + + function cantLoadInitialDatas(response) { + + alert("Error..." + response) + + } + } + + $scope.AddNewplugin = function () { + + url = "/websites/AddNewpluginAjax"; + + var bucketname = $scope.PluginbucketName + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + var data = { + config: arry, + Name: bucketname + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + function ListInitialDatas(response) { + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Bucket created.', + type: 'success' + }); + location.reload(); + } else { + + new PNotify({ + title: 'Error!', + text: response.data.error_message, + type: 'error' + }); + } + + + } + + function cantLoadInitialDatas(response) { + + alert("Error..." + response) + + } + } + + $scope.deletesPlgin = function (val) { + + url = "/websites/deletesPlgin"; + + + var data = { + pluginname: val, + pluginbBucketID: $('#pluginbID').html() + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.status === 1) { + location.reload(); + + } else { + + // $scope.errorMessage = response.data.error_message; + alert("Status not = 1: Error..." + response.data.error_message) + } + + + } + + function cantLoadInitialDatas(response) { + + alert("Error..." + response) + + } + + } + + $scope.Addplugin = function (slug) { + $('#mysearch').hide() + + url = "/websites/Addplugineidt"; + + + var data = { + pluginname: slug, + pluginbBucketID: $('#pluginbID').html() + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.status === 1) { + location.reload(); + + } else { + + // $scope.errorMessage = response.data.error_message; + alert("Status not = 1: Error..." + response.data.error_message) + } + + + } + + function cantLoadInitialDatas(response) { + + alert("Error..." + response) + + } + + + } + +}); + +var domain_check = 0; + +function checkbox_function() { + + var checkBox = document.getElementById("myCheck"); + // Get the output text + + + // If the checkbox is checked, display the output text + if (checkBox.checked == true) { + domain_check = 0; + document.getElementById('Test_Domain').style.display = "block"; + document.getElementById('Own_Domain').style.display = "none"; + + } else { + document.getElementById('Test_Domain').style.display = "none"; + document.getElementById('Own_Domain').style.display = "block"; + domain_check = 1; + } + + // alert(domain_check); +} + +app.controller('createWordpress', function ($scope, $http, $timeout, $compile, $window) { + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = false; + $scope.installationProgress = true; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + + + var statusFile; + + $scope.createWordPresssite = function () { + + $scope.webSiteCreationLoading = false; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + + + $scope.currentStatus = "Starting creation.."; + + var apacheBackend = 0; + + if ($scope.apacheBackend === true) { + apacheBackend = 1; + } else { + apacheBackend = 0 + } + + var package = $scope.packageForWebsite; + var websiteOwner = $scope.websiteOwner; + var WPtitle = $scope.WPtitle; + + // if (domain_check == 0) { + // var Part2_domainNameCreate = document.getElementById('Part2_domainNameCreate').value; + // var domainNameCreate = document.getElementById('TestDomainNameCreate').value + Part2_domainNameCreate; + // } + // if (domain_check == 1) { + // + // var domainNameCreate = $scope.own_domainNameCreate; + // } + + var domainNameCreate = $scope.domainNameCreate; + + + var WPUsername = $scope.WPUsername; + var adminEmail = $scope.adminEmail; + var WPPassword = $scope.WPPassword; + var WPVersions = $scope.WPVersions; + var pluginbucket = $scope.pluginbucket; + var autoupdates = $scope.autoupdates; + var pluginupdates = $scope.pluginupdates; + var themeupdates = $scope.themeupdates; + + if (domain_check == 0) { + + var path = ""; + + } + if (domain_check = 1) { + + var path = $scope.installPath; + + } + + + var home = "1"; + + if (typeof path != 'undefined') { + home = "0"; + } + + //alert(domainNameCreate); + var data = { + + title: WPtitle, + domain: domainNameCreate, + WPVersion: WPVersions, + pluginbucket: pluginbucket, + adminUser: WPUsername, + Email: adminEmail, + PasswordByPass: WPPassword, + AutomaticUpdates: autoupdates, + Plugins: pluginupdates, + Themes: themeupdates, + websiteOwner: websiteOwner, + package: package, + home: home, + path: path, + apacheBackend: apacheBackend + } + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + var url = "/websites/submitWorpressCreation"; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.webSiteCreationLoading = true; + if (response.data.status === 1) { + statusFile = response.data.tempStatusPath; + getCreationStatus(); + + } else { + $scope.goBackDisable = false; + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + + } + + function cantLoadInitialDatas(response) { + + alert("Error..." + response) + + } + + }; + $scope.goBack = function () { + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = false; + $scope.installationProgress = true; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + $("#installProgress").css("width", "0%"); + }; + + function getCreationStatus() { + + url = "/websites/installWordpressStatus"; + + var data = { + statusFile: statusFile + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.abort === 1) { + + if (response.data.installStatus === 1) { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = false; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $("#installProgress").css("width", "100%"); + $scope.installPercentage = "100"; + $scope.currentStatus = response.data.currentStatus; + $timeout.cancel(); + + } else { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = false; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $scope.errorMessage = response.data.error_message; + + $("#installProgress").css("width", "0%"); + $scope.installPercentage = "0"; + $scope.goBackDisable = false; + + } + + } else { + $scope.webSiteCreationLoading = false; + $("#installProgress").css("width", response.data.installationProgress + "%"); + $scope.installPercentage = response.data.installationProgress; + $scope.currentStatus = response.data.currentStatus; + $timeout(getCreationStatus, 1000); + } + + } + + function cantLoadInitialDatas(response) { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = false; + $scope.goBackDisable = false; + + } + + + } + + +}); + + +//........... delete wp list +var FurlDeleteWP; + +function DeleteWPNow(url) { + FurlDeleteWP = url; +} + +function FinalDeleteWPNow() { + window.location.href = FurlDeleteWP; +} + +var DeploytoProductionID; + +function DeployToProductionInitial(vall) { + DeploytoProductionID = vall; +} + +var create_staging_domain_check = 0; + +function create_staging_checkbox_function() { + + try { + + var checkBox = document.getElementById("Create_Staging_Check"); + // Get the output text + + + // If the checkbox is checked, display the output text + if (checkBox.checked == true) { + create_staging_domain_check = 0; + document.getElementById('Website_Create_Test_Domain').style.display = "block"; + document.getElementById('Website_Create_Own_Domain').style.display = "none"; + + } else { + document.getElementById('Website_Create_Test_Domain').style.display = "none"; + document.getElementById('Website_Create_Own_Domain').style.display = "block"; + create_staging_domain_check = 1; + } + } catch (e) { + + } + + // alert(domain_check); +} + +create_staging_checkbox_function(); + +app.controller('WPsiteHome', function ($scope, $http, $timeout, $compile, $window) { + + var CheckBoxpasssword = 0; + + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = false; + $scope.installationProgress = true; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + $(document).ready(function () { + var checkstatus = document.getElementById("wordpresshome"); + if (checkstatus !== null) { + $scope.LoadWPdata(); + + } + }); + + + $scope.LoadWPdata = function () { + + $scope.wordpresshomeloading = false; + $('#wordpresshomeloading').show(); + + var url = "/websites/FetchWPdata"; + + var data = { + WPid: $('#WPid').html(), + } + + console.log(data); + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + wordpresshomeloading = true; + $('#wordpresshomeloading').hide(); + + if (response.data.status === 1) { + $('#WPVersion').text(response.data.ret_data.version); + if (response.data.ret_data.lscache === 1) { + $('#lscache').prop('checked', true); + } + if (response.data.ret_data.debugging === 1) { + $('#debugging').prop('checked', true); + } + if (response.data.ret_data.searchIndex === 1) { + $('#searchIndex').prop('checked', true); + } + if (response.data.ret_data.maintenanceMode === 1) { + $('#maintenanceMode').prop('checked', true); + } + if (response.data.ret_data.wpcron === 1) { + $('#wpcron').prop('checked', true); + } + if (response.data.ret_data.passwordprotection == 1) { + + var dc = '\n' + + ' ' + var mp = $compile(dc)($scope); + angular.element(document.getElementById('prsswdprodata')).append(mp); + CheckBoxpasssword = 1; + } else if (response.data.ret_data.passwordprotection == 0) { + var dc = '\n' + + ' ' + $('#prsswdprodata').append(dc); + CheckBoxpasssword = 0; + } + + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = false; + $scope.goBackDisable = false; + + } + + + }; + + $scope.UpdateWPSettings = function (setting) { + + $scope.wordpresshomeloading = false; + $('#wordpresshomeloading').show(); + + + var url = "/websites/UpdateWPSettings"; + + if (setting === "PasswordProtection") { + if (CheckBoxpasssword == 0) { + var data = { + WPid: $('#WPid').html(), + setting: setting, + PPUsername: $scope.PPUsername, + PPPassword: $scope.PPPassword, + } + + } else { + var data = { + WPid: $('#WPid').html(), + setting: setting, + PPUsername: '', + PPPassword: '', + } + + } + + } else { + var settingValue = 0; + if ($('#' + setting).is(":checked")) { + settingValue = 1; + } + var data = { + WPid: $('#WPid').html(), + setting: setting, + settingValue: settingValue + } + } + + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.wordpresshomeloading = true; + $('#wordpresshomeloading').hide(); + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Successfully Updated!.', + type: 'success' + }); + if (setting === "PasswordProtection") { + location.reload(); + } + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + if (setting === "PasswordProtection") { + location.reload(); + } + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + + + }; + + $scope.GetCurrentPlugins = function () { + $('#wordpresshomeloading').show(); + + $scope.wordpresshomeloading = false; + + var url = "/websites/GetCurrentPlugins"; + + var data = { + WPid: $('#WPid').html(), + } + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + wordpresshomeloading = true; + $('#wordpresshomeloading').hide(); + + if (response.data.status === 1) { + $('#PluginBody').html(''); + var plugins = JSON.parse(response.data.plugins); + plugins.forEach(AddPlugins); + + } else { + alert("Error:" + response.data.error_message) + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = false; + $scope.goBackDisable = false; + + } + + + }; + + $scope.GetCurrentThemes = function () { + $('#wordpresshomeloading').show(); + + $scope.wordpresshomeloading = false; + + var url = "/websites/GetCurrentThemes"; + + var data = { + WPid: $('#WPid').html(), + } + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + wordpresshomeloading = true; + $('#wordpresshomeloading').hide(); + + if (response.data.status === 1) { + + $('#ThemeBody').html(''); + var themes = JSON.parse(response.data.themes); + themes.forEach(AddThemes); + + } else { + alert("Error:" + response.data.error_message) + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = false; + $scope.goBackDisable = false; + + } + + + }; + + $scope.UpdatePlugins = function (plugin) { + $('#wordpresshomeloading').show(); + var data = { + plugin: plugin, + pluginarray: PluginsList, + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/UpdatePlugins"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Updating Plugins in Background!.', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + + + }; + + $scope.DeletePlugins = function (plugin) { + $('#wordpresshomeloading').show(); + var data = { + plugin: plugin, + pluginarray: PluginsList, + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/DeletePlugins"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Deleting Plugin in Background!', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + + } + + $scope.ChangeStatus = function (plugin) { + $('#wordpresshomeloading').show(); + var data = { + plugin: plugin, + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/ChangeStatus"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Changed Plugin state Successfully !.', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + + } + + function AddPlugins(value, index, array) { + var FinalMarkup = '' + FinalMarkup = FinalMarkup + ''; + for (let x in value) { + if (x === 'status') { + if (value[x] === 'inactive') { + FinalMarkup = FinalMarkup + '
    '; + } else { + FinalMarkup = FinalMarkup + '
    '; + } + } else if (x === 'update') { + if (value[x] === 'none') { + FinalMarkup = FinalMarkup + 'Upto Date'; + } else { + FinalMarkup = FinalMarkup + ''; + } + } else { + FinalMarkup = FinalMarkup + '' + value[x] + ""; + } + } + FinalMarkup = FinalMarkup + '' + FinalMarkup = FinalMarkup + '' + var temp = $compile(FinalMarkup)($scope) + AppendToTable('#PluginBody', temp) + } + + $scope.UpdateThemes = function (theme) { + $('#wordpresshomeloading').show(); + var data = { + Theme: theme, + Themearray: ThemesList, + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/UpdateThemes"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Updating Theme in background !.', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + + + }; + + $scope.DeleteThemes = function (theme) { + $('#wordpresshomeloading').show(); + var data = { + Theme: theme, + Themearray: ThemesList, + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/DeleteThemes"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Deleting Theme in Background!.', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + }; + + $scope.ChangeStatusThemes = function (theme) { + $('#wordpresshomeloading').show(); + var data = { + theme: theme, + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/StatusThemes"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Change Theme state in Bsckground!.', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + + }; + + function AddThemes(value, index, array) { + var FinalMarkup = '' + FinalMarkup = FinalMarkup + ''; + for (let x in value) { + if (x === 'status') { + if (value[x] === 'inactive') { + FinalMarkup = FinalMarkup + '
    '; + } else { + FinalMarkup = FinalMarkup + '
    '; + } + } else if (x === 'update') { + if (value[x] === 'none') { + FinalMarkup = FinalMarkup + 'Upto Date'; + } else { + FinalMarkup = FinalMarkup + ''; + } + } else { + FinalMarkup = FinalMarkup + '' + value[x] + ""; + } + } + FinalMarkup = FinalMarkup + '' + FinalMarkup = FinalMarkup + '' + var temp = $compile(FinalMarkup)($scope) + AppendToTable('#ThemeBody', temp) + } + + $scope.CreateStagingNow = function () { + $('#wordpresshomeloading').show(); + + $scope.wordpresshomeloading = false; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + + + $scope.currentStatus = "Starting creation Staging.."; + + //here enter domain name + if (create_staging_domain_check == 0) { + var Part2_domainNameCreate = document.getElementById('Part2_domainNameCreate').value; + var domainNameCreate = document.getElementById('TestDomainNameCreate').value + Part2_domainNameCreate; + } + if (create_staging_domain_check == 1) { + + var domainNameCreate = $scope.own_domainNameCreate; + } + var data = { + StagingName: $('#stagingName').val(), + StagingDomain: domainNameCreate, + WPid: $('#WPid').html(), + } + var url = "/websites/CreateStagingNow"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + if (response.data.status === 1) { + statusFile = response.data.tempStatusPath; + getCreationStatus(); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + }; + + function getCreationStatus() { + $('#wordpresshomeloading').show(); + + url = "/websites/installWordpressStatus"; + + var data = { + statusFile: statusFile + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + //$('#wordpresshomeloading').hide(); + + if (response.data.abort === 1) { + if (response.data.installStatus === 1) { + + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = false; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + + $("#installProgress").css("width", "100%"); + $("#installProgressbackup").css("width", "100%"); + $scope.installPercentage = "100"; + $scope.currentStatus = response.data.currentStatus; + $timeout.cancel(); + + + } else { + + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = false; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $scope.errorMessage = response.data.error_message; + + $("#installProgress").css("width", "0%"); + $("#installProgressbackup").css("width", "0%"); + $scope.installPercentage = "0"; + $scope.goBackDisable = false; + + + } + + } else { + + $("#installProgress").css("width", response.data.installationProgress + "%"); + $("#installProgressbackup").css("width", response.data.installationProgress + "%"); + $scope.installPercentage = response.data.installationProgress; + $scope.currentStatus = response.data.currentStatus; + $timeout(getCreationStatus, 1000); + + } + + } + + function cantLoadInitialDatas(response) { + //$('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = false; + $scope.goBackDisable = false; + + } + + + } + + $scope.goBack = function () { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = false; + $scope.installationProgress = true; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + $("#installProgress").css("width", "0%"); + }; + + $scope.fetchstaging = function () { + + $('#wordpresshomeloading').show(); + $scope.wordpresshomeloading = false; + + var url = "/websites/fetchstaging"; + + var data = { + WPid: $('#WPid').html(), + } + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + wordpresshomeloading = true; + $('#wordpresshomeloading').hide(); + + if (response.data.status === 1) { + + // $('#ThemeBody').html(''); + // var themes = JSON.parse(response.data.themes); + // themes.forEach(AddThemes); + + $('#StagingBody').html(''); + var staging = JSON.parse(response.data.wpsites); + staging.forEach(AddStagings); + + } else { + alert("Error data.error_message:" + response.data.error_message) + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + alert("Error" + response) + + } + + }; + + $scope.fetchDatabase = function () { + + $('#wordpresshomeloading').show(); + $scope.wordpresshomeloading = false; + + var url = "/websites/fetchDatabase"; + + var data = { + WPid: $('#WPid').html(), + } + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + wordpresshomeloading = true; + $('#wordpresshomeloading').hide(); + + if (response.data.status === 1) { + $('#DB_Name').html(response.data.DataBaseName); + $('#DB_User').html(response.data.DataBaseUser); + $('#tableprefix').html(response.data.tableprefix); + } else { + alert("Error data.error_message:" + response.data.error_message) + + } + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + alert("Error" + response) + + } + + }; + + $scope.SaveUpdateConfig = function () { + $('#wordpresshomeloading').show(); + var data = { + AutomaticUpdates: $('#AutomaticUpdates').find(":selected").text(), + Plugins: $('#Plugins').find(":selected").text(), + Themes: $('#Themes').find(":selected").text(), + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/SaveUpdateConfig"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Update Configurations Sucessfully!.', + type: 'success' + }); + $("#autoUpdateConfig").modal('hide'); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + new PNotify({ + title: 'Operation Failed!', + text: response, + type: 'error' + }); + + } + }; + + function AddStagings(value, index, array) { + var FinalMarkup = '' + for (let x in value) { + if (x === 'name') { + FinalMarkup = FinalMarkup + '
    ' + value[x] + ''; + } else if (x !== 'url' && x !== 'deleteURL' && x !== 'id') { + FinalMarkup = FinalMarkup + '' + value[x] + ""; + } + } + FinalMarkup = FinalMarkup + '' + + ' ' + FinalMarkup = FinalMarkup + '' + AppendToTable('#StagingBody', FinalMarkup); + } + + $scope.FinalDeployToProduction = function () { + + $('#wordpresshomeloading').show(); + + $scope.wordpresshomeloading = false; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + + var data = { + WPid: $('#WPid').html(), + StagingID: DeploytoProductionID + } + + var url = "/websites/DeploytoProduction"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + function ListInitialDatas(response) { + + $('#wordpresshomeloading').hide(); + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Deploy To Production start!.', + type: 'success' + }); + statusFile = response.data.tempStatusPath; + getCreationStatus(); + + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + new PNotify({ + title: 'Operation Failed!', + text: response, + type: 'error' + }); + + } + + }; + + + $scope.CreateBackup = function () { + $('#wordpresshomeloading').show(); + + $scope.wordpresshomeloading = false; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + $scope.currentStatus = "Starting creation Backups.."; + var data = { + WPid: $('#WPid').html(), + Backuptype: $('#backuptype').val() + } + var url = "/websites/WPCreateBackup"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $('createbackupbutton').hide(); + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Creating Backups!.', + type: 'success' + }); + statusFile = response.data.tempStatusPath; + getCreationStatus(); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + alert(response) + + } + + }; + + + $scope.installwpcore = function () { + + $('#wordpresshomeloading').show(); + $('#wordpresshomeloadingsec').show(); + var data = { + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/installwpcore"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $('#wordpresshomeloadingsec').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Results fetched..', + type: 'success' + }); + $('#SecurityResult').html(response.data.result); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $('#wordpresshomeloadingsec').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + + }; + + $scope.dataintegrity = function () { + + $('#wordpresshomeloading').show(); + $('#wordpresshomeloadingsec').show(); + var data = { + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/dataintegrity"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $('#wordpresshomeloadingsec').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Results fetched', + type: 'success' + }); + $('#SecurityResult').html(response.data.result); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $('#wordpresshomeloadingsec').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + }; + +}); + + +var PluginsList = []; + + +function AddPluginToArray(cBox, name) { + if (cBox.checked) { + PluginsList.push(name); + // alert(PluginsList); + } else { + const index = PluginsList.indexOf(name); + if (index > -1) { + PluginsList.splice(index, 1); + } + // alert(PluginsList); + } +} + +var ThemesList = []; + +function AddThemeToArray(cBox, name) { + if (cBox.checked) { + ThemesList.push(name); + // alert(ThemesList); + } else { + const index = ThemesList.indexOf(name); + if (index > -1) { + ThemesList.splice(index, 1); + } + // alert(ThemesList); + } +} + + +function AppendToTable(table, markup) { + $(table).append(markup); +} + + +//..................Restore Backup Home + + +app.controller('RestoreWPBackup', function ($scope, $http, $timeout, $window) { + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = false; + $scope.installationProgress = true; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + + + $scope.checkmethode = function () { + var val = $('#RestoreMethode').children("option:selected").val(); + if (val == 1) { + $('#Newsitediv').show(); + $('#exinstingsitediv').hide(); + } else if (val == 0) { + $('#exinstingsitediv').show(); + $('#Newsitediv').hide(); + } else { + + } + }; + + + $scope.RestoreWPbackupNow = function () { + $('#wordpresshomeloading').show(); + $scope.wordpresshomeloading = false; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + $scope.currentStatus = "Start Restoring WordPress.."; + + var Domain = $('#wprestoresubdirdomain').val() + var path = $('#wprestoresubdirpath').val(); + var home = "1"; + + if (typeof path != 'undefined' || path != '') { + home = "0"; + } + if (typeof path == 'undefined') { + path = ""; + } + + + var backuptype = $('#backuptype').html(); + var data; + if (backuptype == "DataBase Backup") { + data = { + backupid: $('#backupid').html(), + DesSite: $('#DesSite').children("option:selected").val(), + Domain: '', + path: path, + home: home, + } + } else { + data = { + backupid: $('#backupid').html(), + DesSite: $('#DesSite').children("option:selected").val(), + Domain: Domain, + path: path, + home: home, + } + + } + + var url = "/websites/RestoreWPbackupNow"; + + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + // console.log(data) + + var d = $('#DesSite').children("option:selected").val(); + var c = $("input[name=Newdomain]").val(); + // if (d == -1 || c == "") { + // alert("Please Select Method of Backup Restore"); + // } else { + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + // } + + + function ListInitialDatas(response) { + wordpresshomeloading = true; + $('#wordpresshomeloading').hide(); + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Restoring process starts!.', + type: 'success' + }); + statusFile = response.data.tempStatusPath; + getCreationStatus(); + + } else { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = false; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $scope.errorMessage = response.data.error_message; + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + + } + } + + function getCreationStatus() { + $('#wordpresshomeloading').show(); + + url = "/websites/installWordpressStatus"; + + var data = { + statusFile: statusFile + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + //$('#wordpresshomeloading').hide(); + + if (response.data.abort === 1) { + + if (response.data.installStatus === 1) { + + + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = false; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + + $("#installProgress").css("width", "100%"); + $("#installProgressbackup").css("width", "100%"); + $scope.installPercentage = "100"; + $scope.currentStatus = response.data.currentStatus; + $timeout.cancel(); + + + } else { + + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = false; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $scope.errorMessage = response.data.error_message; + + $("#installProgress").css("width", "0%"); + $("#installProgressbackup").css("width", "0%"); + $scope.installPercentage = "0"; + $scope.goBackDisable = false; + + + } + + } else { + + $("#installProgress").css("width", response.data.installationProgress + "%"); + $("#installProgressbackup").css("width", response.data.installationProgress + "%"); + $scope.installPercentage = response.data.installationProgress; + $scope.currentStatus = response.data.currentStatus; + $timeout(getCreationStatus, 1000); + + } + + } + + function cantLoadInitialDatas(response) { + //$('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = false; + $scope.goBackDisable = false; + + } + + + } + + $scope.goBack = function () { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = false; + $scope.installationProgress = true; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + $("#installProgress").css("width", "0%"); + }; +}); + + +//.......................................Remote Backup + +//........... delete DeleteBackupConfigNow + +function DeleteBackupConfigNow(url) { + window.location.href = url; +} + +function DeleteRemoteBackupsiteNow(url) { + window.location.href = url; +} + +function DeleteBackupfileConfigNow(url) { + window.location.href = url; +} + + +app.controller('RemoteBackupConfig', function ($scope, $http, $timeout, $window) { + $scope.RemoteBackupLoading = true; + $scope.SFTPBackUpdiv = true; + + $scope.EndpointURLdiv = true; + $scope.Selectprovider = true; + $scope.S3keyNamediv = true; + $scope.Accesskeydiv = true; + $scope.SecretKeydiv = true; + $scope.SelectRemoteBackuptype = function () { + var val = $scope.RemoteBackuptype; + if (val == "SFTP") { + $scope.SFTPBackUpdiv = false; + $scope.EndpointURLdiv = true; + $scope.Selectprovider = true; + $scope.S3keyNamediv = true; + $scope.Accesskeydiv = true; + $scope.SecretKeydiv = true; + } else if (val == "S3") { + $scope.EndpointURLdiv = true; + $scope.Selectprovider = false; + $scope.S3keyNamediv = false; + $scope.Accesskeydiv = false; + $scope.SecretKeydiv = false; + $scope.SFTPBackUpdiv = true; + } else { + $scope.RemoteBackupLoading = true; + $scope.SFTPBackUpdiv = true; + + $scope.EndpointURLdiv = true; + $scope.Selectprovider = true; + $scope.S3keyNamediv = true; + $scope.Accesskeydiv = true; + $scope.SecretKeydiv = true; + } + } + + $scope.SelectProvidertype = function () { + $scope.EndpointURLdiv = true; + var provider = $scope.Providervalue + if (provider == 'Backblaze') { + $scope.EndpointURLdiv = false; + } else { + $scope.EndpointURLdiv = true; + } + } + + $scope.SaveBackupConfig = function () { + $scope.RemoteBackupLoading = false; + var Hname = $scope.Hostname; + var Uname = $scope.Username; + var Passwd = $scope.Password; + var path = $scope.path; + var type = $scope.RemoteBackuptype; + var Providervalue = $scope.Providervalue; + var data; + if (type == "SFTP") { + + data = { + Hname: Hname, + Uname: Uname, + Passwd: Passwd, + path: path, + type: type + } + } else if (type == "S3") { + if (Providervalue == "Backblaze") { + data = { + S3keyname: $scope.S3keyName, + Provider: Providervalue, + AccessKey: $scope.Accesskey, + SecertKey: $scope.SecretKey, + EndUrl: $scope.EndpointURL, + type: type + } + } else { + data = { + S3keyname: $scope.S3keyName, + Provider: Providervalue, + AccessKey: $scope.Accesskey, + SecertKey: $scope.SecretKey, + type: type + } + + } + + } + var url = "/websites/SaveBackupConfig"; + + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.RemoteBackupLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Successfully Saved!.', + type: 'success' + }); + location.reload(); + + + } else { + new PNotify({ + title: 'Error!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialDatas(response) { + $scope.RemoteBackupLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + + } + + + } + +}); + +var UpdatescheduleID; +app.controller('BackupSchedule', function ($scope, $http, $timeout, $window) { + $scope.BackupScheduleLoading = true; + $scope.SaveBackupSchedule = function () { + $scope.RemoteBackupLoading = false; + var FileRetention = $scope.Fretention; + var Backfrequency = $scope.Bfrequency; + + + var data = { + FileRetention: FileRetention, + Backfrequency: Backfrequency, + ScheduleName: $scope.ScheduleName, + RemoteConfigID: $('#RemoteConfigID').html(), + BackupType: $scope.BackupType + } + var url = "/websites/SaveBackupSchedule"; + + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.RemoteBackupLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Successfully Saved!.', + type: 'success' + }); + location.reload(); + + + } else { + new PNotify({ + title: 'Error!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialDatas(response) { + $scope.RemoteBackupLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + + } + + + }; + + + $scope.getupdateid = function (ID) { + UpdatescheduleID = ID; + } + + $scope.UpdateRemoteschedules = function () { + $scope.RemoteBackupLoading = false; + var Frequency = $scope.RemoteFrequency; + var fretention = $scope.RemoteFileretention; + + var data = { + ScheduleID: UpdatescheduleID, + Frequency: Frequency, + FileRetention: fretention + } + var url = "/websites/UpdateRemoteschedules"; + + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.RemoteBackupLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Successfully Updated!.', + type: 'success' + }); + location.reload(); + + + } else { + new PNotify({ + title: 'Error!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialDatas(response) { + $scope.RemoteBackupLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + + } + }; + + $scope.AddWPsiteforRemoteBackup = function () { + $scope.RemoteBackupLoading = false; + + + var data = { + WpsiteID: $('#Wpsite').val(), + RemoteScheduleID: $('#RemoteScheduleID').html() + } + var url = "/websites/AddWPsiteforRemoteBackup"; + + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.RemoteBackupLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Successfully Saved!.', + type: 'success' + }); + location.reload(); + + + } else { + new PNotify({ + title: 'Error!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialDatas(response) { + $scope.RemoteBackupLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + + } + + + }; +}); +/* Java script code to create account */ + +var website_create_domain_check = 0; + +function website_create_checkbox_function() { + + var checkBox = document.getElementById("myCheck"); + // Get the output text + + + // If the checkbox is checked, display the output text + if (checkBox.checked == true) { + website_create_domain_check = 0; + document.getElementById('Website_Create_Test_Domain').style.display = "block"; + document.getElementById('Website_Create_Own_Domain').style.display = "none"; + + } else { + document.getElementById('Website_Create_Test_Domain').style.display = "none"; + document.getElementById('Website_Create_Own_Domain').style.display = "block"; + website_create_domain_check = 1; + } + + // alert(domain_check); +} + +app.controller('createWebsite', function ($scope, $http, $timeout, $window) { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = false; + $scope.installationProgress = true; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + + var statusFile; + + $scope.createWebsite = function () { + + $scope.webSiteCreationLoading = false; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + + $scope.currentStatus = "Starting creation.."; + + var ssl, dkimCheck, openBasedir, mailDomain, apacheBackend; + + if ($scope.sslCheck === true) { + ssl = 1; + } else { + ssl = 0 + } + + if ($scope.apacheBackend === true) { + apacheBackend = 1; + } else { + apacheBackend = 0 + } + + if ($scope.dkimCheck === true) { + dkimCheck = 1; + } else { + dkimCheck = 0 + } + + if ($scope.openBasedir === true) { + openBasedir = 1; + } else { + openBasedir = 0 + } + + if ($scope.mailDomain === true) { + mailDomain = 1; + } else { + mailDomain = 0 + } + + + url = "/websites/submitWebsiteCreation"; + + var package = $scope.packageForWebsite; + + // if (website_create_domain_check == 0) { + // var Part2_domainNameCreate = document.getElementById('Part2_domainNameCreate').value; + // var domainName = document.getElementById('TestDomainNameCreate').value + Part2_domainNameCreate; + // } + // if (website_create_domain_check == 1) { + // + // var domainName = $scope.domainNameCreate; + // } + var domainName = $scope.domainNameCreate; + + // var domainName = $scope.domainNameCreate; + + var adminEmail = $scope.adminEmail; + var phpSelection = $scope.phpSelection; + var websiteOwner = $scope.websiteOwner; + + + var data = { + package: package, + domainName: domainName, + adminEmail: adminEmail, + phpSelection: phpSelection, + ssl: ssl, + websiteOwner: websiteOwner, + dkimCheck: dkimCheck, + openBasedir: openBasedir, + mailDomain: mailDomain, + apacheBackend: apacheBackend + }; + + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.createWebSiteStatus === 1) { + statusFile = response.data.tempStatusPath; + getCreationStatus(); + } else { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = false; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $scope.errorMessage = response.data.error_message; + } + + + } + + function cantLoadInitialDatas(response) { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = false; + $scope.goBackDisable = false; + + } + + + }; + $scope.goBack = function () { + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = false; + $scope.installationProgress = true; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + $("#installProgress").css("width", "0%"); + }; + + function getCreationStatus() { + + url = "/websites/installWordpressStatus"; + + var data = { + statusFile: statusFile + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + + if (response.data.abort === 1) { + + if (response.data.installStatus === 1) { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = false; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $("#installProgress").css("width", "100%"); + $scope.installPercentage = "100"; + $scope.currentStatus = response.data.currentStatus; + $timeout.cancel(); + + } else { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = false; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $scope.errorMessage = response.data.error_message; + + $("#installProgress").css("width", "0%"); + $scope.installPercentage = "0"; + $scope.goBackDisable = false; + + } + + } else { + $("#installProgress").css("width", response.data.installationProgress + "%"); + $scope.installPercentage = response.data.installationProgress; + $scope.currentStatus = response.data.currentStatus; + $timeout(getCreationStatus, 1000); + } + + } + + function cantLoadInitialDatas(response) { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = false; + $scope.goBackDisable = false; + + } + + + } + +}); +/* Java script code to create account ends here */ + +/* Java script code to list accounts */ + +$("#listFail").hide(); + + +app.controller('listWebsites', function ($scope, $http, $window) { + $scope.web = {}; + $scope.WebSitesList = []; + + $scope.currentPage = 1; + $scope.recordsToShow = 10; + + // Initial fetch of websites + $scope.getFurtherWebsitesFromDB = function () { + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + var data = { + page: $scope.currentPage, + recordsToShow: $scope.recordsToShow + }; + + var dataurl = "/websites/fetchWebsitesList"; + + $http.post(dataurl, data, config).then(function(response) { + if (response.data.listWebSiteStatus === 1) { + $scope.WebSitesList = JSON.parse(response.data.data); + $scope.pagination = response.data.pagination; + $("#listFail").hide(); + } else { + $("#listFail").fadeIn(); + $scope.errorMessage = response.data.error_message; + } + }).catch(function(error) { + $("#listFail").fadeIn(); + $scope.errorMessage = error.message || 'An error occurred while fetching websites'; + }); + }; + + // Call it immediately + $scope.getFurtherWebsitesFromDB(); + + $scope.showWPSites = function(domain) { + console.log('showWPSites called for domain:', domain); + + // Make sure domain is defined + if (!domain) { + console.error('Domain is undefined'); + return; + } + + var url = '/websites/fetchWPDetails'; + var data = { + domain: domain + }; + + console.log('Making request to:', url, 'with data:', data); + + $http({ + method: 'POST', + url: url, + data: $.param(data), + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'X-CSRFToken': getCookie('csrftoken') + } + }).then(function(response) { + console.log('Response received:', response); + if (response.data.status === 1 && response.data.fetchStatus === 1) { + // Find the website in the list and update its properties + $scope.WebSitesList.forEach(function(website) { + if (website.domain === domain) { + website.wp_sites = response.data.sites; + website.showWPSites = true; + console.log('Updated website:', website); + } + }); + $("#listFail").hide(); + } else { + $("#listFail").fadeIn(); + $scope.errorMessage = response.data.error_message || 'Failed to fetch WordPress sites'; + console.error('Error in response:', response.data.error_message); + } + }).catch(function(error) { + $("#listFail").fadeIn(); + $scope.errorMessage = error.message || 'An error occurred while fetching WordPress sites'; + console.error('Request failed:', error); + }); + }; + + $scope.visitSite = function(url) { + window.open(url, '_blank'); + }; + + $scope.wpLogin = function(wpId) { + window.open('/websites/wpLogin?wpID=' + wpId, '_blank'); + }; + + $scope.manageWP = function(wpId) { + window.location.href = '/websites/listWPsites?wpID=' + wpId; + }; + + $scope.currentWP = null; + $scope.PPUsername = ''; + $scope.PPPassword = ''; + + $scope.togglePasswordProtection = function(wp) { + if (!wp.passwordProtection) { + // Show password protection modal + $('#Passwordprotection').modal('show'); + $scope.currentWP = wp; + } else { + // Disable password protection + $scope.updateSetting(wp, 'password-protection', 0); + } + }; + + $scope.enablePasswordProtection = function() { + if (!$scope.PPUsername || !$scope.PPPassword) { + new PNotify({ + title: 'Error!', + text: 'Username and password are required.', + type: 'error' + }); + return; + } + + $scope.updateSetting($scope.currentWP, 'password-protection', 1); + $('#Passwordprotection').modal('hide'); + }; + + $scope.updateSetting = function(wp, setting, value) { + var data = { + WPid: wp.id, + setting: setting, + value: value + }; + + if (setting === 'password-protection' && value === 1) { + data.PPUsername = $scope.PPUsername; + data.PPPassword = $scope.PPPassword; + } + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post('/websites/UpdateWPSettings', data, config).then(function(response) { + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Setting updated successfully.', + type: 'success' + }); + if (setting === 'password-protection') { + wp.passwordProtection = value; + // Reset form + $scope.PPUsername = ''; + $scope.PPPassword = ''; + $scope.currentWP = null; + } + } else { + new PNotify({ + title: 'Error!', + text: response.data.error_message, + type: 'error' + }); + } + }, function(error) { + new PNotify({ + title: 'Error!', + text: 'An error occurred while updating the setting.', + type: 'error' + }); + console.error(error); }); }; @@ -6405,33 +9319,63 @@ app.controller('listWebsites', function ($scope, $http, $window) { }; - $scope.togglePasswordProtection = function(wp) { - if (wp.passwordProtection) { - // Show modal for credentials - $('#Passwordprotection').modal('show'); - // Store the current WordPress site for later use - $scope.currentWPSite = wp; - } else { - // Disable password protection - $scope.updateSetting(wp, 'password-protection'); - } - }; +}); - $scope.enablePasswordProtection = function() { - if (!$scope.PPUsername || !$scope.PPPassword) { - new PNotify({ - title: 'Error!', - text: 'Please provide both username and password', - type: 'error' - }); - return; - } +app.controller('listChildDomainsMain', function ($scope, $http, $timeout) { + + $scope.currentPage = 1; + $scope.recordsToShow = 10; + + $scope.getFurtherWebsitesFromDB = function () { + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; var data = { - siteId: $scope.currentWPSite.id, - setting: 'password-protection', - PPUsername: $scope.PPUsername, - PPPassword: $scope.PPPassword + page: $scope.currentPage, + recordsToShow: $scope.recordsToShow + }; + + + dataurl = "/websites/fetchChildDomainsMain"; + + $http.post(dataurl, data, config).then(ListInitialData, cantLoadInitialData); + + + function ListInitialData(response) { + if (response.data.listWebSiteStatus === 1) { + + $scope.WebSitesList = JSON.parse(response.data.data); + $scope.pagination = response.data.pagination; + $scope.clients = JSON.parse(response.data.data); + $("#listFail").hide(); + } else { + $("#listFail").fadeIn(); + $scope.errorMessage = response.data.error_message; + + } + } + + function cantLoadInitialData(response) { + } + + + }; + $scope.getFurtherWebsitesFromDB(); + + $scope.cyberPanelLoading = true; + + $scope.issueSSL = function (virtualHost) { + $scope.cyberPanelLoading = false; + + var url = "/manageSSL/issueSSL"; + + + var data = { + virtualHost: virtualHost }; var config = { @@ -6440,36 +9384,3357 @@ app.controller('listWebsites', function ($scope, $http, $window) { } }; - $http.post('/websites/UpdateWPSettings', data, config).then( - function(response) { - if (response.data.status) { - new PNotify({ - title: 'Success!', - text: 'Password protection enabled successfully', - type: 'success' - }); - $('#Passwordprotection').modal('hide'); - // Clear the credentials - $scope.PPUsername = ''; - $scope.PPPassword = ''; - } else { - $scope.currentWPSite.passwordProtection = false; - new PNotify({ - title: 'Error!', - text: response.data.error_message || 'Failed to enable password protection', - type: 'error' - }); - } - }, - function(response) { - $scope.currentWPSite.passwordProtection = false; + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.cyberPanelLoading = true; + if (response.data.SSL === 1) { new PNotify({ - title: 'Error!', - text: 'Could not connect to server', + title: 'Success!', + text: 'SSL successfully issued.', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, type: 'error' }); } - ); + + } + + function cantLoadInitialDatas(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); + } + + + }; + + $scope.cyberPanelLoading = true; + + $scope.searchWebsites = function () { + + $scope.cyberPanelLoading = false; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + var data = { + patternAdded: $scope.patternAdded + }; + + dataurl = "/websites/searchChilds"; + + $http.post(dataurl, data, config).then(ListInitialData, cantLoadInitialData); + + + function ListInitialData(response) { + $scope.cyberPanelLoading = true; + if (response.data.listWebSiteStatus === 1) { + + var finalData = JSON.parse(response.data.data); + $scope.WebSitesList = finalData; + $("#listFail").hide(); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + } + + function cantLoadInitialData(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Connect disrupted, refresh the page.', + type: 'error' + }); + } + + + }; + + $scope.initConvert = function (virtualHost) { + $scope.domainName = virtualHost; + }; + + var statusFile; + + $scope.installationProgress = true; + + $scope.convert = function () { + + $scope.cyberPanelLoading = false; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.goBackDisable = true; + + $scope.currentStatus = "Starting creation.."; + + var ssl, dkimCheck, openBasedir; + + if ($scope.sslCheck === true) { + ssl = 1; + } else { + ssl = 0 + } + + if ($scope.dkimCheck === true) { + dkimCheck = 1; + } else { + dkimCheck = 0 + } + + if ($scope.openBasedir === true) { + openBasedir = 1; + } else { + openBasedir = 0 + } + + url = "/websites/convertDomainToSite"; + + + var data = { + package: $scope.packageForWebsite, + domainName: $scope.domainName, + adminEmail: $scope.adminEmail, + phpSelection: $scope.phpSelection, + websiteOwner: $scope.websiteOwner, + ssl: ssl, + dkimCheck: dkimCheck, + openBasedir: openBasedir + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.createWebSiteStatus === 1) { + statusFile = response.data.tempStatusPath; + getCreationStatus(); + } else { + + $scope.cyberPanelLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.goBackDisable = false; + + $scope.currentStatus = response.data.error_message; + } + + + } + + function cantLoadInitialDatas(response) { + + $scope.cyberPanelLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.goBackDisable = false; + + } + + + }; + $scope.goBack = function () { + $scope.cyberPanelLoading = true; + $scope.installationDetailsForm = false; + $scope.installationProgress = true; + $scope.goBackDisable = true; + $("#installProgress").css("width", "0%"); + }; + + function getCreationStatus() { + + url = "/websites/installWordpressStatus"; + + var data = { + statusFile: statusFile + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + + if (response.data.abort === 1) { + + if (response.data.installStatus === 1) { + + $scope.cyberPanelLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.goBackDisable = false; + + $("#installProgress").css("width", "100%"); + $scope.installPercentage = "100"; + $scope.currentStatus = response.data.currentStatus; + $timeout.cancel(); + + } else { + + $scope.cyberPanelLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.goBackDisable = false; + + $scope.currentStatus = response.data.error_message; + + $("#installProgress").css("width", "0%"); + $scope.installPercentage = "0"; + $scope.goBackDisable = false; + + } + + } else { + $("#installProgress").css("width", response.data.installationProgress + "%"); + $scope.installPercentage = response.data.installationProgress; + $scope.currentStatus = response.data.currentStatus; + $timeout(getCreationStatus, 1000); + } + + } + + function cantLoadInitialDatas(response) { + + $scope.cyberPanelLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.goBackDisable = false; + + } + + + } + + var DeleteDomain; + $scope.deleteDomainInit = function (childDomainForDeletion) { + DeleteDomain = childDomainForDeletion; + }; + + $scope.deleteChildDomain = function () { + $scope.cyberPanelLoading = false; + url = "/websites/submitDomainDeletion"; + + var data = { + websiteName: DeleteDomain, + DeleteDocRoot: $scope.DeleteDocRoot + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + function ListInitialDatas(response) { + $scope.cyberPanelLoading = true; + if (response.data.websiteDeleteStatus === 1) { + new PNotify({ + title: 'Success!', + text: 'Child Domain successfully deleted.', + type: 'success' + }); + $scope.getFurtherWebsitesFromDB(); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialDatas(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); + + } + + }; + +}); + +/* Java script code to list accounts ends here */ + + +/* Java script code to delete Website */ + + +$("#websiteDeleteFailure").hide(); +$("#websiteDeleteSuccess").hide(); + +$("#deleteWebsiteButton").hide(); +$("#deleteLoading").hide(); + +app.controller('deleteWebsiteControl', function ($scope, $http) { + + + $scope.deleteWebsite = function () { + + $("#deleteWebsiteButton").fadeIn(); + + + }; + + $scope.deleteWebsiteFinal = function () { + + $("#deleteLoading").show(); + + var websiteName = $scope.websiteToBeDeleted; + + + url = "/websites/submitWebsiteDeletion"; + + var data = { + websiteName: websiteName + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.websiteDeleteStatus === 0) { + $scope.errorMessage = response.data.error_message; + $("#websiteDeleteFailure").fadeIn(); + $("#websiteDeleteSuccess").hide(); + $("#deleteWebsiteButton").hide(); + + + $("#deleteLoading").hide(); + + } else { + $("#websiteDeleteFailure").hide(); + $("#websiteDeleteSuccess").fadeIn(); + $("#deleteWebsiteButton").hide(); + $scope.deletedWebsite = websiteName; + $("#deleteLoading").hide(); + + } + + + } + + function cantLoadInitialDatas(response) { + } + + + }; + +}); + + +/** + * Created by usman on 7/26/17. + */ +function getCookie(name) { + var cookieValue = null; + var t = document.cookie; + if (document.cookie && document.cookie !== '') { + var cookies = document.cookie.split(';'); + for (var i = 0; i < cookies.length; i++) { + var cookie = jQuery.trim(cookies[i]); + // Does this cookie string begin with the name we want? + if (cookie.substring(0, name.length + 1) === (name + '=')) { + cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); + break; + } + } + } + return cookieValue; +} + + +var arry = [] + +function selectpluginJs(val) { + $('#mysearch').hide() + arry.push(val) + + // console.log(arry) + document.getElementById('selJS').innerHTML = ""; + + for (var i = 0; i < arry.length; i++) { + $('#selJS').show() + var mlm = ' ' + arry[i] + '    ' + $('#selJS').append(mlm) + } + + +} + + +var DeletePluginURL; + +function DeletePluginBuucket(url) { + DeletePluginURL = url; +} + +function FinalDeletePluginBuucket() { + window.location.href = DeletePluginURL; +} + +var SPVal; + +app.controller('WPAddNewPlugin', function ($scope, $http, $timeout, $window, $compile) { + $scope.webSiteCreationLoading = true; + + $scope.SearchPluginName = function (val) { + $scope.webSiteCreationLoading = false; + SPVal = val; + url = "/websites/SearchOnkeyupPlugin"; + + var searchcontent = $scope.searchcontent; + + + var data = { + pluginname: searchcontent + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.webSiteCreationLoading = true; + + if (response.data.status === 1) { + if (SPVal == 'add') { + $('#mysearch').show() + document.getElementById('mysearch').innerHTML = ""; + var res = response.data.plugns.plugins + // console.log(res); + for (i = 0; i <= res.length; i++) { + // + var tml = '
    '; + $('#mysearch').append(tml); + } + } else if (SPVal == 'eidt') { + $('#mysearch').show() + document.getElementById('mysearch').innerHTML = ""; + var res = response.data.plugns.plugins + // console.log(res); + for (i = 0; i <= res.length; i++) { + // + var tml = '
    '; + var temp = $compile(tml)($scope) + angular.element(document.getElementById('mysearch')).append(temp); + } + + } + + + } else { + + // $scope.errorMessage = response.data.error_message; + alert("Status not = 1: Error..." + response.data.error_message) + } + + + } + + function cantLoadInitialDatas(response) { + + alert("Error..." + response) + + } + } + + $scope.AddNewplugin = function () { + + url = "/websites/AddNewpluginAjax"; + + var bucketname = $scope.PluginbucketName + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + var data = { + config: arry, + Name: bucketname + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + function ListInitialDatas(response) { + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Bucket created.', + type: 'success' + }); + location.reload(); + } else { + + new PNotify({ + title: 'Error!', + text: response.data.error_message, + type: 'error' + }); + } + + + } + + function cantLoadInitialDatas(response) { + + alert("Error..." + response) + + } + } + + $scope.deletesPlgin = function (val) { + + url = "/websites/deletesPlgin"; + + + var data = { + pluginname: val, + pluginbBucketID: $('#pluginbID').html() + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.status === 1) { + location.reload(); + + } else { + + // $scope.errorMessage = response.data.error_message; + alert("Status not = 1: Error..." + response.data.error_message) + } + + + } + + function cantLoadInitialDatas(response) { + + alert("Error..." + response) + + } + + } + + $scope.Addplugin = function (slug) { + $('#mysearch').hide() + + url = "/websites/Addplugineidt"; + + + var data = { + pluginname: slug, + pluginbBucketID: $('#pluginbID').html() + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.status === 1) { + location.reload(); + + } else { + + // $scope.errorMessage = response.data.error_message; + alert("Status not = 1: Error..." + response.data.error_message) + } + + + } + + function cantLoadInitialDatas(response) { + + alert("Error..." + response) + + } + + + } + +}); + +var domain_check = 0; + +function checkbox_function() { + + var checkBox = document.getElementById("myCheck"); + // Get the output text + + + // If the checkbox is checked, display the output text + if (checkBox.checked == true) { + domain_check = 0; + document.getElementById('Test_Domain').style.display = "block"; + document.getElementById('Own_Domain').style.display = "none"; + + } else { + document.getElementById('Test_Domain').style.display = "none"; + document.getElementById('Own_Domain').style.display = "block"; + domain_check = 1; + } + + // alert(domain_check); +} + +app.controller('createWordpress', function ($scope, $http, $timeout, $compile, $window) { + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = false; + $scope.installationProgress = true; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + + + var statusFile; + + $scope.createWordPresssite = function () { + + $scope.webSiteCreationLoading = false; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + + + $scope.currentStatus = "Starting creation.."; + + var apacheBackend = 0; + + if ($scope.apacheBackend === true) { + apacheBackend = 1; + } else { + apacheBackend = 0 + } + + var package = $scope.packageForWebsite; + var websiteOwner = $scope.websiteOwner; + var WPtitle = $scope.WPtitle; + + // if (domain_check == 0) { + // var Part2_domainNameCreate = document.getElementById('Part2_domainNameCreate').value; + // var domainNameCreate = document.getElementById('TestDomainNameCreate').value + Part2_domainNameCreate; + // } + // if (domain_check == 1) { + // + // var domainNameCreate = $scope.own_domainNameCreate; + // } + + var domainNameCreate = $scope.domainNameCreate; + + + var WPUsername = $scope.WPUsername; + var adminEmail = $scope.adminEmail; + var WPPassword = $scope.WPPassword; + var WPVersions = $scope.WPVersions; + var pluginbucket = $scope.pluginbucket; + var autoupdates = $scope.autoupdates; + var pluginupdates = $scope.pluginupdates; + var themeupdates = $scope.themeupdates; + + if (domain_check == 0) { + + var path = ""; + + } + if (domain_check = 1) { + + var path = $scope.installPath; + + } + + + var home = "1"; + + if (typeof path != 'undefined') { + home = "0"; + } + + //alert(domainNameCreate); + var data = { + + title: WPtitle, + domain: domainNameCreate, + WPVersion: WPVersions, + pluginbucket: pluginbucket, + adminUser: WPUsername, + Email: adminEmail, + PasswordByPass: WPPassword, + AutomaticUpdates: autoupdates, + Plugins: pluginupdates, + Themes: themeupdates, + websiteOwner: websiteOwner, + package: package, + home: home, + path: path, + apacheBackend: apacheBackend + } + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + var url = "/websites/submitWorpressCreation"; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.webSiteCreationLoading = true; + if (response.data.status === 1) { + statusFile = response.data.tempStatusPath; + getCreationStatus(); + + } else { + $scope.goBackDisable = false; + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + + } + + function cantLoadInitialDatas(response) { + + alert("Error..." + response) + + } + + }; + $scope.goBack = function () { + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = false; + $scope.installationProgress = true; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + $("#installProgress").css("width", "0%"); + }; + + function getCreationStatus() { + + url = "/websites/installWordpressStatus"; + + var data = { + statusFile: statusFile + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.abort === 1) { + + if (response.data.installStatus === 1) { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = false; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $("#installProgress").css("width", "100%"); + $scope.installPercentage = "100"; + $scope.currentStatus = response.data.currentStatus; + $timeout.cancel(); + + } else { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = false; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $scope.errorMessage = response.data.error_message; + + $("#installProgress").css("width", "0%"); + $scope.installPercentage = "0"; + $scope.goBackDisable = false; + + } + + } else { + $scope.webSiteCreationLoading = false; + $("#installProgress").css("width", response.data.installationProgress + "%"); + $scope.installPercentage = response.data.installationProgress; + $scope.currentStatus = response.data.currentStatus; + $timeout(getCreationStatus, 1000); + } + + } + + function cantLoadInitialDatas(response) { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = false; + $scope.goBackDisable = false; + + } + + + } + + +}); + + +//........... delete wp list +var FurlDeleteWP; + +function DeleteWPNow(url) { + FurlDeleteWP = url; +} + +function FinalDeleteWPNow() { + window.location.href = FurlDeleteWP; +} + +var DeploytoProductionID; + +function DeployToProductionInitial(vall) { + DeploytoProductionID = vall; +} + +var create_staging_domain_check = 0; + +function create_staging_checkbox_function() { + + try { + + var checkBox = document.getElementById("Create_Staging_Check"); + // Get the output text + + + // If the checkbox is checked, display the output text + if (checkBox.checked == true) { + create_staging_domain_check = 0; + document.getElementById('Website_Create_Test_Domain').style.display = "block"; + document.getElementById('Website_Create_Own_Domain').style.display = "none"; + + } else { + document.getElementById('Website_Create_Test_Domain').style.display = "none"; + document.getElementById('Website_Create_Own_Domain').style.display = "block"; + create_staging_domain_check = 1; + } + } catch (e) { + + } + + // alert(domain_check); +} + +create_staging_checkbox_function(); + +app.controller('WPsiteHome', function ($scope, $http, $timeout, $compile, $window) { + + var CheckBoxpasssword = 0; + + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = false; + $scope.installationProgress = true; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + $(document).ready(function () { + var checkstatus = document.getElementById("wordpresshome"); + if (checkstatus !== null) { + $scope.LoadWPdata(); + + } + }); + + + $scope.LoadWPdata = function () { + + $scope.wordpresshomeloading = false; + $('#wordpresshomeloading').show(); + + var url = "/websites/FetchWPdata"; + + var data = { + WPid: $('#WPid').html(), + } + + console.log(data); + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + wordpresshomeloading = true; + $('#wordpresshomeloading').hide(); + + if (response.data.status === 1) { + $('#WPVersion').text(response.data.ret_data.version); + if (response.data.ret_data.lscache === 1) { + $('#lscache').prop('checked', true); + } + if (response.data.ret_data.debugging === 1) { + $('#debugging').prop('checked', true); + } + if (response.data.ret_data.searchIndex === 1) { + $('#searchIndex').prop('checked', true); + } + if (response.data.ret_data.maintenanceMode === 1) { + $('#maintenanceMode').prop('checked', true); + } + if (response.data.ret_data.wpcron === 1) { + $('#wpcron').prop('checked', true); + } + if (response.data.ret_data.passwordprotection == 1) { + + var dc = '\n' + + ' ' + var mp = $compile(dc)($scope); + angular.element(document.getElementById('prsswdprodata')).append(mp); + CheckBoxpasssword = 1; + } else if (response.data.ret_data.passwordprotection == 0) { + var dc = '\n' + + ' ' + $('#prsswdprodata').append(dc); + CheckBoxpasssword = 0; + } + + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = false; + $scope.goBackDisable = false; + + } + + + }; + + $scope.UpdateWPSettings = function (setting) { + + $scope.wordpresshomeloading = false; + $('#wordpresshomeloading').show(); + + + var url = "/websites/UpdateWPSettings"; + + if (setting === "PasswordProtection") { + if (CheckBoxpasssword == 0) { + var data = { + WPid: $('#WPid').html(), + setting: setting, + PPUsername: $scope.PPUsername, + PPPassword: $scope.PPPassword, + } + + } else { + var data = { + WPid: $('#WPid').html(), + setting: setting, + PPUsername: '', + PPPassword: '', + } + + } + + } else { + var settingValue = 0; + if ($('#' + setting).is(":checked")) { + settingValue = 1; + } + var data = { + WPid: $('#WPid').html(), + setting: setting, + settingValue: settingValue + } + } + + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.wordpresshomeloading = true; + $('#wordpresshomeloading').hide(); + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Successfully Updated!.', + type: 'success' + }); + if (setting === "PasswordProtection") { + location.reload(); + } + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + if (setting === "PasswordProtection") { + location.reload(); + } + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + + + }; + + $scope.GetCurrentPlugins = function () { + $('#wordpresshomeloading').show(); + + $scope.wordpresshomeloading = false; + + var url = "/websites/GetCurrentPlugins"; + + var data = { + WPid: $('#WPid').html(), + } + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + wordpresshomeloading = true; + $('#wordpresshomeloading').hide(); + + if (response.data.status === 1) { + $('#PluginBody').html(''); + var plugins = JSON.parse(response.data.plugins); + plugins.forEach(AddPlugins); + + } else { + alert("Error:" + response.data.error_message) + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = false; + $scope.goBackDisable = false; + + } + + + }; + + $scope.GetCurrentThemes = function () { + $('#wordpresshomeloading').show(); + + $scope.wordpresshomeloading = false; + + var url = "/websites/GetCurrentThemes"; + + var data = { + WPid: $('#WPid').html(), + } + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + wordpresshomeloading = true; + $('#wordpresshomeloading').hide(); + + if (response.data.status === 1) { + + $('#ThemeBody').html(''); + var themes = JSON.parse(response.data.themes); + themes.forEach(AddThemes); + + } else { + alert("Error:" + response.data.error_message) + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = false; + $scope.goBackDisable = false; + + } + + + }; + + $scope.UpdatePlugins = function (plugin) { + $('#wordpresshomeloading').show(); + var data = { + plugin: plugin, + pluginarray: PluginsList, + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/UpdatePlugins"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Updating Plugins in Background!.', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + + + }; + + $scope.DeletePlugins = function (plugin) { + $('#wordpresshomeloading').show(); + var data = { + plugin: plugin, + pluginarray: PluginsList, + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/DeletePlugins"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Deleting Plugin in Background!', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + + } + + $scope.ChangeStatus = function (plugin) { + $('#wordpresshomeloading').show(); + var data = { + plugin: plugin, + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/ChangeStatus"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Changed Plugin state Successfully !.', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + + } + + function AddPlugins(value, index, array) { + var FinalMarkup = '' + FinalMarkup = FinalMarkup + ''; + for (let x in value) { + if (x === 'status') { + if (value[x] === 'inactive') { + FinalMarkup = FinalMarkup + '
    '; + } else { + FinalMarkup = FinalMarkup + '
    '; + } + } else if (x === 'update') { + if (value[x] === 'none') { + FinalMarkup = FinalMarkup + 'Upto Date'; + } else { + FinalMarkup = FinalMarkup + ''; + } + } else { + FinalMarkup = FinalMarkup + '' + value[x] + ""; + } + } + FinalMarkup = FinalMarkup + '' + FinalMarkup = FinalMarkup + '' + var temp = $compile(FinalMarkup)($scope) + AppendToTable('#PluginBody', temp) + } + + $scope.UpdateThemes = function (theme) { + $('#wordpresshomeloading').show(); + var data = { + Theme: theme, + Themearray: ThemesList, + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/UpdateThemes"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Updating Theme in background !.', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + + + }; + + $scope.DeleteThemes = function (theme) { + $('#wordpresshomeloading').show(); + var data = { + Theme: theme, + Themearray: ThemesList, + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/DeleteThemes"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Deleting Theme in Background!.', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + }; + + $scope.ChangeStatusThemes = function (theme) { + $('#wordpresshomeloading').show(); + var data = { + theme: theme, + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/StatusThemes"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Change Theme state in Bsckground!.', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + + }; + + function AddThemes(value, index, array) { + var FinalMarkup = '' + FinalMarkup = FinalMarkup + ''; + for (let x in value) { + if (x === 'status') { + if (value[x] === 'inactive') { + FinalMarkup = FinalMarkup + '
    '; + } else { + FinalMarkup = FinalMarkup + '
    '; + } + } else if (x === 'update') { + if (value[x] === 'none') { + FinalMarkup = FinalMarkup + 'Upto Date'; + } else { + FinalMarkup = FinalMarkup + ''; + } + } else { + FinalMarkup = FinalMarkup + '' + value[x] + ""; + } + } + FinalMarkup = FinalMarkup + '' + FinalMarkup = FinalMarkup + '' + var temp = $compile(FinalMarkup)($scope) + AppendToTable('#ThemeBody', temp) + } + + $scope.CreateStagingNow = function () { + $('#wordpresshomeloading').show(); + + $scope.wordpresshomeloading = false; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + + + $scope.currentStatus = "Starting creation Staging.."; + + //here enter domain name + if (create_staging_domain_check == 0) { + var Part2_domainNameCreate = document.getElementById('Part2_domainNameCreate').value; + var domainNameCreate = document.getElementById('TestDomainNameCreate').value + Part2_domainNameCreate; + } + if (create_staging_domain_check == 1) { + + var domainNameCreate = $scope.own_domainNameCreate; + } + var data = { + StagingName: $('#stagingName').val(), + StagingDomain: domainNameCreate, + WPid: $('#WPid').html(), + } + var url = "/websites/CreateStagingNow"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + if (response.data.status === 1) { + statusFile = response.data.tempStatusPath; + getCreationStatus(); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + }; + + function getCreationStatus() { + $('#wordpresshomeloading').show(); + + url = "/websites/installWordpressStatus"; + + var data = { + statusFile: statusFile + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + //$('#wordpresshomeloading').hide(); + + if (response.data.abort === 1) { + if (response.data.installStatus === 1) { + + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = false; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + + $("#installProgress").css("width", "100%"); + $("#installProgressbackup").css("width", "100%"); + $scope.installPercentage = "100"; + $scope.currentStatus = response.data.currentStatus; + $timeout.cancel(); + + + } else { + + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = false; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $scope.errorMessage = response.data.error_message; + + $("#installProgress").css("width", "0%"); + $("#installProgressbackup").css("width", "0%"); + $scope.installPercentage = "0"; + $scope.goBackDisable = false; + + + } + + } else { + + $("#installProgress").css("width", response.data.installationProgress + "%"); + $("#installProgressbackup").css("width", response.data.installationProgress + "%"); + $scope.installPercentage = response.data.installationProgress; + $scope.currentStatus = response.data.currentStatus; + $timeout(getCreationStatus, 1000); + + } + + } + + function cantLoadInitialDatas(response) { + //$('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = false; + $scope.goBackDisable = false; + + } + + + } + + $scope.goBack = function () { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = false; + $scope.installationProgress = true; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + $("#installProgress").css("width", "0%"); + }; + + $scope.fetchstaging = function () { + + $('#wordpresshomeloading').show(); + $scope.wordpresshomeloading = false; + + var url = "/websites/fetchstaging"; + + var data = { + WPid: $('#WPid').html(), + } + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + wordpresshomeloading = true; + $('#wordpresshomeloading').hide(); + + if (response.data.status === 1) { + + // $('#ThemeBody').html(''); + // var themes = JSON.parse(response.data.themes); + // themes.forEach(AddThemes); + + $('#StagingBody').html(''); + var staging = JSON.parse(response.data.wpsites); + staging.forEach(AddStagings); + + } else { + alert("Error data.error_message:" + response.data.error_message) + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + alert("Error" + response) + + } + + }; + + $scope.fetchDatabase = function () { + + $('#wordpresshomeloading').show(); + $scope.wordpresshomeloading = false; + + var url = "/websites/fetchDatabase"; + + var data = { + WPid: $('#WPid').html(), + } + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + wordpresshomeloading = true; + $('#wordpresshomeloading').hide(); + + if (response.data.status === 1) { + $('#DB_Name').html(response.data.DataBaseName); + $('#DB_User').html(response.data.DataBaseUser); + $('#tableprefix').html(response.data.tableprefix); + } else { + alert("Error data.error_message:" + response.data.error_message) + + } + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + alert("Error" + response) + + } + + }; + + $scope.SaveUpdateConfig = function () { + $('#wordpresshomeloading').show(); + var data = { + AutomaticUpdates: $('#AutomaticUpdates').find(":selected").text(), + Plugins: $('#Plugins').find(":selected").text(), + Themes: $('#Themes').find(":selected").text(), + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/SaveUpdateConfig"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Update Configurations Sucessfully!.', + type: 'success' + }); + $("#autoUpdateConfig").modal('hide'); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + new PNotify({ + title: 'Operation Failed!', + text: response, + type: 'error' + }); + + } + }; + + function AddStagings(value, index, array) { + var FinalMarkup = '' + for (let x in value) { + if (x === 'name') { + FinalMarkup = FinalMarkup + '' + value[x] + ''; + } else if (x !== 'url' && x !== 'deleteURL' && x !== 'id') { + FinalMarkup = FinalMarkup + '' + value[x] + ""; + } + } + FinalMarkup = FinalMarkup + '' + + ' ' + FinalMarkup = FinalMarkup + '' + AppendToTable('#StagingBody', FinalMarkup); + } + + $scope.FinalDeployToProduction = function () { + + $('#wordpresshomeloading').show(); + + $scope.wordpresshomeloading = false; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + + var data = { + WPid: $('#WPid').html(), + StagingID: DeploytoProductionID + } + + var url = "/websites/DeploytoProduction"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + function ListInitialDatas(response) { + + $('#wordpresshomeloading').hide(); + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Deploy To Production start!.', + type: 'success' + }); + statusFile = response.data.tempStatusPath; + getCreationStatus(); + + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + new PNotify({ + title: 'Operation Failed!', + text: response, + type: 'error' + }); + + } + + }; + + + $scope.CreateBackup = function () { + $('#wordpresshomeloading').show(); + + $scope.wordpresshomeloading = false; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + $scope.currentStatus = "Starting creation Backups.."; + var data = { + WPid: $('#WPid').html(), + Backuptype: $('#backuptype').val() + } + var url = "/websites/WPCreateBackup"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $('createbackupbutton').hide(); + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Creating Backups!.', + type: 'success' + }); + statusFile = response.data.tempStatusPath; + getCreationStatus(); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + alert(response) + + } + + }; + + + $scope.installwpcore = function () { + + $('#wordpresshomeloading').show(); + $('#wordpresshomeloadingsec').show(); + var data = { + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/installwpcore"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $('#wordpresshomeloadingsec').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Results fetched..', + type: 'success' + }); + $('#SecurityResult').html(response.data.result); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $('#wordpresshomeloadingsec').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + + }; + + $scope.dataintegrity = function () { + + $('#wordpresshomeloading').show(); + $('#wordpresshomeloadingsec').show(); + var data = { + WPid: $('#WPid').html(), + } + + $scope.wordpresshomeloading = false; + + var url = "/websites/dataintegrity"; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $('#wordpresshomeloadingsec').hide(); + $scope.wordpresshomeloading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Results fetched', + type: 'success' + }); + $('#SecurityResult').html(response.data.result); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + $('#wordpresshomeloadingsec').hide(); + $scope.wordpresshomeloading = true; + alert(response) + + } + }; + +}); + + +var PluginsList = []; + + +function AddPluginToArray(cBox, name) { + if (cBox.checked) { + PluginsList.push(name); + // alert(PluginsList); + } else { + const index = PluginsList.indexOf(name); + if (index > -1) { + PluginsList.splice(index, 1); + } + // alert(PluginsList); + } +} + +var ThemesList = []; + +function AddThemeToArray(cBox, name) { + if (cBox.checked) { + ThemesList.push(name); + // alert(ThemesList); + } else { + const index = ThemesList.indexOf(name); + if (index > -1) { + ThemesList.splice(index, 1); + } + // alert(ThemesList); + } +} + + +function AppendToTable(table, markup) { + $(table).append(markup); +} + + +//..................Restore Backup Home + + +app.controller('RestoreWPBackup', function ($scope, $http, $timeout, $window) { + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = false; + $scope.installationProgress = true; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + + + $scope.checkmethode = function () { + var val = $('#RestoreMethode').children("option:selected").val(); + if (val == 1) { + $('#Newsitediv').show(); + $('#exinstingsitediv').hide(); + } else if (val == 0) { + $('#exinstingsitediv').show(); + $('#Newsitediv').hide(); + } else { + + } + }; + + + $scope.RestoreWPbackupNow = function () { + $('#wordpresshomeloading').show(); + $scope.wordpresshomeloading = false; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + $scope.currentStatus = "Start Restoring WordPress.."; + + var Domain = $('#wprestoresubdirdomain').val() + var path = $('#wprestoresubdirpath').val(); + var home = "1"; + + if (typeof path != 'undefined' || path != '') { + home = "0"; + } + if (typeof path == 'undefined') { + path = ""; + } + + + var backuptype = $('#backuptype').html(); + var data; + if (backuptype == "DataBase Backup") { + data = { + backupid: $('#backupid').html(), + DesSite: $('#DesSite').children("option:selected").val(), + Domain: '', + path: path, + home: home, + } + } else { + data = { + backupid: $('#backupid').html(), + DesSite: $('#DesSite').children("option:selected").val(), + Domain: Domain, + path: path, + home: home, + } + + } + + var url = "/websites/RestoreWPbackupNow"; + + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + // console.log(data) + + var d = $('#DesSite').children("option:selected").val(); + var c = $("input[name=Newdomain]").val(); + // if (d == -1 || c == "") { + // alert("Please Select Method of Backup Restore"); + // } else { + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + // } + + + function ListInitialDatas(response) { + wordpresshomeloading = true; + $('#wordpresshomeloading').hide(); + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Restoring process starts!.', + type: 'success' + }); + statusFile = response.data.tempStatusPath; + getCreationStatus(); + + } else { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = false; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $scope.errorMessage = response.data.error_message; + + } + + } + + function cantLoadInitialDatas(response) { + $('#wordpresshomeloading').hide(); + + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + + } + } + + function getCreationStatus() { + $('#wordpresshomeloading').show(); + + url = "/websites/installWordpressStatus"; + + var data = { + statusFile: statusFile + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + //$('#wordpresshomeloading').hide(); + + if (response.data.abort === 1) { + + if (response.data.installStatus === 1) { + + + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = false; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + + $("#installProgress").css("width", "100%"); + $("#installProgressbackup").css("width", "100%"); + $scope.installPercentage = "100"; + $scope.currentStatus = response.data.currentStatus; + $timeout.cancel(); + + + } else { + + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = false; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $scope.errorMessage = response.data.error_message; + + $("#installProgress").css("width", "0%"); + $("#installProgressbackup").css("width", "0%"); + $scope.installPercentage = "0"; + $scope.goBackDisable = false; + + + } + + } else { + + $("#installProgress").css("width", response.data.installationProgress + "%"); + $("#installProgressbackup").css("width", response.data.installationProgress + "%"); + $scope.installPercentage = response.data.installationProgress; + $scope.currentStatus = response.data.currentStatus; + $timeout(getCreationStatus, 1000); + + } + + } + + function cantLoadInitialDatas(response) { + //$('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = false; + $scope.goBackDisable = false; + + } + + + } + + $scope.goBack = function () { + $('#wordpresshomeloading').hide(); + $scope.wordpresshomeloading = true; + $scope.stagingDetailsForm = false; + $scope.installationProgress = true; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + $("#installProgress").css("width", "0%"); + }; +}); + + +//.......................................Remote Backup + +//........... delete DeleteBackupConfigNow + +function DeleteBackupConfigNow(url) { + window.location.href = url; +} + +function DeleteRemoteBackupsiteNow(url) { + window.location.href = url; +} + +function DeleteBackupfileConfigNow(url) { + window.location.href = url; +} + + +app.controller('RemoteBackupConfig', function ($scope, $http, $timeout, $window) { + $scope.RemoteBackupLoading = true; + $scope.SFTPBackUpdiv = true; + + $scope.EndpointURLdiv = true; + $scope.Selectprovider = true; + $scope.S3keyNamediv = true; + $scope.Accesskeydiv = true; + $scope.SecretKeydiv = true; + $scope.SelectRemoteBackuptype = function () { + var val = $scope.RemoteBackuptype; + if (val == "SFTP") { + $scope.SFTPBackUpdiv = false; + $scope.EndpointURLdiv = true; + $scope.Selectprovider = true; + $scope.S3keyNamediv = true; + $scope.Accesskeydiv = true; + $scope.SecretKeydiv = true; + } else if (val == "S3") { + $scope.EndpointURLdiv = true; + $scope.Selectprovider = false; + $scope.S3keyNamediv = false; + $scope.Accesskeydiv = false; + $scope.SecretKeydiv = false; + $scope.SFTPBackUpdiv = true; + } else { + $scope.RemoteBackupLoading = true; + $scope.SFTPBackUpdiv = true; + + $scope.EndpointURLdiv = true; + $scope.Selectprovider = true; + $scope.S3keyNamediv = true; + $scope.Accesskeydiv = true; + $scope.SecretKeydiv = true; + } + } + + $scope.SelectProvidertype = function () { + $scope.EndpointURLdiv = true; + var provider = $scope.Providervalue + if (provider == 'Backblaze') { + $scope.EndpointURLdiv = false; + } else { + $scope.EndpointURLdiv = true; + } + } + + $scope.SaveBackupConfig = function () { + $scope.RemoteBackupLoading = false; + var Hname = $scope.Hostname; + var Uname = $scope.Username; + var Passwd = $scope.Password; + var path = $scope.path; + var type = $scope.RemoteBackuptype; + var Providervalue = $scope.Providervalue; + var data; + if (type == "SFTP") { + + data = { + Hname: Hname, + Uname: Uname, + Passwd: Passwd, + path: path, + type: type + } + } else if (type == "S3") { + if (Providervalue == "Backblaze") { + data = { + S3keyname: $scope.S3keyName, + Provider: Providervalue, + AccessKey: $scope.Accesskey, + SecertKey: $scope.SecretKey, + EndUrl: $scope.EndpointURL, + type: type + } + } else { + data = { + S3keyname: $scope.S3keyName, + Provider: Providervalue, + AccessKey: $scope.Accesskey, + SecertKey: $scope.SecretKey, + type: type + } + + } + + } + var url = "/websites/SaveBackupConfig"; + + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.RemoteBackupLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Successfully Saved!.', + type: 'success' + }); + location.reload(); + + + } else { + new PNotify({ + title: 'Error!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialDatas(response) { + $scope.RemoteBackupLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + + } + + + } + +}); + +var UpdatescheduleID; +app.controller('BackupSchedule', function ($scope, $http, $timeout, $window) { + $scope.BackupScheduleLoading = true; + $scope.SaveBackupSchedule = function () { + $scope.RemoteBackupLoading = false; + var FileRetention = $scope.Fretention; + var Backfrequency = $scope.Bfrequency; + + + var data = { + FileRetention: FileRetention, + Backfrequency: Backfrequency, + ScheduleName: $scope.ScheduleName, + RemoteConfigID: $('#RemoteConfigID').html(), + BackupType: $scope.BackupType + } + var url = "/websites/SaveBackupSchedule"; + + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.RemoteBackupLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Successfully Saved!.', + type: 'success' + }); + location.reload(); + + + } else { + new PNotify({ + title: 'Error!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialDatas(response) { + $scope.RemoteBackupLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + + } + + + }; + + + $scope.getupdateid = function (ID) { + UpdatescheduleID = ID; + } + + $scope.UpdateRemoteschedules = function () { + $scope.RemoteBackupLoading = false; + var Frequency = $scope.RemoteFrequency; + var fretention = $scope.RemoteFileretention; + + var data = { + ScheduleID: UpdatescheduleID, + Frequency: Frequency, + FileRetention: fretention + } + var url = "/websites/UpdateRemoteschedules"; + + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.RemoteBackupLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Successfully Updated!.', + type: 'success' + }); + location.reload(); + + + } else { + new PNotify({ + title: 'Error!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialDatas(response) { + $scope.RemoteBackupLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + + } + }; + + $scope.AddWPsiteforRemoteBackup = function () { + $scope.RemoteBackupLoading = false; + + + var data = { + WpsiteID: $('#Wpsite').val(), + RemoteScheduleID: $('#RemoteScheduleID').html() + } + var url = "/websites/AddWPsiteforRemoteBackup"; + + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.RemoteBackupLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Successfully Saved!.', + type: 'success' + }); + location.reload(); + + + } else { + new PNotify({ + title: 'Error!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialDatas(response) { + $scope.RemoteBackupLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + + } + + + }; +}); +/* Java script code to create account */ + +var website_create_domain_check = 0; + +function website_create_checkbox_function() { + + var checkBox = document.getElementById("myCheck"); + // Get the output text + + + // If the checkbox is checked, display the output text + if (checkBox.checked == true) { + website_create_domain_check = 0; + document.getElementById('Website_Create_Test_Domain').style.display = "block"; + document.getElementById('Website_Create_Own_Domain').style.display = "none"; + + } else { + document.getElementById('Website_Create_Test_Domain').style.display = "none"; + document.getElementById('Website_Create_Own_Domain').style.display = "block"; + website_create_domain_check = 1; + } + + // alert(domain_check); +} + +app.controller('createWebsite', function ($scope, $http, $timeout, $window) { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = false; + $scope.installationProgress = true; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + + var statusFile; + + $scope.createWebsite = function () { + + $scope.webSiteCreationLoading = false; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + + $scope.currentStatus = "Starting creation.."; + + var ssl, dkimCheck, openBasedir, mailDomain, apacheBackend; + + if ($scope.sslCheck === true) { + ssl = 1; + } else { + ssl = 0 + } + + if ($scope.apacheBackend === true) { + apacheBackend = 1; + } else { + apacheBackend = 0 + } + + if ($scope.dkimCheck === true) { + dkimCheck = 1; + } else { + dkimCheck = 0 + } + + if ($scope.openBasedir === true) { + openBasedir = 1; + } else { + openBasedir = 0 + } + + if ($scope.mailDomain === true) { + mailDomain = 1; + } else { + mailDomain = 0 + } + + + url = "/websites/submitWebsiteCreation"; + + var package = $scope.packageForWebsite; + + // if (website_create_domain_check == 0) { + // var Part2_domainNameCreate = document.getElementById('Part2_domainNameCreate').value; + // var domainName = document.getElementById('TestDomainNameCreate').value + Part2_domainNameCreate; + // } + // if (website_create_domain_check == 1) { + // + // var domainName = $scope.domainNameCreate; + // } + var domainName = $scope.domainNameCreate; + + // var domainName = $scope.domainNameCreate; + + var adminEmail = $scope.adminEmail; + var phpSelection = $scope.phpSelection; + var websiteOwner = $scope.websiteOwner; + + + var data = { + package: package, + domainName: domainName, + adminEmail: adminEmail, + phpSelection: phpSelection, + ssl: ssl, + websiteOwner: websiteOwner, + dkimCheck: dkimCheck, + openBasedir: openBasedir, + mailDomain: mailDomain, + apacheBackend: apacheBackend + }; + + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.createWebSiteStatus === 1) { + statusFile = response.data.tempStatusPath; + getCreationStatus(); + } else { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = false; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $scope.errorMessage = response.data.error_message; + } + + + } + + function cantLoadInitialDatas(response) { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = false; + $scope.goBackDisable = false; + + } + + + }; + $scope.goBack = function () { + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = false; + $scope.installationProgress = true; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = true; + $("#installProgress").css("width", "0%"); + }; + + function getCreationStatus() { + + url = "/websites/installWordpressStatus"; + + var data = { + statusFile: statusFile + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + + if (response.data.abort === 1) { + + if (response.data.installStatus === 1) { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = false; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $("#installProgress").css("width", "100%"); + $scope.installPercentage = "100"; + $scope.currentStatus = response.data.currentStatus; + $timeout.cancel(); + + } else { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = false; + $scope.success = true; + $scope.couldNotConnect = true; + $scope.goBackDisable = false; + + $scope.errorMessage = response.data.error_message; + + $("#installProgress").css("width", "0%"); + $scope.installPercentage = "0"; + $scope.goBackDisable = false; + + } + + } else { + $("#installProgress").css("width", response.data.installationProgress + "%"); + $scope.installPercentage = response.data.installationProgress; + $scope.currentStatus = response.data.currentStatus; + $timeout(getCreationStatus, 1000); + } + + } + + function cantLoadInitialDatas(response) { + + $scope.webSiteCreationLoading = true; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.errorMessageBox = true; + $scope.success = true; + $scope.couldNotConnect = false; + $scope.goBackDisable = false; + + } + + + } + +}); +/* Java script code to create account ends here */ + +/* Java script code to list accounts */ + +$("#listFail").hide(); + + +app.controller('listWebsites', function ($scope, $http, $window) { + $scope.web = {}; + $scope.WebSitesList = []; + + $scope.currentPage = 1; + $scope.recordsToShow = 10; + + // Initial fetch of websites + $scope.getFurtherWebsitesFromDB = function () { + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + var data = { + page: $scope.currentPage, + recordsToShow: $scope.recordsToShow + }; + + var dataurl = "/websites/fetchWebsitesList"; + + $http.post(dataurl, data, config).then(function(response) { + if (response.data.listWebSiteStatus === 1) { + $scope.WebSitesList = JSON.parse(response.data.data); + $scope.pagination = response.data.pagination; + $("#listFail").hide(); + } else { + $("#listFail").fadeIn(); + $scope.errorMessage = response.data.error_message; + } + }).catch(function(error) { + $("#listFail").fadeIn(); + $scope.errorMessage = error.message || 'An error occurred while fetching websites'; + }); + }; + + // Call it immediately + $scope.getFurtherWebsitesFromDB(); + + $scope.showWPSites = function(domain) { + console.log('showWPSites called for domain:', domain); + + // Make sure domain is defined + if (!domain) { + console.error('Domain is undefined'); + return; + } + + var url = '/websites/fetchWPDetails'; + var data = { + domain: domain + }; + + console.log('Making request to:', url, 'with data:', data); + + $http({ + method: 'POST', + url: url, + data: $.param(data), + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'X-CSRFToken': getCookie('csrftoken') + } + }).then(function(response) { + console.log('Response received:', response); + if (response.data.status === 1 && response.data.fetchStatus === 1) { + // Find the website in the list and update its properties + $scope.WebSitesList.forEach(function(website) { + if (website.domain === domain) { + website.wp_sites = response.data.sites; + website.showWPSites = true; + console.log('Updated website:', website); + } + }); + $("#listFail").hide(); + } else { + $("#listFail").fadeIn(); + $scope.errorMessage = response.data.error_message || 'Failed to fetch WordPress sites'; + console.error('Error in response:', response.data.error_message); + } + }).catch(function(error) { + $("#listFail").fadeIn(); + $scope.errorMessage = error.message || 'An error occurred while fetching WordPress sites'; + console.error('Request failed:', error); + }); + }; + + $scope.visitSite = function(url) { + window.open(url, '_blank'); + }; + + $scope.wpLogin = function(wpId) { + window.open('/websites/wpLogin?wpID=' + wpId, '_blank'); + }; + + $scope.manageWP = function(wpId) { + window.location.href = '/websites/listWPsites?wpID=' + wpId; + }; + + $scope.currentWP = null; + $scope.PPUsername = ''; + $scope.PPPassword = ''; + + $scope.togglePasswordProtection = function(wp) { + if (!wp.passwordProtection) { + // Show password protection modal + $('#Passwordprotection').modal('show'); + $scope.currentWP = wp; + } else { + // Disable password protection + $scope.updateSetting(wp, 'password-protection', 0); + } + }; + + $scope.enablePasswordProtection = function() { + if (!$scope.PPUsername || !$scope.PPPassword) { + new PNotify({ + title: 'Error!', + text: 'Username and password are required.', + type: 'error' + }); + return; + } + + $scope.updateSetting($scope.currentWP, 'password-protection', 1); + $('#Passwordprotection').modal('hide'); + }; + + $scope.updateSetting = function(wp, setting, value) { + var data = { + WPid: wp.id, + setting: setting, + value: value + }; + + if (setting === 'password-protection' && value === 1) { + data.PPUsername = $scope.PPUsername; + data.PPPassword = $scope.PPPassword; + } + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post('/websites/UpdateWPSettings', data, config).then(function(response) { + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Setting updated successfully.', + type: 'success' + }); + if (setting === 'password-protection') { + wp.passwordProtection = value; + // Reset form + $scope.PPUsername = ''; + $scope.PPPassword = ''; + $scope.currentWP = null; + } + } else { + new PNotify({ + title: 'Error!', + text: response.data.error_message, + type: 'error' + }); + } + }, function(error) { + new PNotify({ + title: 'Error!', + text: 'An error occurred while updating the setting.', + type: 'error' + }); + console.error(error); + }); + }; + + $scope.cyberPanelLoading = true; + + $scope.issueSSL = function (virtualHost) { + $scope.cyberPanelLoading = false; + + var url = "/manageSSL/issueSSL"; + + + var data = { + virtualHost: virtualHost + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.cyberPanelLoading = true; + if (response.data.SSL === 1) { + new PNotify({ + title: 'Success!', + text: 'SSL successfully issued.', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + + } + + function cantLoadInitialDatas(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); + } + + + }; + + $scope.cyberPanelLoading = true; + + $scope.searchWebsites = function () { + + $scope.cyberPanelLoading = false; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + var data = { + patternAdded: $scope.patternAdded + }; + + dataurl = "/websites/searchWebsites"; + + $http.post(dataurl, data, config).then(ListInitialData, cantLoadInitialData); + + + function ListInitialData(response) { + $scope.cyberPanelLoading = true; + if (response.data.listWebSiteStatus === 1) { + + var finalData = JSON.parse(response.data.data); + $scope.WebSitesList = finalData; + $("#listFail").hide(); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + } + + function cantLoadInitialData(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Connect disrupted, refresh the page.', + type: 'error' + }); + } + + + }; + + $scope.ScanWordpressSite = function () { + + $('#cyberPanelLoading').show(); + + + var url = "/websites/ScanWordpressSite"; + + var data = {} + + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + $('#cyberPanelLoading').hide(); + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Successfully Saved!.', + type: 'success' + }); + location.reload(); + + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + + } + + function cantLoadInitialDatas(response) { + $('#cyberPanelLoading').hide(); + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + + } + + }; }); From d8b401f00a5567dc2408538d77fc5b9a08480ac6 Mon Sep 17 00:00:00 2001 From: usmannasir Date: Sat, 5 Apr 2025 21:34:44 +0500 Subject: [PATCH 034/273] add pp protection model and seprate function --- .../websiteFunctions/websiteFunctions.js | 6658 +---------------- 1 file changed, 243 insertions(+), 6415 deletions(-) diff --git a/websiteFunctions/static/websiteFunctions/websiteFunctions.js b/websiteFunctions/static/websiteFunctions/websiteFunctions.js index 35e3fcb4a..af65ab946 100755 --- a/websiteFunctions/static/websiteFunctions/websiteFunctions.js +++ b/websiteFunctions/static/websiteFunctions/websiteFunctions.js @@ -2733,84 +2733,135 @@ app.controller('listWebsites', function ($scope, $http, $window) { window.location.href = '/websites/listWPsites?wpID=' + wpId; }; - $scope.currentWP = null; - $scope.PPUsername = ''; - $scope.PPPassword = ''; - - $scope.togglePasswordProtection = function(wp) { - if (!wp.passwordProtection) { - // Show password protection modal - $('#Passwordprotection').modal('show'); - $scope.currentWP = wp; - } else { - // Disable password protection - $scope.updateSetting(wp, 'password-protection', 0); - } - }; - - $scope.enablePasswordProtection = function() { - if (!$scope.PPUsername || !$scope.PPPassword) { - new PNotify({ - title: 'Error!', - text: 'Username and password are required.', - type: 'error' - }); - return; - } - - $scope.updateSetting($scope.currentWP, 'password-protection', 1); - $('#Passwordprotection').modal('hide'); - }; - - $scope.updateSetting = function(wp, setting, value) { - var data = { - WPid: wp.id, - setting: setting, - value: value + $scope.updateSetting = function(wp, setting) { + var settingMap = { + 'search-indexing': 'searchIndex', + 'debugging': 'debugging', + 'password-protection': 'passwordProtection', + 'maintenance-mode': 'maintenanceMode' }; - if (setting === 'password-protection' && value === 1) { - data.PPUsername = $scope.PPUsername; - data.PPPassword = $scope.PPPassword; + var data = { + wpID: wp.id, + setting: setting, + value: wp[settingMap[setting]] ? 'enable' : 'disable' + }; + + $http({ + method: 'POST', + url: '/websites/UpdateWPSettings', + data: data, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'X-CSRFToken': getCookie('csrftoken') + }, + transformRequest: function(obj) { + var str = []; + for(var p in obj) + str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); + return str.join("&"); + } + }).then(function(response) { + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: 'Setting updated successfully.', + type: 'success' + }); + } else { + wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change + new PNotify({ + title: 'Error', + text: 'Failed to update setting.', + type: 'error' + }); + } + }).catch(function(error) { + wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change + new PNotify({ + title: 'Error', + text: 'Connection failed while updating setting.', + type: 'error' + }); + }); + }; + + $scope.UpdateWPSettings = function(wp) { + $('#wordpresshomeloading').show(); + + var url = "/websites/UpdateWPSettings"; + var data = {}; + + if (wp.setting === "PasswordProtection") { + data = { + wpID: wp.id, + setting: wp.setting, + PPUsername: wp.PPUsername, + PPPassword: wp.PPPassword + }; } var config = { headers: { - 'X-CSRFToken': getCookie('csrftoken') + 'X-CSRFToken': getCookie('csrftoken'), + 'Content-Type': 'application/x-www-form-urlencoded' + }, + transformRequest: function(obj) { + var str = []; + for(var p in obj) + str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); + return str.join("&"); } }; - $http.post('/websites/UpdateWPSettings', data, config).then(function(response) { + $http.post(url, data, config).then(function(response) { + $('#wordpresshomeloading').hide(); + if (response.data.status === 1) { new PNotify({ title: 'Success!', - text: 'Setting updated successfully.', + text: 'Successfully Updated!', type: 'success' }); - if (setting === 'password-protection') { - wp.passwordProtection = value; - // Reset form - $scope.PPUsername = ''; - $scope.PPPassword = ''; - $scope.currentWP = null; + if (wp.setting === "PasswordProtection") { + location.reload(); } } else { new PNotify({ - title: 'Error!', + title: 'Operation Failed!', text: response.data.error_message, type: 'error' }); + if (wp.setting === "PasswordProtection") { + location.reload(); + } } }, function(error) { + $('#wordpresshomeloading').hide(); new PNotify({ - title: 'Error!', - text: 'An error occurred while updating the setting.', + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', type: 'error' }); - console.error(error); }); }; + $scope.togglePasswordProtection = function(wp) { + if (wp.passwordProtection) { + // Show modal or form to collect username/password + wp.setting = "PasswordProtection"; + wp.PPUsername = ""; + wp.PPPassword = ""; + $('#passwordProtectionModal').modal('show'); + } else { + // Disable password protection + wp.setting = "PasswordProtection"; + wp.PPUsername = ""; + wp.PPPassword = ""; + $scope.UpdateWPSettings(wp); + } + }; + $scope.cyberPanelLoading = true; $scope.issueSSL = function (virtualHost) { @@ -6151,4342 +6202,97 @@ app.controller('listWebsites', function ($scope, $http, $window) { window.location.href = '/websites/listWPsites?wpID=' + wpId; }; - $scope.currentWP = null; - $scope.PPUsername = ''; - $scope.PPPassword = ''; + $scope.updateSetting = function(wp, setting) { + var settingMap = { + 'search-indexing': 'searchIndex', + 'debugging': 'debugging', + 'password-protection': 'passwordProtection', + 'maintenance-mode': 'maintenanceMode' + }; - $scope.togglePasswordProtection = function(wp) { - if (!wp.passwordProtection) { - // Show password protection modal - $('#Passwordprotection').modal('show'); - $scope.currentWP = wp; - } else { - // Disable password protection - $scope.updateSetting(wp, 'password-protection', 0); - } - }; - - $scope.enablePasswordProtection = function() { - if (!$scope.PPUsername || !$scope.PPPassword) { - new PNotify({ - title: 'Error!', - text: 'Username and password are required.', - type: 'error' - }); - return; - } - - $scope.updateSetting($scope.currentWP, 'password-protection', 1); - $('#Passwordprotection').modal('hide'); - }; - - $scope.updateSetting = function(wp, setting, value) { var data = { - WPid: wp.id, + wpID: wp.id, setting: setting, - value: value + value: wp[settingMap[setting]] ? 'enable' : 'disable' }; - if (setting === 'password-protection' && value === 1) { - data.PPUsername = $scope.PPUsername; - data.PPPassword = $scope.PPPassword; - } - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post('/websites/UpdateWPSettings', data, config).then(function(response) { - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Setting updated successfully.', - type: 'success' - }); - if (setting === 'password-protection') { - wp.passwordProtection = value; - // Reset form - $scope.PPUsername = ''; - $scope.PPPassword = ''; - $scope.currentWP = null; - } - } else { - new PNotify({ - title: 'Error!', - text: response.data.error_message, - type: 'error' - }); - } - }, function(error) { - new PNotify({ - title: 'Error!', - text: 'An error occurred while updating the setting.', - type: 'error' - }); - console.error(error); - }); - }; - - $scope.cyberPanelLoading = true; - - $scope.issueSSL = function (virtualHost) { - $scope.cyberPanelLoading = false; - - var url = "/manageSSL/issueSSL"; - - - var data = { - virtualHost: virtualHost - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.cyberPanelLoading = true; - if (response.data.SSL === 1) { - new PNotify({ - title: 'Success!', - text: 'SSL successfully issued.', - type: 'success' - }); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - } - - } - - function cantLoadInitialDatas(response) { - $scope.cyberPanelLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: 'Could not connect to server, please refresh this page', - type: 'error' - }); - } - - - }; - - $scope.cyberPanelLoading = true; - - $scope.searchWebsites = function () { - - $scope.cyberPanelLoading = false; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - var data = { - patternAdded: $scope.patternAdded - }; - - dataurl = "/websites/searchWebsites"; - - $http.post(dataurl, data, config).then(ListInitialData, cantLoadInitialData); - - - function ListInitialData(response) { - $scope.cyberPanelLoading = true; - if (response.data.listWebSiteStatus === 1) { - - var finalData = JSON.parse(response.data.data); - $scope.WebSitesList = finalData; - $("#listFail").hide(); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - } - - function cantLoadInitialData(response) { - $scope.cyberPanelLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: 'Connect disrupted, refresh the page.', - type: 'error' - }); - } - - - }; - - $scope.ScanWordpressSite = function () { - - $('#cyberPanelLoading').show(); - - - var url = "/websites/ScanWordpressSite"; - - var data = {} - - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - -/** - * Created by usman on 7/26/17. - */ -function getCookie(name) { - var cookieValue = null; - var t = document.cookie; - if (document.cookie && document.cookie !== '') { - var cookies = document.cookie.split(';'); - for (var i = 0; i < cookies.length; i++) { - var cookie = jQuery.trim(cookies[i]); - // Does this cookie string begin with the name we want? - if (cookie.substring(0, name.length + 1) === (name + '=')) { - cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); - break; - } - } - } - return cookieValue; -} - - -var arry = [] - -function selectpluginJs(val) { - $('#mysearch').hide() - arry.push(val) - - // console.log(arry) - document.getElementById('selJS').innerHTML = ""; - - for (var i = 0; i < arry.length; i++) { - $('#selJS').show() - var mlm = ' ' + arry[i] + '    ' - $('#selJS').append(mlm) - } - - -} - - -var DeletePluginURL; - -function DeletePluginBuucket(url) { - DeletePluginURL = url; -} - -function FinalDeletePluginBuucket() { - window.location.href = DeletePluginURL; -} - -var SPVal; - -app.controller('WPAddNewPlugin', function ($scope, $http, $timeout, $window, $compile) { - $scope.webSiteCreationLoading = true; - - $scope.SearchPluginName = function (val) { - $scope.webSiteCreationLoading = false; - SPVal = val; - url = "/websites/SearchOnkeyupPlugin"; - - var searchcontent = $scope.searchcontent; - - - var data = { - pluginname: searchcontent - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.webSiteCreationLoading = true; - - if (response.data.status === 1) { - if (SPVal == 'add') { - $('#mysearch').show() - document.getElementById('mysearch').innerHTML = ""; - var res = response.data.plugns.plugins - // console.log(res); - for (i = 0; i <= res.length; i++) { - // - var tml = '
    '; - $('#mysearch').append(tml); - } - } else if (SPVal == 'eidt') { - $('#mysearch').show() - document.getElementById('mysearch').innerHTML = ""; - var res = response.data.plugns.plugins - // console.log(res); - for (i = 0; i <= res.length; i++) { - // - var tml = '
    '; - var temp = $compile(tml)($scope) - angular.element(document.getElementById('mysearch')).append(temp); - } - - } - - - } else { - - // $scope.errorMessage = response.data.error_message; - alert("Status not = 1: Error..." + response.data.error_message) - } - - - } - - function cantLoadInitialDatas(response) { - - alert("Error..." + response) - - } - } - - $scope.AddNewplugin = function () { - - url = "/websites/AddNewpluginAjax"; - - var bucketname = $scope.PluginbucketName - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - var data = { - config: arry, - Name: bucketname - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - function ListInitialDatas(response) { - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Bucket created.', - type: 'success' - }); - location.reload(); - } else { - - new PNotify({ - title: 'Error!', - text: response.data.error_message, - type: 'error' - }); - } - - - } - - function cantLoadInitialDatas(response) { - - alert("Error..." + response) - - } - } - - $scope.deletesPlgin = function (val) { - - url = "/websites/deletesPlgin"; - - - var data = { - pluginname: val, - pluginbBucketID: $('#pluginbID').html() - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.status === 1) { - location.reload(); - - } else { - - // $scope.errorMessage = response.data.error_message; - alert("Status not = 1: Error..." + response.data.error_message) - } - - - } - - function cantLoadInitialDatas(response) { - - alert("Error..." + response) - - } - - } - - $scope.Addplugin = function (slug) { - $('#mysearch').hide() - - url = "/websites/Addplugineidt"; - - - var data = { - pluginname: slug, - pluginbBucketID: $('#pluginbID').html() - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.status === 1) { - location.reload(); - - } else { - - // $scope.errorMessage = response.data.error_message; - alert("Status not = 1: Error..." + response.data.error_message) - } - - - } - - function cantLoadInitialDatas(response) { - - alert("Error..." + response) - - } - - - } - -}); - -var domain_check = 0; - -function checkbox_function() { - - var checkBox = document.getElementById("myCheck"); - // Get the output text - - - // If the checkbox is checked, display the output text - if (checkBox.checked == true) { - domain_check = 0; - document.getElementById('Test_Domain').style.display = "block"; - document.getElementById('Own_Domain').style.display = "none"; - - } else { - document.getElementById('Test_Domain').style.display = "none"; - document.getElementById('Own_Domain').style.display = "block"; - domain_check = 1; - } - - // alert(domain_check); -} - -app.controller('createWordpress', function ($scope, $http, $timeout, $compile, $window) { - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - - - var statusFile; - - $scope.createWordPresssite = function () { - - $scope.webSiteCreationLoading = false; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - - - $scope.currentStatus = "Starting creation.."; - - var apacheBackend = 0; - - if ($scope.apacheBackend === true) { - apacheBackend = 1; - } else { - apacheBackend = 0 - } - - var package = $scope.packageForWebsite; - var websiteOwner = $scope.websiteOwner; - var WPtitle = $scope.WPtitle; - - // if (domain_check == 0) { - // var Part2_domainNameCreate = document.getElementById('Part2_domainNameCreate').value; - // var domainNameCreate = document.getElementById('TestDomainNameCreate').value + Part2_domainNameCreate; - // } - // if (domain_check == 1) { - // - // var domainNameCreate = $scope.own_domainNameCreate; - // } - - var domainNameCreate = $scope.domainNameCreate; - - - var WPUsername = $scope.WPUsername; - var adminEmail = $scope.adminEmail; - var WPPassword = $scope.WPPassword; - var WPVersions = $scope.WPVersions; - var pluginbucket = $scope.pluginbucket; - var autoupdates = $scope.autoupdates; - var pluginupdates = $scope.pluginupdates; - var themeupdates = $scope.themeupdates; - - if (domain_check == 0) { - - var path = ""; - - } - if (domain_check = 1) { - - var path = $scope.installPath; - - } - - - var home = "1"; - - if (typeof path != 'undefined') { - home = "0"; - } - - //alert(domainNameCreate); - var data = { - - title: WPtitle, - domain: domainNameCreate, - WPVersion: WPVersions, - pluginbucket: pluginbucket, - adminUser: WPUsername, - Email: adminEmail, - PasswordByPass: WPPassword, - AutomaticUpdates: autoupdates, - Plugins: pluginupdates, - Themes: themeupdates, - websiteOwner: websiteOwner, - package: package, - home: home, - path: path, - apacheBackend: apacheBackend - } - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - var url = "/websites/submitWorpressCreation"; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.webSiteCreationLoading = true; - if (response.data.status === 1) { - statusFile = response.data.tempStatusPath; - getCreationStatus(); - - } else { - $scope.goBackDisable = false; - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - } - - } - - function cantLoadInitialDatas(response) { - - alert("Error..." + response) - - } - - }; - $scope.goBack = function () { - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - $("#installProgress").css("width", "0%"); - }; - - function getCreationStatus() { - - url = "/websites/installWordpressStatus"; - - var data = { - statusFile: statusFile - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.abort === 1) { - - if (response.data.installStatus === 1) { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = false; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $("#installProgress").css("width", "100%"); - $scope.installPercentage = "100"; - $scope.currentStatus = response.data.currentStatus; - $timeout.cancel(); - - } else { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = false; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $scope.errorMessage = response.data.error_message; - - $("#installProgress").css("width", "0%"); - $scope.installPercentage = "0"; - $scope.goBackDisable = false; - - } - - } else { - $scope.webSiteCreationLoading = false; - $("#installProgress").css("width", response.data.installationProgress + "%"); - $scope.installPercentage = response.data.installationProgress; - $scope.currentStatus = response.data.currentStatus; - $timeout(getCreationStatus, 1000); - } - - } - - function cantLoadInitialDatas(response) { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - } - - -}); - - -//........... delete wp list -var FurlDeleteWP; - -function DeleteWPNow(url) { - FurlDeleteWP = url; -} - -function FinalDeleteWPNow() { - window.location.href = FurlDeleteWP; -} - -var DeploytoProductionID; - -function DeployToProductionInitial(vall) { - DeploytoProductionID = vall; -} - -var create_staging_domain_check = 0; - -function create_staging_checkbox_function() { - - try { - - var checkBox = document.getElementById("Create_Staging_Check"); - // Get the output text - - - // If the checkbox is checked, display the output text - if (checkBox.checked == true) { - create_staging_domain_check = 0; - document.getElementById('Website_Create_Test_Domain').style.display = "block"; - document.getElementById('Website_Create_Own_Domain').style.display = "none"; - - } else { - document.getElementById('Website_Create_Test_Domain').style.display = "none"; - document.getElementById('Website_Create_Own_Domain').style.display = "block"; - create_staging_domain_check = 1; - } - } catch (e) { - - } - - // alert(domain_check); -} - -create_staging_checkbox_function(); - -app.controller('WPsiteHome', function ($scope, $http, $timeout, $compile, $window) { - - var CheckBoxpasssword = 0; - - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - $(document).ready(function () { - var checkstatus = document.getElementById("wordpresshome"); - if (checkstatus !== null) { - $scope.LoadWPdata(); - - } - }); - - - $scope.LoadWPdata = function () { - - $scope.wordpresshomeloading = false; - $('#wordpresshomeloading').show(); - - var url = "/websites/FetchWPdata"; - - var data = { - WPid: $('#WPid').html(), - } - - console.log(data); - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - wordpresshomeloading = true; - $('#wordpresshomeloading').hide(); - - if (response.data.status === 1) { - $('#WPVersion').text(response.data.ret_data.version); - if (response.data.ret_data.lscache === 1) { - $('#lscache').prop('checked', true); - } - if (response.data.ret_data.debugging === 1) { - $('#debugging').prop('checked', true); - } - if (response.data.ret_data.searchIndex === 1) { - $('#searchIndex').prop('checked', true); - } - if (response.data.ret_data.maintenanceMode === 1) { - $('#maintenanceMode').prop('checked', true); - } - if (response.data.ret_data.wpcron === 1) { - $('#wpcron').prop('checked', true); - } - if (response.data.ret_data.passwordprotection == 1) { - - var dc = '\n' + - ' ' - var mp = $compile(dc)($scope); - angular.element(document.getElementById('prsswdprodata')).append(mp); - CheckBoxpasssword = 1; - } else if (response.data.ret_data.passwordprotection == 0) { - var dc = '\n' + - ' ' - $('#prsswdprodata').append(dc); - CheckBoxpasssword = 0; - } - - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - }; - - $scope.UpdateWPSettings = function (setting) { - - $scope.wordpresshomeloading = false; - $('#wordpresshomeloading').show(); - - - var url = "/websites/UpdateWPSettings"; - - if (setting === "PasswordProtection") { - if (CheckBoxpasssword == 0) { - var data = { - WPid: $('#WPid').html(), - setting: setting, - PPUsername: $scope.PPUsername, - PPPassword: $scope.PPPassword, - } - - } else { - var data = { - WPid: $('#WPid').html(), - setting: setting, - PPUsername: '', - PPPassword: '', - } - - } - - } else { - var settingValue = 0; - if ($('#' + setting).is(":checked")) { - settingValue = 1; - } - var data = { - WPid: $('#WPid').html(), - setting: setting, - settingValue: settingValue - } - } - - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.wordpresshomeloading = true; - $('#wordpresshomeloading').hide(); - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Successfully Updated!.', - type: 'success' - }); - if (setting === "PasswordProtection") { - location.reload(); - } - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - if (setting === "PasswordProtection") { - location.reload(); - } - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - - - }; - - $scope.GetCurrentPlugins = function () { - $('#wordpresshomeloading').show(); - - $scope.wordpresshomeloading = false; - - var url = "/websites/GetCurrentPlugins"; - - var data = { - WPid: $('#WPid').html(), - } - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - wordpresshomeloading = true; - $('#wordpresshomeloading').hide(); - - if (response.data.status === 1) { - $('#PluginBody').html(''); - var plugins = JSON.parse(response.data.plugins); - plugins.forEach(AddPlugins); - - } else { - alert("Error:" + response.data.error_message) - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - }; - - $scope.GetCurrentThemes = function () { - $('#wordpresshomeloading').show(); - - $scope.wordpresshomeloading = false; - - var url = "/websites/GetCurrentThemes"; - - var data = { - WPid: $('#WPid').html(), - } - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - wordpresshomeloading = true; - $('#wordpresshomeloading').hide(); - - if (response.data.status === 1) { - - $('#ThemeBody').html(''); - var themes = JSON.parse(response.data.themes); - themes.forEach(AddThemes); - - } else { - alert("Error:" + response.data.error_message) - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - }; - - $scope.UpdatePlugins = function (plugin) { - $('#wordpresshomeloading').show(); - var data = { - plugin: plugin, - pluginarray: PluginsList, - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/UpdatePlugins"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Updating Plugins in Background!.', - type: 'success' - }); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - - - }; - - $scope.DeletePlugins = function (plugin) { - $('#wordpresshomeloading').show(); - var data = { - plugin: plugin, - pluginarray: PluginsList, - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/DeletePlugins"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Deleting Plugin in Background!', - type: 'success' - }); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - - } - - $scope.ChangeStatus = function (plugin) { - $('#wordpresshomeloading').show(); - var data = { - plugin: plugin, - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/ChangeStatus"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Changed Plugin state Successfully !.', - type: 'success' - }); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - - } - - function AddPlugins(value, index, array) { - var FinalMarkup = '' - FinalMarkup = FinalMarkup + ''; - for (let x in value) { - if (x === 'status') { - if (value[x] === 'inactive') { - FinalMarkup = FinalMarkup + '
    '; - } else { - FinalMarkup = FinalMarkup + '
    '; - } - } else if (x === 'update') { - if (value[x] === 'none') { - FinalMarkup = FinalMarkup + 'Upto Date'; - } else { - FinalMarkup = FinalMarkup + ''; - } - } else { - FinalMarkup = FinalMarkup + '' + value[x] + ""; - } - } - FinalMarkup = FinalMarkup + '' - FinalMarkup = FinalMarkup + '' - var temp = $compile(FinalMarkup)($scope) - AppendToTable('#PluginBody', temp) - } - - $scope.UpdateThemes = function (theme) { - $('#wordpresshomeloading').show(); - var data = { - Theme: theme, - Themearray: ThemesList, - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/UpdateThemes"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Updating Theme in background !.', - type: 'success' - }); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - - - }; - - $scope.DeleteThemes = function (theme) { - $('#wordpresshomeloading').show(); - var data = { - Theme: theme, - Themearray: ThemesList, - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/DeleteThemes"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Deleting Theme in Background!.', - type: 'success' - }); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - }; - - $scope.ChangeStatusThemes = function (theme) { - $('#wordpresshomeloading').show(); - var data = { - theme: theme, - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/StatusThemes"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Change Theme state in Bsckground!.', - type: 'success' - }); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - - }; - - function AddThemes(value, index, array) { - var FinalMarkup = '' - FinalMarkup = FinalMarkup + ''; - for (let x in value) { - if (x === 'status') { - if (value[x] === 'inactive') { - FinalMarkup = FinalMarkup + '
    '; - } else { - FinalMarkup = FinalMarkup + '
    '; - } - } else if (x === 'update') { - if (value[x] === 'none') { - FinalMarkup = FinalMarkup + 'Upto Date'; - } else { - FinalMarkup = FinalMarkup + ''; - } - } else { - FinalMarkup = FinalMarkup + '' + value[x] + ""; - } - } - FinalMarkup = FinalMarkup + '' - FinalMarkup = FinalMarkup + '' - var temp = $compile(FinalMarkup)($scope) - AppendToTable('#ThemeBody', temp) - } - - $scope.CreateStagingNow = function () { - $('#wordpresshomeloading').show(); - - $scope.wordpresshomeloading = false; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - - - $scope.currentStatus = "Starting creation Staging.."; - - //here enter domain name - if (create_staging_domain_check == 0) { - var Part2_domainNameCreate = document.getElementById('Part2_domainNameCreate').value; - var domainNameCreate = document.getElementById('TestDomainNameCreate').value + Part2_domainNameCreate; - } - if (create_staging_domain_check == 1) { - - var domainNameCreate = $scope.own_domainNameCreate; - } - var data = { - StagingName: $('#stagingName').val(), - StagingDomain: domainNameCreate, - WPid: $('#WPid').html(), - } - var url = "/websites/CreateStagingNow"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - if (response.data.status === 1) { - statusFile = response.data.tempStatusPath; - getCreationStatus(); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - }; - - function getCreationStatus() { - $('#wordpresshomeloading').show(); - - url = "/websites/installWordpressStatus"; - - var data = { - statusFile: statusFile - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - //$('#wordpresshomeloading').hide(); - - if (response.data.abort === 1) { - if (response.data.installStatus === 1) { - - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = false; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - - $("#installProgress").css("width", "100%"); - $("#installProgressbackup").css("width", "100%"); - $scope.installPercentage = "100"; - $scope.currentStatus = response.data.currentStatus; - $timeout.cancel(); - - - } else { - - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = false; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $scope.errorMessage = response.data.error_message; - - $("#installProgress").css("width", "0%"); - $("#installProgressbackup").css("width", "0%"); - $scope.installPercentage = "0"; - $scope.goBackDisable = false; - - - } - - } else { - - $("#installProgress").css("width", response.data.installationProgress + "%"); - $("#installProgressbackup").css("width", response.data.installationProgress + "%"); - $scope.installPercentage = response.data.installationProgress; - $scope.currentStatus = response.data.currentStatus; - $timeout(getCreationStatus, 1000); - - } - - } - - function cantLoadInitialDatas(response) { - //$('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - } - - $scope.goBack = function () { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - $("#installProgress").css("width", "0%"); - }; - - $scope.fetchstaging = function () { - - $('#wordpresshomeloading').show(); - $scope.wordpresshomeloading = false; - - var url = "/websites/fetchstaging"; - - var data = { - WPid: $('#WPid').html(), - } - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - wordpresshomeloading = true; - $('#wordpresshomeloading').hide(); - - if (response.data.status === 1) { - - // $('#ThemeBody').html(''); - // var themes = JSON.parse(response.data.themes); - // themes.forEach(AddThemes); - - $('#StagingBody').html(''); - var staging = JSON.parse(response.data.wpsites); - staging.forEach(AddStagings); - - } else { - alert("Error data.error_message:" + response.data.error_message) - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - alert("Error" + response) - - } - - }; - - $scope.fetchDatabase = function () { - - $('#wordpresshomeloading').show(); - $scope.wordpresshomeloading = false; - - var url = "/websites/fetchDatabase"; - - var data = { - WPid: $('#WPid').html(), - } - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - wordpresshomeloading = true; - $('#wordpresshomeloading').hide(); - - if (response.data.status === 1) { - $('#DB_Name').html(response.data.DataBaseName); - $('#DB_User').html(response.data.DataBaseUser); - $('#tableprefix').html(response.data.tableprefix); - } else { - alert("Error data.error_message:" + response.data.error_message) - - } - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - alert("Error" + response) - - } - - }; - - $scope.SaveUpdateConfig = function () { - $('#wordpresshomeloading').show(); - var data = { - AutomaticUpdates: $('#AutomaticUpdates').find(":selected").text(), - Plugins: $('#Plugins').find(":selected").text(), - Themes: $('#Themes').find(":selected").text(), - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/SaveUpdateConfig"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Update Configurations Sucessfully!.', - type: 'success' - }); - $("#autoUpdateConfig").modal('hide'); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - new PNotify({ - title: 'Operation Failed!', - text: response, - type: 'error' - }); - - } - }; - - function AddStagings(value, index, array) { - var FinalMarkup = '' - for (let x in value) { - if (x === 'name') { - FinalMarkup = FinalMarkup + '' + value[x] + ''; - } else if (x !== 'url' && x !== 'deleteURL' && x !== 'id') { - FinalMarkup = FinalMarkup + '' + value[x] + ""; - } - } - FinalMarkup = FinalMarkup + '' + - ' ' - FinalMarkup = FinalMarkup + '' - AppendToTable('#StagingBody', FinalMarkup); - } - - $scope.FinalDeployToProduction = function () { - - $('#wordpresshomeloading').show(); - - $scope.wordpresshomeloading = false; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - - var data = { - WPid: $('#WPid').html(), - StagingID: DeploytoProductionID - } - - var url = "/websites/DeploytoProduction"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - function ListInitialDatas(response) { - - $('#wordpresshomeloading').hide(); - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Deploy To Production start!.', - type: 'success' - }); - statusFile = response.data.tempStatusPath; - getCreationStatus(); - - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - new PNotify({ - title: 'Operation Failed!', - text: response, - type: 'error' - }); - - } - - }; - - - $scope.CreateBackup = function () { - $('#wordpresshomeloading').show(); - - $scope.wordpresshomeloading = false; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - $scope.currentStatus = "Starting creation Backups.."; - var data = { - WPid: $('#WPid').html(), - Backuptype: $('#backuptype').val() - } - var url = "/websites/WPCreateBackup"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $('createbackupbutton').hide(); - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Creating Backups!.', - type: 'success' - }); - statusFile = response.data.tempStatusPath; - getCreationStatus(); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - alert(response) - - } - - }; - - - $scope.installwpcore = function () { - - $('#wordpresshomeloading').show(); - $('#wordpresshomeloadingsec').show(); - var data = { - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/installwpcore"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $('#wordpresshomeloadingsec').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Results fetched..', - type: 'success' - }); - $('#SecurityResult').html(response.data.result); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $('#wordpresshomeloadingsec').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - - }; - - $scope.dataintegrity = function () { - - $('#wordpresshomeloading').show(); - $('#wordpresshomeloadingsec').show(); - var data = { - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/dataintegrity"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $('#wordpresshomeloadingsec').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Results fetched', - type: 'success' - }); - $('#SecurityResult').html(response.data.result); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $('#wordpresshomeloadingsec').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - }; - -}); - - -var PluginsList = []; - - -function AddPluginToArray(cBox, name) { - if (cBox.checked) { - PluginsList.push(name); - // alert(PluginsList); - } else { - const index = PluginsList.indexOf(name); - if (index > -1) { - PluginsList.splice(index, 1); - } - // alert(PluginsList); - } -} - -var ThemesList = []; - -function AddThemeToArray(cBox, name) { - if (cBox.checked) { - ThemesList.push(name); - // alert(ThemesList); - } else { - const index = ThemesList.indexOf(name); - if (index > -1) { - ThemesList.splice(index, 1); - } - // alert(ThemesList); - } -} - - -function AppendToTable(table, markup) { - $(table).append(markup); -} - - -//..................Restore Backup Home - - -app.controller('RestoreWPBackup', function ($scope, $http, $timeout, $window) { - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - - - $scope.checkmethode = function () { - var val = $('#RestoreMethode').children("option:selected").val(); - if (val == 1) { - $('#Newsitediv').show(); - $('#exinstingsitediv').hide(); - } else if (val == 0) { - $('#exinstingsitediv').show(); - $('#Newsitediv').hide(); - } else { - - } - }; - - - $scope.RestoreWPbackupNow = function () { - $('#wordpresshomeloading').show(); - $scope.wordpresshomeloading = false; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - $scope.currentStatus = "Start Restoring WordPress.."; - - var Domain = $('#wprestoresubdirdomain').val() - var path = $('#wprestoresubdirpath').val(); - var home = "1"; - - if (typeof path != 'undefined' || path != '') { - home = "0"; - } - if (typeof path == 'undefined') { - path = ""; - } - - - var backuptype = $('#backuptype').html(); - var data; - if (backuptype == "DataBase Backup") { - data = { - backupid: $('#backupid').html(), - DesSite: $('#DesSite').children("option:selected").val(), - Domain: '', - path: path, - home: home, - } - } else { - data = { - backupid: $('#backupid').html(), - DesSite: $('#DesSite').children("option:selected").val(), - Domain: Domain, - path: path, - home: home, - } - - } - - var url = "/websites/RestoreWPbackupNow"; - - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - // console.log(data) - - var d = $('#DesSite').children("option:selected").val(); - var c = $("input[name=Newdomain]").val(); - // if (d == -1 || c == "") { - // alert("Please Select Method of Backup Restore"); - // } else { - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - // } - - - function ListInitialDatas(response) { - wordpresshomeloading = true; - $('#wordpresshomeloading').hide(); - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Restoring process starts!.', - type: 'success' - }); - statusFile = response.data.tempStatusPath; - getCreationStatus(); - - } else { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = false; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $scope.errorMessage = response.data.error_message; - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - - } - } - - function getCreationStatus() { - $('#wordpresshomeloading').show(); - - url = "/websites/installWordpressStatus"; - - var data = { - statusFile: statusFile - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - //$('#wordpresshomeloading').hide(); - - if (response.data.abort === 1) { - - if (response.data.installStatus === 1) { - - - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = false; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - - $("#installProgress").css("width", "100%"); - $("#installProgressbackup").css("width", "100%"); - $scope.installPercentage = "100"; - $scope.currentStatus = response.data.currentStatus; - $timeout.cancel(); - - - } else { - - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = false; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $scope.errorMessage = response.data.error_message; - - $("#installProgress").css("width", "0%"); - $("#installProgressbackup").css("width", "0%"); - $scope.installPercentage = "0"; - $scope.goBackDisable = false; - - - } - - } else { - - $("#installProgress").css("width", response.data.installationProgress + "%"); - $("#installProgressbackup").css("width", response.data.installationProgress + "%"); - $scope.installPercentage = response.data.installationProgress; - $scope.currentStatus = response.data.currentStatus; - $timeout(getCreationStatus, 1000); - - } - - } - - function cantLoadInitialDatas(response) { - //$('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - } - - $scope.goBack = function () { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - $("#installProgress").css("width", "0%"); - }; -}); - - -//.......................................Remote Backup - -//........... delete DeleteBackupConfigNow - -function DeleteBackupConfigNow(url) { - window.location.href = url; -} - -function DeleteRemoteBackupsiteNow(url) { - window.location.href = url; -} - -function DeleteBackupfileConfigNow(url) { - window.location.href = url; -} - - -app.controller('RemoteBackupConfig', function ($scope, $http, $timeout, $window) { - $scope.RemoteBackupLoading = true; - $scope.SFTPBackUpdiv = true; - - $scope.EndpointURLdiv = true; - $scope.Selectprovider = true; - $scope.S3keyNamediv = true; - $scope.Accesskeydiv = true; - $scope.SecretKeydiv = true; - $scope.SelectRemoteBackuptype = function () { - var val = $scope.RemoteBackuptype; - if (val == "SFTP") { - $scope.SFTPBackUpdiv = false; - $scope.EndpointURLdiv = true; - $scope.Selectprovider = true; - $scope.S3keyNamediv = true; - $scope.Accesskeydiv = true; - $scope.SecretKeydiv = true; - } else if (val == "S3") { - $scope.EndpointURLdiv = true; - $scope.Selectprovider = false; - $scope.S3keyNamediv = false; - $scope.Accesskeydiv = false; - $scope.SecretKeydiv = false; - $scope.SFTPBackUpdiv = true; - } else { - $scope.RemoteBackupLoading = true; - $scope.SFTPBackUpdiv = true; - - $scope.EndpointURLdiv = true; - $scope.Selectprovider = true; - $scope.S3keyNamediv = true; - $scope.Accesskeydiv = true; - $scope.SecretKeydiv = true; - } - } - - $scope.SelectProvidertype = function () { - $scope.EndpointURLdiv = true; - var provider = $scope.Providervalue - if (provider == 'Backblaze') { - $scope.EndpointURLdiv = false; - } else { - $scope.EndpointURLdiv = true; - } - } - - $scope.SaveBackupConfig = function () { - $scope.RemoteBackupLoading = false; - var Hname = $scope.Hostname; - var Uname = $scope.Username; - var Passwd = $scope.Password; - var path = $scope.path; - var type = $scope.RemoteBackuptype; - var Providervalue = $scope.Providervalue; - var data; - if (type == "SFTP") { - - data = { - Hname: Hname, - Uname: Uname, - Passwd: Passwd, - path: path, - type: type - } - } else if (type == "S3") { - if (Providervalue == "Backblaze") { - data = { - S3keyname: $scope.S3keyName, - Provider: Providervalue, - AccessKey: $scope.Accesskey, - SecertKey: $scope.SecretKey, - EndUrl: $scope.EndpointURL, - type: type - } - } else { - data = { - S3keyname: $scope.S3keyName, - Provider: Providervalue, - AccessKey: $scope.Accesskey, - SecertKey: $scope.SecretKey, - type: type - } - - } - - } - var url = "/websites/SaveBackupConfig"; - - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.RemoteBackupLoading = true; - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Successfully Saved!.', - type: 'success' - }); - location.reload(); - - - } else { - new PNotify({ - title: 'Error!', - text: response.data.error_message, - type: 'error' - }); - } - } - - function cantLoadInitialDatas(response) { - $scope.RemoteBackupLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - - } - - - } - -}); - -var UpdatescheduleID; -app.controller('BackupSchedule', function ($scope, $http, $timeout, $window) { - $scope.BackupScheduleLoading = true; - $scope.SaveBackupSchedule = function () { - $scope.RemoteBackupLoading = false; - var FileRetention = $scope.Fretention; - var Backfrequency = $scope.Bfrequency; - - - var data = { - FileRetention: FileRetention, - Backfrequency: Backfrequency, - ScheduleName: $scope.ScheduleName, - RemoteConfigID: $('#RemoteConfigID').html(), - BackupType: $scope.BackupType - } - var url = "/websites/SaveBackupSchedule"; - - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.RemoteBackupLoading = true; - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Successfully Saved!.', - type: 'success' - }); - location.reload(); - - - } else { - new PNotify({ - title: 'Error!', - text: response.data.error_message, - type: 'error' - }); - } - } - - function cantLoadInitialDatas(response) { - $scope.RemoteBackupLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - - } - - - }; - - - $scope.getupdateid = function (ID) { - UpdatescheduleID = ID; - } - - $scope.UpdateRemoteschedules = function () { - $scope.RemoteBackupLoading = false; - var Frequency = $scope.RemoteFrequency; - var fretention = $scope.RemoteFileretention; - - var data = { - ScheduleID: UpdatescheduleID, - Frequency: Frequency, - FileRetention: fretention - } - var url = "/websites/UpdateRemoteschedules"; - - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.RemoteBackupLoading = true; - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Successfully Updated!.', - type: 'success' - }); - location.reload(); - - - } else { - new PNotify({ - title: 'Error!', - text: response.data.error_message, - type: 'error' - }); - } - } - - function cantLoadInitialDatas(response) { - $scope.RemoteBackupLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - - } - }; - - $scope.AddWPsiteforRemoteBackup = function () { - $scope.RemoteBackupLoading = false; - - - var data = { - WpsiteID: $('#Wpsite').val(), - RemoteScheduleID: $('#RemoteScheduleID').html() - } - var url = "/websites/AddWPsiteforRemoteBackup"; - - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.RemoteBackupLoading = true; - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Successfully Saved!.', - type: 'success' - }); - location.reload(); - - - } else { - new PNotify({ - title: 'Error!', - text: response.data.error_message, - type: 'error' - }); - } - } - - function cantLoadInitialDatas(response) { - $scope.RemoteBackupLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - - } - - - }; -}); -/* Java script code to create account */ - -var website_create_domain_check = 0; - -function website_create_checkbox_function() { - - var checkBox = document.getElementById("myCheck"); - // Get the output text - - - // If the checkbox is checked, display the output text - if (checkBox.checked == true) { - website_create_domain_check = 0; - document.getElementById('Website_Create_Test_Domain').style.display = "block"; - document.getElementById('Website_Create_Own_Domain').style.display = "none"; - - } else { - document.getElementById('Website_Create_Test_Domain').style.display = "none"; - document.getElementById('Website_Create_Own_Domain').style.display = "block"; - website_create_domain_check = 1; - } - - // alert(domain_check); -} - -app.controller('createWebsite', function ($scope, $http, $timeout, $window) { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - - var statusFile; - - $scope.createWebsite = function () { - - $scope.webSiteCreationLoading = false; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - - $scope.currentStatus = "Starting creation.."; - - var ssl, dkimCheck, openBasedir, mailDomain, apacheBackend; - - if ($scope.sslCheck === true) { - ssl = 1; - } else { - ssl = 0 - } - - if ($scope.apacheBackend === true) { - apacheBackend = 1; - } else { - apacheBackend = 0 - } - - if ($scope.dkimCheck === true) { - dkimCheck = 1; - } else { - dkimCheck = 0 - } - - if ($scope.openBasedir === true) { - openBasedir = 1; - } else { - openBasedir = 0 - } - - if ($scope.mailDomain === true) { - mailDomain = 1; - } else { - mailDomain = 0 - } - - - url = "/websites/submitWebsiteCreation"; - - var package = $scope.packageForWebsite; - - // if (website_create_domain_check == 0) { - // var Part2_domainNameCreate = document.getElementById('Part2_domainNameCreate').value; - // var domainName = document.getElementById('TestDomainNameCreate').value + Part2_domainNameCreate; - // } - // if (website_create_domain_check == 1) { - // - // var domainName = $scope.domainNameCreate; - // } - var domainName = $scope.domainNameCreate; - - // var domainName = $scope.domainNameCreate; - - var adminEmail = $scope.adminEmail; - var phpSelection = $scope.phpSelection; - var websiteOwner = $scope.websiteOwner; - - - var data = { - package: package, - domainName: domainName, - adminEmail: adminEmail, - phpSelection: phpSelection, - ssl: ssl, - websiteOwner: websiteOwner, - dkimCheck: dkimCheck, - openBasedir: openBasedir, - mailDomain: mailDomain, - apacheBackend: apacheBackend - }; - - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.createWebSiteStatus === 1) { - statusFile = response.data.tempStatusPath; - getCreationStatus(); - } else { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = false; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $scope.errorMessage = response.data.error_message; - } - - - } - - function cantLoadInitialDatas(response) { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - }; - $scope.goBack = function () { - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - $("#installProgress").css("width", "0%"); - }; - - function getCreationStatus() { - - url = "/websites/installWordpressStatus"; - - var data = { - statusFile: statusFile - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - - if (response.data.abort === 1) { - - if (response.data.installStatus === 1) { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = false; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $("#installProgress").css("width", "100%"); - $scope.installPercentage = "100"; - $scope.currentStatus = response.data.currentStatus; - $timeout.cancel(); - - } else { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = false; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $scope.errorMessage = response.data.error_message; - - $("#installProgress").css("width", "0%"); - $scope.installPercentage = "0"; - $scope.goBackDisable = false; - - } - - } else { - $("#installProgress").css("width", response.data.installationProgress + "%"); - $scope.installPercentage = response.data.installationProgress; - $scope.currentStatus = response.data.currentStatus; - $timeout(getCreationStatus, 1000); - } - - } - - function cantLoadInitialDatas(response) { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - } - -}); -/* Java script code to create account ends here */ - -/* Java script code to list accounts */ - -$("#listFail").hide(); - - -app.controller('listWebsites', function ($scope, $http, $window) { - $scope.web = {}; - $scope.WebSitesList = []; - - $scope.currentPage = 1; - $scope.recordsToShow = 10; - - // Initial fetch of websites - $scope.getFurtherWebsitesFromDB = function () { - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - var data = { - page: $scope.currentPage, - recordsToShow: $scope.recordsToShow - }; - - var dataurl = "/websites/fetchWebsitesList"; - - $http.post(dataurl, data, config).then(function(response) { - if (response.data.listWebSiteStatus === 1) { - $scope.WebSitesList = JSON.parse(response.data.data); - $scope.pagination = response.data.pagination; - $("#listFail").hide(); - } else { - $("#listFail").fadeIn(); - $scope.errorMessage = response.data.error_message; - } - }).catch(function(error) { - $("#listFail").fadeIn(); - $scope.errorMessage = error.message || 'An error occurred while fetching websites'; - }); - }; - - // Call it immediately - $scope.getFurtherWebsitesFromDB(); - - $scope.showWPSites = function(domain) { - console.log('showWPSites called for domain:', domain); - - // Make sure domain is defined - if (!domain) { - console.error('Domain is undefined'); - return; - } - - var url = '/websites/fetchWPDetails'; - var data = { - domain: domain - }; - - console.log('Making request to:', url, 'with data:', data); - $http({ method: 'POST', - url: url, - data: $.param(data), + url: '/websites/UpdateWPSettings', + data: data, headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-CSRFToken': getCookie('csrftoken') + }, + transformRequest: function(obj) { + var str = []; + for(var p in obj) + str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); + return str.join("&"); } }).then(function(response) { - console.log('Response received:', response); - if (response.data.status === 1 && response.data.fetchStatus === 1) { - // Find the website in the list and update its properties - $scope.WebSitesList.forEach(function(website) { - if (website.domain === domain) { - website.wp_sites = response.data.sites; - website.showWPSites = true; - console.log('Updated website:', website); - } - }); - $("#listFail").hide(); - } else { - $("#listFail").fadeIn(); - $scope.errorMessage = response.data.error_message || 'Failed to fetch WordPress sites'; - console.error('Error in response:', response.data.error_message); - } - }).catch(function(error) { - $("#listFail").fadeIn(); - $scope.errorMessage = error.message || 'An error occurred while fetching WordPress sites'; - console.error('Request failed:', error); - }); - }; - - $scope.visitSite = function(url) { - window.open(url, '_blank'); - }; - - $scope.wpLogin = function(wpId) { - window.open('/websites/wpLogin?wpID=' + wpId, '_blank'); - }; - - $scope.manageWP = function(wpId) { - window.location.href = '/websites/listWPsites?wpID=' + wpId; - }; - - $scope.currentWP = null; - $scope.PPUsername = ''; - $scope.PPPassword = ''; - - $scope.togglePasswordProtection = function(wp) { - if (!wp.passwordProtection) { - // Show password protection modal - $('#Passwordprotection').modal('show'); - $scope.currentWP = wp; - } else { - // Disable password protection - $scope.updateSetting(wp, 'password-protection', 0); - } - }; - - $scope.enablePasswordProtection = function() { - if (!$scope.PPUsername || !$scope.PPPassword) { - new PNotify({ - title: 'Error!', - text: 'Username and password are required.', - type: 'error' - }); - return; - } - - $scope.updateSetting($scope.currentWP, 'password-protection', 1); - $('#Passwordprotection').modal('hide'); - }; - - $scope.updateSetting = function(wp, setting, value) { - var data = { - WPid: wp.id, - setting: setting, - value: value - }; - - if (setting === 'password-protection' && value === 1) { - data.PPUsername = $scope.PPUsername; - data.PPPassword = $scope.PPPassword; - } - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post('/websites/UpdateWPSettings', data, config).then(function(response) { if (response.data.status === 1) { new PNotify({ - title: 'Success!', + title: 'Success', text: 'Setting updated successfully.', type: 'success' }); - if (setting === 'password-protection') { - wp.passwordProtection = value; - // Reset form - $scope.PPUsername = ''; - $scope.PPPassword = ''; - $scope.currentWP = null; - } } else { + wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change new PNotify({ - title: 'Error!', - text: response.data.error_message, + title: 'Error', + text: 'Failed to update setting.', type: 'error' }); } - }, function(error) { + }).catch(function(error) { + wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change new PNotify({ - title: 'Error!', - text: 'An error occurred while updating the setting.', + title: 'Error', + text: 'Connection failed while updating setting.', type: 'error' }); - console.error(error); }); }; - $scope.cyberPanelLoading = true; - - $scope.issueSSL = function (virtualHost) { - $scope.cyberPanelLoading = false; - - var url = "/manageSSL/issueSSL"; - - - var data = { - virtualHost: virtualHost - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.cyberPanelLoading = true; - if (response.data.SSL === 1) { - new PNotify({ - title: 'Success!', - text: 'SSL successfully issued.', - type: 'success' - }); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - } - - } - - function cantLoadInitialDatas(response) { - $scope.cyberPanelLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: 'Could not connect to server, please refresh this page', - type: 'error' - }); - } - - - }; - - $scope.cyberPanelLoading = true; - - $scope.searchWebsites = function () { - - $scope.cyberPanelLoading = false; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - var data = { - patternAdded: $scope.patternAdded - }; - - dataurl = "/websites/searchWebsites"; - - $http.post(dataurl, data, config).then(ListInitialData, cantLoadInitialData); - - - function ListInitialData(response) { - $scope.cyberPanelLoading = true; - if (response.data.listWebSiteStatus === 1) { - - var finalData = JSON.parse(response.data.data); - $scope.WebSitesList = finalData; - $("#listFail").hide(); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - } - - function cantLoadInitialData(response) { - $scope.cyberPanelLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: 'Connect disrupted, refresh the page.', - type: 'error' - }); - } - - - }; - - $scope.ScanWordpressSite = function () { - - $('#cyberPanelLoading').show(); - - - var url = "/websites/ScanWordpressSite"; - - var data = {} - - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - $('#cyberPanelLoading').hide(); - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Successfully Saved!.', - type: 'success' - }); - location.reload(); - - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#cyberPanelLoading').hide(); - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - - } - - - }; - -}); - -app.controller('listChildDomainsMain', function ($scope, $http, $timeout) { - - $scope.currentPage = 1; - $scope.recordsToShow = 10; - - $scope.getFurtherWebsitesFromDB = function () { - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - var data = { - page: $scope.currentPage, - recordsToShow: $scope.recordsToShow - }; - - - dataurl = "/websites/fetchChildDomainsMain"; - - $http.post(dataurl, data, config).then(ListInitialData, cantLoadInitialData); - - - function ListInitialData(response) { - if (response.data.listWebSiteStatus === 1) { - - $scope.WebSitesList = JSON.parse(response.data.data); - $scope.pagination = response.data.pagination; - $scope.clients = JSON.parse(response.data.data); - $("#listFail").hide(); - } else { - $("#listFail").fadeIn(); - $scope.errorMessage = response.data.error_message; - - } - } - - function cantLoadInitialData(response) { - } - - - }; - $scope.getFurtherWebsitesFromDB(); - - $scope.cyberPanelLoading = true; - - $scope.issueSSL = function (virtualHost) { - $scope.cyberPanelLoading = false; - - var url = "/manageSSL/issueSSL"; - - - var data = { - virtualHost: virtualHost - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.cyberPanelLoading = true; - if (response.data.SSL === 1) { - new PNotify({ - title: 'Success!', - text: 'SSL successfully issued.', - type: 'success' - }); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - } - - } - - function cantLoadInitialDatas(response) { - $scope.cyberPanelLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: 'Could not connect to server, please refresh this page', - type: 'error' - }); - } - - - }; - - $scope.cyberPanelLoading = true; - - $scope.searchWebsites = function () { - - $scope.cyberPanelLoading = false; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - var data = { - patternAdded: $scope.patternAdded - }; - - dataurl = "/websites/searchChilds"; - - $http.post(dataurl, data, config).then(ListInitialData, cantLoadInitialData); - - - function ListInitialData(response) { - $scope.cyberPanelLoading = true; - if (response.data.listWebSiteStatus === 1) { - - var finalData = JSON.parse(response.data.data); - $scope.WebSitesList = finalData; - $("#listFail").hide(); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - } - - function cantLoadInitialData(response) { - $scope.cyberPanelLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: 'Connect disrupted, refresh the page.', - type: 'error' - }); - } - - - }; - - $scope.initConvert = function (virtualHost) { - $scope.domainName = virtualHost; - }; - - var statusFile; - - $scope.installationProgress = true; - - $scope.convert = function () { - - $scope.cyberPanelLoading = false; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.goBackDisable = true; - - $scope.currentStatus = "Starting creation.."; - - var ssl, dkimCheck, openBasedir; - - if ($scope.sslCheck === true) { - ssl = 1; - } else { - ssl = 0 - } - - if ($scope.dkimCheck === true) { - dkimCheck = 1; - } else { - dkimCheck = 0 - } - - if ($scope.openBasedir === true) { - openBasedir = 1; - } else { - openBasedir = 0 - } - - url = "/websites/convertDomainToSite"; - - - var data = { - package: $scope.packageForWebsite, - domainName: $scope.domainName, - adminEmail: $scope.adminEmail, - phpSelection: $scope.phpSelection, - websiteOwner: $scope.websiteOwner, - ssl: ssl, - dkimCheck: dkimCheck, - openBasedir: openBasedir - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.createWebSiteStatus === 1) { - statusFile = response.data.tempStatusPath; - getCreationStatus(); - } else { - - $scope.cyberPanelLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.goBackDisable = false; - - $scope.currentStatus = response.data.error_message; - } - - - } - - function cantLoadInitialDatas(response) { - - $scope.cyberPanelLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.goBackDisable = false; - - } - - - }; - $scope.goBack = function () { - $scope.cyberPanelLoading = true; - $scope.installationDetailsForm = false; - $scope.installationProgress = true; - $scope.goBackDisable = true; - $("#installProgress").css("width", "0%"); - }; - - function getCreationStatus() { - - url = "/websites/installWordpressStatus"; - - var data = { - statusFile: statusFile - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - - if (response.data.abort === 1) { - - if (response.data.installStatus === 1) { - - $scope.cyberPanelLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.goBackDisable = false; - - $("#installProgress").css("width", "100%"); - $scope.installPercentage = "100"; - $scope.currentStatus = response.data.currentStatus; - $timeout.cancel(); - - } else { - - $scope.cyberPanelLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.goBackDisable = false; - - $scope.currentStatus = response.data.error_message; - - $("#installProgress").css("width", "0%"); - $scope.installPercentage = "0"; - $scope.goBackDisable = false; - - } - - } else { - $("#installProgress").css("width", response.data.installationProgress + "%"); - $scope.installPercentage = response.data.installationProgress; - $scope.currentStatus = response.data.currentStatus; - $timeout(getCreationStatus, 1000); - } - - } - - function cantLoadInitialDatas(response) { - - $scope.cyberPanelLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.goBackDisable = false; - - } - - - } - - var DeleteDomain; - $scope.deleteDomainInit = function (childDomainForDeletion) { - DeleteDomain = childDomainForDeletion; - }; - - $scope.deleteChildDomain = function () { - $scope.cyberPanelLoading = false; - url = "/websites/submitDomainDeletion"; - - var data = { - websiteName: DeleteDomain, - DeleteDocRoot: $scope.DeleteDocRoot - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - function ListInitialDatas(response) { - $scope.cyberPanelLoading = true; - if (response.data.websiteDeleteStatus === 1) { - new PNotify({ - title: 'Success!', - text: 'Child Domain successfully deleted.', - type: 'success' - }); - $scope.getFurtherWebsitesFromDB(); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - } - } - - function cantLoadInitialDatas(response) { - $scope.cyberPanelLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: 'Could not connect to server, please refresh this page', - type: 'error' - }); - - } - - }; - -}); - -/* Java script code to list accounts ends here */ - - -/* Java script code to delete Website */ - - -$("#websiteDeleteFailure").hide(); -$("#websiteDeleteSuccess").hide(); - -$("#deleteWebsiteButton").hide(); -$("#deleteLoading").hide(); - -app.controller('deleteWebsiteControl', function ($scope, $http) { - - - $scope.deleteWebsite = function () { - - $("#deleteWebsiteButton").fadeIn(); - - - }; - - $scope.deleteWebsiteFinal = function () { - - $("#deleteLoading").show(); - - var websiteName = $scope.websiteToBeDeleted; - - - url = "/websites/submitWebsiteDeletion"; - - var data = { - websiteName: websiteName - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.websiteDeleteStatus === 0) { - $scope.errorMessage = response.data.error_message; - $("#websiteDeleteFailure").fadeIn(); - $("#websiteDeleteSuccess").hide(); - $("#deleteWebsiteButton").hide(); - - - $("#deleteLoading").hide(); - - } else { - $("#websiteDeleteFailure").hide(); - $("#websiteDeleteSuccess").fadeIn(); - $("#deleteWebsiteButton").hide(); - $scope.deletedWebsite = websiteName; - $("#deleteLoading").hide(); - - } - - - } - - function cantLoadInitialDatas(response) { - } - - - }; - -}); - - -/** - * Created by usman on 7/26/17. - */ -function getCookie(name) { - var cookieValue = null; - var t = document.cookie; - if (document.cookie && document.cookie !== '') { - var cookies = document.cookie.split(';'); - for (var i = 0; i < cookies.length; i++) { - var cookie = jQuery.trim(cookies[i]); - // Does this cookie string begin with the name we want? - if (cookie.substring(0, name.length + 1) === (name + '=')) { - cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); - break; - } - } - } - return cookieValue; -} - - -var arry = [] - -function selectpluginJs(val) { - $('#mysearch').hide() - arry.push(val) - - // console.log(arry) - document.getElementById('selJS').innerHTML = ""; - - for (var i = 0; i < arry.length; i++) { - $('#selJS').show() - var mlm = ' ' + arry[i] + '    ' - $('#selJS').append(mlm) - } - - -} - - -var DeletePluginURL; - -function DeletePluginBuucket(url) { - DeletePluginURL = url; -} - -function FinalDeletePluginBuucket() { - window.location.href = DeletePluginURL; -} - -var SPVal; - -app.controller('WPAddNewPlugin', function ($scope, $http, $timeout, $window, $compile) { - $scope.webSiteCreationLoading = true; - - $scope.SearchPluginName = function (val) { - $scope.webSiteCreationLoading = false; - SPVal = val; - url = "/websites/SearchOnkeyupPlugin"; - - var searchcontent = $scope.searchcontent; - - - var data = { - pluginname: searchcontent - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.webSiteCreationLoading = true; - - if (response.data.status === 1) { - if (SPVal == 'add') { - $('#mysearch').show() - document.getElementById('mysearch').innerHTML = ""; - var res = response.data.plugns.plugins - // console.log(res); - for (i = 0; i <= res.length; i++) { - // - var tml = '
    '; - $('#mysearch').append(tml); - } - } else if (SPVal == 'eidt') { - $('#mysearch').show() - document.getElementById('mysearch').innerHTML = ""; - var res = response.data.plugns.plugins - // console.log(res); - for (i = 0; i <= res.length; i++) { - // - var tml = '
    '; - var temp = $compile(tml)($scope) - angular.element(document.getElementById('mysearch')).append(temp); - } - - } - - - } else { - - // $scope.errorMessage = response.data.error_message; - alert("Status not = 1: Error..." + response.data.error_message) - } - - - } - - function cantLoadInitialDatas(response) { - - alert("Error..." + response) - - } - } - - $scope.AddNewplugin = function () { - - url = "/websites/AddNewpluginAjax"; - - var bucketname = $scope.PluginbucketName - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - var data = { - config: arry, - Name: bucketname - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - function ListInitialDatas(response) { - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Bucket created.', - type: 'success' - }); - location.reload(); - } else { - - new PNotify({ - title: 'Error!', - text: response.data.error_message, - type: 'error' - }); - } - - - } - - function cantLoadInitialDatas(response) { - - alert("Error..." + response) - - } - } - - $scope.deletesPlgin = function (val) { - - url = "/websites/deletesPlgin"; - - - var data = { - pluginname: val, - pluginbBucketID: $('#pluginbID').html() - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.status === 1) { - location.reload(); - - } else { - - // $scope.errorMessage = response.data.error_message; - alert("Status not = 1: Error..." + response.data.error_message) - } - - - } - - function cantLoadInitialDatas(response) { - - alert("Error..." + response) - - } - - } - - $scope.Addplugin = function (slug) { - $('#mysearch').hide() - - url = "/websites/Addplugineidt"; - - - var data = { - pluginname: slug, - pluginbBucketID: $('#pluginbID').html() - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.status === 1) { - location.reload(); - - } else { - - // $scope.errorMessage = response.data.error_message; - alert("Status not = 1: Error..." + response.data.error_message) - } - - - } - - function cantLoadInitialDatas(response) { - - alert("Error..." + response) - - } - - - } - -}); - -var domain_check = 0; - -function checkbox_function() { - - var checkBox = document.getElementById("myCheck"); - // Get the output text - - - // If the checkbox is checked, display the output text - if (checkBox.checked == true) { - domain_check = 0; - document.getElementById('Test_Domain').style.display = "block"; - document.getElementById('Own_Domain').style.display = "none"; - - } else { - document.getElementById('Test_Domain').style.display = "none"; - document.getElementById('Own_Domain').style.display = "block"; - domain_check = 1; - } - - // alert(domain_check); -} - -app.controller('createWordpress', function ($scope, $http, $timeout, $compile, $window) { - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - - - var statusFile; - - $scope.createWordPresssite = function () { - - $scope.webSiteCreationLoading = false; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - - - $scope.currentStatus = "Starting creation.."; - - var apacheBackend = 0; - - if ($scope.apacheBackend === true) { - apacheBackend = 1; - } else { - apacheBackend = 0 - } - - var package = $scope.packageForWebsite; - var websiteOwner = $scope.websiteOwner; - var WPtitle = $scope.WPtitle; - - // if (domain_check == 0) { - // var Part2_domainNameCreate = document.getElementById('Part2_domainNameCreate').value; - // var domainNameCreate = document.getElementById('TestDomainNameCreate').value + Part2_domainNameCreate; - // } - // if (domain_check == 1) { - // - // var domainNameCreate = $scope.own_domainNameCreate; - // } - - var domainNameCreate = $scope.domainNameCreate; - - - var WPUsername = $scope.WPUsername; - var adminEmail = $scope.adminEmail; - var WPPassword = $scope.WPPassword; - var WPVersions = $scope.WPVersions; - var pluginbucket = $scope.pluginbucket; - var autoupdates = $scope.autoupdates; - var pluginupdates = $scope.pluginupdates; - var themeupdates = $scope.themeupdates; - - if (domain_check == 0) { - - var path = ""; - - } - if (domain_check = 1) { - - var path = $scope.installPath; - - } - - - var home = "1"; - - if (typeof path != 'undefined') { - home = "0"; - } - - //alert(domainNameCreate); - var data = { - - title: WPtitle, - domain: domainNameCreate, - WPVersion: WPVersions, - pluginbucket: pluginbucket, - adminUser: WPUsername, - Email: adminEmail, - PasswordByPass: WPPassword, - AutomaticUpdates: autoupdates, - Plugins: pluginupdates, - Themes: themeupdates, - websiteOwner: websiteOwner, - package: package, - home: home, - path: path, - apacheBackend: apacheBackend - } - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - var url = "/websites/submitWorpressCreation"; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.webSiteCreationLoading = true; - if (response.data.status === 1) { - statusFile = response.data.tempStatusPath; - getCreationStatus(); - - } else { - $scope.goBackDisable = false; - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - } - - } - - function cantLoadInitialDatas(response) { - - alert("Error..." + response) - - } - - }; - $scope.goBack = function () { - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - $("#installProgress").css("width", "0%"); - }; - - function getCreationStatus() { - - url = "/websites/installWordpressStatus"; - - var data = { - statusFile: statusFile - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.abort === 1) { - - if (response.data.installStatus === 1) { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = false; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $("#installProgress").css("width", "100%"); - $scope.installPercentage = "100"; - $scope.currentStatus = response.data.currentStatus; - $timeout.cancel(); - - } else { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = false; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $scope.errorMessage = response.data.error_message; - - $("#installProgress").css("width", "0%"); - $scope.installPercentage = "0"; - $scope.goBackDisable = false; - - } - - } else { - $scope.webSiteCreationLoading = false; - $("#installProgress").css("width", response.data.installationProgress + "%"); - $scope.installPercentage = response.data.installationProgress; - $scope.currentStatus = response.data.currentStatus; - $timeout(getCreationStatus, 1000); - } - - } - - function cantLoadInitialDatas(response) { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - } - - -}); - - -//........... delete wp list -var FurlDeleteWP; - -function DeleteWPNow(url) { - FurlDeleteWP = url; -} - -function FinalDeleteWPNow() { - window.location.href = FurlDeleteWP; -} - -var DeploytoProductionID; - -function DeployToProductionInitial(vall) { - DeploytoProductionID = vall; -} - -var create_staging_domain_check = 0; - -function create_staging_checkbox_function() { - - try { - - var checkBox = document.getElementById("Create_Staging_Check"); - // Get the output text - - - // If the checkbox is checked, display the output text - if (checkBox.checked == true) { - create_staging_domain_check = 0; - document.getElementById('Website_Create_Test_Domain').style.display = "block"; - document.getElementById('Website_Create_Own_Domain').style.display = "none"; - - } else { - document.getElementById('Website_Create_Test_Domain').style.display = "none"; - document.getElementById('Website_Create_Own_Domain').style.display = "block"; - create_staging_domain_check = 1; - } - } catch (e) { - - } - - // alert(domain_check); -} - -create_staging_checkbox_function(); - -app.controller('WPsiteHome', function ($scope, $http, $timeout, $compile, $window) { - - var CheckBoxpasssword = 0; - - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - $(document).ready(function () { - var checkstatus = document.getElementById("wordpresshome"); - if (checkstatus !== null) { - $scope.LoadWPdata(); - - } - }); - - - $scope.LoadWPdata = function () { - - $scope.wordpresshomeloading = false; + $scope.UpdateWPSettings = function(wp) { $('#wordpresshomeloading').show(); - var url = "/websites/FetchWPdata"; - - var data = { - WPid: $('#WPid').html(), - } - - console.log(data); - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - wordpresshomeloading = true; - $('#wordpresshomeloading').hide(); - - if (response.data.status === 1) { - $('#WPVersion').text(response.data.ret_data.version); - if (response.data.ret_data.lscache === 1) { - $('#lscache').prop('checked', true); - } - if (response.data.ret_data.debugging === 1) { - $('#debugging').prop('checked', true); - } - if (response.data.ret_data.searchIndex === 1) { - $('#searchIndex').prop('checked', true); - } - if (response.data.ret_data.maintenanceMode === 1) { - $('#maintenanceMode').prop('checked', true); - } - if (response.data.ret_data.wpcron === 1) { - $('#wpcron').prop('checked', true); - } - if (response.data.ret_data.passwordprotection == 1) { - - var dc = '\n' + - ' ' - var mp = $compile(dc)($scope); - angular.element(document.getElementById('prsswdprodata')).append(mp); - CheckBoxpasssword = 1; - } else if (response.data.ret_data.passwordprotection == 0) { - var dc = '\n' + - ' ' - $('#prsswdprodata').append(dc); - CheckBoxpasssword = 0; - } - - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - }; - - $scope.UpdateWPSettings = function (setting) { - - $scope.wordpresshomeloading = false; - $('#wordpresshomeloading').show(); - - var url = "/websites/UpdateWPSettings"; + var data = {}; - if (setting === "PasswordProtection") { - if (CheckBoxpasssword == 0) { - var data = { - WPid: $('#WPid').html(), - setting: setting, - PPUsername: $scope.PPUsername, - PPPassword: $scope.PPPassword, - } - - } else { - var data = { - WPid: $('#WPid').html(), - setting: setting, - PPUsername: '', - PPPassword: '', - } - - } - - } else { - var settingValue = 0; - if ($('#' + setting).is(":checked")) { - settingValue = 1; - } - var data = { - WPid: $('#WPid').html(), - setting: setting, - settingValue: settingValue - } + if (wp.setting === "PasswordProtection") { + data = { + wpID: wp.id, + setting: wp.setting, + PPUsername: wp.PPUsername, + PPPassword: wp.PPPassword + }; } - var config = { headers: { - 'X-CSRFToken': getCookie('csrftoken') + 'X-CSRFToken': getCookie('csrftoken'), + 'Content-Type': 'application/x-www-form-urlencoded' + }, + transformRequest: function(obj) { + var str = []; + for(var p in obj) + str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); + return str.join("&"); } }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.wordpresshomeloading = true; + $http.post(url, data, config).then(function(response) { $('#wordpresshomeloading').hide(); - + if (response.data.status === 1) { new PNotify({ title: 'Success!', - text: 'Successfully Updated!.', + text: 'Successfully Updated!', type: 'success' }); - if (setting === "PasswordProtection") { + if (wp.setting === "PasswordProtection") { location.reload(); } } else { @@ -10495,2090 +6301,36 @@ app.controller('WPsiteHome', function ($scope, $http, $timeout, $compile, $windo text: response.data.error_message, type: 'error' }); - if (setting === "PasswordProtection") { + if (wp.setting === "PasswordProtection") { location.reload(); } - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - - - }; - - $scope.GetCurrentPlugins = function () { - $('#wordpresshomeloading').show(); - - $scope.wordpresshomeloading = false; - - var url = "/websites/GetCurrentPlugins"; - - var data = { - WPid: $('#WPid').html(), - } - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - wordpresshomeloading = true; - $('#wordpresshomeloading').hide(); - - if (response.data.status === 1) { - $('#PluginBody').html(''); - var plugins = JSON.parse(response.data.plugins); - plugins.forEach(AddPlugins); - - } else { - alert("Error:" + response.data.error_message) - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - }; - - $scope.GetCurrentThemes = function () { - $('#wordpresshomeloading').show(); - - $scope.wordpresshomeloading = false; - - var url = "/websites/GetCurrentThemes"; - - var data = { - WPid: $('#WPid').html(), - } - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - wordpresshomeloading = true; - $('#wordpresshomeloading').hide(); - - if (response.data.status === 1) { - - $('#ThemeBody').html(''); - var themes = JSON.parse(response.data.themes); - themes.forEach(AddThemes); - - } else { - alert("Error:" + response.data.error_message) - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - }; - - $scope.UpdatePlugins = function (plugin) { - $('#wordpresshomeloading').show(); - var data = { - plugin: plugin, - pluginarray: PluginsList, - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/UpdatePlugins"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Updating Plugins in Background!.', - type: 'success' - }); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - - - }; - - $scope.DeletePlugins = function (plugin) { - $('#wordpresshomeloading').show(); - var data = { - plugin: plugin, - pluginarray: PluginsList, - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/DeletePlugins"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Deleting Plugin in Background!', - type: 'success' - }); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - - } - - $scope.ChangeStatus = function (plugin) { - $('#wordpresshomeloading').show(); - var data = { - plugin: plugin, - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/ChangeStatus"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Changed Plugin state Successfully !.', - type: 'success' - }); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - - } - - function AddPlugins(value, index, array) { - var FinalMarkup = '' - FinalMarkup = FinalMarkup + ''; - for (let x in value) { - if (x === 'status') { - if (value[x] === 'inactive') { - FinalMarkup = FinalMarkup + '
    '; - } else { - FinalMarkup = FinalMarkup + '
    '; - } - } else if (x === 'update') { - if (value[x] === 'none') { - FinalMarkup = FinalMarkup + 'Upto Date'; - } else { - FinalMarkup = FinalMarkup + ''; - } - } else { - FinalMarkup = FinalMarkup + '' + value[x] + ""; - } - } - FinalMarkup = FinalMarkup + '' - FinalMarkup = FinalMarkup + '' - var temp = $compile(FinalMarkup)($scope) - AppendToTable('#PluginBody', temp) - } - - $scope.UpdateThemes = function (theme) { - $('#wordpresshomeloading').show(); - var data = { - Theme: theme, - Themearray: ThemesList, - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/UpdateThemes"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Updating Theme in background !.', - type: 'success' - }); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - - - }; - - $scope.DeleteThemes = function (theme) { - $('#wordpresshomeloading').show(); - var data = { - Theme: theme, - Themearray: ThemesList, - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/DeleteThemes"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Deleting Theme in Background!.', - type: 'success' - }); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - }; - - $scope.ChangeStatusThemes = function (theme) { - $('#wordpresshomeloading').show(); - var data = { - theme: theme, - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/StatusThemes"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Change Theme state in Bsckground!.', - type: 'success' - }); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - - }; - - function AddThemes(value, index, array) { - var FinalMarkup = '' - FinalMarkup = FinalMarkup + ''; - for (let x in value) { - if (x === 'status') { - if (value[x] === 'inactive') { - FinalMarkup = FinalMarkup + '
    '; - } else { - FinalMarkup = FinalMarkup + '
    '; - } - } else if (x === 'update') { - if (value[x] === 'none') { - FinalMarkup = FinalMarkup + 'Upto Date'; - } else { - FinalMarkup = FinalMarkup + ''; - } - } else { - FinalMarkup = FinalMarkup + '' + value[x] + ""; - } - } - FinalMarkup = FinalMarkup + '' - FinalMarkup = FinalMarkup + '' - var temp = $compile(FinalMarkup)($scope) - AppendToTable('#ThemeBody', temp) - } - - $scope.CreateStagingNow = function () { - $('#wordpresshomeloading').show(); - - $scope.wordpresshomeloading = false; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - - - $scope.currentStatus = "Starting creation Staging.."; - - //here enter domain name - if (create_staging_domain_check == 0) { - var Part2_domainNameCreate = document.getElementById('Part2_domainNameCreate').value; - var domainNameCreate = document.getElementById('TestDomainNameCreate').value + Part2_domainNameCreate; - } - if (create_staging_domain_check == 1) { - - var domainNameCreate = $scope.own_domainNameCreate; - } - var data = { - StagingName: $('#stagingName').val(), - StagingDomain: domainNameCreate, - WPid: $('#WPid').html(), - } - var url = "/websites/CreateStagingNow"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - if (response.data.status === 1) { - statusFile = response.data.tempStatusPath; - getCreationStatus(); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - }; - - function getCreationStatus() { - $('#wordpresshomeloading').show(); - - url = "/websites/installWordpressStatus"; - - var data = { - statusFile: statusFile - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - //$('#wordpresshomeloading').hide(); - - if (response.data.abort === 1) { - if (response.data.installStatus === 1) { - - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = false; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - - $("#installProgress").css("width", "100%"); - $("#installProgressbackup").css("width", "100%"); - $scope.installPercentage = "100"; - $scope.currentStatus = response.data.currentStatus; - $timeout.cancel(); - - - } else { - - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = false; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $scope.errorMessage = response.data.error_message; - - $("#installProgress").css("width", "0%"); - $("#installProgressbackup").css("width", "0%"); - $scope.installPercentage = "0"; - $scope.goBackDisable = false; - - - } - - } else { - - $("#installProgress").css("width", response.data.installationProgress + "%"); - $("#installProgressbackup").css("width", response.data.installationProgress + "%"); - $scope.installPercentage = response.data.installationProgress; - $scope.currentStatus = response.data.currentStatus; - $timeout(getCreationStatus, 1000); - - } - - } - - function cantLoadInitialDatas(response) { - //$('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - } - - $scope.goBack = function () { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - $("#installProgress").css("width", "0%"); - }; - - $scope.fetchstaging = function () { - - $('#wordpresshomeloading').show(); - $scope.wordpresshomeloading = false; - - var url = "/websites/fetchstaging"; - - var data = { - WPid: $('#WPid').html(), - } - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - wordpresshomeloading = true; - $('#wordpresshomeloading').hide(); - - if (response.data.status === 1) { - - // $('#ThemeBody').html(''); - // var themes = JSON.parse(response.data.themes); - // themes.forEach(AddThemes); - - $('#StagingBody').html(''); - var staging = JSON.parse(response.data.wpsites); - staging.forEach(AddStagings); - - } else { - alert("Error data.error_message:" + response.data.error_message) - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - alert("Error" + response) - - } - - }; - - $scope.fetchDatabase = function () { - - $('#wordpresshomeloading').show(); - $scope.wordpresshomeloading = false; - - var url = "/websites/fetchDatabase"; - - var data = { - WPid: $('#WPid').html(), - } - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - wordpresshomeloading = true; - $('#wordpresshomeloading').hide(); - - if (response.data.status === 1) { - $('#DB_Name').html(response.data.DataBaseName); - $('#DB_User').html(response.data.DataBaseUser); - $('#tableprefix').html(response.data.tableprefix); - } else { - alert("Error data.error_message:" + response.data.error_message) - - } - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - alert("Error" + response) - - } - - }; - - $scope.SaveUpdateConfig = function () { - $('#wordpresshomeloading').show(); - var data = { - AutomaticUpdates: $('#AutomaticUpdates').find(":selected").text(), - Plugins: $('#Plugins').find(":selected").text(), - Themes: $('#Themes').find(":selected").text(), - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/SaveUpdateConfig"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Update Configurations Sucessfully!.', - type: 'success' - }); - $("#autoUpdateConfig").modal('hide'); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - new PNotify({ - title: 'Operation Failed!', - text: response, - type: 'error' - }); - - } - }; - - function AddStagings(value, index, array) { - var FinalMarkup = '' - for (let x in value) { - if (x === 'name') { - FinalMarkup = FinalMarkup + '' + value[x] + ''; - } else if (x !== 'url' && x !== 'deleteURL' && x !== 'id') { - FinalMarkup = FinalMarkup + '' + value[x] + ""; - } - } - FinalMarkup = FinalMarkup + '' + - ' ' - FinalMarkup = FinalMarkup + '' - AppendToTable('#StagingBody', FinalMarkup); - } - - $scope.FinalDeployToProduction = function () { - - $('#wordpresshomeloading').show(); - - $scope.wordpresshomeloading = false; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - - var data = { - WPid: $('#WPid').html(), - StagingID: DeploytoProductionID - } - - var url = "/websites/DeploytoProduction"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - function ListInitialDatas(response) { - - $('#wordpresshomeloading').hide(); - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Deploy To Production start!.', - type: 'success' - }); - statusFile = response.data.tempStatusPath; - getCreationStatus(); - - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - new PNotify({ - title: 'Operation Failed!', - text: response, - type: 'error' - }); - - } - - }; - - - $scope.CreateBackup = function () { - $('#wordpresshomeloading').show(); - - $scope.wordpresshomeloading = false; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - $scope.currentStatus = "Starting creation Backups.."; - var data = { - WPid: $('#WPid').html(), - Backuptype: $('#backuptype').val() - } - var url = "/websites/WPCreateBackup"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $('createbackupbutton').hide(); - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Creating Backups!.', - type: 'success' - }); - statusFile = response.data.tempStatusPath; - getCreationStatus(); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - alert(response) - - } - - }; - - - $scope.installwpcore = function () { - - $('#wordpresshomeloading').show(); - $('#wordpresshomeloadingsec').show(); - var data = { - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/installwpcore"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $('#wordpresshomeloadingsec').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Results fetched..', - type: 'success' - }); - $('#SecurityResult').html(response.data.result); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $('#wordpresshomeloadingsec').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - - }; - - $scope.dataintegrity = function () { - - $('#wordpresshomeloading').show(); - $('#wordpresshomeloadingsec').show(); - var data = { - WPid: $('#WPid').html(), - } - - $scope.wordpresshomeloading = false; - - var url = "/websites/dataintegrity"; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $('#wordpresshomeloadingsec').hide(); - $scope.wordpresshomeloading = true; - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Results fetched', - type: 'success' - }); - $('#SecurityResult').html(response.data.result); - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - $('#wordpresshomeloadingsec').hide(); - $scope.wordpresshomeloading = true; - alert(response) - - } - }; - -}); - - -var PluginsList = []; - - -function AddPluginToArray(cBox, name) { - if (cBox.checked) { - PluginsList.push(name); - // alert(PluginsList); - } else { - const index = PluginsList.indexOf(name); - if (index > -1) { - PluginsList.splice(index, 1); - } - // alert(PluginsList); - } -} - -var ThemesList = []; - -function AddThemeToArray(cBox, name) { - if (cBox.checked) { - ThemesList.push(name); - // alert(ThemesList); - } else { - const index = ThemesList.indexOf(name); - if (index > -1) { - ThemesList.splice(index, 1); - } - // alert(ThemesList); - } -} - - -function AppendToTable(table, markup) { - $(table).append(markup); -} - - -//..................Restore Backup Home - - -app.controller('RestoreWPBackup', function ($scope, $http, $timeout, $window) { - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - - - $scope.checkmethode = function () { - var val = $('#RestoreMethode').children("option:selected").val(); - if (val == 1) { - $('#Newsitediv').show(); - $('#exinstingsitediv').hide(); - } else if (val == 0) { - $('#exinstingsitediv').show(); - $('#Newsitediv').hide(); - } else { - - } - }; - - - $scope.RestoreWPbackupNow = function () { - $('#wordpresshomeloading').show(); - $scope.wordpresshomeloading = false; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - $scope.currentStatus = "Start Restoring WordPress.."; - - var Domain = $('#wprestoresubdirdomain').val() - var path = $('#wprestoresubdirpath').val(); - var home = "1"; - - if (typeof path != 'undefined' || path != '') { - home = "0"; - } - if (typeof path == 'undefined') { - path = ""; - } - - - var backuptype = $('#backuptype').html(); - var data; - if (backuptype == "DataBase Backup") { - data = { - backupid: $('#backupid').html(), - DesSite: $('#DesSite').children("option:selected").val(), - Domain: '', - path: path, - home: home, - } - } else { - data = { - backupid: $('#backupid').html(), - DesSite: $('#DesSite').children("option:selected").val(), - Domain: Domain, - path: path, - home: home, - } - - } - - var url = "/websites/RestoreWPbackupNow"; - - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - // console.log(data) - - var d = $('#DesSite').children("option:selected").val(); - var c = $("input[name=Newdomain]").val(); - // if (d == -1 || c == "") { - // alert("Please Select Method of Backup Restore"); - // } else { - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - // } - - - function ListInitialDatas(response) { - wordpresshomeloading = true; - $('#wordpresshomeloading').hide(); - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Restoring process starts!.', - type: 'success' - }); - statusFile = response.data.tempStatusPath; - getCreationStatus(); - - } else { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = false; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $scope.errorMessage = response.data.error_message; - - } - - } - - function cantLoadInitialDatas(response) { - $('#wordpresshomeloading').hide(); - - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - - } - } - - function getCreationStatus() { - $('#wordpresshomeloading').show(); - - url = "/websites/installWordpressStatus"; - - var data = { - statusFile: statusFile - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - //$('#wordpresshomeloading').hide(); - - if (response.data.abort === 1) { - - if (response.data.installStatus === 1) { - - - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = false; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - - $("#installProgress").css("width", "100%"); - $("#installProgressbackup").css("width", "100%"); - $scope.installPercentage = "100"; - $scope.currentStatus = response.data.currentStatus; - $timeout.cancel(); - - - } else { - - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = false; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $scope.errorMessage = response.data.error_message; - - $("#installProgress").css("width", "0%"); - $("#installProgressbackup").css("width", "0%"); - $scope.installPercentage = "0"; - $scope.goBackDisable = false; - - - } - - } else { - - $("#installProgress").css("width", response.data.installationProgress + "%"); - $("#installProgressbackup").css("width", response.data.installationProgress + "%"); - $scope.installPercentage = response.data.installationProgress; - $scope.currentStatus = response.data.currentStatus; - $timeout(getCreationStatus, 1000); - - } - - } - - function cantLoadInitialDatas(response) { - //$('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - } - - $scope.goBack = function () { - $('#wordpresshomeloading').hide(); - $scope.wordpresshomeloading = true; - $scope.stagingDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - $("#installProgress").css("width", "0%"); - }; -}); - - -//.......................................Remote Backup - -//........... delete DeleteBackupConfigNow - -function DeleteBackupConfigNow(url) { - window.location.href = url; -} - -function DeleteRemoteBackupsiteNow(url) { - window.location.href = url; -} - -function DeleteBackupfileConfigNow(url) { - window.location.href = url; -} - - -app.controller('RemoteBackupConfig', function ($scope, $http, $timeout, $window) { - $scope.RemoteBackupLoading = true; - $scope.SFTPBackUpdiv = true; - - $scope.EndpointURLdiv = true; - $scope.Selectprovider = true; - $scope.S3keyNamediv = true; - $scope.Accesskeydiv = true; - $scope.SecretKeydiv = true; - $scope.SelectRemoteBackuptype = function () { - var val = $scope.RemoteBackuptype; - if (val == "SFTP") { - $scope.SFTPBackUpdiv = false; - $scope.EndpointURLdiv = true; - $scope.Selectprovider = true; - $scope.S3keyNamediv = true; - $scope.Accesskeydiv = true; - $scope.SecretKeydiv = true; - } else if (val == "S3") { - $scope.EndpointURLdiv = true; - $scope.Selectprovider = false; - $scope.S3keyNamediv = false; - $scope.Accesskeydiv = false; - $scope.SecretKeydiv = false; - $scope.SFTPBackUpdiv = true; - } else { - $scope.RemoteBackupLoading = true; - $scope.SFTPBackUpdiv = true; - - $scope.EndpointURLdiv = true; - $scope.Selectprovider = true; - $scope.S3keyNamediv = true; - $scope.Accesskeydiv = true; - $scope.SecretKeydiv = true; - } - } - - $scope.SelectProvidertype = function () { - $scope.EndpointURLdiv = true; - var provider = $scope.Providervalue - if (provider == 'Backblaze') { - $scope.EndpointURLdiv = false; - } else { - $scope.EndpointURLdiv = true; - } - } - - $scope.SaveBackupConfig = function () { - $scope.RemoteBackupLoading = false; - var Hname = $scope.Hostname; - var Uname = $scope.Username; - var Passwd = $scope.Password; - var path = $scope.path; - var type = $scope.RemoteBackuptype; - var Providervalue = $scope.Providervalue; - var data; - if (type == "SFTP") { - - data = { - Hname: Hname, - Uname: Uname, - Passwd: Passwd, - path: path, - type: type - } - } else if (type == "S3") { - if (Providervalue == "Backblaze") { - data = { - S3keyname: $scope.S3keyName, - Provider: Providervalue, - AccessKey: $scope.Accesskey, - SecertKey: $scope.SecretKey, - EndUrl: $scope.EndpointURL, - type: type - } - } else { - data = { - S3keyname: $scope.S3keyName, - Provider: Providervalue, - AccessKey: $scope.Accesskey, - SecertKey: $scope.SecretKey, - type: type - } - - } - - } - var url = "/websites/SaveBackupConfig"; - - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.RemoteBackupLoading = true; - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Successfully Saved!.', - type: 'success' - }); - location.reload(); - - - } else { - new PNotify({ - title: 'Error!', - text: response.data.error_message, - type: 'error' - }); - } - } - - function cantLoadInitialDatas(response) { - $scope.RemoteBackupLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - - } - - - } - -}); - -var UpdatescheduleID; -app.controller('BackupSchedule', function ($scope, $http, $timeout, $window) { - $scope.BackupScheduleLoading = true; - $scope.SaveBackupSchedule = function () { - $scope.RemoteBackupLoading = false; - var FileRetention = $scope.Fretention; - var Backfrequency = $scope.Bfrequency; - - - var data = { - FileRetention: FileRetention, - Backfrequency: Backfrequency, - ScheduleName: $scope.ScheduleName, - RemoteConfigID: $('#RemoteConfigID').html(), - BackupType: $scope.BackupType - } - var url = "/websites/SaveBackupSchedule"; - - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.RemoteBackupLoading = true; - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Successfully Saved!.', - type: 'success' - }); - location.reload(); - - - } else { - new PNotify({ - title: 'Error!', - text: response.data.error_message, - type: 'error' - }); - } - } - - function cantLoadInitialDatas(response) { - $scope.RemoteBackupLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - - } - - - }; - - - $scope.getupdateid = function (ID) { - UpdatescheduleID = ID; - } - - $scope.UpdateRemoteschedules = function () { - $scope.RemoteBackupLoading = false; - var Frequency = $scope.RemoteFrequency; - var fretention = $scope.RemoteFileretention; - - var data = { - ScheduleID: UpdatescheduleID, - Frequency: Frequency, - FileRetention: fretention - } - var url = "/websites/UpdateRemoteschedules"; - - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.RemoteBackupLoading = true; - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Successfully Updated!.', - type: 'success' - }); - location.reload(); - - - } else { - new PNotify({ - title: 'Error!', - text: response.data.error_message, - type: 'error' - }); - } - } - - function cantLoadInitialDatas(response) { - $scope.RemoteBackupLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - - } - }; - - $scope.AddWPsiteforRemoteBackup = function () { - $scope.RemoteBackupLoading = false; - - - var data = { - WpsiteID: $('#Wpsite').val(), - RemoteScheduleID: $('#RemoteScheduleID').html() - } - var url = "/websites/AddWPsiteforRemoteBackup"; - - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - $scope.RemoteBackupLoading = true; - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Successfully Saved!.', - type: 'success' - }); - location.reload(); - - - } else { - new PNotify({ - title: 'Error!', - text: response.data.error_message, - type: 'error' - }); - } - } - - function cantLoadInitialDatas(response) { - $scope.RemoteBackupLoading = true; - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - - - } - - - }; -}); -/* Java script code to create account */ - -var website_create_domain_check = 0; - -function website_create_checkbox_function() { - - var checkBox = document.getElementById("myCheck"); - // Get the output text - - - // If the checkbox is checked, display the output text - if (checkBox.checked == true) { - website_create_domain_check = 0; - document.getElementById('Website_Create_Test_Domain').style.display = "block"; - document.getElementById('Website_Create_Own_Domain').style.display = "none"; - - } else { - document.getElementById('Website_Create_Test_Domain').style.display = "none"; - document.getElementById('Website_Create_Own_Domain').style.display = "block"; - website_create_domain_check = 1; - } - - // alert(domain_check); -} - -app.controller('createWebsite', function ($scope, $http, $timeout, $window) { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - - var statusFile; - - $scope.createWebsite = function () { - - $scope.webSiteCreationLoading = false; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - - $scope.currentStatus = "Starting creation.."; - - var ssl, dkimCheck, openBasedir, mailDomain, apacheBackend; - - if ($scope.sslCheck === true) { - ssl = 1; - } else { - ssl = 0 - } - - if ($scope.apacheBackend === true) { - apacheBackend = 1; - } else { - apacheBackend = 0 - } - - if ($scope.dkimCheck === true) { - dkimCheck = 1; - } else { - dkimCheck = 0 - } - - if ($scope.openBasedir === true) { - openBasedir = 1; - } else { - openBasedir = 0 - } - - if ($scope.mailDomain === true) { - mailDomain = 1; - } else { - mailDomain = 0 - } - - - url = "/websites/submitWebsiteCreation"; - - var package = $scope.packageForWebsite; - - // if (website_create_domain_check == 0) { - // var Part2_domainNameCreate = document.getElementById('Part2_domainNameCreate').value; - // var domainName = document.getElementById('TestDomainNameCreate').value + Part2_domainNameCreate; - // } - // if (website_create_domain_check == 1) { - // - // var domainName = $scope.domainNameCreate; - // } - var domainName = $scope.domainNameCreate; - - // var domainName = $scope.domainNameCreate; - - var adminEmail = $scope.adminEmail; - var phpSelection = $scope.phpSelection; - var websiteOwner = $scope.websiteOwner; - - - var data = { - package: package, - domainName: domainName, - adminEmail: adminEmail, - phpSelection: phpSelection, - ssl: ssl, - websiteOwner: websiteOwner, - dkimCheck: dkimCheck, - openBasedir: openBasedir, - mailDomain: mailDomain, - apacheBackend: apacheBackend - }; - - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if (response.data.createWebSiteStatus === 1) { - statusFile = response.data.tempStatusPath; - getCreationStatus(); - } else { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = false; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $scope.errorMessage = response.data.error_message; - } - - - } - - function cantLoadInitialDatas(response) { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - }; - $scope.goBack = function () { - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = false; - $scope.installationProgress = true; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = true; - $("#installProgress").css("width", "0%"); - }; - - function getCreationStatus() { - - url = "/websites/installWordpressStatus"; - - var data = { - statusFile: statusFile - }; - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - - if (response.data.abort === 1) { - - if (response.data.installStatus === 1) { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = false; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $("#installProgress").css("width", "100%"); - $scope.installPercentage = "100"; - $scope.currentStatus = response.data.currentStatus; - $timeout.cancel(); - - } else { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = false; - $scope.success = true; - $scope.couldNotConnect = true; - $scope.goBackDisable = false; - - $scope.errorMessage = response.data.error_message; - - $("#installProgress").css("width", "0%"); - $scope.installPercentage = "0"; - $scope.goBackDisable = false; - - } - - } else { - $("#installProgress").css("width", response.data.installationProgress + "%"); - $scope.installPercentage = response.data.installationProgress; - $scope.currentStatus = response.data.currentStatus; - $timeout(getCreationStatus, 1000); - } - - } - - function cantLoadInitialDatas(response) { - - $scope.webSiteCreationLoading = true; - $scope.installationDetailsForm = true; - $scope.installationProgress = false; - $scope.errorMessageBox = true; - $scope.success = true; - $scope.couldNotConnect = false; - $scope.goBackDisable = false; - - } - - - } - -}); -/* Java script code to create account ends here */ - -/* Java script code to list accounts */ - -$("#listFail").hide(); - - -app.controller('listWebsites', function ($scope, $http, $window) { - $scope.web = {}; - $scope.WebSitesList = []; - - $scope.currentPage = 1; - $scope.recordsToShow = 10; - - // Initial fetch of websites - $scope.getFurtherWebsitesFromDB = function () { - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - var data = { - page: $scope.currentPage, - recordsToShow: $scope.recordsToShow - }; - - var dataurl = "/websites/fetchWebsitesList"; - - $http.post(dataurl, data, config).then(function(response) { - if (response.data.listWebSiteStatus === 1) { - $scope.WebSitesList = JSON.parse(response.data.data); - $scope.pagination = response.data.pagination; - $("#listFail").hide(); - } else { - $("#listFail").fadeIn(); - $scope.errorMessage = response.data.error_message; - } - }).catch(function(error) { - $("#listFail").fadeIn(); - $scope.errorMessage = error.message || 'An error occurred while fetching websites'; - }); - }; - - // Call it immediately - $scope.getFurtherWebsitesFromDB(); - - $scope.showWPSites = function(domain) { - console.log('showWPSites called for domain:', domain); - - // Make sure domain is defined - if (!domain) { - console.error('Domain is undefined'); - return; - } - - var url = '/websites/fetchWPDetails'; - var data = { - domain: domain - }; - - console.log('Making request to:', url, 'with data:', data); - - $http({ - method: 'POST', - url: url, - data: $.param(data), - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', - 'X-CSRFToken': getCookie('csrftoken') - } - }).then(function(response) { - console.log('Response received:', response); - if (response.data.status === 1 && response.data.fetchStatus === 1) { - // Find the website in the list and update its properties - $scope.WebSitesList.forEach(function(website) { - if (website.domain === domain) { - website.wp_sites = response.data.sites; - website.showWPSites = true; - console.log('Updated website:', website); - } - }); - $("#listFail").hide(); - } else { - $("#listFail").fadeIn(); - $scope.errorMessage = response.data.error_message || 'Failed to fetch WordPress sites'; - console.error('Error in response:', response.data.error_message); - } - }).catch(function(error) { - $("#listFail").fadeIn(); - $scope.errorMessage = error.message || 'An error occurred while fetching WordPress sites'; - console.error('Request failed:', error); - }); - }; - - $scope.visitSite = function(url) { - window.open(url, '_blank'); - }; - - $scope.wpLogin = function(wpId) { - window.open('/websites/wpLogin?wpID=' + wpId, '_blank'); - }; - - $scope.manageWP = function(wpId) { - window.location.href = '/websites/listWPsites?wpID=' + wpId; - }; - - $scope.currentWP = null; - $scope.PPUsername = ''; - $scope.PPPassword = ''; - - $scope.togglePasswordProtection = function(wp) { - if (!wp.passwordProtection) { - // Show password protection modal - $('#Passwordprotection').modal('show'); - $scope.currentWP = wp; - } else { - // Disable password protection - $scope.updateSetting(wp, 'password-protection', 0); - } - }; - - $scope.enablePasswordProtection = function() { - if (!$scope.PPUsername || !$scope.PPPassword) { - new PNotify({ - title: 'Error!', - text: 'Username and password are required.', - type: 'error' - }); - return; - } - - $scope.updateSetting($scope.currentWP, 'password-protection', 1); - $('#Passwordprotection').modal('hide'); - }; - - $scope.updateSetting = function(wp, setting, value) { - var data = { - WPid: wp.id, - setting: setting, - value: value - }; - - if (setting === 'password-protection' && value === 1) { - data.PPUsername = $scope.PPUsername; - data.PPPassword = $scope.PPPassword; - } - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post('/websites/UpdateWPSettings', data, config).then(function(response) { - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Setting updated successfully.', - type: 'success' - }); - if (setting === 'password-protection') { - wp.passwordProtection = value; - // Reset form - $scope.PPUsername = ''; - $scope.PPPassword = ''; - $scope.currentWP = null; - } - } else { - new PNotify({ - title: 'Error!', - text: response.data.error_message, - type: 'error' - }); } }, function(error) { + $('#wordpresshomeloading').hide(); new PNotify({ - title: 'Error!', - text: 'An error occurred while updating the setting.', + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', type: 'error' }); - console.error(error); }); }; + $scope.togglePasswordProtection = function(wp) { + if (wp.passwordProtection) { + // Show modal or form to collect username/password + wp.setting = "PasswordProtection"; + wp.PPUsername = ""; + wp.PPPassword = ""; + $('#passwordProtectionModal').modal('show'); + } else { + // Disable password protection + wp.setting = "PasswordProtection"; + wp.PPUsername = ""; + wp.PPPassword = ""; + $scope.UpdateWPSettings(wp); + } + }; + $scope.cyberPanelLoading = true; $scope.issueSSL = function (virtualHost) { @@ -16482,6 +10234,82 @@ app.controller('manageAliasController', function ($scope, $http, $timeout, $wind }); }; + $scope.UpdateWPSettings = function(wp) { + $('#wordpresshomeloading').show(); + + var url = "/websites/UpdateWPSettings"; + var data = {}; + + if (wp.setting === "PasswordProtection") { + data = { + wpID: wp.id, + setting: wp.setting, + PPUsername: wp.PPUsername, + PPPassword: wp.PPPassword + }; + } + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken'), + 'Content-Type': 'application/x-www-form-urlencoded' + }, + transformRequest: function(obj) { + var str = []; + for(var p in obj) + str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); + return str.join("&"); + } + }; + + $http.post(url, data, config).then(function(response) { + $('#wordpresshomeloading').hide(); + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Successfully Updated!', + type: 'success' + }); + if (wp.setting === "PasswordProtection") { + location.reload(); + } + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + if (wp.setting === "PasswordProtection") { + location.reload(); + } + } + }, function(error) { + $('#wordpresshomeloading').hide(); + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); + }); + }; + + $scope.togglePasswordProtection = function(wp) { + if (wp.passwordProtection) { + // Show modal or form to collect username/password + wp.setting = "PasswordProtection"; + wp.PPUsername = ""; + wp.PPPassword = ""; + $('#passwordProtectionModal').modal('show'); + } else { + // Disable password protection + wp.setting = "PasswordProtection"; + wp.PPUsername = ""; + wp.PPPassword = ""; + $scope.UpdateWPSettings(wp); + } + }; + $scope.visitSite = function(url) { window.open(url, '_blank'); }; From b9a1a079d78f05def278405fcc948564e0b5721f Mon Sep 17 00:00:00 2001 From: usmannasir Date: Sat, 5 Apr 2025 21:35:01 +0500 Subject: [PATCH 035/273] add pp protection model and seprate function --- .../websiteFunctions/websiteFunctions.js | 198 +++++++++++++----- 1 file changed, 147 insertions(+), 51 deletions(-) diff --git a/websiteFunctions/static/websiteFunctions/websiteFunctions.js b/websiteFunctions/static/websiteFunctions/websiteFunctions.js index af65ab946..25dc912ec 100755 --- a/websiteFunctions/static/websiteFunctions/websiteFunctions.js +++ b/websiteFunctions/static/websiteFunctions/websiteFunctions.js @@ -6255,66 +6255,162 @@ app.controller('listWebsites', function ($scope, $http, $window) { }); }; - $scope.UpdateWPSettings = function(wp) { - $('#wordpresshomeloading').show(); + // First, update the updateSetting function to handle all settings except password protection +$scope.updateSetting = function(wp, setting) { + var settingMap = { + 'search-indexing': 'searchIndex', + 'debugging': 'debugging', + 'maintenance-mode': 'maintenanceMode' + }; - var url = "/websites/UpdateWPSettings"; - var data = {}; + var data = { + wpID: wp.id, + setting: setting, + value: wp[settingMap[setting]] ? 'enable' : 'disable' + }; - if (wp.setting === "PasswordProtection") { - data = { - wpID: wp.id, - setting: wp.setting, - PPUsername: wp.PPUsername, - PPPassword: wp.PPPassword - }; + $http({ + method: 'POST', + url: '/websites/UpdateWPSettings', + data: data, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'X-CSRFToken': getCookie('csrftoken') + }, + transformRequest: function(obj) { + var str = []; + for(var p in obj) + str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); + return str.join("&"); } - - var config = { - headers: { - 'X-CSRFToken': getCookie('csrftoken'), - 'Content-Type': 'application/x-www-form-urlencoded' - }, - transformRequest: function(obj) { - var str = []; - for(var p in obj) - str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); - return str.join("&"); - } - }; - - $http.post(url, data, config).then(function(response) { - $('#wordpresshomeloading').hide(); - - if (response.data.status === 1) { - new PNotify({ - title: 'Success!', - text: 'Successfully Updated!', - type: 'success' - }); - if (wp.setting === "PasswordProtection") { - location.reload(); - } - } else { - new PNotify({ - title: 'Operation Failed!', - text: response.data.error_message, - type: 'error' - }); - if (wp.setting === "PasswordProtection") { - location.reload(); - } - } - }, function(error) { - $('#wordpresshomeloading').hide(); + }).then(function(response) { + if (response.data.status === 1) { new PNotify({ - title: 'Operation Failed!', - text: 'Could not connect to server, please refresh this page', + title: 'Success', + text: 'Setting updated successfully.', + type: 'success' + }); + } else { + wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change + new PNotify({ + title: 'Error', + text: response.data.error_message || 'Failed to update setting.', type: 'error' }); + } + }).catch(function(error) { + wp[settingMap[setting]] = !wp[settingMap[setting]]; // Revert the change + new PNotify({ + title: 'Error', + text: 'Connection failed while updating setting.', + type: 'error' }); + }); +}; + +// Handle password protection specifically +$scope.togglePasswordProtection = function(wp) { + if (wp.passwordProtection) { + // Show modal for credentials + wp.PPUsername = ""; + wp.PPPassword = ""; + $('#passwordProtectionModal').modal('show'); + $scope.currentWP = wp; // Store current WP site + } else { + // Disable password protection + var data = { + wpID: wp.id, + setting: 'PasswordProtection', + PPUsername: '', + PPPassword: '' + }; + $scope.UpdateWPSettings(data); + } +}; + +// Handle the actual password protection update +$scope.UpdateWPSettings = function(data) { + $('#wordpresshomeloading').show(); + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken'), + 'Content-Type': 'application/x-www-form-urlencoded' + }, + transformRequest: function(obj) { + var str = []; + for(var p in obj) + str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); + return str.join("&"); + } }; + $http.post('/websites/UpdateWPSettings', data, config).then(function(response) { + $('#wordpresshomeloading').hide(); + + if (response.data.status === 1) { + new PNotify({ + title: 'Success!', + text: 'Successfully Updated!', + type: 'success' + }); + location.reload(); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message || 'Failed to update password protection.', + type: 'error' + }); + // Revert the checkbox + if ($scope.currentWP) { + $scope.currentWP.passwordProtection = !$scope.currentWP.passwordProtection; + } + } + }, function(error) { + $('#wordpresshomeloading').hide(); + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); + // Revert the checkbox + if ($scope.currentWP) { + $scope.currentWP.passwordProtection = !$scope.currentWP.passwordProtection; + } + }); +}; + +// Function to submit password protection from modal +$scope.submitPasswordProtection = function() { + if (!$scope.currentWP) { + new PNotify({ + title: 'Error!', + text: 'No WordPress site selected.', + type: 'error' + }); + return; + } + + if (!$scope.currentWP.PPUsername || !$scope.currentWP.PPPassword) { + new PNotify({ + title: 'Error!', + text: 'Please provide both username and password', + type: 'error' + }); + return; + } + + var data = { + wpID: $scope.currentWP.id, + setting: 'PasswordProtection', + PPUsername: $scope.currentWP.PPUsername, + PPPassword: $scope.currentWP.PPPassword + }; + + $('#passwordProtectionModal').modal('hide'); + $scope.UpdateWPSettings(data); +}; + $scope.togglePasswordProtection = function(wp) { if (wp.passwordProtection) { // Show modal or form to collect username/password From 28fec8ba4e1c3fa006dc627970a4fcf29218e58c Mon Sep 17 00:00:00 2001 From: usmannasir Date: Sun, 6 Apr 2025 16:19:57 +0500 Subject: [PATCH 036/273] fix a js issue in listwebsites.html --- .../websiteFunctions/listWebsites.html | 39 +++++++++---------- 1 file changed, 19 insertions(+), 20 deletions(-) diff --git a/websiteFunctions/templates/websiteFunctions/listWebsites.html b/websiteFunctions/templates/websiteFunctions/listWebsites.html index 12c7ecf79..c03f721b9 100755 --- a/websiteFunctions/templates/websiteFunctions/listWebsites.html +++ b/websiteFunctions/templates/websiteFunctions/listWebsites.html @@ -17,31 +17,30 @@ -