Просмотр исходного кода

cleanup and docu ready to test

andre 5 лет назад
Родитель
Сommit
9c52269287
1 измененных файлов с 305 добавлено и 101 удалено
  1. 305 101
      zimbraSingle.php

+ 305 - 101
zimbraSingle.php

@@ -3,7 +3,7 @@
 /**
  * WHMCS Zimbra Provisioning Module
  *
- * Provisioning for private user accounts on the Zimbra Server
+ * Provisioning for private mailboxes on a Zimbra Server
  *
  * @see https://www.zimbra.com
  * @copyright Copyright (c) Thurdata GmbH 2020
@@ -14,24 +14,32 @@ if (!defined("WHMCS")) {
     die("This file cannot be accessed directly");
 }
 use WHMCS\Database\Capsule;
+
+/**
+ * Requires this PHP api to make soap calls and parse responses
+ * This is an extend version of:
+ * @see https://github.com/alloylab/zimbra-admin-api-soap-php
+ */
 require_once("api/Zm/Auth.php");
 require_once("api/Zm/Account.php");
 require_once("api/Zm/Domain.php");
 require_once("api/Zm/Server.php");
 
+/**
+ * Helper function to get the zimbra server access data from whmcs database
+ * 
+ * @return array $accessData {
+ *      @type string 'zimbraServer' zimbra server IP address
+ *      @type string 'adminUser' zimbra admin username
+ *      @type string 'password' zimbra admin password
+ * } or false in case of error
+ */
 function zimbraSingleGetAccess()
 {
     $accessData = array('zimbraServer' => '', 'adminUser' => '', 'adminPass' => '');
     $whmcs = App::self();
     $serverGroupID = $whmcs->get_req_var('servergroup');
     $action = $whmcs->get_req_var('action');
-    logModuleCall(
-        'zimbrasingle',
-        __FUNCTION__,
-        $action,
-        "Debug" ,
-        $whmcs
-    );
     if(($action == 'module-settings') || ($action == 'ConfigOptions') || ($action == 'save')) {
         $productID = $whmcs->get_req_var('id');
         $serverGroupIDObj = Capsule::table('tblproducts')
@@ -63,42 +71,28 @@ function zimbraSingleGetAccess()
     $adminPassDecrypt = localAPI('DecryptPassword', array('password2' => $adminPassCrypt));
     if ($adminPassDecrypt['result'] == 'success') {
         $accessData['adminPass'] = $adminPassDecrypt['password'];
-    }
-    return $accessData;
-}
-
-/**
- * Checks if a given email address in the given domain already exists
- *
- * @param  $emailNameOnly       The name before the @-sign only
- * @param  $domainName          The domain to search for existance of the email account
- * @return true if such an account was found or false if not
- */
-function zimbraSingleDoesEMailExist($emailNameOnly, $domainName)
-{
-    $account_name = $emailNameOnly . "@" . $domainName;
-    $accessData = zimbraSingleGetAccess();
-    $api = new Zm_Auth($accessData['zimbraServer'], $accessData['adminUser'], $accessData['adminPass'], "admin");
-    $login = $api->login();
-    if(is_a($login, "Exception")) {
+    } else {
         logModuleCall(
             'zimbrasingle',
             __FUNCTION__,
-            $params,
-            "Error : cannot login to " . $accessData['zimbraServer'],
-            "$login->getMessage()"
+            $adminPassCrypt,
+            "Error: cloud not decrypt admin password" ,
+            $adminPassDecrypt
         );
-        exit();
-    } else {
-        $apiAccountManager = new Zm_Account($api);
-            if( $apiAccountManager->accountExists($account_name)) {
-            return true;
-        } else {
-            return false;
-        }
+        return false;
     }
+    return $accessData;
 }
 
+/**
+ * Helper function creates all necessary custom fields depending on selected configuration options
+ * 
+ * @param array $packageconfigoption {
+ *      @type string 1 class of service
+ *      @type string 2 comma seperated list of maildomains
+ * }
+ * @return bool true in case of success or false on any error
+ */
 function zimbraSingleCreateCustomFields($packageconfigoption)
 {
     $whmcs = App::self();
@@ -106,7 +100,8 @@ function zimbraSingleCreateCustomFields($packageconfigoption)
     Capsule::table('tblcustomfields')
         ->where('relid', '=', $productID)
         ->delete();
-    Capsule::table('tblcustomfields')
+    try {
+        Capsule::table('tblcustomfields')
         ->insert(
             array(
                 'type' => 'product',
@@ -117,8 +112,8 @@ function zimbraSingleCreateCustomFields($packageconfigoption)
                 'showorder' => 'on',
                 'sortorder' => '0'
             )
-    );
-    Capsule::table('tblcustomfields')
+        );
+        Capsule::table('tblcustomfields')
         ->insert(
             array(
                 'type' => 'product',
@@ -129,8 +124,8 @@ function zimbraSingleCreateCustomFields($packageconfigoption)
                 'showorder' => 'on',
                 'sortorder' => '1'
             )
-    );
-    Capsule::table('tblcustomfields')
+        );
+        Capsule::table('tblcustomfields')
         ->insert(
             array(
                 'type' => 'product',
@@ -141,8 +136,8 @@ function zimbraSingleCreateCustomFields($packageconfigoption)
                 'showorder' => 'on',
                 'sortorder' => '2'
             )
-    );
-    Capsule::table('tblcustomfields')
+        );
+        Capsule::table('tblcustomfields')
         ->insert(
             array(
                 'type' => 'product',
@@ -154,8 +149,8 @@ function zimbraSingleCreateCustomFields($packageconfigoption)
                 'showorder' => 'on',
                 'sortorder' => '3'
             )
-    );
-    Capsule::table('tblcustomfields')
+        );
+        Capsule::table('tblcustomfields')
         ->insert(
             array(
                 'type' => 'product',
@@ -166,8 +161,8 @@ function zimbraSingleCreateCustomFields($packageconfigoption)
                 'showorder' => 'on',
                 'sortorder' => '4'
             )
-    );
-    Capsule::table('tblcustomfields')
+        );
+        Capsule::table('tblcustomfields')
         ->insert(
             array(
                 'type' => 'product',
@@ -178,8 +173,8 @@ function zimbraSingleCreateCustomFields($packageconfigoption)
                 'showorder' => 'on',
                 'sortorder' => '5'
             )
-    );
-    Capsule::table('tblcustomfields')
+        );
+        Capsule::table('tblcustomfields')
         ->insert(
             array(
                 'type' => 'product',
@@ -191,9 +186,27 @@ function zimbraSingleCreateCustomFields($packageconfigoption)
                 'required' => 'on',
                 'sortorder' => '6'
             )
-    );
+        );
+        return true;
+    } catch (\Exception $e) {
+        logModuleCall(
+            'zimbrasingle',
+            __FUNCTION__,
+            $params,
+            "Error: could not create custom fields",
+            $e->getMessage()
+        );
+        return false;
+    }
 }
 
+/**
+ * Helper function to find values of a named key in a multidimensional array or object
+ * 
+ * @param array $haystack mixed data
+ * @param string $needle key to search for values
+ * @return array of values
+ */
 function recursiveFindAll($haystack, $needle)
 {
     $values = array();
@@ -210,6 +223,12 @@ function recursiveFindAll($haystack, $needle)
     return $values;
 }
 
+/**
+ * Helper function to check a password strength
+ * 
+ * @param string $pwd password to check
+ * @return string $message what is missing in the password (empty if it is okay)
+ */
 function zimbraSingleCheckPassword($pwd)
 {
     $message = '';
@@ -231,6 +250,14 @@ function zimbraSingleCheckPassword($pwd)
     return $message;
 }
 
+/**
+ * Convert raw byte value to human readable
+ * 
+ * Helper function to convert byte in huam readable format
+ * 
+ * @param int $bytes value in bytes
+ * @return string value rounded and in human readable units
+ */
 function bytesToHuman($bytes)
 {
     $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
@@ -238,6 +265,16 @@ function bytesToHuman($bytes)
     return round($bytes, 2) . ' ' . $units[$i];
 }
 
+/**
+ * Define module related meta data.
+ *
+ * Values returned here are used to determine module related abilities and
+ * settings.
+ *
+ * @see https://developers.whmcs.com/provisioning-modules/meta-data-params/
+ *
+ * @return array
+ */
 function zimbraSingle_MetaData()
 {
     return array(
@@ -251,6 +288,23 @@ function zimbraSingle_MetaData()
     );
 }
 
+/**
+ * Test connection to a Zimbra server with the given server parameters.
+ *
+ * Allows an admin user to verify that an API connection can be
+ * successfully made with the given configuration parameters for a
+ * server.
+ *
+ * When defined in a module, a Test Connection button will appear
+ * alongside the Server Type dropdown when adding or editing an
+ * existing server.
+ *
+ * @param array $params common module parameters
+ *
+ * @see https://developers.whmcs.com/provisioning-modules/module-parameters/
+ *
+ * @return array
+ */
 function zimbraSingle_TestConnection($params)
 {
     $auth = new Zm_Auth($params['serverip'], $params['serverusername'], $params['serverpassword'], "admin");
@@ -275,6 +329,36 @@ function zimbraSingle_TestConnection($params)
     }
 }
 
+/**
+ * Client area output logic handling.
+ *
+ * This function is used to define module specific client area output. It should
+ * return an array consisting of a template file and optional additional
+ * template variables to make available to that template.
+ *
+ * The template file you return can be one of two types:
+ *
+ * * tabOverviewModuleOutputTemplate - The output of the template provided here
+ *   will be displayed as part of the default product/service client area
+ *   product overview page.
+ *
+ * * tabOverviewReplacementTemplate - Alternatively using this option allows you
+ *   to entirely take control of the product/service overview page within the
+ *   client area.
+ *
+ * Whichever option you choose, extra template variables are defined in the same
+ * way. This demonstrates the use of the full replacement.
+ *
+ * Please Note: Using tabOverviewReplacementTemplate means you should display
+ * the standard information such as pricing and billing details in your custom
+ * template or they will not be visible to the end user.
+ *
+ * @param array $params common module parameters
+ *
+ * @see https://developers.whmcs.com/provisioning-modules/module-parameters/
+ *
+ * @return array
+ */
 function zimbraSingle_ClientArea($params)
 {
     $accessData = zimbraSingleGetAccess();
@@ -310,7 +394,7 @@ function zimbraSingle_ClientArea($params)
             'zimbrasingle',
             __FUNCTION__,
             $params,
-            "Error : could not fetch mailbox info for $account_name",
+            "Error: could not fetch mailbox info for $account_name",
             $response
         );
         return false;
@@ -326,7 +410,7 @@ function zimbraSingle_ClientArea($params)
             'zimbrasingle',
             __FUNCTION__,
             $params,
-            "Error : could not gather informations for  $account_name",
+            "Error: could not gather informations for  $account_name",
             $response
         );
         return false;
@@ -339,6 +423,22 @@ function zimbraSingle_ClientArea($params)
     );
 }
 
+/**
+ * Change the password for a Zimbra account.
+ *
+ * Called when a password change is requested. This can occur either due to a
+ * client requesting it via the client area or an admin requesting it from the
+ * admin side.
+ *
+ * This option is only available to client end users when the product is in an
+ * active status.
+ *
+ * @param array $params common module parameters
+ *
+ * @see https://developers.whmcs.com/provisioning-modules/module-parameters/
+ *
+ * @return string "success" or an error message
+ */
 function zimbraSingle_ChangePassword($params)
 {
     $accessData = zimbraSingleGetAccess();
@@ -353,7 +453,7 @@ function zimbraSingle_ChangePassword($params)
             'zimbrasingle',
             __FUNCTION__,
             $params,
-            "Error : cannot login to " . $accessData['zimbraServer'],
+            "Error: cannot login to " . $accessData['zimbraServer'],
             $login
         );
         return false;
@@ -365,7 +465,7 @@ function zimbraSingle_ChangePassword($params)
             'zimbrasingle',
             __FUNCTION__,
             $params,
-            "Error : password for $account_name could not be set",
+            "Error: password for $account_name could not be set",
             $response
         );
         return false;
@@ -373,9 +473,52 @@ function zimbraSingle_ChangePassword($params)
     return 'success';
 }
 
+/**
+ * Provision a new instance of a Zimbra account.
+ *
+ * Attempt to provision a new Zimbra mail account. This is
+ * called any time provisioning is requested inside of WHMCS. Depending upon the
+ * configuration, this can be any of:
+ * * When a new order is placed
+ * * When an invoice for a new order is paid
+ * * Upon manual request by an admin user
+ *
+ * @param array $params common module parameters
+ *
+ * @see https://developers.whmcs.com/provisioning-modules/module-parameters/
+ *
+ * @return string "success" or an error message
+ */
 function zimbraSingle_CreateAccount($params)
 {
     $accessData = zimbraSingleGetAccess();
+    $api = new Zm_Auth($accessData['zimbraServer'], $accessData['adminUser'], $accessData['adminPass'], "admin");
+    $login = $api->login();
+    if(is_a($login, "Exception")) {
+        logModuleCall(
+            'zimbrasingle',
+            __FUNCTION__,
+            $params,
+            "Error: cannot login to $accessData[zimbraServer]",
+            $login
+        );
+        return $login->getMessage();
+    }
+    $apiAccountManager = new Zm_Account($api);
+    $accountExists = $apiAccountManager->accountExists($account_name);
+    if(is_a($accountExists, "Exception")) {
+        logModuleCall(
+            'zimbrasingle',
+            __FUNCTION__,
+            $params,
+            "Error: could not check account availibility",
+            $account_name
+        );
+        return false;
+    }
+    if($accountExists == true) {
+        return 'Account already exist';
+    }
     $attrs = array();
     $attrs["gn"] = $params['customfields']["givenname"];
     $attrs["sn"] = $params['customfields']["sn"];
@@ -383,30 +526,25 @@ function zimbraSingle_CreateAccount($params)
     $passDecrypt = localAPI('DecryptPassword', array('password2' => $params['customfields']['password']));
     if ($passDecrypt['result'] == 'success') {
         $params['customfields']['password'] = $passDecrypt['password'];
-    }
-    $account_name = $params['customfields']['username'] . '@' . $params['customfields']['maildomain'];
-    $api = new Zm_Auth($accessData['zimbraServer'], $accessData['adminUser'], $accessData['adminPass'], "admin");
-    $login = $api->login();
-    if(is_a($login, "Exception")) {
+    } else {
         logModuleCall(
             'zimbrasingle',
             __FUNCTION__,
-            $params,
-            "Error : cannot login to " . $accessData['zimbraServer'],
-            ""
-        );
-        return false;
+            $params['customfields']['password'],
+            "Error: could not decrypt password",
+            $passDecrypt
+            );
+            return false;
     }
-    $apiAccountManager = new Zm_Account($api);
-    $cosName = $params['customfields']['cos'];
-    $cosID = $apiAccountManager->getCosId($cosName);
+    $account_name = $params['customfields']['username'] . '@' . $params['customfields']['maildomain'];
+    $cosID = $apiAccountManager->getCosId($params['customfields']['cos']);
     if(is_a($cosID, "Exception")) {
         logModuleCall(
-        'zimbrasingle',
-        __FUNCTION__,
-        $params,
-        "Error : serviceclass $cosName not available",
-        $params['customfields']['cos']
+            'zimbrasingle',
+            __FUNCTION__,
+            $params['customfields']['cos'],
+            "Error: serviceclass not available",
+            $cosID
         );
         return false;
     }
@@ -414,17 +552,30 @@ function zimbraSingle_CreateAccount($params)
     $id = $apiAccountManager->createAccount($account_name, $params['customfields']['password'], $attrs);
     if(is_a($id, "Exception")) {
         logModuleCall(
-        'zimbrasingle',
-        __FUNCTION__,
-        $params,
-        "Error : account $account_name not created",
-        $id
+            'zimbrasingle',
+            __FUNCTION__,
+            $params,
+            "Error: account $account_name not created",
+            $id
         );
         return false;
     }
     return 'success';
 }
 
+/**
+ * Set a Zimbra account to status locked.
+ *
+ * Called when a suspension is requested. This is invoked automatically by WHMCS
+ * when a product becomes overdue on payment or can be called manually by admin
+ * user.
+ *
+ * @param array $params common module parameters
+ *
+ * @see https://developers.whmcs.com/provisioning-modules/module-parameters/
+ *
+ * @return string "success" or an error message
+ */
 function zimbraSingle_SuspendAccount($params)
 {
     $accessData = zimbraSingleGetAccess();
@@ -436,10 +587,10 @@ function zimbraSingle_SuspendAccount($params)
             'zimbrasingle',
             __FUNCTION__,
             $params,
-            "Error : cannot login to " . $accessData['zimbraServer'],
+            "Error: cannot login to " . $accessData['zimbraServer'],
             $login
         );
-        return false;
+        return $login->getMessage();
     }
     $apiAccountManager = new Zm_Account($api);
     $response = $apiAccountManager->setAccountStatus($account_name, "locked");
@@ -448,7 +599,7 @@ function zimbraSingle_SuspendAccount($params)
             'zimbrasingle',
             __FUNCTION__,
             $params,
-            "Error : account $account_name could not locked",
+            "Error: account $account_name could not locked",
             $response
         );
         return false;
@@ -456,6 +607,19 @@ function zimbraSingle_SuspendAccount($params)
     return 'success';
 }
 
+/**
+ * Set a Zimbra account to status active.
+ *
+ * Called when an un-suspension is requested. This is invoked
+ * automatically upon payment of an overdue invoice for a product, or
+ * can be called manually by admin user.
+ *
+ * @param array $params common module parameters
+ *
+ * @see https://developers.whmcs.com/provisioning-modules/module-parameters/
+ *
+ * @return string "success" or an error message
+ */
 function zimbraSingle_UnsuspendAccount($params)
 {
     $accessData = zimbraSingleGetAccess();
@@ -467,10 +631,10 @@ function zimbraSingle_UnsuspendAccount($params)
             'zimbrasingle',
             __FUNCTION__,
             $params,
-            "Error : cannot login to " . $accessData['zimbraServer'],
+            "Error: cannot login to " . $accessData['zimbraServer'],
             $login
         );
-        return false;
+        return $login->getMessage();
     }
     $apiAccountManager = new Zm_Account($api);
     $response = $apiAccountManager->setAccountStatus($account_name, "active");
@@ -479,14 +643,26 @@ function zimbraSingle_UnsuspendAccount($params)
             'zimbrasingle',
             __FUNCTION__,
             $params,
-            "Error : account $account_name could not unlocked",
+            "Error: account $account_name could not unlocked",
             $response
             );
-        return false;
+        return "Error: account $account_name could not unlocked";
     }
     return 'success';
 }
 
+/**
+ * Removes a Zimbra account.
+ *
+ * Called when a termination is requested. This can be invoked automatically for
+ * overdue products if enabled, or requested manually by an admin user.
+ *
+ * @param array $params common module parameters
+ *
+ * @see https://developers.whmcs.com/provisioning-modules/module-parameters/
+ *
+ * @return string "success" or an error message
+ */
 function zimbraSingle_TerminateAccount($params)
 {
     $accessData = zimbraSingleGetAccess();
@@ -498,10 +674,10 @@ function zimbraSingle_TerminateAccount($params)
             'zimbrasingle',
             __FUNCTION__,
             $params,
-            "Error : cannot login to " . $accessData['zimbraServer'],
+            "Error: cannot login to " . $accessData['zimbraServer'],
             $login
         );
-        return false;
+        return $login->getMessage();
     }
     $apiAccountManager = new Zm_Account($api);
     $response = $apiAccountManager->getAccountStatus($accountName);
@@ -510,28 +686,44 @@ function zimbraSingle_TerminateAccount($params)
             'zimbrasingle',
             __FUNCTION__,
             $params,
-            "Error : account $accountName could not verified",
+            "Error: account $accountName could not verified",
             $response
         );
-        return false;
+        return "Error : account $accountName could not verified";
     }
     if ($response != 'locked') {
-        return "Account $accountName active, suspend account first";
+        return "Account $accountName active, suspend account first!";
     }
     $response = $apiAccountManager->deleteAccount($accountName);
     if(is_a($response, "Exception")) {
         logModuleCall(
-        'zimbrasingle',
-        __FUNCTION__,
-        $params,
-        "Error : account $accountName could not removed",
-        $response
+            'zimbrasingle',
+            __FUNCTION__,
+            $params,
+            "Error: account $accountName could not removed",
+            $response
         );
-        return false;
+        return "Error: account $accountName could not removed";
     }
     return 'success';
 }
 
+/**
+ * Set a new class of service for a Zimbra account.
+ *
+ * Called to apply a change of the class of service. It
+ * is called to provision upgrade or downgrade orders, as well as being
+ * able to be invoked manually by an admin user.
+ *
+ * This same function is called for upgrades and downgrades of both
+ * products and configurable options.
+ *
+ * @param array $params common module parameters
+ *
+ * @see https://developers.whmcs.com/provisioning-modules/module-parameters/
+ *
+ * @return string "success" or an error message
+ */
 function zimbraSingle_ChangePackage($params)
 {
     $accessData = zimbraSingleGetAccess();
@@ -543,10 +735,10 @@ function zimbraSingle_ChangePackage($params)
             'zimbrasingle',
             __FUNCTION__,
             $params,
-            "Error : cannot login to " . $accessData['zimbraServer'],
+            "Error: cannot login to " . $accessData['zimbraServer'],
             $login
         );
-        return false;
+        return $login->getMessage();
     }
     $apiAccountManager = new Zm_Account($api);
     $response = $apiAccountManager->setAccountCos($account_name, $params['customfields']['cos']);
@@ -555,18 +747,30 @@ function zimbraSingle_ChangePackage($params)
             'zimbrasingle',
             __FUNCTION__,
             $params,
-            "Error : class of service for $account_name could not be set",
+            "Error: class of service for $account_name could not be set",
             $response
         );
-        return false;
+        return "Error: class of service for $account_name could not be set";
     }
     return 'success';
 }
 
+/**
+ * Define Zimbra product configuration options.
+ *
+ * Gather classes of service and available mail domains from the Zinbra server.
+ * Calls a function to create all necessary customfields for the order form using the selected values.
+ *
+ * @see https://developers.whmcs.com/provisioning-modules/config-options/
+ *
+ * @return array
+ */
 function zimbraSingle_ConfigOptions($params)
 {
     if(isset($_POST['packageconfigoption'])) {
-        zimbraSingleCreateCustomFields($_POST['packageconfigoption']);
+        if(zimbraSingleCreateCustomFields($_POST['packageconfigoption']) == false) {
+            return false;
+        };
     }
     $accessData = zimbraSingleGetAccess();
     $api = new Zm_Auth($accessData['zimbraServer'], $accessData['adminUser'], $accessData['adminPass'], "admin");