root/freepbx/tags/2.2.2/install_amp

Revision 4015, 33.5 kB (checked in by p_lindheimer, 6 years ago)

oops - didn't get install_amp checked in before making the tarball

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