Open Source Training Seminar FreePBX Paid Support

root/freepbx/trunk/amp_conf/bin/retrieve_conf

Revision 6492, 26.0 kB (checked in by p_lindheimer, 2 days ago)

Merged revisions 6458-6459,6461-6490 via svnmerge from
http://svn.freepbx.org/freepbx/branches/2.5

........

r6462 | p_lindheimer | 2008-08-24 20:37:24 -0700 (Sun, 24 Aug 2008) | 1 line


Creating release 2.5.0rc2

........

r6474 | p_lindheimer | 2008-08-25 12:06:13 -0700 (Mon, 25 Aug 2008) | 1 line


fixes #3104 - looks like some of the code paths do extra urlencodes/decodes - this looks like it does it

........

r6477 | p_lindheimer | 2008-08-25 15:26:43 -0700 (Mon, 25 Aug 2008) | 1 line


fixes #3107 don't include module specific css/js files twice in some circumstances

........

r6478 | sasargen | 2008-08-26 05:30:34 -0700 (Tue, 26 Aug 2008) | 1 line


fixes #3104 - removes manual urlencode of checkbox values because they are form fields and are automatically urlencoded by the browser when the form is submitted

........

r6483 | p_lindheimer | 2008-08-26 12:15:04 -0700 (Tue, 26 Aug 2008) | 1 line


closes #3093 reset the execution time limit to the system configured limit before each module download and install so downloading many modules at once does not result in a timeout failure, this still counts on a reasonable php.ini setting for any given installation of which the default is typically adeqaute

........

r6484 | p_lindheimer | 2008-08-26 19:06:13 -0700 (Tue, 26 Aug 2008) | 1 line


closes #3113 and ref #3090 - puts error in notification panel if magic_quotes_gpc is enabled

........

r6486 | p_lindheimer | 2008-08-27 11:40:19 -0700 (Wed, 27 Aug 2008) | 1 line


improve the symlink failure message to provide feedback on what can be done to resolve the issue

........

r6490 | p_lindheimer | 2008-08-27 22:29:03 -0700 (Wed, 27 Aug 2008) | 1 line


updated CHANGES

........

  • Property svn:mime-type set to text/html
  • Property svn:eol-style set to native
  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
Line 
1 #!/usr/bin/php -q
2
3 <?php
4
5 if (! function_exists("_")) {
6         function _($str) {
7                 return $str;
8         }
9 }
10
11 ini_set('error_reporting', E_ALL & ~E_NOTICE);
12
13 define("AMP_CONF", "/etc/amportal.conf");
14 $amportalconf = AMP_CONF;
15
16 //define("ASTERISK_CONF", "/etc/asterisk/asterisk.conf");
17 define("WARNING_BANNER", "; "._("do not edit this file, this is an auto-generated file by freepbx\n")."; "._("all modifications must be done from the web gui")."\n\n\n");
18
19 // Emulate gettext extension functions if gettext is not available
20 if (!function_exists('_')) {
21         function _($str) {
22                 return $str;
23         }
24 }
25
26 function out($text) {
27         echo $text."\n";
28 }
29
30 function outn($text) {
31         echo $text;
32 }
33
34 function error($text) {
35         echo "[ERROR] ".$text."\n";
36 }
37
38 function fatal($text, $extended_text="", $type="FATAL") {
39         global $db;
40
41         echo "[$type] ".$text." ".$extended_text."\n";
42
43         if(!DB::isError($db)) {
44                 $nt = notifications::create($db);
45                 $nt->add_critical('retrieve_conf', $type, $text, $extended_text);
46         }
47
48         exit(1);
49 }
50
51 function debug($text) {
52         global $debug;
53        
54         if ($debug) echo "[DEBUG-preDB] ".$text."\n";
55 }
56
57 function showHelp() {
58         out(_("Optional parameters:"));
59         out(_("  --help, -h, -?           Show this help"));
60         out(_("  --debug                  Enable debug output"));
61         out(_("  --dry-run                Don't actually do anything"));
62 }
63
64
65 // bootstrap retrieve_conf by getting the AMPWEBROOT since that is currently where the necessary
66 // functions.inc.php resides, and then use that parser to properly parse the file and get all
67 // the defaults as needed.
68 //
69 function parse_amportal_conf_bootstrap($filename) {
70         $file = file($filename);
71         foreach ($file as $line) {
72                 if (preg_match("/^\s*([\w]+)\s*=\s*\"?([\w\/\:\.\*\%-]*)\"?\s*([;#].*)?/",$line,$matches)) {
73                         $conf[ $matches[1] ] = $matches[2];
74                 }
75         }
76         if ( !isset($conf["AMPWEBROOT"]) || ($conf["AMPWEBROOT"] == "")) {
77                 $conf["AMPWEBROOT"] = "/var/www/html";
78         } else {
79                 $conf["AMPWEBROOT"] = rtrim($conf["AMPWEBROOT"],'/');
80         }
81
82         return $conf;
83 }
84
85 /** Adds a trailing slash to a directory, if it doesn't already have one
86  */
87 function addslash($dir) {
88         return (($dir[ strlen($dir)-1 ] == '/') ? $dir : $dir.'/');
89 }
90
91
92 /********************************************************************************************************************/
93
94 // **** Make sure we have STDIN etc
95
96 // from  ben-php dot net at efros dot com   at  php.net/install.unix.commandline
97 if (version_compare(phpversion(),'4.3.0','<') || !defined("STDIN")) {
98         define('STDIN',fopen("php://stdin","r"));
99         define('STDOUT',fopen("php://stdout","r"));
100         define('STDERR',fopen("php://stderr","r"));
101         register_shutdown_function( create_function( '' , 'fclose(STDIN); fclose(STDOUT); fclose(STDERR); return true;' ) );
102 }
103    
104 // **** Make sure we have PEAR's DB.php, and include it
105
106 outn(_("Checking for PEAR DB.."));
107 if (! @ include('DB.php')) {
108         out(_("FAILED"));
109         fatal(_("PEAR Missing"),sprintf(_("PEAR must be installed (requires DB.php). Include path: %s "), ini_get("include_path")));
110 }
111 out(_("OK"));
112
113
114 // **** Make sure we have PEAR's GetOpts.php, and include it
115
116 outn(_("Checking for PEAR Console::Getopt.."));
117 if (! @ include("Console/Getopt.php")) {
118         out(_("FAILED"));
119         fatal(_("PEAR Getopt.php Missing"),sprintf(_("PEAR must be installed (requires Console/Getopt.php). Include path: %s"), ini_get("include_path")));
120 }
121 out(_("OK"));
122
123
124 // **** Parse out command-line options
125
126 $shortopts = "h?u:p:";
127 $longopts = array("help","debug","dry-run","run-install","amportalconf=");
128
129 $args = Console_Getopt::getopt(Console_Getopt::readPHPArgv(), $shortopts, $longopts);
130 if (is_object($args)) {
131         // assume it's PEAR_ERROR
132         out($args->message);
133         exit(255);
134 }
135
136 $debug = false;
137 $dryrun = false;
138 $run_install = false;
139
140 foreach ($args[0] as $arg) {
141         switch ($arg[0]) {
142                 case "--help": case "h": case "?":
143                         showHelp();
144                         exit(10);
145                 break;
146                 case "--dry-run":
147                         out(_("Dry-run only, no files will be written"));
148                         $dryrun = true;
149                 break;
150                 case "--debug":
151                         $debug = true;
152                         debug(_("Debug mode enabled"));
153                 break;
154                 case "--run-install":
155                         $run_install = true;
156                         out(_("Running module install.php and install.sql scripts"));
157                 break;
158                 case "--amportalconf":
159                         $amportalconf = $arg[1];
160                         out(sprintf(_("Using %s configuration file"), $amportalconf));
161                 break;
162         }
163 }
164
165 // **** Check for amportal.conf
166
167 outn(sprintf(_("Checking for %s "), $amportalconf)._(".."));
168 if (!file_exists($amportalconf)) {
169         fatal(_("amportal.conf access problem: "),sprintf(_("The %s file does not exist, or is inaccessible"), $amportalconf));
170 }
171 out(_("OK"));
172
173 // **** read amportal.conf
174
175 outn(sprintf(_("Bootstrapping %s .."), $amportalconf));
176 $amp_conf = parse_amportal_conf_bootstrap($amportalconf);
177 if (count($amp_conf) == 0) {
178         fatal(_("amportal.conf parsing failure"),sprintf(_("no entries found in %s"), $amportalconf));
179 }
180 out(_("OK"));
181
182 outn(sprintf(_("Parsing %s .."), $amportalconf));
183 require_once($amp_conf['AMPWEBROOT']."/admin/functions.inc.php");
184 $amp_conf = parse_amportal_conf($amportalconf);
185 if (count($amp_conf) == 0) {
186         fatal(_("amportal.conf parsing failure"),sprintf(_("no entries found in %s"), $amportalconf));
187 }
188 out(_("OK"));
189
190 $asterisk_conf_file = $amp_conf["ASTETCDIR"]."/asterisk.conf";
191 outn(sprintf(_("Parsing %s .."), $asterisk_conf_file));
192 $asterisk_conf = parse_asterisk_conf($asterisk_conf_file);
193 if (count($asterisk_conf) == 0) {
194         fatal(_("asterisk.conf parsing failure"),sprintf(_("no entries found in %s"), $asterisk_conf_file));
195 }
196 out(_("OK"));
197
198 // **** Connect to database
199
200 outn(_("Connecting to database.."));
201
202 # the engine to be used for the SQL queries,
203 # if none supplied, backfall to mysql
204 $db_engine = "mysql";
205 if (isset($amp_conf["AMPDBENGINE"])){
206         $db_engine = $amp_conf["AMPDBENGINE"];
207 }
208
209 // **** Create symlinks array
210 $symlink_dirs = array();
211 $symlink_dirs['sounds'] = $amp_conf['ASTVARLIBDIR'].'/sounds';
212 $symlink_dirs['bin']    = $amp_conf['AMPBIN'];
213 $symlink_dirs['etc']    = $amp_conf['ASTETCDIR'];
214 $symlink_dirs['images'] = $amp_conf['AMPWEBROOT']."/admin/images";
215
216 $cp_errors = "";
217 $cp_dirs = array();
218 $cp_dirs['agi-bin'] = $amp_conf['ASTAGIDIR'];
219
220 switch ($db_engine)
221 {
222         case "pgsql":
223         case "mysql":
224                 /* datasource in in this style:
225                 dbengine://username:password@host/database */
226        
227                 $db_user = $amp_conf["AMPDBUSER"];
228                 $db_pass = $amp_conf["AMPDBPASS"];
229                 $db_host = $amp_conf["AMPDBHOST"];
230                 $db_name = $amp_conf["AMPDBNAME"];
231        
232                 $datasource = $db_engine.'://'.$db_user.':'.$db_pass.'@'.$db_host.'/'.$db_name;
233                 $db = DB::connect($datasource); // attempt connection
234                 break;
235        
236         case "sqlite":
237                 die_freepbx("SQLite2 support is deprecated. Please use sqlite3 only.");
238                 break;
239        
240         case "sqlite3":
241                 if (!isset($amp_conf["AMPDBFILE"]))
242                         fatal("You must setup properly AMPDBFILE in $amportalconf");
243                        
244                 if (isset($amp_conf["AMPDBFILE"]) == "")
245                         fatal("AMPDBFILE in $amportalconf cannot be blank");
246
247                 /* on centos this extension is not loaded by default */
248                 if (! extension_loaded('sqlite3.so')  && ! extension_loaded('SQLITE3'))
249                         dl('sqlite3.so');
250
251                 if (! @require_once('DB/sqlite3.php') )
252                 {
253                         die_freepbx("Your PHP installation has no PEAR/SQLite3 support. Please install php-sqlite3 and php-pear.");
254                 }
255
256                 require_once('DB/sqlite3.php');
257                 $datasource = "sqlite3:///" . $amp_conf["AMPDBFILE"] . "?mode=0666";
258                 $db = DB::connect($datasource);
259                 break;
260
261         default:
262                 fatal( "Unknown SQL engine: [$db_engine]");
263 }
264
265 if(DB::isError($db)) {
266         out(_("FAILED"));
267         debug($db->userinfo);
268         fatal(_("database connection failure"),("failed trying to connect to the configured database"));
269        
270 }
271 out(_("OK"));
272
273 // Define the notification class for logging to the dashboard
274 //
275 $nt = notifications::create($db);
276
277 /*
278 */
279 // Check and increase php memory_limit if needed and if allowed on the system
280 //
281 $current_memory_limit = rtrim(ini_get('memory_limit'),'M');
282 $proper_memory_limit = '100';
283 if ($current_memory_limit < $proper_memory_limit) {
284         if (ini_set('memory_limit',$proper_memory_limit.'M') !== false) {
285                 $nt->add_notice('core', 'MEMLIMIT', _("Memory Limit Changed"), sprintf(_("Your memory_limit, %sM, is set too low and has been increased to %sM. You may want to change this in you php.ini config file"),$current_memory_limit,$proper_memory_limit));
286         } else {
287                 $nt->add_warning('core', 'MEMERR', _("Low Memory Limit"), sprintf(_("Your memory_limit, %sM, is set too low and may cause problems. FreePBX is not able to change this on your system. You should increase this to %sM in you php.ini config file"),$current_memory_limit,$proper_memory_limit));
288         }
289 } else {
290         $nt->delete('core', 'MEMLIMIT');
291 }
292
293 //TODO : make this engine-neutral
294 outn(_("Connecting to Asterisk manager interface.."));
295 // connect to asterisk manager
296 require_once($amp_conf['AMPWEBROOT'].'/admin/common/php-asmanager.php');
297 $astman = new AGI_AsteriskManager();
298 if (! $res = $astman->connect("127.0.0.1:".$amp_conf["ASTMANAGERPORT"], $amp_conf["AMPMGRUSER"] , $amp_conf["AMPMGRPASS"])) {
299         out(_("FAILED"));
300         fatal(_("Asterisk Manager Connection Failure"),sprintf(_("Failed to connect to the Asterisk manager through port: %s"), $amp_conf['ASTMANAGERPORT']));
301 }
302 out(_("OK"));
303
304 //include common functions
305 require_once($amp_conf['AMPWEBROOT']."/admin/extensions.class.php");
306 freepbx_log("retrieve_conf", "devel-debug", "Started retrieve_conf, DB Connection OK");
307
308 // query for our modules
309 // var_dump( $db );
310 $modules = module_getinfo();
311
312 //Putting the core module last, to move outbound-allroutes
313 // last in from-internals-additional
314 if (array_key_exists('core', $modules)) {
315         $core_tmp = $modules['core'];
316         unset($modules['core']);
317         $modules['core'] = $core_tmp;
318 }
319
320 // include any module global functions
321 if(is_array($modules)){
322         foreach($modules as $key => $module) {
323                 //only use this module if it's enabled (status=2)
324                 if (isset($module['status']) && $module['status'] == MODULE_STATUS_ENABLED) {
325                         // Make sure the module is installed and up to date
326                         if ($run_install) module_install($key);
327                         // active_modules array used in genConf function
328                         $active_modules[] = $key;
329                         //include module functions
330                         if (is_file($amp_conf['AMPWEBROOT']."/admin/modules/{$key}/functions.inc.php")) {
331                                 freepbx_log('retrieve_conf', 'devel-debug', 'Including '.$amp_conf['AMPWEBROOT']."/admin/modules/{$key}/functions.inc.php");
332                                 include_once($amp_conf['AMPWEBROOT']."/admin/modules/{$key}/functions.inc.php");
333                                 freepbx_log('retrieve_conf', 'devel-debug', $amp_conf['AMPWEBROOT']."/admin/modules/{$key}/functions.inc.php processed OK");
334                         }
335
336                         // create symlinks for files in appropriate sub directories
337                         // don't symlink framework files, it is a special case module that happens to have
338                         // some conflicting names
339                         //
340                         if ($key != 'framework') {
341                                 symlink_subdirs( $amp_conf['AMPWEBROOT'].'/admin/modules/'.$key );
342                                 cp_subdirs( $amp_conf['AMPWEBROOT'].'/admin/modules/'.$key );
343                         }
344                 }
345         }
346 }
347
348 // create an object of the extensions class
349 require_once($amp_conf['AMPWEBROOT']."/admin/extensions.class.php");
350 $ext = new extensions;
351
352 // create objects for any module classes
353 // currently only 1 class can be declared per module, not sure if that will be an issue
354 if(isset($active_modules) && is_array($active_modules)){
355         foreach($active_modules as $active_module) {
356                 freepbx_log('retrieve_conf', 'devel-debug', "Creating ".$active_module."_conf class");
357                 $classname = $active_module."_conf";
358                 if(class_exists($classname)) {
359                         ${$classname} = new $classname;
360                 }
361         }
362 }
363
364 $engineinfo = engine_getinfo();
365 if($engineinfo['version'] == 0){
366         freepbx_log('retrieve_conf', 'fatal', "Failed to get engine information (engine_getinfo: {$engineinfo['engine']})");
367         fatal(_("Failed to get engine_info"),_("retreive_conf failed to get engine information and cannot configure up a softwitch with out it. Error: {$engineinfo['engine']}"));
368 }
369 // was setting these variables before, assume we still need them
370 $engine = $engineinfo['engine'];
371 $version = $engineinfo['version'];
372
373 // Check for and report any extension conflicts
374 //
375
376 $extens_ok = true;
377 $dests_ok = true;
378
379 $nt = notifications::create($db);
380
381 $my_hash = array_flip($active_modules);
382 $my_prob_extens = framework_list_extension_conflicts($my_hash);
383
384 if (empty($my_prob_extens)) {
385         $nt->delete('retrieve_conf', 'XTNCONFLICT');
386 } else {
387         $previous = null;
388         $str = null;
389         $count = 0;
390         foreach ($my_prob_extens as $extens) {
391                 foreach ($extens as $exten => $details) {
392                         if ($exten != $previous) {
393                                 $str .=  "Extension: $exten:<br />";
394                                 $count++;
395                         }
396                         $str .= sprintf("%8s: %s<br />",$details['status'], $details['description']);
397                         $previous = $exten;
398                 }
399         }
400         $nt->add_error('retrieve_conf', 'XTNCONFLICT', sprintf(_("There are %s conflicting extensions"),$count), $str);
401         $extens_ok = false;
402 }
403
404 // Check for and report any bogus destinations
405 //
406 $my_probs = framework_list_problem_destinations($my_hash, !$amp_conf['CUSTOMASERROR']);
407
408 if (empty($my_probs)) {
409         $nt->delete('retrieve_conf', 'BADDEST');
410 } else {
411         $results = array();
412         $count = 0;
413         $str = null;
414         foreach ($my_probs as $problem) {
415                 //print_r($problem);
416                 $results[$problem['status']][] = $problem['description'];
417                 $count++;
418         }
419         foreach ($results as $status => $subjects) {
420                 $str .= sprintf(_("DEST STATUS: %s%s"),$status,"\n");
421                 foreach ($subjects as $subject) {
422                         //$str .= $subject."<br />";
423                         $str .= "   ".$subject."\n";
424                 }
425         }
426         $nt->add_error('retrieve_conf', 'BADDEST', sprintf(_("There are %s bad destinations"),$count), $str);
427         $dests_ok = false;
428 }
429
430 if ((!$exten_ok && $amp_conf['XTNCONFLICTABORT']) || (!$dest_ok && $amp_conf['BADDESTABORT'])) {
431         out(_("Aborting reload because extension conflicts or bad destinations"));
432         exit(20);
433 }
434
435 // run all of the *_get_config and _hookGet_config functions, which will populate the appropriate objects
436 if(isset($active_modules) && is_array($active_modules)){
437         foreach($active_modules as $module) {
438                 $funcname = $module."_get_config";
439                 if (function_exists($funcname)) {
440                         freepbx_log('retrieve_conf', 'devel-debug', 'Calling '.$funcname.'()');
441                         $funcname($engine);
442                 }
443         }
444         foreach($active_modules as $module) {
445                 $funcname = $module."_hookGet_config";
446                 if (function_exists($funcname)) {
447                         freepbx_log('retrieve_conf', 'devel-debug', 'Calling '.$funcname.'()');
448                         $funcname($engine);
449                 }
450         }
451 }
452
453 // extensions_additional.conf
454 // create the from-internal-additional context so other can add to it
455 $ext->add('from-internal-additional', 'h', '', new ext_hangup(''));
456 //echo $ext->get_filename();
457 //echo $ext->generateConf();
458 write_file($ext->get_filename(),$ext->generateConf());
459
460 // now we write out our conf files for modules
461 // check for any objects for each of the active modules
462 // ** conferences is an example of a module that write a conf
463 if(isset($active_modules) && is_array($active_modules)){
464         foreach($active_modules as $active_module) {
465                 $classname = $active_module."_conf";
466                 if(class_exists($classname) && get_class(${$classname}) !== false) {
467                         //echo ${$classname}->get_filename();
468                         //echo ${$classname}->generateConf();
469                        
470                         // if the module returns an array, it wants to write multiple files
471                         // ** pinsets is an example of a module that does this
472                         if (is_array(${$classname}->get_filename())) {
473                                 foreach(${$classname}->get_filename() as $modconf) {
474                                         freepbx_log('retrieve_conf', 'devel-debug', 'generateConf from '.$classname.'->'.$modconf.'');
475                                         if (isset(${$classname}->use_warning_banner)) {
476                                                 write_file($modconf,${$classname}->generateConf($modconf),${$classname}->use_warning_banner);
477                                         } else {
478                                                 write_file($modconf,${$classname}->generateConf($modconf));
479                                         }
480                                 }
481                         } else {
482                                 freepbx_log('retrieve_conf', 'devel-debug', 'generateConf from '.$classname);
483                                 if (isset(${$classname}->use_warning_banner)) {
484                                         write_file(${$classname}->get_filename(),${$classname}->generateConf(),${$classname}->use_nowarning_banner);
485                                 } else {
486                                         write_file(${$classname}->get_filename(),${$classname}->generateConf());
487                                 }
488                         }
489                 }
490         }
491 }
492
493
494 function write_file($filename,$contents,$use_warning_banner=true) {
495         global $asterisk_conf;
496         freepbx_log('retrieve_conf', 'devel-debug', 'Writing '.$filename);
497         if (isset($filename) && !empty($filename)) {
498                 if ($fd = fopen(addslash($asterisk_conf['astetcdir']).$filename, "w")) {
499                         if ($use_warning_banner) {
500                                 fwrite($fd, WARNING_BANNER );
501                         }
502                         fwrite($fd, $contents);
503                         fclose($fd);
504                 }
505         }
506 }
507
508 /* file_exists_wrapper()
509  * wrapper for file_exists() with the following additonal functionality.
510  * if the file is a symlink, it will check if the link exists and if not
511  * it will try to remove this file. It returns a false (file does not exists)
512  * if the file is successfully removed, true if not. If not a symlink, just
513  * returns file_exists()
514  */
515 function file_exists_wrapper($string) {
516         if (is_link($string)) {
517                 $linkinfo = readlink($string);
518                 if ($linkinfo === false) {
519                         //TODO: throw error?
520                         return !unlink($string);
521                 } else {
522                         if (file_exists($linkinfo)) {
523                                 return true;
524                         } else {
525                                 return !unlink($string);
526                         }
527                 }
528         } else {
529                 return file_exists($string);
530         }
531 }
532
533 function symlink_subdirs($moduledir) {
534         global $symlink_dirs;
535         $symlink_errors = false;
536
537         $nt = notifications::create($db);
538
539         $error_modules = '';
540         foreach ($symlink_dirs as $subdir => $targetdir) {
541                 $dir = addslash($moduledir).$subdir;
542                 if (is_dir($dir)) {
543                         $d = opendir($dir);
544                         while ($file = readdir($d)) {
545                                 if ($file[0] != '.') {
546                                         $src = addslash($dir).$file;
547                                         $dest = addslash($targetdir).$file;
548                                         if (file_exists_wrapper($dest)) {
549                                                 if (!is_link($dest)) {
550                                                         freepbx_log('retrieve-conf', 'error', $dest.' already exists, and is not a symlink!');
551                                                         $error_modules .= "<br />&nbsp;&nbsp;&nbsp;".$dest;
552                                                         $symlink_errors = true;
553                                                 } else if (readlink($dest) != $src) {
554                                                         // TODO : is this the proper handling? should we just overwrite..?
555                                                         freepbx_log('retrieve-conf', 'error', $dest.' already exists, and is linked to something else!');
556                                                         $error_modules .= "<br />&nbsp;&nbsp;&nbsp;".$dest;
557                                                         $symlink_errors = true;
558                                                 } else {
559                                                         freepbx_log('retrieve-conf', 'devel-debug', $dest.' already points to '.$src.' - OK');
560                                                 }
561                                         } else {
562 //                                              // symlink, unlike copy, doesn't overwrite - have to delete first
563 //                                              if (is_link($dest) || file_exists($dest)) {
564 //                                                      unlink($dest);
565 //                                              }
566                                                 if (symlink($src, $dest)) {
567                                                         freepbx_log('retrieve-conf', 'devel-debug', 'Symlinked '.$src.' to '.$dest);
568                                                 } else {
569                                                         freepbx_log('retreive-conf', 'devel-debug', 'Cannot symlink '.$src.' to '.$dest.'. Check Permissions?');
570                                                 }
571                                         }
572                                 }
573                         }
574                         closedir($d);
575                 }
576         }
577         if ($error_modules) {
578                 $nt->add_error('retrieve_conf', 'SYMLINK', _("Symlink from modules failed"), sprintf(_("retrieve_conf failed to sym link: %s<br \>This can result in FATAL failures to your PBX. If the target file exists, the symlink will not occur and you should rename the target file to allow the automatic sym link to occur and remove this error, unless this is an intentional customization."),$error_modules));
579         } else {
580                 $nt->delete('retrieve_conf', 'SYMLINK');
581         }
582 }
583
584 // wrap copy with error handler
585 //
586 function err_copy($source, $dest) {
587         $ret = false;
588         set_error_handler("report_errors");
589         if (copy($source, $dest)) {
590                 $ret = chmod($dest,'0754');
591         }
592         restore_error_handler();
593         return $ret;
594 }
595
596 // wrap unlink with error handler
597 //
598 function err_unlink($dest) {
599         set_error_handler("report_errors");
600         $ret = unlink($dest);
601         restore_error_handler();
602         return $ret;
603 }
604
605 function cp_subdirs($moduledir) {
606         global $cp_errors;
607         global $cp_dirs;
608
609         $cp_errors = "";
610         foreach ($cp_dirs as $subdir => $targetdir) {
611                 $dir = addslash($moduledir).$subdir;
612                 if (is_dir($dir)) {
613                         $d = opendir($dir);
614                         while ($file = readdir($d)) {
615                                 if ($file[0] != '.') {
616                                         $sourcefile = addslash($dir).$file;
617                                         $targetfile = addslash($targetdir).$file;
618
619                                         if (file_exists_wrapper($targetfile)) {
620                                                 if (is_link($targetfile)) {
621                                                         if (err_unlink($targetfile)) {
622                                                                 freepbx_log('retrieve-conf', 'devel-debug', "$targetfile was symbolic link, unlink successful");
623                                                         } else {
624                                                                 freepbx_log('retrieve-conf', 'error', "$targetfile is a symblolic link, failed to unlink!");
625                                                                 break;
626                                                         }
627                                                 }
628                                         }
629                                         // OK, now either the file is a regular file or isn't there, so proceed
630                                         //
631                                         if (err_copy($sourcefile,$targetfile)) {
632                                                 freepbx_log('retrieve-conf', 'devel-debug', "$targetfile successfully copied");
633                                                 // copy was successful, make sure it has execute permissions
634                                                 chmod($targetfile,0754);
635                                         } else {
636                                                 freepbx_log('retrieve-conf', 'error', "$targetfile failed to copy from module directory");
637                                         }
638                                 }
639                         }
640                         closedir($d);
641                 }
642         }
643         $nt = notifications::create($db);
644         if ($cp_errors) {
645                 $nt->add_error('retrieve_conf', 'CPAGIBIN', _("Failed to copy from module agi-bin"), sprintf(_("Retrieve conf failed to copy file(s) from a module's agi-bin dir: %s"),$cp_errors));
646         } else {
647                 $nt->delete('retrieve_conf', 'CPAGIBIN');
648         }
649 }
650
651 function report_errors($errno, $errstr, $errfile, $errline) {
652         global $cp_errors;
653         switch($db_engine) {
654                 case "sqlite3":
655                         $escaped_string = sqlite_real_escape($errstr);
656                         break;
657                 case "mysql":
658                         $escaped_string = mysql_real_escape_string($errstr);
659                         break;
660                 case "pgsql":
661                         $escaped_string = pgsql_escape_string($errstr);
662                         break;
663         }
664         freepbx_log('retrieve-conf', 'error', "php reported: '$escaped_string' after copy or unlink attempt!");
665         $cp_errors .= $errstr."\n";
666 }
667
668 /** Check if there is a job running, if one is found then all is good, if one is not found, it will be added and a
669  *  notification will be sent.
670  */
671 function install_cron_scheduler() {
672         global $amp_conf;
673         global $nt;
674
675         // crontab appears to return an error when no entries, os only fail if error returned AND a list of entries.
676         // Don't know if this will ever happen, but a failure and a list could indicate something wrong.
677         //
678         exec("/usr/bin/crontab -l", $outlines, $ret);
679         if ($ret && count($outlines)) {
680                 $nt->add_error('retrieve_conf', 'CRONMGR', _("Failed to check crontab for cron manager"), sprintf(_("crontab returned %s error code when checking for crontab entries to start freepbx-cron-scheduler.php crontab manager"),$ret));
681         } else {
682                 $nt->delete('retrieve_conf', 'CRONMGR');
683                 $outlines2 = preg_grep("/freepbx-cron-scheduler.php/",$outlines);
684                 $cnt = count($outlines2);
685                 switch ($cnt) {
686                         case 0:
687                                 /** grab any other cronjobs that are running as asterisk and NOT associated with backups
688                                 *  this code was taken from the backup module for the most part. But seems to work...
689                                 */
690                                 $outlines = array();
691                                 exec("/usr/bin/crontab -l | grep -v ^#\ DO\ NOT | grep -v ^#\ \( |  grep -v freepbx-cron-scheduler.php", $outlines, $ret);
692                                 $crontab_entry = "";
693                                 foreach ($outlines as $line) {
694                                         $crontab_entry .= $line."\n";
695                                 }
696                                 // schedule to run hourly, at a random time. The random time is explicit to accomodate things like module_admin online update checking
697                                 // since we will want a random access to the server. In the case of module_admin, that will also be scheduled randomly within the hour
698                                 // that it is to run
699                                 //
700                                 $crontab_entry .= rand(0,59)." * * * * ".$amp_conf['AMPBIN']."/freepbx-cron-scheduler.php";
701                                 system("/bin/echo '$crontab_entry' | /usr/bin/crontab -");
702                                 break;
703                         case 1:
704                                 // already running, nothing to do
705                                 break;
706                         default:
707                                 // error, there should never be more than one running
708                                 echo "TODO: deal with error here\n";
709                                 $nt->add_error('retrieve_conf', 'CRONMGR', _("Multiple freepbx-cron-scheduler.php running"), sprintf(_("There were %s freepbx-cron-scheduler.php instances running. There should be only 1."),$cnt));
710                 }
711         }
712 }
713
714 include("libfreepbx.confgen.php");
715
716 // script to write op_server.cfg file from mysql
717 //
718 $script = $amp_conf['AMPBIN'].'/retrieve_op_conf_from_mysql.pl '.$amportalconf.' '.rtrim($asterisk_conf['astetcdir'],DIRECTORY_SEPARATOR);
719 exec($script, $output, $ret);
720 if ($ret) {
721         fatal(sprintf(_("retrieve_op_conf_from_mysql.pl returned with an error code %s"),$ret));
722 }
723
724 // generate configuration files
725 //
726 // Leave the legacy scripts in for a little while to help with odd-ball upgrade scenarios if they haven't gotten
727 // a module upgraded yet. In particular Queues
728 //
729 if (!isset($core_conf) || !is_a($core_conf, "core_conf")) {
730         generate_configurations_sip($version);
731         generate_configurations_iax($version);
732         generate_configurations_zap($version);
733 }
734 if (!isset($queues_conf) || !is_a($queues_conf, "queues_conf")) {
735         generate_configurations_queues($version);
736 }
737        
738 // Check and install the freepbx-cron-scheduler.php manager
739 //
740 install_cron_scheduler();
741
742 // run retrieve_conf_post_custom
743 // If the following file exists, it will be run. This allows customization to be run automatically after the normal
744 // processing. Caution should be taken using this as it is only deisgned for expert usage. Errors in the code will
745 // have bad consequences and can cripple the system.
746 //
747 if (isset($amp_conf['AMPLOCALBIN'])) {
748 $post_custom = $amp_conf['AMPLOCALBIN'].'/retrieve_conf_post_custom';
749         if (file_exists($post_custom)) {
750                 outn(sprintf(_("Found script %s, executing.."), $post_custom));
751                 include($post_custom);
752                 out(_("OK"));
753         }
754 }
755
756 /* As of Asterisk 1.4.16 or there abouts, a missing #include file will make the reload fail. So
757    we need to make sure that we have such for everything that is in our configs. We will simply
758          look for the #include statements and touch the files vs. trying to inventory everything we may
759          need and then forgetting something.
760 */
761
762 exec("grep '#include' ".$amp_conf['ASTETCDIR']."/*.conf | sed 's/;.*//; s/#include//'",$output,$retcode);
763 if ($retcode != 0) {
764         error("Error code $retcode: trying to search for missing #include files");
765 }
766
767 foreach($output as $file) {
768         if (trim($file) == '') {
769                 continue;
770         }
771         $parse1 = explode(':',$file);
772         $parse2 = explode(';',$parse1[1]);
773         $rawfile = trim($parse2[0]);
774         if ($rawfile == '') {
775                 continue;
776         }
777
778         $target = ($rawfile[0] == '/') ? $rawfile : $amp_conf['ASTETCDIR']."/$rawfile";
779
780         if (!file_exists($target)) {
781                 exec("touch $target", $output, $retcode);
782                 if ($retcode != 0) {
783                         error("Error code $retcode: trying to create empty file $target");
784                 }
785         }
786 }
787
788
789 // **** Set reload flag for AMP admin
790 needreload();
791 if (isset($amp_conf["AMPWEBADDRESS"]) && $amp_conf["AMPWEBADDRESS"])
792 {
793         out(sprintf(_("Please update your modules and reload Asterisk by visiting %s"), "http://".$amp_conf["AMPWEBADDRESS"]."/admin"));
794 }
795 else
796 {
797         out(_("Please update your modules and reload Asterisk by browsing to your server."));
798 }
799         $nt->delete('retrieve_conf', 'FATAL');
800 ?>
Note: See TracBrowser for help on using the browser.
Donate



Support
Download
Develop
Forums
News
Documentation
Paid Support
About

Paid Ads