-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.php
509 lines (420 loc) · 17.6 KB
/
index.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
<?php
#
# Copyright (C) 2024 Nethesis S.r.l.
# SPDX-License-Identifier: AGPL-3.0
#
// function to print debug log messagges
function debug($message)
{
// print deubg if env is set
if (getenv('DEBUG') && $_ENV['DEBUG'] === 'true')
error_log("DEBUG: " . $message);
}
// function to make http GET requests
function makeRequest($username, $token, $url)
{
// init curl
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// set headers
$headers = array("Authorization: $username:$token");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
curl_close($ch);
// read response
$response = json_decode($response, true);
// return response
return $response;
}
// function get auth token
function getAuthToken($cloudUsername, $cloudPassword, $cloudDomain)
{
// compose login url
$authUrl = "https://$cloudDomain/webrest/authentication/login";
$authData = "username=" . urlencode($cloudUsername) . "&password=" . urlencode($cloudPassword);
// exec login
$ch = curl_init($authUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $authData);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, true);
// get response
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// close curl and read response
curl_close($ch);
if ($httpCode !== 401) {
error_log("ERROR: Authentication failed for {$cloudUsername}@{$cloudDomain}. Expected HTTP code 401, got $httpCode");
return False;
}
// extract the nonce from the response header
preg_match('/uthenticate: Digest ([0-9a-f]+)/', $response, $matches);
// if nonce is empty, return error
if (!isset($matches[1])) {
error_log("ERROR: Authentication failed for {$cloudUsername}@{$cloudDomain}. No nonce found in response");
return False;
}
// read nonce
$nonce = $matches[1];
// build the authentication token
$tohash = "$cloudUsername:$cloudPassword:$nonce";
$token = hash_hmac('sha1', $tohash, $cloudPassword);
// print debug
debug("Token generated for {$cloudUsername}@{$cloudDomain}");
return $token;
}
// login to cti using the cloud credentials and get the sip credentials using the /user/me API
function getSipCredentials($cloudUsername, $cloudPassword, $cloudDomain, $isToken = false)
{
// Step 1: Authenticate and obtain the authentication token if isToken is false
if (!$isToken) {
// get auth token
$token = getAuthToken($cloudUsername, $cloudPassword, $cloudDomain);
// print debug
debug("Token generated for {$cloudUsername}@{$cloudDomain}");
} else {
// print debug
debug("Password is already a token for {$cloudUsername}@{$cloudDomain}");
// assign password as token
$token = $cloudPassword;
}
// Step 2: Make the request to user/me API
$url = "https://$cloudDomain/webrest/user/me";
// make response
$response = makeRequest($cloudUsername, $token, $url);
// Step 3: check if lk is set and is valid
if (isset($response['lkhash'])) {
// read api url from env
$url = getenv("VALIDATE_LK_URL");
// create curl state
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// set headers
$headers = array("Authorization: Bearer " . $response['lkhash']);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// exec curl
$lkcheck = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// print debug
debug("lkhash validated for {$cloudUsername}@{$cloudDomain}");
// check if return code is 200, otherwise return false
if ($httpCode !== 200) {
error_log("ERROR: Failed to validate lkhash for {$cloudUsername}@{$cloudDomain}. Expected HTTP code 200, got $httpCode");
return false;
}
} else {
error_log("ERROR: Missing lkhash in response for {$cloudUsername}@{$cloudDomain}");
return false;
}
// Step 4: Return the sip credentials
foreach ($response['endpoints']['extension'] as $extension) {
if ($extension['type'] == 'mobile') {
$sipUser = $extension['id'];
$sipPassword = $extension['secret'];
return [
'sipUser' => $sipUser,
'sipPassword' => $sipPassword,
'proxy_fqdn' => (isset($response['proxy_fqdn']) ? $response['proxy_fqdn'] : "")
];
}
}
// if step 4 has no endpoints, return false
return false;
}
function handle($data)
{
// check if username, password and token are set
if (!isset($data['username']) or !isset($data['password']) or !isset($data['token'])) {
error_log("ERROR: Missing parameters. Expected username, password and token, got " . implode(',', array_keys($data)));
return header('HTTP/1.1 400 Bad Request');
}
// read TOKEN from env
$token = getenv("TOKEN");
// check if token is the same, otherwise return 401
if ($token != $data['token']) {
error_log("ERROR: Invalid hardcoded token for {$data['username']}");
return header('HTTP/1.1 401 Invalid Token');
}
// extract domain from username
$tmp = explode('@', trim(strtolower($data['username'])));
$cloudUsername = $tmp[0];
$cloudDomain = $tmp[1];
// check if login is made with qrcode
if (isset($tmp[2]) && $tmp[2] === 'qrcode') {
$isToken = true;
$loginTypeString = "@qrcode";
// print debug
debug("Using qrcode login for {$cloudUsername}@{$cloudDomain}");
} else {
$isToken = false;
$loginTypeString = "";
}
// read password
$cloudPassword = $data['password'];
// check if app attribute is set, otherwise set login
if (!isset($data['app'])) {
$app = 'login';
} else {
// read app
$app = $data['app'];
}
// switch app case
switch ($app) {
// handle External Provisioning app
case 'login':
// get sip credentials with POST data
$result = getSipCredentials($cloudUsername, $cloudPassword, $cloudDomain, $isToken);
// check if sip credentials exists
if (!$result) {
error_log("ERROR: Failed to get sip credentials for {$cloudUsername}@{$cloudDomain}");
return header("HTTP/1.0 404 Not Found");
}
// check auth token
if (!$isToken) {
// get auth token
$token = getAuthToken($cloudUsername, $cloudPassword, $cloudDomain);
// print debug
debug("Token generated for {$cloudUsername}@{$cloudDomain}");
} else {
// print debug
debug("Password is already a token for {$cloudUsername}@{$cloudDomain}");
// assign password as token
$token = $cloudPassword;
}
// get busy lamp extensions
$url = "https://$cloudDomain/webrest/astproxy/extensions";
// make request
$response = makeRequest($cloudUsername, $token, $url);
// create busy lamp extensions object
$busylamps = array();
// loop busy lamp extensions api response
foreach (array_keys($response) as $busylamp) {
// compose xml structure
$busylamps[] = '<uri>' . $busylamp . '</uri>';
}
// set headers
header("Content-type: text/xml");
// compose xml configuration string
$proxy = "";
if ($result['proxy_fqdn']) {
$proxy = "<proxy>{$result['proxy_fqdn']}:5061</proxy>";
} else {
// print debug
debug("No proxy fqdn found in response for {$cloudUsername}@{$cloudDomain}");
}
// compose final xml string
$xmlConfString = "
<account>
<cloud_username>{$cloudUsername}@{$cloudDomain}{$loginTypeString}</cloud_username>
<cloud_password>{$cloudPassword}</cloud_password>
<username>{$result['sipUser']}</username>
<password>{$result['sipPassword']}</password>
<extProvInterval>3600</extProvInterval>
$proxy
<host>{$cloudDomain}</host>
<transport>tls+sip:</transport>
<blf>" . implode("", $busylamps) . "</blf>
</account>
";
// return xml string
echo $xmlConfString;
// print debug
debug('Returning sip credentials: ' . preg_replace('/password>.*<\//', 'password>xxxx</', $xmlConfString));
break;
// handle Contact Sources app
case 'contacts':
// get auth token
if (!$isToken) {
// get auth token
$token = getAuthToken($cloudUsername, $cloudPassword, $cloudDomain);
// print debug
debug("Contacts. Token generated for {$cloudUsername}@{$cloudDomain}");
} else {
// print debug
debug("Contacts. Password is already a token for {$cloudUsername}@{$cloudDomain}");
// assign password as token
$token = $cloudPassword;
}
// get phonebook counters
$url = "https://$cloudDomain/webrest/phonebook/search/?offset=0&limit=1&view=all";
// make request
$response = makeRequest($cloudUsername, $token, $url);
// read counter file
$count = 0;
if (file_exists('/tmp/phonebook_counters_' . $cloudDomain)) {
$count = file_get_contents('/tmp/phonebook_counters_' . $cloudDomain);
}
// get request headers
$headers = apache_request_headers();
// check if counter is equal or last modified is 24 hours ago, return 304 Not Modified
if (isset($headers['If-Modified-Since']) && strtotime($headers['If-Modified-Since']) >= strtotime('-24 hours', time()) && $count == $response['count']) {
// print debug
debug('Phonebook contacts are the same: ' . $count . ' since ' . $headers['If-Modified-Since']);
// return header 304
header('HTTP/1.1 304 Not Modified');
return;
}
// new contacts found, write to debug log
debug('Phonebook new contacts found: ' . $response['count']);
// make request to get all phonebook contacts
$url = "https://$cloudDomain/webrest/phonebook/search/?view=all";
// make request
$response = makeRequest($cloudUsername, $token, $url);
// create contacts object
$contacts = array();
// loop contacts api response
foreach ($response['rows'] as $contact) {
// compose contacts object
$contacts[] = [
"avatar" => "",
"largeAvatar" => "",
"birthday" => "",
"checksum" => "",
"contactEntries" => [
[
"entryId" => "0",
"label" => "home phone",
"type" => "tel",
"uri" => $contact["homephone"]
],
[
"entryId" => "1",
"label" => "work phone",
"type" => "tel",
"uri" => $contact["workphone"]
],
[
"entryId" => "2",
"label" => "mobile",
"type" => "tel",
"uri" => $contact["cellphone"]
],
[
"entryId" => "3",
"label" => "home email",
"type" => "email",
"uri" => $contact["homeemail"]
],
[
"entryId" => "4",
"label" => "work email",
"type" => "email",
"uri" => $contact["workemail"]
],
],
"contactAddresses" => [
[
"addressId" => "0",
"label" => "home address",
"city" => $contact["homecity"],
"country" => $contact["homecountry"],
"countryCode" => "",
"state" => $contact["homeprovince"],
"street" => $contact["homestreet"],
"zip" => $contact["homepostalcode"]
],
[
"addressId" => "1",
"label" => "work address",
"city" => $contact["workcity"],
"country" => $contact["workcountry"],
"countryCode" => "",
"state" => $contact["workprovince"],
"street" => $contact["workstreet"],
"zip" => $contact["workpostalcode"]
]
],
"contactId" => $contact["id"],
"company" => $contact["company"],
"displayName" => $contact["name"],
"fname" => "",
"lname" => "",
"notes" => $contact["notes"]
];
}
// set counter in a file
file_put_contents("/tmp/phonebook_counters_" . $cloudDomain, $response['count']);
// set headers
header("Content-type: application/json");
header("Last-Modified: " . date(DATE_RFC2822));
header('HTTP/1.1 200 OK');
// print results
$result = json_encode(array("contacts" => $contacts));
echo $result;
break;
case 'quickdial':
// get auth token
if (!$isToken) {
// get auth token
$token = getAuthToken($cloudUsername, $cloudPassword, $cloudDomain);
// print debug
debug("QuickDials. Token generated for {$cloudUsername}@{$cloudDomain}");
} else {
// print debug
debug("QuickDials. Password is already a token for {$cloudUsername}@{$cloudDomain}");
// assign password as token
$token = $cloudPassword;
}
// get quick dials
$url = "https://$cloudDomain/webrest/phonebook/speeddials";
// make request
$response = makeRequest($cloudUsername, $token, $url);
// create quickdials object
$quickdials = array();
// create favorite list
$favorites = array();
// loop quickdials api response
foreach ($response as $quickdial) {
// check if type is speeddial-favorite
if ($quickdial['notes'] == 'speeddial-favorite') {
// compose xml structure
$quickdials[] = '<item id="' . $quickdial['speeddial_num'] . '"><displayName>' . $quickdial['company'] . '</displayName><uri>' . $quickdial['speeddial_num'] . '</uri></item>';
// add favorite num to list, useful to check extensions to remove from list
$favorites[] = $quickdial['speeddial_num'];
// print debug message
debug("Quick dials is a favorite: " . $quickdial['company'] . " " . $quickdial['speeddial_num']);
}
}
// get all extensions
$url = "https://$cloudDomain/webrest/astproxy/extensions";
// make request
$response = makeRequest($cloudUsername, $token, $url);
// get keys of response
$extensions = array_keys($response);
// create remove keys
$removes = array();
// loop extensions to remove
foreach ($extensions as $extension) {
if (!in_array($extension, $favorites)) {
// compose xml structure
$removes[] = '<item id="' . $extension . '" action="remove"/>';
// print debug message
debug("Quick dials is not a favorite: " . $extension);
}
}
// set header
header("Content-type: text/xml");
header('HTTP/1.1 200 OK');
// print results
echo '<root><quickDial>' . implode("", $quickdials) . implode("", $removes) . '</quickDial></root>';
break;
default:
break;
}
}
// read json from input
$jsonData = file_get_contents('php://input');
// decode json
$data = json_decode($jsonData, true);
// check if data is set
if ($data) {
// start request handle
handle($data);
} else {
// no data, return 400
error_log("ERROR: Invalid request: missing data");
header('HTTP/1.1 400 Bad Request');
}