-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathDpviz.class.php
More file actions
2699 lines (2302 loc) · 96.5 KB
/
Copy pathDpviz.class.php
File metadata and controls
2699 lines (2302 loc) · 96.5 KB
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
// License for all code of this FreePBX module can be found in the license file inside the module directory
// Copyright 2015 Sangoma Technologies.
// vim: set ai ts=4 sw=4 ft=php:
namespace FreePBX\modules;
class Dpviz extends \FreePBX_Helpers implements \BMO {
private $freepbx;
public function __construct($freepbx = null) {
parent::__construct($freepbx);
$this->freepbx = $freepbx;
$this->db = $this->freepbx->Database;
}
protected function hasPersistentInstallTable() {
try {
$sth = $this->db->query("SHOW TABLES LIKE 'dpviz_persist'");
return (bool)$sth->fetchColumn();
} catch (\Exception $e) {
return false;
}
}
protected function getPersistentInstallUuid() {
if (!$this->hasPersistentInstallTable()) {
return '';
}
try {
$sth = $this->db->prepare("SELECT install_uuid FROM dpviz_persist WHERE id = 1");
$sth->execute();
$uuid = $sth->fetchColumn();
return is_string($uuid) ? trim($uuid) : '';
} catch (\Exception $e) {
return '';
}
}
protected function setPersistentInstallUuid($uuid) {
if (!$this->isValidUuid($uuid) || !$this->hasPersistentInstallTable()) {
return false;
}
try {
$sth = $this->db->prepare("REPLACE INTO dpviz_persist (id, install_uuid) VALUES (1, :uuid)");
return (bool)$sth->execute(array(':uuid' => $uuid));
} catch (\Exception $e) {
return false;
}
}
protected function ensureInstallUuid($forceRegenerate = false) {
$uuid = false;
if (!$forceRegenerate) {
$uuid = $this->getPersistentInstallUuid();
if (!$this->isValidUuid($uuid)) {
$uuid = $this->getConfig('install_uuid');
if ($this->isValidUuid($uuid)) {
$this->setPersistentInstallUuid($uuid);
}
}
}
if (!$this->isValidUuid($uuid)) {
$uuid = $this->generateUuidV4();
$this->setPersistentInstallUuid($uuid);
}
$this->setConfig('install_uuid', $uuid);
return $uuid;
}
protected function isValidUuid($uuid) {
return is_string($uuid) && preg_match('/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i', $uuid);
}
protected function generateUuidV4() {
$bytes = '';
if (function_exists('openssl_random_pseudo_bytes')) {
$strong = false;
$bytes = openssl_random_pseudo_bytes(16, $strong);
if ($bytes === false || strlen($bytes) !== 16) {
$bytes = '';
}
}
if (strlen($bytes) !== 16) {
$bytes = '';
for ($i = 0; $i < 16; $i++) {
$bytes .= chr(mt_rand(0, 255));
}
}
$bytes[6] = chr((ord($bytes[6]) & 0x0f) | 0x40);
$bytes[8] = chr((ord($bytes[8]) & 0x3f) | 0x80);
$hex = bin2hex($bytes);
return sprintf(
'%s-%s-%s-%s-%s',
substr($hex, 0, 8),
substr($hex, 8, 4),
substr($hex, 12, 4),
substr($hex, 16, 4),
substr($hex, 20, 12)
);
}
protected function readFirstAvailableFile($paths) {
foreach ((array)$paths as $path) {
if (is_readable($path)) {
$value = trim((string)@file_get_contents($path));
if ($value !== '') {
return $value;
}
}
}
return '';
}
protected function getMacAddresses() {
$macs = array();
$paths = glob('/sys/class/net/*/address');
if (!is_array($paths)) {
return $macs;
}
foreach ($paths as $path) {
$iface = basename(dirname($path));
if ($iface === 'lo') {
continue;
}
$mac = strtolower(trim((string)@file_get_contents($path)));
if ($mac !== '' && $mac !== '00:00:00:00:00:00') {
$macs[] = $iface . ':' . $mac;
}
}
sort($macs);
return $macs;
}
protected function getInstallFingerprint() {
$parts = array();
$parts[] = 'host:' . php_uname('n');
$machineId = $this->readFirstAvailableFile(array('/etc/machine-id', '/var/lib/dbus/machine-id'));
if ($machineId !== '') {
$parts[] = 'machine:' . $machineId;
}
$macs = $this->getMacAddresses();
if (!empty($macs)) {
$parts[] = 'macs:' . implode(',', $macs);
}
return hash('sha256', implode('|', $parts));
}
/**
* Reject cross-site requests to state-changing commands.
*
* The framework already referer-checks, but only when the CHECKREFERER
* config setting is enabled -- a system-wide toggle this module does not
* control and an admin can switch off. This repeats the check locally so
* dpviz's write endpoints defend themselves either way, and additionally
* honors Origin, which the framework does not look at.
*
* By construction this can never reject a request the framework would
* have accepted with CHECKREFERER on: that path already required a
* same-host Referer, which satisfies this too.
*/
protected function requireSameOrigin() {
$host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '';
if ($host === '') {
return $this->denyCrossOrigin();
}
// A cross-site <form> cannot set a custom header, and a cross-origin
// fetch that tries one is stopped by the CORS preflight, so this
// header is proof the call came from our own page's JavaScript.
if (!empty($_SERVER['HTTP_X_DPVIZ_REQUEST'])) {
return true;
}
// Origin first (sent on cross-origin form posts, so it is the more
// reliable signal), then Referer. First one present decides.
foreach (array('HTTP_ORIGIN', 'HTTP_REFERER') as $key) {
if (empty($_SERVER[$key])) {
continue;
}
$parsed = parse_url($_SERVER[$key]);
if (empty($parsed['host'])) {
continue;
}
$candidate = $parsed['host'] . (isset($parsed['port']) ? ':' . $parsed['port'] : '');
return ($candidate === $host) ? true : $this->denyCrossOrigin();
}
return $this->denyCrossOrigin();
}
protected function denyCrossOrigin() {
if (!headers_sent()) {
header('Content-Type: application/json');
http_response_code(403);
}
echo json_encode(array(
'status' => 'error',
'message' => _('Request rejected: cross-site or unverifiable origin.')
));
exit;
}
/**
* Does the logged-in admin hold the given FreePBX section (ACL) permission?
*
* Section names are the menuitem keys from each module's module.xml -- the
* same keys config.php gates page display on (ivr, queues, did, ...). We
* defer to ampuser::checkSection() so the '*' wildcard and the legacy
* ampuser conversion path are handled exactly as core handles them.
*
* Returns false when there is no authenticated admin in the session. That
* matters: Ajax.class.php skips authentication entirely for requests
* originating from 127.0.0.1, so without this the loopback interface would
* be an unauthenticated write path into the dialplan.
*/
protected function userHasSection($section) {
if ($section === '' || !isset($_SESSION['AMP_user'])) {
return false;
}
$user = $_SESSION['AMP_user'];
if (!is_object($user) || !method_exists($user, 'checkSection')) {
return false;
}
return (bool)$user->checkSection($section);
}
/**
* Gate a state-changing ajax command on a section permission.
*
* Emits a JSON error and exits when the admin lacks the permission, so
* callers can treat a return as "allowed". The graph only draws the
* add/edit affordances a user has access to, but that is a client-side
* decision -- this is the server-side enforcement behind it.
*/
protected function requireSection($section) {
if ($this->userHasSection($section)) {
return true;
}
if (!headers_sent()) {
header('Content-Type: application/json');
http_response_code(403);
}
echo json_encode(array(
'status' => 'error',
'message' => _('Permission denied: your account does not have access to this module.')
));
exit;
}
/**
* Maps the module names the create-destination modal posts to the FreePBX
* section that governs them. Anything not listed here is refused outright.
*/
protected function createDestinationSection($module) {
$map = array(
'Announcements' => 'announcement',
'Call Flow Control' => 'daynight',
'Call Recording' => 'callrecording',
'Dynamic Routes' => 'dynroute',
'Inbound Routes' => 'did',
'IVR' => 'ivr',
'Languages' => 'languages',
'Misc Destinations' => 'miscdests',
'Queues' => 'queues',
'Ring Groups' => 'ringgroups',
'Set CallerID' => 'setcid',
'Time Conditions' => 'timeconditions'
);
return isset($map[$module]) ? $map[$module] : '';
}
/**
* Resolve a requested audio file to a real path inside one of the two
* directories this module is allowed to serve, or false.
*
* The roots come from FreePBX config where available so installs that move
* ASTVARLIBDIR/ASTSPOOLDIR keep working; the literals are the stock paths
* and only act as a fallback.
*/
protected function resolveAudioPath($filename) {
$varlib = '/var/lib/asterisk';
$spool = '/var/spool/asterisk';
try {
$cfg = \FreePBX::Config();
$v = $cfg->get('ASTVARLIBDIR');
$s = $cfg->get('ASTSPOOLDIR');
if (!empty($v)) { $varlib = $v; }
if (!empty($s)) { $spool = $s; }
} catch (\Exception $e) {
// fall back to the stock paths
}
$roots = array(
rtrim($varlib, '/') . '/sounds',
rtrim($spool, '/') . '/voicemail'
);
$real = realpath($filename);
if ($real === false || !is_file($real)) {
return false;
}
foreach ($roots as $root) {
$realRoot = realpath($root);
if ($realRoot === false) {
continue;
}
// Trailing separator matters: without it "/var/lib/asterisk/sounds"
// would also prefix-match "/var/lib/asterisk/sounds-stolen/x.wav"
$realRoot = rtrim($realRoot, '/') . '/';
if (strpos($real, $realRoot) === 0) {
return $real;
}
}
return false;
}
protected function getCurrentUsername() {
if (isset($_SESSION['AMP_user'])) {
if (is_string($_SESSION['AMP_user']) && $_SESSION['AMP_user'] !== '') {
return (string)$_SESSION['AMP_user'];
}
if (is_array($_SESSION['AMP_user']) && !empty($_SESSION['AMP_user']['username'])) {
return (string)$_SESSION['AMP_user']['username'];
}
if (is_object($_SESSION['AMP_user'])) {
if (!empty($_SESSION['AMP_user']->username)) {
return (string)$_SESSION['AMP_user']->username;
}
if (method_exists($_SESSION['AMP_user'], 'getUsername')) {
return (string)$_SESSION['AMP_user']->getUsername();
}
}
}
if (!empty($_SERVER['PHP_AUTH_USER'])) {
return (string)$_SERVER['PHP_AUTH_USER'];
}
return 'noid';
}
protected function getCurrentModuleVersion() {
$modinfo = \FreePBX::Modules()->getInfo('dpviz');
return isset($modinfo['dpviz']['version']) ? (string)$modinfo['dpviz']['version'] : '0.0.0';
}
protected function getUserSettingsOverrides($username = null) {
$username = $username ?: $this->getCurrentUsername();
$settings = $this->getConfig('user_settings', $username);
return is_array($settings) ? $settings : array();
}
protected function saveUserSettingsOverrides(array $settings, $username = null) {
$username = $username ?: $this->getCurrentUsername();
return $this->setConfig('user_settings', $settings, $username);
}
protected function valuesEquivalent($left, $right) {
$left = ($left === null) ? '' : (string)$left;
$right = ($right === null) ? '' : (string)$right;
return $left === $right;
}
protected function getOverrideableSettingsColumns() {
return array_values(array_diff($this->getSettingsColumns(), array('id', 'hidewhatsnew')));
}
protected function saveCurrentUserOverrides(array $newValues) {
$global = $this->fetchSettingsRow();
if (!$global && $this->restoreSettingsRowFromKv()) {
$global = $this->fetchSettingsRow();
}
if (!is_array($global)) {
$global = array();
}
$allowed = array_flip($this->getOverrideableSettingsColumns());
$overrides = $this->getUserSettingsOverrides();
foreach ($newValues as $key => $value) {
if (!isset($allowed[$key])) {
continue;
}
$globalValue = array_key_exists($key, $global) ? $global[$key] : null;
if ($this->valuesEquivalent($value, $globalValue)) {
unset($overrides[$key]);
} else {
$overrides[$key] = $value;
}
}
return $this->saveUserSettingsOverrides($overrides);
}
protected function getCurrentUserWhatsNewHiddenVersion() {
$username = $this->getCurrentUsername();
$hiddenVersion = $this->getConfig('whatsnew_hidden_version', $username);
return is_string($hiddenVersion) ? trim($hiddenVersion) : '';
}
protected function setCurrentUserWhatsNewHiddenVersion($version) {
$username = $this->getCurrentUsername();
return $this->setConfig('whatsnew_hidden_version', (string)$version, $username);
}
protected function fetchSettingsRow() {
$sql = "SELECT * FROM dpviz LIMIT 1";
$sth = $this->db->prepare($sql);
$sth->execute();
return $sth->fetch(\PDO::FETCH_ASSOC);
}
protected function getSettingsColumns() {
$columns = array();
$sth = $this->db->query("DESCRIBE dpviz");
while ($row = $sth->fetch(\PDO::FETCH_ASSOC)) {
if (!empty($row['Field'])) {
$columns[] = $row['Field'];
}
}
return $columns;
}
public function syncSettingsRowToKv() {
$settings = $this->fetchSettingsRow();
if (!is_array($settings) || empty($settings)) {
return false;
}
$this->setConfig('settings_row', $settings);
return true;
}
public function restoreSettingsRowFromKv() {
$settings = $this->getConfig('settings_row');
if (!is_array($settings) || empty($settings)) {
return false;
}
$columns = $this->getSettingsColumns();
$updates = array();
$params = array();
foreach ($columns as $column) {
if ($column === 'id' || !array_key_exists($column, $settings)) {
continue;
}
$updates[] = '`' . $column . '` = :' . $column;
$params[':' . $column] = $settings[$column];
}
if (empty($updates)) {
return false;
}
$sql = "UPDATE dpviz SET " . implode(', ', $updates) . " WHERE id = 1";
$sth = $this->db->prepare($sql);
return $sth->execute($params);
}
protected function sendAction($action) {
return $this->sendCurlPost("action.php", array('action' => $action));
}
public function install() {
return $this->sendAction('install');
}
public function uninstall() {
return $this->sendAction('uninstall');
}
public function getOptions() {
$row = $this->fetchSettingsRow();
if (!$row && $this->restoreSettingsRowFromKv()) {
$row = $this->fetchSettingsRow();
}
if (!is_array($row)) {
$row = array();
}
$overrides = $this->getUserSettingsOverrides();
foreach ($overrides as $key => $value) {
$row[$key] = $value;
}
$hiddenVersion = trim((string)$this->getCurrentUserWhatsNewHiddenVersion());
$row['debug_current_username'] = $this->getCurrentUsername();
$row['whatsnew_hidden_version'] = $hiddenVersion;
$row['hidewhatsnew'] = ($hiddenVersion !== '') ? 1 : 0;
return $row;
}
public function editDpviz($panzoom, $horizontal, $datetime,$dynmembers, $combineQueueRing,
$extOptional, $fmfm, $minimal, $queue_member_display,
$ring_member_display, $queue_penalty, $allowlist, $blacklist, $autoplay,
$displaydestinations, $inuseby, $insertnode, $exportprefix)
{
$sql = "UPDATE dpviz SET
`panzoom` = :panzoom,
`horizontal` = :horizontal,
`datetime` = :datetime,
`dynmembers` = :dynmembers,
`combineQueueRing` = :combineQueueRing,
`extOptional` = :extOptional,
`fmfm` = :fmfm,
`minimal` = :minimal,
`queue_member_display` = :queue_member_display,
`ring_member_display` = :ring_member_display,
`queue_penalty` = :queue_penalty,
`allowlist` = :allowlist,
`blacklist` = :blacklist,
`autoplay` = :autoplay,
`displaydestinations` = :displaydestinations,
`inuseby` = :inuseby,
`insertnode` = :insertnode,
`exportprefix` = :exportprefix
WHERE `id` = 1";
$insert = array(
':panzoom' => $panzoom,
':horizontal' => $horizontal,
':datetime' => $datetime,
':dynmembers' => $dynmembers,
':combineQueueRing' => $combineQueueRing,
':extOptional' => $extOptional,
':fmfm' => $fmfm,
':minimal' => $minimal,
':queue_member_display' => $queue_member_display,
':ring_member_display' => $ring_member_display,
':queue_penalty' => $queue_penalty,
':allowlist' => $allowlist,
':blacklist' => $blacklist,
':autoplay' => $autoplay,
':displaydestinations' => $displaydestinations,
':inuseby' => $inuseby,
':insertnode' => $insertnode,
':exportprefix' => $exportprefix
);
$stmt = $this->db->prepare($sql);
$success = $stmt->execute($insert);
if ($success) {
$this->syncSettingsRowToKv();
}
return $success;
}
public function doConfigPageInit($page) {
$request = $_REQUEST;
$action = isset($request['action']) ? $request['action'] : '';
$panzoom = isset($request['panzoom']) ? $request['panzoom'] : '';
$horizontal = isset($request['horizontal']) ? $request['horizontal'] : '';
$datetime = isset($request['datetime']) ? $request['datetime'] : '';
$dynmembers = isset($request['dynmembers']) ? $request['dynmembers'] : '';
$combineQueueRing = isset($request['combineQueueRing']) ? $request['combineQueueRing'] : '';
$extOptional = isset($request['extOptional']) ? $request['extOptional'] : '';
$fmfm = isset($request['fmfm']) ? $request['fmfm'] : '';
$minimal = isset($request['minimal']) ? $request['minimal'] : '';
$queue_member_display = isset($request['queue_member_display']) ? $request['queue_member_display'] : '';
$ring_member_display = isset($request['ring_member_display']) ? $request['ring_member_display'] : '';
$queue_penalty = isset($request['queue_penalty']) ? $request['queue_penalty'] : '';
$allowlist = isset($request['allowlist']) ? $request['allowlist'] : '';
$blacklist = isset($request['blacklist']) ? $request['blacklist'] : '';
$autoplay = isset($request['autoplay']) ? $request['autoplay'] : '';
$displaydestinations = isset($request['displaydestinations']) ? $request['displaydestinations'] : '';
$inuseby = isset($request['inuseby']) ? $request['inuseby'] : '';
$insertnode = isset($request['insertnode']) ? $request['insertnode'] : '';
$exportprefix = isset($request['exportprefix']) ? trim($request['exportprefix']) : '';
switch ($action) {
case 'edit':
$this->saveCurrentUserOverrides(array(
'panzoom' => $panzoom,
'horizontal' => $horizontal,
'datetime' => $datetime,
'dynmembers' => $dynmembers,
'combineQueueRing' => $combineQueueRing,
'extOptional' => $extOptional,
'fmfm' => $fmfm,
'minimal' => $minimal,
'queue_member_display' => $queue_member_display,
'ring_member_display' => $ring_member_display,
'queue_penalty' => $queue_penalty,
'allowlist' => $allowlist,
'blacklist' => $blacklist,
'autoplay' => $autoplay,
'displaydestinations' => $displaydestinations,
'inuseby' => $inuseby,
'insertnode' => $insertnode,
'exportprefix' => $exportprefix
));
break;
default:
break;
}
//error_log(print_r($user,true));
}
public function ajaxRequest($req, &$setting) {
switch ($req) {
case 'save_options':
case 'save_whatsnew':
case 'check_update':
case 'make':
case 'getrecording':
case 'getfile':
case 'getvoicemail':
case 'saveview':
case 'deleteview':
case 'feedback':
case 'coffee':
case 'nodestselect':
case 'save_nodest':
case 'create_destination':
case 'add_ivr_entry':
case 'add_dyn_entry':
case 'list_timegroups':
case 'list_calendars':
case 'list_calendargroups':
case 'list_languages':
case 'list_music':
case 'list_recordings':
case 'set_simtime':
case 'need_reload_status':
case 'get_sections':
return true;
}
return false;
}
public function ajaxHandler() {
$action = isset($_REQUEST['command']) ? $_REQUEST['command'] : '';
// Every command that changes state is origin-checked here, in one
// place, so a new endpoint cannot quietly skip the gate.
$stateChanging = array(
'save_options', 'save_whatsnew', 'saveview', 'deleteview',
'save_nodest', 'create_destination', 'add_ivr_entry',
'add_dyn_entry', 'set_simtime'
);
if (in_array($action, $stateChanging, true)) {
$this->requireSameOrigin();
}
switch ($action) {
case 'save_options':
$panzoom = isset($_POST['panzoom']) ? $_POST['panzoom'] : '';
$horizontal = isset($_POST['horizontal']) ? $_POST['horizontal'] : '';
$datetime = isset($_POST['datetime']) ? $_POST['datetime'] : '';
$dynmembers = isset($_POST['dynmembers']) ? $_POST['dynmembers'] : '';
$combineQueueRing = isset($_POST['combineQueueRing']) ? $_POST['combineQueueRing'] : '';
$extOptional = isset($_POST['extOptional']) ? $_POST['extOptional'] : '';
$fmfm = isset($_POST['fmfm']) ? $_POST['fmfm'] : '';
$minimal= isset($_POST['minimal']) ? $_POST['minimal'] : '';
$queue_member_display= isset($_POST['queue_member_display']) ? $_POST['queue_member_display'] : '';
$ring_member_display= isset($_POST['ring_member_display']) ? $_POST['ring_member_display'] : '';
$queue_penalty= isset($_POST['queue_penalty']) ? $_POST['queue_penalty'] : '';
$allowlist = isset($_POST['allowlist']) ? $_POST['allowlist'] : '';
$blacklist = isset($_POST['blacklist']) ? $_POST['blacklist'] : '';
$autoplay = isset($_POST['autoplay']) ? $_POST['autoplay'] : '';
$displaydestinations = isset($_POST['displaydestinations']) ? $_POST['displaydestinations'] : '';
$inuseby = isset($_POST['inuseby']) ? $_POST['inuseby'] : '';
$insertnode = isset($_POST['insertnode']) ? $_POST['insertnode'] : '';
$exportprefix = isset($_POST['exportprefix']) ? trim($_POST['exportprefix']) : '';
$success = $this->saveCurrentUserOverrides(array(
'panzoom' => $panzoom,
'horizontal' => $horizontal,
'datetime' => $datetime,
'dynmembers' => $dynmembers,
'combineQueueRing' => $combineQueueRing,
'extOptional' => $extOptional,
'fmfm' => $fmfm,
'minimal' => $minimal,
'queue_member_display' => $queue_member_display,
'ring_member_display' => $ring_member_display,
'queue_penalty' => $queue_penalty,
'allowlist' => $allowlist,
'blacklist' => $blacklist,
'autoplay' => $autoplay,
'displaydestinations' => $displaydestinations,
'inuseby' => $inuseby,
'insertnode' => $insertnode,
'exportprefix' => $exportprefix
));
echo json_encode(array('success' => $success));
exit;
case 'save_whatsnew':
$hidewhatsnew = (isset($_POST['hidewhatsnew']) && $_POST['hidewhatsnew'] == '1') ? 1 : 0;
try {
$success = $hidewhatsnew
? $this->setCurrentUserWhatsNewHiddenVersion($this->getCurrentModuleVersion())
: $this->setCurrentUserWhatsNewHiddenVersion('');
echo json_encode(array(
'status' => 'success',
'saved' => $success,
'hidewhatsnew' => $hidewhatsnew
));
} catch (\PDOException $e) {
echo json_encode(array(
'status' => 'error',
'message' => $e->getMessage()
));
}
exit;
case 'check_update':
$result = $this->checkForGitHubUpdate();
if (isset($result['error'])) {
echo json_encode(array('status' => 'error', 'message' => $result['error']));
} else {
echo json_encode(array(
'status' => 'success',
'current' => $result['current'],
'latest' => $result['latest'],
'up_to_date' => $result['up_to_date']
));
}
exit;
case 'make':
$fpbx = \FreePBX::create();
if (isset($fpbx->View) && method_exists($fpbx->View, 'setAdminLocales')) {
$fpbx->View->setAdminLocales();
\bindtextdomain("dpviz", __DIR__ . "/i18n");
\textdomain("dpviz");
} else {
// fallback or do nothing
}
include 'process.php';
echo json_encode(array(
'vizHeader' => $header,
'gtext' => json_decode($gtext)
));
exit;
case 'getrecording':
$mod = isset($_POST['app']) ? $_POST['app'] : '';
$id = isset($_POST['id']) ? $_POST['id'] : 0;
$lang = isset($_POST['lang']) ? $_POST['lang'] : '';
$desc = '';
$recId = 0;
$displayname = '';
$audiolist = '';
if ($mod=='systemrecording'){
$desc = '';
$recId = $id;
} elseif ($mod=='announcement'){
$annResults= \FreePBX::Announcement()->getAnnouncements();
foreach ($annResults as $a=>$aa){
if ($aa['announcement_id']==$id){
$desc = $aa['description'];
$recId = $aa['recording_id'];
break;
}
}
} elseif ($mod=='ivr'){
$ivrResults= \FreePBX::Ivr()->getDetails($id);
$desc = $ivrResults['name'];
$recId = $ivrResults['announcement'];
} elseif ($mod=='queues'){
$sql = "SELECT * FROM queues_config WHERE extension = ?";
$sth = $this->db->prepare($sql);
$sth->execute(array($id));
$qResults = $sth->fetch(\PDO::FETCH_ASSOC);
$desc = $qResults['descr'];
if (isset($qResults['joinannounce_id']) && $qResults['joinannounce_id'] !==''){
$recId = $qResults['joinannounce_id'];
}else{
$recId=0;
}
} elseif ($mod=='ringgroup'){
$sql = "SELECT * FROM ringgroups WHERE grpnum = ?";
$sth = $this->db->prepare($sql);
$sth->execute(array($id));
$rgResults = $sth->fetch(\PDO::FETCH_ASSOC);
$desc = $rgResults['description'];
if (isset($rgResults['annmsg_id']) && $rgResults['annmsg_id'] !==''){
$recId = $rgResults['annmsg_id'];
}else{
$recId=0;
}
} elseif ($mod=='vmblast'){
$sql = "SELECT * FROM vmblast WHERE grpnum = ?";
$sth = $this->db->prepare($sql);
$sth->execute(array($id));
$vmblastResults = $sth->fetch(\PDO::FETCH_ASSOC);
$desc = $vmblastResults['description'];
if (isset($vmblastResults['audio_label']) && $vmblastResults['audio_label'] !==''){
$recId = $vmblastResults['audio_label'];
}else{
$recId=0;
}
} elseif ($mod=='pagegroups'){
$sql = "SELECT * FROM paging_config WHERE page_group = ?";
$sth = $this->db->prepare($sql);
$sth->execute(array($id));
$vmblastResults = $sth->fetch(\PDO::FETCH_ASSOC);
$desc = $vmblastResults['description'];
if (isset($vmblastResults['announcement']) && $vmblastResults['announcement'] !==''){
$recId = $vmblastResults['announcement'];
}else{
$recId=0;
}
} elseif ($mod=='dynroute'){
$sql = "SELECT * FROM dynroute WHERE id = ?";
$sth = $this->db->prepare($sql);
$sth->execute(array($id));
$dynResults = $sth->fetch(\PDO::FETCH_ASSOC);
$desc = $dynResults['name'];
if (isset($dynResults['announcement_id']) && $dynResults['announcement_id'] !==''){
$recId = $dynResults['announcement_id'];
}else{
$recId=0;
}
} elseif ($mod=='queuecallback'){
$sql = "SELECT * FROM vqplus_callback_config WHERE id = ?";
$sth = $this->db->prepare($sql);
$sth->execute(array($id));
$qcbResults = $sth->fetch(\PDO::FETCH_ASSOC);
$desc = $qcbResults['name'];
if (!empty($qcbResults['announcement'])){
$recId = $qcbResults['announcement'];
}else{
$recId=0;
}
} elseif ($mod=='voicemail'){
$desc='voicemail';
if (preg_match('/vm([a-z])(\d+)/', $id, $matches)) {
$type = $matches[1]; // "u"
$ext = $matches[2]; // "210"
$vm = \FreePBX::Voicemail();
$vmResults = $vm->getGreetingsByExtension($ext);
$typeMap = array(
'u' => 'unavail',
'b' => 'busy',
);
$audiolist='';
/* TODO all VM greetings??
foreach ($vmResults as $type=>$file){
$audiolist.=$file.'&';
}
$audiolist = rtrim($audiolist, '&');
*/
$greetKey = isset($typeMap[$type]) ? $typeMap[$type] : null;
$audiolist = isset($vmResults[$greetKey]) ? $vmResults[$greetKey] : null;
$recId = 'voicemail';
$displayname= _('Ext').' '.$ext;
}
}
if (is_numeric($recId) && $recId > 0){
$fpbxResults= \FreePBX::Recordings()->getRecordingById($recId);
if (!empty($fpbxResults)){
//getrecording
if (isset($fpbxResults) && !empty($fpbxResults['playbacklist'])){
$audiolist='';
foreach ($fpbxResults['playbacklist'] as $f){
if (!empty($fpbxResults['soundlist'][$f]['filenames'][$lang])){
$audiolist.='/var/lib/asterisk/sounds/'.$lang.'/'.$f.'&';
}
}
$audiolist = rtrim($audiolist, '&');
$displayname = $fpbxResults['displayname'];
}
}else{
$recId = 0;
$displayname = '';
$audiolist = '';
}
}elseif ($recId==='voicemail'){
}else{
$displayname = '';
$audiolist = '';
}
header('Content-Type: application/json');
echo json_encode(array(
'modDescription' => $desc,
'recId' => $recId,
'displayname' => $displayname,
'filename' => $audiolist
));
exit;
case 'getfile':
if (isset($_POST['file'])){
$filename= $_POST['file'];
if (substr($filename, -4) !== ".wav") {
$filename .= ".wav";
}
// Confine the read to the two directories this endpoint is
// meant to serve. realpath() collapses ../ and resolves
// symlinks first, so the comparison is against the true
// on-disk path, not the string the browser sent. Without
// this, any .wav anywhere on the box was readable.
$filename = $this->resolveAudioPath($filename);
if ($filename !== false && is_readable($filename)) {
$xFilename = str_replace(
array("/var/lib/asterisk/sounds/", "/var/spool/asterisk/voicemail/"),
"",
$filename
);
header('Content-Type: audio/wav');
header('Content-Length: ' . filesize($filename));
header('Content-Disposition: inline; filename="' . basename($xFilename) . '"');
header('X-Filename: ' . "$xFilename");
readfile($filename);
exit;
} else {
http_response_code(404);
echo "File not found.";
exit;
}
}
exit;
case 'saveview':
// Saved views are shared by every admin, so writing one is
// only for admins who actually hold the dpviz section
$this->requireSection('dpviz');
try {
$description = isset($_POST['description']) ? trim($_POST['description']) : '';
$ext = isset($_POST['ext']) ? trim($_POST['ext']) : '';
$jump = isset($_POST['jump']) ? trim($_POST['jump']) : '';
$viewId = isset($_POST['id']) ? (int)$_POST['id'] : 0;
$skip = '';
// Decode 'skip' JSON array if present and sanitize each value
if (!empty($_POST['skip'])) {
$decoded = json_decode($_POST['skip'], true);
if (is_array($decoded)) {
$skipArray = array_map(function($item) {
return trim($item); // remove whitespace
}, $decoded);
$skip = implode(';', $skipArray);
}
}
$params = array(
':description' => $description,
':ext' => $ext,