-
Notifications
You must be signed in to change notification settings - Fork 93
/
Superfecta.class.php
871 lines (786 loc) · 35.7 KB
/
Superfecta.class.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
<?php
// vim: set ai ts=4 sw=4 ft=php:
/*
* License for all code of this FreePBX module can be found in the license file inside the module directory
* Copyright (c) 2013 POSSA Working Group
* Copyright (c) 2018 Sangoma Technologies
*/
namespace FreePBX\modules;
use BMO;
use FreePBX_Helpers;
use PDO;
class Superfecta extends FreePBX_Helpers implements BMO {
function __construct($options=array()) {
}
const DEFAULT_CHARACTER_ENCODINGS = 'ISO-8859-1';
const DEFAULT_CALLER_ID_MAX_LENGTH = 60;
const CALLER_ID_MAX_LENGTH_MIN = 10;
private $schemeDefaults = array(
'Curl_Timeout' => 3,
'SPAM_Text' => 'SPAM',
'DID' => '',
'CID_rules' => '',
'processor' => 'superfecta_single.php',
'multifecta_timeout' => '1.5',
'Prefix_URL' => '',
'SPAM_Text_Substitute' => false,
'spam_interceptor' => false,
'SPAM_threshold' => '3',
'interceptor_select' => '',
'Character_Encodings' => self::DEFAULT_CHARACTER_ENCODINGS,
'Strip_Accent_Characters' => true,
'Caller_Id_Max_Length' => self::DEFAULT_CALLER_ID_MAX_LENGTH,
'sources' => array(),
'name' => null
);
private $spamCount = 0;
private $destination = null;
private $agi = null;
public function install() {
$sql = "SELECT * FROM superfectaconfig LIMIT 1;";
$res = $this->Database->query($sql);
if ($res->rowCount() != 1) {
$defaults = [
[':source' => 'base_Default', ':field' => 'order', ':value' => '0'],
[':source' => 'base_Default', ':field' => 'Curl_Timeout', ':value' => '3'],
[':source' => 'base_Default', ':field' => 'SPAM_Text', ':value' => 'SPAM'],
[':source' => 'base_Default', ':field' => 'Character_Encodings', ':value' => self::DEFAULT_CHARACTER_ENCODINGS], // To keep it backward compatible and make sure we don't break existing schemes
[':source' => 'base_Default', ':field' => 'Strip_Accent_Characters', ':value' => 'Y'], // To keep it backward compatible and make sure we don't break existing schemes
[':source' => 'base_Default', ':field' => 'Caller_Id_Max_Length', ':value' => self::DEFAULT_CALLER_ID_MAX_LENGTH],
[':source' => 'base_Default', ':field' => 'sources', ':value' => 'Asterisk_Phonebook,Superfecta_Cache,Trunk_Provided,Telco_Data'],
[':source' => 'Trunk_Provided', ':field' => 'Ignore_Keywords', ':value' => 'unknown, wireless, toll free, unlisted'],
[':source' => 'Superfecta_Cache', ':field' => 'Cache_Timeout', ':value' => '120'],
[':source' => 'PhoneSpamFilter', ':field' => 'SPAM_Threshold', ':value' => '5'],
];
$sql = "REPLACE INTO superfectaconfig (source,field,value) VALUES(:source, :field, :value)";
$stmt = $this->Database->prepare($sql);
foreach ($defaults as $default) {
$stmt->execute($default);
}
}
}
public function uninstall() {
}
public function doConfigPageInit($page){
return true;
}
/**
* Chown hook for freepbx fwconsole
*/
public function chownFreepbx() {
return [
[
'type' => 'file',
'path' => __DIR__."/agi/superfecta.agi",
'perms' => 0755,
],
];
}
private function out($message) {
if(is_object($this->agi)) {
$this->agi->verbose($message);
} elseif (php_sapi_name() != "cli") {
echo "<span class='header'>".$message."</span><br/>";
} else {
echo $message."\n";
}
}
public function setAgi($agi) {
$this->agi = $agi;
}
public function execute($scheme='ALL', $request, $debug=0, $keepGoing=false) {
if(empty($scheme) || !is_array($request) || empty($request)) {
return '';
}
$trunk_info = array();
foreach($request as $key => $value) {
$key = preg_replace('/^agi_/','',$key);
$trunk_info[$key] = $value;
}
$this->out(sprintf(_("Scheme Asked is: %s"),$scheme));
$this->out(sprintf(_("The DID is: %s"),$trunk_info['extension']));
$this->out(sprintf(_("The CNUM is: %s"),$trunk_info['callerid']));
$this->out(sprintf(_("The CNAME is: %s"),$trunk_info['calleridname']));
//If ALL then run through all Schemes, else just the single one
if($scheme == 'ALL') {
$schemes = $this->getAllPoweredSchemes();
} else {
$schemes[0] = array("name" => $scheme);
}
include __DIR__ . '/includes/superfecta_base.php';
include __DIR__ . '/includes/processors/superfecta_multi.php';
include __DIR__ . '/includes/processors/superfecta_single.php';
global $db, $amp_conf, $astman;
$options = array(
'db' => $this->Database,
'amp_conf' => $amp_conf,
'astman' => $astman,
'debug' => 0,
'path_location' => __DIR__ . '/sources',
'trunk_info' => $trunk_info
);
foreach ($schemes as $s) {
try{
$this->out("");
$this->out(sprintf(_("Starting scheme %s"),$s['name']));
//reset these each time
$cnum = $trunk_info['callerid'];
$cnam = $trunk_info['calleridname'];
$did = $trunk_info['extension'];
$options['scheme_name'] = "base_".$s['name'];
$options['scheme_settings'] = $this->getScheme($s['name']);
$options['module_parameters'] = $this->getSchemeAllModuleSettings($s['name']);
switch ($options['scheme_settings']) {
case 'superfecta_multi.php':
//TODO: This is broken and needs to be fixed, there are better ways to do it of course
//for now send all results back through to single
//$options['multifecta_id'] = isset($multifecta_id) ? $multifecta_id : null;
//$options['source'] = isset($source) ? $source : null;
//$superfecta = NEW \superfecta_multi($options);
//break;
case 'superfecta_single.php':
default:
$superfecta = NEW \superfecta_single($options);
break;
}
$superfecta->setDebug($debug);
$superfecta->setCLI(true);
$superfecta->setDID($did);
$superfecta->set_CurlTimeout($options['scheme_settings']['Curl_Timeout']);
// Determine if this is the correct DID, if this scheme is limited to a DID.
$rule_match = $superfecta->match_pattern_all((isset($options['scheme_settings']['DID'])) ? $options['scheme_settings']['DID'] : '', $did);
if ($rule_match['number']) {
$this->out(sprintf(_("Matched DID Rule: %s with %s"),$rule_match['pattern'], $rule_match['number']));
} elseif ($rule_match['status']) {
$this->out(_("No matching DID rules. Skipping scheme"));
continue;
}
// Determine if the CID matches any patterns defined for this scheme
$rule_match = $superfecta->match_pattern_all((isset($options['scheme_settings']['CID_rules'])) ? $options['scheme_settings']['CID_rules'] : '', $cnum);
if ($rule_match['number']) {
$this->out(sprintf(_("Matched CID Rule: %s with %s"),$rule_match['pattern'], $rule_match['number']));
$cnum = $rule_match['number'];
$this->out(sprintf(_("Changed CNUM to: %s"),$cnum));
} elseif ($rule_match['status']) {
$this->out(_("No matching CID rules. Skipping scheme"));
continue;
}
//if a prefix lookup is enabled, look it up, and truncate the result to 10 characters
///Clean these up, set NULL values instead of blanks then don't check for ''
$superfecta->set_Prefix('');
if ((isset($options['scheme_settings']['Prefix_URL'])) && (trim($options['scheme_settings']['Prefix_URL'])) != '') {
$start_time = $superfecta->mctime_float();
$superfecta->set_Prefix($superfecta->get_url_contents(str_replace("[thenumber]", $cnum, $options['scheme_settings']['Prefix_URL'])));
if ($superfecta->prefix != '') {
$this->out(sprintf(_("Prefix Url defined as: %s"),$superfecta->get_Prefix()));
} else {
$this->out(_("Prefix Url defined but result was empty"));
}
$this->out(sprintf(_("Prefix Url result took %s seconds."),number_format(($superfecta->mctime_float() - $start_time), 4)));
}
$trunk_info['callerid'] = $cnum;
$superfecta->set_TrunkInfo($trunk_info);
if($this->agi === null) {
$callerid = $superfecta->web_debug();
} else {
$callerid = $superfecta->get_results();
}
$callerid = trim($callerid);
$found = false;
$Caller_Id_Max_Length = isset($options['scheme_settings']['Caller_Id_Max_Length']) ? $options['scheme_settings']['Caller_Id_Max_Length'] : self::DEFAULT_CALLER_ID_MAX_LENGTH;
$Caller_Id_Max_Length = ($Caller_Id_Max_Length < self::CALLER_ID_MAX_LENGTH_MIN and $Caller_Id_Max_Length != -1) ? self::CALLER_ID_MAX_LENGTH_MIN : $Caller_Id_Max_Length;
if (!empty($callerid)) {
$found = true;
$this->out(sprintf(_("Caller ID before strip_tags: %s, length: %s"), $callerid,strlen($callerid)) . ((function_exists('mb_strlen')) ? (sprintf(_(", mb_strlen: %s"),mb_strlen($callerid))) : ''));
$callerid = trim(strip_tags($callerid));
$this->out(sprintf(_("Caller ID after strip_tags: %s, length: %s"), $callerid,strlen($callerid)) . ((function_exists('mb_strlen')) ? (sprintf(_(", mb_strlen: %s"),mb_strlen($callerid))) : ''));
$stripAccentsCharacters = (isset($options['scheme_settings']['Strip_Accent_Characters'])) ? $options['scheme_settings']['Strip_Accent_Characters'] : 'Y'; // Default to stripping accent character for backward compatibility
$this->out("Strip_Accent_Characters: " . $stripAccentsCharacters);
if ($superfecta->isCharSetIA5() && $stripAccentsCharacters == 'Y') {
$this->out(sprintf(_("Caller ID before stripAccents: %s, length: %s"), $callerid,strlen($callerid)) . ((function_exists('mb_strlen')) ? (sprintf(_(", mb_strlen: %s"),mb_strlen($callerid))) : ''));
$callerid = $superfecta->stripAccents($callerid);
$this->out(sprintf(_("Caller ID after stripAccents: %s, length: %s"), $callerid,strlen($callerid)) . ((function_exists('mb_strlen')) ? (sprintf(_(", mb_strlen: %s"),mb_strlen($callerid))) : ''));
}
//Why?
$this->out(sprintf(_("Caller ID before preg_replace: %s, length: %s"), $callerid,strlen($callerid)) . ((function_exists('mb_strlen')) ? (sprintf(_(", mb_strlen: %s"),mb_strlen($callerid))) : ''));
$callerid = preg_replace("/[\";']/", "", $callerid);
$this->out(sprintf(_("Caller ID after preg_replace: %s, length: %s"), $callerid,strlen($callerid)) . ((function_exists('mb_strlen')) ? (sprintf(_(", mb_strlen: %s"),mb_strlen($callerid))) : ''));
// Display issues on phones and CDR with special characters
// convert CNAM to UTF-8 to fix
$character_encodings = (isset($options['scheme_settings']['Character_Encodings'])) ? $options['scheme_settings']['Character_Encodings'] : self::DEFAULT_CHARACTER_ENCODINGS;
$this->out(sprintf(_("Character Encodings: '%s'"), $character_encodings));
if (in_array('pass',explode(',', $character_encodings))){
$this->out(_("Bypassing character conversion."));
}
elseif(!function_exists('mb_convert_encoding')) {
$this->out(_("Function mb_convert_encoding does not exist."));
}
else{
$this->out(_("Converting result to UTF-8"));
try{
$this->out(sprintf(_("Caller ID before mb_convert_encoding: %s, length: %s"), $callerid,strlen($callerid)) . ((function_exists('mb_strlen')) ? (sprintf(_(", mb_strlen: %s"),mb_strlen($callerid))) : ''));
$callerid = mb_convert_encoding($callerid, "UTF-8", $character_encodings);
$this->out(sprintf(_("Caller ID after mb_convert_encoding: %s, length: %s"), $callerid,strlen($callerid)) . ((function_exists('mb_strlen')) ? (sprintf(_(", mb_strlen: %s"),mb_strlen($callerid))) : ''));
}
catch(Exception $e) {
$this->out(sprintf(_('Caught exception calling mb_convert_encoding: %s'), $e->getMessage()));
}
}
$this->out(sprintf(_("Caller_Id_Max_Length: '%s'"),$Caller_Id_Max_Length));
if ($Caller_Id_Max_Length != -1){
$this->out(sprintf(_("Caller ID before %s: %s, length: %s"), ((function_exists('mb_substr')) ? 'mb_substr' : 'substr'), $callerid,strlen($callerid)) . ((function_exists('mb_strlen')) ? (sprintf(_(", mb_strlen: %s"),mb_strlen($callerid))) : ''));
$callerid = (function_exists('mb_substr')) ? mb_substr($callerid, 0, $Caller_Id_Max_Length) : substr($callerid, 0, $Caller_Id_Max_Length);
$this->out(sprintf(_("Caller ID after %s: %s, length: %s"), ((function_exists('mb_substr')) ? 'mb_substr' : 'substr'), $callerid,strlen($callerid)) . ((function_exists('mb_strlen')) ? (sprintf(_(", mb_strlen: %s"),mb_strlen($callerid))) : ''));
}
else{
$this->out(sprintf(_("Caller ID string length is not limited")));
}
//send off
$superfecta->send_results($callerid);
}
//Set Spam text
$spam_text = ($superfecta->isSpam()) ? $options['scheme_settings']['SPAM_Text'] : '';
if($superfecta->isSpam() && $options['scheme_settings']['SPAM_Text_Substitute'] == 'Y') {
$callerid = $spam_text;
} else {
$callerid = trim($spam_text . " " . $superfecta->get_Prefix() . $callerid);
}
if ($Caller_Id_Max_Length != -1){
$this->out(sprintf(_("Caller ID before %s: %s, length: %s"), ((function_exists('mb_substr')) ? 'mb_substr' : 'substr'), $callerid,strlen($callerid)) . ((function_exists('mb_strlen')) ? (sprintf(_(", mb_strlen: %s"),mb_strlen($callerid))) : ''));
$callerid = (function_exists('mb_substr')) ? mb_substr($callerid, 0, $Caller_Id_Max_Length) : substr($callerid, 0, $Caller_Id_Max_Length);
$this->out(sprintf(_("Caller ID after %s: %s, length: %s"), ((function_exists('mb_substr')) ? 'mb_substr' : 'substr'), $callerid,strlen($callerid)) . ((function_exists('mb_strlen')) ? (sprintf(_(", mb_strlen: %s"),mb_strlen($callerid))) : ''));
}
//Set Spam Destination
$spam_dest = (!empty($options['scheme_settings']['spam_interceptor']) && ($options['scheme_settings']['spam_interceptor'] == 'Y')) ? $options['scheme_settings']['spam_destination'] : '';
$this->spamCount = $this->spamCount + (int)$superfecta->get_SpamCount();
if(!empty($spam_dest) && ($this->spamCount >= (int)$options['scheme_settings']['SPAM_threshold'])) {
$parts = explode(",", $spam_dest);
$this->destination = $parts;
//stop all processing at this point, the spam score is too high
if(!$keepGoing) {
$this->out(sprintf(_("Spam Call, Sending call to: %s"),$spam_dest));
return $callerid;
} else {
$this->out(sprintf(_("Call detected as spam, would send call to: %s"),$spam_dest));
}
}
if(!empty(trim($callerid))) {
if(!$keepGoing) {
$this->out(sprintf(_("Setting caller id to: %s"),$callerid));
return $callerid;
} else {
$this->out(sprintf(_("This scheme would set the caller id to: %s"),$callerid));
}
} else {
$this->out(_("No callerid found"));
}
}
catch(Exception $e) {
$this->out(sprintf(_('Caught exception: %s<br>Skipping scheme %s<br>'), $e->getMessage(), $s['name']));
}
}
if(empty($callerid) && !$keepGoing) {
//No callerid so I guess?
return $trunk_info['calleridname'];
} elseif(empty($callerid) && $keepGoing) {
return false;
} elseif(!empty($callerid) && $keepGoing) {
return $callerid;
}
}
public function getSpamScore() {
return $this->spamCount;
}
public function getDest() {
return $this->destination;
}
public function getSchemeDefaults() {
$defaults = $this->schemeDefaults;
$defaults['processors_list'] = $this->getProcessors();
return $defaults;
}
public function getProcessors() {
$processors_list = array();
foreach (glob(__DIR__ . "/includes/processors/*.php") as $filename) {
$name = explode("_", basename($filename));
include $filename;
$class_name = basename($filename, '.php');
$class_class = new $class_name();
$processors_list[] = array(
"name" => strtoupper($class_class->name),
"description" => $class_class->description,
"filename" => basename($filename),
"selected" => false, //functionality seems strange here
);
unset($class_class);
}
return $processors_list;
}
public function ajaxRequest($req, &$setting) {
switch($req) {
case "power":
case "position":
case "delete":
case "options":
case "save_options":
case "update_sources":
case "update_scheme":
case "copy":
case "sort":
case "debug":
return true;
default:
return false;
}
}
public function ajaxCustomHandler() {
switch($_REQUEST['command']) {
case "debug":
$tel = htmlEntities($_REQUEST['tel']);
$level = htmlEntities($_REQUEST['level']);
$schem = htmlEntities($_REQUEST['scheme']);
$thedid = htmlEntities($_REQUEST['thedid']);
if (empty($thedid)){
$thedid = '5555555555';
}
echo "<span class='header'>"._('Debug is on and set at level:')."</span> ". $level."</br>";
echo "<span class='header'>"._('The DID:')."</span> ".$thedid."</br>";
echo "<span class='header'>"._('The Original Number:')."</span> ".$tel."</br>";
echo "<span class='header'>"._('The Scheme:')."</span> ".$schem."</br>";
echo "<span class='header'>"._('Scheme Type:')."</span> SINGLEFECTA</br>";
echo "<span class='header'>"._('Debugging Enabled, will not stop after first result')."</span></br>";
echo "</br>";
$time_start = microtime(true);
$callerid = $this->execute($schem,array(
'callerid' => $tel,
'did' => $thedid,
'extension'=> $thedid,
'calleridname' => 'CID Superfecta!',
), $level ,true);
$time_end = microtime(true);
echo "</br>";
echo "<span class='header'>"._('Returned Result would be:')."</span>".$callerid."</br>";
echo "<span class='header'>".sprintf(_('result took %s seconds'),$time_end - $time_start)."</span>";
return true;
}
}
public function ajaxHandler() {
switch($_REQUEST['command']) {
case "debug":
return false;
case "sort":
$oper = $_POST['position'] == 'up' ? "-" : "+";
$sql = "UPDATE superfectaconfig SET value = ABS(value ".$oper." 11) WHERE source = ? AND field = 'order'";
$sth = $this->Database->prepare($sql);
$sth->execute(array('base_'.$_REQUEST['scheme']));
$this->reorderSchemes();
return array("status" => true);
case "copy":
$scheme = $_REQUEST['scheme'];
$int = rand(1,10);
/** GET SCHEME CONFIGS **/
$sql = "SELECT * FROM superfectaconfig WHERE source = ?";
$sth = $this->Database->prepare($sql);
$sth->execute(array('base_'.$scheme));
$options = $sth->fetchAll(PDO::FETCH_ASSOC);
$sql = "INSERT INTO superfectaconfig (source, field, value) VALUES (?,?,?)";
$sth = $this->Database->prepare($sql);
foreach($options as $option) {
$source = preg_replace('/^base_'.$scheme.'/','base_'.$scheme.'copy'.$int,$option['source']);
$sth->execute(array($source,$option['field'],$option['value']));
}
/** GET MODULE CONFIGS **/
$sql = "SELECT * FROM superfectaconfig WHERE source LIKE ?";
$sth = $this->Database->prepare($sql);
$sth->execute(array($scheme.'\_%'));
$options = $sth->fetchAll(PDO::FETCH_ASSOC);
$sql = "INSERT INTO superfectaconfig (source, field, value) VALUES (?,?,?)";
$sth = $this->Database->prepare($sql);
foreach($options as $option) {
$source = preg_replace('/^'.$scheme.'_/','base_'.$scheme.'copy'.$int.'_',$option['source']);
$sth->execute(array($source,$option['field'],$option['value']));
}
$this->reorderSchemes();
return array("status" => true, "redirect" => "config.php?display=superfecta&action=edit&scheme=".$scheme.'copy'.$int);
case "update_scheme":
$data = array(
"enable_interceptor" => $_POST['enable_interceptor'] == "on",
"scheme_name" => preg_replace('/\s/i', '_', preg_replace('/\+/i', '_', trim($_POST['scheme_name']))),
"scheme_name_orig" => $_POST['scheme_name_orig'],
"DID" => $_POST['DID'],
"CID_rules" => $_POST['CID_rules'],
"Prefix_URL" => $_POST['Prefix_URL'],
"Curl_Timeout" => $_POST['Curl_Timeout'],
"SPAM_Text" => $_POST['SPAM_Text'],
"SPAM_Text_Substitute" => $_POST['SPAM_Text_Substitute'] == "on" ? 'Y' : 'N',
"processor" => utf8_decode($_POST['processor']),
"multifecta_timeout" => utf8_decode($_POST['multifecta_timeout']),
"SPAM_threshold" => $_POST['SPAM_threshold'],
"Character_Encodings" => $_POST['Character_Encodings'],
"Strip_Accent_Characters" => $_POST['Strip_Accent_Characters'] == "on" ? 'Y' : 'N',
"Caller_Id_Max_Length" => ($_POST['Caller_Id_Max_Length'] < self::CALLER_ID_MAX_LENGTH_MIN and $_POST['Caller_Id_Max_Length'] != -1) ? self::CALLER_ID_MAX_LENGTH_MIN : $_POST['Caller_Id_Max_Length'],
);
$type = $_POST['goto0'];
$data['destination'] = !empty($type) ? $_POST[$type.'0'] : '';
//see if the scheme name has changed, and make sure that there isn't already one named the new name.
if(empty($data['scheme_name'])) {
return array("status" => false, "message" => _("Scheme names cannot be blank"));
}
$ret = $this->updateScheme($data['scheme_name_orig'],$data);
if(!$ret['status']) {
return array("status" => false, "message" => $ret['message']);
}
if($data['scheme_name'] != $data['scheme_name_orig']) {
return array("status" => true, "redirect" => "config.php?display=superfecta&action=edit&scheme=".$data['scheme_name']);
} else {
return array("status" => true, "redirect" => "");
}
//add ordering information to database if this scheme doesn't have it
$highest_order = 0;
$already_has_order = false;
$sql = "SELECT source,ABS(value) FROM superfectaconfig WHERE field = 'order' ORDER BY ABS(value)";
$results = sql($sql, "getAll");
foreach($results as $val) {
if($val[0] == "base_".$scheme_name)
{
$already_has_order = true;
break;
}
$highest_order = $val[1];
}
if(!$already_has_order) {
$sql = "REPLACE INTO superfectaconfig (source,field,value) VALUES('base_".$scheme_name."','order',".($highest_order+1).")";
sql($sql);
}
break;
case "update_sources":
$sources = isset($_REQUEST['data'])?implode(",", $_REQUEST['data']):'';
$sql = "REPLACE INTO superfectaconfig (value, source, field) VALUES(?, ?, 'sources')";
$sth = $this->Database->prepare($sql);
$sth->execute(array($sources, 'base_'.$_REQUEST['scheme']));
return array("success" => true);
case "power":
$data = preg_replace('/^scheme_/i', '', $_REQUEST['scheme']);
$sql = "UPDATE superfectaconfig SET value = (value * -1) WHERE field = 'order' AND source = ?";
$sth = $this->Database->prepare($sql);
$sth->execute(array('base_'.$data));
return array("status" => true);
case "delete":
$sql = "DELETE FROM superfectaconfig WHERE source LIKE ?";
$sth = $this->Database->prepare($sql);
$sth->execute(array('base_'.$_REQUEST['scheme']));
$sth->execute(array('base_'.$_REQUEST['scheme'].'\_%'));
$this->reorderSchemes();
return array("status" => true);
case "save_options":
include(__DIR__."/includes/superfecta_base.php");
$path = __DIR__;
include $path.'/sources/source-'.$_REQUEST['source'].'.module';
if(!class_exists($_REQUEST['source'])) {
return array("status" => false);
}
$module = new $_REQUEST['source'];
$params = $module->source_param;
$scheme = $_REQUEST['scheme'];
$source = $_REQUEST['source'];
$sql = "REPLACE INTO superfectaconfig (source,field,value) VALUES (?, ?, ?)";
$sth = $this->Database->prepare($sql);
foreach($params as $key => $data) {
if (strcmp($data['type'], 'internal') != 0) {
$sth->execute(array($scheme . "_" . $source, $key, $_POST[$key]));
}
}
return array("status" => true);
case "options":
include(__DIR__."/includes/superfecta_base.php");
$scheme = $_REQUEST['scheme'];
$source = $_REQUEST['source'];
$sql = "SELECT field, value FROM superfectaconfig WHERE source = ?";
$sth = $this->Database->prepare($sql);
$sth->execute(array($scheme . "_" . $source));
$n_settings = $sth->fetchAll(PDO::FETCH_KEY_PAIR);
$path = __DIR__;
include $path.'/sources/source-'.$_REQUEST['source'].'.module';
if(!class_exists($_REQUEST['source'])) {
return array("status" => false);
}
$module = new $_REQUEST['source'];
$params = $module->source_param;
$form_html = '<form id="form_options_'.$_REQUEST['source'].'" action="ajax.php?module=superfecta&command=save_options&scheme='.urlencode($scheme).'&source='.$source.'" method="post">';
foreach($params as $key => $data) {
$form_html .= '<div class="form-group">';
$default = isset($data['default']) ? $data['default'] : '';
switch($data['type']) {
case "text":
$value = isset($n_settings[$key]) ? $n_settings[$key] : $default;
$form_html .= '<label for="'.$key.'">'.str_replace("_", " ", $key).'</label><a class="info"><span>'.$data['description'].'</span></a>';
$form_html .= '<input type="text" class="form-control" name="'.$key.'" id="'.$key.'" value="'.$value.'"/>';
break;
case "password":
$value = isset($n_settings[$key]) ? $n_settings[$key] : $default;
$form_html .= '<label for="'.$key.'">'.str_replace("_", " ", $key).'</label><a class="info"><span>'.$data['description'].'</span></a>';
$form_html .= '<input type="password" class="form-control" name="'.$key.'" id="'.$key.'" value="'.$value.'"/>';
break;
case "checkbox":
$checked = $default;
if(isset($n_settings[$key])) {
if($n_settings[$key] == 'on') {
$checked = 'checked';
} else {
$checked = '';
}
}
$form_html .= '<label for="'.$key.'">'.str_replace("_", " ", $key).'</label><a class="info"><span>'.$data['description'].'</span></a>';
$form_html .= '<br/><span class="radioset">';
$form_html .= '<input type="radio" id="'.$key.'_yes" name="'.$key.'"value="on" '.($checked == 'checked' ? 'checked' : '').'>';
$form_html .= '<label for="'.$key.'_yes">'._('Yes').'</label>';
$form_html .= '<input type="radio" id="'.$key.'_no" name="'.$key.'"value="off" '.($checked != 'checked' ? 'checked' : '').'>';
$form_html .= '<label for="'.$key.'_no">'._('No').'</label>';
$form_html .= '</span>';
break;
case "textarea":
$value = isset($n_settings[$key]) ? $n_settings[$key] : $default;
$form_html .= '<label for="'.$key.'">'.str_replace("_", " ", $key).'</label><a class="info"><span>'.$data['description'].'</span></a>';
$form_html .= '<textarea for="'.$key.'"area name="'.$key.'" class="form-control" rows="5" id="'.$key.'">'.$value.'</textarea>';
break;
case "number":
$value = isset($n_settings[$key]) ? $n_settings[$key] : $default;
$form_html .= '<label for="'.$key.'">'.str_replace("_", " ", $key).'</label><a class="info"><span>'.$data['description'].'</span></a>';
$form_html .= '<input type="number" class="form-control" name="'.$key.'" id="'.$key.'" value="'.$value.'" /></td>';
break;
case "info":
$form_html .= $default;
break;
case "select":
$value = isset($n_settings[$key]) ? $n_settings[$key] : $default;
$form_html .= '<label for="'.$key.'">'.str_replace("_", " ", $key).'</label><a class="info"><span>'.$data['description'].'</span></a>';
$form_html .= '<select name="'.$key.'" class="form-control" id="'.$key.'">';
foreach($data['option'] as $options_k => $options_l) {
$selected = ($value == $options_k) ? 'selected' : '';
$form_html .= "<option value=".$options_k." ".$selected.">".$options_l."</option>";
}
$form_html .= "</select>";
break;
default:
break;
}
$form_html .= '</div>';
}
return array("status" => true, "title" => str_replace('_', ' ', $_REQUEST['source']), "html" => $form_html);
}
}
public function reorderSchemes() {
$sql = "SELECT * FROM superfectaconfig WHERE field = 'order' ORDER BY CONVERT(value, SIGNED INTEGER)";
$start = 1;
$sth = $this->Database->prepare($sql);
$sth->execute();
$results = $sth->fetchAll(PDO::FETCH_ASSOC);
foreach($results as $result) {
$sql = "UPDATE superfectaconfig SET value = ? WHERE source = ? AND field = 'order'";
$sth = $this->Database->prepare($sql);
$sth->execute(array($start*10, $result['source']));
$start++;
}
}
public function getAllPoweredSchemes() {
$allSchemes = $this->getAllSchemes();
$schemes = array();
foreach($allSchemes as $scheme) {
if($scheme['powered']) {
$schemes[] = $scheme;
}
}
return $schemes;
}
public function getAllSchemes() {
$sql = "SELECT source as scheme, value as powered FROM superfectaconfig WHERE source LIKE 'base\_%' AND field = 'order' ORDER BY ABS(CONVERT(value, SIGNED INTEGER))";
$sth = $this->Database->prepare($sql);
$sth->execute();
$results = $sth->fetchAll(PDO::FETCH_ASSOC);
$i = 1;
$scheme_list = array();
$total = count($results);
foreach ($results as $data) {
$scheme_list[$i] = $data;
$scheme_list[$i]['name'] = substr($data['scheme'], 5);
$scheme_list[$i]['showdown'] = $i == $total ? FALSE : TRUE;
$scheme_list[$i]['showup'] = $i == 1 ? FALSE : TRUE;
$scheme_list[$i]['showdelete'] = true;
$scheme_list[$i]['powered'] = $data['powered'] < 0 ? FALSE : TRUE;
$i++;
}
return $scheme_list;
}
public function addScheme($scheme, $data = array()) {
if(empty($scheme)) {
return array("status" => false, "message" => _("Scheme can not be empty!"));
}
$res = $this->getScheme($scheme);
if(!empty($res)) {
return array("status" => false, "message" => _("You cannot create a scheme the same name as an existing scheme"));
}
$data['order'] = 200;
$data['scheme_name'] = $scheme;
return $this->updateScheme($scheme,$data);
}
public function updateScheme($scheme, $data = array()) {
if($data['scheme_name'] != $scheme) {
$res = $this->getScheme($data['scheme_name']);
if(!empty($res)) {
return array("status" => false, "message" => _("You cannot rename a scheme the same thing as an existing scheme"));
} else {
$sql = "UPDATE superfectaconfig SET source = REPLACE(source, ?, ?) WHERE source LIKE ?";
$sth = $this->Database->prepare($sql);
$sth->execute(array('base_'.$scheme, 'base_'.$data['scheme_name'], 'base_'.$scheme));
$sth->execute(array('base_'.$scheme.'_', 'base_'.$data['scheme_name'].'_', 'base_'.$scheme.'\_%'));
$sql = "UPDATE superfecta_to_incoming SET scheme = ? WHERE scheme = ?";
$sth = $this->Database->prepare($sql);
$sth->execute(array('base_'.$data['scheme_name'], 'base_'.$scheme));
$scheme = 'base_'.$data['scheme_name'];
}
} else {
$scheme = 'base_'.$data['scheme_name'];
}
$sql = "REPLACE INTO superfectaconfig (source,field,value) VALUES(?,?,?)";
$sth = $this->Database->prepare($sql);
$sth->execute(array($scheme,'spam_interceptor',(!empty($data['enable_interceptor']) && $data['enable_interceptor'] == 'Y' ? 'Y' : 'N')));
$sth->execute(array($scheme,'spam_destination',$data['destination']));
$sth->execute(array($scheme,'Prefix_URL',$data['Prefix_URL']));
$sth->execute(array($scheme,'Curl_Timeout',$data['Curl_Timeout']));
$sth->execute(array($scheme,'processor',$data['processor']));
$sth->execute(array($scheme,'multifecta_timeout',$data['multifecta_timeout']));
$sth->execute(array($scheme,'SPAM_Text',$data['SPAM_Text']));
$sth->execute(array($scheme,'SPAM_Text_Substitute',(!empty($data['SPAM_Text_Substitute']) && $data['SPAM_Text_Substitute'] == 'Y' ? 'Y' : 'N')));
$sth->execute(array($scheme,'DID',$data['DID']));
$sth->execute(array($scheme,'CID_rules',$data['CID_rules']));
$sth->execute(array($scheme,'SPAM_threshold',$data['SPAM_threshold']));
$sth->execute(array($scheme,'Character_Encodings',(!empty($data['Character_Encodings']) ? $data['Character_Encodings'] : self::DEFAULT_CHARACTER_ENCODINGS)));
$sth->execute(array($scheme,'Strip_Accent_Characters',(!empty($data['Strip_Accent_Characters']) && $data['Strip_Accent_Characters'] == 'Y' ? 'Y' : 'N')));
$sth->execute(array($scheme,'Caller_Id_Max_Length',$data['Caller_Id_Max_Length']));
if(isset($data['order'])) {
$sth->execute(array($scheme,'order',$data['order']));
}
return array("status" => true);
}
public function bulkhandler_superfecta_cfg($settings) {
global $db;
$sfenable = $settings['sf_enable'];
if (isset($sfenable) && !empty($sfenable) && (strtolower($sfenable) == 'true')) {
if (!isset($settings['sf_scheme']) || empty($settings['sf_scheme'])) {
$sfscheme = 'ALL|ALL'; //default scheme
} else if (strstr($settings['sf_scheme'],'ALL')) {
$sfscheme = 'ALL|ALL'; //default scheme
} else {
$sfscheme = $settings['sf_scheme'];
$res = $this->getScheme(trim($sfscheme));
if(!$res || empty($res)) {
dbug("bulkhandler_scheme_cfg: Invalid superfecta scheme ".$sfscheme);
return;
}
$sfscheme = 'base_'.$sfscheme;
}
$invalidDIDChars = array('<', '>');
$settings['extension'] = trim(str_replace($invalidDIDChars, "", $settings['extension']));
$settings['cidnum'] = trim(str_replace($invalidDIDChars, "", $settings['cidnum']));
$sql = "REPLACE INTO superfecta_to_incoming (extension, cidnum, scheme) values (:extension, :cidnum,:superfecta_scheme)";
$q = $db->prepare($sql);
$q->bindParam(':extension', $settings['extension'], \PDO::PARAM_STR);
$q->bindParam(':cidnum', $settings['cidnum'], \PDO::PARAM_STR);
$q->bindParam(':superfecta_scheme', $sfscheme, \PDO::PARAM_STR);
$q->execute();
dbug("bulkhandler_scheme_cfg: superfecta scheme ".$sfscheme. " enabled for incoming did".$settings['extension']);
}
}
public function getScheme($scheme) {
//strip off base if it's sent to us we dont need it
$scheme = preg_replace('/^base_/','',$scheme);
//set some default values for creating a new scheme
$sql = "SELECT field, value FROM superfectaconfig WHERE source = ?";
$sth = $this->Database->prepare($sql);
$sth->execute(array('base_'.$scheme));
$return = $sth->fetchAll(PDO::FETCH_KEY_PAIR);
if(empty($return)) {
return false;
}
foreach($this->schemeDefaults as $key => $value) {
if($key == 'SPAM_Text_Substitute' || $key == 'spam_interceptor') {
if(!isset($return[$key])) {
$return[$key] = $key;
} else {
$return[$key] = ($return[$key] == 'Y');
}
} else {
$return[$key] = !isset($return[$key]) ? $value : $return[$key];
}
}
$return['name'] = $scheme;
$return['sources'] = !empty($return['sources']) ? explode(',', $return['sources']) : array();
return $return;
}
public function getSchemeAllModuleSettings($scheme) {
$sql = "SELECT source, field, value FROM superfectaconfig WHERE source LIKE ?";
$sth = $this->Database->prepare($sql);
$sth->execute(array($scheme.'\_%'));
$results = $sth->fetchAll(PDO::FETCH_ASSOC);
$return = array();
foreach($results as $result) {
$result['source'] = preg_replace('/^'.$scheme.'_/i','',$result['source']);
if(trim($result['value']) == 'off') {
continue;
}
$return[$result['source']][$result['field']] = $result['value'];
}
return $return;
}
public function getSchemeModuleSettings($scheme, $module) {
$sql = "SELECT source, field, value FROM superfectaconfig WHERE source LIKE ?";
$sth = $this->Database->prepare($sql);
$sth->execute(array($scheme.'\_'.$module.'\_%'));
$results = $sth->fetchAll(PDO::FETCH_ASSOC);
$return = array();
foreach($results as $result) {
$result['source'] = preg_replace('/^'.$scheme.'_/i','',$result['source']);
if(trim($result['value']) == 'off') {
continue;
}
$return[$result['source']][$result['field']] = $result['value'];
}
return $return;
}
public function getActionBar($request) {
$buttons = array();
$request['action'] = !empty($request['action']) ? $request['action'] : "";
switch($request['action']) {
case 'add':
$buttons = array(
'reset' => array(
'name' => 'reset',
'id' => 'reset',
'value' => _('Reset')
),
'submit' => array(
'name' => 'submit',
'id' => 'submit',
'value' => _('Submit')
)
);
break;
}
return $buttons;
}
public function didList($id = false){
$sql = "SELECT superfecta_to_incoming_id, a.extension extension, a.cidnum cidnum, pricid, scheme FROM superfecta_to_incoming a
INNER JOIN incoming b
ON a.extension = b.extension AND a.cidnum = b.cidnum
";
$vars = [];
if ($id !== false && ctype_digit($id)) {
$sql .= " WHERE superfecta_to_incoming_id = :id";
$vars = [':id' => $id];
}
$stmt = $this->Database->prepare($sql);
$stmt->execute($vars);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
return is_array($results) ? $results : array();
}
}