root/freepbx/trunk/install_amp

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

Merged revisions 3536-3541,3543-3545,3547-3548 via svnmerge from
https://amportal.svn.sourceforge.net/svnroot/amportal/freepbx/branches/2.2

........

r3538 | gregmac | 2007-01-05 04:31:02 +1000 (Fri, 05 Jan 2007) | 2 lines


Fix typo #1636

........

r3540 | qldrob | 2007-01-05 07:29:08 +1000 (Fri, 05 Jan 2007) | 2 lines


Prepare for 2.2.0 release. Yay.

........

r3543 | qldrob | 2007-01-05 08:33:40 +1000 (Fri, 05 Jan 2007) | 2 lines


Fix md5 for 2.2.0

........

r3548 | qldrob | 2007-01-09 10:56:02 +1000 (Tue, 09 Jan 2007) | 2 lines


Convert mp3 MOH files to sln

........

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