-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathfleio.php
More file actions
447 lines (420 loc) · 16.6 KB
/
fleio.php
File metadata and controls
447 lines (420 loc) · 16.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
<?php
if (!defined("WHMCS")) {
die("This file cannot be accessed directly");
}
require_once __DIR__ . DIRECTORY_SEPARATOR . 'api.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'utils.php';
use Illuminate\Database\Capsule\Manager as Capsule;
function fleio_MetaData()
{
return array(
'DisplayName' => 'Fleio',
'APIVersion' => '1.1',
'RequiresServer' => false, // Set true if module requires a server to work
'DefaultNonSSLPort' => '80',
'DefaultSSLPort' => '443',
'ServiceSingleSignOnLabel' => 'Login to Fleio',
'AdminSingleSignOnLabel' => 'Login to Fleio',
);
}
function fleio_ConfigOptions() {
global $_LANG;
$default_currency_code = getCurrency()['code'];
$configarray = array(
"admintoken" => array (
"FriendlyName" => "Fleio staff Token",
"Type" => "password", # Password Field
"Size" => "64", # Defines the Field Width
"Default" => "",
),
"frontendurl" => array (
"FriendlyName" => "Frontend URL",
"Type" => "text", # Text Box
"Size" => "64", # Defines the Field Width
"Description" => "",
"Default" => "https://",
),
"frontendadminurl" => array (
"FriendlyName" => "Frontend staff URL",
"Type" => "text", # Text Box
"Size" => "64", # Defines the Field Width
"Description" => "",
"Default" => "https://",
),
"backendadminurl" => array (
"FriendlyName" => "Backend admin URL",
"Type" => "text", # Text Box
"Size" => "64", # Defines the Field Width
"Description" => "",
"Default" => "https://",
),
"minamount" => array (
"FriendlyName" => "Minimum payment amount",
"Type" => "text", # Text Box
"Size" => "10", # Defines the Field Width
"Description" => "". $default_currency_code,
"Default" => "10",
),
"maxamount" => array (
"FriendlyName" => "Maximum payment amount",
"Type" => "text", # Text Box
"Size" => "10", # Defines the Field Width
"Description" => "". $default_currency_code,
"Default" => "1000",
),
"clientgroup" => array (
"FriendlyName" => "Place clients inside a Fleio client group",
"Type" => "text", # Text Box
"Size" => "64", # Defines the Field Width
"Description" => "",
"Default" => "",
),
"configuration" => array (
"FriendlyName" => "Fleio Configuration Name",
"Type" => "text",
"Size" => "32",
"Description" => "Fleio configuration for new clients",
"Default" => ""
),
"userprefix" => array (
"FriendlyName" => "Fleio username prefix",
"Type" => "text",
"Size" => "12",
"Description" => "Leave blank for 'whmcs'. Field is not used anymore from Fleio version 2022.09.0.",
"Default" => "whmcs",
),
"issueinvoice" => array (
"FriendlyName" => "Invoice clients without billing agreement",
"Type" => "yesno",
"Description" => "Issue invoice at the end of billing cycle for clients without billing agreement",
),
"issueInvWAgr" => array (
"FriendlyName" => "Invoice clients with billing agreement",
"Type" => "yesno",
"Description" => "Issue invoice at the end of billing cycle for clients with billing agreement",
),
"chargeInvoiceRightAway" => array (
"FriendlyName" => "Attempt a charge immediately",
"Type" => "yesno",
"Description" => "Attempt charging of auto generated invoices when CC is on file immediately after the invoice was issued",
),
"gatewaysNamesForBillingAg" => array (
"FriendlyName" => "Names of gateways to use for billing agreement",
"Type" => "text",
"Size" => "32",
"Description" => "Comma separated string, each entry representing a name for a gateway that uses billing agreements. Leave empty to take into account all gateways",
"Default" => ""
),
"doNotInvoiceAmountBelow" => array (
"FriendlyName" => "Do not invoice amount below",
"Type" => "text",
"Size" => "10",
"Default" => "0",
"Description" => "".$default_currency_code
),
"retryChargesEveryXHours" => array (
"FriendlyName" => "Retry auto charging invoice after defined time (hours)",
"Type" => "text",
"Size" => "5",
"Description" => "If an invoice is not paid automatically, retry every hours you define here. Leave 0 or blank to disable this option.",
"Default" => "0",
),
"removeAgreementStatusAfterXFailedCharges" => array (
"FriendlyName" => "Remove on agreement status after defined number of failed charges (currently working with either 1 or 2).",
"Type" => "text",
"Size" => "1",
"Description" => "If an invoice belonging to a client on agreement is not successfully paid after a number of retries you define, he will not be considered on agreement anymore. The number of retries that will work is limited to 2. Choose either 1 or 2. Also, setting this to 2 does not make sense if you do not use the retry auto-charge setting.",
"Default" => "0",
),
"endUserWidgetNonAgreementMessage" => array (
"FriendlyName" => "Add a text to show to the enduser on the fleio dashboard widget if he is not on a billing agreement",
"Type" => "text",
"Size" => "10240",
"Description" => "Add a text to show to the enduser on the fleio dashboard widget if he is not on a billing agreement",
"Default" => "You can create a billing agreement when paying an invoice.",
),
"fleioWidgetExtraHtml" => array (
"FriendlyName" => "Fleio widget extra html",
"Type" => "text",
"Size" => "10240",
"Description" => "Add html input on the fleio dashboard widget after the existing content",
"Default" => "",
),
"invoiceOnlyInEndOfCycleTimespan" => array (
"FriendlyName" => "Invoice only in end of cycle timespan",
"Type" => "yesno",
"Description" => "Will not invoice for end of cycle if more than 72h passed after cycle end date",
),
"activateVerifiedClientServices" => array (
"FriendlyName" => "Activate services for clients with verified email",
"Type" => "yesno",
"Description" => "Each time cron runs, will activate Fleio services for clients with verified email",
),
"invoiceSuspendedClients" => array (
"FriendlyName" => "Generate invoices for suspended services",
"Type" => "yesno",
"Description" => "Also process suspended clients and generate invoices for them. Works only starting with Fleio 2024.04",
),
"doNotTaxInvoices" => array (
"FriendlyName" => "Do not apply tax to invoices created by this module",
"Type" => "yesno",
"Description" => "Invoices created by this module will not contain taxes even if tax rules apply to the client",
),
);
return $configarray;
}
function fleio_CreateAccount($params){
$fl = Fleio::fromParams($params);
try {
$fl->createBillingClient($params['configoption7'], $params['serviceid']);
} catch (FlApiException $e) {
return $e->getMessage();
}
return "success";
}
function fleio_SuspendAccount($params) {
$fl = Fleio::fromParams($params);
try {
$result = $fl->suspendOpenstack($params['serviceid']);
} catch (FlApiException $e) {
return $e->getMessage();
}
return "success";
}
function fleio_UnsuspendAccount($params) {
$fl = Fleio::fromParams($params);
try {
$result = $fl->resumeOpenstack($params['serviceid']);
} catch (FlApiException $e) {
return $e->getMessage();
}
return "success";
}
function fleio_TerminateAccount($params) {
$fl = Fleio::fromParams($params);
try {
$result = $fl->terminateOpenstack($params['serviceid']);
} catch (FlApiException $e) {
return ($e->getMessage());
}
return "success";
}
function fleio_login($params) {
$fl = Fleio::fromParams($params);
try {
$url = $fl->getSSOUrl();
header("Location: " . $url);
exit;
} catch (FlApiException $e) {
logActivity('Fleio SSO login error: ' . $e->getMessage());
return "Unable to retrieve a SSO session";
}
}
function fleio_ClientAreaCustomButtonArray() {
$buttonarray = array(
"Login to Fleio" => "login",
);
return $buttonarray;
}
/**
* 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 http://docs.whmcs.com/Provisioning_Module_SDK_Parameters
*
* @return array
*/
function fleio_ClientArea(array $params)
{
// Min/Max in base currency
$min_amount = 10;
$max_amount = 1000;
// Min/Max in client's currency
$minamount = convertCurrency($min_amount, 1, $params['clientsdetails']['currency']);
$maxamount = convertCurrency($max_amount, 1, $params['clientsdetails']['currency']);
$requestedAction = isset($_REQUEST['customAction']) ? $_REQUEST['customAction'] : '';
if ($requestedAction == 'manage') {
$serviceAction = 'get_usage';
$templateFile = 'templates/manage.tpl';
$exv2 = 'manage';
}
if ($requestedAction == 'stats') {
$serviceAction = 'get_stats';
$templateFile = 'templates/overview.tpl';
$exv2 = 'stats';
}
if ($requestedAction == 'createflinvoice') {
$serviceAction = 'actionCreateInvoice';
$templateFile = 'templates/overview.tpl';
} else {
$serviceAction = 'actionOverview';
$templateFile = 'templates/overview.tpl';
}
try {
// Call the service's function based on the request action, using the
// values provided by WHMCS in `$params`.
return array(
'tabOverviewReplacementTemplate' => $templateFile,
'templateVariables' => $serviceAction($params, $_REQUEST),
);
} catch (Exception $e) {
// Record the error in WHMCS's module log.
logModuleCall(
'fleio',
__FUNCTION__,
$params,
$e->getMessage(),
$e->getTraceAsString()
);
// In an error condition, display an error page.
return array(
'tabOverviewReplacementTemplate' => 'templates/error.tpl',
'templateVariables' => array(
'usefulErrorHelper' => $e->getMessage(),
),
);
}
}
function actionOverview($params, $request) {
$min_amount = $params['configoption5'];
$max_amount = $params['configoption6'];
// Min/Max in client's currency
$whmcsClientCurrencyId = $params['clientsdetails']['currency'];
$minamount = convertCurrency($min_amount, 1, $whmcsClientCurrencyId);
$maxamount = convertCurrency($max_amount, 1, $whmcsClientCurrencyId);
$fl = Fleio::fromParams($params);
try {
$client = $fl->getClient();
} catch (Exception $e) {
logModuleCall(
'fleio',
__FUNCTION__,
$params,
$e->getMessage(),
$e->getTraceAsString()
);
$client = False;
};
// Convert from Fleio client currency to the WHMCS client currency
$tax1 = getTaxRate(1, $params['clientsdetails']['state'], $params['clientsdetails']['countrycode']);
$tax2 = getTaxRate(2, $params['clientsdetails']['state'], $params['clientsdetails']['countrycode']);
$taxexempt = $params['clientsdetails']['taxexempt'];
$doNotTaxInvoices = $params['configoption22'] ? true : false;
if ($taxexempt || $doNotTaxInvoices) {
$tax1_rate = 0;
$tax2_rate = 0;
} else {
$tax1_rate = $tax1['rate'];
$tax2_rate = $tax2['rate'];
}
$uptodateCredit = NULL;
$outofcreditDatetime = NULL;
$whmcsClientCurrency = getCurrency($params['clientsdetails']['userid']);
if (is_array($client) && array_key_exists('uptodate_credit', $client) && array_key_exists('outofcredit_datetime', $client)) {
$uptodateCredit = $client['uptodate_credit'];
$outofcreditDatetime = $client['outofcredit_datetime'];
$whmcsCurrency = Capsule::table('tblcurrencies')
->select('id', 'code')
->where('code', '=', $client['currency'])
->first();
try {
$uptodateCreditFormatted = formatCurrency($uptodateCredit, $whmcsCurrency->id);
} catch (Exception $e) {
$uptodateCreditFormatted = '' . $uptodateCredit;
}
}
return array('minamount' => $minamount,
'maxamount' => $maxamount,
'tax1_rate' => $tax1_rate,
'tax2_rate' => $tax2_rate,
'currency' => $whmcsClientCurrency,
'uptodateCredit' => $uptodateCreditFormatted,
'outofcreditDatetime' => $outofcreditDatetime);
}
function validateAmount($original_amount, $min, $max) {
// Validate amount
// Using , instead of . (dot) ?
$amount = str_replace(",", ".", $original_amount);
if (!is_numeric($amount)) {
throw new Exception("Please enter a valid amount.");
}
if ($amount < $min) {
$def_msg = isset($_LANG['addfundsminimumerror']) ? $_LANG['addfundsminimumerror'] : 'Amount must be equal or greated than';
throw new Exception($def_msg." ".formatCurrency($min));
}
if ($amount > $max) {
$def_msg = isset($_LANG['addfundsmaximumerror']) ? $_LANG['addfundsmaximumerror'] : 'Amount must be smaller than';
throw new Exception($def_msg." ".formatCurrency($max));
}
return $amount;
}
function canAddCredit($serviceStatus) {
if ($serviceStatus === 'Cancelled' || $serviceStatus === 'Terminated') {
throw new Exception("You cannot add credit while your service status is " . $serviceStatus . ".");
}
}
function actionCreateInvoice($params, $request) {
# Action used for the Add Credit functionality
$min_amount = $params['configoption5'];
$max_amount = $params['configoption6'];
// Min/Max in client's currency
$minamount = convertCurrency($min_amount, 1, $params['clientsdetails']['currency']);
$maxamount = convertCurrency($max_amount, 1, $params['clientsdetails']['currency']);
$original_amount = $request["amount"];
try {
$amount = validateAmount($original_amount, $minamount, $maxamount);
} catch (Exception $e) {
$overview_vars = actionOverview($params, $request);
return array_merge($overview_vars, array('validateAmountError' => $e->getMessage(),));
}
$service = FleioUtils::getServiceById($params['serviceid']);
if ($service) {
try {
canAddCredit($service->domainstatus);
} catch (Exception $e) {
$overview_vars = actionOverview($params, $request);
return array_merge($overview_vars, array('validateServiceError' => $e->getMessage(),));
}
}
$clientsdetails = $params['clientsdetails'];
$values["userid"] = $clientsdetails['userid'];
$values["sendinvoice"] = true;
$values["itemdescription1"] = $service->name;
$values["itemamount1"] = $amount;
$applyTaxes = $params['configoption22'] == 'on' ? false : true;
$values["itemtaxed1"] = $applyTaxes;
if ($service && !is_null($service->paymentmethod)) {
$values['paymentmethod'] = $service->paymentmethod;
}
try {
$invoice_id = FleioUtils::createFleioInvoice($params['serviceid'], $values);
} catch (Exception $e) {
logActivity('Fleio: unable to create invoice for service ' . $params['serviceid'] . ': ' . $e->getMessage());
throw new Exception('Unable to create invoice');
}
$log_msg = "Fleio: Client ID: ".$clientsdetails['userid']." created credit Invoice ID: ".$invoice_id." with amount ".formatCurrency($amount);
logActivity($log_msg);
redir("id=".(int) $invoice_id,"viewinvoice.php");
}