root/freepbx/trunk/install_amp

Revision 3436, 32.8 kB (checked in by qldrob, 6 years ago)

Start support for 'asterisk14' engine. I may end up taking this out.

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