/
asteriskLogger.php
2330 lines (2041 loc) · 108 KB
/
asteriskLogger.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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Asterisk SugarCRM Integration
* (c) KINAMU Business Solutions AG 2009
*
* Project Home: www.github.com/blak3r/yaai
*
* Parts of this code are (c) 2006. RustyBrick, Inc. http://www.rustybrick.com/
* Parts of this code are (c) 2008 vertico software GmbH
* Parts of this code are (c) 2009 abcona e. K. Angelo Malaguarnera E-Mail admin@abcona.de
* Parts of this code are (c) 2011 Blake Robertson http://www.blakerobertson.com
* Sugarforge: http://www.sugarforge.org/projects/yaai/
* GitHub: http://www.github.com/blak3r/yaai
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact KINAMU Business Solutions AG at office@kinamu.com
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
*/
require_once 'parse.php';
//
// Debug flags
//
$dial_events_log = 'c:/sugarcrm/htdocs/dial_events_log_ast1.html';
$mysql_loq_queries = 0;
$mysql_log_results = 0;
$verbose_log = 0;
$log_memory_usage = 0;
$memory_usage_log_file = "c:\mem_usage.csv";
$memory_usage_log_frequency_secs = 10*60;
$last_memory_log_entry = "";
$last_push_time=0;
dev_clearDialEventsLog();
// All Sugar timestamps are UTC
date_default_timezone_set('UTC');
//
// Say hello, setup include path(s)
//
define('sugarEntry', TRUE);
logLine("\n\n\n******** Asterisk Logger Starting " . getTimestamp() . "**************\n", true);
// Determine SugarCRM's root dir (we'll use this to find the config filez
$scriptRoot = dirname(__FILE__);
$sugarRoot = $scriptRoot . "/../../../";
print "[Config Settings]\n";
print " Sugar root set to [$sugarRoot]\n";
//set_include_path(get_include_path() . PATH_SEPARATOR . $sugarRoot . "include");
//print "# PHP include path set to [" . get_include_path() . "]\n";
// Specify a custom sugar root on commandline when in test mode (I used this to debug from eclipse)
if ($argc > 2) {
$sugarRoot = $argv[2];
if (!endsWith($sugarRoot, "/")) {
$sugarRoot .= "/";
}
print " New sugar root is: " . $sugarRoot;
}
//
// Required libraries
//
require_once($sugarRoot . "include/nusoap/nusoap.php");
// Wrapper class auto logins in if session expires.
class SugarSoap extends nusoapclient {
public $sessionid;
public $auth_array;
function __construct($endpoint, $something, $auth_array) {
$this->auth_array = $auth_array;
parent::__construct($endpoint, $something);
$this->login();
}
function login() {
$result = parent::call('login', $this->auth_array);
$this->sessionid = $result['id'];
if ($this->sessionid == -1) {
logLine("! Soap login failed!\n");
print_r($result);
}
return ($result);
}
function call($method, $params) {
$params['session'] = $this->sessionid;
$result = parent::call($method, $params);
if (is_array($result) && array_key_exists("error", $result) && $result['error']['number'] != 0) {
$this->login();
$result = parent::call($method, $params);
}
//print_r($result);
return ($result);
}
}
//
// Pull in config file(s)
//
require_once($sugarRoot . 'config.php');
include_once($sugarRoot . 'config_override.php');
logLine(" Logging to: " . $sugar_config['asterisk_log_file'] . "\n");
$asteriskServer = $sugar_config['asterisk_host'];
$asteriskManagerPort = (int) $sugar_config['asterisk_port'];
$asteriskUser = "Username: " . $sugar_config['asterisk_user'] . "\r\n";
$asteriskSecret = "Secret: " . $sugar_config['asterisk_secret'] . "\r\n";
$asteriskMatchInternal = $sugar_config['asterisk_expr'];
// Load localization if available
$locale_path = $sugarRoot . 'custom/modules/Asterisk/language/' . $sugar_config['default_language'] . '.lang.php';
if (file_exists($locale_path)) {
logLine(" Found Language file for " . $sugar_config['default_language'] );
include_once $locale_path;
}
else {
logLine("### WARNING: No language file exists for: " . $sugar_config['default_language'] . ". Defaulting to english");
logLine(" __See https://github.com/blak3r/yaai/wiki/How-to-Translate__ for translation instructions.");
include_once( $sugarRoot . 'custom/modules/Asterisk/language/en_us.lang.php' );
}
// Make regex pattern compatible with preg_match
if (!startsWith($asteriskMatchInternal, '/')) {
$asteriskMatchInternal = '/' . $asteriskMatchInternal . '/i';
}
// Fetch Asterisk dialprefix - must strip this from inbound callerIDs if set
$calloutPrefix = isset($sugar_config['asterisk_prefix']) ? $sugar_config['asterisk_prefix'] : "";
echo (" Callout prefix is [$calloutPrefix]\n");
$callinPrefix = isset($sugar_config['asterisk_dialinPrefix']) ? $sugar_config['asterisk_dialinPrefix'] : "";
echo (" Callin prefix is [$callinPrefix]\n");
echo (" Match Internal Regex = $asteriskMatchInternal\n");
//
// Connect to mySQL DB
//
logLine("[Database Connection]\n");
logLine(" Selecting DB Name: {$sugar_config['dbconfig']['db_name']}\n");
$sql_connection = mysql_connect($sugar_config['dbconfig']['db_host_name'], $sugar_config['dbconfig']['db_user_name'], $sugar_config['dbconfig']['db_password']);
$sql_db = mysql_select_db($sugar_config['dbconfig']['db_name']);
// Prune asterisk_log
// Note only use this for development
// mysql_query('DELETE FROM asterisk_log');
// Set all MySQL dates to UTC
mysql_query("SET time_zone='+00:00'");
purgeExpiredEventsFromDb();
// Get SOAP config
$sugarSoapEndpoint = $sugar_config['site_url'] . "/soap.php"; //"/soap.php";
$sugarSoapUser = $sugar_config['asterisk_soapuser'];
$sugarSoapCredential = md5($sugar_config['asterisk_soappass']);
// Here we check if LDAP Authentication is used, if so we must build credential differently
$q = mysql_query('select value from config where category=\'system\' and name=\'ldap_enabled\'');
$r = mysql_fetch_assoc($q);
if ($r['value'] != 1) {
$sugarSoapCredential = md5($sugar_config['asterisk_soappass']);
} else {
$q = mysql_query('select value from config where category=\'ldap\' and name=\'enc_key\'');
$r = mysql_fetch_assoc($q);
$ldap_enc_key = substr(md5($r['value']), 0, 24);
$sugarSoapCredential = bin2hex(mcrypt_cbc(MCRYPT_3DES, $ldap_enc_key, $sugar_config['asterisk_soappass'], MCRYPT_ENCRYPT, 'password'));
}
// Added this while loop to keep retrying the soap login b/c I found when I started it through daemon script...
// despite specifying apache as a dependency... it was failing to connect... (this will keep retrying login until it's successful).
// Probably should have this script reload the SOAP config from config.php. Wasn't sure how to do that since it's already been
// included at top of file in require_once.
$successfullyLoggedInThroughSoap = false;
while (!$successfullyLoggedInThroughSoap) {
//
// And finally open a SOAP connection to SugarCRM
//
logLine("[SOAP Connection]\n");
logLine(" Trying SOAP login endpoint=[$sugarSoapEndpoint] user=[$sugarSoapUser] password=[$sugarSoapCredential]\n");
$auth_array = array(
'user_auth' => array(
'user_name' => $sugarSoapUser,
'password' => $sugarSoapCredential
)
);
$soapClient = new SugarSoap($sugarSoapEndpoint . '?wsdl', true, $auth_array); // This method logs in also
$soapSessionId = $soapClient->sessionid;
$userGUID = $soapClient->call('get_user_id', array(
$soapSessionId
));
if (is_array($userGUID) && array_key_exists("error", $userGUID) && $userGUID['error']['number'] != 0) {
logLine(" **WARNING Unable to make initial SOAP Call " . $userGUID['error']['number'] . " " . $userGUID['error']['name'] . " // " . $userGUID['error']['description'] . "**\n");
logLine(" Retrying in 5 seconds...\n\n");
sleep(5);
}
// This case might be obsolete at this point...
else if (empty($userGUID) || empty($soapSessionId) || $userGUID == -1) {
logLine(" __FATAL: SOAP login failed, something didn't get set by login... check your site_url, and make sure sugarcrm is running. SessionID:" . $soapSessionId . " user=" . $auth_array['user_auth']['user_name'] . " GUID=" . $userGUID . "__\n");
logLine(" Sleeping for 5 seconds then retrying...\n\n");
sleep(5);
} else {
logLine(" Successfully logged into Sugar via SOAP! SessionId=" . $soapSessionId . " user=" . $auth_array['user_auth']['user_name'] . " GUID=" . $userGUID . "\n");
$successfullyLoggedInThroughSoap = true;
}
}
if ($argc > 1 && $argv[1] == "test") {
// MODIFY these variables to help diagnose misc incompatibilities between your configuration / sugarcrm edition.
$ext1 = 51;
$ext2 = 52;
//$extensions = (51,52,207);
$phones = array('4102152497', '4108464565', 'sdfasdf', '(267) 222-8385', '2672228385');
print "Entered test mode!";
$obj = findSugarObjectByPhoneNumber("4102152497");
$obj = findSugarObjectByPhoneNumber("4108464565");
print "findUserByAsteriskExtension(51) returned: " . findUserByAsteriskExtension("51") . "\n";
print "findUserByAsteriskExtension(207) returned: " . findUserByAsteriskExtension("207") . "\n";
print "findUserByAsteriskExtension(710) returned: " . findUserByAsteriskExtension('710') . "\n";
findUserByAsteriskExtension('206');
foreach ($phones as $currPhone) {
$obj = findSugarObjectByPhoneNumber($currPhone);
if ($obj === FALSE) {
print "!!! DIDN'T FIND OBJ for $currPhone\n";
} else {
print " For $currPhone I found: " . $obj['values']['id'] . ' ' . $obj['values']['first_name'] . ' ' . $obj['values']['last_name'] . "\n";
}
}
// Test for memory leaks...
$cnt = 0;
gc_enable();
$GLOBALS['_transient']['static']['nusoap_base']->globalDebugLevel = 0;
$lastMem = 0;
while( $cnt++ < 1000 ) {
$set_entry_params = array(
'session' => $soapSessionId,
'module_name' => 'Calls',
'name_value_list' => array(
array(
'name' => 'name',
'value' => $mod_strings['YAAI']['CALL_AUTOMATIC_RECORD']
),
array(
'name' => 'status',
'value' => $mod_strings['YAAI']['CALL_IN_LIMBO']
),
array(
'name' => 'assigned_user_id',
'value' => '1'
)
)
);
$soapResult = $soapClient->call('set_entry', $set_entry_params);
unset($set_entry_params);
unset($soapResult);
$currMem = memory_get_usage() ;
if( $lastMem > $currMem ) {
logLine("\n\nmemory usage decreased!!! $lastMem --> $currMem\n\n");
}
$lastMem = $currMem;
if( $cnt % 10 == 0 ) {
logLine( "mem usage: " . memory_get_usage() . "\n");
}
}
exit;
}
// BR: Added this while loop to keep logging in to AMI if asterisk goes down.
while (true) {
/*
$cString = "tls://ast2.alertus.com:5039";
$context = stream_context_create();
//$errno = 0;
//$errstr = '';
$amiSocket = stream_socket_client(
$cString, $errno, $errstr,
5000, STREAM_CLIENT_CONNECT, $context
);
if ($sock === false) {
print('Error connecting to ami: ' . $errstr);
}
// $amiSocket = fsockopen('tls://' . $asteriskServer, $asteriskManagerPort, $errno, $errstr, 5);
// $asteriskManagerPort = 5038;
*/
logLine("[Asterisk Manager Interface (AMI) Connection]\n");
$amiSocket = fsockopen($asteriskServer, $asteriskManagerPort, $errno, $errstr, 5); // connect to Asterisk server
if (!$amiSocket) {
logLine(" __ ERROR $errno connecting to Asterisk: $errstr __");
sleep(5); // retry connecting
continue;
} else {
logLine(" Successfully opened socket connection to $asteriskServer:$asteriskManagerPort\n");
}
// Here we extract the AMI Version Number and set a varible with it for creating special if cases for special versions of AMI in the future.
$result = AMI_ReadResponse($amiSocket, 2000000);
logLine(" AMI Version Info:\n" . markdown_indent($result)); // Prints the AMI Version
if (preg_match("/Call Manager\/(\d\.\d)/", $result, $ver_matches)) {
$managerVersion = $ver_matches[1];
if ($managerVersion === "1.1") {
logLine(" Supported AMI version: $managerVersion Detected");
}
else if($managerVersion === "1.0") {
logLine("\n __READ!!! You have a partially supported AMI version: $managerVersion Detected__");
logLine(" __Some features like Ring Groups and Queues probably will not work.__\n\n ");
}
} else {
logLine(" __WARNING: Unable to detect the manager version. Setting to 1.1 and hoping for the best. But, this is probably an error__");
$managerVersion = "1.1";
}
// Perform AMI Login command
fputs($amiSocket, "Action: Login\r\n");
fputs($amiSocket, $asteriskUser);
fputs($amiSocket, $asteriskSecret);
fputs($amiSocket, "Events: call,hud\r\n\r\n"); // to monitor just call data, for Asterisk Manager 1.0 remove hud
$result = AMI_ReadResponse($amiSocket, 2000000);
logLine(" AMI Login action raw response:\n" . markdown_indent($result));
if (AMI_WasCmdSuccessful($result)) {
logLine(" AMI Login was a *success!*");
logLine("Waiting for call events...");
} else {
logLine(" __ERROR: AMI Login FAILED__, Depending on your asterisk version helpful info may be above.\n **Check Asterisk Username / Password in config, then verify AMI user has proper permissions in manager.conf**\n\n");
sleep(5);
continue;
}
$event = '';
$stack = 0;
$event_started = false;
$start = NULL;
$timeout = ini_get('default_socket_timeout');
stream_set_timeout($amiSocket, 60); // sets timeout to 60 seconds.
$consecutiveFailures = 0;
$queueChannels = array();
// Keep a loop going to read the socket and parse the resulting commands.
// Apparently there is no good way to detect if socket is still alive???
// This is my hack... if we fail 60 times in a row we reconnect to manager...
// I suspect that fgets will return very quickly if socket error has occurs
// So, it'll reach 60 very quickly and then force relogin.
// Otherwise, every hour it'll just relogin.
// Perhaps you can check socket error some other way then socket_read?
// All I know is this reconnect method has made my asteriskLogger a lot more stable.
while ($consecutiveFailures < 60 && !safe_feof($amiSocket, $start) && (microtime(true) - $start) < $timeout) {
$buffer = fgets($amiSocket, 4096);
// echo("# Read " . strlen($buffer) . " " . $buffer . "\n");
if ($buffer === FALSE) {
logLine(getTimestamp() . " Patiently Waiting...! (mem_used: " . memory_get_usage() . ")\n");
purgeExpiredEventsFromDb();
$consecutiveFailures++;
} else {
$consecutiveFailures = 0;
if ($buffer == "\r\n") { // handle partial packets
$event_started = false;
// parse the event and get the result hashtable
$e = getEvent($event);
dumpEvent($e); // prints to screen
//if ($e['Event'] == 'Join' && !empty($e['Queue']) /*&& in_array($e['Queue'], $allowedQueueIds)*/ )
//{
// $queueChannels[ AMI_getUniqueIdFromEvent($e) ] = $e['Channel']; // TODO: This array will grow indefinitely... the data put into it is pretty small so probably fine for now but would be best to have a expiration policy.
// // Easy solution would be to test during the hangup event... IF( isset($queueChannels[ $e['UniqueID'] ] ) remove the index for $e['UniqueID']
// logLine("Incoming Queue Event, channel = " . $e['Channel']);
//}
//
// Call Event
//
if (($e['Event'] == 'Dial' && $e['SubEvent'] == 'Begin') ||
($e['Event'] == 'Join' && !empty($e['Queue'])))
{
purgeExpiredEventsFromDb(); // clears out db of old events... also called when timeouts occcur
logLine("! Dial Event src=" . $e['Channel'] . " dest=" . $e['Destination'] . "\n"); //Asterisk Manager 1.1
//print "! Dial Event src=" . $e['Source'] . " dest=" . $e['Destination'] . "\n"; //Asterisk Manager 1.0
$eChannel = $e['Channel'];
// Attempt to make compatible with AMI 1.0
if (!empty($e['Source'])) {
$eChannel = $e['Source'];
}
$eDestination = $e['Destination'];
if (empty($e['DestUniqueID']) && $e['Event'] == 'Join') {
logLine("DestUniqueID is empty, this must be a queue call... or logic error");
$e['DestUniqueID'] = AMI_getUniqueIdFromEvent($e); // We set destination id because Join events don't set them, and the destination id is what is used to lookup hangup events.
}
//
// Before we log this Dial event, we create a corresponding object in Calls module.
// We'll need this later to record the call when finished, but create it right here
// to get the ID
//
$set_entry_params = array(
'session' => $soapSessionId,
'module_name' => 'Calls',
'name_value_list' => array(
array(
'name' => 'name',
'value' => $mod_strings['YAAI']['CALL_AUTOMATIC_RECORD']
),
array(
'name' => 'status',
'value' => $mod_strings['YAAI']['CALL_IN_LIMBO']
),
array(
'name' => 'assigned_user_id',
'value' => $userGUID
)
)
);
$soapResult = $soapClient->call('set_entry', $set_entry_params);
//print_r( $soapResult );
$callRecordId = $soapResult['id'];
logLine("! Successfully created CALL record with id=" . $callRecordId . "\n");
$call = NULL;
$tmpCallerID = trim(AMI_getCallerIdFromEvent($e)); //Asterisk Manager 1.0 $e['CallerID']
// Typically for outbound calls there are NewCallerID events which contain the phone number dialed.
// This isn't the case on POTS lines.
// The dialstring will be like g0/14101234567 for outbound calls and 14101234567 for inbound
// Regex only matches the outbound case since in the inbound case the CallerIDNum variable is set properly.
// Note: this cases also seems to happen on the INTERNAL inbound call events to Ring Groups which is harmless.
if (!empty($e['Dialstring'])) {
if (preg_match("/(.*?\/)N?(\d+)/", $e['Dialstring'], $ds_matches)) {
$tmpCallerID = $ds_matches[2];
logLine(" CallerID set from Dialstring to: " . $tmpCallerID);
}
}
// Fix for issue on some asterisk 1.8 boxes where CallerId on click to dial is not set. See https://github.com/blak3r/yaai/issues/75
if ($tmpCallerID == '<unknown>' && !empty($e['ConnectedLineNum'])) {
$tmpCallerID = trim($e['ConnectedLineNum']);
// If Call ID is blocked it comes in as "<unknown>"
if( $tmpCallerID == "<unknown>") {
$tmpCallerID = "BLOCKED";
}
logLine(" CallerID set from ConnectedLineNum to $tmpCallerID");
}
if (startsWith($tmpCallerID, $calloutPrefix)) {
logLine(" Stripping callout prefix: $calloutPrefix\n");
$tmpCallerID = substr($tmpCallerID, strlen($calloutPrefix));
}
if (startsWith($tmpCallerID, $callinPrefix)) {
logLine(" Stripping callin prefix: $calloutPrefix\n");
$tmpCallerID = substr($tmpCallerID, strlen($callinPrefix));
}
logLine(" CallerID is: $tmpCallerID\n");
$rgDetectRegex = "/" . $sugar_config['asterisk_rg_detect_expr'] . "/i";
$rgCellRingRegex = "/" . $sugar_config['asterisk_rg_cell_ring_expr'] . "/i"; // This detects in a RG when an outside line is called (usually for a cellphone)... for some reason the cell shows up as the Channel (aka the source)... We detect this by finding a number thats at least 7-10 characters long..
// Check if both ends of the call are internal (then delete created (** Automatic record **) record)
// 2nd condition looks for Local/RG-52-4102152497
if ((preg_match($asteriskMatchInternal, $eChannel) && preg_match($asteriskMatchInternal, $eDestination)) ||
preg_match($rgDetectRegex, $eDestination) ||
preg_match($rgCellRingRegex, $eChannel)) {
deleteCall($callRecordId);
logLine("INTERNAL call detected, Deleting Call Record $callRecordId\n");
// FIXME Delete this! Trying to visualize internal call for RingGroups
/*
$userExtension = extractExtensionNumberFromChannel($eDestination);
$inboundExtension = NULL;
if (!empty($e['Queue']) ) {
$inboundExtension = $e['Queue'];
}
else {
// Extract from eDestination
$inboundExtension = extractExtensionNumberFromChannel($eDestination);
}
$query = sprintf("INSERT INTO asterisk_log (asterisk_id, call_record_id, channel, remote_channel, callstate, direction, CallerID, timestamp_call, asterisk_dest_id,user_extension,inbound_extension) VALUES('%s','%s','%s','%s','%s','%s','%s',%s,'%s','%s','%s')", AMI_getUniqueIdFromEvent($e), $callRecordId, $eDestination, $eChannel, 'Dial', 'X', $tmpCallerID, 'FROM_UNIXTIME(' . time() . ')', $e['DestUniqueID'], $userExtension, $inboundExtension);
$callDirection = 'Inbound';
logLine("INTERNAL FIXME REMOVE state detected... $asteriskMatchInternal is astMatchInternal eChannel= " . $eChannel . ' eDestination=' . $eDestination . "\n");
mysql_checked_query($query);
*/
// HERE We detect if this is the outbound call to a cell phone...
/*
$query = "SELECT * FROM asterisk_log WHERE channel like '%" . $e['ConnectedLineNum'] . "%' AND callerID = '" . $tmpCallerID . "'";
$result = mysql_checked_query($query);
while ($pd = mysql_fetch_array($result)) {
callinize_push("207", $tmpCallerID,$pd['call_record_id'], $e['ConnectedLineNum'] ); // FIXME
}
*/
} else {
//Asterisk Manager 1.1 (If the call is internal, this will be skipped)
if (preg_match($asteriskMatchInternal, $eChannel) && !preg_match($asteriskMatchInternal, $eDestination)) {
$userExtension = extractExtensionNumberFromChannel($eChannel);
$query = sprintf("INSERT INTO asterisk_log (asterisk_id, call_record_id, channel, remote_channel, callstate, direction, CallerID, timestamp_call,user_extension) VALUES('%s','%s','%s','%s','%s','%s','%s',%s,'%s')", AMI_getUniqueIdFromEvent($e)/*BR: In an attempt to make Dial End work for Outbound calls switching this over to use Unique ID... I have no idea why DestId was used originally... TBD $e['DestUniqueID']*/, $callRecordId, $eChannel, $eDestination, 'NeedID', 'O', $tmpCallerID, 'FROM_UNIXTIME(' . time() . ')', $userExtension);
dev_logString("Insert Outbound");
$callDirection = 'Outbound';
logLine("OUTBOUND state detected... $asteriskMatchInternal is astMatchInternal eChannel= " . $eChannel . ' eDestination=' . $eDestination . "\n");
} else if (!preg_match($asteriskMatchInternal, $eChannel)) {
$userExtension = extractExtensionNumberFromChannel($eDestination);
if( $e['Event'] == 'Join' && !empty($e['Queue'])) {
$userExtension = $e['Queue'];
}
$inboundExtension = NULL;
if (!empty($e['Queue']) ) {
$inboundExtension = $e['Queue'];
}
else {
// Extract from eDestination
$inboundExtension = extractExtensionNumberFromChannel($eDestination);
}
logLine(" inbound_extension = " . $inboundExtension );
$query = sprintf("INSERT INTO asterisk_log (asterisk_id, call_record_id, channel, remote_channel, callstate, direction, CallerID, timestamp_call, asterisk_dest_id,user_extension,inbound_extension) VALUES('%s','%s','%s','%s','%s','%s','%s',%s,'%s','%s','%s')", AMI_getUniqueIdFromEvent($e), $callRecordId, $eDestination, $eChannel, 'Dial', 'I', $tmpCallerID, 'FROM_UNIXTIME(' . time() . ')', $e['DestUniqueID'], $userExtension, $inboundExtension);
$callDirection = 'Inbound';
dev_logString("Insert Inbound");
logLine("Inbound state detected... $asteriskMatchInternal is astMatchInternal eChannel= " . $eChannel . ' eDestination=' . $eDestination . "\n");
//FIXME REENABLE
if( $inboundExtension == "211" || $inboundExtension == "52") {
// TODO Fix
callinize_push($inboundExtension,$tmpCallerID, $callRecordId, "+14102152497");
}
else if( $inboundExtension == "216") {
// TODO Fix
callinize_push($inboundExtension,$tmpCallerID, $callRecordId, "+14153435295");
}
else if( $inboundExtension == "215") {
// TODO Fix
callinize_push($inboundExtension,$tmpCallerID, $callRecordId, "+14153435295");
}
else if( $inboundExtension == "217") {
// TODO Fix
callinize_push($inboundExtension,$tmpCallerID, $callRecordId, "+12026883230");
}
}
mysql_checked_query($query);
//
// Update CALL record with direction...
//
$set_entry_params = array(
'session' => $soapSessionId,
'module_name' => 'Calls',
'name_value_list' => array(
array(
'name' => 'id',
'value' => $callRecordId
),
array(
'name' => 'direction',
'value' => $callDirection
)
)
);
$soapResult = $soapClient->call('set_entry', $set_entry_params);
}
}
//
// NewCallerID for Outgoing Call
//
// NewCallerid == 1.1, Newcallerid == 1.0
if ($e['Event'] == 'NewCallerid' || $e['Event'] == 'Newcallerid') {
$id = AMI_getUniqueIdFromEvent($e);
$tmpCallerID = AMI_getCallerIdFromEvent($e);
if ((strlen($calloutPrefix) > 0) && (strpos($tmpCallerID, $calloutPrefix) === 0)) {
logLine("* Stripping prefix: $calloutPrefix");
$tmpCallerID = substr($tmpCallerID, strlen($calloutPrefix));
}
logLine(" CallerID Changed to: $tmpCallerID\n");
$query = "UPDATE asterisk_log SET CallerID='" . $tmpCallerID . "', callstate='Dial' WHERE asterisk_id='" . $id . "'";
mysql_checked_query($query);
}
// Had to switch to using Dial End commands because when using hangups I couldn't do calls to cell phones properly... (basically there are so many
// hangup events it killed me...
// Queues have the opposite issue... I can't detect the end of a Queue call unfortuntely...
// Queues -- Could not use Dial End, only Hangup would work.
//
// Process "Hangup" events
// Yup, we really get TWO hangup events from Asterisk! (Even more with Ringgroups)
// Obviously, we need to take only one of them....
//
// Asterisk Manager 1.1
/*$e['Event'] == 'Hangup'*/
if (($e['Event'] == 'Dial' && $e['SubEvent'] == 'End') ||
($e['Event'] == 'Hangup' /*&& preg_match( '/from-queue/', $e['Channel'])*/ )) {
$id = AMI_getUniqueIdFromEvent($e);
logLine(" In DialEnd... $id");
$query = "SELECT call_record_id,direction,bean_module,bean_id,user_extension,inbound_extension FROM asterisk_log WHERE asterisk_dest_id = '$id' OR asterisk_id = '$id'";
$result = mysql_checked_query($query);
$direction = mysql_fetch_array($result);
//var_dump($direction);
if ($direction['direction'] == "I") {
$callDirection = "Inbound";
} else {
$callDirection = "Outbound";
}
//logLine( print_r($direction,true) );
// TODO verify configurator boolean issues will not present a problem for this.
if( $sugar_config['asterisk_only_log_calls_matching_user_extension'] &&
(empty($direction['user_extension'] ) ||
!findUserByAsteriskExtension($direction['user_extension'])))
{
logLine(" ## Deleting callid = " . $direction['call_record_id'] . " because it didn't match any user extension");
deleteCall( $direction['call_record_id']);
}
else if ($callDirection == "Outbound") { //Outbound callhandling
//
// Fetch associated call record
//
$callRecord = findCallByAsteriskId($id);
if ($callRecord) {
logLine("### [$id] FOUND outbound CALL\n");
//
// update entry in asterisk_log...
//
$rawData = $callRecord['bitter']; // raw data from asterisk_log
$query = sprintf("UPDATE asterisk_log SET callstate='%s', timestamp_hangup=%s WHERE asterisk_id='%s'", //asterisk_dest_id was asterisk_id
'Hangup', 'FROM_UNIXTIME(' . time() . ')', $id);
dev_logString("Hungup $id");
$updateResult = mysql_checked_query($query);
if ($updateResult) {
$assignedUser = findUserIdFromChannel($rawData['channel']);
//
// ... on success also update entry in Calls module
//
//
// Calculate call duration...
//
$failedCall = FALSE;
$hangupTime = time();
$callDurationRaw = 0; // call duration in seconds, only matters if timestamp_link != NULL
if ($rawData['timestamp_link'] != NULL) {
$callStartLink = strtotime($rawData['timestamp_link']);
$callDurationRaw = $hangupTime - $callStartLink;
} else {
$failedCall = TRUE;
}
$callStart = strtotime($rawData['timestamp_call']);
logLine(" [$id] Measured call duration is $callDurationRaw seconds\n");
// Recalculate call direction in minutes
$callDuration = (int) ($callDurationRaw / 60);
$callDurationHours = (int) ($callDuration / 60);
//$callDurationMinutes = ceil($callDuration / 60); //voor afronden naar boven.
$callDurationMinutes = ($callDuration % 60);
//
// Calculate final call state
//
$callStatus = NULL;
$callName = NULL;
$callDescription = "";
// BR: 3/16/2012 I originally had this check to make sure call was longer then 5 seconds... I don't know why. Whey you have callStatus of Missed it creates a task which is undesirable.
// So i'm commenting it out. If it's April and I still haven't deleted this comment it's safe to delete this code.
//if (!$failedCall) {
$callStatus = 'Held';
$callName = $mod_strings['YAAI']['ASTERISKLBL_GOING_OUT'];
// This means call description was updated through AJAX so lets not overwrite the subject/description already assigned to the call.
if (!empty($callRecord['sweet']['description'])) {
$callName = $callRecord['sweet']['name'];
$callDescription = $callRecord['sweet']['description'];
}
// } else {
// $callStatus = 'Missed';
// $callName = $mod_strings['YAAI']['CALL_NAME_MISSED'];
// $callDescription = "{$mod_strings['YAAI']['CALL_DESCRIPTION_MISSED']} ({$e['Cause-txt']}\n";
// $callDescription .= "------------------\n";
// $callDescription .= sprintf(" %-20s : %-40s\n", $mod_strings['YAAI']['CALL_DESCRIPTION_PHONE_NUMBER'], $rawData['callerID']);
// if( $rawData['opencnam'] ) {
// $callName .= " - " . $rawData['opencnam'];
// $callDescription .= sprintf(" %-20s : %-40s\n", $mod_strings['YAAI']['CALL_DESCRIPTION_CALLER_ID'], $rawData['opencnam']);
// }
// logLine("Adding OUTBOUND Failed Call, id=$id, call_id = " . $callRecord['sweet']['id'] . "\n");
// }
// Establish Relationships with the Call and Contact/Account
$beanID = NULL;
$beanType = NULL;
$parentID = NULL;
$parentType = NULL;
if (!empty($direction['bean_id'])) {
logLine("Bean Id already set by callListener to: " . $direction['bean_id'] . "\n");
$beanID = $direction['bean_id'];
$beanType = ucfirst($direction['bean_module']);
} else {
$assocAccount = findSugarAccountByPhoneNumber($rawData['callerID']);
if ($assocAccount != FALSE) {
logLine("Found a matching account, relating to account instead of contact\n");
$beanID = $assocAccount['values']['id'];
$beanType = $assocAccount['type'];
$parentType = 'Accounts';
$parentID = $beanID;
} else {
$assoSugarObject = findSugarObjectByPhoneNumber($rawData['callerID']);
$beanID = $assoSugarObject['values']['id'];
$beanType = $assoSugarObject['type'];
}
}
setRelationshipBetweenCallAndBean($callRecord['sweet']['id'], $beanType, $beanID);
if ($beanType == "Contacts" && !empty($beanID)) {
$assocAccount = findAccountForContact($beanID);
if ($assocAccount) {
$parentType = 'Accounts';
$parentID = $assocAccount;
}
} else if ($beanType == "Accounts") {
$parentType = "Accounts";
$parentID = $beanID;
}
//var_dump($parentType);
//var_dump($parentID);
logLine(" Call start was " . gmdate('Y-m-d H:i:s', $callStart) . "\n");
//
// ... on success also update entry in Calls module
//
logLine(" [$id] (OUTBOUND) Now updating record in /Calls/ id=" . $callRecord['sweet']['id'] . "...\n");
//print_r($callRecord);
logLine("NAME: " . $callRecord['sweet']['name'] . "\n");
logLine("DESCRIPTION: " . $callRecord['sweet']['description'] . "\n");
gitimg_log("call-out");
$soapResult = $soapClient->call('set_entry', array(
'session' => $soapSessionId,
'module_name' => 'Calls',
'name_value_list' => array(
array(
'name' => 'id',
'value' => $callRecord['sweet']['id']
),
array(
'name' => 'name',
'value' => $callName
),
array(
'name' => 'duration_hours',
'value' => $callDurationHours
),
array(
'name' => 'duration_minutes',
'value' => $callDurationMinutes
),
array(
'name' => 'status',
'value' => $callStatus
),
array(
'name' => 'description',
'value' => $callDescription
),
array(
'name' => 'asterisk_caller_id_c',
'value' => $rawData['callerID']
),
array(
'name' => 'asterisk_user_extension_c',
'value' => $direction['user_extension']
),
array(
'name' => 'asterisk_inbound_extension_c',
'value' => $direction['inbound_extension']
),
array(
'name' => 'date_start',
'value' => gmdate('Y-m-d H:i:s', $callStart)
),
array(
'name' => 'parent_type',
'value' => $parentType
),
array(
'name' => 'parent_id',
'value' => $parentID
),
array(
'name' => 'assigned_user_id',
'value' => $assignedUser
)
)
));
}
} else {
logLine("[$id] FAILED TO FIND A CALL (note: there are two hangups per call, so this might not be an error)\n");
}
} else {
//-----------------[ INBOUND HANGUP HANDLING ]----------------------
$id = AMI_getUniqueIdFromEvent($e);
//
// Fetch associated call record
//
//$callRecord = findCallByAsteriskDestId($id);
$callRecord = findCallByAsteriskId($id);
if ($callRecord) {
//
// update entry in asterisk_log...
//
$rawData = $callRecord['bitter']; // raw data from asterisk_log
// 2013 - march removed hangup_cause=%d, hangup_cause_txt='%s'
$query = sprintf("UPDATE asterisk_log SET callstate='%s', timestamp_hangup=%s, answered='%s' WHERE asterisk_id='%s'", //asterisk_dest_id was asterisk_id
'Hangup', 'FROM_UNIXTIME(' . time() . ')', was_call_answered($id), $id);
dev_logString("Hungup Inbound $id");
$updateResult = mysql_checked_query($query);
if ($updateResult) {
$assignedUser = findUserIdFromChannel($rawData['channel']);
//
// ... on success also update entry in Calls module
//
//
// Calculate call duration...
//
$failedCall = FALSE;
$hangupTime = time();
$callDurationRaw = 0; // call duration in seconds, only matters if timestamp_link != NULL
if ($rawData['timestamp_link'] != NULL) {
$callStartLink = strtotime($rawData['timestamp_link']);
$callDurationRaw = $hangupTime - $callStartLink;
} else {
$failedCall = TRUE;
}
$callStart = strtotime($rawData['timestamp_call']);
logLine(" Measured call duration is $callDurationRaw seconds\n");
// Recalculate call direction in minutes
$callDuration = (int) ($callDurationRaw / 60);
$callDurationHours = (int) ($callDuration / 60);
//$callDurationMinutes = ceil($callDuration / 60); //voor afronden naar boven.
$callDurationMinutes = ($callDuration % 60);
//
// Calculate final call state
//
$callStatus = NULL;
$callName = NULL;
$callDescription = "";
if (!$failedCall) {
$callStatus = 'Held';
$callName = $mod_strings['YAAI']['ASTERISKLBL_COMING_IN'];
// This means call description was updated through AJAX so lets not overwrite the subject/description already assigned to the call.
if (!empty($callRecord['sweet']['description'])) {
$callName = $callRecord['sweet']['name'];
$callDescription = $callRecord['sweet']['description'];
}
} else {
$callStatus = $sugar_config['asterisk_short_call_status']; // User gets to choose if they should be Missed or Held, if Missed then it leaves an open activity which has to be closed.
$callName = $mod_strings['YAAI']['CALL_NAME_MISSED'];
$callDescription = "{$mod_strings['YAAI']['CALL_DESCRIPTION_MISSED']} ({$e['Cause-txt']}\n";
$callDescription .= "------------------\n";
$callDescription .= sprintf(" %-20s : %-40s\n", $mod_strings['YAAI']['CALL_DESCRIPTION_PHONE_NUMBER'], $rawData['callerID']);
if ($rawData['opencnam']) {
$callName .= " - " . $rawData['opencnam'];
$callDescription .= sprintf(" %-20s : %-40s\n", $mod_strings['YAAI']['CALL_DESCRIPTION_CALLER_ID'], $rawData['opencnam']);
}
logLine(" Adding INBOUND Missed (or Failed) Call, id=$id, call_id = " . $callRecord['sweet']['id'] . "\n");
dev_logString(" Adding INBOUND Missed (or Failed) Call, id=$id, call_id = " . $callRecord['sweet']['id'] . "\n");
}
// Establish Relationships with the Call and Contact/Account
$beanID = NULL;
$beanType = NULL;
$parentID = NULL;
$parentType = NULL;
if (!empty($direction['bean_id'])) {
logLine("Bean Id already set by callListener to: " . $direction['bean_id'] . "\n");
$beanID = $direction['bean_id'];
$beanType = ucfirst($direction['bean_module']);
} else {
$assocAccount = findSugarAccountByPhoneNumber($rawData['callerID']);
if ($assocAccount != FALSE) {
logLine("Found a matching account, relating to account instead of contact\n");
$beanID = $assocAccount['values']['id'];
$beanType = $assocAccount['type'];
$parentType = 'Accounts';
$parentID = $beanID;
} else {
$assoSugarObject = findSugarObjectByPhoneNumber($rawData['callerID']);
$beanID = $assoSugarObject['values']['id'];
$beanType = $assoSugarObject['type'];
}
}
setRelationshipBetweenCallAndBean($callRecord['sweet']['id'], $beanType, $beanID);
if ($beanType == "Contacts" && !empty($beanID)) {
$assocAccount = findAccountForContact($beanID);
if ($assocAccount) {
$parentType = 'Accounts';
$parentID = $assocAccount;
}
} else if ( $beanType == "Accounts") {
$parentType = "Accounts";
$parentID = $beanID;
}
echo ("! Call start was " . gmdate('Y-m-d H:i:s', $callStart) . "\n");
//
// ... on success also update entry in Calls module
//
logLine(" Updating record in /Calls/ id=" . $callRecord['sweet']['id'] . "...\n");
//print_r($callRecord);
logLine(" NAME: " . $callRecord['sweet']['name'] . "\n");
logLine(" DESCRIPTION: " . $callRecord['sweet']['description'] . "\n");
gitimg_log("call-in");
$soapResult = $soapClient->call('set_entry', array(
'session' => $soapSessionId,
'module_name' => 'Calls',
'name_value_list' => array(
array(
'name' => 'id',
'value' => $callRecord['sweet']['id']
),
array(
'name' => 'name',
'value' => $callName
),
array(
'name' => 'duration_hours',
'value' => $callDurationHours
),
array(
'name' => 'duration_minutes',
'value' => $callDurationMinutes
),