Passed
Push — master ( d789d7...5ab264 )
by Joe
02:33
created

Cloudlinux::removeLicense()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 0
cts 7
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 8
nc 2
nop 2
crap 6
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 1
	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 1
		$this->login = $login;
58 1
		$this->key = $key;
59 1
		$this->apiType = $apiType;
60 1
		$limitType = false;
61 1
		if (!isset($GLOBALS['HTTP_RAW_POST_DATA']))
62 1
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents('php://input');
63 1
		if (!$limitType || $this->apiType == 'xml') {
64 1
			include_once('XML/RPC2/Client.php');
65 1
			$this->xmlOptions['prefix'] = $this->prefix;
66 1
			$this->xmlOptions['encoding'] = $this->encoding;
67 1
			$this->xmlOptions['sslverify'] = $this->sslverify;
68 1
			$this->xmlClient = \XML_RPC2_Client::create($this->xmlUrl, $this->xmlOptions);
69
		}
70 1
		if (!$limitType || $this->apiType == 'rest') {
71 1
			$this->restOptions[CURLOPT_SSL_VERIFYHOST] = $this->sslverify;
72
		}
73 1
	}
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 1
	public function getcurlpage($url, $postfields = '', $options = '') {
85 1
		$agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2790.0 Safari/537.36';
86 1
		$curl = curl_init($url);
87 1
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
88 1
		curl_setopt($curl, CURLOPT_USERAGENT, $agent);
89 1
		if (is_array($postfields) || $postfields != '') {
90
			if (is_array($postfields)) {
91
				$postdata = [];
92
				foreach ($postfields as $field => $value) {
93
					$postdata[] = $field . '=' . urlencode($value);
94
				}
95
				curl_setopt($curl, CURLOPT_POSTFIELDS, implode('&', $postdata));
96
			} else {
97
				curl_setopt($curl, CURLOPT_POSTFIELDS, $postfields);
98
			}
99
		}
100 1
		if (is_array($options) && sizeof($options) > 0) {
101
			foreach ($options as $key => $value) {
102
				curl_setopt($curl, $key, $value);
103
			}
104
		}
105 1
		$tmp = curl_exec($curl);
106 1
		curl_close($curl);
107 1
		$ret = $tmp;
108 1
		return $ret;
109
	}
110
111
	public function log($level, $text, $line = '', $file = '') {
112
		if (function_exists('myadmin_log'))
113
			myadmin_log('cloudlinux', $level, $text, $line, $file);
114
		else
115
			error_log($text);
116
	}
117
118
	/**
119
	 * Return system information about several Cloudlinux services
120
	 *
121
	 * @return array array of system information
122
	 */
123 1
	public function status() {
124 1
		$this->response = $this->getcurlpage($this->restUrl.'status.json', '', $this->restOptions);
125 1
		return json_decode($this->response, true);
126
	}
127
128
	/**
129
	 * Will return information about what kind of license types are available for registration and what types are already used by current account.
130
	 * @param string $ipAddress ip address to check
131
	 * @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
132
	 */
133
	public function availability($ipAddress) {
134
		$this->response = $this->getcurlpage($this->restUrl.'ipl/availability.json?ip='.$ipAddress.'&token='.$this->authToken(), '', $this->restOptions);
135
		return json_decode($this->response, true);
136
	}
137
138
	/**
139
	 * Check if IP license is registered by any customer.
140
	 *
141
	 * @param string $ipAddress ip address to check
142
	 * @return false|array Will return list of registered license types or empty list if provided IP is not registered yet.
143
	 */
144
	public function check($ipAddress) {
145
		$this->response = $this->getcurlpage($this->restUrl.'ipl/check.json?ip='.$ipAddress.'&token='.$this->authToken(), '', $this->restOptions);
146
		$response = json_decode($this->response, true);
147
		if ($response['success'] == 1)
148
			return $response['data'];
149
		else
150
			return false;
151
	}
152
153
	/**
154
	 * Will register IP based license for authorized user.
155
	 *
156
	 * @param string $ipAddress ip address to registger
157
	 * @param int $type IP license type (1,2 or 16)
158
	 * @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
159
	 */
160
	public function register($ipAddress, $type) {
161
		$this->response = $this->getcurlpage($this->restUrl.'ipl/register.json?ip='.$ipAddress.'&type='.$type.'&token='.$this->authToken(), '', $this->restOptions);
162
		return json_decode($this->response, true);
163
	}
164
165
	/**
166
	 * Will remove IP based license from authorized user licenses.
167
	 *
168
	 * @param string $ipAddress ip address to remove licenses on
169
	 * @param int $type optional license type. If empty, will remove licenses with all types
170
	 * @return bool
171
	 */
172
	public function restRemove($ipAddress, $type = 0) {
173
		if ($type != 0)
174
			$this->response = $this->getcurlpage($this->restUrl.'ipl/remove.json?ip='.$ipAddress.'&type='.$type.'&token='.$this->authToken(), '', $this->restOptions);
175
		else
176
			$this->response = $this->getcurlpage($this->restUrl.'ipl/remove.json?ip='.$ipAddress.'&token='.$this->authToken(), '', $this->restOptions);
177
		return json_decode($this->response, true);
178
	}
179
180
	/**
181
	 * Will remove IP based license from authorized user licenses.
182
	 *
183
	 * @param string $ipAddress ip address to remove licenses on
184
	 * @param int $type optional license type. If empty or 0, will remove licenses with all types
185
	 * @return bool
0 ignored issues
show
Documentation introduced by
Should the return type not be boolean|integer?

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...
186
	 */
187
	public function remove($ipAddress, $type = 0) {
188
		if ($this->apiType == 'xml')
189
			return $this->removeLicense($ipAddress, $type);
190
		else
191
			return $this->restRemove($ipAddress, $type);
192
	}
193
194
	/**
195
	 * Return all IP licenses owned by authorized user.
196
	 *
197
	 * @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
198
	 */
199
	public function restList() {
200
		$this->response = $this->getcurlpage($this->restUrl.'ipl/list.json?token='.$this->authToken(), '', $this->restOptions);
201
		return json_decode($this->response, true);
202
	}
203
204
	/**
205
	 * automatic authToken generator
206
	 *
207
	 * @return false|string the authToken
208
	 */
209
	public function authToken() {
210
		$time = time();
211
		try {
212
			return $this->login . '|' . $time . '|' . sha1($this->key . $time);
213
		} catch (\Exception $e) {
214
			$this->log('error', 'Caught exception code: ' . $e->getCode());
215
			$this->log('error', 'Caught exception message: ' . $e->getMessage());
216
			return false;
217
		}
218
	}
219
220
	/**
221
	 * Register new IP license.
222
	 *
223
	 * @param string $ipAddress IP Address
224
	 * @param integer $type license type (1,2 or 16)
225
	 * @throws XmlRpcException for critical errors
226
	 * @return false|integer 0 on success, -1 on error
227
	 */
228
	public function license($ipAddress, $type) {
229
		$type = (int)$type;
230
		$xmlClient = $this->xmlClient;
231
		try {
232
			$this->log('error', 'Calling License(' . $this->authToken() . ',' . $ipAddress . ',' . $type . ')');
233
			$this->response = $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 bool|int 0 on success, -1 on error, Error will be returned also if account have no licenses for provided IP.
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 false|array (list<int>): List of registered license types or empty list if no license found
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
	 * @throws XmlRpcException for critical errors
280
	 * @param string $ipAddress ip address to remove
281
	 * @param bool $checkAll True will search for any type of license. False ­ only for types 1 or 2
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
		$xmlClient = $this->xmlClient;
286
		try {
287
			return $this->response = $xmlClient->isLicensed($this->authToken(), $ipAddress, $checkAll);
288
		} catch (\Exception $e) {
289
			$this->log('error', 'Caught exception code: ' . $e->getCode());
290
			$this->log('error', 'Caught exception message: ' . $e->getMessage());
291
			return false;
292
		}
293
	}
294
295
	/**
296
	 * @return false|array
297
	 */
298
	public function licenseList() {
299
		try {
300
			return json_decode($this->getcurlpage($this->restUrl.'ipl/list.json?token=' . $this->authToken()));
301
		} catch (\Exception $e) {
302
			$this->log('error', 'Caught exception code: ' . $e->getCode());
303
			$this->log('error', 'Caught exception message: ' . $e->getMessage());
304
			return false;
305
		}
306
	}
307
308
	/**
309
	 * Return list of all IP licenses owned by authorized user
310
	 *
311
	 * @throws XmlRpcException for critical errors
312
	 * @return false|array (list<structure>): List of structures or empty list. Each structure contains keys:  IP(string)   TYPE(int) ­ license type  REGISTERED(boolean) ­ True if server was registered in CLN with this license
313
	 */
314 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...
315
		$xmlClient = $this->xmlClient;
316
		try {
317
			return $this->response = $xmlClient->reconcile($this->authToken());
318
		} catch (\Exception $e) {
319
			$this->log('error', 'Caught exception code: ' . $e->getCode());
320
			$this->log('error', 'Caught exception message: ' . $e->getMessage());
321
			return false;
322
		}
323
	}
324
}
325
326