-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathContactmanager.class.php
4115 lines (3752 loc) · 135 KB
/
Contactmanager.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
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
// 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 2014 Schmooze Com Inc.
//
namespace FreePBX\modules;
include __DIR__.'/vendor/autoload.php';
use BMO;
use FreePBX_Helpers;
use Exception;
use UnexpectedValueException;
use PDO;
use libphonenumber\PhoneNumberUtil;
use libphonenumber\NumberParseException;
use libphonenumber\PhoneNumberFormat;
use libphonenumber\ShortNumberInfo;
class Contactmanager extends FreePBX_Helpers implements BMO {
private $message = '';
private $lookupCache = array();
private $contactsCache = array();
private $types = array();
private $groupCache = array();
private $groupsCache = array();
private $token = null;
private $cachedSpeedDials = array();
public $tmp;
private $maxAvatar = 200; //this needs to be set in advanced settings (1-2048)
private $displayNameTemplateCreator = '';
private $userNameTemplateCreator = '';
public function __construct($freepbx = null) {
$this->db = $freepbx->Database;
$this->freepbx = $freepbx;
$this->userman = $this->freepbx->Userman;
$this->types = array(
"internal" => array(
"name" => _("Internal"),
"fields" => array(
"displayname" => _("Display Name"),
"fname" => _("First Name"),
"lname" => _("Last Name"),
"username" => _("User"),
"actions" => _("Actions")
)
),
"external" => array(
"name" => _("External"),
"fields" => array(
"displayname" => _("Display Name"),
"company" => _("Company"),
"numbers" => _("Numbers"),
"actions" => _("Actions")
)
),
"private" => array(
"name" => _("Private"),
"fields" => array(
"displayname" => _("Display Name"),
"company" => _("Company"),
"numbers" => _("Numbers"),
"actions" => _("Actions")
)
)
);
$this->tmp = $this->freepbx->Config->get("ASTSPOOLDIR") . "/tmp";
// method_exists it is necessary for compatibility with previous versions
// of the userman module 15.0.68 or 16.0.25.31
$this->displayNameTemplateCreator = (method_exists($this->userman, 'getDispalyNameTemplateCreator')) ? $this->userman->getDispalyNameTemplateCreator() : 'Template Creator';
$this->userNameTemplateCreator = (method_exists($this->userman, 'getUserNameTemplateCreator')) ? $this->userman->getUserNameTemplateCreator() : 'FreePBXUCPTemplateCreator';
}
public function setDatabase($pdo){
$this->db = $pdo;
return $this;
}
public function resetDatabase(){
$this->db = $this->freepbx->Database;
return $this;
}
public function ucpDelGroup($id,$display,$data) {
}
public function ucpAddGroup($id, $display, $data) {
$this->ucpUpdateGroup($id,$display,$data);
}
public function ucpUpdateGroup($id,$display,$data) {
if($display == 'userman' && isset($_POST['type']) && $_POST['type'] == 'group') {
if(!empty($_POST['contactmanager_speeddial_enable']) && $_POST['contactmanager_speeddial_enable'] == "yes") {
$this->freepbx->Ucp->setSettingByGID($id,'Contactmanager','speeddial',true);
} else {
$this->freepbx->Ucp->setSettingByGID($id,'Contactmanager','speeddial',false);
}
}
}
/**
* Hook functionality from userman when a user is deleted
* @param {int} $id The userman user id
* @param {string} $display The display page name where this was executed
* @param {array} $data Array of data to be able to use
*/
public function ucpDelUser($id, $display, $ucpStatus, $data) {
}
/**
* Hook functionality from userman when a user is added
* @param {int} $id The userman user id
* @param {string} $display The display page name where this was executed
* @param {array} $data Array of data to be able to use
*/
public function ucpAddUser($id, $display, $ucpStatus, $data) {
$this->ucpUpdateUser($id, $display, $ucpStatus, $data);
}
/**
* Hook functionality from userman when a user is updated
* @param {int} $id The userman user id
* @param {string} $display The display page name where this was executed
* @param {array} $data Array of data to be able to use
*/
public function ucpUpdateUser($id, $display, $ucpStatus, $data) {
if($display == 'userman' && isset($_POST['type']) && $_POST['type'] == 'user') {
if(!empty($_POST['contactmanager_speeddial_enable']) && $_POST['contactmanager_speeddial_enable'] == "yes") {
$this->freepbx->Ucp->setSettingByID($id,'Contactmanager','speeddial',true);
} elseif(!empty($_POST['contactmanager_speeddial_enable']) && $_POST['contactmanager_speeddial_enable'] == "no") {
$this->freepbx->Ucp->setSettingByID($id,'Contactmanager','speeddial',false);
} elseif(!empty($_POST['contactmanager_speeddial_enable']) && $_POST['contactmanager_speeddial_enable'] == "inherit") {
$this->freepbx->Ucp->setSettingByID($id,'Contactmanager','speeddial',null);
}
}
}
public function ucpConfigPage($mode, $user, $action) {
if(empty($user)) {
$speeddial = ($mode == 'group') ? true : null;
} else {
if($mode == "group") {
$speeddial = $this->freepbx->Ucp->getSettingByGID($user['id'],'Contactmanager','speeddial');
$speeddial = !($speeddial) ? false : true;
} else {
$speeddial = $this->freepbx->Ucp->getSettingByID($user['id'],'Contactmanager','speeddial');
}
}
$html[0] = array(
"title" => _("Contact Manager"),
"rawname" => "contactmanager",
"content" => load_view(dirname(__FILE__)."/views/ucp_config.php",array("speeddial" => $speeddial, "mode" => $mode))
);
return $html;
}
public function usermanAddContactInfo($user) {
if(empty($this->allImages)) {
$sql = "SELECT * FROM contactmanager_entry_userman_images";
$sth = $this->db->prepare($sql);
$sth->execute();
$tmp = $sth->fetchAll(PDO::FETCH_ASSOC);
$this->allImages = array();
foreach($tmp as $t) {
$this->allImages[$t['uid']] = true;
}
}
if(isset($user['id']) && !empty($this->allImages[$user['id']])) {
$user['image'] = true;
}
return $user;
}
public function install() {
global $db;
$fcc = new \featurecode('contactmanager', 'app-contactmanager-sd');
$fcc->setDescription('Contact Manager Speed Dials');
$fcc->setDefault('*10');
$fcc->setProvideDest();
$fcc->update();
unset($fcc);
$sql = "SELECT * FROM contactmanager_groups WHERE type = 'userman'";
$sth = $this->db->prepare($sql);
$sth->execute();
$oldgrps = $sth->fetchAll(PDO::FETCH_ASSOC);
$sql = "UPDATE contactmanager_groups SET type = 'internal' WHERE type = 'userman'";
$sth = $this->db->prepare($sql);
$sth->execute();
$sql = "UPDATE contactmanager_group_entries SET `uuid` = UUID() WHERE `uuid` IS NULL";
$sth = $this->db->prepare($sql);
$sth->execute();
$info = $this->freepbx->Modules->getInfo("contactmanager");
$newinstall = ($info['contactmanager']['status'] == MODULE_STATUS_NOTINSTALLED);
if(empty($oldgrps) && $newinstall) {
$ret = $this->addGroup(_("User Manager Group"),"internal");
$defaultgrp = $ret['id'];
} elseif(isset($oldgrps[0])) {
$defaultgrp = $oldgrps[0]['id'];
}
if(!empty($info['contactmanager']['dbversion']) && version_compare_freepbx($info['contactmanager']['dbversion'],"13.0.37","<")) {
$sql = "SELECT e.* FROM contactmanager_group_entries e, contactmanager_groups g WHERE type = 'internal' AND e.groupid = g.id";
$sth = $this->db->prepare($sql);
$sth->execute();
$entries = $sth->fetchAll(PDO::FETCH_ASSOC);
foreach($entries as $entry) {
$uid = $entry['user'];
$gs = $this->userman->getModuleSettingByID($uid,"contactmanager","showingroups");
$gs = is_array($gs) ? $gs : array();
if(!in_array($entry['groupid'],$gs)) {
$gs[] = $entry['groupid'];
}
$this->userman->setModuleSettingByID($uid,"contactmanager","showingroups", $gs);
}
}
if(isset($defaultgrp) && !$newinstall) {
//Now scan all the old users/groups from userman and get the setting
$users = $this->userman->getAllUsers();
foreach($users as $user) {
$show = $this->userman->getModuleSettingByID($user['id'],"contactmanager","show");
if($show) {
$gs = $this->userman->getModuleSettingByID($user['id'],"contactmanager","showingroups");
$gs = is_array($gs) ? $gs : array();
if(!in_array($defaultgrp,$gs)) {
$gs[] = $defaultgrp;
}
$this->userman->setModuleSettingByID($user['id'],"contactmanager","showingroups", $gs);
}
$this->usermanUpdateUser($user['id'],'',$user);
}
$groups = $this->userman->getAllGroups();
foreach($groups as $group) {
$show = $this->userman->getModuleSettingByGID($group['id'],"contactmanager","show");
if($show) {
$this->userman->setModuleSettingByGID($group['id'],"contactmanager","showingroups", array($defaultgrp));
}
$this->usermanUpdateGroup($group['id'],'',$group);
}
} elseif($newinstall) {
$id = $this->freepbx->Userman->getAutoGroup();
$id = !empty($id) ? $id : 1;
$group = $this->freepbx->Userman->getGroupByGID($id);
if(!empty($group)) {
$this->userman->setModuleSettingByGID($id,"contactmanager","showingroups", array($defaultgrp));
$this->usermanUpdateGroup($id,'',$group);
}
}
$sql = "SELECT i.*, e.user FROM contactmanager_entry_images i, contactmanager_group_entries e, contactmanager_groups g WHERE i.entryid = e.id AND e.groupid = g.id AND g.type = 'internal'";
$sth = $this->db->prepare($sql);
$sth->execute();
$entries = $sth->fetchAll(PDO::FETCH_ASSOC);
$sql = "INSERT INTO contactmanager_entry_userman_images (`uid`,`image`,`format`,`gravatar`) VALUES (:uid, :image, :format, :gravatar)";
$sth = $this->db->prepare($sql);
$sql1 = "DELETE FROM contactmanager_entry_images WHERE entryid = :id";
$sth1 = $this->db->prepare($sql1);
foreach($entries as $entry) {
try {
$sth->execute(array(
"uid" => $entry['user'],
"image" => $entry['image'],
"format" => $entry['format'],
"gravatar" => $entry['gravatar']
));
} catch(Exception $e) {}
$sth1->execute(array("id" => $entry['entryid']));
}
if(!$this->getConfig("strippedUpgrade2")) {
set_time_limit(0);
$users = $this->userman->getAllUsers();
$groups = $this->getGroups();
$groupIds = [];
foreach($users as $user) {
$showingroups = $this->freepbx->Userman->getCombinedModuleSettingByID($user['id'],'contactmanager','showingroups');
$showingroups = is_array($showingroups) ? $showingroups : array();
foreach ($groups as $group) {
if ($group['type'] != 'internal') {
continue;
}
$groupIds[] = $group['id'];
if (in_array($group['id'],$showingroups) || in_array("*",$showingroups)) {
$user['extraData'] = $user;
$user['user'] = $user['id'];
$this->updateUsermanEntryByGroupID($group['id'], $this->transformUsermanDataToEntry($user), false);
} else {
$entries = $this->getEntriesByGroupID($group['id']);
foreach ($entries as $entryid => $entry) {
if ($entry['user'] == $user['id']) {
$this->deleteEntryByID($entryid);
}
}
}
}
}
$this->updateContactUpdatedDetails(-1, array_unique($groupIds));
$groups = $this->getGroups();
$phoneUtil = PhoneNumberUtil::getInstance();
foreach($groups as $group) {
$entries = $this->getEntriesByGroupID($group['id']);
foreach($entries as $entry) {
if(empty($entry['numbers'])) {
continue;
}
$this->deleteNumbersByEntryID($entry['uid']);
foreach($entry['numbers'] as &$number) {
if(empty($number['locale']) && $number['type'] !== 'internal') {
$number['locale'] = '';
}
}
$this->addNumbersByEntryID($entry['uid'], $entry['numbers']);
}
}
$this->setConfig("strippedUpgrade2",true);
}
$set['module'] = 'contactmanager'; //This will help delete the settings when module is uninstalled
$set['category'] = 'Contact Manager Module';
// CONTACTMANLOOKUPLENGTH in Advanced Settings of FreePBX
$set['value'] = 7;
$set['defaultval'] =& $set['value'];
$set['readonly'] = 0;
$set['hidden'] = 0;
$set['level'] = 1;
$set['emptyok'] = 0;
$set['name'] = 'Partial Match Length';
$set['description'] = 'How many digits should a number be before a partial match is used when looking up a contact';
$set['type'] = CONF_TYPE_INT;
$set['options'] = array(1,86400);
$this->freepbx->Config->define_conf_setting('CONTACTMANLOOKUPLENGTH',$set,true);
// ENABLE_FAVORITE_CONTACTS in Advanced Settings of FreePBX
$set['value'] = false;
$set['defaultval'] =& $set['value'];
$set['options'] = '';
$set['name'] = 'Enable Favorite Contacts';
$set['description'] = 'When Enabled, Admin can configure multiple Favorite Contact Lists under Favorites tab in Contact Manager and Sangoma Phone users can see a list of their favorite contacts when viewing the Contacts panel on the desktop client. Users will be able to manage their Favorites through UCP, based on the settings they have set in User Manager -> Contact Manager. When Disabled, the Favorites section will be hidden on Admin Panel, desktop clients and Contacts panel in UCP. In either case, the user will still be able to Search among the system contacts.';
$set['emptyok'] = 0;
$set['level'] = 1;
$set['readonly'] = 0;
$set['type'] = CONF_TYPE_BOOL;
$set['hidden'] = 0;
$this->freepbx->Config->define_conf_setting('ENABLE_FAVORITE_CONTACTS',$set,true);
}
public function uninstall() {
}
public function doDialplanHook(&$ext, $engine, $priority) {
$contextname = 'app-contactmanager-sd';
$fcc = new \featurecode('contactmanager', $contextname);
$code = $fcc->getCodeActive();
unset($fcc);
if (!empty($code)) {
$this->syncSpeedDials();
$entries = $this->getAllSpeedDials();
foreach($entries as $entry) {
$ext->add('ext-contactmanager-sd', $code.$entry['speeddial'], '', new \ext_goto($contextname.',${EXTEN},1'));
}
$ext->add($contextname, "_".$code."X!", '', new \ext_answer());
$ext->add($contextname, "_".$code."X!", '', new \ext_macro('user-callerid'));
$ext->add($contextname, "_".$code."X!", '', new \ext_gotoif('$[${DB_EXISTS(CM/speeddial/${EXTEN:'.strlen($code).'})}=1]','from-internal,${DB(CM/speeddial/${EXTEN:'.strlen($code).'})},1'));
$ext->add($contextname, "_".$code."X!", '', new \ext_goto('bad-number,s,1'));
$ext->addInclude('from-internal-additional', $contextname);
}
}
public static function myDialplanHooks() {
return 400;
}
/**
* Get the Contact Image URL
* @param integer $did The incoming DID to lookup
* @param integer $ext The local extension to use for lookups
* @return string The link to return
*/
public function getExternalImageUrl($did,$ext=null) {
if(!empty($ext)) {
return 'ajax.php?module=contactmanager&command=image&token='.$this->getToken().'&ext='.$ext.'&did='.$did;
} else {
return 'ajax.php?module=contactmanager&command=image&token='.$this->getToken().'&did='.$did;
}
}
/**
* Get Token for unauthenticated Ajax requests
* Will generate a token if one does not exist
* @return string The Token
*/
public function getToken() {
if(!empty($this->token)) {
return $this->token;
}
$this->token = $this->getConfig("token");
if(empty($this->token)) {
$this->token = bin2hex(openssl_random_pseudo_bytes(16));
$this->setConfig("token",$this->token);
}
return $this->token;
}
public function ajaxRequest($req, &$setting) {
switch ($req) {
case 'image':
$setting['authenticate'] = false;
$setting['allowremote'] = true;
case 'limage':
case 'uploadimage':
case 'delimage':
case 'grid':
case 'favorite_list':
case 'getgravatar':
case 'checksd':
case 'sdgrid':
case 'delete':
return true;
break;
}
return false;
}
public function ajaxCustomHandler() {
switch($_REQUEST['command']) {
case "image":
$token = !empty($_REQUEST['token']) ? $_REQUEST['token'] : "";
$stoken = $this->getToken();
if($token != $stoken) {
header('HTTP/1.0 403 Forbidden');
return true;
}
case "limage":
$entryid = !empty($_REQUEST['entryid']) ? $_REQUEST['entryid'] : null;
$type = !empty($_REQUEST['type']) ? $_REQUEST['type'] : null;
$this->displayContactImage($entryid, $type);
return true;
break;
}
}
/**
* Lookup a Contact Image
* @method getContactImage
* @param integer $entryid The EntryID in Contact Manager
* @param string $type Type of Entry, Internal or External
* @return string The image binary
*/
public function getContactImage($entryid=null,$type=null) {
$mods = $this->freepbx->Hooks->processHooks($entryid,$type);
foreach($mods as $mod => $contents) {
if(!empty($contents)) {
$buffer = $contents;
break;
}
}
if(empty($buffer)) {
$buffer = '';
if(!empty($entryid)) {
if(!empty($type)) {
switch($type) {
case "internal":
$data = $this->freepbx->Userman->getUserByID($entryid);
$data = $this->getImageByID($data['id'], $data['email'], 'internal');
break;
case "private" :
case "external":
$data = $this->getEntryByID($entryid);
if(!empty($data['image']['image'])) {
$data['image'] = $data['image']['image'];
}
break;
}
} else {
$data = $this->getEntryByID($entryid);
if(!empty($data['image']['image'])) {
$data['image'] = $data['image']['image'];
}
}
if(!empty($data['image'])) {
$buffer = $data['image'];
}
} elseif(!empty($_REQUEST['temporary'])) {
$name = basename($_REQUEST['name']);
$buffer = file_get_contents($this->tmp."/".$name);
} elseif(!empty($_REQUEST['entryid'])) {
$data = $this->getEntryByID($_REQUEST['entryid']);
if(!empty($data['image']['image'])) {
$buffer = $data['image']['image'];
}
} elseif(!empty($_REQUEST['did'])) {
$parts = explode(".",$_REQUEST['did']);
$did = $parts[0];
if(!empty($did)) {
$did = preg_replace("/[^0-9\*#]/","",$parts[0]);
if(!empty($_POST['ext'])) {
$user = $this->userman->getUserByDefaultExtension($_POST['ext']);
if(!empty($user)) {
$data = $this->lookupNumberByUserID($user['id'], $did);
}
}
if(empty($data)) {
$data = $this->lookupNumberByUserID(-1, $did);
}
if(!empty($data) && !empty($data['image']['image'])) {
$buffer = $data['image']['image'];
}
}
}
}
return $buffer;
}
/**
* Display Contact Image in browser
* @method displayContactImage
* @param integer $entryid The EntryID in Contact Manager
* @param string $type Type of Entry, Internal or External
*/
public function displayContactImage($entryid=null,$type=null) {
$buffer = $this->getContactImage($entryid,$type);
if(!empty($buffer)) {
$finfo = new \finfo(FILEINFO_MIME);
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
header("Content-type: ".$finfo->buffer($buffer));
echo $buffer;
} else {
header('HTTP/1.0 404 Not Found');
}
}
public function getAllSpeedDials($cached=true) {
if($cached && !empty($this->cachedSpeedDials)) {
return $this->cachedSpeedDials;
}
$sql = "SELECT e.*, s.id as speeddial, n.number, n.type as numbertype, g.type as grouptype FROM contactmanager_entry_speeddials s, contactmanager_group_entries e, contactmanager_entry_numbers n, contactmanager_groups g WHERE e.groupid = g.id AND e.id = s.entryid AND n.id = s.numberid ORDER BY s.id";
$sth = $this->db->prepare($sql);
$sth->execute();
$this->cachedSpeedDials = $sth->fetchAll(PDO::FETCH_ASSOC);
return $this->cachedSpeedDials;
}
public function syncSpeedDials() {
$sds = $this->getAllSpeedDials(false);
$active = array();
foreach($sds as $sd) {
$this->freepbx->astman->database_put("CM","speeddial/".$sd['speeddial'],$sd['number']);
$active[] = '/CM/speeddial/'.$sd['speeddial'];
}
$all = $this->freepbx->astman->database_show('CM');
foreach($all as $key => $value) {
if(!in_array($key,$active)) {
preg_match('/^\/CM\/speeddial\/(\d+)$/',$key,$match);
$this->freepbx->astman->database_del("CM","speeddial/".$match[1]);
}
}
}
public function checkSpeedDialConflict($id,$entryid=null) {
if(is_null($entryid)) {
$sql = "SELECT * FROM contactmanager_entry_speeddials WHERE id = :id";
$sth = $this->db->prepare($sql);
$sth->execute(array(
':id' => $id
));
} else {
$sql = "SELECT * FROM contactmanager_entry_speeddials WHERE id = :id AND entryid != :entryid";
$sth = $this->db->prepare($sql);
$sth->execute(array(
':id' => $id,
':entryid' => $entryid
));
}
$ret = $sth->fetch(PDO::FETCH_ASSOC);
return empty($ret);
}
public function ajaxHandler(){
switch ($_REQUEST['command']) {
case 'sdgrid':
return $this->getAllSpeedDials();
break;
case 'checksd':
if(empty($_POST['entryid'])) {
$ret = $this->checkSpeedDialConflict($_POST['id']);
} else {
$ret = $this->checkSpeedDialConflict($_POST['id'],$_POST['entryid']);
}
return array("status" => $ret);
break;
case 'getgravatar':
$type = !empty($_POST['grouptype']) ? $_POST['grouptype'] : "";
$id = !empty($_POST['id']) ? $_POST['id'] : "";
switch($type) {
case "private" :
case "external":
$email = !empty($_POST['email']) ? $_POST['email'] : '';
break;
case "userman":
case "internal":
$email = !empty($_POST['email']) ? $_POST['email'] : '';
if(empty($email)) {
$data = $this->freepbx->Userman->getUserByID($id);
$email = $data['email'];
}
break;
}
if(empty($email)) {
return array("status" => false, "message" => _("Please enter a valid email address"));
}
$data = $this->getGravatar($email);
if(!empty($data)) {
$dname = "cm-".rand()."-".md5($email);
imagepng(imagecreatefromstring($data), $this->tmp."/".$dname.".png");
return array("status" => true, "name" => $dname, "filename" => $dname.".png");
} else {
return array("status" => false, "message" => sprintf(_("Unable to find gravatar for %s"),$email));
}
break;
case "delimage":
$type = !empty($_POST['type']) ? $_POST['type'] : 'external';
if(!empty($_POST['id'])) {
$this->delImageByID($_POST['id'],$type);
return array("status" => true);
} elseif(!empty($_POST['img'])) {
$name = basename($_POST['img']);
if(file_exists($this->tmp."/".$name)) {
unlink($this->tmp."/".$name);
return array("status" => true);
}
}
return array("status" => false, "message" => _("Invalid"));
break;
case 'uploadimage':
// XXX If the posted file was too large,
// we will get here, but $_FILES is empty!
// Specifically, if the file that was posted is
// larger than 'post_max_size' in php.ini.
// So, php will throw an error, as index
// $_FILES["files"] does not exist, because
// $_FILES is empty.
if (!isset($_FILES)) {
return array("status" => false,
"message" => _("File upload failed"));
}
$this->freepbx->Media();
foreach ($_FILES["files"]["error"] as $key => $error) {
switch($error) {
case UPLOAD_ERR_OK:
$extension = pathinfo($_FILES["files"]["name"][$key], PATHINFO_EXTENSION);
$extension = strtolower($extension);
$supported = array("jpg","png");
if(in_array($extension,$supported)) {
$tmp_name = $_FILES["files"]["tmp_name"][$key];
$dname = \Media\Media::cleanFileName($_FILES["files"]["name"][$key]);
$dname = "cm-".rand()."-".pathinfo($dname,PATHINFO_FILENAME);
//imagepng(imagecreatefromstring(file_get_contents($tmp_name)), $this->tmp."/".$dname.".png");
$this->resizeImage(file_get_contents($tmp_name),$dname);
return array("status" => true, "name" => $dname, "filename" => $dname.".png");
} else {
return array("status" => false, "message" => _("Unsupported file format"));
}
break;
case UPLOAD_ERR_INI_SIZE:
return array("status" => false, "message" => _("The uploaded file exceeds the upload_max_filesize directive in php.ini"));
case UPLOAD_ERR_FORM_SIZE:
return array("status" => false, "message" => _("The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"));
case UPLOAD_ERR_PARTIAL:
return array("status" => false, "message" => _("The uploaded file was only partially uploaded"));
case UPLOAD_ERR_NO_FILE:
return array("status" => false, "message" => _("No file was uploaded"));
case UPLOAD_ERR_NO_TMP_DIR:
return array("status" => false, "message" => _("Missing a temporary folder"));
case UPLOAD_ERR_CANT_WRITE:
return array("status" => false, "message" => _("Failed to write file to disk"));
case UPLOAD_ERR_EXTENSION:
return array("status" => false, "message" => _("A PHP extension stopped the file upload"));
}
}
return array("status" => false, "message" => _("Can Not Find Uploaded Files"));
case 'grid':
$group = $this->getGroupByID((int) $_REQUEST['group']);
$entries = $this->getEntriesByGroupID((int) $_REQUEST['group']);
$entries = array_values($entries);
$final = array();
switch($group['type']) {
case "internal":
$i = 0;
foreach($entries as $entry) {
if(empty($entry['user'])) {
continue;
}
$user = $this->freepbx->Userman->getUserByID($entry['user']);
if (empty($user['username'])) {
continue;
}
if($user['username'] == $this->userNameTemplateCreator) {
continue;
}
$final[$i] = $user;
$final[$i]['id'] = $entry['uid'];
$final[$i]['displayname'] = !empty($user['displayname']) ? $user['displayname'] : $user['fname'] . " " . $user['lname'];
$final[$i]['displayname'] = !empty($user['displayname']) ? $user['displayname'] . " (".$user['username'].")" : $user['username'];
$final[$i]['actions'] = '<a href="config.php?display=userman&action=showuser&user='.$user['id'].'"><i class="fa fa-edit fa-fw"></i></a><a class="delcontact" href="config.php?display=contactmanager&action=delentry&group='.(int) $_REQUEST['group'].'&entry='.$entry['uid'].'"><i class="fa fa-ban fa-fw"></i></a>';
$i++;
}
break;
case "private":
case "external":
$i = 0;
foreach($entries as $entry) {
$entry['numbers'] = !empty($entry['numbers']) ? $entry['numbers'] : array();
$nums = array();
foreach($entry['numbers'] as &$number) {
$nums[] = $number['number'] . "(".$number['type'].")";
}
$entry['numbers'] = !empty($entry['numbers']) ? implode("<br>",$nums) : "";
$entry['actions'] = '<a href="config.php?display=contactmanager&action=showentry&group='.(int) $_REQUEST['group'].'&entry='.$entry['uid'].'"><i class="fa fa-edit fa-fw"></i></a><a class="delcontact" href="config.php?display=contactmanager&action=delentry&group='.(int) $_REQUEST['group'].'&entry='.$entry['uid'].'"><i class="fa fa-ban fa-fw"></i></a>';
$final[$i] = $entry;
$i++;
}
break;
}
return $final;
case 'favorite_list':
$favoriteList = $this->getFavoriteContactList();
foreach($favoriteList as &$list) {
$list['actions'] = '<a href="config.php?display=contactmanager&action=edit_list&list_id='.$list['id'].'"><i class="fa fa-edit fa-fw"></i></a><a href="config.php?display=contactmanager&action=dellist&list_id='.$list['id'].'"><i class="fa fa-ban fa-fw"></i></a>';
}
return $favoriteList;
case 'delete':
foreach($_POST['extensions'] as $id => $name) {
$ret = $this->deleteEntryByID($name);
}
return array('message' => count($_POST['extensions']).' Contacts entries successfully deleted','type' => $_POST['type']);
}
}
/**
* Resize and image using constraints
* @param string $data Binary image data
* @param string $filename The final filename
* @return string The basename of the filepath
*/
public function resizeImage($data, $filename) {
$thumb_width = $thumb_height = $this->maxAvatar;
$image = imagecreatefromstring($data);
$filename = $this->tmp.'/'.$filename.'.png';
$width = imagesx($image);
$height = imagesy($image);
$original_aspect = $width / $height;
$thumb_aspect = $thumb_width / $thumb_height;
if ( $original_aspect >= $thumb_aspect ) {
// If image is wider than thumbnail (in aspect ratio sense)
$new_height = $thumb_height;
$new_width = $width / ($height / $thumb_height);
} else {
// If the thumbnail is wider than the image
$new_width = $thumb_width;
$new_height = $height / ($width / $thumb_width);
}
$thumb = imagecreatetruecolor( $thumb_width, $thumb_height );
// Resize and crop
$horizontalOffset = round(0 - ($new_width - $thumb_width) / 2);
$verticalOffset = round(0 - ($new_height - $thumb_height) / 2);
imagecopyresampled($thumb,
$image,
$horizontalOffset, // Center the image horizontally
$verticalOffset, // Center the image vertically
0, 0,
round($new_width), round($new_height),
$width, $height);
imagepng($thumb, $filename, 9);
return basename($filename);
}
/**
* Get either a Gravatar URL or complete image tag for a specified email address.
*
* @param string $email The email address
* @source https://gravatar.com/site/implement/images/php/
*/
function getGravatar($email) {
$s = $this->maxAvatar; //Size in pixels, defaults to 80px [ 1 - 2048 ]
$d = '404'; //Default imageset to use [ 404 | mm | identicon | monsterid | wavatar ]
$r = 'g'; //Maximum rating (inclusive) [ g | pg | r | x ]
$pest = new \Pest('https://www.gravatar.com/avatar/');
$email = md5( strtolower( trim( $email ) ) );
try{
return $pest->get($email.'?s='.$s.'&d='.$d.'&r='.$r);
} catch(Exception $e) {
return false;
}
}
/**
* Get Inital Display
* @param {string} $display The Page name
*/
public function doConfigPageInit($display) {
$_REQUEST = freepbxGetSanitizedRequest();
if (isset($_REQUEST['action'])) {
switch ($_REQUEST['action']) {
case "delgroup":
$ret = $this->deleteGroupByID((int) $_REQUEST['group']);
$this->message = array(
'message' => $ret['message'],
'type' => $ret['type']
);
return true;
case "delentry":
$ret = $this->deleteEntryByID($_REQUEST['entry']);
$this->message = array(
'message' => $ret['message'],
'type' => $ret['type']
);
return true;
case "dellist":
$ret = $this->deleteFavoriteContactListByID((int) $_REQUEST['list_id']);
$this->message = array(
'message' => $ret['message'],
'type' => $ret['type']
);
return true;
}
}
$_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
if (isset($_POST['group'])) {
$group = !empty($_POST['group']) ? $_POST['group'] : '';
if (!isset($_POST['entry'])) {
$entry = !empty($_POST['entry']) ? $_POST['entry'] : '';
$grouptype = !empty($_POST['grouptype']) ? $_POST['grouptype'] : '';
$groupname = !empty($_POST['groupname']) ? $_POST['groupname'] : '';
$groupowner = !empty($_POST['owner']) ? $_POST['owner'] : '';
if ($groupname) {
if ($group) {
$ret = $this->updateGroup($group, $groupname,$groupowner);
} else {
$ret = $this->addGroup($groupname, $grouptype);
}
$this->message = array(
'message' => $ret['message'],
'type' => $ret['type']
);
return true;
} else {
$this->message = array(
'message' => _('Group name can not be blank'),
'type' => 'danger'
);
return false;
}
} else {
$grouptype = !empty($_POST['grouptype']) ? $_POST['grouptype'] : '';
$image = !empty($_POST['image']) ? $_POST['image'] : '';
$gravatar = !empty($_POST['gravatar']) && $_POST['gravatar'] == 'on' ? true : false;
$numbers = array();
$websites = array();
if(!empty($_POST['number']) && is_array($_POST['number'])) {
foreach ($_POST['number'] as $index => $number) {
if (!$number) {
continue;
}
$numbers[$index]['number'] = $number;
$numbers[$index]['extension'] = $_POST['extension'][$index] ?? '';
$numbers[$index]['type'] = $_POST['numbertype'][$index] ?? '';
$numbers[$index]['locale'] = $_POST['numberlocale'][$index] ?? '';
if (!empty($_POST['sms'][$index])) {
$numbers[$index]['flags'][] = 'sms';
}
if (!empty($_POST['fax'][$index])) {
$numbers[$index]['flags'][] = 'fax';
}
$numbers[$index]['speeddial'] = isset($_POST['numbersde'][$index]) ? $_POST['numbersd'][$index] : "";
}
}
$xmpps = array();
if(!empty($_POST['xmpp']) && is_array($_POST['xmpp'])) {
foreach ($_POST['xmpp'] as $index => $xmpp) {
if (!$xmpp) {
continue;
}
$xmpps[$index]['xmpp'] = $xmpp;
}
}
$emails = array();
if(!empty($_POST['email']) && is_array($_POST['email'])) {
foreach ($_POST['email'] as $index => $email) {
if (!$email) {
continue;
}
$emails[$index]['email'] = $email;
}
}
$website = array();
if(!empty($_POST['website']) && is_array($_POST['website'])) {
foreach ($_POST['website'] as $index => $website) {
if (!$website) {
continue;
}
$websites[$index]['website'] = $website;
}
}
$entry = array(
'id' => $_POST['entry'] ? $_POST['entry'] : '',
'groupid' => $group,
'user' => -1,
'numbers' => $numbers,
'xmpps' => $xmpps,
'emails' => $emails,
'websites' => $websites,
'displayname' => $_POST['displayname'] ? $_POST['displayname'] : '',
'fname' => $_POST['fname'] ? $_POST['fname'] : '',
'lname' => $_POST['lname'] ? $_POST['lname'] : '',
'title' => $_POST['title'] ? $_POST['title'] : '',
'company' => $_POST['company'] ? $_POST['company'] : '',
'address' => $_POST['address'] ? $_POST['address'] : '',
'image' => $image,
'gravatar' => $gravatar
);
switch ($grouptype) {
case "internal":
throw new UnexpectedValueException("Cant add users this way");
break;
case "private":
case "external":
if (count($entry['numbers']) < 1) {
$this->message = array(
'message' => _('An entry must have numbers.'),
'type' => 'danger'
);
return false;
}
break;
}
if ($entry['id']) {
$ret = $this->updateEntry($entry['id'], $entry);
} else {
$ret = $this->addEntryByGroupID($group, $entry);
}
$this->message = array(
'message' => $ret['message'],
'type' => $ret['type']
);
return true;
}
}
if (isset($_POST['list_name'])) {
if(empty($_POST['list_name'])) {
$this->message = array(
'message' => _('List name can not be blank'),
'type' => 'danger'
);
return false;
}
if(empty($_POST['included_contacts'])) {
$this->message = array(
'message' => _('Pelase include atleast one contact'),
'type' => 'danger'
);
return false;
}
$listName = $_POST['list_name'];
$includedContacts = $_POST['included_contacts'];
if (isset($_POST['list_id'])) {
$this->updateFavoriteContactList($_POST['list_id'], $listName, $includedContacts);
} else {
$this->addFavoriteContactList($listName, $includedContacts);
}