-
Notifications
You must be signed in to change notification settings - Fork 109
/
Copy pathApi.php
418 lines (377 loc) · 13.7 KB
/
Api.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
<?php
# Copyright (c) 2013-2017, OVH SAS.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of OVH SAS nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY OVH SAS AND CONTRIBUTORS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL OVH SAS AND CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* This file contains code about \Ovh\Api class
*/
namespace Ovh;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
/**
* Wrapper to manage login and exchanges with simpliest Ovh API
*
* This class manage how works connections to the simple Ovh API with
* login method and call wrapper
* Http connections use guzzle http client api and result of request are
* object from this http wrapper
*
* @package Ovh
* @category Ovh
*/
class Api
{
/**
* Url to communicate with Ovh API
*
* @var array
*/
private $endpoints = [
'ovh-eu' => 'https://eu.api.ovh.com/1.0',
'ovh-ca' => 'https://ca.api.ovh.com/1.0',
'ovh-us' => 'https://api.ovh.us/1.0',
'kimsufi-eu' => 'https://eu.api.kimsufi.com/1.0',
'kimsufi-ca' => 'https://ca.api.kimsufi.com/1.0',
'soyoustart-eu' => 'https://eu.api.soyoustart.com/1.0',
'soyoustart-ca' => 'https://ca.api.soyoustart.com/1.0',
'runabove-ca' => 'https://api.runabove.com/1.0',
];
/**
* Contain endpoint selected to choose API
*
* @var string
*/
private $endpoint = null;
/**
* Contain key of the current application
*
* @var string
*/
private $application_key = null;
/**
* Contain secret of the current application
*
* @var string
*/
private $application_secret = null;
/**
* Contain consumer key of the current application
*
* @var string
*/
private $consumer_key = null;
/**
* Contain delta between local timestamp and api server timestamp
*
* @var string
*/
private $time_delta = null;
/**
* Contain http client connection
*
* @var Client
*/
private $http_client = null;
/**
* Construct a new wrapper instance
*
* @param string $application_key key of your application.
* For OVH APIs, you can create a application's credentials on
* https://api.ovh.com/createApp/
* @param string $application_secret secret of your application.
* @param string $api_endpoint name of api selected
* @param string $consumer_key If you have already a consumer key, this parameter prevent to do a
* new authentication
* @param Client $http_client instance of http client
*
* @throws Exceptions\InvalidParameterException if one parameter is missing or with bad value
*/
public function __construct(
$application_key,
$application_secret,
$api_endpoint,
$consumer_key = null,
Client $http_client = null
) {
if (!isset($api_endpoint)) {
throw new Exceptions\InvalidParameterException("Endpoint parameter is empty");
}
if (preg_match('/^https?:\/\/..*/',$api_endpoint))
{
$this->endpoint = $api_endpoint;
}
else
{
if (!array_key_exists($api_endpoint, $this->endpoints)) {
throw new Exceptions\InvalidParameterException("Unknown provided endpoint");
}
else
{
$this->endpoint = $this->endpoints[$api_endpoint];
}
}
if (!isset($http_client)) {
$http_client = new Client([
'timeout' => 30,
'connect_timeout' => 5,
]);
}
$this->application_key = $application_key;
$this->application_secret = $application_secret;
$this->http_client = $http_client;
$this->consumer_key = $consumer_key;
$this->time_delta = null;
}
/**
* Calculate time delta between local machine and API's server
*
* @throws \GuzzleHttp\Exception\ClientException if http request is an error
* @return int
*/
private function calculateTimeDelta()
{
if (!isset($this->time_delta)) {
$response = $this->rawCall(
'GET',
"/auth/time",
null,
false
);
$serverTimestamp = (int)(string)$response->getBody();
$this->time_delta = $serverTimestamp - (int)\time();
}
return $this->time_delta;
}
/**
* Request a consumer key from the API and the validation link to
* authorize user to validate this consumer key
*
* @param array $accessRules list of rules your application need.
* @param string $redirection url to redirect on your website after authentication
*
* @return mixed
* @throws \GuzzleHttp\Exception\ClientException if http request is an error
*/
public function requestCredentials(
array $accessRules,
$redirection = null
) {
$parameters = new \StdClass();
$parameters->accessRules = $accessRules;
$parameters->redirection = $redirection;
//bypass authentication for this call
$response = $this->decodeResponse(
$this->rawCall(
'POST',
'/auth/credential',
$parameters,
false
)
);
$this->consumer_key = $response["consumerKey"];
return $response;
}
/**
* This is the main method of this wrapper. It will
* sign a given query and return its result.
*
* @param string $method HTTP method of request (GET,POST,PUT,DELETE)
* @param string $path relative url of API request
* @param \stdClass|array|null $content body of the request
* @param bool $is_authenticated if the request use authentication
*
* @return array
* @throws \GuzzleHttp\Exception\ClientException if http request is an error
*/
protected function rawCall($method, $path, $content = null, $is_authenticated = true, $headers = null)
{
if ( $is_authenticated )
{
if (!isset($this->application_key)) {
throw new Exceptions\InvalidParameterException("Application key parameter is empty");
}
if (!isset($this->application_secret)) {
throw new Exceptions\InvalidParameterException("Application secret parameter is empty");
}
}
$url = $this->endpoint . $path;
$request = new Request($method, $url);
if (isset($content) && $method == 'GET') {
$query_string = $request->getUri()->getQuery();
$query = array();
if (!empty($query_string)) {
$queries = explode('&', $query_string);
foreach ($queries as $element) {
$key_value_query = explode('=', $element, 2);
$query[$key_value_query[0]] = $key_value_query[1];
}
}
$query = array_merge($query, (array)$content);
// rewrite query args to properly dump true/false parameters
foreach ($query as $key => $value) {
if ($value === false) {
$query[$key] = "false";
} elseif ($value === true) {
$query[$key] = "true";
}
}
$query = \GuzzleHttp\Psr7\build_query($query);
$url = $request->getUri()->withQuery($query);
$request = $request->withUri($url);
$body = "";
} elseif (isset($content)) {
$body = json_encode($content, JSON_UNESCAPED_SLASHES);
$request->getBody()->write($body);
} else {
$body = "";
}
if(!is_array($headers))
{
$headers = [];
}
$headers['Content-Type'] = 'application/json; charset=utf-8';
if ($is_authenticated) {
$headers['X-Ovh-Application'] = $this->application_key;
if (!isset($this->time_delta)) {
$this->calculateTimeDelta();
}
$now = time() + $this->time_delta;
$headers['X-Ovh-Timestamp'] = $now;
if (isset($this->consumer_key)) {
$toSign = $this->application_secret . '+' . $this->consumer_key . '+' . $method
. '+' . (string) $request->getUri() . '+' . $body . '+' . $now;
$signature = '$1$' . sha1($toSign);
$headers['X-Ovh-Consumer'] = $this->consumer_key;
$headers['X-Ovh-Signature'] = $signature;
}
}
/** @var Response $response */
return $this->http_client->send($request, ['headers' => $headers]);
}
/**
* Decode a Response object body to an Array
*
* @param Response $response
*
* @return array
*/
private function decodeResponse(Response $response)
{
return json_decode($response->getBody(), true);
}
/**
* Wrap call to Ovh APIs for GET requests
*
* @param string $path path ask inside api
* @param array $content content to send inside body of request
* @param array headers custom HTTP headers to add on the request
* @param bool is_authenticated if the request need to be authenticated
*
* @return array
* @throws \GuzzleHttp\Exception\ClientException if http request is an error
*/
public function get($path, $content = null, $headers = null, $is_authenticated = true)
{
if(preg_match('/^\/[^\/]+\.json$/', $path))
{
// Schema description must be access without authentication
return $this->decodeResponse(
$this->rawCall("GET", $path, $content, false, $headers)
);
}
else
{
return $this->decodeResponse(
$this->rawCall("GET", $path, $content, $is_authenticated, $headers)
);
}
}
/**
* Wrap call to Ovh APIs for POST requests
*
* @param string $path path ask inside api
* @param array $content content to send inside body of request
* @param array headers custom HTTP headers to add on the request
* @param bool is_authenticated if the request need to be authenticated
*
* @return array
* @throws \GuzzleHttp\Exception\ClientException if http request is an error
*/
public function post($path, $content = null, $headers = null, $is_authenticated = true)
{
return $this->decodeResponse(
$this->rawCall("POST", $path, $content, $is_authenticated, $headers)
);
}
/**
* Wrap call to Ovh APIs for PUT requests
*
* @param string $path path ask inside api
* @param array $content content to send inside body of request
* @param array headers custom HTTP headers to add on the request
* @param bool is_authenticated if the request need to be authenticated
*
* @return array
* @throws \GuzzleHttp\Exception\ClientException if http request is an error
*/
public function put($path, $content, $headers = null, $is_authenticated = true)
{
return $this->decodeResponse(
$this->rawCall("PUT", $path, $content, $is_authenticated, $headers)
);
}
/**
* Wrap call to Ovh APIs for DELETE requests
*
* @param string $path path ask inside api
* @param array $content content to send inside body of request
* @param array headers custom HTTP headers to add on the request
* @param bool is_authenticated if the request need to be authenticated
*
* @return array
* @throws \GuzzleHttp\Exception\ClientException if http request is an error
*/
public function delete($path, $content = null, $headers = null, $is_authenticated = true)
{
return $this->decodeResponse(
$this->rawCall("DELETE", $path, $content, $is_authenticated, $headers)
);
}
/**
* Get the current consumer key
*/
public function getConsumerKey()
{
return $this->consumer_key;
}
/**
* Return instance of http client
*/
public function getHttpClient()
{
return $this->http_client;
}
}