-
Notifications
You must be signed in to change notification settings - Fork 45
/
utility.functions.php
1617 lines (1447 loc) · 54.8 KB
/
utility.functions.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
define('EOL', isset($_SERVER['REQUEST_METHOD']) ? "<br />" : PHP_EOL);
define("IPBX_LOG_FATAL", "FATAL");
define("IPBX_LOG_CRITICAL", "CRITICAL");
define("IPBX_LOG_SECURITY", "SECURITY");
define("IPBX_LOG_UPDATE", "UPDATE");
define("IPBX_LOG_ERROR", "ERROR");
define("IPBX_LOG_WARNING", "WARNING");
define("IPBX_LOG_NOTICE", "NOTICE");
define("IPBX_LOG_INFO", "INFO");
define("IPBX_LOG_PHP", "PHP");
/** IssabelPBX Logging facility to FILE or syslog
* @param string The level/severity of the error. Valid levels use constants:
* IPBX_LOG_FATAL, IPBX_LOG_CRITICAL, IPBX_LOG_SECURITY, IPBX_LOG_UPDATE,
* IPBX_LOG_ERROR, IPBX_LOG_WARNING, IPBX_LOG_NOTICE, IPBX_LOG_INFO.
* @param string The error message
*/
function issabelpbx_log($level, $message) {
global $amp_conf;
global $runas_uid;
global $runas_gid;
$php_error_handler = false;
$bt = debug_backtrace();
/*
if($bt[0]['args'][0]!='INFO') {
file_put_contents("/tmp/backtrace.log",print_r($bt,1),FILE_APPEND); // nico
}
*/
if (isset($bt[1])) {
if($bt[1]['function'] == 'issabelpbx_error_handler') {
$php_error_handler = true;
} elseif ($bt[1]['function'] == 'out' || $bt[1]['function'] == 'die_issabelpbx') {
$file_full = $bt[1]['file'];
$line = $bt[1]['line'];
} elseif (basename($bt[0]['file']) == 'notifications.class.php') {
$file_full = $bt[2]['file'];
$line = $bt[2]['line'];
} else {
$file_full = $bt[0]['file'];
$line = $bt[0]['line'];
}
} else {
if (basename($bt[0]['file']) == 'notifications.class.php') {
$file_full = $bt[2]['file'];
$line = $bt[2]['line'];
} else {
$file_full = $bt[0]['file'];
$line = $bt[0]['line'];
}
}
if (!$php_error_handler) {
$file_base = basename($file_full);
$file_dir = basename(dirname($file_full));
$txt = sprintf("[%s] (%s/%s:%s) - %s\n", $level, $file_dir, $file_base, $line, $message);
} else {
// PHP Error Handler provides it's own formatting
$txt = sprintf("[%s-%s\n", $level, $message);
}
// if it is not set, it's probably an initial installation so we want to log something
if (!isset($amp_conf['AMPDISABLELOG']) || !$amp_conf['AMPDISABLELOG']) {
$log_type = isset($amp_conf['AMPSYSLOGLEVEL']) ? $amp_conf['AMPSYSLOGLEVEL'] : 'FILE';
switch ($log_type) {
case 'LOG_EMERG':
case 'LOG_ALERT':
case 'LOG_CRIT':
case 'LOG_ERR':
case 'LOG_WARNING':
case 'LOG_NOTICE':
case 'LOG_INFO':
case 'LOG_DEBUG':
syslog(constant($log_type),"IssabelPBX - $txt");
break;
case 'SQL': // Core will remove these settings once migrated,
case 'LOG_SQL': // default to FILE during any interim steps.
case 'FILE':
default:
// during initial install, there may be no log file provided because the script has not fully bootstrapped
// so we will default to a pre-install log file name. We will make a file name mandatory with a proper
// default in IPBX_LOG_FILE
$log_file = isset($amp_conf['IPBX_LOG_FILE']) ? $amp_conf['IPBX_LOG_FILE'] : '/tmp/issabelpbx_pre_install.log';
// PHP Throws an error on install running of install_amp because the tiemzone isn't set. This is something that
// should be done in the php.ini file but we will make an attempt to set it to something if we can't derive it
// from the date_default_timezone_get() command which goes through heuristics of guessing.
//
$tz = date_default_timezone_get();
if (!$tz) {
$tz = 'America/Los_Angeles';
}
date_default_timezone_set($tz);
$tstamp = date("Y-m-d H:i:s");
$dir = dirname($log_file);
if(!file_exists($dir)) {
if (mkdir($dir, 0777, true)) {
chown($dir,'asterisk');
chgrp($dir,'asterisk');
}
}
// Create file if it does not exist
if(!file_exists($log_file)) {
file_put_contents($log_file,"");
if($runas_uid!='') {
chown($log_file,$runas_uid);
chgrp($log_file,$runas_gid);
}
}
// Don't append if the file is greater than ~2G since some systems fail
$size = file_exists($log_file) ? sprintf("%u", filesize($log_file)) + strlen($txt) : 0;
if ($size < 2000000000 && is_writable($log_file)) {
file_put_contents($log_file, "[$tstamp] $txt", FILE_APPEND);
}
break;
}
}
}
/* version_compare that works with IssabelPBX version numbers
*/
function version_compare_issabel($version1, $version2, $op = null) {
$version1 = str_replace("rc","RC", strtolower($version1));
$version2 = str_replace("rc","RC", strtolower($version2));
if (!is_null($op)) {
return version_compare($version1, $version2, $op);
} else {
return version_compare($version1, $version2);
}
}
function compress_framework_css() {
global $amp_conf;
$mainstyle_css = $amp_conf['BRAND_CSS_ALT_MAINSTYLE']
? $amp_conf['BRAND_CSS_ALT_MAINSTYLE']
: 'assets/css/mainstyle.css';
$wwwroot = $amp_conf['AMPWEBROOT'] . "/admin";
$mainstyle_css_gen = $wwwroot . '/' . $amp_conf['mainstyle_css_generated'];
$mainstyle_css = $wwwroot . '/' . $mainstyle_css;
$new_css = file_get_contents($mainstyle_css)
. file_get_contents($wwwroot . '/' . $amp_conf['JQUERY_CSS']);
$new_css = CssMin::minify($new_css);
$new_md5 = md5($new_css);
$gen_md5 = file_exists($mainstyle_css_gen) ? md5(file_get_contents($mainstyle_css_gen)) : '';
//regenerate if hashes dont match
if ($new_md5 != $gen_md5) {
$ms_path = dirname($mainstyle_css);
// it's important for filename tp unique
//because that will force browsers to reload vs. caching it
$mainstyle_css_generated = $ms_path.'/mstyle_autogen_' . time() . '.css';
//remove any stale generated css files
exec(ipbx_which('rm') . ' -f ' . $ms_path . '/mstyle_autogen_*');
$ret = file_put_contents($mainstyle_css_generated, $new_css);
// Now assuming we write something reasonable, we need to save the generated file name and mtimes so
// next time through this ordeal, we see everything is setup and skip all of this.
//
// we skip this all this if we get back false or 0 (nothing written) in which case we will use the original
// We need to set the value in addition to defining the setting
//since if already defined the value won't be reset.
if ($ret) {
$issabelpbx_conf =& issabelpbx_conf::create();
$val_update['mainstyle_css_generated'] = str_replace($wwwroot . '/', '', $mainstyle_css_generated);
// Update the values (in case these are new) and commit
$issabelpbx_conf->set_conf_values($val_update, true, true);
// If it is a regular file (could have been first time and previous was blank then delete old
if (is_file($mainstyle_css_gen) && !unlink($mainstyle_css_gen)) {
issabelpbx_log(IPBX_LOG_WARNING,
sprintf(__('failed to delete %s from assets/css directory after '
. 'creating updated CSS file.'),
$mainstyle_css_generated_full_path));
}
}
}
}
function die_issabelpbx($text, $extended_text="", $type="FATAL") {
global $amp_conf;
if(!isset($amp_conf['DIE_ISSABELPBX_VERBOSE'])) {
$amp_conf['DIE_ISSABELPBX_VERBOSE'] = true;
}
$bt = debug_backtrace();
issabelpbx_log(IPBX_LOG_FATAL, "die_issabelpbx(): ".$text);
if (isset($_SERVER['REQUEST_METHOD'])) {
$head='<!DOCTYPE html><html lang="en">
<head>
<link rel="stylesheet" href="assets/css/bulma.min.css">
</head>
<body>
<div class="container content mt-3"><div class="box">';
$foot='</div></div></body></html';
// running in webserver
$trace = $head."<h1>".$type." ERROR</h1>\n";
$trace .= "<h3>".$text."</h3>\n";
if (!empty($extended_text)) {
$trace .= "<p>".$extended_text."</p>\n";
}
$trace .= "<h4>".__("Trace Back")."</h4>";
$main_fmt = "%s:%s %s()<br />\n";
$arg_fmt = " [%s]: %s<br />\n";
$separator = "<br />\n";
$tail = "<br />\n";
$f = 'htmlspecialchars';
} else {
// CLI
$trace = "[$type] ".$text." ".$extended_text."\n\n";
$trace .= "Trace Back:\n\n";
$main_fmt = "%s:%s %s()\n";
$arg_fmt = " [%s]: %s\n";
$separator = "\n";
$tail = "";
$f = 'trim';
}
foreach ($bt as $l) {
$cl = isset($l['class']) ? $f($l['class']) : '';
$ty = isset($l['type']) ? $f($l['type']) : '';
$func = $f($cl . $ty . $l['function']);
$trace .= sprintf($main_fmt, $l['file'], $l['line'], $func);
if (isset($l['args'])) foreach ($l['args'] as $i => $a) {
$trace .= sprintf($arg_fmt, $i, $f($a));
}
$trace .= $separator;
}
echo $trace . $tail;
if ($amp_conf['DIE_ISSABELPBX_VERBOSE']) {
$trace = print_r($bt,true);
if (isset($_SERVER['REQUEST_METHOD'])) {
echo '<pre>' .$trace. '</pre>';
} else {
echo $trace;
}
}
if (isset($_SERVER['REQUEST_METHOD'])) {
echo $foot;
}
// Now die!
exit(1);
}
//get the version number
function getversion($cached=true) {
global $db;
static $version;
if (isset($version) && $version && $cached) {
return $version;
}
$sql = "SELECT value FROM admin WHERE variable = 'version'";
$results = $db->getRow($sql);
if($db->IsError($results)) {
die_issabelpbx($sql."<br>\n".$results->getMessage());
}
return $results[0];
}
//get the version number
function get_framework_version($cached=true) {
global $db;
static $version;
if (isset($version) && $version && $cached) {
return $version;
}
$sql = "SELECT version FROM modules WHERE modulename = 'framework' AND enabled = 1";
$version = $db->getOne($sql);
if($db->IsError($version)) {
die_issabelpbx($sql."<br>\n".$version->getMessage());
}
return $version;
}
//tell application we need to reload asterisk
function needreload() {
global $db;
$sql = "UPDATE admin SET value = 'true' WHERE variable = 'need_reload'";
$result = $db->query($sql);
if($db->IsError($result)) {
die_issabelpbx($sql.$result->getMessage());
}
}
function check_reload_needed() {
global $db;
global $amp_conf;
$sql = "SELECT value FROM admin WHERE variable = 'need_reload'";
$row = $db->getRow($sql);
if($db->IsError($row)) {
die_issabelpbx($sql.$row->getMessage());
}
//check from amp user if we are allowed to execute apply changes
if(!isset($_SESSION["AMP_user"]) || !is_object($_SESSION["AMP_user"]) || !(get_class($_SESSION["AMP_user"]) == 'ampuser') || !$_SESSION["AMP_user"]->checkSection(99)) {
return false;
}
return ($row[0] == 'true' || $amp_conf['DEVELRELOAD']);
}
/** Log a debug message to a debug file
* @param string debug message to be printed
* @param string depreciated
* @param string depreciated
*/
function issabelpbx_debug($string, $option='', $filename='') {
dbug($string);
}
/**
* IssabelPBX Debugging function
* This function can be called as follows:
* dbug() - will just print a time stamp to the debug log file ($amp_conf['IPBXDBUGFILE'])
* dbug('string') - same as above + will print the string
* dbug('string',$array) - same as above + will print_r the array after the message
* dbug($array) - will print_r the array with no message (just a time stamp)
* dbug('string',$array,1) - same as above + will var_dump the array
* dbug($array,1) - will var_dump the array with no message (just a time stamp)
*
* @author Moshe Brevda mbrevda => gmail ~ com
*/
function dbug(){
global $amp_conf;
$opts = func_get_args();
$disc = $msg = $dump = null;
// Check if it is set to avoid un-defined errors if using in code portions that are
// not yet bootstrapped. Default to enabling it.
//
if (isset($amp_conf['IPBXDBUGDISABLE']) && $amp_conf['IPBXDBUGDISABLE']) {
return;
}
$dump = 0;
//sort arguments
switch (count($opts)) {
case 1:
$msg = $opts[0];
break;
case 2:
if ( is_array($opts[0]) || is_object($opts[0]) ) {
$msg = $opts[0];
$dump = $opts[1];
} else {
$disc = $opts[0];
$msg = $opts[1];
}
break;
case 3:
$disc = $opts[0];
$msg = $opts[1];
$dump = $opts[2];
break;
}
if (isset($disc) && $disc) {
$disc = ' \'' . $disc . '\':';
} else {
$disc = '';
}
$bt = debug_backtrace();
$txt = date("Y-M-d H:i:s")
. "\t" . $bt[0]['file'] . ':' . $bt[0]['line']
. "\n\n"
. $disc
. "\n"; //add timestamp + file info
dbug_write($txt, true);
if ($dump==1) {//force output via var_dump
ob_start();
var_dump($msg);
$msg=ob_get_contents();
ob_end_clean();
dbug_write($msg."\n\n\n");
} elseif(is_array($msg) || is_object($msg)) {
dbug_write(print_r($msg,true)."\n\n\n");
} else {
dbug_write($msg."\n\n\n");
}
}
//http://php.net/manual/en/function.set-error-handler.php
function issabelpbx_error_handler($errno, $errstr, $errfile, $errline, $errcontext=array()) {
global $amp_conf;
//for pre 5.2
if (!defined('E_RECOVERABLE_ERROR')) {
define('E_RECOVERABLE_ERROR', '');
}
$errortype = array (
E_ERROR => 'ERROR',
E_WARNING => 'WARNING',
E_PARSE => 'PARSE_ERROR',
E_NOTICE => 'NOTICE',
E_CORE_ERROR => 'CORE_ERROR',
E_CORE_WARNING => 'CORE_WARNING',
E_COMPILE_ERROR => 'COMPILE_ERROR',
E_COMPILE_WARNING => 'COMPILE_WARNING',
E_USER_ERROR => 'USER_ERROR',
E_USER_WARNING => 'USER_WARNING',
E_USER_NOTICE => 'USER_NOTICE',
E_STRICT => 'RUNTIM_NOTICE',
E_RECOVERABLE_ERROR => 'CATCHABLE_FATAL_ERROR',
);
if (!isset($amp_conf['PHP_ERROR_HANDLER_OUTPUT'])) {
$amp_conf['PHP_ERROR_HANDLER_OUTPUT'] = 'dbug';
}
$errormsg = isset($errortype[$errno])?$errortype[$errno]:'Undefined Error';
switch($amp_conf['PHP_ERROR_HANDLER_OUTPUT']) {
case 'issabelpbxlog':
$txt = sprintf("%s] (%s:%s) - %s", $errormsg, $errfile, $errline, $errstr);
issabelpbx_log(IPBX_LOG_PHP,$txt);
break;
case 'off':
break;
case 'dbug':
default:
$txt = date("Y-M-d H:i:s")
. "\t" . $errfile . ':' . $errline
. "\n"
. '[' . $errormsg . ']: '
. $errstr
. "\n\n";
dbug_write($txt, $check='');
break;
}
}
global $outn_function_buffer;
$outn_function_buffer='';
function out($text,$log=true) {
global $outn_function_buffer;
global $amp_conf;
echo $text.EOL;
// if not set, could be bootstrapping so default to true
if ($log && (!isset($amp_conf['LOG_OUT_MESSAGES']) || $amp_conf['LOG_OUT_MESSAGES'])) {
$outn_function_buffer .= $text;
issabelpbx_log(IPBX_LOG_INFO,$outn_function_buffer);
$outn_function_buffer = '';
}
}
function outn($text,$log=true) {
global $outn_function_buffer;
global $amp_conf;
echo $text;
// if not set, could be bootstrapping so default to true
if ($log && (!isset($amp_conf['LOG_OUT_MESSAGES']) || $amp_conf['LOG_OUT_MESSAGES'])) {
// Don't log, just accumualte until matching out() dumps the accumulated text
$outn_function_buffer .= $text;
}
}
function error($text,$log=true) {
echo "[ERROR] ".$text.EOL;
if ($log) {
issabelpbx_log(IPBX_LOG_ERROR,$text);
}
}
// TODO: used in retrieve_conf, scan code base and remove if appropriate
// replacing with logging and die_issabelpbx (which should log also)
//
function fatal($text,$log=true) {
echo "[FATAL] ".$text.EOL;
if ($log) {
issabelpbx_log(IPBX_LOG_FATAL,$text);
}
exit(1);
}
// TODO: used in retrieve_conf, scan code base and remove if appropriate
//
function debug($text,$log=true) {
global $debug;
if ($debug) echo "[DEBUG-preDB] ".$text.EOL;
if ($log) {
dbug($text);
}
}
/** like file_get_contents designed to work with url only, will try
* wget if fails or if MODULEADMINWGET set to true. If it detects
* failure, will set MODULEADMINWGET to true for future improvements.
*
* @param mixed url to be fetches or array of multiple urls to try
* @return mixed content of first successful url, boolean false if it failed.
*/
function file_get_contents_url($file_url) {
global $amp_conf;
$contents = '';
if (!is_array($file_url)) {
$file_url = array($file_url);
}
foreach ($file_url as $fn) {
if (!$amp_conf['MODULEADMINWGET']) {
ini_set('user_agent','Wget/1.10.2 (Red Hat modified)');
$contents = @ file_get_contents($fn);
}
if (empty($contents)) {
$fn2 = str_replace('&','\\&',$fn);
exec("wget --tries=1 --timeout=30 -O - $fn2 2>> /dev/null", $data_arr, $retcode);
if ($retcode) {
// if server isn't available for some reason should return non-zero
// so we return and we don't set the flag below
issabelpbx_log(IPBX_LOG_ERROR,sprintf(__('Failed to get remote file, mirror site may be down: %s'),$fn));
continue;
// We are here if contents were blank. It's possible that whatever we were getting were suppose to be blank
// so we only auto set the WGET var if we received something so as to not false trigger. If there are issues
// with content filters that this is designed to get around, we will eventually get a non-empty file which
// will trigger this for now and the future.
} elseif (!empty($data_arr) && !$amp_conf['MODULEADMINWGET']) {
$issabelpbx_conf =& issabelpbx_conf::create();
$issabelpbx_conf->set_conf_values(array('MODULEADMINWGET' => true),true);
$nt =& notifications::create($db);
$text = sprintf(__("Forced %s to true"),'MODULEADMINWGET');
$extext = sprintf(__("The system detected a problem trying to access external server data and changed internal setting %s (Use wget For Module Admin) to true, see the tooltip in Advanced Settings for more details."),'MODULEADMINWGET');
$nt->add_warning('issabelpbx', 'MODULEADMINWGET', $text, $extext, '', false, true);
}
$contents = implode("\n",$data_arr);
return $contents;
} else {
return $contents;
}
// we get here if all wget's fail
return false;
}
}
/**
* function generate_module_repo_url
* short create array of full URLs to get a file from repo
* use this function to generate an array of URLs for all configured REPOs
* @author Philippe Lindheimer
*
* @pram string
* @returns string
*/
function generate_module_repo_url($path, $add_options=false) {
global $db;
global $amp_conf;
$urls = array();
if ($add_options) {
$firstinstall=false;
$type=null;
$sql = "SELECT * FROM module_xml WHERE id = 'installid'";
$result = sql($sql,'getRow',DB_FETCHMODE_ASSOC);
// if not set so this is a first time install
// get a new hash to account for first time install
//
$install_hash = _module_generate_unique_id();
$installid = $install_hash['uniqueid'];
$type = $install_hash['type'];
if (!isset($result['data']) || trim($result['data']) == "" || ($installid != $result['data'])) {
//Yes they do the same thing but thats ok
if(!isset($result['data']) || trim($result['data']) == "") {
$firstinstall=true;
} else {
$install_hash = _module_regenerate_unique_id();
$installid = $install_hash['uniqueid'];
$type = $install_hash['type'];
}
// save the hash so we remeber this is a first time install
//
$data4sql = $db->escapeSimple($installid);
sql("REPLACE INTO module_xml (id,time,data) VALUES ('installid',".time().",'".$data4sql."')");
$data4sql = $db->escapeSimple($type);
sql("REPLACE INTO module_xml (id,time,data) VALUES ('type',".time().",'".$data4sql."')");
// Not a first time so save the queried hash and check if there is a type set
//
} else {
$installid=$result['data'];
$sql = "SELECT * FROM module_xml WHERE id = 'type'";
$result = sql($sql,'getRow',DB_FETCHMODE_ASSOC);
if (isset($result['data']) && trim($result['data']) != "") {
$type=$result['data'];
}
}
// Now we have the id and know if this is a firstime install so we can get the announcement
//
$options = "?installid=".urlencode($installid);
$options .= "&sv=2";
if (trim($type) != "") {
$options .= "&type=".urlencode($type);
}
if ($firstinstall) {
$options .= "&firstinstall=yes";
}
// We check specifically for false because evenif blank it means the file
// was there so we want module.xml to do appropriate actions
$brandid = _module_brandid();
if ($brandid !== false) {
$options .= "&brandid=" . urlencode($brandid);
}
$deploymentid = _module_deploymentid();
if ($deploymentid !== false) {
$options .= "&depolymentid=" . urlencode($deploymentid);
}
$engver=engine_getinfo();
if ($engver['engine'] == 'asterisk' && trim($engver['engine']) != "") {
$options .="&astver=".urlencode($engver['version']);
} else {
$options .="&astver=".urlencode($engver['raw']);
}
$options .= "&phpver=".urlencode(phpversion());
$distro_info = _module_distro_id();
$options .= "&distro=".urlencode($distro_info['pbx_type']);
$options .= "&distrover=".urlencode($distro_info['pbx_version']);
$options .= "&ipbxver=".urlencode(getversion());
if (function_exists('core_users_list')) {
$options .= "&ucount=".urlencode(count(core_users_list()));
}
$path .= $options;
// Other modules may need to add 'get' paramters to the call to the repo. Check and add them
// here if we are adding paramters. The module should return an array of key/value pairs each of which
// is to be appended to the GET parameters. The variable name will be prepended with the module name
// when sent.
//
$repo_params = array();
foreach (mod_func_iterator('module_repo_parameters_callback', $path) as $mod => $res) {
if (is_array($res)) {
foreach ($res as $p => $v) {
$path .= '&' . urlencode($mod) . '_' . urlencode($p) . '=' . urlencode($v);
}
}
}
}
$repos = explode(',', $amp_conf['MODULE_REPO']);
foreach ($repos as $repo) {
$urls[] = $repo . $path;
}
return $urls;
}
/**
* function edit crontab
* short Add/removes stuff rom conrtab
* long Use this function to programmatically add/remove data from the crontab
* will always run as the asterisk user
* @author Moshe Brevda mbrevda => gmail ~ com
*
* @pram string
* @pram mixed
* @returns bool
*/
function edit_crontab($remove = '', $add = array()) {
global $amp_conf;
$cron_out = array();
$cron_add = false;
//if were running as root (i.e. uid === 0), use the asterisk users crontab. If were running as the asterisk user,
//that will happen automatically. If were anyone else, this cron entry will go the current user
//and run as them
$current_user = posix_getpwuid(posix_geteuid());
if ($current_user['uid'] === 0) {
$cron_user = '-u' . $amp_conf['AMPASTERISKWEBUSER'] . ' ';
} else {
$cron_user = '';
}
//get all crontabs
$exec = '/usr/bin/crontab -l ' . $cron_user. ' 2>&1';
exec($exec, $cron_out, $ret);
// empty crontab is ok
if(preg_match("/no crontab for/",implode(" ",$cron_out))) {
$cron_out=array();
$ret=0;
}
//make sure the command was executed successfully before continuing
if ($ret > 0) {
return false;
}
//remove anythign that nteeds to be removed
foreach ($cron_out as $my => $c) {
//ignore comments
if (substr($c, 0, 1) == '#') {
continue;
}
//remove blank lines
if (!$c) {
unset($cron_out[$my]);
}
//remove $remove
if ($remove) {
if (strpos($c, $remove)) {
unset($cron_out[$my]);
}
}
}
//if we have $add and its an array, parse it & fill in the missing options
//if its a string, add it as is
if($add) {
if (is_array($add)) {
if (isset($add['command'])) {
//see if we have a one word event such as daily, weekly, anually, etc
if (isset($add['event'])) {
$cron_add['event'] = '@' . trim($add['event'], '@');
} else {
$cron_add['minute'] = isset($add['minute']) && $add['minute'] !== ''
? $add['minute']
: '*';
$cron_add['hour'] = isset($add['hour']) && $add['hour'] !== ''
? $add['hour']
: '*';
$cron_add['dom'] = isset($add['dom']) && $add['dom'] !== ''
? $add['dom']
: '*';
$cron_add['month'] = isset($add['month']) && $add['month'] !== ''
? $add['month']
: '*';
$cron_add['dow'] = isset($add['dow']) && $add['dow'] !== ''
? $add['dow']
: '*';
}
$cron_add['command'] = $add['command'];
$cron_add = implode(' ', $cron_add);
} else {
//no command? No cron!
$cron_add = '';
}
} else {
//no array? Just use the string
$cron_add = $add;
}
}
//if we have soemthing to add
if ($cron_add) {
$cron_out[] = $cron_add;
}
//write out crontab
$exec = '/bin/echo "' . implode("\n", $cron_out) . '" | /usr/bin/crontab ' . $cron_user . '-';
//dbug('writing crontab', $exec);
exec($exec, $out_arr, $ret);
return ($ret > 0 ? false : true);
}
/**
*
* @author Moshe Brevda mbrevda => gmail ~ com
*/
function dbug_write($txt, $check = false){
global $amp_conf;
// dbug can be used prior to bootstrapping and initialization, so we set
// it if not defined here to a default.
//
if (!isset($amp_conf['IPBXDBUGFILE'])) {
$amp_conf['IPBXDBUGFILE'] = '/var/log/asterisk/issabelpbx_dbug';
}
// If not check set max size just under 2G which is the php limit before it gets upset
if($check) { $max_size = 52428800; } else { $max_size = 2000000000; }
//optionaly ensure that dbug file is smaller than $max_size
$size = file_exists($amp_conf['IPBXDBUGFILE']) ? sprintf("%u", filesize($amp_conf['IPBXDBUGFILE'])) + strlen($txt) : 0;
if ($size > $max_size) {
file_put_contents($amp_conf['IPBXDBUGFILE'], $txt);
} else {
file_put_contents($amp_conf['IPBXDBUGFILE'], $txt, FILE_APPEND);
}
}
/**
* this function can print a json object in a "pretty" (i.e. human-readbale) format
* @author Moshe Brevda mbrevda => gmail ~ com
*
* @pram string - json string
* @pram string - string to use for indentation
*
*/
function json_print_pretty($json, $indent = "\t") {
$f = '';
$len = strlen($json);
$depth = 0;
$newline = false;
for ($i = 0; $i < $len; ++$i) {
if ($newline) {
$f .= "\n";
$f .= str_repeat($indent, $depth);
$newline = false;
}
$c = $json[$i];
if ($c == '{' || $c == '[') {
$f .= $c;
$depth++;
$newline = true;
} else if ($c == '}' || $c == ']') {
$depth--;
$f .= "\n";
$f .= str_repeat($indent, $depth);
$f .= $c;
} else if ($c == '"') {
$s = $i;
do {
$c = $json[++$i];
if ($c == '\\') {
$i += 2;
$c = $json[$i];
}
} while ($c != '"');
$f .= substr($json, $s, $i-$s+1);
} else if ($c == ':') {
$f .= ': ';
} else if ($c == ',') {
$f .= ',';
$newline = true;
} else {
$f .= $c;
}
}
return $f;
}
/**
*
* @author Moshe Brevda mbrevda => gmail ~ com
*/
function astdb_get($exclude = array()) {
global $astman;
$db = $astman->database_show();
$astdb = array();
foreach ($db as $k => $v) {
if (!in_array($k, $exclude)) {
$key = explode('/', trim($k, '/'), 2);
//dbug($k, $key[1]);
$astdb[$key[0]][$key[1]] = $v;
}
}
return $astdb;
}
/**
*
* @author Moshe Brevda mbrevda => gmail ~ com
*/
function astdb_put($astdb, $exclude = array()) {
global $astman;
$db = $astman->database_show();
foreach ($astdb as $family => $key) {
if ($family && !in_array($family, $exclude)) {
$astman->database_deltree($family);
}
foreach($key as $k => $v) {
//if ($k == 'Array' && $v == '<bad value>') continue;
$astman->database_put($family, $k, $v);
}
}
return true;
}
/**
* function scandirr
* scans a directory just like scandir(), only recursively
* returns a hierarchical array representing the directory structure
*
* @pram string - directory to scan
* @pram strin - retirn absolute paths
* @returns array
*
* @author Moshe Brevda mbrevda => gmail ~ com
*/
function scandirr($dir, $absolute = false) {
$list = array();
if ($absolute) {
global $list;
}
//get directory contents
foreach (scandir($dir) as $d) {
//ignore any of the files in the array
if (in_array($d, array('.', '..'))) {
continue;
}
//if current file ($d) is a directory, call scandirr
if (is_dir($dir . '/' . $d)) {
if ($absolute) {
scandirr($dir . '/' . $d, $absolute);
} else {
$list[$d] = scandirr($dir . '/' . $d, $absolute);
}
//otherwise, add the file to the list
} elseif (is_file($dir . '/' . $d) || is_link($dir . '/' . $d)) {
if ($absolute) {
$list[] = $dir . '/' . $d;
} else {
$list[] = $d;
}
}
}
return $list;
}
/**
* Prints an array as a "tree" of data
*/
function dbug_printtree($dir, $indent = "\t") {
static $t = 0;
$foo = '';
foreach ($dir as $key => $val) {
//if this item is an array, its probobly a direcotry
if (is_array($val)) {
for ($i = 0; $i < $t; $i++) {
$foo .= $indent;
}
//return the directory name
$foo .= '[' . $key . ']' . "\n";
++$t;
printtree($val, $indent);
--$t;
} else {
for ($i = 0; $i < $t; $i++) {
$foo .= $indent;
}
//return file name
$foo .= $val . "\n";
}
}
}
/**
* returns the absolute path to a system application
*
* @author Moshe Brevda mbrevda => gmail ~ com
* @pram string
* @retruns string
*/
function ipbx_which($app) {
// don't know if we will always have an open class and not even sure if
// $amp_conf will be set so to be safe deal with it all here.
//
$issabelpbx_conf =& issabelpbx_conf::create();