-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathcometbackup.php
More file actions
475 lines (399 loc) · 18.6 KB
/
cometbackup.php
File metadata and controls
475 lines (399 loc) · 18.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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
<?php
use WHMCS\Database\Capsule;
require_once __DIR__ . '/functions.php';
if (!defined("WHMCS")) {
die("This file cannot be accessed directly");
}
function cometbackup_MetaData() {
return [
'DisplayName' => 'Comet Backup',
'APIVersion' => '1.1',
'RequiresServer' => true,
'DefaultNonSSLPort' => 8060,
'DefaultSSLPort' => 443,
];
}
function cometbackup_ConfigOptions($params) {
return [
'PolicyGroupGUID' => [
'FriendlyName' => 'Policy Group',
'Type' => 'dropdown',
'Description' => '<br>Select a policy group to apply to users of this product.',
'Loader' => 'cometbackup_ConfigOptionsPolicyGroupLoader',
'SimpleMode' => true
],
'StorageProviderID' => [
'FriendlyName' => 'Storage Vault',
'Type' => 'dropdown',
'Description' => '<br>Request an initial storage vault for new users.',
'Loader' => 'cometbackup_ConfigOptionsStorageProvidersLoader',
'SimpleMode' => true
],
'RequirePasswordChange' => [
'FriendlyName' => 'Require password change at initial login',
'Type' => 'dropdown',
'Description' => '<br>Require the user to change their password after logging in (i.e. initial password becomes temporary). Best combined with the non-custom password approach.',
'Loader' => 'cometbackup_ConfigOptionsRequirePasswordChange',
'SimpleMode' => true
],
'Message' => [
'FriendlyName' => 'Note',
'Description' => 'The [Create New Policy Group] option will cause a new policy group to be created - for technical reasons, this one-time action is postponed to the first time a new account is created using this product. <style>div.module-settings-mode > a.btn > span.text-advanced{display:none;}</style>',
'SimpleMode' => true
],
];
}
function cometbackup_ConfigOptionsPolicyGroupLoader(array $params) {
$policyGroups = performAPIRequest($params, [], 'policies/list');
if (array_key_exists('curlerror', $policyGroups)) {
throw new Exception('Invalid request. Server mis-configured?');
}
$newPolicyGroupID = uniqid("WHMCS_", true);
return ['' => 'None'] + $policyGroups + [$newPolicyGroupID => '[Create New Policy Group] (' . $newPolicyGroupID . ')'];
}
function cometbackup_ConfigOptionsStorageProvidersLoader(array $params) {
$storageProviders = performAPIRequest($params, [], 'request-storage-vault-providers');
if (array_key_exists('curlerror', $storageProviders)) {
throw new Exception('Invalid request. Server mis-configured?');
}
return ["" => "None"] + $storageProviders;
}
function cometbackup_ConfigOptionsRequirePasswordChange(array $params) {
return ["no" => "No", "yes" => "Yes"];
}
function cometbackup_CreateAccount(array $params) {
$isUsingCustomUsername = false;
$isUsingCustomPassword = false;
// Try a few different options for automatic username selection
if (!empty(trim($params['customfields']['Username']))) {
// Use a manually specified username, if this has been configured
$username = trim($params['customfields']['Username']);
$isUsingCustomUsername = true;
} else if (!empty($params['clientsdetails']['email'])) {
// Use the client's email address, if present
$username = $params['clientsdetails']['email'];
} else if (!empty(strtolower($params['clientsdetails']['firstname']))) {
// If we somehow ended up here, use the client's first name and service ID as a base
$username = strtolower($params['clientsdetails']['firstname'] . $params['serviceid']);
} else {
// Everything else has failed, so we'll start with the word 'user' and append some random characters in the next step
$username = 'user';
}
// Make sure username is of sufficient length
$usernameLength = strlen($username);
if ($usernameLength < 6) { // Minimum username length is 6 characters
$randomData = strval(rand(100000, getrandmax())); // Need to supplement with up to 6 random numbers
$username = $username . substr($randomData, 0, 6 - $usernameLength);
}
// Prepare base API request params
$baseRequestData = [
'TargetUser' => $username,
];
// Check if username is already in use
$alreadyExists = true;
$newUsername = $username;
while ($alreadyExists === true) {
$usernameExistsCheck = performAPIRequest($params, $baseRequestData, 'get-user-profile');
$alreadyExists = array_key_exists('Username', $usernameExistsCheck);
// If the username is taken, supplement with random characters and try again
if ($alreadyExists) {
$newUsername = $username . '_' . strval(rand(1000, 9999)); // Supplement with 4 random numbers
$baseRequestData['TargetUser'] = $newUsername;
}
}
// Update the custom parameter username to be set to the new username that has been created for the service
$username = $newUsername;
$params['username'] = $username;
$results = localAPI(
'UpdateClientProduct',
[
'serviceid' => $params['serviceid'],
'customfields' => base64_encode(serialize(array("username" => $newUsername))),
]
);
if (isset($results['result']) && $results['result'] !== 'success') {
throw new Exception("Provisioning Comet Backup Account $newUsername: WHMCS Update custom fields error:" . $results['message']);
}
// Create policy if it doesn't yet exist
if (!empty($params['configoption1'])) {
maybeCreatePolicyGroup($params, $params['configoption1']);
}
// Get account password
$password = getPasswordFromParams($params);
$isUsingCustomPassword = getIsUsingCustomPasswordFromParams($params);
// Prepare add-user API request params
$addUserRequestQuery = $baseRequestData + [
'TargetPassword' => $password,
'StoreRecoveryCode' => 1
];
// Apply the 'Require password change at initial login' setting
if (!empty($params['configoption3']) && $params['configoption3'] === 'yes') {
$addUserRequestQuery['RequirePasswordChange'] = 1;
}
// Update username on record in case this changed
$dbQueryParams = [
'username' => ($isUsingCustomUsername ? '[Using custom field]' : $username)
];
// Clear auto-generated service password if a custom password field is in use
if ($isUsingCustomPassword) {
$dbQueryParams['password'] = '';
}
// Apply DB updates
$result = Capsule::table('tblhosting')->where('id', $params['serviceid'])->update($dbQueryParams);
$response = performAPIRequest($params, $addUserRequestQuery, 'add-user');
// Account creation succeeded
if (isset($response['Status']) && $response['Status'] == 200) {
// Request storage vault
if (!empty($params['configoption2'])) {
$requestStorageVaultRequestData = $baseRequestData + [
'StorageProvider' => $params['configoption2'],
'SelfAddress' => getHost($params).'/'
];
performAPIRequest($params, $requestStorageVaultRequestData, 'request-storage-vault');
}
return applyRestrictions($params);
// Account creation failed
} else {
return handleErrorResponse($response);
}
}
function cometbackup_SuspendAccount(array $params) {
return modifyAccountSuspensionState($params, true);
}
function cometbackup_UnsuspendAccount(array $params) {
return modifyAccountSuspensionState($params, false);
}
function cometbackup_TerminateAccount(array $params) {
$requestData = [
'TargetUser' => getUsernameFromParams($params)
];
$response = performAPIRequest($params, $requestData, 'delete-user');
if (array_key_exists('Status', $response) && $response['Status'] === 200) {
return 'success';
} else if (array_key_exists('Message', $response)) {
return $response['Message'];
} else {
return 'Unknown error - please contact support: ' . base64_encode($response);
}
}
function cometbackup_ChangePassword(array $params) {
$password = getPasswordFromParams($params);
$isUsingCustomPassword = getIsUsingCustomPasswordFromParams($params);
// Clear auto-generated service password if a custom password field is in use
if ($isUsingCustomPassword && !empty($params['password'])) {
// If not empty the WHMCS service password likely reflects a change
$password = $params['password'];
// Re-clear service password
Capsule::table('tblhosting')->where('id', $params['serviceid'])->update(['password' => '']);
// Apply the new password to the custom password field
foreach (Capsule::table('tblcustomfields')->where([['relid', $params['pid']],['fieldname', 'Password']])->get() as $customField) {
Capsule::table('tblcustomfieldsvalues')
->where([['relid', $params['serviceid']],['fieldid', $customField->id]])
->update(['value' => $password]);
break;
}
}
if (strlen($password) < 8) {
return '<span style="color:darkred;">ERROR: Password must contain at least 8 characters.</span>';
}
$requestData = [
'TargetUser' => getUsernameFromParams($params),
'NewPassword' => $password
];
$response = performAPIRequest($params, $requestData, 'reset-user-password');
if (array_key_exists('Status', $response) && $response['Status'] === 200) {
return 'success';
} else {
return handleErrorResponse($response);
}
}
function cometbackup_ClientArea(array $params) {
// Handle client download request
if (!!$_GET['type'] && strpos($_GET['type'], 'downloadResponse') !== false) {
switch ($_GET['type']) {
case 'downloadResponseLinux':
$fileName = 'ClientInstaller.run';
$generateClientApiPath = 'linuxgeneric';
break;
case 'downloadResponseMacOSX86':
$fileName = 'ClientInstaller.pkg';
$generateClientApiPath = 'macos-x86_64';
break;
case 'downloadResponseWindowsX86_32Zip':
$fileName = 'ClientInstaller(32-bit).zip';
$generateClientApiPath = 'windows-x86_32-zip';
break;
case 'downloadResponseWindowsX86_64Zip':
$fileName = 'ClientInstaller(64-bit).zip';
$generateClientApiPath = 'windows-x86_64-zip';
break;
case 'downloadResponseWindowsAnyCPUZip':
default:
$fileName = 'ClientInstaller(AnyCPU).zip';
$generateClientApiPath = 'windows-anycpu-zip';
}
header("Content-type:application/x-octet-stream");
header("Content-Disposition:attachment;filename=\"" . $fileName . "\"");
echo softwareDownload(
$params,
['SelfAddress' => getHost($params)],
'branding/generate-client/' . $generateClientApiPath
);
exit(); // Exit here to prevent any other data being added to the stream
// Handle regular client area page request
} else {
$userProfile = performAPIRequest(
$params,
['TargetUser' => getUsernameFromParams($params)],
'get-user-profile-and-hash'
);
if (array_key_exists('ProfileHash', $userProfile)) {
$getJobsForUser = performAPIRequest(
$params,
[
'Query' => json_encode([
"ClauseType" => "and",
"ClauseChildren" => [
[
"ClauseType" => "",
"RuleField" => "BackupJobDetail.Username",
"RuleOperator" => "str_eq",
"RuleValue" => getUsernameFromParams($params),
],
[
"ClauseType" => "",
"RuleField" => "BackupJobDetail.StartTime",
"RuleOperator" => "int_gt",
"RuleValue" => strval(strtotime("-2 week")),
]
]
])
],
'get-jobs-for-custom-search'
);
// Expand and format job details for human-readability
foreach ($getJobsForUser as $key => &$job) {
// Ignore jobs for removed items
if (!array_key_exists($job['SourceGUID'], $userProfile['Profile']['Sources'])) {
unset($getJobsForUser[$key]);
continue;
}
if (
!array_key_exists('Devices', $userProfile['Profile']) ||
!array_key_exists($job['DeviceID'], $userProfile['Profile']['Devices'])
) {
$job['DeviceName'] = 'Unknown';
} else {
$job['DeviceName'] = $userProfile['Profile']['Devices'][$job['DeviceID']]['FriendlyName'];
}
$job['SourceDescription'] = $userProfile['Profile']['Sources'][$job['SourceGUID']]['Description'];
$job['Status'] = formatStatusType($job['Status']);
$job['Classification'] = formatJobType($job['Classification']);
$job['TotalSize'] = formatBytes($job['TotalSize']);
$job['UploadSize'] = formatBytes($job['UploadSize']);
$job['DownloadSize'] = formatBytes($job['DownloadSize']);
$job['StartTime'] = date("Y-m-d h:i", $job['StartTime']);
}
// Calculate data usage across all protected items
$totalSize = 0;
foreach ($userProfile['Profile']['Sources'] as $source) {
$totalSize += $source['Statistics']['LastBackupJob']['TotalSize'];
}
$templateVars = [
'Username' => $userProfile['Profile']['Username'],
'AllProtectedItemsQuota' => ($userProfile['Profile']['AllProtectedItemsQuotaBytes'] / pow(1024, 3)), // Bytes / GiB
'MaximumDevices' => $userProfile['Profile']['MaximumDevices'],
'CreateTime' => date("Y-m-d h:i:sa", $userProfile['Profile']['CreateTime']),
'getJobsForUser' => $getJobsForUser,
'userProfile' => $userProfile,
'totalSize' => formatBytes($totalSize),
];
if (!empty($userProfile['Profile']['Destinations'])) {
$destination = array_values($userProfile['Profile']['Destinations'])[0];
if ($destination['StorageLimitEnabled'] === true) {
$templateVars['StorageVaultQuota'] = $destination['StorageLimitBytes'] / pow(1024, 3); // Bytes / GiB
}
} else {
$templateVars['StorageVaultQuota'] = false;
}
// Return template data
return [
'templatefile' => 'clientarea',
'vars' => $templateVars
];
} else if (array_key_exists('Status', $userProfile) && $userProfile['Status'] === 500 && array_key_exists('Message', $userProfile)) {
return (
'Error - please contact support: <span style="color:#A22;word-break:break-word;">' . $userProfile['Message'] . '</span><br>' .
'<span style="color:#A22;">Error data:</span> <span style="color:#CCC;word-break:break-word;">' .
base64_encode(
'TargetUser: ' .
var_export(getUsernameFromParams($params), true)
) .
'</span>'
);
} else {
return (
'Unknown error - please contact support. <br>' .
'<span style="color:#A22;">Error data:</span> <span style="color:#CCC;word-break:break-word;">' .
base64_encode(
var_export($userProfile, true) .
'TargetUser: ' . var_export(getUsernameFromParams($params), true)
) .
'</span>'
);
}
}
}
function cometbackup_TestConnection(array $params) {
$resp = performAPIRequest($params, [], 'meta/version');
if (array_key_exists('Version', $resp)) { // Expected Success Response
$success = 'Server connection test success.';
$error = false;
} else if (array_key_exists('Status', $resp) && array_key_exists('Message', $resp) && $resp['Status'] == 403) { // Failed Authentication Response
$success = false;
$error = $resp['Message'];
} else if (array_key_exists('curlerror', $resp)) { // Failed Connection Response
$success = false;
$error = $resp['curlerror'];
} else if (is_array($resp) && count($resp) === 0) { // No Valid Listener Response
$success = false;
$error = 'Empty response from server: No service listening on this port?';
} else if ($resp === NULL) { // Invalid Response
$success = false;
$error = 'Invalid response.';
} else { // Unknown Bad Response
$success = false;
$keys = array_keys($resp);
if (count($keys) === 1 && strlen($resp[$keys[0]]) > 0) {
$error = $resp[$keys[0]];
} else {
$error = 'Unknown error - please contact support: ' . base64_encode(var_export($resp, true));
}
}
return [
'success' => $success,
'error' => $error
];
}
function cometbackup_ChangePackage($params) {
return applyRestrictions($params);
}
function cometbackup_AdminSingleSignOn($params) {
$startSessionResult = performAPIRequest($params, [], 'account/session-start');
if (!empty($startSessionResult['SessionKey'])) {
$requiredParameters = base64_encode(json_encode([
'Server' => getHost($params),
'SessionKey' => $startSessionResult['SessionKey'],
'TargetUser' => $params['serverusername']
]));
return [
'success' => true,
'redirectTo' => '?CometSSO=' . $requiredParameters
];
} else {
return [
'success' => false,
'errorMsg' => (empty($startSessionResult['Message']) ? 'Login failed.' : $startSessionResult['Message'])
];
}
}