root/freepbx/branches/2.3.views/install_amp

Revision 4344, 39.2 kB (checked in by gregmac, 2 years ago)

syntax typo (r4343)

  • 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 # constants
5 define("AMP_CONF", "/etc/amportal.conf");
6 define("ASTERISK_CONF", "/etc/asterisk/asterisk.conf");
7 define("UPGRADE_DIR", dirname(__FILE__)."/upgrades");
8
9 # semi constants
10 $webroot        = "/var/www/html/";
11 $fopwebroot     = "";                           // if blank, will use $webroot/panel
12 $bin_dir        = "/var/lib/asterisk/bin/";
13 $sbin_dir       = "/usr/sbin/";
14 $asterisk_user  = "asteriskuser";
15 $asterisk_pass  = "amp109";
16
17
18 /*
19 freepbx versions
20                 '1.10.005',
21                 '1.10.006',
22                 '1.10.007beta1',
23                 '1.10.007beta2',
24                 '1.10.007',
25                 '1.10.007a',
26                 '1.10.008beta1',
27                 '1.10.008beta2',
28                 '1.10.008beta3',
29                 '1.10.008',
30                 '1.10.009beta1',
31                 '1.10.009beta2',
32                 '1.10.009',
33                 '1.10.010beta1',
34                 '1.10.010',
35                 '2.0beta1',
36                 '2.0beta2',
37                 '2.0beta3',
38                 '2.0beta4',
39                 '2.0beta5',
40                 '2.0.0',
41                 '2.0.1',
42                 '2.1beta1',
43                 '2.1beta2',
44                 '2.1beta3',
45                 '2.1.0',
46                 '2.1.1',
47                 '2.1.2',
48                 '2.1.3',
49                 '2.2.0beta1',
50                 '2.2.0beta2',
51                 '2.2.0beta3',
52                 '2.2.0rc1',
53                 '2.2.0rc2',
54                 '2.2.0rc3',
55                 '2.2.0',
56                 '2.2.1',
57                 '2.2.2',
58                 '2.2.3',
59                 '2.3.0beta1',
60 */
61
62
63 /********************************************************************************************************************/
64
65 function out($text) {
66         echo $text."\n";
67 }
68
69 function outn($text) {
70         echo $text;
71 }
72
73 function error($text) {
74         echo "[ERROR] ".$text."\n";
75 }
76
77 function fatal($text) {
78         echo "[FATAL] ".$text."\n";
79         exit(1);
80 }
81
82 function debug($text) {
83         global $debug;
84        
85         if ($debug) echo "[DEBUG-preDB] ".$text."\n";
86 }
87
88 function version_compare_freepbx($version1, $version2) {
89         $version1 = str_replace("rc","RC", strtolower($version1));
90         $version2 = str_replace("rc","RC", strtolower($version2));
91         return version_compare($version1, $version2);
92 }
93
94 function showHelp() {
95         out("Optional parameters:");
96         out("  --help, -h, -?           Show this help");
97         out("  --dbhost <ip address>    Use a remote database server");
98         out("  --dbname databasename    Use database name specified, instead of 'asterisk'");
99         out("  --username <user>        Use <user> to connect to db and write config");
100         out("  --password <pass>        Use <pass> to connect to db and write config");
101         out("  --fopwebroot <path>      Web path where fop will be installed");
102         out("  --webroot <path>         Web root where freepbx will be installed");
103         out("  --cgibin <path>          Path where cgi-bin's lives");
104         out("  --bin <path>             Path of asterisk binaries");
105         out("  --sbin <path>            Path of system admin binaries");
106         out("  --asteriskuser <user>    Asterisk Manager username");
107         out("  --asteriskpass <pass>    Asterisk Manager password");
108         out("  --systemconfig <path>    System config files");
109         out("  --debug                  Enable debug output");
110         out("  --dry-run                Don't actually do anything");
111         out("  --force-version <ver>    Force upgrade from version <ver>");
112         out("  --no-files               Just run updates without installing files");
113         out("  --install-moh            Install default music-on-hold files (normally doesn't, unless ");
114         out("                           it's a new installation)");
115         //out("  --make-links-devel       Make links to files in the source directory instead of copying");
116         //out("                           (intended for developers only)");
117         out("  --my-svn-is-correct      Ignore Asterisk version, assume it is correct");
118         out("  --engine <name>          Use the specified PBX Engine ('asterisk', 'asterisk14' or 'openpbx')");
119 }
120
121 function install_parse_amportal_conf($filename) {
122         $file = file($filename);
123         foreach ($file as $line) {
124                 if (preg_match("/^\s*([a-zA-Z0-9]+)\s*=\s*(.*)\s*([;#].*)?/",$line,$matches)) {
125                         $conf[ $matches[1] ] = $matches[2];
126                 }
127         }
128
129         // use same defaults as function.inc.php
130         if ( !isset($conf["AMPDBENGINE"]) || ($conf["AMPDBENGINE"] == "")) {
131                 $conf["AMPDBENGINE"] = "mysql";
132         }
133        
134         if ( !isset($conf["AMPDBNAME"]) || ($conf["AMPDBNAME"] == "")) {
135                 $conf["AMPDBNAME"] = "asterisk";
136         }
137        
138         if ( !isset($conf["AMPENGINE"]) || ($conf["AMPENGINE"] == "")) {
139                 $conf["AMPENGINE"] = "asterisk";
140         }
141
142         return $conf;
143 }
144
145 function install_parse_asterisk_conf($filename) {
146         $file = file($filename);
147         foreach ($file as $line) {
148                 if (preg_match("/^\s*([a-zA-Z0-9]+)\s* => \s*(.*)\s*([;#].*)?/",$line,$matches)) {
149                         $conf[ $matches[1] ] = $matches[2];
150                 }
151         }
152         // Now set defaults if not set (although asterisk should fail if not set but at least
153         // it will get the setup somewhat right
154         //
155         if (!isset($asterisk_conf['astetcdir']))    { $asterisk_conf['astetcdir']    = "/etc/asterisk"; }
156         if (!isset($asterisk_conf['astmoddir']))    { $asterisk_conf['astmoddir']    = "/usr/lib/asterisk/modules"; }
157         if (!isset($asterisk_conf['astvarlibdir'])) { $asterisk_conf['astvarlibdir'] = "/var/lib/asterisk"; }
158         if (!isset($asterisk_conf['astagidir']))    { $asterisk_conf['astagidir']    = "/var/lib/asterisk/agi-bin"; }
159         if (!isset($asterisk_conf['astspooldir']))  { $asterisk_conf['astspooldir']  = "/var/spool/asterisk"; }
160         if (!isset($asterisk_conf['astrundir']))    { $asterisk_conf['astrundir']    = "/var/run/asterisk"; }
161         if (!isset($asterisk_conf['astlogdir']))    { $asterisk_conf['astlogdir']    = "/var/log/asterisk"; }
162
163         return $conf;
164 }
165
166 //get the version number
167 function install_getversion() {
168         global $db;
169         $sql = "SELECT value FROM admin WHERE variable = 'version'";
170         $results = $db->getAll($sql);
171         if(DB::IsError($results)) {
172                 return false;
173         }
174         return $results[0][0];
175 }
176
177 //set the version number
178 function setversion($version) {
179         global $db;
180         $sql = "UPDATE admin SET value = '".$version."' WHERE variable = 'version'";
181         debug($sql);
182         $result = $db->query($sql);
183         if(DB::IsError($result)) {     
184                 die($result->getMessage());
185         }
186 }
187
188 function write_amportal_conf($filename, $conf) {
189         $file = file($filename);
190         // parse through the file
191         foreach (array_keys($file) as $key) {
192                 if (preg_match("/^\s*([a-zA-Z0-9]+)\s*=\s*(.*)\s*([;#].*)?/",$file[$key],$matches)) {
193                         // this is an option=value line
194                         if (isset($conf[ $matches[1] ])) {
195                                 // rewrite the line, if we have this in $conf
196                                 $file[$key] = $matches[1]."=".$conf[ $matches[1] ]."\n";
197                                 // unset it so we know what's new
198                                 unset($conf[ $matches[1] ]);
199                         }
200                 }
201         }
202        
203         // add new entries
204         foreach ($conf as $key=>$val) {
205                 $file[] = $key."=".$val."\n";
206         }
207        
208         // write the file
209         if (!$fd = fopen($filename, "w")) {
210                 fatal("Could not open ".$filename." for writing");
211         }
212         fwrite($fd, implode("",$file));
213         fclose($fd);
214 }
215
216 function ask_overwrite($file1, $file2) {
217         global $check_md5s;
218         do {
219                 out($file2." has been changed from the original version.");
220                 outn("Overwrite (y=yes/a=all/n=no/d=diff/s=shell/x=exit)? ");
221                 $key = fgets(STDIN,1024);
222                 switch (strtolower($key[0])) {
223                         case "y": return true;
224                         case "a": $check_md5s=false; return true;
225                         case "n": return false;
226                         case "d":
227                                 out("");
228                                 // w = ignore whitespace, u = unified
229                                 passthru("diff -wu ".escapeshellarg($file2)." ".escapeshellarg($file1));
230                         break;
231                         case "s":
232                                 if (function_exists("pcntl_fork")) {
233                                         out("");
234                                         $shell = (isset($_ENV["SHELL"]) ? $_ENV["SHELL"] : "/bin/bash");
235                                         out("Dropping to shell. Type 'exit' to return");
236                                         out("-> Original file:  ".$file2);
237                                         out("-> New file:       ".$file1);
238                                        
239                                         $pid = pcntl_fork();
240                                         if ($pid == -1) {
241                                                 out("[ERROR] cannot fork");
242                                         } else if ($pid) {
243                                                 // parent
244                                                 pcntl_waitpid($pid, $status);
245                                                 // we wait till the child exits/dies/whatever
246                                         } else {
247                                                 pcntl_exec($shell, array(), $_ENV);
248                                         }
249                                        
250                                         out("Returned from shell");
251                                 } else {
252                                         out("[ERROR] PHP not built with process control (--enable-pcntl) support: cannot spawn shell");
253                                 }
254                                
255                         break;
256                         case "x":
257                                 out("-> Original file:  ".$file2);
258                                 out("-> New file:       ".$file1);
259                                 out("Exiting install program.");
260                                 exit(1);
261                         break;
262                 }
263                 out("");
264         } while(1);
265 }
266
267 function checkDiff($file1, $file2) {
268         // diff, ignore whitespace and be quiet
269         exec("diff -wq ".escapeshellarg($file2)." ".escapeshellarg($file1), $output, $retVal);
270         return ($retVal != 0);
271 }
272
273 function amp_mkdir($directory, $mode = "0755", $recursive = false) {
274         debug("mkdir ".$directory.", ".$mode);
275         $ntmp = sscanf($mode,"%o",$modenum); //assumes all inputs are octal
276         if (version_compare(phpversion(), 5.0) < 0) {
277                 // php <5 can't recursively create directories
278                 if ($recursive) {
279                         $output = false;
280                         $return_value = false;
281                         exec("mkdir -m ".$mode." -p ".$directory,  $output, $return_value);
282                         return ($return_value == 0);
283                 } else {
284                         return mkdir($directory, $modenum);
285                 }
286         } else {
287                 return mkdir($directory, $modenum, $recursive);
288         }
289 }
290
291 /** Recursively copy a directory
292  */
293 function recursive_copy($dirsourceparent, $dirdest, &$md5sums, $dirsource = "") {
294         global $dryrun;
295         global $check_md5s;
296         global $amp_conf;
297         global $asterisk_conf;
298         global $install_moh;
299         global $make_links;
300
301         // total # files, # actually copied
302         $num_files = $num_copied = 0;
303        
304         if ($dirsource && ($dirsource[0] != "/")) $dirsource = "/".$dirsource;
305        
306         if (is_dir($dirsourceparent.$dirsource)) $dir_handle = opendir($dirsourceparent.$dirsource);
307        
308         /*
309         echo "dirsourceparent: "; var_dump($dirsourceparent);
310         echo "dirsource: "; var_dump($dirsource);
311         echo "dirdest: "; var_dump($dirdest);
312         */
313        
314         while (isset($dir_handle) && ($file = readdir($dir_handle))) {
315                 if (($file!=".") && ($file!="..") && ($file != "CVS") && ($file != ".svn")) {
316                         $source = $dirsourceparent.$dirsource."/".$file;
317                         $destination =  $dirdest.$dirsource."/".$file;
318                        
319                         if ($dirsource == "" && $file == "mohmp3" && !$install_moh) {
320                                 // skip to the next dir
321                                 continue;
322                         }
323
324                        
325                         // configurable in amportal.conf
326                         if (strpos($destination,"htdocs_panel")) {
327                                 $destination=str_replace("/htdocs_panel",trim($amp_conf["FOPWEBROOT"]),$destination);
328                         } else {
329                                 $destination=str_replace("/htdocs",trim($amp_conf["AMPWEBROOT"]),$destination);
330                         }
331                         $destination=str_replace("/htdocs_panel",trim($amp_conf["FOPWEBROOT"]),$destination);
332 //                      $destination=str_replace("/cgi-bin",trim($amp_conf["AMPCGIBIN"]),$destination);
333                         if(strpos($dirsource, 'modules') === false) $destination=str_replace("/bin",trim($amp_conf["AMPBIN"]),$destination);
334                         $destination=str_replace("/sbin",trim($amp_conf["AMPSBIN"]),$destination);
335                        
336                         // the following are configurable in asterisk.conf
337                         $destination=str_replace("/astetc",trim($asterisk_conf["astetcdir"]),$destination);
338                         $destination=str_replace("/mohmp3",trim($asterisk_conf["astvarlibdir"])."/mohmp3",$destination);
339                         $destination=str_replace("/astvarlib",trim($asterisk_conf["astvarlibdir"]),$destination);
340                         if(strpos($dirsource, 'modules') === false) $destination=str_replace("/agi-bin",trim($asterisk_conf["astagidir"]),$destination);
341                         if(strpos($dirsource, 'modules') === false) $destination=str_replace("/sounds",trim($asterisk_conf["astvarlibdir"])."/sounds",$destination);
342
343                         // if this is a directory, ensure destination exists
344                         if (is_dir($source)) {
345                                 if (!file_exists($destination)) {
346                                         if ((!$dryrun) && ($destination != "")) {
347                                                 amp_mkdir($destination, "0750", true);
348                                         }
349                                 }
350                         }
351                        
352                         //var_dump($md5sums);
353                         if (!is_dir($source)) {
354                                 $md5_source = preg_replace("|^/?amp_conf/|", "/", $source);
355
356                                 if ($check_md5s && file_exists($destination) && isset($md5sums[$md5_source]) && (md5_file($destination) != $md5sums[$md5_source])) {
357                                         // double check using diff utility (and ignoring whitespace)
358                                         // This is a somewhat edge case (eg, the file doesn't match
359                                         // it's md5 sum from the previous version, but no substantial
360                                         // changes exist compared to the current version), but it
361                                         // pervents a useless prompt to the user.
362                                         if (checkDiff($source, $destination)) {
363                                                 $overwrite = ask_overwrite($source, $destination);
364                                         } else {
365                                                 debug("NOTE: MD5 for ".$destination." was different, but `diff` did not detect any (non-whitespace) changes: overwriting");
366                                                 $overwrite = true;
367                                         }
368                                 } else {
369                                         $overwrite = true;
370                                 }
371                                
372                                 $num_files++;
373                                 if ($overwrite) {
374                                         debug(($make_links ? "link" : "copy")." ".$source." -> ".$destination);
375                                         if (!$dryrun) {
376                                                 if ($make_links) {
377                                                         // symlink, unlike copy, doesn't overwrite - have to delete first
378                                                         if (is_link($destination) || file_exists($destination)) {
379                                                                 unlink($destination);
380                                                         }
381                                                         symlink($_ENV["PWD"]."/".$source, $destination);
382                                                 } else {
383                                                         copy($source, $destination);
384                                                 }
385                                                 $num_copied++;
386                                         }
387                                 } else {
388                                         debug("not overwriting ".$destination);
389                                 }
390                         } else {
391                                 //echo "recursive_copy($dirsourceparent, $dirdest, $md5sums, $dirsource/$file)";
392                                 list($tmp_num_files, $tmp_num_copied) = recursive_copy($dirsourceparent, $dirdest, $md5sums, $dirsource."/".$file);
393                                 $num_files += $tmp_num_files;
394                                 $num_copied += $tmp_num_copied;
395                         }
396                 }
397         }
398        
399         if (isset($dir_handle)) closedir($dir_handle);
400        
401         return array($num_files, $num_copied);
402 }
403
404 function read_md5_file($filename) {
405         $md5 = array();
406         if (file_exists($filename)) {
407                 foreach (file($filename) as $line) {
408                         if (preg_match("/^([a-f0-9]{32})\s+(.*)$/", $line, $matches)) {
409                                 $md5[ "/".$matches[2] ] = $matches[1];
410                         }
411                 }
412         }
413         return $md5;
414 }
415
416 /** Include a .php file
417  * This is a function just to keep a seperate context
418  */
419 function run_included($file) {
420         global $db;
421         global $amp_conf;
422        
423         include($file);
424 }
425
426
427 function install_sqlupdate( $version, $file )
428 {
429         global $db;
430         global $dryrun;
431
432         out("-> Running SQL script ".UPGRADE_DIR."/".$version."/".$file);
433         // run sql script
434         $fd = fopen(UPGRADE_DIR."/".$version."/".$file, "r");
435         $data = "";
436         while (!feof($fd)) {
437                 $data .= fread($fd, 1024);
438         }
439         fclose($fd);
440
441         preg_match_all("/((SELECT|INSERT|UPDATE|DELETE|CREATE|DROP|ALTER).*);\s*\n/Us", $data, $matches);
442        
443         foreach ($matches[1] as $sql) {
444                 debug($sql);
445                 if (!$dryrun) {
446                         $result = $db->query($sql);
447                         if(DB::IsError($result)) {     
448                                 fatal($result->getDebugInfo()."\" while running ".$file."\n");
449                         }
450                 }
451         }
452 }
453
454 /** Install a particular version
455  */
456 function install_upgrade($version) {
457         global $db;
458         global $dryrun;
459         global $amp_conf;
460        
461         $db_engine = $amp_conf["AMPDBENGINE"];
462        
463         if (is_dir(UPGRADE_DIR."/".$version)) {
464                 // sql scripts first
465                 $dir = opendir(UPGRADE_DIR."/".$version);
466                 while ($file = readdir($dir)) {
467                         if (($file[0] != ".") && is_file(UPGRADE_DIR."/".$version."/".$file)) {
468                                 if ( (strtolower(substr($file,-4)) == ".sqlite") && ($db_engine == "sqlite") ) {
469                                         install_sqlupdate( $version, $file );
470                                 }
471                                 elseif ((strtolower(substr($file,-4)) == ".sql") &&
472                                                 ( ($db_engine  == "mysql")  ||  ($db_engine  == "pgsql") || ($db_engine == "sqlite3") ) ) {
473                                         install_sqlupdate( $version, $file );
474                                 }
475                         }
476                 }
477
478                 // now non sql scripts
479                 $dir = opendir(UPGRADE_DIR."/".$version);
480                 while ($file = readdir($dir)) {
481                         if (($file[0] != ".") && is_file(UPGRADE_DIR."/".$version."/".$file)) {
482                                 if ((strtolower(substr($file,-4)) == ".sql") || (strtolower(substr($file,-7)) == ".sqlite")) {
483                                         // sql scripts were dealt with first
484                                 } else if (strtolower(substr($file,-4)) == ".php") {
485                                         out("-> Running PHP script ".UPGRADE_DIR."/".$version."/".$file);
486                                         if (!$dryrun) {
487                                                 run_included(UPGRADE_DIR."/".$version."/".$file);
488                                         }
489
490                                 } else if (is_executable(UPGRADE_DIR."/".$version."/".$file)) {
491                                         out("-> Executing ".UPGRADE_DIR."/".$version."/".$file);
492                                         if (!$dryrun) {
493                                                 exec(UPGRADE_DIR."/".$version."/".$file);
494                                         }
495                                 } else {
496                                         error("-> Don't know what to do with ".UPGRADE_DIR."/".$version."/".$file);
497                                 }
498                         }
499                 }
500
501         }
502 }
503
504 /** Set base of core and framework to the main release and make sure enabled
505  *
506  * TODO: CHANGE THIS, SET BASE VERSION BASED ON WHAT IS PACKAGED SINCE SVN INSTALLS WILL BE DIFFERENT
507  */
508 function set_base_version() {
509         global $dryrun;
510
511         outn("Checking framework.. ");
512         if (!$dryrun) {
513                 out(set_module_version('framework'));
514         } else {
515                 out("Dry Run Not Updated");
516         }
517
518         outn("Checking core.. ");
519         if (!$dryrun) {
520                 out(set_module_version('core'));
521         } else {
522                 out("Dry Run Not Updated");
523         }
524
525 }
526
527 /** Set the module version number to the packaged version and enable
528  *  module must require not install.php or install.sql script
529  *  this is primarily to package core and framework with freepbx tarballs
530  *
531  */
532 function set_module_version($module) {
533         global $db;
534
535         $module_dir = dirname(__FILE__)."/amp_conf/htdocs/admin/modules/";
536         $file_path = $module_dir.$module."/module.xml";
537         if (file_exists($file_path)) {
538                 // TODO: this is bad, there are other version tags (depends on) but this
539                 //       is equivalnet to what publish.pl does, so it expects this to be
540                 //       at the top.
541                 //
542                 $module_xml = file_get_contents($file_path);
543                 if (preg_match('/<version>(.+)<\/version>/', $module_xml, $matches)) {
544                         $version = $matches[1];
545                 } else {
546                         fatal("ERROR: $file_path found but no verison information");
547                 }
548         } else {
549                 return  "not packaged, no updating needed";
550         }
551
552         // If we didn't return above, then we found the package as part of the install
553         // tarball and want to update the version info since this might be overwriting
554         // and existing install that has a newever version.
555         //
556         $sql = "SELECT version FROM modules WHERE modulename = '$module'";
557         $result = $db->getCol($sql);
558         if(DB::IsError($result)) {     
559                 die($result->getMessage());
560         }
561         $sql = "";
562         if (count($result) == 0) {
563                 $sql = "INSERT INTO modules (modulename, version, enabled) VALUES ('$module', '$version', 1)";
564         } else if ($result[0] != $version) {
565                 $sql = "UPDATE modules SET version = '$version', enabled = 1 WHERE modulename = '$module'";
566         }
567         if ($sql) {
568                 debug($sql);
569                 $result = $db->query($sql);
570                 if(DB::IsError($result)) {     
571                         die($result->getMessage());
572                 }
573                 return "updated to $version";
574         } else {
575                 return "already at $version";
576         }
577 }
578
579 /** Invoke upgrades
580  * @param $versions array       The version upgrade scripts to run
581  */
582 function run_upgrade($versions) {
583         global $dryrun;
584        
585         foreach ($versions as $version) {
586                 out("Upgrading to ".$version."..");
587                 install_upgrade($version);
588                 if (!$dryrun) {
589                         setversion($version);
590                 }
591                 out("Upgrading to ".$version."..OK");
592         }
593 }
594
595 /** Write AMP-generated configuration files
596  */
597 function generate_configs() {
598         global $amp_conf;
599         global $dryrun;
600         global $debug;
601        
602         out("Generating Configurations.conf, (if Asterisk is not running, you will get an error");
603         out("In case of error, start Asterisk and hit the red bar in the GUI to generate the Configuraions.conf files");
604         if (!$dryrun)
605                 // added --run-install to make it work like it has been working since retrieve_conf changed to not run module install scripts by default
606
607                 //
608                 // TODO: Should check if Asterisk is running and/or try to start it.
609                 //
610                 passthru("su - asterisk -c \"".trim($amp_conf["AMPBIN"])."/retrieve_conf --run-install ".($debug ? ' --debug' : '').'"');
611 }
612
613
614 /** Set reload flag for AMP admin
615  */
616 function install_needreload() {
617         global $db;
618         $sql = "UPDATE admin SET value = 'true' WHERE variable = 'need_reload'";
619         $result = $db->query($sql);
620         if(DB::IsError($result)) {     
621                 die($result->getMessage());
622         }
623 }
624
625
626 /** Collect AMP settings
627  */
628 function collect_settings($filename, $dbhost = '', $dbuser = '', $dbpass = '', $dbname = 'asterisk') {
629         out("Creating new $filename");
630        
631         outn("Enter your USERNAME to connect to the '$dbname' database:\n [".($dbuser ? $dbuser : $asterisk_user) . "] ");
632         $key = trim(fgets(STDIN,1024));
633         if (preg_match('/^$/',$key))
634                 $amp_conf["AMPDBUSER"] = ($dbuser ? $dbuser : "asteriskuser");
635         else
636                 $amp_conf["AMPDBUSER"] = $key;
637        
638         outn("Enter your PASSWORD to connect to the '$dbname' database:\n [".($dbpass ? $dbpass : $asterisk_pass)."] ");
639         $key = trim(fgets(STDIN,1024));
640         if (preg_match('/^$/',$key))
641                 $amp_conf["AMPDBPASS"] = ($dbpass ? $dbpass : $asterisk_pas);
642         else
643                 $amp_conf["AMPDBPASS"] = $key;
644        
645         outn("Enter the hostname of the '$dbname' database:\n [".($dbhost ? $dbhost : "localhost")."] ");
646         $key = trim(fgets(STDIN,1024));
647         if (preg_match('/^$/',$key))
648                 $amp_conf["AMPDBHOST"] = ($dbhost ? $dbhost : "localhost");
649         else
650                 $amp_conf["AMPDBHOST"] = $key;
651        
652         outn("Enter a USERNAME to connect to the Asterisk Manager interface:\n [admin] ");
653         $key = trim(fgets(STDIN,1024));
654         if (preg_match('/^$/',$key)) $amp_conf["AMPMGRUSER"] = "admin";
655         else $amp_conf["AMPMGRUSER"] = $key;
656        
657         outn("Enter a PASSWORD to connect to the Asterisk Manager interface:\n [amp111] ");
658         $key = trim(fgets(STDIN,1024));
659         if (preg_match('/^$/',$key)) $amp_conf["AMPMGRPASS"] = "amp111";
660         else $amp_conf["AMPMGRPASS"] = $key;
661        
662         do {
663                 out("Enter the path to use for your AMP web root:\n [$webroot] ");
664                 $key = trim(fgets(STDIN,1024));
665                 if (preg_match('/^$/',$key))
666                         $amp_conf["AMPWEBROOT"] = "$webroot";
667                 else
668                         $amp_conf["AMPWEBROOT"] = rtrim($key,'/');
669
670                 if (is_dir($amp_conf["AMPWEBROOT"])) {
671                         break;
672                 } else if (amp_mkdir($amp_conf["AMPWEBROOT"],"0755",true)){
673                         out("Created ".$amp_conf["AMPWEBROOT"]);
674                         break;
675                 } else {
676                         fatal("Cannot create ".$amp_conf["AMPWEBROOT"]."!");
677                 }
678         } while(1);
679        
680         // Really no need to ask, is there.
681         if (empty($fopwebroot))
682                 $amp_conf["FOPWEBROOT"] = $amp_conf["AMPWEBROOT"];
683         else
684                 $amp_conf["FOPWEBROOT"] = $fopwebroot;
685        
686         outn("Enter the IP ADDRESS or hostname used to access the AMP web-admin:\n [xx.xx.xx.xx] ");
687         $key = trim(fgets(STDIN,1024));
688         if (preg_match('/^$/',$key)) $amp_conf["AMPWEBADDRESS"] = "xx.xx.xx.xx";
689         else $amp_conf["AMPWEBADDRESS"] = $key;
690        
691         outn("Enter a PASSWORD to perform call transfers with the Flash Operator Panel:\n [passw0rd] ");
692         $key = trim(fgets(STDIN,1024));
693         if (preg_match('/^$/',$key)) $amp_conf["FOPPASSWORD"] = "passw0rd";
694         else $amp_conf["FOPPASSWORD"] = $key;
695        
696         outn("Use simple Extensions [extensions] admin or separate Devices and Users [deviceanduser]?\n [extensions] ");
697         $key = trim(fgets(STDIN,1024));
698         if (preg_match('/^$/',$key)) $amp_conf["AMPEXTENSIONS"] = "extensions";
699         else $amp_conf["AMPEXTENSIONS"] = $key;
700        
701         do {
702                 out("Enter directory in which to store AMP executable scripts:\n [$ampbin_dir] ");
703                 $key = trim(fgets(STDIN,1024));
704                 if (preg_match('/^$/',$key))
705                         $amp_conf["AMPBIN"] = $ampbin_di;
706                 else
707                         $amp_conf["AMPBIN"] = rtrim($key,'/');
708
709                 if (is_dir($amp_conf["AMPBIN"])) {
710                         break;
711                 } else if (amp_mkdir($amp_conf["AMPBIN"],"0755",true)){
712                         out("Created ".$amp_conf["AMPBIN"]);
713                         break;
714                 } else {
715                         fatal("Cannot create ".$amp_conf["AMPBIN"]."!");
716                 }
717         } while(1);
718        
719         do {
720                 out("Enter directory in which to store super-user scripts:\n [$ampsbin_dir] ");
721                 $key = trim(fgets(STDIN,1024));
722                 if (preg_match('/^$/',$key))
723                         $amp_conf["AMPSBIN"] = "$ampsbin_dir";
724                 else
725                         $amp_conf["AMPSBIN"] = rtrim($key,'/');
726
727                 if (is_dir($amp_conf["AMPSBIN"])) {
728                         break;
729                 } else if (amp_mkdir($amp_conf["AMPSBIN"],"0755",true)){
730                         out("Created ".$amp_conf["AMPSBIN"]);
731                         break;
732                 } else {
733                         fatal("Cannot create ".$amp_conf["AMPSBIN"]."!");
734                 }
735         } while(1);
736        
737         // write amportal.conf
738         write_amportal_conf($filename, $amp_conf);
739         outn(AMP_CONF." written");
740 }
741
742 /********************************************************************************************************************/
743
744 // **** Make sure we have STDIN etc
745
746 // from  ben-php dot net at efros dot com   at  php.net/install.unix.commandline
747 if (version_compare(phpversion(),'4.3.0','<') || !defined("STDIN")) {
748         define('STDIN',fopen("php://stdin","r"));
749         define('STDOUT',fopen("php://stdout","r"));
750         define('STDERR',fopen("php://stderr","r"));
751         register_shutdown_function( create_function( '' , 'fclose(STDIN); fclose(STDOUT); fclose(STDERR); return true;' ) );
752 }
753    
754 // **** Make sure we have PEAR's DB.php, and include it
755
756 outn("Checking for PEAR DB..");
757 if (! @ include('DB.php')) {
758         out("FAILED");
759         fatal("PEAR must be installed (requires DB.php). Include path: ".ini_get("include_path"));
760 }
761 out("OK");
762
763 // **** Make sure we have PEAR's GetOpts.php, and include it
764
765 outn("Checking for PEAR Console::Getopt..");
766 if (! @ include("Console/Getopt.php")) {
767         out("FAILED");
768         fatal("PEAR must be installed (requires Console/Getopt.php). Include path: ".ini_get("include_path"));
769 }
770 out("OK");
771
772 // **** Parse out command-line options
773 $shortopts = "h?u:p:";
774 $longopts = array("help","debug","dry-run","username=","password=","force-version=","dbhost=","no-files","dbname=","my-svn-is-correct","engine=","install-moh","make-links-devel");
775
776 $args = Console_Getopt::getopt(Console_Getopt::readPHPArgv(), $shortopts, $longopts);
777 if (is_object($args)) {
778         // assume it's PEAR_ERROR
779         out($args->message);
780         exit(255);
781 }
782
783 $debug = false;
784 $dryrun = false;
785 $install_files = true;
786 $override_astvers = false;
787
788 $install_moh = false;
789 $make_links = false;
790
791 //initialize variables to avoid php notices
792 $dbhost = null;
793 $dbname = null;
794 $new_username = null;
795 $new_password = null;
796
797 foreach ($args[0] as $arg) {
798         switch ($arg[0]) {
799                 case "--help": case "h": case "?":
800                         showHelp();
801                         exit(10);
802                 break;
803                 case "--dry-run":
804                         out("Dry-run only, nothing will be changed");
805                         $dryrun = true;
806                 break;
807                 case "--debug":
808                         $debug = true;
809                         debug("Debug mode enabled");
810                 break;
811                 case "--username": case "u":
812                         out("Using username: ".$arg[1]);
813                         $new_username = $arg[1];
814                 break;
815                 case "--password": case "p":
816                         out("Using password: ".str_repeat("*",strlen($arg[1])));
817                         $new_password = $arg[1];
818                 break;
819                 case "--force-version":
820                         $version = $arg[1];
821                         out("Forcing upgrade from version ".$version);
822                 break;
823                 case "--dbhost":
824                         $dbhost = $arg[1];
825                         out("Using remote database server at ".$dbhost);
826                 break;
827                 case "--dbname":
828                         $dbname = $arg[1];
829                         out("Using database ".$dbname);
830                 break;
831                 case "--no-files":
832                         $install_files = false;
833                         out("Running upgrade only, without installing files.");
834                 break;
835                 case "--my-svn-is-correct":
836                         $override_astvers = true;
837                 break;
838