forked from plesk/api-php-lib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClient.php
534 lines (457 loc) · 13.8 KB
/
Client.php
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
<?php
// Copyright 1999-2022. Plesk International GmbH.
namespace PleskX\Api;
use SimpleXMLElement;
/**
* Client for Plesk XML-RPC API.
*/
class Client
{
public const RESPONSE_SHORT = 1;
public const RESPONSE_FULL = 2;
private string $host;
private int $port;
private string $protocol;
protected string $login = '';
private string $password = '';
private string $proxy = '';
private string $secretKey = '';
private string $version = '';
protected array $operatorsCache = [];
/**
* @var callable|null
*/
protected $verifyResponseCallback;
/**
* Create client.
*
* @param string $host
* @param int $port
* @param string $protocol
*/
public function __construct(string $host, int $port = 8443, string $protocol = 'https')
{
$this->host = $host;
$this->port = $port;
$this->protocol = $protocol;
}
/**
* Setup credentials for authentication.
*
* @param string $login
* @param string $password
*/
public function setCredentials(string $login, string $password): void
{
$this->login = $login;
$this->password = $password;
}
/**
* Define secret key for alternative authentication.
*
* @param string $secretKey
*/
public function setSecretKey(string $secretKey): void
{
$this->secretKey = $secretKey;
}
/**
* Set proxy server for requests.
*
* @param string $proxy
*/
public function setProxy(string $proxy): void
{
$this->proxy = $proxy;
}
/**
* Set default version for requests.
*
* @param string $version
*/
public function setVersion(string $version): void
{
$this->version = $version;
}
/**
* Set custom function to verify response of API call according your own needs.
* Default verifying will be used if it is not specified.
*
* @param callable|null $function
*/
public function setVerifyResponse(callable $function = null): void
{
$this->verifyResponseCallback = $function;
}
/**
* Retrieve host used for communication.
*
* @return string
*/
public function getHost(): string
{
return $this->host;
}
/**
* Retrieve port used for communication.
*
* @return int
*/
public function getPort(): int
{
return $this->port;
}
/**
* Retrieve name of the protocol (http or https) used for communication.
*
* @return string
*/
public function getProtocol(): string
{
return $this->protocol;
}
/**
* Retrieve XML template for packet.
*
* @param string|null $version
*
* @return SimpleXMLElement
*/
public function getPacket($version = null): SimpleXMLElement
{
$protocolVersion = !is_null($version) ? $version : $this->version;
$content = "<?xml version='1.0' encoding='UTF-8' ?>";
$content .= '<packet' . ('' === $protocolVersion ? '' : " version='$protocolVersion'") . '/>';
return new SimpleXMLElement($content);
}
/**
* Perform API request.
*
* @param string|array|SimpleXMLElement $request
* @param int $mode
*
* @return XmlResponse
* @throws \Exception
*/
public function request($request, int $mode = self::RESPONSE_SHORT): XmlResponse
{
if ($request instanceof SimpleXMLElement) {
$request = $request->asXml();
} else {
$xml = $this->getPacket();
if (is_array($request)) {
$request = $this->arrayToXml($request, $xml)->asXML();
} elseif (preg_match('/^[a-z]/', $request)) {
$request = $this->expandRequestShortSyntax($request, $xml);
}
}
if ('sdk' == $this->protocol) {
$version = ('' == $this->version) ? null : $this->version;
$requestXml = new SimpleXMLElement((string) $request);
/** @psalm-suppress UndefinedClass */
$xml = \pm_ApiRpc::getService($version)->call($requestXml->children()[0]->asXml(), $this->login);
} else {
$xml = $this->performHttpRequest((string) $request);
}
$this->verifyResponseCallback
? call_user_func($this->verifyResponseCallback, $xml)
: $this->verifyResponse($xml);
$result = (self::RESPONSE_FULL === $mode) ? $xml : $xml->xpath('//result')[0];
return new XmlResponse((string) $result->asXML());
}
/**
* Perform HTTP request to end-point.
*
* @param string $request
*
* @throws Client\Exception
*
* @return XmlResponse
*/
private function performHttpRequest($request)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "$this->protocol://$this->host:$this->port/enterprise/control/agent.php");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_HTTPHEADER, $this->getHeaders());
curl_setopt($curl, CURLOPT_POSTFIELDS, $request);
if ('' !== $this->proxy) {
curl_setopt($curl, CURLOPT_PROXY, $this->proxy);
}
$result = curl_exec($curl);
if (false === $result) {
throw new Client\Exception(curl_error($curl), curl_errno($curl));
}
curl_close($curl);
return new XmlResponse((string) $result);
}
/**
* Perform multiple API requests using single HTTP request.
*
* @param array $requests
* @param int $mode
*
* @throws Client\Exception
*
* @return array
*/
public function multiRequest(array $requests, $mode = self::RESPONSE_SHORT): array
{
$requestXml = $this->getPacket();
foreach ($requests as $request) {
if ($request instanceof SimpleXMLElement) {
throw new Client\Exception('SimpleXML type of request is not supported for multi requests.');
} else {
if (is_array($request)) {
$request = $this->arrayToXml($request, $requestXml)->asXML();
if (!$request) {
throw new Client\Exception('Failed to create an XML string for request');
}
} elseif (preg_match('/^[a-z]/', $request)) {
$this->expandRequestShortSyntax($request, $requestXml);
}
}
}
if ('sdk' == $this->protocol) {
throw new Client\Exception('Multi requests are not supported via SDK.');
} else {
$xmlString = $requestXml->asXML();
if (!$xmlString) {
throw new Client\Exception('Failed to create an XML string for request');
}
$responseXml = $this->performHttpRequest($xmlString);
}
$responses = [];
foreach ($responseXml->children() as $childNode) {
$xml = $this->getPacket();
$dom = dom_import_simplexml($xml)->ownerDocument;
if (!$dom) {
continue;
}
$childDomNode = dom_import_simplexml($childNode);
$childDomNode = $dom->importNode($childDomNode, true);
$dom->documentElement->appendChild($childDomNode);
$response = simplexml_load_string($dom->saveXML());
$responses[] = (self::RESPONSE_FULL == $mode) ? $response : $response->xpath('//result')[0];
}
return $responses;
}
/**
* Retrieve list of headers needed for request.
*
* @return array
*/
private function getHeaders()
{
$headers = [
'Content-Type: text/xml',
'HTTP_PRETTY_PRINT: TRUE',
];
if ($this->secretKey) {
$headers[] = "KEY: $this->secretKey";
} else {
$headers[] = "HTTP_AUTH_LOGIN: $this->login";
$headers[] = "HTTP_AUTH_PASSWD: $this->password";
}
return $headers;
}
/**
* Verify that response does not contain errors.
*
* @param XmlResponse $xml
*
* @throws Exception
*/
private function verifyResponse($xml): void
{
if ($xml->system && $xml->system->status && 'error' == (string) $xml->system->status) {
throw new Exception((string) $xml->system->errtext, (int) $xml->system->errcode);
}
if ($xml->xpath('//status[text()="error"]') && $xml->xpath('//errcode') && $xml->xpath('//errtext')) {
$errorCode = (int) $xml->xpath('//errcode')[0];
$errorMessage = (string) $xml->xpath('//errtext')[0];
throw new Exception($errorMessage, $errorCode);
}
}
/**
* Expand short syntax (some.method.call) into full XML representation.
*
* @param string $request
* @param SimpleXMLElement $xml
*
* @return false|string
*/
private function expandRequestShortSyntax($request, SimpleXMLElement $xml)
{
$parts = explode('.', $request);
$node = $xml;
$lastParts = end($parts);
foreach ($parts as $part) {
// phpcs:ignore
@list($name, $value) = explode('=', $part);
if ($part !== $lastParts) {
$node = $node->addChild($name);
} else {
$node->{$name} = (string) $value;
}
}
return $xml->asXML();
}
/**
* Convert array to XML representation.
*
* @param array $array
* @param SimpleXMLElement $xml
* @param string $parentEl
*
* @return SimpleXMLElement
*/
private function arrayToXml(array $array, SimpleXMLElement $xml, $parentEl = null)
{
foreach ($array as $key => $value) {
$el = is_int($key) && $parentEl ? $parentEl : $key;
if (is_array($value)) {
$this->arrayToXml($value, $this->isAssocArray($value) ? $xml->addChild($el) : $xml, $el);
} elseif (!isset($xml->{$el})) {
$xml->{$el} = (string) $value;
} else {
$xml->{$el}[] = (string) $value;
}
}
return $xml;
}
/**
* @param array $array
*
* @return bool
*/
private function isAssocArray(array $array)
{
return $array && array_keys($array) !== range(0, count($array) - 1);
}
/**
* @param string $name
*
* @return mixed
*/
private function getOperator(string $name)
{
if (!isset($this->operatorsCache[$name])) {
$className = '\\PleskX\\Api\\Operator\\' . $name;
/** @psalm-suppress InvalidStringClass */
$this->operatorsCache[$name] = new $className($this);
}
return $this->operatorsCache[$name];
}
public function server(): Operator\Server
{
return $this->getOperator('Server');
}
public function customer(): Operator\Customer
{
return $this->getOperator('Customer');
}
public function webspace(): Operator\Webspace
{
return $this->getOperator('Webspace');
}
public function subdomain(): Operator\Subdomain
{
return $this->getOperator('Subdomain');
}
public function dns(): Operator\Dns
{
return $this->getOperator('Dns');
}
public function dnsTemplate(): Operator\DnsTemplate
{
return $this->getOperator('DnsTemplate');
}
public function databaseServer(): Operator\DatabaseServer
{
return $this->getOperator('DatabaseServer');
}
public function mail(): Operator\Mail
{
return $this->getOperator('Mail');
}
public function certificate(): Operator\Certificate
{
return $this->getOperator('Certificate');
}
public function siteAlias(): Operator\SiteAlias
{
return $this->getOperator('SiteAlias');
}
public function ip(): Operator\Ip
{
return $this->getOperator('Ip');
}
public function eventLog(): Operator\EventLog
{
return $this->getOperator('EventLog');
}
public function secretKey(): Operator\SecretKey
{
return $this->getOperator('SecretKey');
}
public function ui(): Operator\Ui
{
return $this->getOperator('Ui');
}
public function servicePlan(): Operator\ServicePlan
{
return $this->getOperator('ServicePlan');
}
public function virtualDirectory(): Operator\VirtualDirectory
{
return $this->getOperator('VirtualDirectory');
}
public function database(): Operator\Database
{
return $this->getOperator('Database');
}
public function session(): Operator\Session
{
return $this->getOperator('Session');
}
public function locale(): Operator\Locale
{
return $this->getOperator('Locale');
}
public function logRotation(): Operator\LogRotation
{
return $this->getOperator('LogRotation');
}
public function protectedDirectory(): Operator\ProtectedDirectory
{
return $this->getOperator('ProtectedDirectory');
}
public function reseller(): Operator\Reseller
{
return $this->getOperator('Reseller');
}
public function resellerPlan(): Operator\ResellerPlan
{
return $this->getOperator('ResellerPlan');
}
public function aps(): Operator\Aps
{
return $this->getOperator('Aps');
}
public function servicePlanAddon(): Operator\ServicePlanAddon
{
return $this->getOperator('ServicePlanAddon');
}
public function site(): Operator\Site
{
return $this->getOperator('Site');
}
public function phpHandler(): Operator\PhpHandler
{
return $this->getOperator('PhpHandler');
}
}