forked from Telerivet/telerivet-php-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
telerivet.php
374 lines (309 loc) · 11.2 KB
/
telerivet.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
<?php
/**
PHP client library for Telerivet's REST API.
Example Usage:
--------------
$API_KEY = 'YOUR_API_KEY'; // from https://telerivet.com/dashboard/api
$PROJECT_ID = 'YOUR_PROJECT_ID';
$telerivet = new Telerivet_API($API_KEY);
$project = $telerivet->initProjectById($PROJECT_ID);
// Send a SMS message
$project->sendMessage(array(
'to_number' => '555-0001',
'content' => 'Hello world!'
));
*/
class Telerivet_API
{
private $api_key;
private $api_url;
public $num_requests = 0;
private $client_version = '1.4.3';
private $curl;
public $debug = false;
/**
$tr = new Telerivet_API($api_key)
Initializes a client handle to the Telerivet REST API.
Each API key is associated with a Telerivet user account, and all
API actions are performed with that user's permissions. If you want to restrict the
permissions of an API client, simply add another user account at
<https://telerivet.com/dashboard/users> with the desired permissions.
Arguments:
- $api_key (Your Telerivet API key; see <https://telerivet.com/dashboard/api>)
* Required
*/
public function __construct($api_key, $api_url = 'https://api.telerivet.com/v1')
{
$this->api_key = $api_key;
$this->api_url = $api_url;
}
/**
$tr->getProjectById($id)
Retrieves the Telerivet project with the given ID.
Arguments:
- $id
* ID of the project -- see <https://telerivet.com/dashboard/api>
* Required
Returns:
Telerivet_Project
*/
function getProjectById($id)
{
return new Telerivet_Project($this, $this->doRequest("GET", "{$this->getBaseApiPath()}/projects/{$id}"));
}
/**
$tr->initProjectById($id)
Initializes the Telerivet project with the given ID without making an API request.
Arguments:
- $id
* ID of the project -- see <https://telerivet.com/dashboard/api>
* Required
Returns:
Telerivet_Project
*/
function initProjectById($id)
{
return new Telerivet_Project($this, array('id' => $id), false);
}
/**
$tr->queryProjects($options)
Queries projects accessible to the current user account.
Arguments:
- $options (associative array)
- name
* Filter projects by name
* Allowed modifiers: name[ne], name[prefix], name[not_prefix], name[gte], name[gt],
name[lt], name[lte]
- sort
* Sort the results based on a field
* Allowed values: default, name
* Default: default
- sort_dir
* Sort the results in ascending or descending order
* Allowed values: asc, desc
* Default: asc
- page_size (int)
* Number of results returned per page (max 200)
* Default: 50
- offset (int)
* Number of items to skip from beginning of result set
* Default: 0
Returns:
Telerivet_APICursor (of Telerivet_Project)
*/
function queryProjects($options = null)
{
return $this->newApiCursor('Telerivet_Project', "{$this->getBaseApiPath()}/projects", $options);
}
/**
$tr->getOrganizationById($id)
Retrieves the Telerivet organization with the given ID.
Arguments:
- $id
* ID of the organization -- see <https://telerivet.com/dashboard/api>
* Required
Returns:
Telerivet_Organization
*/
function getOrganizationById($id)
{
return new Telerivet_Organization($this, $this->doRequest("GET", "{$this->getBaseApiPath()}/organizations/{$id}"));
}
/**
$tr->initOrganizationById($id)
Initializes the Telerivet organization with the given ID without making an API request.
Arguments:
- $id
* ID of the organization -- see <https://telerivet.com/dashboard/api>
* Required
Returns:
Telerivet_Organization
*/
function initOrganizationById($id)
{
return new Telerivet_Organization($this, array('id' => $id), false);
}
/**
$tr->queryOrganizations($options)
Queries organizations accessible to the current user account.
Arguments:
- $options (associative array)
- name
* Filter organizations by name
* Allowed modifiers: name[ne], name[prefix], name[not_prefix], name[gte], name[gt],
name[lt], name[lte]
- sort
* Sort the results based on a field
* Allowed values: default, name
* Default: default
- sort_dir
* Sort the results in ascending or descending order
* Allowed values: asc, desc
* Default: asc
- page_size (int)
* Number of results returned per page (max 200)
* Default: 50
- offset (int)
* Number of items to skip from beginning of result set
* Default: 0
Returns:
Telerivet_APICursor (of Telerivet_Organization)
*/
function queryOrganizations($options = null)
{
return $this->newApiCursor('Telerivet_Organization', "{$this->getBaseApiPath()}/organizations", $options);
}
function getBaseApiPath()
{
return "";
}
function doRequest($method, $path, $params = null)
{
$curl = $this->curl;
if (!$curl)
{
$curl = $this->curl = curl_init();
}
$url = "{$this->api_url}{$path}";
$headers = array(
"User-Agent: Telerivet PHP Client/{$this->client_version} PHP/" . PHP_VERSION . " OS/" . PHP_OS,
"Expect:", // avoid sending Expect: 100-continue to reduce latency
);
if ($method === 'POST' || $method == 'PUT')
{
$headers[] = "Content-Type: application/json";
$post_data = json_encode($params);
$data_len = strlen($post_data);
if ($data_len >= 400 && function_exists('gzencode'))
{
$headers[] = "Content-Encoding: gzip";
$post_data = gzencode($post_data);
}
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
}
else
{
if ($params)
{
$url .= "?" . http_build_query($params, '', '&');
}
curl_setopt($curl, CURLOPT_POSTFIELDS, '');
}
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_BUFFERSIZE, 4096);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($curl, CURLOPT_TIMEOUT, 60);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
if ($this->debug)
{
error_log("$method $url");
}
$cacert_file = dirname(__FILE__) . "/cacert.pem";
if (file_exists($cacert_file))
{
curl_setopt($curl, CURLOPT_CAINFO, $cacert_file);
}
curl_setopt($curl, CURLOPT_USERPWD, "{$this->api_key}:");
$this->num_requests++;
$response_json = curl_exec($curl);
$network_error = curl_error($curl);
if ($network_error)
{
throw new Telerivet_IOException("Error connecting to Telerivet API: {$network_error}");
}
else
{
$response = json_decode($response_json, true);
if (isset($response['error']))
{
$error = $response['error'];
$error_code = $error['code'];
switch ($error_code)
{
case 'invalid_param':
throw new Telerivet_InvalidParameterException($error['message'], $error['code'], $error['param']);
case 'not_found':
throw new Telerivet_NotFoundException($error['message'], $error['code']);
default:
throw new Telerivet_APIException($error['message'], $error['code']);
}
}
else if ($response)
{
return $response;
}
else if (json_last_error() != JSON_ERROR_NONE || $response_json === '')
{
$info = curl_getinfo($curl);
$http_code = $info['http_code'];
throw new Telerivet_IOException("Unexpected response from Telerivet API (HTTP {$http_code}): {$response_json}");
}
else
{
return $response;
}
}
}
function __destruct()
{
if ($this->curl)
{
curl_close($this->curl);
}
}
function newApiCursor($item_cls, $path, $options)
{
return new Telerivet_ApiCursor($this, $item_cls, $path, $options);
}
}
// base class for exceptions raised by this library
class Telerivet_Exception extends Exception {}
// exception corresponding to error returned in API response
class Telerivet_APIException extends Telerivet_Exception
{
public $error_code;
function __construct($message, $error_code)
{
parent::__construct($message);
$this->error_code = $error_code;
}
}
class Telerivet_InvalidParameterException extends Telerivet_APIException
{
public $param;
function __construct($message, $error_code, $param)
{
parent::__construct($message, $error_code);
$this->param = $param;
}
}
class Telerivet_NotFoundException extends Telerivet_APIException
{
function __construct($message, $error_code)
{
parent::__construct($message, $error_code);
}
}
// exception raised when client could not connect to server
class Telerivet_IOException extends Telerivet_Exception {}
$tr_lib_dir = dirname(__FILE__) . '/lib';
require_once "{$tr_lib_dir}/entity.php";
require_once "{$tr_lib_dir}/apicursor.php";
require_once "{$tr_lib_dir}/message.php";
require_once "{$tr_lib_dir}/scheduledmessage.php";
require_once "{$tr_lib_dir}/contact.php";
require_once "{$tr_lib_dir}/broadcast.php";
require_once "{$tr_lib_dir}/project.php";
require_once "{$tr_lib_dir}/label.php";
require_once "{$tr_lib_dir}/group.php";
require_once "{$tr_lib_dir}/phone.php";
require_once "{$tr_lib_dir}/route.php";
require_once "{$tr_lib_dir}/datatable.php";
require_once "{$tr_lib_dir}/datarow.php";
require_once "{$tr_lib_dir}/service.php";
require_once "{$tr_lib_dir}/contactservicestate.php";
require_once "{$tr_lib_dir}/organization.php";