Passed
Push — master ( dbe529...8b2e72 )
by Shaharia
01:35
created

Accounts::getDomains()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 35
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 25
nc 4
nop 0
dl 0
loc 35
rs 9.2088
c 0
b 0
f 0
1
<?php
2
3
namespace PreviewTechs\cPanelWHM\WHM;
4
5
use Http\Client\Exception;
6
use PreviewTechs\cPanelWHM\Entity\Account;
7
use PreviewTechs\cPanelWHM\Entity\Domain;
8
use PreviewTechs\cPanelWHM\Entity\DomainUser;
9
use PreviewTechs\cPanelWHM\Exceptions\ClientExceptions;
10
use PreviewTechs\cPanelWHM\WHMClient;
11
12
/**
13
 * Class Accounts
14
 *
15
 * @package PreviewTechs\cPanelWHM\WHM
16
 */
17
class Accounts
18
{
19
    /**
20
     *
21
     * @var WHMClient
22
     */
23
    protected $client;
24
25
    /**
26
     * Accounts constructor.
27
     *
28
     * @param WHMClient $client
29
     */
30
    public function __construct(WHMClient $client)
31
    {
32
        $this->client = $client;
33
    }
34
35
    /**
36
     * Search accounts from your WHM server.
37
     *
38
     * WHM API function: Accounts -> listaccts
39
     *
40
     * $accounts = new Accounts($c);
41
     * $keyword = "search_keyword";
42
     * $searchType = "username";   //valid search types are "domain", "owner", "user", "ip", "package"
43
     * $options = [
44
     *       'searchmethod' => "exact",   //"exact" or "regex",
45
     *       "page" => 1,
46
     *       "limit" => 10,   //per page,
47
     *       "want" => "username"    //A comma-separated list of fields you want to fetch
48
     *   ];
49
     *
50
     * try {
51
     *       $accounts->searchAccounts($keyword, $searchType, $options);
52
     *   } catch (\Http\Client\Exception $e) {
53
     *       echo $e->getMessage();
54
     *   } catch (\PreviewTechs\cPanelWHM\Exceptions\ClientExceptions $e) {
55
     *       echo $e->getMessage();
56
     *   }
57
     *
58
     * @link https://documentation.cpanel.net/display/DD/WHM+API+1+Functions+-+listaccts
59
     *
60
     * @param null $keyword
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $keyword is correct as it would always require null to be passed?
Loading history...
61
     * @param null $searchType
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $searchType is correct as it would always require null to be passed?
Loading history...
62
     * @param array $options
63
     *
64
     * @return array
65
     * @throws ClientExceptions
66
     * @throws Exception
67
     */
68
    public function searchAccounts($keyword = null, $searchType = null, array $options = [])
69
    {
70
        $limit = 10;
71
        $page = 1;
72
73
        $params = [
74
            'api.version' => 1,
75
            'api.chunk.enable' => 1,
76
            'api.chunk.size' => $limit,
77
            'api.chunk.start' => $page * $limit
78
        ];
79
80
        if (!empty($options['limit'])) {
81
            $params['api.chunk.size'] = intval($options['limit']);
82
        }
83
84
        if (!empty($options['page'])) {
85
            $params['api.chunk.start'] = intval($options['page']) * $params['api.chunk.size'];
86
        }
87
88
        if (!empty($searchType) && !in_array($searchType, ["domain", "owner", "user", "ip", "package"])) {
89
            throw new \InvalidArgumentException("`searchType` must be one of these - domain, owner, user, ip, package");
90
        }
91
92
        if (!empty($options['searchmethod']) && !in_array($options['searchmethod'], ["exact", "regex"])) {
93
            throw new \InvalidArgumentException("options[searchmethod] must be either `regex` or `exact`");
94
        }
95
96
        if (!empty($options['want'])) {
97
            $params['want'] = $options['want'];
98
        }
99
100
        if (!empty($searchType)) {
101
            $params['searchtype'] = $searchType;
102
        }
103
104
        if (!empty($keyword)) {
105
            $params['search'] = $keyword;
106
            empty($searchType) ? $params['searchtype'] = "user" : null;
107
        }
108
109
        $results = $this->client->sendRequest("/json-api/listaccts", "GET", $params);
110
        if (empty($results['data']['acct'])) {
111
            return [];
112
        }
113
114
        $accounts = [];
115
        foreach ($results['data']['acct'] as $account) {
116
            $accounts[] = Account::buildFromArray($account);
117
        }
118
119
        return [
120
            'accounts' => $accounts,
121
            'count' => $params['api.chunk.size'],
122
            'page' => $page
123
        ];
124
    }
125
126
    /**
127
     * Get an account details
128
     *
129
     * WHM API function: Accounts -> accountsummary
130
     *
131
     * @link https://documentation.cpanel.net/display/DD/WHM+API+1+Functions+-+accountsummary
132
     *
133
     * @param null $user
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $user is correct as it would always require null to be passed?
Loading history...
134
     * @param null $domain
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $domain is correct as it would always require null to be passed?
Loading history...
135
     *
136
     * @return null|Account
137
     * @throws ClientExceptions
138
     * @throws Exception
139
     */
140
    public function getDetails($user = null, $domain = null)
141
    {
142
        if (empty($user) && empty($domain)) {
143
            throw ClientExceptions::invalidArgument("You must provide either a username or a domain or both");
144
        }
145
146
        if (!empty($user) && !empty($domain)) {
147
            throw ClientExceptions::invalidArgument(
148
                "You must provide only one argument either user OR domain (not both)"
149
            );
150
        }
151
152
        $params = [];
153
154
        if (!empty($user)) {
155
            $params['user'] = $user;
156
        }
157
158
        if (!empty($domain)) {
159
            $params['domain'] = $domain;
160
        }
161
162
        $result = $this->client->sendRequest("/json-api/accountsummary", "GET", $params);
163
        if (empty($result)) {
164
            return null;
165
        }
166
167
        if ($result['status'] === 0) {
168
            throw ClientExceptions::recordNotFound(
169
                !empty($result['statusmsg']) ? $result['statusmsg'] : "Record not found"
170
            );
171
        }
172
173
        if (!empty($result['acct']) && is_array($result['acct'])) {
174
            return Account::buildFromArray($result['acct'][0]);
175
        }
176
177
        return null;
178
    }
179
180
    /**
181
     * This function lists available WHM API 1 functions.
182
     *
183
     * This function only lists the functions that are available to the current user.
184
     * For example, if the authenticated user is a reseller without root -level privileges,
185
     * the function will not list WHM API 1 functions that require root privileges.
186
     *
187
     * WHM API function: Accounts -> applist
188
     *
189
     * @link https://documentation.cpanel.net/display/DD/WHM+API+1+Functions+-+applist
190
     *
191
     * @return array
192
     * @throws ClientExceptions
193
     * @throws Exception
194
     */
195
    public function availableFunctions()
196
    {
197
        $result = $this->client->sendRequest("/json-api/applist", 'GET', []);
198
199
        if (!empty($result['app']) && sizeof($result['app']) > 0) {
200
            return $result['app'];
201
        }
202
203
        return [];
204
    }
205
206
    /**
207
     * Create a new account. This function creates a cPanel account.
208
     * The function also sets up the new account's domain information.
209
     *
210
     * WHM API function: Accounts -> createacct
211
     *
212
     * @link    https://documentation.cpanel.net/display/DD/WHM+API+1+Functions+-+createacct
213
     *
214
     * @param Account $account
215
     * @param array $options
216
     * @return array
217
     * @throws ClientExceptions
218
     * @throws Exception
219
     */
220
    public function create(Account $account, array $options = [])
221
    {
222
        if (empty($account->getUser())) {
223
            throw ClientExceptions::invalidArgument("You must provide an username to create new account");
224
        }
225
226
        if (empty($account->getDomain())) {
227
            throw ClientExceptions::invalidArgument("You must provide a domain to create new account");
228
        }
229
230
        $params = [];
231
        $params['username'] = $account->getUser();
232
        $params['domain'] = $account->getDomain();
233
        !empty($account->getPlanName()) ? $params['plan'] = $account->getPlanName() : null;
234
        !empty($options['pkgname']) ? $params['pkgname'] = $options['pkgname'] : null;
235
        if (!empty($options['savepkg'])) {
236
            if (!in_array(intval($options['savepkg']), [0, 1])) {
237
                throw new ClientExceptions("`savepkg` must be either 0 or 1");
238
            }
239
240
            $params['savepkg'] = $options['savepkg'];
241
        }
242
243
        !empty($options['featurelist']) ? $params['featurelist'] = $options['featurelist'] : null;
244
        if (!empty($account->getDiskLimit())) {
245
            if ($account->getDiskLimit() === -1) {
246
                $params['quota'] = 0;
247
            } else {
248
                $params['quota'] = intval($account->getDiskLimit());
249
            }
250
        }
251
252
        !empty($account->getPassword()) ? $params['password'] = $account->getPassword() : null;
253
        !empty($account->getIpAddress()) ? $params['ip'] = $account->getIpAddress() : null;
254
        !empty($account->isCgiEnable()) ? $params['cgi'] = (int)$account->isCgiEnable() : null;
255
        !empty($account->isSpamAssassinEnable()) ?
256
            $params['spamassassin'] = (int)$account->isSpamAssassinEnable()
257
            : null;
258
        !empty($account->isFrontPageEnable()) ? $params['frontpage'] = (int)$account->isFrontPageEnable() : null;
259
        !empty($account->getShell()) ? $params['hasshell'] = 1 : null;
260
        !empty($account->getEmail()) ? $params['contactemail'] = 1 : null;
261
        !empty($account->getEmail()) ? $params['contactemail'] = 1 : null;
262
        !empty($account->getTheme()) ? $params['cpmod'] = 1 : null;
263
264
        if ($account->getMaxFTP() === -1) {
265
            $params['maxftp'] = "unlimited";
266
        } elseif ($account->getMaxFTP() > 0) {
267
            $params['maxftp'] = intval($account->getMaxFTP());
268
        }
269
270
        if ($account->getMaxSQL() === -1) {
271
            $params['maxsql'] = "unlimited";
272
        } elseif ($account->getMaxSQL() > 0) {
273
            $params['maxsql'] = intval($account->getMaxSQL());
274
        }
275
276
        if ($account->getMaxPOP() === -1) {
277
            $params['maxpop'] = "unlimited";
278
        } elseif ($account->getMaxPOP() > 0) {
279
            $params['maxpop'] = intval($account->getMaxPOP());
280
        }
281
282
        if ($account->getMaxMailingList() === -1) {
283
            $params['maxlst'] = "unlimited";
284
        } elseif ($account->getMaxMailingList() > 0) {
285
            $params['maxlst'] = intval($account->getMaxMailingList());
286
        }
287
288
        if ($account->getMaxSubDomain() === -1) {
289
            $params['maxsub'] = "unlimited";
290
        } elseif ($account->getMaxSubDomain() > 0) {
291
            $params['maxsub'] = intval($account->getMaxSubDomain());
292
        }
293
294
        if ($account->getMaxParkedDomains() === -1) {
295
            $params['maxpark'] = "unlimited";
296
        } elseif ($account->getMaxParkedDomains() > 0) {
297
            $params['maxpark'] = intval($account->getMaxParkedDomains());
298
        }
299
300
        if ($account->getMaxAddonDomains() === -1) {
301
            $params['maxaddon'] = "unlimited";
302
        } elseif ($account->getMaxAddonDomains() > 0) {
303
            $params['maxaddon'] = intval($account->getMaxAddonDomains());
304
        }
305
306
        if ($account->getBandwidthLimit() === -1) {
307
            $params['bwlimit'] = "unlimited";
308
        } elseif ($account->getBandwidthLimit() > 0) {
309
            $params['bwlimit'] = intval($account->getBandwidthLimit());
310
        }
311
312
        !empty($options['customip']) ? $params['customip'] = $options['customip'] : null;
313
314
        !empty($account->getLanguagePreference()) ? $params['language'] = $account->getLanguagePreference() : null;
315
316
        !empty($options['useregns']) ? $params['useregns'] = $options['useregns'] : null;
317
        !empty($options['reseller']) ? $params['reseller'] = (int)$options['reseller'] : null;
318
        !empty($options['forcedns']) ? $params['forcedns'] = (int)$options['forcedns'] : null;
319
320
        !empty($account->getMailboxFormat()) ? $params['mailbox_format'] = $account->getMailboxFormat() : null;
321
322
        if (!empty($options['mxcheck'])) {
323
            if (!in_array($options['mxcheck'], ['local', 'secondary', 'remote', 'auto'])) {
324
                throw new ClientExceptions("options[mxcheck] parameters must be one of local, secondary, remote, auto");
325
            }
326
327
            $params['mxcheck'] = $options['mxcheck'];
328
        }
329
330
        if ($account->getMaxEmailPerHour() === -1) {
331
            $params['max_email_per_hour'] = "unlimited";
332
        } elseif ($account->getMaxEmailPerHour() > 0) {
333
            $params['max_email_per_hour'] = intval($account->getMaxEmailPerHour());
334
        }
335
336
        if ($account->getMaxEmailAccountQuota() === -1) {
337
            $params['max_emailacct_quota'] = "unlimited";
338
        } elseif ($account->getMaxEmailAccountQuota() > 0) {
339
            $params['max_email_per_hour'] = intval($account->getMaxEmailAccountQuota());
340
        }
341
342
        if ($account->getMaxDeferFailMailPercentage() === -1) {
343
            $params['max_defer_fail_percentage'] = "unlimited";
344
        } elseif ($account->getMaxDeferFailMailPercentage() > 0) {
345
            $params['max_defer_fail_percentage'] = intval($account->getMaxDeferFailMailPercentage());
346
        }
347
348
        !empty($account->getUid()) ? $params['uid'] = $account->getUid() : null;
349
        !empty($account->getPartition()) ? $params['homedir'] = $account->getPartition() : null;
350
        !empty($options['dkim']) ? $params['dkim'] = intval($options['dkim']) : null;
351
        !empty($options['spf']) ? $params['spf'] = intval($options['spf']) : null;
352
        !empty($account->getOwner()) ? $params['owner'] = $account->getOwner() : null;
353
354
        $result = $this->client->sendRequest("/json-api/createacct", "GET", $params);
355
356
        if (!empty($result) && !empty($result['result'][0]) && $result['result'][0]['status'] === 0) {
357
            throw new ClientExceptions($result['result'][0]['statusmsg']);
358
        }
359
360
        if (!empty($result) && !empty($result['result'][0]) && $result['result'][0]['status'] === 1) {
361
            return ['result' => $result['result'][0]['options'], 'raw_output' => $result['result'][0]['rawout']];
362
        }
363
364
        return [];
365
    }
366
367
    /**
368
     * This function retrieves domain data.
369
     *
370
     * WHM API function: Accounts -> domainuserdata
371
     *
372
     * @link https://documentation.cpanel.net/display/DD/WHM+API+1+Functions+-+domainuserdata
373
     * @param $domain
374
     * @return null|DomainUser
375
     * @throws ClientExceptions
376
     * @throws Exception
377
     */
378
    public function domainDetails($domain)
379
    {
380
        $params = ['domain' => $domain];
381
382
        $result = $this->client->sendRequest("/json-api/domainuserdata", "GET", $params);
383
        if(empty($result)){
384
            return null;
385
        }
386
387
        if($result['result'][0]['status'] === 0){
388
            throw new ClientExceptions($result['result'][0]['statusmsg']);
389
        }
390
391
        $userData = $result['userdata'];
392
        $domainUser = new DomainUser();
393
        $domainUser->setHasCGI((bool) $userData['hascgi']);
394
        $domainUser->setServerName($userData['servername']);
395
        $domainUser->setOwner($userData['owner']);
396
        $domainUser->setScriptAlias($userData['scriptalias']);
397
        $domainUser->setHomeDirectory($userData['homedir']);
398
        $domainUser->setCustomLog($userData['customlog']);
399
        $domainUser->setUser($userData['user']);
400
        $domainUser->setGroup($userData['group']);
401
        $domainUser->setIpAddress($userData['ip']);
402
        $domainUser->setPort($userData['port']);
403
        $domainUser->setPhpOpenBaseDirectoryProtect((bool) $userData['phpopenbasedirprotect']);
404
405
        if($userData['usecanonicalname'] === "Off"){
406
            $domainUser->setUseCanonicalName(false);
407
        }elseif($userData['usecanonicalname'] === "On"){
408
            $domainUser->setUseCanonicalName(true);
409
        }
410
411
        $domainUser->setServerAdmin($userData['serveradmin']);
412
        $domainUser->setServerAlias($userData['serveralias']);
413
        $domainUser->setDocumentRoot($userData['documentroot']);
414
415
        return $domainUser;
416
    }
417
418
    /**
419
     * This function modifies a user's disk quota.
420
     * WHM API function: Accounts -> editquota
421
     * @link https://documentation.cpanel.net/display/DD/WHM+API+1+Functions+-+editquota
422
     *
423
     * @param $username
424
     * @param $newQuota
425
     * @return bool
426
     * @throws ClientExceptions
427
     * @throws Exception
428
     */
429
    public function changeDiskSpaceQuota($username, $newQuota)
430
    {
431
        $params = ['user' => $username, 'quota' => $newQuota];
432
433
        $this->client->sendRequest("/json-api/editquota", "GET", $params);
434
        return true;
435
    }
436
437
    /**
438
     * This function forces a user to change the account password after the next login attempt.
439
     *
440
     * WHM API function: Accounts -> forcepasswordchange
441
     *
442
     * @link https://documentation.cpanel.net/display/DD/WHM+API+1+Functions+-+forcepasswordchange
443
     *
444
     * @param array $usernames
445
     * @param int $stopOnFail
446
     * @return null
447
     * @throws ClientExceptions
448
     * @throws Exception
449
     */
450
    public function forcePasswordChange(array $usernames, $stopOnFail = 1)
451
    {
452
        $params = [
453
            "stop_on_failure" => $stopOnFail
454
        ];
455
456
        $usersJson = [];
457
        foreach ($usernames as $username){
458
            $usersJson[$username] = 1;
459
        }
460
461
        $params['users_json'] = json_encode($usersJson);
462
463
        $result = $this->client->sendRequest("/json-api/forcepasswordchange", "GET", $params);
464
        if($result['metadata']['result'] === 0){
465
            throw new ClientExceptions($result['metadata']['reason']);
466
        }
467
468
        if(!empty($result['data'])){
469
            return $result['updated'];
470
        }
471
472
        return null;
473
    }
474
475
    /**
476
     * This function returns information about each domain on the server.
477
     *
478
     * WHM API function: Accounts -> get_domain_info
479
     * @link https://documentation.cpanel.net/display/DD/WHM+API+1+Functions+-+get_domain_info
480
     *
481
     * @return Domain[]|null
482
     * @throws ClientExceptions
483
     * @throws Exception
484
     */
485
    public function getDomains()
486
    {
487
        $params = [];
488
        $result = $this->client->sendRequest("/json-api/get_domain_info", "GET", $params);
489
490
        if(empty($result)){
491
            return null;
492
        }
493
494
        if(!empty($result['metadata']) && $result['metadata']['result'] === 1){
495
            $domains = $result['data']['domains'];
496
497
            $domainList = [];
498
            foreach ($domains as $domain){
499
                $do = new Domain();
500
                $do->setPort(intval($domain['port']));
501
                $do->setUser($domain['user']);
502
                $do->setDomain($domain['domain']);
503
                $do->setIpv4SSL($domain['ipv4_ssl']);
504
                $do->setIpv6($domain['ipv6']);
505
                $do->setSslPort(intval($domain['port_ssl']));
506
                $do->setPhpVersion($domain['php_version']);
507
                $do->setUserOwner($domain['user_owner']);
508
                $do->setDomainType($domain['domain_type']);
509
                $do->setIpv6IsDedicated((bool) $domain['ipv6_is_dedicated']);
510
                $do->setIpv4($domain['ipv4']);
511
                $do->setModSecurityEnabled((bool) $domain['modsecurity_enabled']);
512
                $do->setDocRoot($domain['docroot']);
513
                $domainList[] = $do;
514
            }
515
516
            return $domainList;
517
        }
518
519
        return null;
520
    }
521
}
522