callerid.php

CallerID PHP test patch - tshif, 10/23/2009 12:02 pm

Download (16.9 KB)

 
1
<?php
2
/*** Original script by Nerd Vittles. (Google for Caller Id Trifecta)
3
    3/12/2009          Put into module format by Tony Shiffer & Jerry Swordsteel
4
                        commented out fixed variables.  Added db code to get values from db.
5
        3/30/2009          New SugarCRM by jpeterman is now included.
6
        4/8/2009          Removed dependancy on default id/pw for db connection. now parses amportal.conf
7
        5-8-2009        Version 2.0.0 Major update - Tickets: Tickets: #7, #10, #15, #17, #36, and #19.(projects.colsolgrp.net)(jjacobs)
8
        8-18-2009        Version 2.2.0  CID Schemes and online update for data sources (projects.colsolgrp.net)(jjacobs)
9
        10-16-2009        Version 2.2.1  http://projects.colsolgrp.net/versions/show/52 (projects.colsolgrp.net)
10
        10-22-2009  Version 2.2.2  http://projects.colsolgrp.net/versions/show/55 (projects.colsolgrp.net)
11
***/
12
13
require_once("../../../functions.inc.php");
14
15
$caller_id = '';
16
$prefix = '';
17
$cache_found = false;
18
$spam = false;
19
$winning_source = '';
20
$usage_mode = 'get caller id';
21
$thenumber_orig = trim($_REQUEST['thenumber']);
22
$scheme = trim($_REQUEST['scheme']);
23
//$thenumber_orig = ereg_replace('[^0-9]+', '', $thenumber_orig);
24
$debug_val = (isset($_REQUEST['debug'])) ? $_REQUEST['debug'] : '';
25
$debug = ($debug_val == 'yes') ? true : false;
26
27
if($debug)
28
{
29
        $start_time_whole = mctime_float();
30
        $end_time_whole = 0;
31
}
32
33
// new code - causes config values to be pulled from db  3/12/2009
34
require_once 'DB.php';
35
define("AMP_CONF", "/etc/amportal.conf");
36
37
$amp_conf = parse_amportal_conf(AMP_CONF);
38
if(count($amp_conf) == 0)
39
{
40
        fatal("FAILED");
41
}
42
43
$dsn = array(
44
    'phptype'  => 'mysql',
45
    'username' => $amp_conf['AMPDBUSER'],
46
    'password' => $amp_conf['AMPDBPASS'],
47
    'hostspec' => $amp_conf['AMPDBHOST'],
48
    'database' => $amp_conf['AMPDBNAME'],
49
);
50
$options = array();
51
$db =& DB::connect($dsn, $options);
52
if(PEAR::isError($db))
53
{
54
        die($db->getMessage());
55
}
56
57
//connect to the asterisk manager
58
require_once('../../../common/php-asmanager.php');
59
$astman        = new AGI_AsteriskManager();
60
61
// attempt to connect to asterisk manager proxy
62
if(!isset($amp_conf["ASTMANAGERPROXYPORT"]) || !$res = $astman->connect("127.0.0.1:".$amp_conf["ASTMANAGERPROXYPORT"], $amp_conf["AMPMGRUSER"] , $amp_conf["AMPMGRPASS"], 'off'))
63
{
64
        // attempt to connect directly to asterisk, if no proxy or if proxy failed
65
        if (!$res = $astman->connect("127.0.0.1:".$amp_conf["ASTMANAGERPORT"], $amp_conf["AMPMGRUSER"] , $amp_conf["AMPMGRPASS"], 'off'))
66
        {
67
                // couldn't connect at all
68
                unset( $astman );
69
        }
70
}
71
72
//get the DID for this call using the PHP Asterisk Manager
73
$DID = "";
74
$value = $astman->command('core show channels concise');
75
$chan_array = split("\n",$value['data']);
76
foreach($chan_array as $val)
77
{
78
        $this_chan_array = split("!",$val);
79
        if(isset($this_chan_array[7]))
80
        {
81
                $this_chan_array[7]=trim($this_chan_array[7]);
82
//                if($thenumber_orig == substr($this_chan_array[7],-10))
83
                if($thenumber_orig == $this_chan_array[7])
84
                {
85
                        $value = $astman->command('core show channel '.$this_chan_array[0]);
86
                        $this_array = split("\n",$value['data']);
87
                        foreach($this_array as $val2)
88
                        {
89
                                if(strpos($val2,'FROM_DID=') !== false)
90
                                {
91
                                        $DID = trim(str_replace('FROM_DID=','',$val2));
92
                                        break;
93
                                }
94
                        }
95
                        
96
                        //break out if the value is set.
97
                        if($DID != '')
98
                        {
99
                                break;
100
                        }
101
                }
102
        }
103
}
104
105
$param = array();
106
$query = "SELECT * FROM superfectaconfig";
107
$res = $db->query($query);
108
while ($row = $res->fetchRow(DB_FETCHMODE_ASSOC))
109
{
110
        $param[$row['source']][$row['field']] = $row['value'];
111
}
112
113
if($debug)
114
{
115
        print "Debugging Enabled, will not stop after first result.<br>\n";
116
}
117
118
//loop through schemes
119
$query = "SELECT                source
120
                                        FROM                        superfectaconfig
121
                                        WHERE                        field = 'order'
122
                                        AND                                value > 0";
123
if($debug && ($scheme != ""))
124
{
125
        $query .= " AND                source = '$scheme'";
126
}
127
$query .= " ORDER BY value";
128
$res = $db->query($query);
129
while ($row = $res->fetchRow(DB_FETCHMODE_ASSOC))
130
{
131
        $this_scheme = $row['source'];
132
        $run_this_scheme = true;
133
        $thenumber = ereg_replace('[^0-9]+', '', $thenumber_orig);
134
        
135
        if($debug)
136
        {
137
                print "<hr>Processing ".substr($this_scheme,5)." Scheme.<br>\n";
138
        }
139
        //trying to push some info to the CLI
140
        $astman->command('VERBOSE "Processing '.substr($this_scheme,5).' Scheme." 3');
141
        
142
        //determine if this is the correct DID, if this scheme is limited to a DID.
143
        if(!empty($param[$this_scheme]['DID']))
144
        {
145
                $debug_result = "Valid DID.<br>\n";
146
                if($debug)
147
                {
148
                        print "DID matching enabled...";
149
                }
150
                if(substr($param[$this_scheme]['DID'],0,1) == "_")
151
                {
152
                        $DID_return = match_pattern(substr($param[$this_scheme]['DID'],1),$DID);
153
                        if($DID != $DID_return)
154
                        {
155
                                $run_this_scheme = false;
156
                                $debug_result = "DID did not match specified patterns.<br>\n";
157
                        }
158
                }
159
                else if($DID != $param[$this_scheme]['DID'])
160
                {
161
                        $run_this_scheme = false;
162
                        $debug_result = "DID did not match.<br>\n";
163
                }
164
                
165
                if($debug)
166
                {
167
                        print $debug_result;
168
                }
169
        }
170
        
171
        //determine if the CID matches any patterns defined for this scheme
172
        if(!empty($param[$this_scheme]['CID_rules']) && $run_this_scheme)
173
        {
174
                $debug_result = "No Matching CID Patterns.<br>\n";
175
                $run_this_scheme = false;
176
                if($debug)
177
                {
178
                        print "CID matching enabled...";
179
                }
180
                $scheme_rules = split("\n",$param[$this_scheme]['CID_rules']);
181
                foreach($scheme_rules as $val)
182
                {
183
                        $thenumber = match_pattern(trim($val),$thenumber_orig);
184
                        if($thenumber !== false)
185
                        {
186
                                $run_this_scheme = true;
187
                                $debug_result = "Valid CID: ".$thenumber.".<br>\n";
188
                                break;
189
                        }
190
                }
191
                
192
                if($debug)
193
                {
194
                        print $debug_result;
195
                }
196
        }
197
        
198
        if($run_this_scheme)
199
        {
200
                $curl_timeout = $param[$this_scheme]['Curl_Timeout'];
201
                
202
                //if a prefix lookup is enabled, look it up, and truncate the result to 10 characters
203
                if($param[$this_scheme]['Prefix_URL'] != '')
204
                {
205
                        if($debug)
206
                        {
207
                                $start_time = mctime_float();
208
                        }
209
                        
210
                        $prefix = get_url_contents(str_replace("[thenumber]",$thenumber,$param[$this_scheme]['Prefix_URL']));
211
                        
212
                        if($debug)
213
                        {
214
                                print "Prefix Url defined ...\n";
215
                                if($prefix !='')
216
                                {
217
                                        print 'returned: '.$prefix."<br>\n";
218
                                }
219
                                else
220
                                {
221
                                        print "result was empty<br>\n";
222
                                }
223
                                print "result <img src='images/scrollup.gif'> took ".number_format((mctime_float()-$start_time),4)." seconds.<br>\n<br>\n";
224
                        }
225
                }
226
                
227
                //run through the specified sources
228
                $src_array = explode(',',$param[$this_scheme]['sources']);
229
                $first_caller_id = '';
230
                $theoriginalnumber = $thenumber;
231
                foreach($src_array as $source_name)
232
                {
233
                        $thenumber = $theoriginalnumber;
234
                        if($debug)
235
                        {
236
                                $start_time = mctime_float();
237
                        }
238
                        $caller_id = '';
239
                        $run_param = $param[substr($this_scheme,5).'_'.$source_name];
240
                        
241
                        eval('include("source-'.$source_name.'.php");');
242
                        if(($first_caller_id == '') && ($caller_id != ''))
243
                        {
244
                                $first_caller_id = $caller_id;
245
                                $winning_source = $source_name;
246
                                if($debug)
247
                                {
248
                                        $end_time_whole = mctime_float();
249
                                }
250
                        }
251
                        
252
                        if($debug)
253
                        {
254
                                if($caller_id != '')
255
                                {
256
                                        print $caller_id."<br>\nresult <img src='images/scrollup.gif'> took ".number_format((mctime_float()-$start_time),4)." seconds.<br>\n<br>\n";
257
                                }
258
                                else
259
                                {
260
                                        print "result <img src='images/scrollup.gif'> took ".number_format((mctime_float()-$start_time),4)." seconds.<br>\n<br>\n";
261
                                }
262
                        }
263
                        else if($caller_id != '')
264
                        {
265
                                break;
266
                        }
267
                }
268
        
269
                
270
                $prefix = ($prefix != '') ? $prefix.':' : '';
271
                if($spam)
272
                {
273
                        $first_caller_id = $param[$this_scheme]['SPAM_Text'].':'.$first_caller_id;
274
                }
275
        }
276
        
277
        if($first_caller_id != '')
278
        {
279
                break;
280
        }
281
}
282
283
//post-processing
284
if($debug)
285
{
286
        print "Post CID retrieval processing.<br>\n<br>\n";
287
}
288
289
//remove unauthorized character in the caller id
290
if ($first_caller_id !='')
291
        {
292
                $first_caller_id = preg_replace ( "/[\";']/", "", $first_caller_id);
293
                $first_caller_id = trim ($first_caller_id);
294
        }
295
//limit caller id to the first 60 char
296
if (strlen($first_caller_id) > 60)
297
        {
298
                $first_caller_id = substr($first_caller_id,0,60);
299
        }
300
301
$usage_mode = 'post processing';
302
foreach($src_array as $source_name)
303
{        
304
        $thenumber = $theoriginalnumber;
305
        eval('include("source-'.$source_name.'.php");');
306
}
307
308
if($debug)
309
{
310
        print "<b>Returned Result would be: ";
311
}
312
313
print $prefix.$first_caller_id;
314
if($debug)
315
{
316
        $end_time_whole = ($end_time_whole == 0) ? mctime_float() : $end_time_whole;
317
        print "<br>\nresult <img src='images/scrollup.gif'> took ".number_format(($end_time_whole-$start_time_whole),4)." seconds.</b>";
318
}
319
320
$astman->disconnect();
321
322
/**
323
Returns the content of a URL.
324
*/
325
function get_url_contents($url)
326
{
327
        global $debug,$curl_timeout;
328
        $crl = curl_init();
329
        $useragent="Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1";
330
        curl_setopt($crl,CURLOPT_USERAGENT,$useragent);
331
        curl_setopt($crl,CURLOPT_URL,$url);
332
        curl_setopt($crl,CURLOPT_RETURNTRANSFER,true);
333
        curl_setopt($crl,CURLOPT_CONNECTTIMEOUT,$curl_timeout);
334
        curl_setopt($crl,CURLOPT_FAILONERROR,true);
335
        curl_setopt($crl,CURLOPT_TIMEOUT,$curl_timeout);
336
        $ret = trim(curl_exec($crl));
337
        $ret=utf8_encode($ret);
338
339
        if(curl_error($crl) && $debug)
340
        {
341
                print ' '.curl_error($crl).' ';
342
        }
343
        
344
        //if debug is turned on, return the error number if the page fails.
345
        if($ret === false)
346
        {
347
                $ret = '';
348
        }
349
        //something in curl is causing a return of "1" if the page being called is valid, but completely empty.
350
        //to get rid of this, I'm doing a nasty hack of just killing results of "1".
351
        if($ret == '1')
352
        {
353
                $ret = '';
354
        }
355
        curl_close($crl);
356
        return $ret;
357
}
358
359
function mctime_float()
360
{
361
         list($usec, $sec) = explode(" ", microtime());
362
         return ((float)$usec + (float)$sec);
363
}
364
365
/**
366
        Parses Asterisk dial patterns and produces a resulting number if the match is successful or false if there is no match.
367
*/
368
function match_pattern($pattern,$number)
369
{
370
        $return = false;
371
        $pattern_error = false;
372
        $pipe_location = 0;
373
        $plus_location = 0;
374
        $required_length = 0;
375
        $adjustable_length = false;
376
        $character_array = array();
377
        $number_split = str_split($number);
378
        
379
        //parse through the pattern and build an array for matching
380
        $split = str_split($pattern);
381
        $count = 0;
382
        $bracket_open = false;
383
        $range_open = false;
384
        $range_start = 0;
385
        foreach($split as $key=>$val)
386
        {
387
                $skip = false;
388
                if($val == "]")
389
                {
390
                        $bracket_open = false;
391
                        $range_open = false;
392
                        $required_length++;
393
                }
394
                else if($bracket_open)
395
                {
396
                        if(is_numeric($val))
397
                        {
398
                                if($range_open)
399
                                {
400
                                        for($x = ($range_start + 1); $x <= $val; $x++)
401
                                        {
402
                                                $character_array[$count][] = $x;
403
                                        }
404
                                }
405
                                else
406
                                {
407
                                        $character_array[$count][] = $val;
408
                                }
409
                                $range_start = $val;
410
                                $range_open = false;
411
                        }
412
                        else if($val == "-")
413
                        {
414
                                $range_open = true;
415
                        }
416
                        else
417
                        {
418
                                $pattern_error = true;
419
                                break;
420
                        }
421
                        $skip = true;
422
                }
423
                else if($val == "[")
424
                {
425
                        $bracket_open = true;
426
                        $skip = true;
427
                }
428
                else if($val == "+")
429
                {
430
                        if($plus_location > 0)
431
                        {
432
                                $pattern_error = true;
433
                                break;
434
                        }
435
                        else
436
                        {
437
                                $plus_location = $count;
438
                        }
439
                }
440
                else if($val == "|")
441
                {
442
                        if($pipe_location > 0)
443
                        {
444
                                $pattern_error = true;
445
                                break;
446
                        }
447
                        else
448
                        {
449
                                $pipe_location = $count;
450
                        }
451
                }
452
                else if($val == "!")
453
                {
454
                        if(isset($split[($key + 1)]))
455
                        {
456
                                $pattern_error = true;
457
                                break;
458
                        }
459
                        else
460
                        {
461
                                $adjustable_length = true;
462
                                for($x = $count; $x <= ($count + 30); $x++)
463
                                {
464
                                        $character_array[$x] = array(0,1,2,3,4,5,6,7,8,9);
465
                                }
466
                        }
467
                }
468
                else if($val == ".")
469
                {
470
                        if(isset($split[($key + 1)]))
471
                        {
472
                                $pattern_error = true;
473
                                break;
474
                        }
475
                        else
476
                        {
477
                                $adjustable_length = true;
478
                                $required_length++;
479
                                for($x = $count; $x <= ($count + 30); $x++)
480
                                {
481
                                        $character_array[$x] = array(0,1,2,3,4,5,6,7,8,9);
482
                                }
483
                        }
484
                }
485
                else if($val == "N")
486
                {
487
                        $character_array[$count] = array(2,3,4,5,6,7,8,9);
488
                        $required_length++;
489
                }
490
                else if($val == "X")
491
                {
492
                        $character_array[$count] = array(0,1,2,3,4,5,6,7,8,9);
493
                        $required_length++;
494
                }
495
                else if($val == "Z")
496
                {
497
                        $character_array[$count] = array(1,2,3,4,5,6,7,8,9);
498
                        $required_length++;
499
                }
500
                else if(is_numeric($val))
501
                {
502
                        $character_array[$count][0] = $val;
503
                        $required_length++;
504
                }
505
                else
506
                {
507
                        $pattern_error = true;
508
                        break;
509
                }
510
                
511
                if(!$skip)
512
                {
513
                        $count++;
514
                }
515
        }
516
        
517
        if(!$pattern_error)
518
        {
519
                //check for the existence of both the plus and pipe.
520
                if(($pipe_location > 0) && ($plus_location > 0))
521
                {
522
                        $good_number = true;
523
                        $new_number = "";
524
                        $prefix = "";
525
                        if($pipe_location > $plus_location)
526
                        {
527
                                $required_length = $required_length - $plus_location;
528
                                if(($adjustable_length && ($required_length <= strlen($number))) || ($required_length == strlen($number)))
529
                                {
530
                                        for($x = 0; $x < $plus_location; $x++)
531
                                        {
532
                                                if(count($character_array[$x]) > 1)
533
                                                {
534
                                                        $pattern_error = true;
535
                                                        break;
536
                                                }
537
                                                else
538
                                                {
539
                                                        $prefix .= $character_array[$x][0];
540
                                                }
541
                                        }
542
                                        
543
                                        foreach($number_split as $key=>$val)
544
                                        {
545
                                                $key = $key + strlen($prefix) + 1;
546
                                                if(($key < $pipe_location) && !in_array($val,$character_array[$key]))
547
                                                {
548
                                                        $good_number = false;
549
                                                }
550
                                                else if($key > $pipe_location)
551
                                                {
552
                                                        if(!in_array($val,$character_array[$key]))
553
                                                        {
554
                                                                $good_number = false;
555
                                                        }
556
                                                        else
557
                                                        {
558
                                                                $new_number .= $val;
559
                                                        }
560
                                                }
561
                                        }
562
                                        if($good_number)
563
                                        {
564
                                                $return = $prefix.$new_number;
565
                                        }
566
                                }
567
                        }
568
                        else
569
                        {
570
                                $required_length = $required_length - $plus_location + $pipe_location + 1;
571
                                if(($adjustable_length && ($required_length <= strlen($number))) || ($required_length == strlen($number)))
572
                                {
573
                                        for($x = ($pipe_location + 1); $x < $plus_location; $x++)
574
                                        {
575
                                                if(count($character_array[$x]) > 1)
576
                                                {
577
                                                        $pattern_error = true;
578
                                                        break;
579
                                                }
580
                                                else
581
                                                {
582
                                                        $prefix .= $character_array[$x][0];
583
                                                }
584
                                        }
585
                                        
586
                                        foreach($number_split as $key=>$val)
587
                                        {
588
                                                $key = ($key >= $pipe_location) ? ($key + $plus_location - $pipe_location + 1) : $key;
589
                                                if(($key < $pipe_location) && !in_array($val,$character_array[$key]))
590
                                                {
591
                                                        $good_number = false;
592
                                                }
593
                                                else if($key > $pipe_location)
594
                                                {
595
                                                        if(!in_array($val,$character_array[$key]))
596
                                                        {
597
                                                                $good_number = false;
598
                                                        }
599
                                                        else
600
                                                        {
601
                                                                $new_number .= $val;
602
                                                        }
603
                                                }
604
                                        }
605
                                        if($good_number)
606
                                        {
607
                                                $return = $prefix.$new_number;
608
                                        }
609
                                }
610
                        }
611
                }
612
                else if(($pipe_location > 0) && (($adjustable_length && ($required_length <= strlen($number))) || ($required_length == strlen($number))))
613
                {
614
                        $good_number = true;
615
                        $new_number = "";
616
                        foreach($number_split as $key=>$val)
617
                        {
618
                                if(($key < $pipe_location) && !in_array($val,$character_array[$key]))
619
                                {
620
                                        $good_number = false;
621
                                }
622
                                else if($key >= $pipe_location)
623
                                {
624
                                        $key++;
625
                                        if(!in_array($val,$character_array[$key]))
626
                                        {
627
                                                $good_number = false;
628
                                        }
629
                                        else
630
                                        {
631
                                                $new_number .= $val;
632
                                        }
633
                                }
634
                        }
635
                        if($good_number)
636
                        {
637
                                $return = $new_number;
638
                        }
639
                }
640
                else if($plus_location > 0)
641
                {
642
                        $good_number = true;
643
                        $prefix = "";
644
                        $required_length = $required_length - $plus_location;
645
                        if(($adjustable_length && ($required_length <= strlen($number))) || ($required_length == strlen($number)))
646
                        {
647
                                foreach($number_split as $key=>$val)
648
                                {
649
                                        if($key < $plus_location)
650
                                        {
651
                                                if(count($character_array[$key]) > 1)
652
                                                {
653
                                                        $pattern_error = true;
654
                                                        $good_number = false;
655
                                                        break;
656
                                                }
657
                                                else
658
                                                {
659
                                                        $prefix .= $character_array[$key][0];
660
                                                }
661
                                        }
662
                                        else if(($key > $plus_location) && !in_array($val,$character_array[$key]))
663
                                        {
664
                                                $good_number = false;
665
                                        }
666
                                }
667
                                if($good_number)
668
                                {
669
                                        $return = $prefix.$number;
670
                                }
671
                        }
672
                }
673
                else if(($adjustable_length && ($required_length <= strlen($number))) || ($required_length == strlen($number)))
674
                {
675
                        $good_number = true;
676
                        foreach($number_split as $key=>$val)
677
                        {
678
                                if(!in_array($val,$character_array[$key]))
679
                                {
680
                                        $good_number = false;
681
                                }
682
                        }
683
                        if($good_number)
684
                        {
685
                                $return = $number;
686
                        }
687
                }
688
        }
689
        
690
        
691
        //split on "+" and check each segment for a match.
692
        $split = split("\+",$pattern);
693
        $build_number = "";
694
        $this_match = false;
695
        foreach($split as $val)
696
        {
697
                $this_number = match_pattern($val,$number);
698
                if(!$this_number)
699
                {
700
                        $build_number .= $val;
701
                }
702
                else
703
                {
704
                        $build_number .= $this_number;
705
                        $this_match = true;
706
                }
707
        }
708
        
709
        if($this_match)
710
        {
711
                $return = $build_number;
712
        }
713
        
714
        if(!$return)
715
        {
716
                //if we don't have a good number to return, continue processing for "|"
717
                $split = split("+",$pattern);
718
                $combine = str_replace("|","",$pattern);
719
        }
720
        
721
        return $return;
722
}
723
?>
724