From 6e3310d7db9c8943fb3690e3104047ee67abacf7 Mon Sep 17 00:00:00 2001 From: Usman Nasir Date: Sat, 3 Aug 2019 14:53:31 +0500 Subject: [PATCH] bug fix to wp staging --- api/views.py | 2 +- cloudAPI/cloudManager.py | 13 +- install/install.py | 4 +- loginSystem/views.py | 2 +- packages/models.py | 1 + packages/packagesManager.py | 18 +- packages/static/packages/packages.js | 333 ++- .../templates/packages/createPackage.html | 223 +- .../templates/packages/modifyPackage.html | 13 + plogical/acl.py | 12 + plogical/adminPass.py | 2 +- plogical/cPanelImporter.py | 3 + plogical/mysqlUtilities.py | 36 +- plogical/processUtilities.py | 9 + plogical/upgrade.py | 39 +- plogical/vhost.py | 7 +- plogical/virtualHostUtilities.py | 9 + requirments.txt | 1 - serverStatus/views.py | 1 - static/websiteFunctions/websiteFunctions.js | 303 +- userManagment/views.py | 10 +- websiteFunctions/StagingSetup.py | 227 ++ .../websiteFunctions/websiteFunctions.js | 304 +- .../websiteFunctions/createWebsite.html | 4 - .../websiteFunctions/launchChild.html | 1 + .../websiteFunctions/setupStaging.html | 88 + .../websiteFunctions/syncMaster.html | 104 + .../templates/websiteFunctions/website.html | 1 + websiteFunctions/urls.py | 7 + websiteFunctions/views.py | 37 +- websiteFunctions/website.py | 2482 +++++++++++++++++ 31 files changed, 3953 insertions(+), 343 deletions(-) create mode 100644 websiteFunctions/StagingSetup.py create mode 100755 websiteFunctions/templates/websiteFunctions/setupStaging.html create mode 100755 websiteFunctions/templates/websiteFunctions/syncMaster.html create mode 100755 websiteFunctions/website.py diff --git a/api/views.py b/api/views.py index 3be35b466..ca819a439 100755 --- a/api/views.py +++ b/api/views.py @@ -13,7 +13,7 @@ from websiteFunctions.models import Websites import os from baseTemplate.models import version from plogical.mailUtilities import mailUtilities -from plogical.website import WebsiteManager +from websiteFunctions.website import WebsiteManager from s3Backups.s3Backups import S3Backups from plogical.CyberCPLogFileWriter import CyberCPLogFileWriter as logging from plogical.processUtilities import ProcessUtilities diff --git a/cloudAPI/cloudManager.py b/cloudAPI/cloudManager.py index 9cdf6e1d1..ee62f4859 100755 --- a/cloudAPI/cloudManager.py +++ b/cloudAPI/cloudManager.py @@ -1,9 +1,3 @@ -import json -import os -from random import randint - -from django.shortcuts import HttpResponse - import userManagment.views as um from backup.backupManager import BackupManager from databases.databaseManager import DatabaseManager @@ -15,22 +9,17 @@ from loginSystem.models import Administrator from mailServer.mailserverManager import MailServerManager from manageSSL.views import issueSSL, obtainHostNameSSL, obtainMailServerSSL from packages.packagesManager import PackagesManager -from plogical.acl import ACLManager -from plogical.httpProc import httpProc from plogical.mysqlUtilities import mysqlUtilities -from plogical.processUtilities import ProcessUtilities from plogical.virtualHostUtilities import virtualHostUtilities -from plogical.website import WebsiteManager +from websiteFunctions.website import WebsiteManager from s3Backups.s3Backups import S3Backups from serverLogs.views import getLogsFromFile from serverStatus.views import topProcessesStatus, killProcess, switchTOLSWSStatus -from websiteFunctions.models import Websites from plogical import hashPassword from loginSystem.models import ACL from plogical.CyberCPLogFileWriter import CyberCPLogFileWriter as logging from managePHP.phpManager import PHPManager from managePHP.views import submitExtensionRequest, getRequestStatusApache -from containerization.containerManager import ContainerManager from containerization.views import * diff --git a/install/install.py b/install/install.py index 6a4ab1e79..ccc04a042 100755 --- a/install/install.py +++ b/install/install.py @@ -952,7 +952,7 @@ class preFlightsChecks: os.chdir(self.path) - command = "wget http://cyberpanel.sh/CyberPanel.1.8.7.tar.gz" + command = "wget http://cyberpanel.sh/CyberPanel.1.8.8.tar.gz" #command = "wget http://cyberpanel.sh/CyberPanelTemp.tar.gz" preFlightsChecks.call(command, self.distro, '[download_install_CyberPanel]', 'CyberPanel Download', @@ -961,7 +961,7 @@ class preFlightsChecks: ## count = 0 - command = "tar zxf CyberPanel.1.8.7.tar.gz" + command = "tar zxf CyberPanel.1.8.8.tar.gz" #command = "tar zxf CyberPanelTemp.tar.gz" preFlightsChecks.call(command, self.distro, '[download_install_CyberPanel]', 'Extract CyberPanel',1, 1, os.EX_OSERR) diff --git a/loginSystem/views.py b/loginSystem/views.py index d89fe4748..7c5dcf998 100755 --- a/loginSystem/views.py +++ b/loginSystem/views.py @@ -218,7 +218,7 @@ def loadLoginPage(request): firstName="Cyber",lastName="Panel", acl=acl, token=token) admin.save() - vers = version(currentVersion="1.8", build=7) + vers = version(currentVersion="1.8", build=8) vers.save() package = Package(admin=admin, packageName="Default", diskSpace=1000, diff --git a/packages/models.py b/packages/models.py index 145d09259..50a8931a7 100755 --- a/packages/models.py +++ b/packages/models.py @@ -15,3 +15,4 @@ class Package(models.Model): dataBases = models.IntegerField(default=0) ftpAccounts = models.IntegerField(default=0) allowedDomains = models.IntegerField(default=0) + allowFullDomain = models.IntegerField(default=1) diff --git a/packages/packagesManager.py b/packages/packagesManager.py index f1efe1f18..2b7849d4e 100755 --- a/packages/packagesManager.py +++ b/packages/packagesManager.py @@ -74,6 +74,12 @@ class PackagesManager: except: api = '0' + try: + allowFullDomain = int(data['allowFullDomain']) + except: + allowFullDomain = 1 + + if packageSpace < 0 or packageBandwidth < 0 or packageDatabases < 0 or ftpAccounts < 0 or emails < 0 or allowedDomains < 0: data_ret = {'saveStatus': 0, 'error_message': "All values should be positive or 0."} json_data = json.dumps(data_ret) @@ -86,7 +92,7 @@ class PackagesManager: package = Package(admin=admin, packageName=packageName, diskSpace=packageSpace, bandwidth=packageBandwidth, ftpAccounts=ftpAccounts, dataBases=packageDatabases, - emailAccounts=emails, allowedDomains=allowedDomains) + emailAccounts=emails, allowedDomains=allowedDomains, allowFullDomain=allowFullDomain) package.save() @@ -156,9 +162,10 @@ class PackagesManager: dataBases = modifyPack.dataBases emails = modifyPack.emailAccounts + data_ret = {'emails': emails, 'modifyStatus': 1, 'error_message': "None", "diskSpace": diskSpace, "bandwidth": bandwidth, "ftpAccounts": ftpAccounts, - "dataBases": dataBases, "allowedDomains": modifyPack.allowedDomains} + "dataBases": dataBases, "allowedDomains": modifyPack.allowedDomains, 'allowFullDomain': modifyPack.allowFullDomain} json_data = json.dumps(data_ret) return HttpResponse(json_data) @@ -194,6 +201,13 @@ class PackagesManager: modifyPack.dataBases = data['dataBases'] modifyPack.emailAccounts = data['emails'] modifyPack.allowedDomains = data['allowedDomains'] + + try: + modifyPack.allowFullDomain = int(data['allowFullDomain']) + except: + modifyPack.allowFullDomain = 1 + + modifyPack.save() data_ret = {'status': 1, 'saveStatus': 1, 'error_message': "None"} diff --git a/packages/static/packages/packages.js b/packages/static/packages/packages.js index 925f00e40..84bd8a9fb 100755 --- a/packages/static/packages/packages.js +++ b/packages/static/packages/packages.js @@ -3,13 +3,11 @@ */ - /** * Created by usman on 7/25/17. */ - /* Utilities */ function getCookie(name) { @@ -31,72 +29,74 @@ function getCookie(name) { /* Utilities ends here */ - - /* Java script code to create Pacakge */ $("#packageCreationFailed").hide(); $("#packageCreated").hide(); - -app.controller('createPackage', function($scope,$http) { +app.controller('createPackage', function ($scope, $http) { //$scope.pname = /([A-Z]){3,10}/gi; - $scope.insertPackInDB = function(){ - - var packageName = $scope.packageName; - var diskSpace = $scope.diskSpace; - var bandwidth = $scope.bandwidth; - var ftpAccounts = $scope.ftpAccounts; - var dataBases = $scope.dataBases; - var emails = $scope.emails; + $scope.insertPackInDB = function () { - url = "/packages/submitPackage"; + var packageName = $scope.packageName; + var diskSpace = $scope.diskSpace; + var bandwidth = $scope.bandwidth; + var ftpAccounts = $scope.ftpAccounts; + var dataBases = $scope.dataBases; + var emails = $scope.emails; - var data = { - packageName: packageName, - diskSpace: diskSpace, - bandwidth: bandwidth, - ftpAccounts: ftpAccounts, - dataBases: dataBases, - emails:emails, - allowedDomains:$scope.allowedDomains - }; - - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + if($scope.allowFullDomain === undefined){ + $scope.allowFullDomain = 0; + } - function ListInitialDatas(response) { - console.log(response.data) + url = "/packages/submitPackage"; - if (response.data.saveStatus == 0) - { - $scope.errorMessage = response.data.error_message; - $("#packageCreationFailed").fadeIn(); - $("#packageCreated").hide(); + var data = { + packageName: packageName, + diskSpace: diskSpace, + bandwidth: bandwidth, + ftpAccounts: ftpAccounts, + dataBases: dataBases, + emails: emails, + allowedDomains: $scope.allowedDomains, + allowFullDomain: $scope.allowFullDomain + }; - } - else{ - $("#packageCreationFailed").hide(); - $("#packageCreated").fadeIn(); - $scope.createdPackage = $scope.packageName; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - } + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - } - function cantLoadInitialDatas(response) { - console.log("not good"); - } + function ListInitialDatas(response) { + console.log(response.data) + + if (response.data.saveStatus == 0) { + $scope.errorMessage = response.data.error_message; + $("#packageCreationFailed").fadeIn(); + $("#packageCreated").hide(); + + } else { + $("#packageCreationFailed").hide(); + $("#packageCreated").fadeIn(); + $scope.createdPackage = $scope.packageName; + + } + + + } + + function cantLoadInitialDatas(response) { + console.log("not good"); + } }; @@ -107,7 +107,6 @@ app.controller('createPackage', function($scope,$http) { /* Java script code to to create Pacakge ends here */ - /* Java script code to delete Pacakge */ @@ -117,62 +116,60 @@ $("#deleteSuccess").hide(); $("#deletePackageButton").hide(); -app.controller('deletePackage', function($scope,$http) { +app.controller('deletePackage', function ($scope, $http) { - $scope.deletePackage = function(){ + $scope.deletePackage = function () { $("#deletePackageButton").fadeIn(); }; - $scope.deletePackageFinal = function(){ + $scope.deletePackageFinal = function () { - var packageName = $scope.packageToBeDeleted; + var packageName = $scope.packageToBeDeleted; + url = "/packages/submitDelete"; - url = "/packages/submitDelete"; + var data = { + packageName: packageName, + }; - var data = { - packageName: packageName, - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { - console.log(response.data) + function ListInitialDatas(response) { + console.log(response.data) - if (response.data.deleteStatus == 0) - { - $scope.errorMessage = response.data.error_message; - $("#deleteFailure").fadeIn(); - $("#deleteSuccess").hide(); - $("#deletePackageButton").hide(); + if (response.data.deleteStatus == 0) { + $scope.errorMessage = response.data.error_message; + $("#deleteFailure").fadeIn(); + $("#deleteSuccess").hide(); + $("#deletePackageButton").hide(); - } - else{ - $("#deleteFailure").hide(); - $("#deleteSuccess").fadeIn(); - $("#deletePackageButton").hide(); - $scope.deletedPackage = packageName; + } else { + $("#deleteFailure").hide(); + $("#deleteSuccess").fadeIn(); + $("#deletePackageButton").hide(); + $scope.deletedPackage = packageName; - } + } - } - function cantLoadInitialDatas(response) { - console.log("not good"); - } + } + + function cantLoadInitialDatas(response) { + console.log("not good"); + } }; @@ -180,11 +177,9 @@ app.controller('deletePackage', function($scope,$http) { }); - /* Java script code to delete package ends here */ - /* Java script code modify package */ $("#packageDetailsToBeModified").hide(); @@ -194,9 +189,9 @@ $("#modifyButton").hide(); $("#packageLoading").hide(); $("#successfullyModified").hide(); -app.controller('modifyPackages', function($scope,$http) { +app.controller('modifyPackages', function ($scope, $http) { - $scope.fetchDetails = function(){ + $scope.fetchDetails = function () { $("#packageLoading").show(); $("#successfullyModified").hide(); @@ -207,63 +202,65 @@ app.controller('modifyPackages', function($scope,$http) { url = "/packages/submitModify"; - var data = { - packageName: packageName, - }; + var data = { + packageName: packageName, + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if (response.data.modifyStatus == 0) - { - $scope.errorMessage = response.data.error_message; - $("#modifyFailure").fadeIn(); - $("#modifySuccess").hide(); - $("#modifyButton").hide(); - $("#packageLoading").hide(); + if (response.data.modifyStatus === 0) { + $scope.errorMessage = response.data.error_message; + $("#modifyFailure").fadeIn(); + $("#modifySuccess").hide(); + $("#modifyButton").hide(); + $("#packageLoading").hide(); - } - else{ - $("#modifyButton").show(); - $scope.diskSpace = response.data.diskSpace; - $scope.bandwidth = response.data.bandwidth; - $scope.ftpAccounts = response.data.ftpAccounts; - $scope.dataBases = response.data.dataBases; - $scope.emails = response.data.emails; - $scope.allowedDomains = response.data.allowedDomains; - - $scope.modifyButton = "Save Details" - - $("#packageDetailsToBeModified").fadeIn(); - - $("#modifyFailure").hide(); - $("#modifySuccess").fadeIn(); - $("#packageLoading").hide(); - - - - - } - + } else { + $("#modifyButton").show(); + $scope.diskSpace = response.data.diskSpace; + $scope.bandwidth = response.data.bandwidth; + $scope.ftpAccounts = response.data.ftpAccounts; + $scope.dataBases = response.data.dataBases; + $scope.emails = response.data.emails; + $scope.allowedDomains = response.data.allowedDomains; + if (response.data.allowFullDomain === 1) { + $scope.allowFullDomain = true; + } else { + $scope.allowFullDomain = false; } - function cantLoadInitialDatas(response) { - console.log("not good"); - } + + $scope.modifyButton = "Save Details" + + $("#packageDetailsToBeModified").fadeIn(); + + $("#modifyFailure").hide(); + $("#modifySuccess").fadeIn(); + $("#packageLoading").hide(); + + + } + + + } + + function cantLoadInitialDatas(response) { + console.log("not good"); + } }; - $scope.modifyPackageFunc = function () { var packageName = $scope.packageToBeModified; @@ -281,56 +278,53 @@ app.controller('modifyPackages', function($scope,$http) { url = "/packages/saveChanges"; - var data = { - packageName: packageName, - diskSpace:diskSpace, - bandwidth:bandwidth, - ftpAccounts:ftpAccounts, - dataBases:dataBases, - emails:emails, - allowedDomains:$scope.allowedDomains, - }; + var data = { + packageName: packageName, + diskSpace: diskSpace, + bandwidth: bandwidth, + ftpAccounts: ftpAccounts, + dataBases: dataBases, + emails: emails, + allowedDomains: $scope.allowedDomains, + allowFullDomain: $scope.allowFullDomain + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if (response.data.saveStatus == 0) - { - $scope.errorMessage = response.data.error_message; - $("#modifyFailure").fadeIn(); - $("#modifySuccess").hide(); - $("#modifyButton").hide(); - $("#packageLoading").hide(); + if (response.data.saveStatus === 0) { + $scope.errorMessage = response.data.error_message; + $("#modifyFailure").fadeIn(); + $("#modifySuccess").hide(); + $("#modifyButton").hide(); + $("#packageLoading").hide(); - } - else{ - $("#modifyButton").hide(); + } else { + $("#modifyButton").hide(); - $("#successfullyModified").fadeIn(); - $("#modifyFailure").hide(); - $("#packageLoading").hide(); - $scope.packageModified = packageName; + $("#successfullyModified").fadeIn(); + $("#modifyFailure").hide(); + $("#packageLoading").hide(); + $scope.packageModified = packageName; + } - } - - - } - function cantLoadInitialDatas(response) { - console.log("not good"); - } + } + function cantLoadInitialDatas(response) { + console.log("not good"); + } }; @@ -338,5 +332,4 @@ app.controller('modifyPackages', function($scope,$http) { }); - /* Java script code to Modify Pacakge ends here */ diff --git a/packages/templates/packages/createPackage.html b/packages/templates/packages/createPackage.html index 116c06245..a498f9b06 100755 --- a/packages/templates/packages/createPackage.html +++ b/packages/templates/packages/createPackage.html @@ -3,112 +3,127 @@ {% block title %}{% trans "Create Package - CyberPanel" %}{% endblock %} {% block content %} -{% load static %} -{% get_current_language as LANGUAGE_CODE %} - - - -
-
-

{% trans "Create Package" %}

-

{% trans "Packages define resources for your websites, you need to add package before creating a website." %}

-
-
-
-

- {% trans "Package Details" %} -

-
- - -
-
- -
- -
- -
{{ admin }}_{$ packageName $}
-
- -
- -
- -
-
{% trans "(0 = Unlimited)" %}
-
- -
- -
- -
-
{% trans "MB (0 = Unlimited)" %}
-
- -
- -
- -
-
{% trans "MB (0 = Unlimited)" %}
-
- - -
- -
- -
-
- -
- -
- -
-
- - -
- -
- -
-
- -
- -
- -
-
- -
- -
-
-

{% trans "Cannot create package. Error message:" %} {$ errorMessage $}

-
- -
-

{% trans "Package" %} {$ createdPackage $} {% trans "Successfully Created" %}

-
-
- -
- - -
- - + {% load static %} + {% get_current_language as LANGUAGE_CODE %} + +
+
+

{% trans "Create Package" %}

+

{% trans "Packages define resources for your websites, you need to add package before creating a website." %}

+
+
+

+ {% trans "Package Details" %} +

+
+ + +
+
+ +
+ +
+ +
{{ admin }}_{$ packageName $}
+
+ +
+ +
+ +
+
{% trans "(0 = Unlimited)" %}
+
+ +
+ +
+ +
+
{% trans "MB (0 = Unlimited)" %}
+
+ +
+ +
+ +
+
{% trans "MB (0 = Unlimited)" %}
+
+ + +
+ +
+ +
+
+ +
+ +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + +
+
+ +
+
+
+ +
+ +
+ +
+
+ +
+ +
+
+

{% trans "Cannot create package. Error message:" %} {$ errorMessage $}

+
+ +
+

{% trans "Package" %} {$ createdPackage + $} {% trans "Successfully Created" %}

+
+
+ +
+ + +
+ + +
+
+
+ +
-
- - -
{% endblock %} diff --git a/packages/templates/packages/modifyPackage.html b/packages/templates/packages/modifyPackage.html index 4360ba79c..22a343d4a 100755 --- a/packages/templates/packages/modifyPackage.html +++ b/packages/templates/packages/modifyPackage.html @@ -83,6 +83,19 @@
+
+ + +
+
+ +
+
+
+ diff --git a/plogical/acl.py b/plogical/acl.py index 0d9449d90..c1e505c9c 100755 --- a/plogical/acl.py +++ b/plogical/acl.py @@ -108,6 +108,18 @@ class ACLManager: return finalResponse + @staticmethod + def checkUserOwnerShip(currentACL, owner, user): + if currentACL['admin'] == 1: + return 1 + elif owner == user: + return 1 + elif owner.pk == user.owner: + return 1 + else: + return 0 + + @staticmethod def currentContextPermission(currentACL, context): try: diff --git a/plogical/adminPass.py b/plogical/adminPass.py index d2f4fe369..6b52735b8 100755 --- a/plogical/adminPass.py +++ b/plogical/adminPass.py @@ -31,7 +31,7 @@ def main(): firstName="Cyber", lastName="Panel", acl=acl, token=token) admin.save() - vers = version(currentVersion="1.8", build=7) + vers = version(currentVersion="1.8", build=8) vers.save() package = Package(admin=admin, packageName="Default", diskSpace=1000, diff --git a/plogical/cPanelImporter.py b/plogical/cPanelImporter.py index ff400b9c9..885a1249b 100644 --- a/plogical/cPanelImporter.py +++ b/plogical/cPanelImporter.py @@ -51,6 +51,9 @@ class cPanelImporter: self.mailFormat = 1 def PHPDecider(self): + + if self.PHPVersion == 'inherit': + self.PHPVersion = 'PHP 7.2' if self.PHPVersion.find('53') > -1: self.PHPVersion = 'PHP 5.3' elif self.PHPVersion.find('54') > -1: diff --git a/plogical/mysqlUtilities.py b/plogical/mysqlUtilities.py index 7273ee854..be1072d2e 100755 --- a/plogical/mysqlUtilities.py +++ b/plogical/mysqlUtilities.py @@ -145,7 +145,7 @@ class mysqlUtilities: return str(msg) @staticmethod - def createDatabaseBackup(databaseName,tempStoragePath): + def createDatabaseBackup(databaseName, tempStoragePath): try: passFile = "/etc/cyberpanel/mysqlPassword" f = open(passFile) @@ -191,7 +191,7 @@ password=%s return 0 @staticmethod - def restoreDatabaseBackup(databaseName, tempStoragePath,dbPassword): + def restoreDatabaseBackup(databaseName, tempStoragePath, dbPassword, passwordCheck = None, additionalName = None): try: passFile = "/etc/cyberpanel/mysqlPassword" @@ -217,25 +217,33 @@ password=%s command = 'chown cyberpanel:cyberpanel %s' % (cnfPath) subprocess.call(shlex.split(command)) - command = 'sudo mysql --defaults-extra-file=/home/cyberpanel/.my.cnf --host=localhost ' + databaseName + command = 'mysql --defaults-extra-file=/home/cyberpanel/.my.cnf --host=localhost ' + databaseName cmd = shlex.split(command) - with open(tempStoragePath + "/" + databaseName + '.sql', 'r') as f: - res = subprocess.call(cmd, stdin=f) + if additionalName == None: + with open(tempStoragePath + "/" + databaseName + '.sql', 'r') as f: + res = subprocess.call(cmd, stdin=f) + if res != 0: + logging.CyberCPLogFileWriter.writeToFile("Could not restore MYSQL database: " + databaseName +"! [restoreDatabaseBackup]") + return 0 + else: + with open(tempStoragePath + "/" + additionalName + '.sql', 'r') as f: + res = subprocess.call(cmd, stdin=f) - if res == 1: - logging.CyberCPLogFileWriter.writeToFile("Could not restore MYSQL database: " +databaseName +"! [restoreDatabaseBackup]") - return 0 + if res != 0: + logging.CyberCPLogFileWriter.writeToFile("Could not restore MYSQL database: " + additionalName + "! [restoreDatabaseBackup]") + return 0 - connection, cursor = mysqlUtilities.setupConnection() + if passwordCheck == None: + connection, cursor = mysqlUtilities.setupConnection() - if connection == 0: - return 0 + if connection == 0: + return 0 - passwordCMD = "use mysql;SET PASSWORD FOR '" + databaseName + "'@'localhost' = '" + dbPassword + "';FLUSH PRIVILEGES;" + passwordCMD = "use mysql;SET PASSWORD FOR '" + databaseName + "'@'localhost' = '" + dbPassword + "';FLUSH PRIVILEGES;" - cursor.execute(passwordCMD) - connection.close() + cursor.execute(passwordCMD) + connection.close() return 1 except BaseException, msg: diff --git a/plogical/processUtilities.py b/plogical/processUtilities.py index 3058abf7e..d076e8674 100755 --- a/plogical/processUtilities.py +++ b/plogical/processUtilities.py @@ -270,4 +270,13 @@ class ProcessUtilities(multi.Thread): logging.writeToFile(str(msg) + " [popenExecutioner]") + @staticmethod + def BuildCommand(path, functionName, parameters): + execPath = "python %s %s " % (path, functionName) + for key, value in parameters.iteritems(): + execPath = execPath + ' --%s %s' % (key, value) + + return execPath + + diff --git a/plogical/upgrade.py b/plogical/upgrade.py index 1cc5b2fea..bd6c25d15 100755 --- a/plogical/upgrade.py +++ b/plogical/upgrade.py @@ -1443,7 +1443,8 @@ class Upgrade: impFile = ['/etc/pure-ftpd/pure-ftpd.conf', '/etc/pure-ftpd/pureftpd-pgsql.conf', '/etc/pure-ftpd/pureftpd-mysql.conf', '/etc/pure-ftpd/pureftpd-ldap.conf', - '/etc/dovecot/dovecot.conf', '/etc/pdns/pdns.conf', '/etc/pure-ftpd/db/mysql.conf', '/etc/powerdns/pdns.conf'] + '/etc/dovecot/dovecot.conf', '/etc/pdns/pdns.conf', '/etc/pure-ftpd/db/mysql.conf', + '/etc/powerdns/pdns.conf'] for items in impFile: command = 'chmod 600 %s' % (items) @@ -1477,7 +1478,6 @@ class Upgrade: command = 'chmod 644 /etc/postfix/main.cf' subprocess.call(command, shell=True) - Upgrade.stdOut("Permissions updated.") except BaseException, msg: @@ -1498,6 +1498,14 @@ class Upgrade: 'lsphp7?-sqlite3 lsphp7?-tidy' Upgrade.executioner(command, 'Install PHP 73, 0') + CentOSPath = '/etc/redhat-release' + + if not os.path.exists(CentOSPath): + command = 'cp /usr/local/lsws/lsphp71/bin/php /usr/bin/' + Upgrade.executioner(command, 'Set default PHP 7.0, 0') + + + @staticmethod def someDirectories(): command = "mkdir -p /usr/local/lscpd/admin/" @@ -1520,11 +1528,11 @@ class Upgrade: if os.path.exists(CentOSPath): path = '/etc/yum.repos.d/dovecot.repo' content = """[dovecot-2.3-latest] - name=Dovecot 2.3 CentOS $releasever - $basearch - baseurl=http://repo.dovecot.org/ce-2.3-latest/centos/$releasever/RPMS/$basearch - gpgkey=https://repo.dovecot.org/DOVECOT-REPO-GPG - gpgcheck=1 - enabled=1""" +name=Dovecot 2.3 CentOS $releasever - $basearch +baseurl=http://repo.dovecot.org/ce-2.3-latest/centos/$releasever/RPMS/$basearch +gpgkey=https://repo.dovecot.org/DOVECOT-REPO-GPG +gpgcheck=1 +enabled=1""" writeToFile = open(path, 'w') writeToFile.write(content) writeToFile.close() @@ -1580,8 +1588,17 @@ class Upgrade: pass try: - command = 'apt upgrade -y' + command = 'DEBIAN_FRONTEND=noninteractive DEBIAN_PRIORITY=critical sudo apt-get -q -y -o "Dpkg::Options::=--force-confdef" -o "Dpkg::Options::=--force-confold" --only-upgrade install dovecot-mysql -y' + subprocess.call(command, shell=True) + + command = 'dpkg --configure -a' Upgrade.executioner(command, 0) + + command = 'apt --fix-broken install -y' + Upgrade.executioner(command, 0) + + command = 'DEBIAN_FRONTEND=noninteractive DEBIAN_PRIORITY=critical sudo apt-get -q -y -o "Dpkg::Options::=--force-confdef" -o "Dpkg::Options::=--force-confold" --only-upgrade install dovecot-mysql -y' + subprocess.call(command, shell=True) except: pass @@ -1591,12 +1608,12 @@ class Upgrade: data = open(path, 'r').readlines() - updatePasswords = 1 + updatePasswords = 0 writeToFile = open(path, 'w') for items in data: if items.find('default_pass_scheme') > -1: - updatePasswords = 0 + updatePasswords = 1 continue else: writeToFile.writelines(items) @@ -1715,4 +1732,4 @@ def main(): if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/plogical/vhost.py b/plogical/vhost.py index 059af9f98..9c94d57f4 100755 --- a/plogical/vhost.py +++ b/plogical/vhost.py @@ -103,7 +103,12 @@ class vhost: try: os.makedirs(pathLogs) - command = "chown %s:%s %s" % ('root', 'nobody', pathLogs) + if ProcessUtilities.decideDistro() == ProcessUtilities.centos: + groupName = 'nobody' + else: + groupName = 'nogroup' + + command = "chown %s:%s %s" % ('root', groupName, pathLogs) cmd = shlex.split(command) subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) diff --git a/plogical/virtualHostUtilities.py b/plogical/virtualHostUtilities.py index 4291e2549..ba1d595fb 100755 --- a/plogical/virtualHostUtilities.py +++ b/plogical/virtualHostUtilities.py @@ -1019,6 +1019,15 @@ class virtualHostUtilities: master = Websites.objects.get(domain=masterDomain) domainsInPackage = master.package.allowedDomains + if master.package.allowFullDomain == 0: + if virtualHostName.find(masterDomain) > -1: + pass + else: + logging.CyberCPLogFileWriter.statusWriter(tempStatusPath, + 'Fully qualified domain is not allowed in the package. [404]') + return 0, "Fully qualified domain is not allowed in the package." + + if domainsInPackage == 0: pass elif domainsInPackage > master.childdomains_set.all().count(): diff --git a/requirments.txt b/requirments.txt index e4e5e0e04..aff43c221 100755 --- a/requirments.txt +++ b/requirments.txt @@ -35,7 +35,6 @@ MarkupSafe==0.11 mock==2.0.0 parsedatetime==2.4 pbr==4.0.4 -perf==0.1 pexpect==4.4.0 prettytable==0.7.2 psutil==5.4.3 diff --git a/serverStatus/views.py b/serverStatus/views.py index 0d9bb8fc8..90ddeea71 100755 --- a/serverStatus/views.py +++ b/serverStatus/views.py @@ -65,7 +65,6 @@ def litespeedStatus(request): return render(request, "serverStatus/litespeedStatus.html", {"processList": processList, "liteSpeedVersionStatus": "For some reaons not able to load version details, see CyberCP main log file.", 'OLS': OLS}) - if (processList != 0): dataForHtml = {"processList": processList, "lsversion": lsversion, "modules": modules, "loadedModules": loadedModules, 'OLS': OLS} diff --git a/static/websiteFunctions/websiteFunctions.js b/static/websiteFunctions/websiteFunctions.js index 0cd60be54..aea790a01 100644 --- a/static/websiteFunctions/websiteFunctions.js +++ b/static/websiteFunctions/websiteFunctions.js @@ -447,9 +447,8 @@ app.controller('deleteWebsiteControl', function ($scope, $http) { function ListInitialDatas(response) { - console.log(response.data) - if (response.data.websiteDeleteStatus == 0) { + if (response.data.websiteDeleteStatus === 0) { $scope.errorMessage = response.data.error_message; $("#websiteDeleteFailure").fadeIn(); $("#websiteDeleteSuccess").hide(); @@ -471,7 +470,6 @@ app.controller('deleteWebsiteControl', function ($scope, $http) { } function cantLoadInitialDatas(response) { - console.log("not good"); } @@ -4943,7 +4941,6 @@ app.controller('sshAccess', function ($scope, $http, $timeout) { } else { - new PNotify({ title: 'Error!', text: response.data.error_message, @@ -4969,4 +4966,300 @@ app.controller('sshAccess', function ($scope, $http, $timeout) { }; -}); \ No newline at end of file +}); + + +/* Java script code to cloneWebsite */ +app.controller('cloneWebsite', function ($scope, $http, $timeout, $window) { + + $scope.cyberpanelLoading = true; + $scope.installationDetailsForm = false; + $scope.installationProgress = true; + $scope.goBackDisable = true; + + var statusFile; + + $scope.startCloning = function () { + + $scope.cyberpanelLoading = false; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.goBackDisable = true; + + $scope.currentStatus = "Cloning started.."; + + url = "/websites/startCloning"; + + + var data = { + masterDomain: $("#domainName").text(), + domainName: $scope.domain + + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + function ListInitialDatas(response) { + + if (response.data.status === 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; + + } + + + } + +}); +/* Java script code to cloneWebsite ends here */ + + +/* Java script code to syncWebsite */ +app.controller('syncWebsite', function ($scope, $http, $timeout, $window) { + + $scope.cyberpanelLoading = true; + $scope.installationDetailsForm = false; + $scope.installationProgress = true; + $scope.goBackDisable = true; + + var statusFile; + + $scope.startSyncing = function () { + + $scope.cyberpanelLoading = false; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.goBackDisable = true; + + $scope.currentStatus = "Cloning started.."; + + url = "/websites/startSync"; + + + var data = { + childDomain: $("#childDomain").text(), + eraseCheck: $scope.eraseCheck, + dbCheck: $scope.dbCheck, + copyChanged: $scope.copyChanged + + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + function ListInitialDatas(response) { + + if (response.data.status === 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; + + } + + + } + +}); +/* Java script code to syncWebsite ends here */ \ No newline at end of file diff --git a/userManagment/views.py b/userManagment/views.py index bbf0b9af8..c5ea7927e 100755 --- a/userManagment/views.py +++ b/userManagment/views.py @@ -365,12 +365,10 @@ def submitUserDeletion(request): currentACL = ACLManager.loadedACL(userID) - if accountUsername == 'admin': - data_ret = {'status': 0, 'deleteStatus': 0, 'error_message': 'You can not delete the super user.'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) + currentUser = Administrator.objects.get(pk=userID) + userInQuestion = Administrator.objects.get(userName=accountUsername) - if currentACL['admin'] == 1: + if ACLManager.checkUserOwnerShip(currentACL, currentUser, userInQuestion): user = Administrator.objects.get(userName=accountUsername) user.delete() @@ -378,7 +376,7 @@ def submitUserDeletion(request): json_data = json.dumps(data_ret) return HttpResponse(json_data) else: - data_ret = {'status': 0, 'deleteStatus': 1, 'error_message': 'Not enough privileges.'} + data_ret = {'status': 0, 'deleteStatus': 0, 'error_message': 'Not enough privileges.'} json_data = json.dumps(data_ret) return HttpResponse(json_data) diff --git a/websiteFunctions/StagingSetup.py b/websiteFunctions/StagingSetup.py new file mode 100644 index 000000000..678560d4d --- /dev/null +++ b/websiteFunctions/StagingSetup.py @@ -0,0 +1,227 @@ +#!/usr/local/CyberCP/bin/python2 +import threading as multi +from plogical.CyberCPLogFileWriter import CyberCPLogFileWriter as logging +from plogical.virtualHostUtilities import virtualHostUtilities +from plogical.processUtilities import ProcessUtilities +from .models import Websites, ChildDomains +from plogical.applicationInstaller import ApplicationInstaller +from plogical.mysqlUtilities import mysqlUtilities +from random import randint +import os + +class StagingSetup(multi.Thread): + + def __init__(self, function, extraArgs): + multi.Thread.__init__(self) + self.function = function + self.extraArgs = extraArgs + + def run(self): + try: + if self.function == 'startCloning': + self.startCloning() + elif self.function == 'startSyncing': + self.startSyncing() + except BaseException, msg: + logging.writeToFile( str(msg) + ' [StagingSetup.run]') + + def startCloning(self): + try: + tempStatusPath = self.extraArgs['tempStatusPath'] + masterDomain = self.extraArgs['masterDomain'] + domain = self.extraArgs['domain'] + admin = self.extraArgs['admin'] + + website = Websites.objects.get(domain=masterDomain) + + ## Creating Child Domain + + path = "/home/" + masterDomain + "/public_html/" + domain + + logging.statusWriter(tempStatusPath, 'Creating domain for staging environment..,5') + phpSelection = 'PHP 7.1' + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + + execPath = execPath + " createDomain --masterDomain " + masterDomain + " --virtualHostName " + domain + \ + " --phpVersion '" + phpSelection + "' --ssl 0 --dkimCheck 0 --openBasedir 0 --path " + path + ' --websiteOwner ' \ + + admin.userName + ' --tempStatusPath %s' % (tempStatusPath + '1') + " --apache 0" + + ProcessUtilities.executioner(execPath) + + domainCreationStatusPath = tempStatusPath + '1' + + data = open(domainCreationStatusPath, 'r').read() + + if data.find('[200]') > -1: + pass + else: + logging.statusWriter(tempStatusPath, 'Failed to create child-domain for staging enviroment. [404]') + return 0 + + logging.statusWriter(tempStatusPath, 'Domain successfully created..,15') + + ## Copying Data + + masterPath = '/home/%s/public_html' % (masterDomain) + + command = 'rsync -avzh --exclude "%s" --exclude "wp-content/plugins/litespeed-cache" %s/ %s' % (domain, masterPath, path) + ProcessUtilities.executioner(command, website.externalApp) + + logging.statusWriter(tempStatusPath, 'Data copied..,50') + + ## Creating Database + + logging.statusWriter(tempStatusPath, 'Creating and copying database..,50') + + dbNameRestore, dbUser, dbPassword = ApplicationInstaller(None, None).dbCreation(tempStatusPath, website) + + # Create dump of existing database + + configPath = '%s/wp-config.php' % (masterPath) + + if not os.path.exists(configPath): + logging.statusWriter(tempStatusPath, 'WordPress is not detected. [404]') + return 0 + + data = open(configPath, 'r').readlines() + + for items in data: + if items.find('DB_NAME') > -1: + dbName = items.split("'")[3] + if mysqlUtilities.createDatabaseBackup(dbName, '/home/cyberpanel'): + break + else: + raise BaseException('Failed to create database backup.') + + databasePath = '%s/%s.sql' % ('/home/cyberpanel', dbName) + + command = "sed -i 's/%s/%s/g' %s" % (masterDomain, domain, databasePath) + ProcessUtilities.executioner(command, 'cyberpanel') + + if not mysqlUtilities.restoreDatabaseBackup(dbNameRestore, '/home/cyberpanel', None, 1, dbName): + try: + os.remove(databasePath) + except: + pass + raise BaseException('Failed to restore database backup.') + + try: + os.remove(databasePath) + except: + pass + + ## Update final config file + + pathFinalConfig = '%s/wp-config.php' % (path) + data = open(pathFinalConfig, 'r').readlines() + + tmp = "/tmp/" + str(randint(1000, 9999)) + writeToFile = open(tmp, 'w') + + for items in data: + if items.find('DB_NAME') > -1: + writeToFile.write("define( 'DB_NAME', '%s' );\n" % (dbNameRestore)) + elif items.find('DB_USER') > -1: + writeToFile.write("define( 'DB_USER', '%s' );\n" % (dbUser)) + elif items.find('DB_PASSWORD') > -1: + writeToFile.write("define( 'DB_PASSWORD', '%s' );\n" % (dbPassword)) + else: + writeToFile.write(items) + + writeToFile.close() + + command = 'mv %s %s' % (tmp, pathFinalConfig) + ProcessUtilities.executioner(command, website.externalApp) + + logging.statusWriter(tempStatusPath, 'Database synced..,100') + + try: + os.path.remove(databasePath) + except: + pass + + logging.statusWriter(tempStatusPath, 'Data copied..,[200]') + + return 0 + except BaseException, msg: + mesg = '%s. [404]' % (str(msg)) + logging.statusWriter(tempStatusPath, mesg) + + def startSyncing(self): + try: + tempStatusPath = self.extraArgs['tempStatusPath'] + childDomain = self.extraArgs['childDomain'] + eraseCheck = self.extraArgs['eraseCheck'] + dbCheck = self.extraArgs['dbCheck'] + copyChanged = self.extraArgs['copyChanged'] + + child = ChildDomains.objects.get(domain=childDomain) + + configPath = '%s/wp-config.php' % (child.path) + if not os.path.exists(configPath): + logging.statusWriter(tempStatusPath, 'WordPress is not detected. [404]') + return 0 + + if dbCheck: + logging.statusWriter(tempStatusPath, 'Syncing databases..,10') + + ## Create backup of child-domain database + + configPath = '%s/wp-config.php' % (child.path) + + data = open(configPath, 'r').readlines() + + for items in data: + if items.find('DB_NAME') > -1: + dbName = items.split("'")[3] + if mysqlUtilities.createDatabaseBackup(dbName, '/home/cyberpanel'): + break + else: + raise BaseException('Failed to create database backup.') + + databasePath = '%s/%s.sql' % ('/home/cyberpanel', dbName) + command = "sed -i 's/%s/%s/g' %s" % (child.domain, child.master.domain, databasePath) + ProcessUtilities.executioner(command, 'cyberpanel') + + ## Restore to master domain + + masterPath = '/home/%s/public_html' % (child.master.domain) + + configPath = '%s/wp-config.php' % (masterPath) + + data = open(configPath, 'r').readlines() + + for items in data: + if items.find('DB_NAME') > -1: + dbNameRestore = items.split("'")[3] + if not mysqlUtilities.restoreDatabaseBackup(dbNameRestore, '/home/cyberpanel', None, 1, dbName): + try: + os.remove(databasePath) + except: + pass + raise BaseException('Failed to restore database backup.') + + try: + os.remove(databasePath) + except: + pass + + if eraseCheck: + sourcePath = child.path + destinationPath = '/home/%s/public_html' % (child.master.domain) + + command = 'rsync -avzh --exclude "wp-config.php" %s/ %s' % (sourcePath, destinationPath) + ProcessUtilities.executioner(command, child.master.externalApp) + elif copyChanged: + sourcePath = child.path + destinationPath = '/home/%s/public_html' % (child.master.domain) + + command = 'rsync -avzh --exclude "wp-config.php" %s/ %s' % (sourcePath, destinationPath) + ProcessUtilities.executioner(command, child.master.externalApp) + + logging.statusWriter(tempStatusPath, 'Data copied..,[200]') + + return 0 + except BaseException, msg: + mesg = '%s. [404]' % (str(msg)) + logging.statusWriter(tempStatusPath, mesg) \ No newline at end of file diff --git a/websiteFunctions/static/websiteFunctions/websiteFunctions.js b/websiteFunctions/static/websiteFunctions/websiteFunctions.js index 0cd60be54..f9fc0908a 100755 --- a/websiteFunctions/static/websiteFunctions/websiteFunctions.js +++ b/websiteFunctions/static/websiteFunctions/websiteFunctions.js @@ -286,7 +286,6 @@ app.controller('listWebsites', function ($scope, $http) { } else { $("#listFail").fadeIn(); $scope.errorMessage = response.data.error_message; - console.log(response.data); } } @@ -447,9 +446,8 @@ app.controller('deleteWebsiteControl', function ($scope, $http) { function ListInitialDatas(response) { - console.log(response.data) - if (response.data.websiteDeleteStatus == 0) { + if (response.data.websiteDeleteStatus === 0) { $scope.errorMessage = response.data.error_message; $("#websiteDeleteFailure").fadeIn(); $("#websiteDeleteSuccess").hide(); @@ -471,7 +469,6 @@ app.controller('deleteWebsiteControl', function ($scope, $http) { } function cantLoadInitialDatas(response) { - console.log("not good"); } @@ -4943,7 +4940,6 @@ app.controller('sshAccess', function ($scope, $http, $timeout) { } else { - new PNotify({ title: 'Error!', text: response.data.error_message, @@ -4969,4 +4965,300 @@ app.controller('sshAccess', function ($scope, $http, $timeout) { }; -}); \ No newline at end of file +}); + + +/* Java script code to cloneWebsite */ +app.controller('cloneWebsite', function ($scope, $http, $timeout, $window) { + + $scope.cyberpanelLoading = true; + $scope.installationDetailsForm = false; + $scope.installationProgress = true; + $scope.goBackDisable = true; + + var statusFile; + + $scope.startCloning = function () { + + $scope.cyberpanelLoading = false; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.goBackDisable = true; + + $scope.currentStatus = "Cloning started.."; + + url = "/websites/startCloning"; + + + var data = { + masterDomain: $("#domainName").text(), + domainName: $scope.domain + + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + function ListInitialDatas(response) { + + if (response.data.status === 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; + + } + + + } + +}); +/* Java script code to cloneWebsite ends here */ + + +/* Java script code to syncWebsite */ +app.controller('syncWebsite', function ($scope, $http, $timeout, $window) { + + $scope.cyberpanelLoading = true; + $scope.installationDetailsForm = false; + $scope.installationProgress = true; + $scope.goBackDisable = true; + + var statusFile; + + $scope.startSyncing = function () { + + $scope.cyberpanelLoading = false; + $scope.installationDetailsForm = true; + $scope.installationProgress = false; + $scope.goBackDisable = true; + + $scope.currentStatus = "Cloning started.."; + + url = "/websites/startSync"; + + + var data = { + childDomain: $("#childDomain").text(), + eraseCheck: $scope.eraseCheck, + dbCheck: $scope.dbCheck, + copyChanged: $scope.copyChanged + + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + function ListInitialDatas(response) { + + if (response.data.status === 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; + + } + + + } + +}); +/* Java script code to syncWebsite ends here */ \ No newline at end of file diff --git a/websiteFunctions/templates/websiteFunctions/createWebsite.html b/websiteFunctions/templates/websiteFunctions/createWebsite.html index 7a8e1b66d..435b2453b 100755 --- a/websiteFunctions/templates/websiteFunctions/createWebsite.html +++ b/websiteFunctions/templates/websiteFunctions/createWebsite.html @@ -47,7 +47,6 @@ -
@@ -78,7 +77,6 @@
-
@@ -109,7 +107,6 @@
-
@@ -120,7 +117,6 @@
-
diff --git a/websiteFunctions/templates/websiteFunctions/launchChild.html b/websiteFunctions/templates/websiteFunctions/launchChild.html index 8003469e2..2fd80a79c 100755 --- a/websiteFunctions/templates/websiteFunctions/launchChild.html +++ b/websiteFunctions/templates/websiteFunctions/launchChild.html @@ -26,6 +26,7 @@

{% trans "Resource Usage" %} + {% trans "Copy/Sync to Master" %}

diff --git a/websiteFunctions/templates/websiteFunctions/setupStaging.html b/websiteFunctions/templates/websiteFunctions/setupStaging.html new file mode 100755 index 000000000..63eab9c1d --- /dev/null +++ b/websiteFunctions/templates/websiteFunctions/setupStaging.html @@ -0,0 +1,88 @@ +{% extends "baseTemplate/index.html" %} +{% load i18n %} +{% block title %}{% trans "Set up Staging Enviroment - CyberPanel" %}{% endblock %} +{% block content %} + + {% load static %} + {% get_current_language as LANGUAGE_CODE %} + + +
+
+

{% trans "Set up Staging Enviroment" %}

+

{% trans "Set up staging enviroment for " %} {{ domainName }}. {% trans ". Any domain that you will choose here will be created as child-domain for this master site." %}

+
+ + +
+
+

+ {% trans "Set up staging enviroment for " %}{{ domainName }} +

+
+ + +
+ +
+ + +
+ +
+ +
+ +
+
+ +
+ +
+ +
+
+ +
+ +
+ +
+

{$ currentStatus $}

+
+ +
+
+ 70% Complete +
+
+ + +
+
+ +
+ +
+ +
+
+ +
+ +
+
+
+ + +
+ + +{% endblock %} \ No newline at end of file diff --git a/websiteFunctions/templates/websiteFunctions/syncMaster.html b/websiteFunctions/templates/websiteFunctions/syncMaster.html new file mode 100755 index 000000000..3760a7064 --- /dev/null +++ b/websiteFunctions/templates/websiteFunctions/syncMaster.html @@ -0,0 +1,104 @@ +{% extends "baseTemplate/index.html" %} +{% load i18n %} +{% block title %}{% trans "Sync to Master - CyberPanel" %}{% endblock %} +{% block content %} + + {% load static %} + {% get_current_language as LANGUAGE_CODE %} + + +
+
+

{% trans "Sync your site to Master" %}

+

{% trans "Right now you can only sync your child domains to master domains."%} {{ childDomain }} {% trans " will be synced to " %} {{ domainName }}.

+
+ + +
+
+

+ {% trans "Sync " %}{{ childDomain }} {% trans "to " %} {{ domainName }} +

+
+ + +
+ +
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+
+ +
+ +
+ +
+
+ +
+ +
+ +
+

{$ currentStatus $}

+
+ +
+
+ 70% Complete +
+
+ + +
+
+ +
+ +
+ +
+
+ +
+ +
+
+
+ + +
+ + +{% endblock %} \ No newline at end of file diff --git a/websiteFunctions/templates/websiteFunctions/website.html b/websiteFunctions/templates/websiteFunctions/website.html index 7d90b5918..5db506f98 100755 --- a/websiteFunctions/templates/websiteFunctions/website.html +++ b/websiteFunctions/templates/websiteFunctions/website.html @@ -26,6 +26,7 @@

{% trans "Resource Usage" %} + {% trans "Clone/Staging" %} {% trans "Set up SSH Access" %}

diff --git a/websiteFunctions/urls.py b/websiteFunctions/urls.py index b69739854..c75ea0815 100755 --- a/websiteFunctions/urls.py +++ b/websiteFunctions/urls.py @@ -96,6 +96,13 @@ urlpatterns = [ url(r'^(?P(.*))/sshAccess$', views.sshAccess, name='sshAccess'), url(r'^saveSSHAccessChanges$', views.saveSSHAccessChanges, name='saveSSHAccessChanges'), + ## Staging Enviroment + + url(r'^(?P(.*))/setupStaging$', views.setupStaging, name='setupStaging'), + url(r'^startCloning$', views.startCloning, name='startCloning'), + url(r'^(?P(.*))/(?P(.*))/syncToMaster$', views.syncToMaster, name='syncToMaster'), + url(r'^startSync$', views.startSync, name='startSync'), + url(r'^(?P(.*))/gitNotify$', views.gitNotify, name='gitNotify'), url(r'^detachRepo$', views.detachRepo, name='detachRepo'), diff --git a/websiteFunctions/views.py b/websiteFunctions/views.py index 8794bb5a1..f62f89a7b 100755 --- a/websiteFunctions/views.py +++ b/websiteFunctions/views.py @@ -6,7 +6,7 @@ from django.http import HttpResponse from loginSystem.models import Administrator from loginSystem.views import loadLoginPage import json -from plogical.website import WebsiteManager +from websiteFunctions.website import WebsiteManager from websiteFunctions.pluginManager import pluginManager from django.views.decorators.csrf import csrf_exempt @@ -620,5 +620,40 @@ def saveSSHAccessChanges(request): userID = request.session['userID'] wm = WebsiteManager() return wm.saveSSHAccessChanges(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) + + +def setupStaging(request, domain): + try: + userID = request.session['userID'] + wm = WebsiteManager(domain) + return wm.setupStaging(request, userID) + except KeyError: + return redirect(loadLoginPage) + + +def startCloning(request): + try: + userID = request.session['userID'] + wm = WebsiteManager() + return wm.startCloning(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) + + +def syncToMaster(request, domain, childDomain): + try: + userID = request.session['userID'] + wm = WebsiteManager(domain) + return wm.syncToMaster(request, userID, None, childDomain) + except KeyError: + return redirect(loadLoginPage) + +def startSync(request): + try: + userID = request.session['userID'] + wm = WebsiteManager() + return wm.startSync(userID, json.loads(request.body)) except KeyError: return redirect(loadLoginPage) \ No newline at end of file diff --git a/websiteFunctions/website.py b/websiteFunctions/website.py new file mode 100755 index 000000000..90b913ad7 --- /dev/null +++ b/websiteFunctions/website.py @@ -0,0 +1,2482 @@ +#!/usr/local/CyberCP/bin/python2 +import os +import os.path +import sys +import django + +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 +from plogical.virtualHostUtilities import virtualHostUtilities +import subprocess +import shlex +from plogical.installUtilities import installUtilities +from django.shortcuts import HttpResponse, render +from loginSystem.models import Administrator, ACL +from packages.models import Package +from plogical.mailUtilities import mailUtilities +from random import randint +import time +import re +from plogical.childDomain import ChildDomainManager +from math import ceil +from plogical.alias import AliasManager +from plogical.applicationInstaller import ApplicationInstaller +from databases.models import Databases +import hashlib +from plogical.mysqlUtilities import mysqlUtilities +from plogical import hashPassword +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 re import match,I,M +from plogical import randomPassword +from StagingSetup import StagingSetup + + +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): + try: + currentACL = ACLManager.loadedACL(userID) + if ACLManager.currentContextPermission(currentACL, 'createWebsite') == 0: + return ACLManager.loadError() + + adminNames = ACLManager.loadAllUsers(userID) + packagesName = ACLManager.loadPackages(userID, currentACL) + phps = PHPManager.findPHPVersions() + + Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps} + return render(request, 'websiteFunctions/createWebsite.html', Data) + + except BaseException, msg: + return HttpResponse(str(msg)) + + def modifyWebsite(self, request=None, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + + if ACLManager.currentContextPermission(currentACL, 'modifyWebsite') == 0: + return ACLManager.loadError() + + websitesName = ACLManager.findAllSites(currentACL, userID) + phps = PHPManager.findPHPVersions() + + return render(request, 'websiteFunctions/modifyWebsite.html', {'websiteList': websitesName, 'phps': phps}) + except BaseException, msg: + return HttpResponse(str(msg)) + + def deleteWebsite(self, request=None, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + if ACLManager.currentContextPermission(currentACL, 'deleteWebsite') == 0: + return ACLManager.loadError() + + websitesName = ACLManager.findAllSites(currentACL, userID) + + return render(request, 'websiteFunctions/deleteWebsite.html', {'websiteList': websitesName}) + except BaseException, msg: + return HttpResponse(str(msg)) + + def siteState(self, request=None, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + + if ACLManager.currentContextPermission(currentACL, 'suspendWebsite') == 0: + return ACLManager.loadError() + + websitesName = ACLManager.findAllSites(currentACL, userID) + + return render(request, 'websiteFunctions/suspendWebsite.html', {'websiteList': websitesName}) + except BaseException, msg: + return HttpResponse(str(msg)) + + def listWebsites(self, request=None, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + pagination = self.websitePagination(currentACL, userID) + + return render(request, 'websiteFunctions/listWebsites.html', {"pagination": pagination}) + except BaseException, msg: + return HttpResponse(str(msg)) + + def listCron(self, request=None, userID=None, data=None): + try: + currentACL = ACLManager.loadedACL(userID) + websitesName = ACLManager.findAllSites(currentACL, userID) + return render(request, 'websiteFunctions/listCron.html', {'websiteList': websitesName}) + except BaseException, msg: + return HttpResponse(str(msg)) + + def domainAlias(self, request=None, userID=None, data=None): + try: + 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" + + return render(request, 'websiteFunctions/domainAlias.html', { + 'masterDomain': self.domain, + 'aliases': finalAlisList, + 'path': path, + 'noAlias': noAlias + }) + except BaseException, msg: + return HttpResponse(str(msg)) + + def submitWebsiteCreation(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + if ACLManager.currentContextPermission(currentACL, 'createWebsite') == 0: + return ACLManager.loadErrorJson('createWebSiteStatus', 0) + + domain = data['domainName'] + adminEmail = data['adminEmail'] + phpSelection = data['phpSelection'] + packageName = data['package'] + websiteOwner = data['websiteOwner'] + + if not match(r'([\da-z\.-]+\.[a-z\.]{2,12}|[\d\.]+)([\/:?=&#]{1}[\da-z\.-]+)*[\/\?]?', domain, + M | I): + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Invalid domain."} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + if not match(r'\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b', adminEmail, + M | I): + 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))[:7] + + 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" + + ## Create Configurations + + execPath = "sudo /usr/local/CyberCP/bin/python2 " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " createVirtualHost --virtualHostName " + domain + \ + " --administratorEmail " + adminEmail + " --phpVersion '" + phpSelection + \ + "' --virtualHostUser " + externalApp + " --ssl " + str(data['ssl']) + " --dkimCheck " \ + + str(data['dkimCheck']) + " --openBasedir " + str(data['openBasedir']) + \ + ' --websiteOwner ' + websiteOwner + ' --package ' + packageName + ' --tempStatusPath ' + tempStatusPath + " --apache " + apacheBackend + + 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, 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) + + masterDomain = data['masterDomain'] + domain = data['domainName'] + phpSelection = data['phpSelection'] + path = data['path'] + tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + + if not match(r'([\da-z\.-]+\.[a-z\.]{2,12}|[\d\.]+)([\/:?=&#]{1}[\da-z\.-]+)*[\/\?]?', domain, + M | I): + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Invalid domain."} + 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 currentACL['admin'] != 1: + data['openBasedir'] = 1 + + if len(path) > 0: + path = path.lstrip("/") + path = "/home/" + masterDomain + "/public_html/" + path + else: + path = "/home/" + masterDomain + "/public_html/" + domain + + try: + apacheBackend = str(data['apacheBackend']) + except: + apacheBackend = "0" + + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + + execPath = execPath + " createDomain --masterDomain " + masterDomain + " --virtualHostName " + domain + \ + " --phpVersion '" + phpSelection + "' --ssl " + str(data['ssl']) + " --dkimCheck " + str( + data['dkimCheck']) \ + + " --openBasedir " + str(data['openBasedir']) + ' --path ' + path + ' --websiteOwner ' \ + + admin.userName + ' --tempStatusPath ' + tempStatusPath + " --apache " + apacheBackend + + 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, 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'] + + if ACLManager.checkOwnership(masterDomain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('fetchStatus', 0) + + cdManager = ChildDomainManager(masterDomain) + json_data = cdManager.findChildDomainsJson() + + final_json = json.dumps({'status': 1, 'fetchStatus': 1, 'error_message': "None", "data": json_data}) + return HttpResponse(final_json) + + except BaseException, 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, 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, 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, msg: + dic = {'status': 1, 'listWebSiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def submitWebsiteDeletion(self, userID=None, data=None): + try: + + 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 = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " deleteVirtualHostConfigurations --virtualHostName " + websiteName + ProcessUtilities.popenExecutioner(execPath) + + data_ret = {'status': 1, 'websiteDeleteStatus': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException, 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: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + websiteName = data['websiteName'] + + if ACLManager.checkOwnership(websiteName, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('websiteDeleteStatus', 0) + + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " deleteDomain --virtualHostName " + websiteName + ProcessUtilities.outputExecutioner(execPath) + + data_ret = {'status': 1, 'websiteDeleteStatus': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException, 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) + + if state == "Suspend": + confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + websiteName + command = "sudo mv " + confPath + " " + confPath + "-suspended" + ProcessUtilities.popenExecutioner(command) + installUtilities.reStartLiteSpeedSocket() + website.state = 0 + else: + confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + websiteName + + command = "sudo 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, 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, 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, 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) + + confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + domain + completePathToConfigFile = confPath + "/vhost.conf" + + execPath = "sudo 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() + + data_ret = {'status': 1, 'saveStatus': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException, 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 + + diskUsageDetails = virtualHostUtilities.getDiskUsage("/home/" + self.domain, website.package.diskSpace) + + ## bw usage calculation + + try: + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " findDomainBW --virtualHostName " + self.domain + " --bandwidth " + str( + website.package.bandwidth) + + output = ProcessUtilities.outputExecutioner(execPath) + bwData = output.split(",") + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg)) + bwData = [0, 0] + + ## bw usage calculations + + Data['bwInMBTotal'] = website.package.bandwidth + Data['bwInMB'] = bwData[0] + Data['bwUsage'] = bwData[1] + + if diskUsageDetails != None: + if diskUsageDetails[1] > 100: + diskUsageDetails[1] = 100 + + Data['diskUsage'] = diskUsageDetails[1] + Data['diskInMB'] = diskUsageDetails[0] + Data['diskInMBTotal'] = website.package.diskSpace + else: + Data['diskUsage'] = 0 + Data['diskInMB'] = 0 + 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 + + return render(request, 'websiteFunctions/website.html', Data) + + else: + return render(request, 'websiteFunctions/website.html', + {"error": 1, "domain": "This domain does not exists."}) + + 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 + + diskUsageDetails = virtualHostUtilities.getDiskUsage("/home/" + self.domain, website.package.diskSpace) + + ## bw usage calculation + + try: + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " findDomainBW --virtualHostName " + self.domain + " --bandwidth " + str( + website.package.bandwidth) + + output = ProcessUtilities.outputExecutioner(execPath) + bwData = output.split(",") + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg)) + bwData = [0, 0] + + ## bw usage calculations + + Data['bwInMBTotal'] = website.package.bandwidth + Data['bwInMB'] = bwData[0] + Data['bwUsage'] = bwData[1] + + if diskUsageDetails != None: + if diskUsageDetails[1] > 100: + diskUsageDetails[1] = 100 + + Data['diskUsage'] = diskUsageDetails[1] + Data['diskInMB'] = diskUsageDetails[0] + Data['diskInMBTotal'] = website.package.diskSpace + else: + Data['diskUsage'] = 0 + Data['diskInMB'] = 0 + 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 + + return render(request, 'websiteFunctions/launchChild.html', Data) + else: + return render(request, 'websiteFunctions/launchChild.html', + {"error": 1, "domain": "This child domain does not exists"}) + + 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" + + ## get Logs + website = Websites.objects.get(domain=self.domain) + + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " getAccessLogs --path " + fileName + " --page " + str(page) + output = ProcessUtilities.outputExecutioner(execPath, 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. + + data = output.split("\n") + + json_data = "[" + checker = 0 + + for items in reversed(data): + if len(items) > 10: + logData = items.split(" ") + domain = logData[0].strip('"') + ipAddress = logData[1] + time = (logData[4]).strip("[").strip("]") + resource = logData[7].strip('"') + size = logData[10].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" + + ## get Logs + website = Websites.objects.get(domain=self.domain) + + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " getErrorLogs --path " + fileName + " --page " + str(page) + + output = ProcessUtilities.outputExecutioner(execPath, 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) + + filePath = installUtilities.Server_root_path + "/conf/vhosts/" + self.domain + "/vhost.conf" + + command = 'sudo 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) + + 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'] + + 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 = "sudo 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 + + 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' + except: + filePath = "/home/" + self.domain + "/public_html/.htaccess" + + try: + rewriteRules = open(filePath, "r").read() + + 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 IOError: + status = {"rewriteStatus": 1, "error_message": "none", "rewriteRules": ""} + final_json = json.dumps(status) + return HttpResponse(final_json) + + def saveRewriteRules(self, userID=None, data=None): + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + self.domain = data['virtualHost'] + rewriteRules = data['rewriteRules'] + + 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, "w") + 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 + + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " saveRewriteRules --virtualHostName " + self.domain + " --path " + filePath + " --tempPath " + tempPath + + output = ProcessUtilities.outputExecutioner(execPath, externalApp) + + if output.find("1,None") > -1: + installUtilities.reStartLiteSpeedSocket() + status = {"rewriteStatus": 1, 'error_message': output} + final_json = json.dumps(status) + return HttpResponse(final_json) + else: + data_ret = {'rewriteStatus': 0, 'error_message': output} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + 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 = "sudo 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 = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " changePHP --phpVersion '" + phpVersion + "' --path " + completePathToConfigFile + ProcessUtilities.popenExecutioner(execPath) + + 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 = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" + execPath = execPath + " getWebsiteCron --externalApp " + website.externalApp + + f = ProcessUtilities.outputExecutioner(execPath, website.externalApp) + + CronUtil.CronPrem(0) + + 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, 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 = "sudo 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, 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 = "sudo 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, 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 = "sudo 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, 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) + + CronPath = '/var/spool/cron/%s' % (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 = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" + execPath = execPath + " addNewCron --externalApp " + website.externalApp + " --finalCron '" + finalCron + "'" + output = ProcessUtilities.outputExecutioner(execPath, website.externalApp) + + 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, 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 match(r'([\da-z\.-]+\.[a-z\.]{2,12}|[\d\.]+)([\/:?=&#]{1}[\da-z\.-]+)*[\/\?]?', aliasDomain, + M | I): + 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 = "sudo 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, 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) + + sslpath = "/home/" + self.domain + "/public_html" + + ## Create Configurations + + execPath = "sudo 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, 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) + + ## Create Configurations + + execPath = "sudo 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, 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 = "sudo 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, 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): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + return render(request, 'websiteFunctions/installWordPress.html', {'domainName': self.domain}) + + except BaseException, msg: + return HttpResponse(str(msg)) + + 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, 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'] + + statusData = ProcessUtilities.outputExecutioner("sudo cat " + statusFile).splitlines() + + lastLine = statusData[-1] + + if lastLine.find('[200]') > -1: + command = 'sudo 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': lastLine} + 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, msg: + data_ret = {'abort': 1, '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): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + return render(request, 'websiteFunctions/installJoomla.html', {'domainName': self.domain}) + except BaseException, msg: + return HttpResponse(str(msg)) + + 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) + + domainName = data['domain'] + home = data['home'] + + sitename = data['sitename'] + username = data['username'] + password = data['passwordByPass'] + prefix = data['prefix'] + + mailUtilities.checkHome() + + tempStatusPath = "/tmp/" + str(randint(1000, 9999)) + + statusFile = open(tempStatusPath, 'w') + statusFile.writelines('Setting up paths,0') + statusFile.close() + os.chmod(tempStatusPath, 0777) + + finalPath = "" + + admin = Administrator.objects.get(pk=userID) + + ## DB Creation + + statusFile = open(tempStatusPath, 'w') + statusFile.writelines('Creating database..,10') + statusFile.close() + + dbName = randomPassword.generate_pass() + dbUser = dbName + dbPassword = randomPassword.generate_pass() + + if Databases.objects.filter(dbName=dbName).exists() or Databases.objects.filter( + dbUser=dbUser).exists(): + data_ret = {'status': 0, 'installStatus': 0, + 'error_message': "0,This database or user is already taken."} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + result = mysqlUtilities.createDatabase(dbName, dbUser, dbPassword) + + if result == 1: + pass + else: + data_ret = {'status': 0, 'installStatus': 0, + 'error_message': "0,Not able to create database."} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + ## + + try: + website = ChildDomains.objects.get(domain=domainName) + externalApp = website.master.externalApp + + if website.master.package.dataBases > website.master.databases_set.all().count(): + pass + else: + data_ret = {'status': 0, 'installStatus': 0, + 'error_message': "0,Maximum database limit reached for this website."} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + if home == '0': + path = data['path'] + finalPath = website.path.rstrip('/') + "/" + path + "/" + else: + finalPath = website.path + "/" + + db = Databases(website=website.master, dbName=dbName, dbUser=dbUser) + db.save() + + except: + website = Websites.objects.get(domain=domainName) + externalApp = website.externalApp + + if website.package.dataBases > website.databases_set.all().count(): + pass + else: + data_ret = {'status': 0, 'installStatus': 0, + 'error_message': "0,Maximum database limit reached for this website."} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + if home == '0': + path = data['path'] + finalPath = "/home/" + domainName + "/public_html/" + path + "/" + else: + finalPath = "/home/" + domainName + "/public_html/" + + db = Databases(website=website, dbName=dbName, dbUser=dbUser) + db.save() + + if finalPath.find("..") > -1: + data_ret = {'status': 0, 'installStatus': 0, + 'error_message': "Specified path must be inside virtual host home!"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + ## Installation + salt = randomPassword.generate_pass(32) + # return salt + password_hash = hashlib.md5(password + salt).hexdigest() + password = password_hash + ":" + salt + + statusFile = open(tempStatusPath, 'w') + statusFile.writelines('Downloading Joomla Core..,20') + statusFile.close() + + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + + execPath = execPath + " installJoomla --virtualHostName " + domainName + \ + " --virtualHostUser " + externalApp + " --path " + finalPath + " --dbName " + dbName + \ + " --dbUser " + dbUser + " --dbPassword " + dbPassword + " --username " + username + \ + " --password " + password + " --prefix " + prefix + " --sitename '" + sitename + "'" \ + + " --tempStatusPath " + tempStatusPath + + # return execPath + + ProcessUtilities.popenExecutioner(execPath, externalApp) + + data_ret = {'status': 1, "installStatus": 1, 'tempStatusPath': tempStatusPath} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + ## Installation ends + + except BaseException, 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): + try: + + 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] + + webhookURL = 'https://' + ipAddress + ':8090/websites/' + self.domain + '/gitNotify' + + return render(request, 'websiteFunctions/setupGit.html', + {'domainName': self.domain, 'installed': 1, 'webhookURL': webhookURL}) + 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 +""" % (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 = 'sudo 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) + + return render(request, 'websiteFunctions/setupGit.html', + {'domainName': self.domain, 'deploymentKey': deploymentKey, 'installed': 0}) + except BaseException, msg: + return HttpResponse(str(msg)) + + 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, 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, 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, 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, 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): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + return render(request, 'websiteFunctions/installPrestaShop.html', {'domainName': self.domain}) + except BaseException, msg: + return HttpResponse(str(msg)) + + 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'] + + 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, 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'] = 0 + data['dkimCheck'] = 0 + data['openBasedir'] = 1 + data['adminEmail'] = data['ownerEmail'] + data['phpSelection'] = "PHP 7.0" + data['package'] = data['packageName'] + + admin = Administrator.objects.get(userName=adminUser) + + if hashPassword.check_password(admin.password, adminPass): + + if adminEmail is None: + data['adminEmail'] = "usman@cyberpersons.com" + + try: + acl = ACL.objects.get(name='user') + websiteOwn = Administrator(userName=websiteOwner, + password=hashPassword.hash_password(ownerPassword), + email=adminEmail, type=3, owner=admin.pk, + initWebsitesLimit=1, 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, 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, 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" + dic = {'domain': items.domain, 'adminEmail': items.adminEmail, 'ipAddress': ipAddress, + 'admin': items.admin.userName, 'package': items.package.packageName, 'state': state} + + 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, 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" + dic = {'domain': items.domain, 'adminEmail': items.adminEmail, 'ipAddress': ipAddress, + 'admin': items.admin.userName, 'package': items.package.packageName, 'state': state} + + 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 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 + 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, 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 = "sudo 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): + + 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)) + + 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) + + writeToFile = open(tempStatusPath, 'w') + writeToFile.writelines(phpFPMConf) + writeToFile.close() + + command = 'sudo mv %s %s' % (tempStatusPath, phpPath) + ProcessUtilities.executioner(command) + + phpPath = phpPath.split('/') + + if phpPath[1] == 'etc': + phpVersion = phpPath[4][3] + phpPath[4][4] + else: + phpVersion = phpPath[3][3] + phpPath[3][4] + + command = "systemctl stop php%s-php-fpm" % (phpVersion) + ProcessUtilities.executioner(command) + + command = "systemctl restart php%s-php-fpm" % (phpVersion) + ProcessUtilities.executioner(command) + + data_ret = {'status': 1} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def sshAccess(self, request=None, userID=None, data=None): + try: + 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 + + return render(request, 'websiteFunctions/sshAccess.html', + {'domainName': self.domain, 'externalApp': externalApp}) + except BaseException, msg: + return HttpResponse(str(msg)) + + 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) + + command = 'echo "%s" | passwd --stdin %s' % (data['password'], data['externalApp']) + ProcessUtilities.executioner(command) + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException, 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): + try: + 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 + + return render(request, 'websiteFunctions/setupStaging.html', + {'domainName': self.domain, 'externalApp': externalApp}) + except BaseException, msg: + return HttpResponse(str(msg)) + + + def startCloning(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['masterDomain'] + + if not match(r'([\da-z\.-]+\.[a-z\.]{2,12}|[\d\.]+)([\/:?=&#]{1}[\da-z\.-]+)*[\/\?]?', self.domain, + M | I): + data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Invalid domain."} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + if not match(r'([\da-z\.-]+\.[a-z\.]{2,12}|[\d\.]+)([\/:?=&#]{1}[\da-z\.-]+)*[\/\?]?', data['domainName'], + M | I): + 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, 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): + try: + 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 + + return render(request, 'websiteFunctions/syncMaster.html', + {'domainName': self.domain, 'externalApp': externalApp, 'childDomain': childDomain}) + except BaseException, msg: + return HttpResponse(str(msg)) + + + def startSync(self, userID=None, data=None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if not match(r'([\da-z\.-]+\.[a-z\.]{2,12}|[\d\.]+)([\/:?=&#]{1}[\da-z\.-]+)*[\/\?]?', data['childDomain'], + M | I): + 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, msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data)