root/freepbx/trunk/amp_conf/bin/retrieve_conf

Revision 2896, 13.1 kB (checked in by qldrob, 7 years ago)

Re-propogate astdb stuff when ./install_amp is run.

  • 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/env php
2
3 <?php
4
5 define("AMP_CONF", "/etc/amportal.conf");
6 define("ASTERISK_CONF", "/etc/asterisk/asterisk.conf");
7 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" );
8
9 function out($text) {
10   echo $text."\n";
11 }
12
13 function outn($text) {
14   echo $text;
15 }
16
17 function error($text) {
18   echo "[ERROR] ".$text."\n";
19 }
20
21 function fatal($text) {
22   echo "[FATAL] ".$text."\n";
23   exit(1);
24 }
25
26 function debug($text) {
27   global $debug;
28  
29   if ($debug) echo "[DEBUG-preDB] ".$text."\n";
30 }
31
32 function showHelp() {
33   out("Optional parameters:");
34   out("  --help, -h, -?           Show this help");
35   out("  --debug                  Enable debug output");
36   out("  --dry-run                Don't actually do anything");
37 }
38
39
40 function parse_amportal_conf2($filename) {
41   $file = file($filename);
42   foreach ($file as $line) {
43     if (preg_match("/^\s*([\w]+)\s*=\s*\"?([\w\/\:\.\%-]*)\"?\s*([;#].*)?/",$line,$matches)) {
44       $conf[ $matches[1] ] = $matches[2];
45     }
46   }
47
48   // use same defaults as function.inc.php
49   if ( !isset($conf["AMPDBENGINE"]) || ($conf["AMPDBENGINE"] == "")) {
50     $conf["AMPDBENGINE"] = "mysql";
51   }
52  
53   if ( !isset($conf["AMPDBNAME"]) || ($conf["AMPDBNAME"] == "")) {
54     $conf["AMPDBNAME"] = "asterisk";
55   }
56  
57   if ( !isset($conf["AMPENGINE"]) || ($conf["AMPENGINE"] == "")) {
58     $conf["AMPENGINE"] = "asterisk";
59   }
60
61   return $conf;
62 }
63
64 function parse_asterisk_conf2($filename) {
65   $file = file($filename);
66   foreach ($file as $line) {
67     if (preg_match("/^\s*([a-zA-Z0-9]+)\s* => \s*(.*)\s*([;#].*)?/",$line,$matches)) {
68       $conf[ $matches[1] ] = $matches[2];
69     }
70   }
71   return $conf;
72 }
73
74 /** Adds a trailing slash to a directory, if it doesn't already have one
75  */
76 function addslash($dir) {
77   return (($dir[ strlen($dir)-1 ] == '/') ? $dir : $dir.'/');
78 }
79
80
81 /********************************************************************************************************************/
82
83 // **** Make sure we have STDIN etc
84
85 // from  ben-php dot net at efros dot com   at  php.net/install.unix.commandline
86 if (version_compare(phpversion(),'4.3.0','<') || !defined("STDIN")) {
87   define('STDIN',fopen("php://stdin","r"));
88   define('STDOUT',fopen("php://stdout","r"));
89   define('STDERR',fopen("php://stderr","r"));
90   register_shutdown_function( create_function( '' , 'fclose(STDIN); fclose(STDOUT); fclose(STDERR); return true;' ) );
91 }
92   
93 // **** Make sure we have PEAR's DB.php, and include it
94
95 outn("Checking for PEAR DB..");
96 if (! @ include('DB.php')) {
97   out("FAILED");
98   fatal("PEAR must be installed (requires DB.php). Include path: ".ini_get("include_path"));
99 }
100 out("OK");
101
102
103 // **** Make sure we have PEAR's GetOpts.php, and include it
104
105 outn("Checking for PEAR Console::Getopt..");
106 if (! @ include("Console/Getopt.php")) {
107   out("FAILED");
108   fatal("PEAR must be installed (requires Console/Getopt.php). Include path: ".ini_get("include_path"));
109 }
110 out("OK");
111
112
113 // **** Parse out command-line options
114
115 $shortopts = "h?u:p:";
116 $longopts = array("help","debug","dry-run","run-install");
117
118 $args = Console_Getopt::getopt(Console_Getopt::readPHPArgv(), $shortopts, $longopts);
119 if (is_object($args)) {
120   // assume it's PEAR_ERROR
121   out($args->message);
122   exit(255);
123 }
124
125 $debug = false;
126 $dryrun = false;
127 $run_install = false;
128
129 foreach ($args[0] as $arg) {
130   switch ($arg[0]) {
131     case "--help": case "h": case "?":
132       showHelp();
133       exit(10);
134     break;
135     case "--dry-run":
136       out("Dry-run only, no files will be written");
137       $dryrun = true;
138     break;
139     case "--debug":
140       $debug = true;
141       debug("Debug mode enabled");
142     break;
143     case "--run-install":
144       $run_install = true;
145       out("Running module install.php and install.sql scripts");
146     break;
147   }
148 }
149
150 // **** Check for amportal.conf
151
152 outn("Checking for ".AMP_CONF."..");
153 if (!file_exists(AMP_CONF)) {
154   fatal("Does not exist, or is inaccessible");
155 }
156 out("OK");
157
158 // **** read amportal.conf
159
160 outn("Reading ".AMP_CONF."..");
161 $amp_conf = parse_amportal_conf2(AMP_CONF);
162 if (count($amp_conf) == 0) {
163   fatal("FAILED");
164 }
165 out("OK");
166
167 outn("Reading ".ASTERISK_CONF."..");
168 $asterisk_conf = parse_asterisk_conf2(ASTERISK_CONF);
169 if (count($asterisk_conf) == 0) {
170   fatal("FAILED");
171 }
172 out("OK");
173
174 // **** Connect to database
175
176 outn("Connecting to database..");
177
178 # the engine to be used for the SQL queries,
179 # if none supplied, backfall to mysql
180 $db_engine = "mysql";
181 if (isset($amp_conf["AMPDBENGINE"])){
182   $db_engine = $amp_conf["AMPDBENGINE"];
183 }
184
185 // **** Create symlinks array
186 $symlink_dirs = array();
187 $symlink_dirs['agi-bin'] = (isset($amp_conf['ASTAGIDIR']) ? $amp_conf['ASTAGIDIR'] : '/var/lib/asterisk/agi-bin');
188 $symlink_dirs['sounds'] = (isset($amp_conf['ASTVARLIBDIR']) ? $amp_conf['ASTVARLIBDIR'] : '/var/lib/asterisk').'/sounds';
189 $symlink_dirs['bin'] = (isset($amp_conf['AMPBIN']) ? $amp_conf['AMPBIN'] : '/var/lib/asterisk/bin');
190 $symlink_dirs['etc'] = (isset($amp_conf['ASTETCDIR']) ? $amp_conf['ASTETCDIR'] : '/etc/asterisk');
191
192 switch ($db_engine)
193 {
194   case "pgsql":
195   case "mysql":
196     /* datasource in in this style:
197     dbengine://username:password@host/database */
198  
199     $db_user = $amp_conf["AMPDBUSER"];
200     $db_pass = $amp_conf["AMPDBPASS"];
201     $db_host = $amp_conf["AMPDBHOST"];
202     $db_name = $amp_conf["AMPDBNAME"];
203  
204     $datasource = $db_engine.'://'.$db_user.':'.$db_pass.'@'.$db_host.'/'.$db_name;
205     $db = DB::connect($datasource); // attempt connection
206     break;
207  
208   case "sqlite":
209     require_once('DB/sqlite.php');
210  
211     if (!isset($amp_conf["AMPDBFILE"]))
212       die("You must setup properly AMPDBFILE in /etc/amportal.conf");
213  
214     if (isset($amp_conf["AMPDBFILE"]) == "")
215       die("AMPDBFILE in /etc/amportal.conf cannot be blank");
216  
217     $DSN = array (
218       "database" => $amp_conf["AMPDBFILE"],
219       "mode" => 0666
220     );
221  
222     $db = new DB_sqlite();
223     $db->connect( $DSN );
224     break;
225  
226   default:
227     die( "Unknown SQL engine: [$db_engine]");
228 }
229
230 if(DB::isError($db)) {
231   out("FAILED");
232   debug($db->userinfo);
233   fatal("Cannot connect to database");
234  
235 }
236 out("OK");
237
238
239 //TODO : make this engine-neutral
240 outn("Connecting to Asterisk manager interface..");
241 // connect to asterisk manager
242 require_once($amp_conf['AMPWEBROOT'].'/admin/common/php-asmanager.php');
243 $astman = new AGI_AsteriskManager();
244 if (! $res = $astman->connect("127.0.0.1", $amp_conf["AMPMGRUSER"] , $amp_conf["AMPMGRPASS"])) {
245   out("FAILED");
246   fatal("Cannot connect to manager interface");
247 }
248 out("OK");
249
250 //include common functions
251 require_once($amp_conf['AMPWEBROOT']."/admin/extensions.class.php");
252 require_once($amp_conf['AMPWEBROOT']."/admin/functions.inc.php");
253 freepbx_log("retrieve_conf", "devel-debug", "Started retrieve_conf, DB Connection OK");
254
255 // query for our modules
256 // var_dump( $db );
257 $modules = module_getinfo();
258
259 //Putting the core module last, to move outbound-allroutes
260 // last in from-internals-additional
261 if (array_key_exists('core', $modules)) {
262         $core_tmp = $modules['core'];
263         unset($modules['core']);
264         $modules['core'] = $core_tmp;
265 }
266
267 // include any module global functions
268 if(is_array($modules)){
269   foreach($modules as $key => $module) {
270     //only use this module if it's enabled (status=2)
271     if (isset($module['status']) && $module['status'] == MODULE_STATUS_ENABLED) {
272       // Make sure the module is installed and up to date
273       if ($run_install) module_install($key);
274       // active_modules array used in genConf function
275       $active_modules[] = $key;
276       //include module functions
277       if (is_file($amp_conf['AMPWEBROOT']."/admin/modules/{$key}/functions.inc.php")) {
278         freepbx_log('retrieve_conf', 'devel-debug', 'Including '.$amp_conf['AMPWEBROOT']."/admin/modules/{$key}/functions.inc.php");
279         include_once($amp_conf['AMPWEBROOT']."/admin/modules/{$key}/functions.inc.php");
280         freepbx_log('retrieve_conf', 'devel-debug', $amp_conf['AMPWEBROOT']."/admin/modules/{$key}/functions.inc.php processed OK");
281       }
282
283       // create symlinks for files in appropriate sub directories
284       symlink_subdirs( $amp_conf['AMPWEBROOT'].'/admin/modules/'.$key );
285     }
286   }
287 }
288
289 // create an object of the extensions class
290 require_once($amp_conf['AMPWEBROOT']."/admin/extensions.class.php");
291 $ext = new extensions;
292
293 // create objects for any module classes
294 // currently only 1 class can be declared per module, not sure if that will be an issue
295 if(isset($active_modules) && is_array($active_modules)){
296   foreach($active_modules as $active_module) {
297     freepbx_log('retrieve_conf', 'devel-debug', "Creating ".$active_module."_conf class");
298     $classname = $active_module."_conf";
299     if(class_exists($classname)) {
300       ${$classname} = new $classname;
301     }
302   }
303 }
304
305
306 if (!$engineinfo = engine_getinfo()) {
307   freepbx_log('retrive_conf', 'fatal', "Failed to get engine information (engine_getinfo)");
308   fatal("Failed to get engine_info");
309 }
310 // was setting these variables before, assume we still need them
311 $engine = $engineinfo['engine'];
312 $version = $engineinfo['version'];
313
314 // run all of the *_get_config and _hookGet_config functions, which will populate the appropriate objects
315 if(isset($active_modules) && is_array($active_modules)){
316   foreach($active_modules as $module) {
317     $funcname = $module."_get_config";
318     if (function_exists($funcname)) {
319       freepbx_log('retrieve_conf', 'devel-debug', 'Calling '.$funcname.'()');
320       $funcname($engine);
321     }
322   }
323   foreach($active_modules as $module) {
324     $funcname = $module."_hookGet_config";
325     if (function_exists($funcname)) {
326       freepbx_log('retrieve_conf', 'devel-debug', 'Calling '.$funcname.'()');
327       $funcname($engine);
328     }
329   }
330 }
331
332 // extensions_additional.conf
333 // create the from-internal-additional context so other can add to it
334 $ext->add('from-internal-additional', 'h', '', new ext_hangup(''));
335 //echo $ext->get_filename();
336 //echo $ext->generateConf();
337 write_file($ext->get_filename(),$ext->generateConf());
338
339 // now we write out our conf files for modules
340 // check for any objects for each of the active modules
341 // ** conferences is an example of a module that write a conf
342 if(isset($active_modules) && is_array($active_modules)){
343   foreach($active_modules as $active_module) {
344     $classname = $active_module."_conf";
345     if(class_exists($classname) && get_class(${$classname}) !== false) {
346       //echo ${$classname}->get_filename();
347       //echo ${$classname}->generateConf();
348       
349       // if the module returns an array, it wants to write multiple files
350       // ** pinsets is an example of a module that does this
351       if (is_array(${$classname}->get_filename())) {
352         foreach(${$classname}->get_filename() as $modconf) {
353           freepbx_log('retrieve_conf', 'devel-debug', 'generateConf from '.$classname.'->'.$modconf.'');
354           write_file($modconf,${$classname}->generateConf($modconf));
355         }
356       } else {
357         freepbx_log('retrieve_conf', 'devel-debug', 'generateConf from '.$classname);
358         write_file(${$classname}->get_filename(),${$classname}->generateConf());
359       }
360     }
361   }
362 }
363
364 // Finally, if this is an install, re-generate ASTDB entries, as they could be restoring from backup,
365 // just rebuilt the machine, blah blah.
366 if ($run_install) {
367   outn("Re-propogating internal device/extensions database...");
368   core_users2astdb();
369   core_devices2astdb();
370   out("OK");
371 }
372  
373
374
375 function write_file($filename,$contents) {
376   global $asterisk_conf;
377   freepbx_log('retrieve_conf', 'devel-debug', 'Writing '.$filename);
378   if (isset($filename) && !empty($filename)) {
379     if ($fd = fopen(addslash($asterisk_conf['astetcdir']).$filename, "w")) {
380       fwrite($fd, WARNING_BANNER );
381       fwrite($fd, $contents);
382       fclose($fd);
383     }
384   }
385 }
386
387 function symlink_subdirs($moduledir) {
388   global $symlink_dirs;
389
390   foreach ($symlink_dirs as $subdir => $targetdir) {
391     $dir = addslash($moduledir).$subdir;
392     if (is_dir($dir)) {
393       $d = opendir($dir);
394       while ($file = readdir($d)) {
395         if ($file[0] != '.') {
396           if (file_exists(addslash($targetdir).$file)) {
397             if (readlink(addslash($targetdir).$file) != addslash($dir).$file) {
398               freepbx_log('retrieve-conf', 'error', addslash($targetdir).$file.' already exists, and is linked to something else!');
399             } else {
400               freepbx_log('retrieve-conf', 'devel-debug', addslash($targetdir).$file.' already points to '.addslash($dir).$file.' - OK');
401             }
402           } else { 
403             if (symlink(addslash($dir).$file, addslash($targetdir).$file)) {
404               freepbx_log('retrieve-conf', 'devel-debug', 'Symlinked '.addslash($dir).$file.' to '.addslash($targetdir).$file);
405             } else {
406               freepbx_log('Cannot symlink '.addslash($dir).$file.' to '.addslash($targetdir).$file.'. Check Permissions?');
407             }
408           }
409         }
410       }
411       closedir($d);
412     }
413   }
414 }
415
416
417 // run legacy retrieve scripts
418 // TODO these legacy retrieve scripts should be obsoleted, in favor of classes like extensions class
419
420 //script to write op_server.cfg file from mysql
421 $script = $amp_conf['AMPBIN'].'/retrieve_op_conf_from_mysql.pl';
422 exec($script);
423
424 //script to write sip conf file from mysql
425 $script = $amp_conf['AMPBIN'].'/retrieve_sip_conf_from_mysql.pl';
426 exec($script);
427
428 //script to write iax2 conf file from mysql
429 $script = $amp_conf['AMPBIN'].'/retrieve_iax_conf_from_mysql.pl';
430 exec($script);
431
432 //script to write zap conf file from mysql
433 $script = $amp_conf['AMPBIN'].'/retrieve_zap_conf_from_mysql.pl';
434 exec($script);
435
436 //script to write queues conf file from mysql
437 $script = $amp_conf['AMPBIN'].'/retrieve_queues_conf_from_mysql.pl';
438 exec($script);
439  
440 // **** Set reload flag for AMP admin
441 needreload();
442 out("Please Reload Asterisk by visiting http://".$amp_conf["AMPWEBADDRESS"]."/admin");
443 ?>
Note: See TracBrowser for help on using the browser.