Test Failed
Branch master (d789d7)
by Joe
02:33
created

Cloudlinux::__construct()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 18
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 8.8571
c 0
b 0
f 0
cc 6
eloc 15
nc 8
nop 3
1
<?php
2
/**
3
 * Cloudlinux Functionality
4
 *
5
 * API Documentation at: .. ill fill this in later from forum posts
6
 *
7
 * Last Changed: $LastChangedDate: 2017-05-26 04:36:01 -0400 (Fri, 26 May 2017) $
8
 * @author detain
9
 * @version $Revision: 24803 $
10
 * @copyright 2017
11
 * @package MyAdmin
12
 * @category Licenses
13
 */
14
15
namespace Detain\Cloudlinux;
16
17
/**
18
 * Cloudlinux Licensing Class
19
 *
20
 * XMLRPC Exception codes:
21
 * 	1 ­ Internal (unknown) Error
22
 * 	10 ­ Not authorized
23
 * 	30 ­ Invalid call arguments
24
 * 	40 ­ Invalid IP format
25
 *
26
 * @link https://cln.cloudlinux.com/clweb/downloads/cloudlinux-xmlrpc-api.pdf XML API Documentation
27
 * @link https://cln.cloudlinux.com/clweb/downloads/cloudlinux-rest-api.pdf REST API Documentation
28
 *
29
 * @access public
30
 */
31
class Cloudlinux
32
{
33
	private $login = '';
34
	private $key = '';
35
	public $prefix = 'registration.';
36
	public $encoding = 'utf-8'; // utf-8 / UTF-8
37
	public $apiType = 'rest';
38
	public $sslverify = false;
39
	public $xmlOptions = [];
40
	public $xmlUrl = 'https://cln.cloudlinux.com/clweb/xmlrpc';
41
	public $restUrl = 'https://cln.cloudlinux.com/api/';
42
	public $restOptions = [];
43
	/**
44
	 * @var \XML_RPC2_Client
45
	 */
46
	public $xmlClient;
47
	public $response;
48
49
	/**
50
	 * Cloudlinux::__construct()
51
	 *
52
	 * @param string $login API Login Name
53
	 * @param string $key API Key
54
	 * @param string $apiType API type to use, can be 'rest' or 'xml'
55
	 */
56
	public function __construct($login, $key, $apiType = 'rest') {
0 ignored issues
show
Coding Style introduced by
__construct uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
57
		$this->login = $login;
58
		$this->key = $key;
59
		$this->apiType = $apiType;
60
		$limitType = false;
61
		if (!isset($GLOBALS['HTTP_RAW_POST_DATA']))
62
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents('php://input');
63
		if (!$limitType || $this->apiType == 'xml') {
64
			include_once('XML/RPC2/Client.php');
65
			$this->xmlOptions['prefix'] = $this->prefix;
66
			$this->xmlOptions['encoding'] = $this->encoding;
67
			$this->xmlOptions['sslverify'] = $this->sslverify;
68
			$this->xmlClient = \XML_RPC2_Client::create($this->xmlUrl, $this->xmlOptions);
69
		}
70
		if (!$limitType || $this->apiType == 'rest') {
71
			$this->restOptions[CURLOPT_SSL_VERIFYHOST] = $this->sslverify;
72
		}
73
	}
74
75
	/**
76
	 * getcurlpage()
77
	 * gets a webpage via curl and returns the response.
78
	 * also it sets a mozilla type agent.
79
	 * @param string $url        the url of the page you want
80
	 * @param string $postfields postfields in the format of "v1=10&v2=20&v3=30"
81
	 * @param string|array $options
82
	 * @return string the webpage
83
	 */
84
	public function getcurlpage($url, $postfields = '', $options = '') {
85
		//myadmin_log('myadmin', 'info', "Get Url Page $url", __LINE__, __FILE__);
0 ignored issues
show
Unused Code Comprehensibility introduced by
71% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
86
		$agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2790.0 Safari/537.36';
87
		$curl = curl_init($url);
88
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
89
		curl_setopt($curl, CURLOPT_USERAGENT, $agent);
90
		if (is_array($postfields) || $postfields != '') {
91
			if (is_array($postfields)) {
92
				$postdata = [];
93
				foreach ($postfields as $field => $value) {
94
					$postdata[] = $field . '=' . urlencode($value);
95
				}
96
				curl_setopt($curl, CURLOPT_POSTFIELDS, implode('&', $postdata));
97
			} else {
98
				curl_setopt($curl, CURLOPT_POSTFIELDS, $postfields);
99
			}
100
		}
101
		if (is_array($options) && sizeof($options) > 0) {
102
			foreach ($options as $key => $value) {
103
				curl_setopt($curl, $key, $value);
104
			}
105
		}
106
		$tmp = curl_exec($curl);
107
		curl_close($curl);
108
		$ret = $tmp;
109
		return $ret;
110
	}
111
112
	public function log($level, $text, $line = '', $file = '') {
113
		if (function_exists('myadmin_log'))
114
			myadmin_log('cloudlinux', $level, $text, $line, $file);
115
		else
116
			error_log($text);
117
	}
118
119
	/**
120
	 * Return system information about several Cloudlinux services
121
	 *
122
	 * @return array array of system information
123
	 */
124
	public function status() {
125
		$this->response = $this->getcurlpage($this->restUrl.'status.json', '', $this->restOptions);
126
		return json_decode($this->response, true);
127
	}
128
129
	/**
130
	 * Will return information about what kind of license types are available for registration and what types are already used by current account.
131
	 * @param string $ipAddress ip address to check
132
	 * @return array returns an array with  available(int[]) ­ list of types that can be used to register new IP license, and owned(int[]) ­ list of types that already registered(owned) by this account
133
	 */
134
	public function availability($ipAddress) {
135
		$this->response = $this->getcurlpage($this->restUrl.'ipl/availability.json?ip='.$ipAddress.'&token='.$this->authToken(), '', $this->restOptions);
136
		return json_decode($this->response, true);
137
	}
138
139
	/**
140
	 * Check if IP license is registered by any customer.
141
	 *
142
	 * @param string $ipAddress ip address to check
143
	 * @return false|array Will return list of registered license types or empty list if provided IP is not registered yet.
144
	 */
145
	public function check($ipAddress) {
146
		$this->response = $this->getcurlpage($this->restUrl.'ipl/check.json?ip='.$ipAddress.'&token='.$this->authToken(), '', $this->restOptions);
147
		$response = json_decode($this->response, true);
148
		if ($response['success'] == 1)
149
			return $response['data'];
150
		else
151
			return false;
152
	}
153
154
	/**
155
	 * Will register IP based license for authorized user.
156
	 *
157
	 * @param string $ipAddress ip address to registger
158
	 * @param int $type IP license type (1,2 or 16)
159
	 * @return array On success response returns information about created or already registered license.   ip(string)    type(int) ­ license type (1,2,16)   registered(boolean) ­ true if server was registered in CLN with this license (CLN licenses only).     created(string) ­ license creation time
160
	 */
161
	public function register($ipAddress, $type) {
162
		$this->response = $this->getcurlpage($this->restUrl.'ipl/register.json?ip='.$ipAddress.'&type='.$type.'&token='.$this->authToken(), '', $this->restOptions);
163
		return json_decode($this->response, true);
164
	}
165
166
	/**
167
	 * Will remove IP based license from authorized user licenses.
168
	 *
169
	 * @param string $ipAddress ip address to remove licenses on
170
	 * @param int $type optional license type. If empty, will remove licenses with all types
171
	 * @return bool
172
	 */
173
	public function restRemove($ipAddress, $type = 0) {
174
		if ($type != 0)
175
			$this->response = $this->getcurlpage($this->restUrl.'ipl/remove.json?ip='.$ipAddress.'&type='.$type.'&token='.$this->authToken(), '', $this->restOptions);
176
		else
177
			$this->response = $this->getcurlpage($this->restUrl.'ipl/remove.json?ip='.$ipAddress.'&token='.$this->authToken(), '', $this->restOptions);
178
		return json_decode($this->response, true);
179
	}
180
181
	/**
182
	 * Will remove IP based license from authorized user licenses.
183
	 *
184
	 * @param string $ipAddress ip address to remove licenses on
185
	 * @param int $type optional license type. If empty or 0, will remove licenses with all types
186
	 * @return bool
187
	 */
188
	public function remove($ipAddress, $type = 0) {
189
		if ($this->apiType == 'xml')
190
			return $this->removeLicense($ipAddress, $type);
191
		else
192
			return $this->restRemove($ipAddress, $type);
193
	}
194
195
	/**
196
	 * Return all IP licenses owned by authorized user.
197
	 *
198
	 * @return array an array of licenses each one containing these fields: ip(string)   ype(int) ­ license type (1,2,16)   registered(boolean) ­ true if server was registered in CLN with this license (CLN licenses only).    created(string) ­ license creation time
199
	 */
200
	public function restList() {
201
		$this->response = $this->getcurlpage($this->restUrl.'ipl/list.json?token='.$this->authToken(), '', $this->restOptions);
202
		return json_decode($this->response, true);
203
	}
204
205
	/**
206
	 * automatic authToken generator
207
	 *
208
	 * @return false|string the authToken
209
	 */
210
	public function authToken() {
211
		$time = time();
212
		try {
213
			return $this->login . '|' . $time . '|' . sha1($this->key . $time);
214
		} catch (\Exception $e) {
215
			$this->log('error', 'Caught exception code: ' . $e->getCode());
216
			$this->log('error', 'Caught exception message: ' . $e->getMessage());
217
			return false;
218
		}
219
	}
220
221
	/**
222
	 * Register new IP license.
223
	 *
224
	 * @param string $ipAddress IP Address
225
	 * @param integer $type license type (1,2 or 16)
226
	 * @throws XmlRpcException for critical errors
227
	 * @return false|integer 0 on success, -1 on error
228
	 */
229
	public function license($ipAddress, $type) {
230
		$type = (int)$type;
231
		try {
232
			$this->log('error', 'Calling License(' . $this->authToken() . ',' . $ipAddress . ',' . $type . ')');
233
			$this->response = $this->xmlClient->license($this->authToken(), $ipAddress, $type);
234
			$this->log('error', 'Response: ' . var_export($this->response, true));
235
			return $this->response;
236
		} catch (\Exception $e) {
237
			$this->log('error', 'Caught exception code: ' . $e->getCode());
238
			$this->log('error', 'Caught exception message: ' . $e->getMessage());
239
			return false;
240
		}
241
	}
242
243
	/**
244
	 * Remove IP licenses with specified type for customer. Also un­registers from CLN server associated with IP.
245
	 * or
246
	 * Remove IP licenses with specified type for customer. Also un­registers from CLN server associated with IP.
247
	 * @param string         $ipAddress   ip address to remove
248
	 * @param int $type optional parameter to specify the type of license to remove (1,2, or 16) or 0 for all
249
	 * @return false|integer 0 on success, -1 on error, Error will be returned also if account have no licenses for provided IP.
0 ignored issues
show
Documentation introduced by
Should the return type not be boolean?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
250
	 */
251
	public function removeLicense($ipAddress, $type = 0) {
252
		$this->log('info', "Calling CLoudLinux->xmlClient->removeLicense({$this->authToken()}, {$ipAddress}, {$type})", __LINE__, __FILE__);
253
		try {
254
			return $this->response = $this->remove($ipAddress, $type);
255
		} catch (\Exception $e) {
256
			$this->log('error', 'Caught exception code: ' . $e->getCode());
257
			$this->log('error', 'Caught exception message: ' . $e->getMessage());
258
			return false;
259
		}
260
	}
261
262
	/**
263
	 * Check if IP license was registered by any customer. Arguments:
264
	 *
265
	 * @param string $ipAddress ip address to remove
266
	 * @param bool $checkAll True will search for any type of license. False ­ only for types 1 or 2
267
	 * @throws XmlRpcException for critical errors
268
	 * @return array (list<int>): List of registered license types or empty list if no license found
0 ignored issues
show
Documentation introduced by
Should the return type not be false|array?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
269
	 */
270
	public function isLicensed($ipAddress, $checkAll = true) {
271
		if ($this->apiType == 'xml')
272
			return $this->xmlIsLicensed($ipAddress, $checkAll);
273
		else
274
			return $this->check($ipAddress);
275
	}
276
	/**
277
	 * Check if IP license was registered by any customer. Arguments:
278
	 *
279
	 * @param string $ipAddress ip address to remove
280
	 * @param bool $checkAll True will search for any type of license. False ­ only for types 1 or 2
281
	 * @throws XmlRpcException for critical errors
282
	 * @return false|array (list<int>): List of registered license types or empty list if no license found
283
	 */
284 View Code Duplication
	public function xmlIsLicensed($ipAddress, $checkAll = true) {
1 ignored issue
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
285
		try {
286
			return $this->response = $this->xmlClient->isLicensed($this->authToken(), $ipAddress, $checkAll);
287
		} catch (\Exception $e) {
288
			$this->log('error', 'Caught exception code: ' . $e->getCode());
289
			$this->log('error', 'Caught exception message: ' . $e->getMessage());
290
			return false;
291
		}
292
	}
293
294
	/**
295
	 * @return false|array
296
	 */
297
	public function licenseList() {
298
		try {
299
			return json_decode($this->getcurlpage($this->restUrl.'ipl/list.json?token=' . $this->authToken()));
300
		} catch (\Exception $e) {
301
			$this->log('error', 'Caught exception code: ' . $e->getCode());
302
			$this->log('error', 'Caught exception message: ' . $e->getMessage());
303
			return false;
304
		}
305
	}
306
307
	/**
308
	 * Return list of all IP licenses owned by authorized user
309
	 *
310
	 * @throws XmlRpcException for critical errors
311
	 * @return false|array (list<structure>): List of structures or empty list. Each structure contains keys:
312
	 * 	IP(string)
313
	 * 	TYPE(int) ­ license type
314
	 * 	REGISTERED(boolean) ­ True if server was registered in CLN with this license
315
	 */
316 View Code Duplication
	public function reconcile() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
317
		try {
318
			return $this->response = $this->xmlClient->reconcile($this->authToken());
319
		} catch (\Exception $e) {
320
			$this->log('error', 'Caught exception code: ' . $e->getCode());
321
			$this->log('error', 'Caught exception message: ' . $e->getMessage());
322
			return false;
323
		}
324
	}
325
}
326
327