root/freepbx/branches/2.2/install_amp

Revision 4685, 34.0 kB (checked in by gregmac, 5 years ago)

Fix #1878 for 2.2 branch

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