root/freepbx/branches/2.7/amp_conf/bin/retrieve_conf

Revision 10013, 29.2 kB (checked in by p_lindheimer, 3 years ago)

Merged revisions 10010 via svnmerge from
http://www.freepbx.org/v2/svn/freepbx/branches/2.8

........

r10010 | p_lindheimer | 2010-06-30 15:16:06 -0700 (Wed, 30 Jun 2010) | 1 line


fixes #4388 don't symlink from other fw_fop, fw_ari, fw_langpack modules, they are like framework also re #4382 leftover code deleted

........

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