root/freepbx/tags/2.4.1/install_amp

Revision 5749, 34.1 kB (checked in by p_lindheimer, 5 years ago)

Merged revisions 5748 via svnmerge from
http://svn.freepbx.org/freepbx/trunk

........

r5748 | p_lindheimer | 2008-04-24 15:05:50 -0700 (Thu, 24 Apr 2008) | 1 line


#2799 create include files needed by manager.conf prior before issuing reload in install script and add new from of reload for 1.6 and beyond syntax

........

  • Property svn:mime-type set to text/plain
  • 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 require_once ("libfreepbx.install.php");
5
6 # constants
7 define("AMP_CONF", "/etc/amportal.conf");
8 define("ASTERISK_CONF", "/etc/asterisk/asterisk.conf");
9 define("UPGRADE_DIR", dirname(__FILE__)."/upgrades");
10 define("MODULE_DIR", dirname(__FILE__)."/amp_conf/htdocs/admin/modules/");
11
12 # semi constants
13 $webroot  = "/var/www/html";
14 $fopwebroot = "";       // if blank, will use $webroot/panel
15 $ampsbin_dir = "/usr/local/sbin"; // default if not set
16 $ampbin_dir = "/var/lib/asterisk/bin";
17 $asterisk_user  = "asteriskuser";
18 $asterisk_pass  = "amp109";
19
20
21 /*
22 freepbx versions
23     '1.10.005',
24     '1.10.006',
25     '1.10.007beta1',
26     '1.10.007beta2',
27     '1.10.007',
28     '1.10.007a',
29     '1.10.008beta1',
30     '1.10.008beta2',
31     '1.10.008beta3',
32     '1.10.008',
33     '1.10.009beta1',
34     '1.10.009beta2',
35     '1.10.009',
36     '1.10.010beta1',
37     '1.10.010',
38     '2.0beta1',
39     '2.0beta2',
40     '2.0beta3',
41     '2.0beta4',
42     '2.0beta5',
43     '2.0.0',
44     '2.0.1',
45     '2.1beta1',
46     '2.1beta2',
47     '2.1beta3',
48     '2.1.0',
49     '2.1.1',
50     '2.1.2',
51     '2.1.3',
52     '2.2.0beta1',
53     '2.2.0beta2',
54     '2.2.0beta3',
55     '2.2.0rc1',
56     '2.2.0rc2',
57     '2.2.0rc3',
58     '2.2.0',
59     '2.2.1',
60     '2.2.2',
61     '2.2.3',
62     '2.3.0beta1',
63 */
64
65 /********************************************************************************************************************/
66
67 function out($text) {
68   echo $text."\n";
69 }
70
71 function outn($text) {
72   echo $text;
73 }
74
75 function error($text) {
76   echo "[ERROR] ".$text."\n";
77 }
78
79 function fatal($text) {
80   echo "[FATAL] ".$text."\n";
81   exit(1);
82 }
83
84 function debug($text) {
85   global $debug;
86  
87   if ($debug) echo "[DEBUG-preDB] ".$text."\n";
88 }
89
90 if (!function_exists('version_compare_freepbx')) {
91   /* verison_compare that works with freePBX version numbers
92   */
93   function version_compare_freepbx($version1, $version2, $op = null) {
94           $version1 = str_replace("rc","RC", strtolower($version1));
95           $version2 = str_replace("rc","RC", strtolower($version2));
96       if (!is_null($op)) {
97         return version_compare($version1, $version2, $op);
98       } else {
99         return version_compare($version1, $version2);
100       }
101   }
102 }
103
104 function showHelp() {
105   out("Optional parameters:");
106   out("  --help, -h, -?           Show this help");
107   out("  --dbhost <ip address>    Use a remote database server");
108   out("  --dbname databasename    Use database name specified, instead of 'asterisk'");
109   out("  --username <user>        Use <user> to connect to db and write config");
110   out("  --password <pass>        Use <pass> to connect to db and write config");
111   out("  --fopwebroot <path>      Web path where fop will be installed");
112   out("  --webroot <path>         Web root where freepbx will be installed");
113   out("  --cgibin <path>          Path where cgi-bin's lives");
114   out("  --bin <path>             Path of asterisk binaries");
115   out("  --sbin <path>            Path of system admin binaries");
116   out("  --asteriskuser <user>    Asterisk Manager username");
117   out("  --asteriskpass <pass>    Asterisk Manager password");
118   out("  --systemconfig <path>    System config files");
119   out("  --debug                  Enable debug output");
120   out("  --dry-run                Don't actually do anything");
121   out("  --force-version <ver>    Force upgrade from version <ver>");
122   out("  --skip-module-install    Don't run install scripts for packaged modules, the files are still loaded.");
123   out("                           In a development environment you may not want the install scripts run.");
124   out("  --no-files               Just run updates without installing files");
125   out("  --install-moh            Install default music-on-hold files (normally doesn't, unless ");
126   out("                           it's a new installation)");
127   //out("  --make-links-devel       Make links to files in the source directory instead of copying");
128   //out("                           (intended for developers only)");
129   out("  --my-svn-is-correct      Ignore Asterisk version, assume it is correct");
130   out("  --engine <name>          Use the specified PBX Engine ('asterisk', 'asterisk14' or 'openpbx')");
131 }
132
133 function install_parse_amportal_conf($filename) {
134   $file = file($filename);
135   foreach ($file as $line) {
136     if (preg_match("/^\s*([a-zA-Z0-9]+)\s*=\s*(.*)\s*([;#].*)?/",$line,$matches)) {
137       $conf[ $matches[1] ] = $matches[2];
138     }
139   }
140
141   // use same defaults as function.inc.php
142   if ( !isset($conf["AMPDBENGINE"]) || ($conf["AMPDBENGINE"] == "")) {
143     $conf["AMPDBENGINE"] = "mysql";
144   }
145  
146   if ( !isset($conf["AMPDBNAME"]) || ($conf["AMPDBNAME"] == "")) {
147     $conf["AMPDBNAME"] = "asterisk";
148   }
149  
150   if ( !isset($conf["AMPENGINE"]) || ($conf["AMPENGINE"] == "")) {
151     $conf["AMPENGINE"] = "asterisk";
152   }
153
154   return $conf;
155 }
156
157 function install_parse_asterisk_conf($filename) {
158   $file = file($filename);
159   foreach ($file as $line) {
160     if (preg_match("/^\s*([a-zA-Z0-9]+)\s* => \s*(.*)\s*([;#].*)?/",$line,$matches)) {
161       $conf[ $matches[1] ] = $matches[2];
162     }
163   }
164   // Now set defaults if not set (although asterisk should fail if not set but at least
165   // it will get the setup somewhat right
166   //
167   if (!isset($asterisk_conf['astetcdir']))    { $asterisk_conf['astetcdir']    = "/etc/asterisk"; }
168   if (!isset($asterisk_conf['astmoddir']))    { $asterisk_conf['astmoddir']    = "/usr/lib/asterisk/modules"; }
169   if (!isset($asterisk_conf['astvarlibdir'])) { $asterisk_conf['astvarlibdir'] = "/var/lib/asterisk"; }
170   if (!isset($asterisk_conf['astagidir']))    { $asterisk_conf['astagidir']    = "/var/lib/asterisk/agi-bin"; }
171   if (!isset($asterisk_conf['astspooldir']))  { $asterisk_conf['astspooldir']  = "/var/spool/asterisk"; }
172   if (!isset($asterisk_conf['astrundir']))    { $asterisk_conf['astrundir']    = "/var/run/asterisk"; }
173   if (!isset($asterisk_conf['astlogdir']))    { $asterisk_conf['astlogdir']    = "/var/log/asterisk"; }
174
175   return $conf;
176 }
177
178 function write_amportal_conf($filename, $conf) {
179   $file = file($filename);
180   // parse through the file
181   foreach (array_keys($file) as $key) {
182     if (preg_match("/^\s*([a-zA-Z0-9]+)\s*=\s*(.*)\s*([;#].*)?/",$file[$key],$matches)) {
183       // this is an option=value line
184       if (isset($conf[ $matches[1] ])) {
185         // rewrite the line, if we have this in $conf
186         $file[$key] = $matches[1]."=".$conf[ $matches[1] ]."\n";
187         // unset it so we know what's new
188         unset($conf[ $matches[1] ]);
189       }
190     }
191   }
192  
193   // add new entries
194   foreach ($conf as $key=>$val) {
195     $file[] = $key."=".$val."\n";
196   }
197  
198   // write the file
199   if (!$fd = fopen($filename, "w")) {
200     fatal("Could not open ".$filename." for writing");
201   }
202   fwrite($fd, implode("",$file));
203   fclose($fd);
204 }
205
206 function ask_overwrite($file1, $file2) {
207   global $check_md5s;
208   do {
209     out($file2." has been changed from the original version.");
210     outn("Overwrite (y=yes/a=all/n=no/d=diff/s=shell/x=exit)? ");
211     $key = fgets(STDIN,1024);
212     switch (strtolower($key[0])) {
213       case "y": return true;
214       case "a": $check_md5s=false; return true;
215       case "n": return false;
216       case "d":
217         out("");
218         // w = ignore whitespace, u = unified
219         passthru("diff -wu ".escapeshellarg($file2)." ".escapeshellarg($file1));
220       break;
221       case "s":
222         if (function_exists("pcntl_fork")) {
223           out("");
224           $shell = (isset($_ENV["SHELL"]) ? $_ENV["SHELL"] : "/bin/bash");
225           out("Dropping to shell. Type 'exit' to return");
226           out("-> Original file:  ".$file2);
227           out("-> New file:       ".$file1);
228          
229           $pid = pcntl_fork();
230           if ($pid == -1) {
231             out("[ERROR] cannot fork");
232           } else if ($pid) {
233             // parent
234             pcntl_waitpid($pid, $status);
235             // we wait till the child exits/dies/whatever
236           } else {
237             pcntl_exec($shell, array(), $_ENV);
238           }
239          
240           out("Returned from shell");
241         } else {
242           out("[ERROR] PHP not built with process control (--enable-pcntl) support: cannot spawn shell");
243         }
244        
245       break;
246       case "x":
247         out("-> Original file:  ".$file2);
248         out("-> New file:       ".$file1);
249         out("Exiting install program.");
250         exit(1);
251       break;
252     }
253     out("");
254   } while(1);
255 }
256
257 /** Write AMP-generated configuration files
258  */
259 function generate_configs() {
260   global $amp_conf;
261   global $dryrun;
262   global $debug;
263  
264   out("Generating Configurations.conf, (if Asterisk is not running, you will get an error");
265   out("In case of error, start Asterisk and hit the red bar in the GUI to generate the Configuraions.conf files");
266   if (!$dryrun)
267     // added --run-install to make it work like it has been working since retrieve_conf changed to not run module install scripts by default
268
269     //
270     // TODO: Should check if Asterisk is running and/or try to start it.
271     //
272     passthru("su - asterisk -c \"".trim($amp_conf["AMPBIN"])."/retrieve_conf --run-install ".($debug ? ' --debug' : '').'"');
273 }
274
275
276 /** Set reload flag for AMP admin
277  */
278 function install_needreload() {
279   global $db;
280   $sql = "UPDATE admin SET value = 'true' WHERE variable = 'need_reload'";
281   $result = $db->query($sql);
282   if(DB::IsError($result)) {     
283     die($result->getMessage());
284   }
285 }
286
287
288 /** Collect AMP settings
289  */
290 function collect_settings($filename, $dbhost = '', $dbuser = '', $dbpass = '', $dbname = 'asterisk') {
291   global $webroot;
292   global $fopwebroot;
293   global $ampsbin_dir;
294   global $ampbin_dir;
295   global $asterisk_user;
296   global $asterisk_pass;
297
298   out("Creating new $filename");
299  
300   outn("Enter your USERNAME to connect to the '$dbname' database:\n [".($dbuser ? $dbuser : $asterisk_user) . "] ");
301   $key = trim(fgets(STDIN,1024));
302   if (preg_match('/^$/',$key))
303     $amp_conf["AMPDBUSER"] = ($dbuser ? $dbuser : $asterisk_user);
304   else
305     $amp_conf["AMPDBUSER"] = $key;
306  
307   outn("Enter your PASSWORD to connect to the '$dbname' database:\n [".($dbpass ? $dbpass : $asterisk_pass)."] ");
308   $key = trim(fgets(STDIN,1024));
309   if (preg_match('/^$/',$key))
310     $amp_conf["AMPDBPASS"] = ($dbpass ? $dbpass : $asterisk_pass);
311   else
312     $amp_conf["AMPDBPASS"] = $key;
313  
314   outn("Enter the hostname of the '$dbname' database:\n [".($dbhost ? $dbhost : "localhost")."] ");
315   $key = trim(fgets(STDIN,1024));
316   if (preg_match('/^$/',$key))
317     $amp_conf["AMPDBHOST"] = ($dbhost ? $dbhost : "localhost");
318   else
319     $amp_conf["AMPDBHOST"] = $key;
320  
321   outn("Enter a USERNAME to connect to the Asterisk Manager interface:\n [admin] ");
322   $key = trim(fgets(STDIN,1024));
323   if (preg_match('/^$/',$key)) $amp_conf["AMPMGRUSER"] = "admin";
324   else $amp_conf["AMPMGRUSER"] = $key;
325  
326   outn("Enter a PASSWORD to connect to the Asterisk Manager interface:\n [amp111] ");
327   $key = trim(fgets(STDIN,1024));
328   if (preg_match('/^$/',$key)) $amp_conf["AMPMGRPASS"] = "amp111";
329   else $amp_conf["AMPMGRPASS"] = $key;
330  
331   do {
332     out("Enter the path to use for your AMP web root:\n [$webroot] ");
333     $key = trim(fgets(STDIN,1024));
334     if (preg_match('/^$/',$key))
335       $amp_conf["AMPWEBROOT"] = "$webroot";
336     else
337       $amp_conf["AMPWEBROOT"] = rtrim($key,'/');
338
339     if (is_dir($amp_conf["AMPWEBROOT"])) {
340       break;
341     } else if (amp_mkdir($amp_conf["AMPWEBROOT"],"0755",true)){
342       out("Created ".$amp_conf["AMPWEBROOT"]);
343       break;
344     } else {
345       fatal("Cannot create ".$amp_conf["AMPWEBROOT"]."!");
346     }
347   } while(1);
348  
349   // Really no need to ask, is there.
350   if (empty($fopwebroot))
351     $amp_conf["FOPWEBROOT"] = $amp_conf["AMPWEBROOT"]."/panel";
352   else
353     $amp_conf["FOPWEBROOT"] = $fopwebroot;
354  
355   outn("Enter the IP ADDRESS or hostname used to access the AMP web-admin:\n [xx.xx.xx.xx] ");
356   $key = trim(fgets(STDIN,1024));
357   if (preg_match('/^$/',$key)) $amp_conf["AMPWEBADDRESS"] = "xx.xx.xx.xx";
358   else $amp_conf["AMPWEBADDRESS"] = $key;
359  
360   outn("Enter a PASSWORD to perform call transfers with the Flash Operator Panel:\n [passw0rd] ");
361   $key = trim(fgets(STDIN,1024));
362   if (preg_match('/^$/',$key)) $amp_conf["FOPPASSWORD"] = "passw0rd";
363   else $amp_conf["FOPPASSWORD"] = $key;
364  
365   outn("Use simple Extensions [extensions] admin or separate Devices and Users [deviceanduser]?\n [extensions] ");
366   $key = trim(fgets(STDIN,1024));
367   if (preg_match('/^$/',$key)) $amp_conf["AMPEXTENSIONS"] = "extensions";
368   else $amp_conf["AMPEXTENSIONS"] = $key;
369  
370   do {
371     out("Enter directory in which to store AMP executable scripts:\n [$ampbin_dir] ");
372     $key = trim(fgets(STDIN,1024));
373     if (preg_match('/^$/',$key))
374       $amp_conf["AMPBIN"] = $ampbin_dir;
375     else
376       $amp_conf["AMPBIN"] = rtrim($key,'/');
377
378     if (is_dir($amp_conf["AMPBIN"])) {
379       break;
380     } else if (amp_mkdir($amp_conf["AMPBIN"],"0755",true)){
381       out("Created ".$amp_conf["AMPBIN"]);
382       break;
383     } else {
384       fatal("Cannot create ".$amp_conf["AMPBIN"]."!");
385     }
386   } while(1);
387  
388   do {
389     out("Enter directory in which to store super-user scripts:\n [$ampsbin_dir] ");
390     $key = trim(fgets(STDIN,1024));
391     if (preg_match('/^$/',$key))
392       $amp_conf["AMPSBIN"] = "$ampsbin_dir";
393     else
394       $amp_conf["AMPSBIN"] = rtrim($key,'/');
395
396     if (is_dir($amp_conf["AMPSBIN"])) {
397       break;
398     } else if (amp_mkdir($amp_conf["AMPSBIN"],"0755",true)){
399       out("Created ".$amp_conf["AMPSBIN"]);
400       break;
401     } else {
402       fatal("Cannot create ".$amp_conf["AMPSBIN"]."!");
403     }
404   } while(1);
405  
406   // write amportal.conf
407   write_amportal_conf($filename, $amp_conf);
408   outn(AMP_CONF." written");
409 }
410
411 /** Set base of packaged modules to the versions packaged in the tarball since they are
412  *  getting overwritten with the tarball from anything that may have been updated online.
413  *
414  */
415 function set_base_version() {
416   global $dryrun;
417
418   // read modules list from MODULE_DIR
419   //
420   $included_modules = array();
421   $dir = opendir(MODULE_DIR);
422   while ($file = readdir($dir)) {
423     if ($file[0] != "." && $file[0] != "_" && is_dir(MODULE_DIR."/".$file)) {
424       $included_modules[] = $file;
425     }
426   }
427   closedir($dir);
428
429   foreach ($included_modules as $up_module) {
430     outn("Checking $up_module.. ");
431     if (!$dryrun) {
432       out(set_module_version($up_module));
433     } else {
434       out("Dry Run Not Updated");
435     }
436   }
437 }
438
439 /** Install all modules packaged with the install. We use the force flag because the
440  *  the assumption is that the dependencies are met and the package is able to have
441  *  the modules installed.
442  */
443 function install_modules() {
444   global $dryrun;
445   global $amp_conf;
446
447   // read modules list from MODULE_DIR
448   //
449   $included_modules = array();
450   $dir = opendir(MODULE_DIR);
451   while ($file = readdir($dir)) {
452     if ($file[0] != "." && $file[0] != "_" && is_dir(MODULE_DIR."/".$file)) {
453       $included_modules[] = $file;
454     }
455   }
456   closedir($dir);
457
458   foreach ($included_modules as $up_module) {
459     outn("Checking $up_module.. ");
460     if (!$dryrun) {
461       // special case framework, it should not be installed just enabled.
462       //
463       if ($up_module != 'framework') {
464         system($amp_conf['AMPBIN']."/module_admin --no-warnings -f install $up_module");
465         system($amp_conf['AMPBIN']."/module_admin --no-warnings -f enable $up_module");
466         out("installed");
467       } else {
468         system($amp_conf['AMPBIN']."/module_admin --no-warnings -f enable $up_module");
469         out("enabled");
470       }
471     } else {
472       out("Dry Run Not Installed");
473     }
474   }
475 }
476
477 /** Set the module version number to the packaged version and enable
478  *  module must require not install.php or install.sql script
479  *  this is primarily to package core and framework with freepbx tarballs
480  *
481  */
482 function set_module_version($module) {
483   global $db;
484
485   $module_dir = MODULE_DIR;
486   $file_path = $module_dir.$module."/module.xml";
487   if (file_exists($file_path)) {
488     // TODO: this is bad, there are other version tags (depends on) but this
489     //       is equivalnet to what publish.pl does, so it expects this to be
490     //       at the top.
491     //
492     $module_xml = file_get_contents($file_path);
493     if (preg_match('/<version>(.+)<\/version>/', $module_xml, $matches)) {
494       $version = $matches[1];
495     } else {
496       fatal("ERROR: $file_path found but no verison information");
497     }
498   } else {
499     return  "not packaged, no updating needed";
500   }
501
502   // If we didn't return above, then we found the package as part of the install
503   // tarball and want to update the version info since this might be overwriting
504   // an existing install that has a newever version.
505   //
506   $sql = "SELECT version FROM modules WHERE modulename = '$module'";
507   $result = $db->getCol($sql);
508   if(DB::IsError($result)) {     
509     fatal("error accessing version table: ".$result->getMessage());
510   }
511   $sql = "";
512   if (count($result) == 0) {
513     // insert but disable as we have to first run install scripts which come later
514     $sql = "INSERT INTO modules (modulename, version, enabled) VALUES ('$module', '$version', 0)";
515   } else if ($result[0] != $version) {
516     if (version_compare_freepbx($version, $result[0], "gt")) {
517       // if new verison is greater than old, then we disable the module and it will get enabled next when installed
518       //
519       $sql = "UPDATE modules SET version = '$version', enabled = 0 WHERE modulename = '$module'";
520     } else {
521       // if new version is equal to or less than old, then we leave it in the enable/disable state it was in but just
522       // reset the version number.
523       //
524       $sql = "UPDATE modules SET version = '$version' WHERE modulename = '$module'";
525     }
526   }
527   if ($sql) {
528     debug($sql);
529     $result = $db->query($sql);
530     if(DB::IsError($result)) {     
531       fatal("error writing to version table: ".$result->getMessage());
532     }
533     return "updated to $version";
534   } else {
535     return "already at $version";
536   }
537 }
538
539 /********************************************************************************************************************/
540
541 // **** Make sure we have STDIN etc
542
543 // from  ben-php dot net at efros dot com   at  php.net/install.unix.commandline
544 if (version_compare(phpversion(),'4.3.0','<') || !defined("STDIN")) {
545   define('STDIN',fopen("php://stdin","r"));
546   define('STDOUT',fopen("php://stdout","r"));
547   define('STDERR',fopen("php://stderr","r"));
548   register_shutdown_function( create_function( '' , 'fclose(STDIN); fclose(STDOUT); fclose(STDERR); return true;' ) );
549 }
550    
551 // **** Make sure we have PEAR's DB.php, and include it
552
553 outn("Checking for PEAR DB..");
554 if (! @ include('DB.php')) {
555   out("FAILED");
556   fatal("PEAR must be installed (requires DB.php). Include path: ".ini_get("include_path"));
557 }
558 out("OK");
559
560 // **** Make sure we have PEAR's GetOpts.php, and include it
561
562 outn("Checking for PEAR Console::Getopt..");
563 if (! @ include("Console/Getopt.php")) {
564   out("FAILED");
565   fatal("PEAR must be installed (requires Console/Getopt.php). Include path: ".ini_get("include_path"));
566 }
567 out("OK");
568
569 // **** Parse out command-line options
570 $shortopts = "h?u:p:";
571 $longopts = array("help","debug","dry-run","username=","password=","force-version=","dbhost=","no-files","dbname=","my-svn-is-correct","engine=","webroot=","install-moh","make-links-devel","skip-module-install");
572
573 $args = Console_Getopt::getopt(Console_Getopt::readPHPArgv(), $shortopts, $longopts);
574 if (is_object($args)) {
575   // assume it's PEAR_ERROR
576   out($args->message);
577   exit(255);
578 }
579
580 $debug = false;
581 $dryrun = false;
582 $install_files = true;
583 $override_astvers = false;
584
585 $install_moh = false;
586 $make_links = false;
587 $module_install = true;
588
589 //initialize variables to avoid php notices
590 $dbhost = null;
591 $dbname = null;
592 $new_username = null;
593 $new_password = null;
594
595 foreach ($args[0] as $arg) {
596   switch ($arg[0]) {
597     case "--help": case "h": case "?":
598       showHelp();
599       exit(10);
600     break;
601     case "--dry-run":
602       out("Dry-run only, nothing will be changed");
603       $dryrun = true;
604     break;
605     case "--debug":
606       $debug = true;
607       debug("Debug mode enabled");
608     break;
609     case "--username": case "u":
610       out("Using username: ".$arg[1]);
611       $new_username = $arg[1];
612     break;
613     case "--password": case "p":
614       out("Using password: ".str_repeat("*",strlen($arg[1])));
615       $new_password = $arg[1];
616     break;
617     case "--force-version":
618       $version = $arg[1];
619       out("Forcing upgrade from version ".$version);
620     break;
621     case "--dbhost":
622       $dbhost = $arg[1];
623       out("Using remote database server at ".$dbhost);
624     break;
625     case "--dbname":
626       $dbname = $arg[1];
627       out("Using database ".$dbname);
628     break;
629     case "--no-files":
630       $install_files = false;
631       out("Running upgrade only, without installing files.");
632     break;
633     case "--my-svn-is-correct":
634       $override_astvers = true;
635     break;
636     case "--engine":
637       if ($arg[1] != 'asterisk' && $arg[1] != 'asterisk14' && $arg[1] != 'openpbx') {
638         fatal('Currently only "asterisk", "asterisk14" or "openpbx" are supported as a PBX engine');
639       }
640       $pbx_engine = $arg[1];
641     break;
642     case "--install-moh":
643       $install_moh = true;
644     break;
645     case "--make-links-devel":
646       $make_links = true;
647     break;
648     case "--skip-module-install":
649       $module_install = false;
650     break;
651     case "--fopwebroot":
652       $fopwebroot = $arg[1];
653       out("Using fop at ".$fopwebroot);
654     break;
655     case "--webroot":
656       $webroot = $arg[1];
657       out("Using Webroot at ".$webroot);
658     break;
659     case "--cgibin":
660       $cgibin = $arg[1];
661       out("Using CGI-BIN at ".$cgibin);
662     break;
663     case "--bin":
664       $ampbin_dir = $arg[1];
665       out("Using bin at ".$ampbin_dir);
666     break;
667     case "--sbin":
668       $ampsbin_dir = $arg[1];
669       out("Using sbin ar ".$ampsbin_dir);
670     break;
671     case "--asteriskuser":
672       $asterisk_user = $arg[1];
673       out("Using Asterisk user ".$asterisk_user);
674     break;
675     case "--asteriskpass":
676       $asterisk_pass = $arg[1];
677       out("Using asteriskpass ".str_repeat("*",strlen($arg[1])));
678     break;
679
680 /*    do we need this ?
681     case "--systemconfig":
682       $systemconfig = $arg[1];
683       out("Using system config at ". $systemconfig);
684     break;
685 */
686
687   }
688 }
689
690
691 // **** Look for user = root
692
693 outn("Checking user..");
694 //$current_user=(isset($_ENV["USER"]) ? $_ENV["USER"] : exec('whoami',$output));
695 $euid = (posix_getpwuid(posix_geteuid()));
696 $current_user = $euid['name'];
697 if ($current_user != "root"){
698   out("FAILED");
699   fatal($argv[0]." must be run as root");
700 }
701 out("OK");
702
703
704 outn("Checking if Asterisk is running..");
705 exec("pidof asterisk", $pid_val, $ret);
706 if ($ret) {
707   out("FAILED");
708   fatal($argv[0]."\n\tAsterisk must be running. If this is a first time install, you should start\n\tAsterisk by typing './start_asterisk start'\n\tFor upgrading, you should run 'amportal start'");
709 }
710 out("running with PID: ".$pid_val[0]."..OK");
711
712 // **** Check for amportal.conf, create if necessary
713
714 outn("Checking for ".AMP_CONF."..");
715 if (!file_exists(AMP_CONF)) {
716   out(AMP_CONF." does not exist, copying default");
717   copy("amportal.conf", AMP_CONF);
718
719   // this file contains password and should not be a+r
720   // this addresses http://freepbx.org/trac/ticket/1878
721   chown(AMP_CONF, "asterisk");
722   chgrp(AMP_CONF, "asterisk");
723   chmod(AMP_CONF, 0640);
724
725   collect_settings(AMP_CONF, $dbhost, $new_username, $new_password, 'asterisk');
726
727   out("Assuming new install, --install-moh added to command line");
728   $install_moh = true;
729 }
730 out("OK");
731
732 // **** read amportal.conf
733
734 outn("Reading ".AMP_CONF."..");
735 $amp_conf = install_parse_amportal_conf(AMP_CONF);
736 if (count($amp_conf) == 0) {
737   fatal("FAILED");
738 }
739 out("OK");
740
741 // Ensure our "critical" variables are set.  We absolutely need these to copy in files.
742
743 if (!array_key_exists("AMPWEBROOT",$amp_conf)) {
744   out("Adding AMPWEBROOT option to amportal.conf - using AMP default");
745   $amp_conf["AMPWEBROOT"] = "/var/www/html";
746 }
747
748 if (!array_key_exists("FOPWEBROOT",$amp_conf)) {
749   out("Adding FOPWEBROOT option to amportal.conf - using AMP default");
750   $amp_conf["FOPWEBROOT"] = $amp_conf["AMPWEBROOT"]."/panel";
751 }
752
753 if (!array_key_exists("AMPBIN",$amp_conf)) {
754   out("Adding AMPBIN option to amportal.conf - using AMP default");
755   $amp_conf["AMPBIN"] = "/var/lib/asterisk/bin";
756 }
757
758 if (!array_key_exists("AMPSBIN",$amp_conf)) {
759   out("Adding AMPSBIN option to amportal.conf - using AMP default");
760   $amp_conf["AMPSBIN"] = "/usr/sbin";
761 }
762
763 if (!array_key_exists("AMPDBENGINE",$amp_conf)) {
764   out("Adding AMPDBENGINE option to amportal.conf - using AMP default");
765   $amp_conf["AMPDBENGINE"] = "mysql";
766 }
767 if (!array_key_exists("AMPDBNAME",$amp_conf)) {
768   out("Adding AMPDBNAME option to amportal.conf - using AMP default");
769   $amp_conf["AMPDBNAME"] = "asterisk";
770 }
771
772 if (isset($new_username)) {
773   $amp_conf["AMPDBUSER"] = $new_username;
774 }
775
776 if (isset($new_password)) {
777   $amp_conf["AMPDBPASS"] = $new_password;
778 }
779
780 if (isset($dbhost)) {
781   $amp_conf["AMPDBHOST"] = $dbhost;
782 }
783
784 if (isset($dbname)) {
785   $amp_conf["AMPDBNAME"] = $dbname;
786 }
787  
788 // write amportal.conf
789 write_amportal_conf(AMP_CONF, $amp_conf);
790
791 // **** Check for amportal.conf, create if necessary
792
793 outn("Checking for ".ASTERISK_CONF."..");
794 if (!file_exists(ASTERISK_CONF)) {
795   out(ASTERISK_CONF." does not exist, copying default");
796   copy("asterisk.conf", ASTERISK_CONF);
797 }
798 out("OK");
799
800 // **** read asterisk.conf
801
802 outn("Reading ".ASTERISK_CONF."..");
803 $asterisk_conf = install_parse_asterisk_conf(ASTERISK_CONF);
804 if (count($asterisk_conf) == 0) {
805   fatal("FAILED. Have you installed Asterisk?");
806 }
807 out("OK");
808
809 /* deprecated on freepbx 2.2, from now pages need to read this information
810    from $asterik_conf and not $amp_conf.
811    
812    this code will stay in 2.2, but in 2.3 it will be gone. developers - please
813    update your code
814  */
815 if (isset($asterisk_conf['astetcdir'])) { $amp_conf['ASTETCDIR'] = $asterisk_conf['astetcdir']; }
816 if (isset($asterisk_conf['astmoddir'])) { $amp_conf['ASTMODDIR'] = $asterisk_conf['astmoddir']; }
817 if (isset($asterisk_conf['astvarlibdir'])) { $amp_conf['ASTVARLIBDIR'] = $asterisk_conf['astvarlibdir']; }
818 if (isset($asterisk_conf['astagidir'])) { $amp_conf['ASTAGIDIR'] = $asterisk_conf['astagidir']; }
819 if (isset($asterisk_conf['astspooldir'])) { $amp_conf['ASTSPOOLDIR'] = $asterisk_conf['astspooldir']; }
820 if (isset($asterisk_conf['astrundir'])) { $amp_conf['ASTRUNDIR'] = $asterisk_conf['astrundir']; }
821 if (isset($asterisk_conf['astlogdir'])) { $amp_conf['ASTLOGDIR'] = $asterisk_conf['astlogdir']; }
822
823 if (!isset($pbx_engine)) { $pbx_engine='asterisk'; }
824 out("Using $pbx_engine as PBX Engine");
825 $amp_conf["AMPENGINE"]=$pbx_engine;
826
827 write_amportal_conf(AMP_CONF, $amp_conf);
828
829
830 // **** Write asterisk version to ASTETCDIR/version
831
832 $tmpoutput = '';
833 $tmpout = exec("asterisk -V", $tmpoutput, $exitcode);
834 if ($exitcode != 0) {
835   fatal("Error executing asterisk: be sure Asterisk is installed and in the path");
836 }
837 if (!$fd = fopen($amp_conf['ASTETCDIR'].'/version','w')) {
838   fatal('Cannot open '.$amp_conf['ASTETCDIR'].'/version for writing');
839 }
840 fwrite($fd, $tmpout);
841 fclose($fd);
842 // change to read-only
843 chmod($amp_conf['ASTETCDIR'].'/version',0444);
844
845
846 // normally this would be the contents of ASTETCDIR/version, but this is for simplicity, as we just read it above
847 $verinfo = $tmpout;
848
849 // **** Check asterisk verison
850 //  Set the 'engine' to be 'asterisk14' if using asterisk 1.4, otherwise
851 //  'asterisk'
852 outn("Checking for Asterisk version..");
853 if ((preg_match('/^Asterisk (\d+(\.\d+)*)(-?(.*))$/', $verinfo, $matches)) ||
854     (preg_match('/^Asterisk SVN-(\d+(\.\d+)*)(-?(.*))$/', $verinfo, $matches))) {
855
856   if (version_compare($matches[1], "1.2") < 0) {
857     fatal("Asterisk 1.2 or 1.4 is required for this version of FreePBX. Detected version is: ".$matches[1]);
858   }
859   if (version_compare($matches[1], "1.7", "ge")) {
860     fatal("Asterisk 1.2, 1.4, or 1.6 is required for this version of FreePBX. Detected version is: ".$matches[1]);
861   }
862   out("{$matches[1]}");
863 } elseif (preg_match('/^Asterisk SVN.+/', $verinfo)) {
864   out("FAIL");
865   out("*** WARNING ***");
866   out("You are not using a released version of Asterisk. We are unable to verify");
867   out("that your Asterisk version is compatible with FreePBX. Whilst this probably");
868   out("won't cause any problems, YOU NEED TO BE CERTAIN that it is compatible");
869   out("with at least the released Asterisk version 1.2" );
870   if ($override_astvers==false) {
871     out("If you are SURE that this is compatible, you can re-run ".$argv[0]." with");
872     out("the parameter --my-svn-is-correct");
873     exit;
874   } else {
875     out("--my-svn-is-correct specified, continuing");
876   }
877 } else {
878   fatal("Could not determine asterisk version (got: \"".$verinfo."\" please report this)");
879 }
880
881 // **** Make sure selinux isn't enabled
882
883 outn("Checking for selinux..");
884 $tmpoutput = '';
885 $tmpout = exec("selinuxenabled 2>&1", $tmpoutput, $sereturn);
886 if ($sereturn == 0) {
887   fatal("selinux is ENABLED. This is not supported. Please disable selinux before using FreePBX");
888 }
889 out("OK");
890
891 // **** Connect to database
892
893 outn("Connecting to database..");
894
895 $db_user = $amp_conf["AMPDBUSER"];
896 $db_pass = $amp_conf["AMPDBPASS"];
897 $db_host = $amp_conf["AMPDBHOST"];
898 $db_engine = $amp_conf["AMPDBENGINE"];
899 $db_name = $amp_conf["AMPDBNAME"];
900
901 // we still support older configurations,  and fall back
902 // into mysql when no other engine is defined
903 if ($db_engine == "")
904 {
905   $db_engine = "mysql";
906 }
907  
908 switch ($db_engine)
909 {
910   case "pgsql":
911   case "mysql":
912     // datasource in in this style: dbengine://username:password@host/database
913     if (!function_exists($db_engine.'_connect')) {
914       out("FAILED");
915       fatal($db_engine." PHP libraries not installed");
916     }
917  
918     $datasource = $db_engine.'://'.$db_user.':'.$db_pass.'@'.$db_host.'/'.$db_name;
919     $db = DB::connect($datasource); // attempt connection
920     break;
921  
922   case "sqlite":
923     die_freepbx("SQLite2 support is deprecated. Please use sqlite3 only.");
924     break;
925  
926   case "sqlite3":
927     if (!isset($amp_conf["AMPDBFILE"]))
928       die("You must setup properly AMPDBFILE in /etc/amportal.conf");
929      
930     if (isset($amp_conf["AMPDBFILE"]) == "")
931       die("AMPDBFILE in /etc/amportal.conf cannot be blank");
932
933     /* on centos this extension is not loaded by default */
934     if (! extension_loaded('sqlite3.so') )
935       dl('sqlite3.so');
936
937     if (! @require_once('DB/sqlite3.php') )
938     {
939       out("FAILED");
940       fatal( "Your PHP installation has no PEAR/SQLite3 support. Please install php-sqlite3 and php-pear.");
941     }
942
943     $datasource = "sqlite3:///" . $amp_conf["AMPDBFILE"] . "?mode=0666";
944     $db = DB::connect($datasource);
945     break;
946
947   default:
948     die( "Unknown SQL engine: [$db_engine]");
949 }
950
951 if(DB::isError($db)) {
952   out("FAILED");
953   debug($db->userinfo);
954   out("Try running ".$argv[0]." --username=user --password=pass  (using your own user and pass)");
955   fatal("Cannot connect to database");
956  
957 }
958 out("OK");
959
960
961 // **** Read DB for version info
962
963 if (!isset($version)) {
964   outn("Checking current version of AMP..");
965   $version = install_getversion();
966   if (!$version) {
967     out("no version information");
968     out("Assuming new installation");
969   } else {
970     out($version);
971   }
972 }
973
974
975 // **** Copy files
976
977 if ($install_files)
978 {
979   outn("Installing new FreePBX files..");
980   $check_md5s=true;
981   $md5sums = read_md5_file(UPGRADE_DIR."/".$version.".md5");
982   list($num_files, $num_copied) = recursive_copy("amp_conf", "", $md5sums);
983   if (!is_file("/etc/asterisk/voicemail.conf")) copy("/etc/asterisk/voicemail.conf.template","/etc/asterisk/voicemail.conf");
984   if (!is_dir("/var/spool/asterisk/voicemail/device")) amp_mkdir("/var/spool/asterisk/voicemail/device", "0755", true);
985   out("OK (".$num_copied." files copied, ".($num_files-$num_copied)." skipped)");
986 }
987
988 // **** Apply amportal.conf configuration to files
989 debug("Running ".dirname(__FILE__)."/apply_conf.sh");
990 outn("Configuring install for your environment..");
991 if (!$dryrun) {
992   if (file_exists($amp_conf["AMPSBIN"]."/amportal")) {
993     exec("chmod u+x ".$amp_conf["AMPSBIN"]."/amportal");
994     outn("amportal..");
995   } else {
996     outn("no amportal..");
997   }
998   if (file_exists($amp_conf["AMPBIN"]."/freepbx_engine")) {
999     exec("chmod u+x ".$amp_conf["AMPBIN"]."/freepbx_engine");
1000     outn("freepbx_engine..");
1001   } else {
1002     outn("no freepbx_engine..");
1003   }
1004   out("done");
1005   // edit conf file passwords and then
1006   // reload manager in asterisk if it is running:
1007   //
1008   outn("apply username/password changes to conf files..");
1009   exec(dirname(__FILE__)."/apply_conf.sh");
1010   out("done");
1011
1012   /* As of Asterisk 1.4.16 or there abouts, a missing #include file will make the reload fail. So
1013     we need to make sure that we have such for everything that is in our configs. We will simply
1014     look for the #include statements and touch the files vs. trying to inventory everything we may
1015     need and then forgetting something.
1016   */
1017
1018   outn("creating missing #include files..");
1019   $include_err = false;
1020   exec("grep '#include' ".$amp_conf['ASTETCDIR']."/*.conf | sed 's/;.*//; s/#include//'",$output,$retcode);
1021   if ($retcode != 0) {
1022     out("Error code $retcode: trying to search for missing #include files");
1023     $include_err = true;
1024   }
1025
1026   foreach($output as $file) {
1027     if (trim($file) == '') {
1028       continue;
1029     }
1030     $parse1 = explode(':',$file);
1031     $parse2 = explode(';',$parse1[1]);
1032     $rawfile = trim($parse2[0]);
1033     if ($rawfile == '') {
1034       continue;
1035     }
1036
1037     $target = ($rawfile[0] == '/') ? $rawfile : $amp_conf['ASTETCDIR']."/$rawfile";
1038
1039     if (!file_exists($target)) {
1040       exec("touch $target", $output, $retcode);
1041         if ($retcode != 0) {
1042         out("Error code $retcode: trying to create empty file $target");
1043         $include_err = true;
1044       }
1045     }
1046   }
1047   if (! $include_err) {
1048     out("OK");
1049   }
1050   // reload manager in asterisk if it was running:
1051   // Execute the 1.4+ syntax and the 1.2 syntax, it will reload twice on 1.4 and in the other cases
1052   // it will simply ignore the command since it has been removed. (not worth trying to figure out what
1053   // version they have...
1054   //
1055   system("asterisk -rx 'module reload manager'");
1056   system("asterisk -rx 'reload manager'");
1057 }
1058 out("OK");
1059
1060 // **** Create spool directories for monitor and fax
1061 if (!is_dir($asterisk_conf["astspooldir"]."/monitor"))
1062   amp_mkdir($asterisk_conf["astspooldir"]."/monitor","0766",true);
1063 if (!is_dir($asterisk_conf["astspooldir"]."/fax"))
1064   amp_mkdir($asterisk_conf["astspooldir"]."/fax","0766",true);
1065
1066
1067 // **** Set permissions all files
1068
1069 if ($install_files)
1070 {
1071   outn("Setting permissions on files..");
1072   if (!$dryrun) {
1073     exec($amp_conf["AMPSBIN"]."/amportal chown");
1074   }
1075   out("OK");
1076 }
1077
1078 // Run through all the upgrade scripts starting at the specified version
1079 //
1080 upgrade_all($version);
1081
1082 // **** Generate AMP configs
1083 out("Generating AMP configs..");
1084 generate_configs();
1085 out("Generating AMP configs..OK");
1086
1087 $version = install_getversion();
1088 $filename = $amp_conf["AMPWEBROOT"]."/admin/version.txt";
1089 if (!$fd = fopen($filename, "w")) {
1090   fatal("Could not open ".$filename." for writing");
1091 }
1092 fwrite($fd, $version);
1093 fclose($fd);
1094
1095 // **** Bounce FOP
1096 outn("Restarting Flash Operator Panel..");
1097 exec('su - asterisk -c "'.$amp_conf["AMPBIN"].'/bounce_op.sh"');
1098 out("OK");
1099
1100
1101 // Now force an install for all modules that are packaged with the tarball
1102 // directory.
1103 //
1104 if ($module_install) {
1105   install_modules();
1106 } else {
1107   out("bypassing packaged module installation because --skip-module-install flag");
1108 }
1109
1110
1111 // **** Set reload flag for AMP admin
1112 install_needreload();
1113
1114 if ($amp_conf["AMPWEBADDRESS"])
1115 {
1116   out("Please update your modules and reload Asterisk by visiting http://".$amp_conf["AMPWEBADDRESS"]."/admin");
1117 }
1118 else
1119 {
1120   out("Please update your modules and reload Asterisk by browsing to your server.");
1121 }
1122
1123 out("");
1124 out("*************************************************************************");
1125 out("* Note: It's possible that if you click the red 'Update Now' bar BEFORE *");
1126 out("* updating your modules, your machine will start dropping calls. Ensure *");
1127 out("* that all modules are up to date BEFORE YOU CLICK THE RED BAR. As long *");
1128 out("* as this is observed, your machine will be fully functional whilst the *");
1129 out("* upgrade is in progress.                                               *");
1130 out("*************************************************************************");
1131 ?>
Note: See TracBrowser for help on using the browser.