Advertisement
Guest User

Untitled

a guest
Jan 28th, 2011
373
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 91.40 KB | None | 0 0
  1. <?php
  2. // +----------------------------------------------------------------+
  3. // | server-install.php                                          |
  4. // |                                                                |
  5. // | Function: Install Atmail                                       |
  6. // +----------------------------------------------------------------+
  7. // | Source-code (C) ATMAIL. All rights reserved                    |
  8. // | See http://calacode.com/license.ehtml for license agreement    |
  9. // +----------------------------------------------------------------+
  10. // | Date: July 2009                                                |
  11. // +----------------------------------------------------------------+
  12. //
  13. // This script can be run in an unattended manner, but is not recommended
  14. // php server-install.php --install --dbhost=127.0.0.1 --dbuser=root --dbtable=atmail --dbpass=test --adminpass=test --domain=yourdomain.com.au
  15. //
  16. ini_set('memory_limit', "64M");
  17. error_reporting(E_ALL & ~E_NOTICE);
  18.  
  19. require_once('webmail/library/utility.php');
  20. define('APP_ROOT', dirname(__FILE__) . DIRECTORY_SEPARATOR . 'webmail' . DIRECTORY_SEPARATOR);
  21.  
  22. /*
  23.  * Automated installation configuration vars
  24.  */
  25.  
  26. $args = array();
  27. $argsError = 0;
  28.  
  29. // Build a list of arguments
  30. foreach($_SERVER['argv'] as $arg) {
  31.     $arr = explode("=", $arg);
  32.     $arr[0] = str_replace('--', '', $arr[0]);
  33.    
  34.     if(empty($arr[1]))
  35.         $arr[1] = "";      
  36.    
  37.     $args[$arr[0]] = $arr[1];
  38.    
  39. }
  40.  
  41. foreach($args as $key => $value) {
  42. //  echo "$key => $value\n";
  43. }
  44.  
  45. if(isset($args['install']) && (empty($args['dbhost']) || empty($args['dbuser'] ) || empty($args['dbtable']))) {
  46.     $argsError = "Please specify the --dbhost , --dbuser and --dbtable values";
  47. }
  48.  
  49. if(isset($args['install']) && (empty($args['adminpass']) || empty($args['domain'] ))) {
  50.     $argsError = "Please specify the --adminpass and --domain values";
  51. }
  52.  
  53. if(isset($args['help']) || ($argsError)) {
  54.  
  55.     if($argsError)
  56.     echo "ERROR: $argsError\n\n";
  57.  
  58.     echo "Atmail server-install.php\n";
  59.     echo "Usage: php server-install.php [options]\n";
  60.     echo "Note: If no arguments are specified the installation will be interactive\n";
  61.     echo "\t--interactive\tInstall Atmail in interactive mode\n";
  62.     echo "\t--install\tSkip prompts during installation\n";
  63.     echo "\t--dbhost\tMySQL hostname (required)\n";
  64.     echo "\t--dbuser\tMySQL username (required)\n";
  65.     echo "\t--dbtable\tMySQL database table (required)\n";
  66.     echo "\t--dbpass\tMySQL password (optional)\n";
  67.     //echo "\t--create-db\tCreate the specified database table automatically\n";
  68.     echo "\t--create-tables\tCreate the database tables\n";
  69.  
  70.     echo "\t--httpdconf\tPathname to httpdconf\n";
  71.     echo "\t--domain\tDefault domain ( required )\n";
  72.  
  73.     echo "\t--adminemail\tAdmin email address\n";
  74.     echo "\t--adminpass\tAdmin password ( required )\n";
  75.    
  76.     echo "\t--skip-dovecot\tCreate the specified database table automatically\n";
  77.     echo "\t--skip-calendarserver\tSkip Calendar Server compile\n";
  78.     echo "\t--skip-exim\tSkip Exim compile\n";
  79.     echo "\t--skip-spamassassin\tSkip Spamassassin compile\n";
  80.     echo "\t--skip-clamav\tSkip ClamAV compie\n";
  81.     echo "\t--skip-diagnostics\tSkip server diagnostic report\n";
  82.  
  83.     echo "\n";
  84.     echo "Example: php server-install.php --install --dbhost=localhost --dbuser=root --dbpass=mypass --dbtable=atmail6 --create-db --create-tables\n";
  85.    
  86.     echo "\n";
  87.    
  88.     exit;
  89. }
  90.  
  91. // DEFAULT
  92. $HTTPDCONF = '';
  93.  
  94. $exim = array();
  95. $exim['smtp_port'] = 25;
  96. $dovecot = array();
  97.  
  98. $mysqlrestart = 0;
  99.  
  100. $plugins = array();
  101.  
  102. $defaults = array();
  103. $defaults['ThreadLimit'] = 6;
  104.  
  105. $pref['sql_table'] = '';
  106. $pref['install_dir'] = '/usr/local/atmail/';
  107. $pref['user_dir'] = '/usr/local/atmail/';
  108. $pref['smtphost'] = '127.0.0.1';
  109. $pref['admin_email'] = '';
  110. $pref['serverDir'] = '/usr/local/atmail/';
  111.  
  112. $debian = 0;
  113. $suse = 0;
  114.  
  115. $rpmInstall = 0;
  116.  
  117. if(isset($_SERVER['argv'][1]))
  118. $rpmInstall = $_SERVER['argv'][1];
  119.  
  120. if($rpmInstall != 'server' && $rpmInstall != 'client')
  121. $rpmInstall = 0;
  122.  
  123.  
  124. // Do not allow access via web
  125. if(isset($_SERVER['GATEWAY_INTERFACE']))
  126. {
  127.     header("Content-Type: text/html");
  128.  
  129.     print <<<EOF
  130. <h1>Installation Script Error</h1>
  131. <p>The server-install.php script can only be run via the command-line to configure Atmail. Please read
  132. <a href='http://support.atmail.com/'>http://support.atmail.com/</a> for information on
  133. installing.
  134. </p>
  135. EOF;
  136. exit;
  137. }
  138.  
  139.  
  140. // If we don't have the STDOUT, STDIN, STDERR constants defined
  141. // as we should in CLI environment then define them
  142. if(!defined('STDOUT'))
  143. {
  144.     // Define stream constants
  145.     define('STDIN', fopen('php://stdin', 'r'));
  146.     define('STDOUT', fopen('php://stdout', 'w'));
  147.     define('STDERR', fopen('php://stderr', 'w'));
  148.  
  149.     // Close the streams on script termination
  150.     register_shutdown_function(
  151.         create_function('',
  152.             'fclose(STDIN); fclose(STDOUT); fclose(STDERR); return true;')
  153.         );
  154. }
  155.  
  156.  
  157. // Check safe mode is off
  158. if(ini_get('safe_mode') == 1)
  159. {
  160.     exit("\nserver-install.php must be run with safe_mode Off. Please edit your php.ini and set safe_mode = Off before re-running server-install.php\n");
  161. }
  162.  
  163. // Make sure we are running as root
  164. $ps = shell_exec("ps aux | grep 'php .*server-install.php'");
  165.  
  166. if(preg_match("/^(.+?)\s+.+?php .*?server-install\.php/m", $ps, $m))
  167. {
  168.     if(trim($m[1]) != 'root')
  169.         exit("\nThe server-install.php must be run as root. Please su to root, and consult the installation details for further information.\n\n");
  170. }
  171. else
  172.     fwrite(STDOUT, "\nCould not detect what user server-install.php is running as. If you are not running the installation as root please do so.\n");
  173.  
  174. // Make sure we are running required minimum PHP version
  175. if(version_compare(PHP_VERSION, '5.1.0', '<'))
  176.     exit('Your PHP version ' . PHP_VERSION . " is too old, please upgrade to PHP 5.1.0 or greater to use Atmail\n\n");
  177.    
  178. require_once(APP_ROOT . 'library/Atmail/General.php');
  179. $operatingSystemInfo = getOperatingSystemInfo();
  180. if( !$operatingSystemInfo['supported'] )
  181. {
  182.    
  183.     exit("Operating System detected as: " . $operatingSystemInfo['operatingSystem'] . ".\nThis operating system is not supported.\nPlease upgrade your operating system if it is one of the supported distributions or install Atmail on a supported operating system.\n\n");
  184.    
  185. }
  186.  
  187.  
  188. // PHP ini settings
  189. ini_set('track_errors', true);
  190. ini_set('html_errors', false);
  191. ini_set('magic_quotes_runtime', false);
  192.  
  193. define('WWW_USER', 'atmail');
  194.  
  195. putenv('LANG=C');
  196.  
  197. $phpVersion = PHP_VERSION;
  198. //$phpOS = PHP_OS;
  199. $phpOS = $operatingSystemInfo['operatingSystem'];
  200.  
  201. //
  202. // START INSTALLATION
  203. //
  204.  
  205. // Make sure client files are installed to /usr/local/atmail/webmail
  206. if(!is_dir('/usr/local/atmail'))    {
  207.     echo "Please install/extract Atmail to /usr/local/atmail/\nThen run the installer again";
  208.     exit;
  209. }
  210.  
  211. if(!empty($rpmInstall))
  212. system("touch /usr/local/atmail/webmail/.rpminstall");
  213.  
  214. $clientDir = '/usr/local/atmail/webmail';
  215.  
  216. set_include_path("$clientDir/" . PATH_SEPARATOR . "$clientDir/library/" . PATH_SEPARATOR . get_include_path());
  217.  
  218. // Create the the new Config.php
  219. if(!file_exists("/usr/local/atmail/webmail/config/dbconfig.ini"))
  220. copy('/usr/local/atmail/webmail/config/dbconfig.ini.default',
  221.      '/usr/local/atmail/webmail/config/dbconfig.ini');
  222. system("chmod 0660 /usr/local/atmail/webmail/config/dbconfig.ini");
  223.  
  224. $pref['version'] = trim(file_get_contents("webmail/.VERSION"));
  225.  
  226. // Display the welcome message
  227. $msg = <<<EOF
  228. \033[1;32mWelcome to Atmail {$pref['version']} Installation\033[0;39m
  229. ----------------------------------
  230.  
  231. PHP Version: $phpVersion
  232. Operating System: $phpOS
  233.  
  234. This script will setup Atmail for your system
  235.  
  236. When requesting your input during the installation the default values are
  237. presented within square brackets -- to choose the default value, hit "Enter"
  238.  
  239. EOF;
  240.  
  241. if(!isset($args['install']))
  242.     fwrite(STDOUT, $msg);
  243.  
  244. if(!isset($args['install']))
  245.     prompt('[Press Enter to Continue]');
  246.  
  247. // Check the iptables firewall
  248. if(file_exists("/sbin/iptables")) {
  249.    
  250.     $firewall = `/sbin/iptables -nvL | grep dpt`;
  251.     $portError = array();
  252.    
  253.     if(!empty($firewall))   {
  254.  
  255.         $ports = array('25' => 'SMTP', '110' => "POP3", '143' => "IMAP", '993' => "IMAP SSL", '995' => "POP3 SSL", '8008' => "Calendar Server", '11211' => "Memcache");
  256.    
  257.         foreach( array_keys($ports) as $port) {
  258.        
  259.             if(!preg_match("/dpt:$port/", $firewall))   {
  260.                 $portError[] = " * Port $port ({$ports[$port]}) not detected as allowed\n";
  261.             }
  262.     }
  263.  
  264.     if(isset($portError[0]))    {
  265. echo <<<EOF
  266.  
  267. \033[1;32mFirewall Permissions\033[0;39m
  268. --------------------
  269.  
  270. The installer has detected the iptables firewall is active on the server.
  271.  
  272. The following ports have not been detected as open, please alter the iptables rules to allow
  273. the ports below, then continue with the Atmail installer.
  274.  
  275.  
  276. EOF;
  277.  
  278. echo implode($portError);
  279.        
  280.     if(!isset($args['install']))
  281.         prompt('[Press Enter to Continue]');
  282.        
  283.     }
  284.    
  285.     }      
  286. }
  287.  
  288. $mode = 1;
  289. $defaultCharset = 1;
  290. $mbstring = 0;
  291. $openssl = 0;
  292.  
  293. // Check suse
  294. if(file_exists('/etc/SuSE-release') || file_exists('/etc/SuSE-version'))
  295. {
  296.     $suse = 1;
  297. }
  298.  
  299. // Check Debian
  300. if(file_exists('/etc/debian_version') || file_exists('/etc/debian_release'))
  301. {
  302.     $debian = 1;
  303. }
  304.  
  305. // redhat/centos
  306. if(file_exists("/etc/redhat-release") && file_exists("/usr/bin/yum") || file_exists("/etc/fedora-release") && file_exists("/usr/bin/yum"))
  307. {
  308.     //nothing to set here
  309. }
  310.  
  311. $mysqlrestart = 0;
  312.  
  313.  
  314. require_once('webmail/library/Atmail/DepCheck.php');
  315.  
  316. // call the dep checker
  317. check_deps($_SERVER['argv']);
  318.  
  319. if(file_exists('./webmail/library/Atmail/.mysqlrestart'))
  320. {
  321.     unlink('./webmail/library/Atmail/.mysqlrestart');
  322.     $mysqlrestart = 1;
  323. }
  324.  
  325. // depcheck has already complained to the user, lets just exit
  326. if( $mysqlrestart )
  327. {
  328.  
  329.     exit(1);
  330.  
  331. }
  332.  
  333. // Check for required/optional PHP extensions
  334. if(!isset($args['install']))
  335.     fwrite(STDOUT, "\n\033[1;32mInstall Prerequisites \033[0;39m\n---------------------\n");
  336.  
  337. fwrite(STDOUT, "
  338. The installer will check your system has the required PHP runtime settings.
  339. You can install the optional PHP extensions via your system package manager or
  340. via the PHP pecl system. The installer will also scan your php.ini
  341. configuration file and make the required adjustments for Atmail.\n\n");
  342.  
  343. fwrite(STDOUT, "Required Extensions:\n\n");
  344.  
  345. $failedExt = array();
  346.  
  347. $text = '';
  348.  
  349. // Required Extensions
  350.  
  351. // Check we have MySQL support via PHP
  352. $text .= " * MySQL Library for PHP: ";
  353. if(defined('MYSQL_NUM'))
  354.     $text .= "OK\n";
  355. else {
  356.     $text .= "FAILED\n";
  357.     $failedExt[] = 'MySQL';
  358. }
  359.  
  360. // Check we have MySQL support via PHP
  361. $text .= " * PDO MySQL Library for PHP: ";
  362. if(extension_loaded('pdo_mysql'))
  363.     $text .= "OK\n";
  364. else {
  365.     $text .= "FAILED\n";
  366.     $failedExt[] = 'PDO';
  367. }
  368.  
  369. // Check for PCRE Library
  370. $text .= " * PCRE (Perl Compatible Regular Expressions) Library: ";
  371. if(extension_loaded('pcre'))
  372.     $text .= "OK\n";
  373. else {
  374.     $text .= "FAILED\n";
  375.     $failedExt[] = 'PCRE';
  376. }
  377.  
  378. // Check for Session support
  379. $text .= " * PHP Session support: ";
  380. if(extension_loaded('session'))
  381.     $text .= "OK\n";
  382. else {
  383.     $text .= "FAILED\n";
  384.     $failedExt[] = 'Session';
  385. }
  386.  
  387. // Check for Session support
  388. $text .= " * PHP mbstring support: ";
  389. if(extension_loaded('mbstring'))
  390.     $text .= "OK\n";
  391. else {
  392.     $text .= "FAILED\n";
  393.     $failedExt[] = 'mbstring';
  394. }
  395.  
  396. // Check for ctype support
  397. $text .= " * PHP ctype support: ";
  398. if(extension_loaded('ctype'))
  399.     $text .= "OK\n";
  400. else {
  401.     $text .= "FAILED\n";
  402.     $failedExt[] = 'ctype';
  403. }
  404.  
  405. // Check for DOM
  406. $text .= " * DOM Extension for PHP: ";
  407. if( extension_loaded('dom') )
  408. {
  409.  
  410.     $text .= "OK\n";
  411.  
  412. }
  413. else
  414. {
  415.  
  416.     $text .= "FAILED\n";
  417.     $failedExt[] = 'dom';
  418.  
  419. }
  420.  
  421. // Optional Extensions
  422. $text .= "\nOptional PHP Extensions:\n\n";
  423.  
  424. // Check for OpenSSL
  425. $text .= " * OpenSSL Extension for PHP: ";
  426. if(extension_loaded('openssl') || $openssl) {
  427.     $text .= "OK\n";
  428.     $pref['mail_type_ssl'] = 'allow';
  429. }
  430. else {
  431.     $text .= "MISSING - Optionally install the PHP OpenSSL extension to allow secure IMAPs POP3s connections via Webmail\n";
  432.     $pref['mail_type_ssl'] = 'deny';
  433. }
  434.  
  435. // Check for ICONV
  436. $text .= " * ICONV Extension for PHP: ";
  437. if(extension_loaded('iconv'))   {
  438.     $text .= "OK\n";
  439.     $pref['iconv'] = '1';
  440. } else {
  441.     $text .= "MISSING - Optionally install the Iconv library to perform charset conversions. Install the PHP ICONV extension to enable this feature!\n";
  442.     $pref['iconv'] = '0';
  443. }
  444.  
  445. // Check for GD
  446. $text .= " * GD Extension for PHP: ";
  447. if(extension_loaded('gd'))  {
  448.     $text .= "OK\n";
  449. } else {
  450.     $text .= "MISSING - Optionally install the GD library to support image resizing of user photos in the Addressbook\n";
  451. }
  452.  
  453. // Check for PHP-IMAP
  454. $text .= " * IMAP Extension for PHP: ";
  455. if( extension_loaded('imap') )
  456.     $text .= "OK\n";
  457. else
  458.     $text .= "MISSING - Optionally install the php-imap library to support Microsoft Exchange ActiveSync services to Push email, contacts and calendars to mobile devices.\n";
  459.  
  460.  
  461. // Check for required php.ini settings
  462. $text .= "\nphp.ini Settings:\n\n";
  463. $editIni = false;
  464. $reqIniChanges = '';
  465. $iniChangeRestart = 0;
  466.  
  467. // safe mode check
  468. $text .= " * Safe Mode Off: ";
  469. if(ini_get('safe_mode') == '1') {
  470.     if(editIni('safe_mode', 'Off'))
  471.         $text .= "FIXED - Safe Mode now off as required by Atmail\n";
  472.     else
  473.         $text .= "FAILED -  Atmail requires safe mode disabled\n";
  474. }
  475. else
  476.     $text .= "OK\n";
  477.  
  478. // mysql default port check
  479. $text .= " * Default Port Set: ";
  480. if(ini_get('mysql.default_port') == '') {
  481.     if(editIni('mysql.default_port', '3306'))
  482.     {
  483.         $text .= "FIXED - Default port now set to 3306\n";
  484.         $iniChangeRestart = 1;
  485.     }
  486.     else
  487.     {
  488.         $text .= "FAILED -  This may stop PHP from connecting to your mysql server\n";
  489.         $reqIniChanges .= "mysql.default_port = 3306\n";
  490.     }
  491. }
  492. else
  493.     $text .= "OK\n";
  494.  
  495. // register globals check
  496. $text .= " * Register Globals Off: ";
  497. if(ini_get('register_globals') == '1') {
  498.     if(editIni('register_globals', 'Off'))
  499.         $text .= "FIXED - Register Globals now off for enhanced security\n";
  500.     else {
  501.         $text .= "FAILED - Leaving register_globals on is a security hazard\n";
  502.         $reqIniChanges .= "register_globals = Off\n";
  503.     }
  504. }
  505. else
  506.     $text .= "OK\n";
  507.  
  508. // file uploads check
  509. $text .= " * File Uploads Allowed: ";
  510. if(ini_get('file_uploads') != '1') {
  511.     if(editIni('file_uploads', 'On'))
  512.         $text .= "FIXED - File uploads now allowed. Required for email attachments\n";
  513.     else {
  514.         $text .= "FAILED - File Uploads must be enabled for Atmail to add email attachments\n";
  515.         $reqIniChanges .= "file_uploads = On\n";
  516.     }
  517. }
  518. else
  519.     $text .= "OK\n";
  520.  
  521. // magic_quotes_gpc check
  522. $text .= " * Magic Quotes GPC Off: ";
  523. if( get_magic_quotes_gpc() == '1')
  524. {
  525.  
  526.     if( editIni('magic_quotes_gpc', 'Off') )
  527.     {
  528.        
  529.         $text .= "FIXED - Magic Quotes GPC now disabled\n";
  530.  
  531.     }
  532.     else
  533.     {
  534.        
  535.         $text .= "FAILED - Magic Quotes GPC must be off\n";
  536.         $reqIniChanges .= "magic_quotes_gpc = Off\n";
  537.  
  538.     }
  539.  
  540. }
  541. else
  542. {
  543.    
  544.     $text .= "OK\n";           
  545.  
  546. }
  547.  
  548. // Display errors
  549. $text .= " * Display Errors: ";
  550. if(ini_get('display_errors') == '1') {
  551.     if(editIni('display_errors', 'Off'))
  552.         $text .= "FIXED - Display Errors now off for enhanced security\n";
  553.     else {
  554.         $text .= "FAILED - Disable display_errors in the php.ini for increased security\n";
  555.         $reqIniChanges .= "display_errors = Off\n";
  556.     }
  557. }
  558. else
  559.     $text .= "OK\n";
  560.  
  561. // check max upload file size
  562. $text .= " * Maximum upload File Size at least 16M: ";
  563. if( returnBytes(ini_get('upload_max_filesize')) < 16*1024*1024 )
  564. {
  565.  
  566.     if(editIni('upload_max_filesize', '16M'))
  567.     {
  568.        
  569.         $text .= "FIXED - Maximum uploadable file size now 16M\n";
  570.  
  571.     }
  572.     else
  573.     {
  574.    
  575.         $text .= "FAILED - To allow for larger attachments max_upload_filesize should be at least 16M\n";
  576.         $reqIniChanges .= "upload_max_filesize = 16M\n";
  577.    
  578.     }
  579.    
  580. }
  581. else
  582. {
  583.    
  584.     $text .= "OK\n";
  585.  
  586. }
  587.  
  588. // check max post size
  589. $text .= " * Maximum Size of POST data at least 16M: ";
  590. if( returnBytes(ini_get('post_max_size')) < 16*1024*1024 )
  591. {
  592.  
  593.     if(editIni('post_max_size', '16M'))
  594.     {
  595.    
  596.         $text .= "FIXED - Maximum Size of POST data now 16M\n";
  597.  
  598.     }
  599.     else
  600.     {
  601.        
  602.         $text .= "FAILED - To allow for larger POST data size post_max_size should be at least 16M\n";
  603.         $reqIniChanges .= "post_max_size = 16M\n";
  604.  
  605.     }
  606.  
  607. }
  608. else
  609. {
  610.    
  611.     $text .= "OK\n";
  612.  
  613. }
  614.  
  615. // check memory_limit value
  616. $text .= " * Maximum amount of memory usage at least 96M: ";
  617. if( returnBytes(ini_get('memory_limit')) < 96*1024*1024 )
  618. {
  619.  
  620.     if(editIni('memory_limit', '96M'))
  621.     {
  622.        
  623.         $text .= "FIXED - Maximum amount of memory now 96M\n";
  624.  
  625.     }
  626.     else
  627.     {
  628.        
  629.         $text .= "FAILED - To allow for larger amount of memory usage memory_limit should be at least 96M\n";
  630.         $reqIniChanges .= "memory_limit = 96M\n";
  631.  
  632.     }
  633. }
  634. else
  635. {
  636.    
  637.     $text .= "OK\n";
  638.  
  639. }
  640.  
  641. fwrite(STDOUT, $text);
  642.  
  643. // If we have required extensions missing then give message and exit
  644. if( count($failedExt) )
  645. {
  646.     fwrite(STDOUT, "Some required PHP extensions are not available. In order to use Atmail the
  647. PHP extensions listed below must be installed for PHP on your platform:\n\n");
  648.  
  649.     foreach ($failedExt as $ext)
  650.         fwrite(STDOUT, "    * $ext\n");
  651.  
  652.     fwrite(STDOUT, "\nAlso note any missing optional extensions you may wish to install. Once you have installed the required
  653. extensions you may continue with the installation.\n\n");
  654.  
  655.     exit(1);
  656. }
  657.  
  658. // Check for any required php.ini changes
  659. if(!empty($reqIniChanges))
  660. {
  661.     fwrite(STDOUT, "\nInstaller could not alter some php.ini settings. Atmail requires the following php.ini directives to be manually set:\n\n");
  662.     fwrite(STDOUT, $reqIniChanges . "\n");
  663.     fwrite(STDOUT, "Please make these changes and restart Apache before using Atmail.\n\n");
  664. }
  665.  
  666. // restart installer if php5-mysql default port missing
  667. if($iniChangeRestart == 1)
  668. {
  669.     fwrite(STDOUT, "\nMissing PHP init settings have been set, however you may need to re-run the installation script to initialize PHP correctly\n");
  670.     fwrite(STDOUT, "Please run:\n\nphp server-install.php\nIf your mysql tests fail to connect.\n\n");
  671. }
  672.  
  673.  
  674.  
  675. // So we can track that we installed the software
  676. if(!$fh = @fopen('/usr/local/atmail/webmail/.install', 'w'))
  677.     exit("Cannot write .install file in the /usr/local/atmail/ directory! Be sure to change the ownership of the Atmail directory to the user your webserver runs as.\n");
  678. fclose($fh);
  679.  
  680. // Next, scan for other optional binary dependencies ( apsell, ImageMagik, etc )
  681. // TODO: move findBinary to a common library used for web-installer
  682. $convert = findBinary(array('convert'));
  683.  
  684. if(is_executable($convert)) {
  685.         $res = `$convert --version`;
  686.  
  687.         if(preg_match("/ImageMagick/", $res)) {
  688.         $pref['convertPath'] = $convert;
  689.         $plugins['Atmail_FilePreview'] = 1;
  690.         }
  691. }
  692.  
  693. if(!isset($args['install']))
  694.     prompt('[Press Enter to Continue with installation]');
  695.  
  696. $pref['install_type'] = 'server';
  697. $pref['allow_Signup'] = 0;
  698.  
  699. // SQL setup
  700. if(!isset($args['install']))
  701.     print <<<EOF
  702.  
  703. \033[1;32mMySQL Database Setup \033[0;39m
  704. --------------------
  705.  
  706. The following few prompts will set up your MySQL Database for Atmail.
  707. You will need to supply an MySQL user that has permission to create databases.
  708.  
  709. EOF;
  710.  
  711. $default = (!empty($pref['sql_host'])) ? $pref['sql_host'] : '127.0.0.1';
  712.  
  713. if($args['dbhost'] == '')
  714.     $pref['sql_host'] = prompt('Enter your MySQL server\'s hostname or IP address', $default);
  715. else
  716.     $pref['sql_host'] = $args['dbhost'];
  717.  
  718. if(strtolower($pref['sql_host']) == 'localhost')
  719.     $pref['sql_host'] = '127.0.0.1';
  720.  
  721. if($args['dbuser'] == '')
  722.     $sqlAdmin = prompt('Enter username for database', 'root');
  723. else
  724.     $sqlAdmin = $args['dbuser'];
  725.  
  726. if(!isset($args['dbpass']))
  727.     $sqlAdminPass = prompt("Enter password for $sqlAdmin: ");
  728. else
  729.     $sqlAdminPass = $args['dbpass'];
  730.  
  731.  
  732. // Check we can connect to DB
  733. $tries = 1;
  734. while (false === $dbh = mysql_connect($pref['sql_host'], $sqlAdmin, $sqlAdminPass))
  735. {
  736.     fwrite(STDOUT, "\nERROR: Could not connect to MySQL server. Please check the server is running and accepting connections!\n");
  737.     if($tries > 5)
  738.         exit("\nSorry, you'll have to find your correct MySQL server details and retry later. Bye.\n\n");
  739.  
  740.     $a = strtolower(prompt('Enter MySQL details again? "No" or "n" will exit intallation.\n', 'Yes'));
  741.  
  742.     if($a == 'n' || $a == 'no')
  743.         exit("\nSorry, you'll have to find your correct MySQL server details and retry later. Bye.\n\n");
  744.  
  745.     $pref['sql_host'] = prompt('Enter MySQL server\'s hostname', $pref['sql_host']);
  746.     $sqlAdmin = prompt('Enter username for creating database', $sqlAdmin);
  747.     $sqlAdminPass = prompt("Enter password for $sqlAdmin: ", $sqlAdminPass);
  748.     $tries++;
  749. }
  750.  
  751. fwrite(STDOUT, "\nConnected to MySQL Server!\n");
  752.  
  753. fwrite(STDOUT, "\nSelect the database to use or enter the name of a new database to create:\n\n");
  754.  
  755. // Get sql tables
  756. $res = mysql_list_dbs();
  757. $count = 1;
  758. $dbs = array();
  759. while($obj = mysql_fetch_object($res))
  760. {
  761.     fwrite(STDOUT, "[$count] $obj->Database\n");
  762.     $dbs[$count] = $obj->Database;
  763.     $count++;
  764. }
  765.  
  766. if(in_array($pref['sql_table'], $dbs))
  767. {
  768.     if(isset($args['install']))
  769.         $a = 'y';
  770.     else
  771.         $a = strtolower(prompt("I have detected a possible existing Atmail database '{$pref['sql_table']}'. Is this correct?", 'Y'));
  772.  
  773.  
  774.     if($a == 'y' || $a == 'yes')
  775.     {
  776.         $useExistingDB = true;
  777.  
  778.         mysqlPing();
  779.  
  780.         // check for tables
  781.         if(mysql_select_db($pref['sql_table']))
  782.         {
  783.             $res = mysql_query('show tables');
  784.             if(!mysql_num_rows($res))
  785.             {
  786.                 $createTables = true;
  787.                 $prompt = "No tables seem to exist on {$pref['sql_table']}. Shall I create them?";
  788.             }
  789.         }
  790.     }
  791. }
  792.  
  793. if( !isset($useExistingDB) )
  794. {
  795.     if( $args['dbtable'] != '' )
  796.     {
  797.         $db = $args['dbtable'];
  798.         $dbCreateStagePassed = true;
  799.         $createNewTables = true;
  800.         // Create the new DB
  801.         if(!createDb($db))
  802.         {
  803.             fwrite(STDOUT, "\nError: The database $db could not be created. A database by that name may already exist?\n");
  804.         }
  805.         else
  806.         {
  807.             $pref['sql_table'] = $db;
  808.             fwrite(STDOUT, "\nThe database $db was created for Atmail\n");
  809.             $dbCreateStagePassed = true;
  810.             $createNewTables = true;
  811.         }
  812.     }
  813.     else
  814.     {
  815.         $dbCreateStagePassed = false;
  816.         $createNewTables = false;
  817.         while( !$dbCreateStagePassed )
  818.         {
  819.             if( $count > 1 )
  820.             {
  821.                 $db = prompt('Enter the database number to use above, or specify a new name to create a database: ');
  822.             }
  823.             elseif( $count == 1 )
  824.             {
  825.                 $db = prompt('Enter the database number to use above, or specify a new name to create a database: ', '1');
  826.             }
  827.             else
  828.             {
  829.                 $db = prompt('Enter the name of a new database to create', 'atmail');
  830.             }
  831.    
  832.             if( is_numeric($db) && $db > 0 && $db <= $count )
  833.             {
  834.                 $pref['sql_table'] = $dbs[$db];
  835.                 $dbCreateStagePassed = true;
  836.                 $prompt = "You chose an existing database '{$pref['sql_table']}', does it need to be populated with new Atmail tables (Y/N)?";
  837.  
  838.                 $populateWithAtmailTables = prompt($prompt,'N');
  839.  
  840.                 if( strtolower($populateWithAtmailTables) == 'y' || strtolower($populateWithAtmailTables) == 'yes')
  841.                 {
  842.                     $createNewTables = true;
  843.                 }
  844.                 else
  845.                 {
  846.                     $createNewTables = false;
  847.                 }
  848.             }
  849.             else if( !empty($db) )
  850.             {
  851.                 // Create the new DB
  852.                 if(!createDb($db))
  853.                 {
  854.                     fwrite(STDOUT, "\nError: The database $db could not be created. A database by that name may already exist?\n");
  855.                 }
  856.                 else
  857.                 {
  858.                     $pref['sql_table'] = $db;
  859.                     fwrite(STDOUT, "\nThe database $db was created for Atmail\n");
  860.                     $dbCreateStagePassed = true;
  861.                     $createNewTables = true;
  862.                 }
  863.             }
  864.         }
  865.     }
  866. }
  867.  
  868. if( isset($createTables) || $createNewTables == true)
  869. {
  870.     fwrite(STDOUT, "\nCreating Atmail database tables on {$pref['sql_table']}...");
  871.  
  872.     mysqlPing();
  873.     mysql_select_db($pref['sql_table']);
  874.  
  875.     if(createAtmailTables())
  876.     fwrite(STDOUT, "\nAtmail tables successfully created.\n\n");
  877.     else
  878.     print(" ERROR!\n\nAn error occured while creating the Atmail tables. Please check the tables have not already been populated.\n\n");
  879.  
  880. }
  881. else
  882. {
  883.     fwrite(STDOUT, "\nTable creation skipped, tables must exist already.\n");
  884. }
  885.  
  886. // Set the globals
  887. $pref['sql_user'] = $sqlAdmin;
  888. $pref['sql_pass'] = $sqlAdminPass;
  889.  
  890. $dbconfig = <<<_EOF
  891. [production]
  892. database.adapter         = pdo_mysql
  893. database.params.host     = "{$pref['sql_host']}"
  894. database.params.username = "{$pref['sql_user']}"
  895. database.params.password = "{$pref['sql_pass']}"
  896. database.params.dbname   = "{$pref['sql_table']}"
  897. database.params.configtable = Config
  898. _EOF;
  899.  
  900. file_put_contents("webmail/config/dbconfig.ini", $dbconfig);
  901.  
  902. fwrite(STDOUT, "MySQL setup complete!\n");
  903.  
  904. // Double check to create the 'atmail' user account
  905. if(!userExists('atmail'))
  906. {
  907.     if(file_exists('/usr/sbin/useradd') && ($debian || $suse))
  908.         system("/usr/sbin/useradd --uid 3000 atmail > /dev/null 2>&1");
  909.     elseif(file_exists('/usr/sbin/adduser'))
  910.         system("/usr/sbin/adduser -u 3000 atmail > /dev/null 2>&1");
  911. }
  912.  
  913. if(!userExists('atmailimap'))
  914. {
  915.         if(file_exists('/usr/sbin/useradd') && ($debian || $suse))
  916.                 system("/usr/sbin/useradd atmailimap > /dev/null 2>&1");
  917.         elseif(file_exists('/usr/sbin/adduser'))
  918.                 system("/usr/sbin/adduser atmailimap > /dev/null 2>&1");
  919. }
  920.  
  921. if(!groupExists('atmailimap'))
  922. {
  923.         if(file_exists('/usr/sbin/groupadd'))
  924.                 system("/usr/sbin/groupadd -g 3001 atmailimap > /dev/null 2>&1");
  925. }
  926.  
  927.  
  928. if(!groupExists('atmail'))
  929. {
  930.     if(file_exists('/usr/sbin/groupadd'))
  931.         system("/usr/sbin/groupadd -g 3000 atmail > /dev/null 2>&1");
  932. }
  933.  
  934. $id = trim(exec('id -u atmail'));
  935.  
  936. if($id != 3000)
  937.     fwrite(STDOUT, "**** NOTE: The 'atmail' username must be created on your server with UID 3000. Current UID = $id\n\n");
  938.  
  939. // Apache configuration
  940. if(!isset($args['install']))
  941.     print <<<EOF
  942.  
  943. \033[1;32mWebServer Configuration\033[0;39m
  944. -----------------------
  945.  
  946. EOF;
  947.  
  948. $webserverBin = findWebserverBin();
  949.  
  950. while(true)
  951. {
  952.     if(!isset($args['install']))
  953.         $webserverBin = prompt("Specify the binary location of your Webserver: ", $webserverBin);
  954.     if(is_executable($webserverBin))
  955.         break;
  956.  
  957.     fwrite(STDOUT, "\nError: No executable found at $webserverBin\n");
  958. }
  959.  
  960. if($HTTPDCONF == '')
  961. {
  962.     // Find default httpd.conf
  963.     exec("$webserverBin -V", $output);
  964.  
  965.     foreach($output as $line)
  966.     {
  967.         if(preg_match('/SERVER_CONFIG_FILE="(.+?)"/', $line, $m))
  968.             $httpdConf = $m[1];
  969.  
  970.         if(preg_match('/HTTPD_ROOT="(.+?)"/', $line, $m))
  971.             $httpdRoot = $m[1];
  972.     }
  973.  
  974.     if(substr($httpdConf, 0, 1) != '/')
  975.         $httpdConf = "$httpdRoot/$httpdConf";
  976.  
  977.     if(!isset($args['install'])) {
  978.     $a = prompt("Is '$httpdConf' the correct location of your Apache config file?", 'Y');
  979.    
  980.     if(strtolower(substr($a, 0, 1)) != 'y')
  981.         $httpdConf = promptWithOptions('locate httpd.conf', "Select the correct location of your httpd.conf or enter the full path if not listed:\n\n", '1', '/\/httpd\.conf$/');
  982.     }
  983.  
  984. }
  985. else
  986.     $httpdConf = $HTTPDCONF;
  987.  
  988. $confDir = dirname($httpdConf) . '/conf.d/';
  989.  
  990. fwrite(STDOUT, "Reading $httpdConf: \n");
  991.  
  992. $confVars = webserverConf($httpdConf);
  993. extract($confVars);
  994.  
  995.  
  996. // If the httpd.conf includes links to other conf file, load them.
  997. if(isset($httpIncludes) && count($httpdIncludes))
  998. {
  999.     foreach ($httpdIncludes as $include)
  1000.     {
  1001.         fwrite(STDOUT, "Scanning Webserver include file: $include\n");
  1002.  
  1003.         //$incVars = webserver_conf_include($include));
  1004.         $incVars = webserverConf($include);
  1005.         extract($incVars);
  1006.     }
  1007. }
  1008.  
  1009. fwrite(STDOUT, "\nAtmail is scanning your WebServer Configuration. The webserver may require\nconfiguration to recognize Atmail.\n\n");
  1010.  
  1011. if($doc_root)
  1012. fwrite(STDOUT, "DocumentRoot: $doc_root\n\n");
  1013.  
  1014. $addedondate = "\n# ADDED BY Atmail " . date('Y-m-d H:i:s') . "\n";
  1015.  
  1016. if(!isset($mod_php))
  1017. {
  1018.  
  1019.     if(isset($execCGI) && $execCGI)
  1020.     {
  1021.         fwrite(STDOUT, "ExecCGI Permitted for {$pref['install_dir']}: OK\n");
  1022.     }
  1023.     else
  1024.     {
  1025.         print <<<EOF
  1026.  
  1027. \033[1;32mExecCGI Permitted for /usr/local/atmail/webmail: FAIL\033[0;39m
  1028.  
  1029. Solution:
  1030. The ExecCGI tag is required to allow PHP scripts to be executed in the
  1031. /usr/local/atmail/webmail directory.
  1032.  
  1033. -> Add the following to $httpdConf . You must do this manually (for advanced
  1034. httpd.conf configurations) or select to automatically edit the configuration
  1035. file below.
  1036.  
  1037. Append the following to the httpd.conf:
  1038.  
  1039. <Directory "/usr/local/atmail/webmail">
  1040.     Options ExecCGI FollowSymLinks
  1041.     AllowOverride All
  1042.     Order allow,deny
  1043.     Allow from all
  1044. </Directory>
  1045.  
  1046.  
  1047. EOF;
  1048.         if(isset($args['install']))
  1049.             $a = 'y';
  1050.         else
  1051.             $a = prompt("Edit httpd.conf automatically?", "Y" );
  1052.  
  1053.         if( strtolower($a) == 'y')
  1054.         {
  1055.             $restart = true;
  1056.  
  1057.             $conf = <<<EOF
  1058. <Directory "/usr/local/atmail/webmail">
  1059.     Options ExecCGI FollowSymLinks
  1060.     AllowOverride All
  1061.     Order allow,deny
  1062.     Allow from all
  1063. </Directory>
  1064.  
  1065. EOF;
  1066.  
  1067.             appendHttpdConf($httpdConf, array($addedondate, $conf));
  1068.         }
  1069.     }
  1070. }
  1071.  
  1072. if(isset($alias) && $alias)
  1073. {
  1074.     fwrite(STDOUT, "Alias URL setup for Atmail: OK\n");
  1075. }
  1076. else
  1077. {
  1078.     print <<<EOF
  1079.  
  1080. \033[1;32mAlias URL setup for Atmail: FAIL\033[0;39m
  1081.  
  1082. Solution:
  1083. The Alias tag is required to access Atmail via the URL /mail/ on your server.
  1084.  
  1085. -> Add the following to $httpdConf . You must do this manually (for advanced
  1086. httpd.conf configurations) or select to automatically edit the configuration
  1087. file below.
  1088.  
  1089. Append the following to the httpd.conf:
  1090.  
  1091. Alias /mail /usr/local/atmail/webmail
  1092.  
  1093.  
  1094. EOF;
  1095.  
  1096.     if(isset($args['install']))
  1097.         $a = 'y';
  1098.     else
  1099.         $a = prompt('Edit httpd.conf automatically?', 'Y');
  1100.  
  1101.     if( strtolower($a) == 'y')
  1102.     {
  1103.         $restart = true;
  1104.         appendHttpdConf($httpdConf, array($addedondate, "Alias /mail $clientDir\n"));
  1105.     }
  1106. }
  1107.  
  1108.  
  1109. if(isset($defaultCharset) && isset($currentCharset))
  1110. {
  1111.     fwrite(STDOUT, "Default Character Encoding: OK\n");
  1112. }
  1113. elseif(isset($currentCharset))
  1114. {
  1115.     print <<<EOF
  1116.  
  1117. \033[1;32mDefault Character Encoding: FAIL\033[0;39m
  1118.  
  1119. Solution:
  1120. The Apache configuration file requires the default encoding to be disabled.
  1121. This is required because the encoding is automatically defined in the HTML
  1122. pages.
  1123.  
  1124. -> Add the following to $httpdConf . You must do this manually (for advanced
  1125. httpd.conf configurations) or select to automatically edit the configuration
  1126. file below.
  1127.  
  1128. Replace the following:
  1129.  
  1130. AddDefaultCharset $currentCharset
  1131.  
  1132. To read:
  1133.  
  1134. AddDefaultCharset UTF-8
  1135.  
  1136. EOF;
  1137.  
  1138.     if(isset($args['install']))
  1139.         $a = 'y';
  1140.     else
  1141.         $a = prompt('Edit httpd.conf automatically?', 'Y');
  1142.  
  1143.     if(strtolower($a) == 'y')
  1144.     {
  1145.         $restart = true;
  1146.         editHttpdConf($httpdConf, "^AddDefaultCharset $currentCharset", "AddDefaultCharset UTF-8\n# Disable the auto-default charset for WebMail");
  1147.     }
  1148. }
  1149.  
  1150.  
  1151. if($wwwUser == 'atmail')
  1152.     fwrite(STDOUT, "Webserver permissions for atmail: OK\n");
  1153. else
  1154. {
  1155.     print <<<EOF
  1156.  
  1157. \033[1;32mWebserver permissions for Atmail: FAIL\033[0;39m
  1158.  
  1159. Solution:
  1160. The runtime Webserver user must be changed from $wwwUser
  1161. to the username 'atmail' . This is required for Atmail Server Mode.
  1162.  
  1163. -> Add the following to $httpdConf. You must do this manually (for advanced
  1164. httpd.conf configurations) or select to automatically edit the configuration
  1165. file below.
  1166.  
  1167. Replace the following:
  1168.  
  1169. User $wwwUser
  1170.  
  1171. To read:
  1172.  
  1173. User atmail
  1174.  
  1175. EOF;
  1176.  
  1177.     if(isset($args['install']))
  1178.         $a = 'y';
  1179.     else
  1180.         $a = prompt('Edit httpd.conf automatically?', 'Y');
  1181.  
  1182.     if(strtolower($a) == 'y')
  1183.     {
  1184.         $restart = true;
  1185.         $wwwUser = preg_quote($wwwUser);
  1186.     if($suse) {
  1187.         editHttpdConf("/etc/apache2/uid.conf", "^User wwwrun", "# The webserver must run as the atmail user for the server-mode\nUser atmail\n");
  1188.     } else {
  1189.         editHttpdConf($httpdConf, "^User $wwwUser", "# The webserver must run as the atmail user for the server-mode\nUser atmail\n");
  1190.     }
  1191.     }
  1192.  
  1193.     $wwwUser = 'atmail';
  1194. }
  1195.  
  1196. // Additional Apache configuration/tuning
  1197.  
  1198. if(isset($mod_gzip_on) && $mod_gzip_on)
  1199.     print "WebServer Gzip compression: OK\n";
  1200.  
  1201. elseif($mod_gzip)
  1202. {
  1203.     // GZIP support detected, but not installed
  1204.     if(!isset($args['install']))
  1205.         print <<<EOF
  1206.  
  1207. WebServer Gzip compression: \033[1;32mDetected\033[0;39m
  1208.  
  1209. Within Apache 2 the mod_deflate module can be used to automatically compress
  1210. the output of the Atmail interface to the user's browser.
  1211.  
  1212. Compression can increase the performance dramatically for users on a slower
  1213. link ( e.g dialup or congested network ) . The mod_deflate feature can
  1214. compress between 15-60%+ of HTML output via the Webserver.
  1215.  
  1216. This installation utility can automatically configure the Webserver to enable
  1217. GZIP compression.
  1218.  
  1219. EOF;
  1220.     if(isset($args['install']))
  1221.         $a = 'y';
  1222.     else
  1223.         $a = prompt('Edit httpd.conf automatically?', 'Y');
  1224.  
  1225.     if(strtolower($a) == 'y' && is_dir($confDir))
  1226.     {
  1227.         fwrite(STDOUT, "Copying GZIP configuration file to /etc/httpd/conf.d/gzip.conf\n\n");
  1228.         system("cp /usr/local/atmail/server_source/etc/gzip.conf $confDir/gzip.conf");
  1229.     }
  1230.     else
  1231.     {
  1232.         $gzipConf = $addedondate;
  1233.         $gzipConf .= file_get_contents("/usr/local/atmail/server_source/etc/gzip.conf");
  1234.  
  1235.         $fh = fopen($httpdConf, 'a');
  1236.         fwrite($fh, $gzipConf);
  1237.         fclose($fh);
  1238.     }
  1239.  
  1240.     $mod_gzip_on = true;
  1241.     $restart = true;
  1242.  
  1243. }
  1244. else
  1245. {
  1246.     if(!isset($args['install']))
  1247.         print <<<EOF
  1248.  
  1249. WebServer Gzip compression: \033[1;32mFAIL\033[0;39m
  1250.  
  1251. The optional Gzip compression is not available on your Apache configuration.
  1252.  
  1253. Within Apache 2.X the mod_deflate module can be used to automatically compress
  1254. the output of the Atmail interface to the user's browser for increased
  1255. performance.
  1256.  
  1257. *The mod_deflate module is not required;  this message can be safely ignored*
  1258.  
  1259. EOF;
  1260. }
  1261.  
  1262.  
  1263. // Mod-expires configuration
  1264. if(isset($mod_expires_on))
  1265.     fwrite(STDOUT, "WebServer mod_expires module: OK\n");
  1266.  
  1267. elseif(isset($mod_expires))
  1268. {
  1269.     // mod_expires support detected, but not installed
  1270.     $msg = <<<EOF
  1271.  
  1272. Apache mod_expires module: \033[1;32mDetected\033[0;39m
  1273.  
  1274. Within Apache 2 the mod_expires module can be used to force browsers to cache
  1275. the images/Javascript and CSS used by the Atmail interface. This can
  1276. dramatically increase performance for loading the GUI frontend.
  1277.  
  1278. This installation utility can automatically configure Apache to enable the
  1279. mod-expires feature for the Atmail application.
  1280. EOF;
  1281.  
  1282.     if(!isset($args['install']))
  1283.         fwrite(STDOUT, $msg);
  1284.  
  1285.     if(isset($args['install']))
  1286.         $a = 'y';
  1287.     else
  1288.         $a = prompt("Edit httpd.conf automatically?", "Y");
  1289.  
  1290.     if(strtolower($a) == 'y' && is_dir($confDir))
  1291.     {
  1292.         fwrite(STDOUT, "Copying GZIP configuration to /etc/httpd/conf.d/expires.conf\n\n");
  1293.  
  1294.         system("cp /usr/local/atmail/server_source/etc/expires.conf $confDir/expires.conf");
  1295.     }
  1296.     else
  1297.     {
  1298.         $conf = $addedondate . file_get_contents("/usr/local/atmail/server_source/etc/expires.conf");
  1299.         $fh = fopen($httpdConf, 'a');
  1300.         fwrite($fh, $conf);
  1301.         fclose($fh);
  1302.     }
  1303.  
  1304.     $mod_expires_on = true;
  1305.     $restart = true;
  1306. }
  1307. else
  1308. {
  1309.     if(!isset($args['install']))
  1310.         print <<<EOF
  1311.  
  1312. WebServer mod_expires module: \033[1;32mFAIL\033[0;39m
  1313.  
  1314. The mod_expires module for Apache could not be loaded.
  1315.  
  1316. This is an optional configuration module for Atmail which can force the
  1317. users web-browser to cache images/Javascript and CSS files of the UI interface,
  1318. improving performance.
  1319.  
  1320. *The mod_expires module is not required;  this message can be safely ignored*
  1321.  
  1322. EOF;
  1323.  
  1324. }
  1325.  
  1326. // ActiveSync Push configuration
  1327. if( extension_loaded('imap') )
  1328. {
  1329.  
  1330.     if( isset($activeSyncAlias) && $activeSyncAlias == true )
  1331.         fwrite(STDOUT, "Microsoft Exchange ActiveSync Alias: OK\n");
  1332.     else
  1333.     {
  1334.         // mod_expires support detected, but not installed
  1335.         $msg = <<<EOF
  1336.  
  1337. ActiveSync Push support: \033[1;32mDetected\033[0;39m
  1338.  
  1339. Solution:
  1340. An Alias tag is required to enable Microsoft Exchange ActiveSync Push services on your server.
  1341.  
  1342. -> Add the following to $httpdConf . You must do this manually (for advanced
  1343. httpd.conf configurations) or select to automatically edit the configuration
  1344. file below.
  1345.  
  1346. Append the following to the httpd.conf:
  1347.  
  1348. Alias /Microsoft-Server-ActiveSync {$clientDir}/push/index.php
  1349.  
  1350. EOF;
  1351.  
  1352.         if( isset($args['install']) )
  1353.             $a = 'y';
  1354.         else
  1355.         {
  1356.             fwrite(STDOUT, $msg);
  1357.             $a = prompt("Edit httpd.conf automatically?", "Y");
  1358.         }
  1359.         if( strtolower($a) == 'y' )
  1360.         {
  1361.            
  1362.             appendHttpdConf($httpdConf, array($addedondate, "Alias /Microsoft-Server-ActiveSync $clientDir/push/index.php\n"));
  1363.             $restart = true;
  1364.             $activeSyncAlias = true;
  1365.            
  1366.         }
  1367.  
  1368.     }
  1369. }
  1370. //now set default group push support on if enabled
  1371. if( $activeSyncAlias == true )
  1372. {
  1373.    
  1374.     mysql_query("UPDATE `Groups` set `PushSupport`='1' WHERE `GroupName` = 'default'");
  1375.     fwrite(STDOUT, "Push support enabled for default user group\n");
  1376.    
  1377. }
  1378.  
  1379. if(isset($restart) && $restart)
  1380. {
  1381.     print <<<EOF
  1382. The installer has edited your httpd.conf ($httpdConf).
  1383.  
  1384. For changes to take effect, you are required to restart  Apache.
  1385. The installer can attempt to restart Apache (if this fails, restart the
  1386. Apache service manually).
  1387.  
  1388. EOF;
  1389.  
  1390.     if( isset($args['install']) || strtolower( prompt("Restart HTTPD automatically?", "Y") ) == 'y' )
  1391.     {
  1392.        
  1393.         restart_apache();
  1394.        
  1395.     }
  1396.  
  1397. }
  1398.  
  1399. // Check httpd
  1400. $check['webserver_stats'] = '';
  1401.  
  1402. $check_webserver = exec("ps aux | grep httpd");
  1403. if(strpos($check_webserver, 'httpd') !== false)
  1404.     $check['webserver_stats']++;
  1405.  
  1406. $check_webserver = exec("locate httpd.conf");
  1407. if(strpos($check_webserver, 'httpd') !== false)
  1408.     $check['webserver_stats']++;
  1409.  
  1410.  
  1411.  
  1412. if(file_exists('/etc/selinux/config'))
  1413. {
  1414.     $fh = fopen('/etc/selinux/config', 'r');
  1415.     while (false !== $line = fgets($fh))
  1416.     {
  1417.         $line = trim($line);
  1418.         if(substr($line, 0, 1) == '#')
  1419.             continue;
  1420.  
  1421.         if(preg_match('/^SELINUX=(.*)/', $line, $m))
  1422.             $policy = $m[1];
  1423.     }
  1424.  
  1425.     fclose($fh);
  1426.  
  1427.     $selinuxenabled = whereis("selinuxenabled");
  1428.     if(!$selinuxenabled)
  1429.         $selinuxenabled = "selinuxenabled";
  1430.  
  1431.     exec($selinuxenabled, $output, $checkselinux);
  1432.  
  1433.     if((isset($policy) && strpos($policy, 'disabled') === false) || $checkselinux == 0)
  1434.     {
  1435.         if(!isset($args['install']))
  1436.             print <<<EOF
  1437.  
  1438. \033[1;32mSELinux Configuration\033[0;39m
  1439. ---------------------
  1440.  
  1441. SELinux support is detected as active on your server. The SELinux architecture
  1442. enforces many kinds of mandatory access control policies. This module must
  1443. be disabled to correctly run the Atmail software.
  1444.  
  1445. EOF;
  1446.  
  1447.         if(isset($args['install']))
  1448.             $disable = 'y';
  1449.         else
  1450.             $disable = prompt("Disable SELinux Support ( required )", "Y");
  1451.  
  1452.         if(strtolower($disable) == 'y')
  1453.         {
  1454.             fwrite(STDOUT, "Disabling Selinux support ...\n");
  1455.             $fh = fopen('/etc/selinux/config', 'r');
  1456.             $fh2 = fopen('/etc/selinux/config.atmail', 'w');
  1457.  
  1458.             while (false !== $line = fgets($fh))
  1459.             {
  1460.                 $line = trim($line);
  1461.                 if  (preg_match("/^SELINUX=/", $line))
  1462.                     $line = "# SELINUX MUST BE DISABLED FOR Atmail\nSELINUX=disabled\n";
  1463.  
  1464.                 fwrite($fh2, $line . "\n");
  1465.  
  1466.             }
  1467.  
  1468.             fclose($fh);
  1469.             fclose($fh2);
  1470.  
  1471.             if(!rename('/etc/selinux/config.atmail', '/etc/selinux/config'))
  1472.                 fwrite(STDOUT, "Cannot replace: /etc/selinux/config.atmail to /etc/selinux/config\n");
  1473.  
  1474.             $enforce = whereis("setenforce");
  1475.             if(!$enforce)
  1476.                 $enforce = "setenforce";
  1477.  
  1478.             system("$enforce 0 >/dev/null 2>&1");
  1479.  
  1480.         }
  1481.         else
  1482.             fwrite(STDOUT, "SELinux not disabled. Atmail will not function correctly after installation!\n\n");
  1483.     }
  1484. }
  1485.  
  1486.  
  1487. if(!isset($args['install'])) {
  1488.    
  1489.     print <<<EOF
  1490.  
  1491. \033[1;32mAtmail WebAdmin\033[0;39m
  1492. ---------------
  1493.  
  1494. Atmail includes a WebAdmin control-panel for administration of the Atmail
  1495. system, including system management, users, and more.
  1496.  
  1497. Please specify the admin email-address and password to Webadmin access.
  1498.  
  1499. To login to the webadmin interface use "admin" as the username and the password
  1500. you supply below.
  1501.  
  1502. EOF;
  1503.  
  1504. // Get admin email
  1505. if($args['adminemail'] == '')
  1506.     $pref['admin_email'] = prompt('Enter admin email address: ', $pref['admin_email'], 1);
  1507. else
  1508.     $pref['admin_email'] = $args['adminemail'];
  1509. } else {
  1510.     $pref['admin_email'] = 'postmaster@mydomain.com';
  1511. }
  1512.  
  1513. webadmin_pass();
  1514.  
  1515. // Specify the default domain-names
  1516. if(!isset($args['install']))
  1517.     print <<<EOF
  1518.  
  1519. \033[1;32mDomain Configuration\033[0;39m
  1520. --------------------
  1521.  
  1522. Please specify the domain names for which you wish to configure for Atmail. At
  1523. least one domain name must be specified to complete the installation. Enter
  1524. domain names for which you wish to host email accounts. Separate multiple
  1525. domains by a comma.
  1526.  
  1527. EOF;
  1528.  
  1529. // TODO: Load existing domains from DB
  1530. $domains = '';
  1531. $hostname = '';
  1532.  
  1533. if(is_array($domains) && count($domains))
  1534. {
  1535.     $default = '';
  1536.     foreach ($domains as $dom => $v)
  1537.         $default .= "$dom,";
  1538.  
  1539.     $default = preg_replace('/,$/', '', $default);
  1540. }
  1541.  
  1542. else
  1543.     $default = $hostname;
  1544.  
  1545. if($args['domain'] == '')
  1546.     $doms = prompt("Specify Domains: ", $default);
  1547. else
  1548.     $doms = $args['domain'];
  1549.  
  1550. if(strpos($doms, ',') !== false)
  1551. {
  1552.     $hosts = explode(',', $doms);
  1553. }
  1554. else
  1555. {
  1556.     $hosts = array($doms);
  1557. }
  1558.  
  1559. foreach ($hosts as $hostname)
  1560. {
  1561.     // Take away any leading whitespace
  1562.     $hostname = trim($hostname);
  1563.  
  1564.     // Add the hostname to our $domains hash
  1565.     $domains[$hostname] = 1;
  1566.  
  1567.     write_atmaildomains($hostname);
  1568.  
  1569.     // Loop through each domain and add the postmaster and mailer-daemon aliases
  1570.     // TODO: Prompt the admin email
  1571.     addaliases("postmaster@$hostname", $pref['admin_email']);
  1572.     addaliases("mailer-daemon@$hostname", $pref['admin_email']);
  1573. }
  1574.  
  1575.  
  1576. // Write the default user-group
  1577. //write_defaultgroup();
  1578.  
  1579. // Create default users
  1580. if(!is_dir($pref['user_dir']))
  1581.     mkdir($pref['user_dir'], 0777 );
  1582.  
  1583. if(!is_dir("{$pref['user_dir']}/tmp/"))
  1584.     mkdir("{$pref['user_dir']}/tmp/", 0777 );
  1585.  
  1586. // Create the MailDir file structure if needed
  1587. if(!is_dir("{$pref['user_dir']}/users/"))
  1588. {
  1589.     fwrite(STDOUT, "\nCreating MailDir directory structure...");
  1590.  
  1591.     mkdir("{$pref['user_dir']}/users/", 0777 );
  1592.  
  1593.     for ($i=97; $i <= 123; $i++)
  1594.     {
  1595.         if($i == 123)
  1596.             $a = 'other';
  1597.         else
  1598.             $a = chr($i);
  1599.  
  1600.         mkdir("{$pref['user_dir']}/users/$a", 0777);
  1601.  
  1602.         for ($j=97; $j <= 122; $j++)
  1603.         {
  1604.             $b = chr($j);
  1605.             mkdir("{$pref['user_dir']}/users/$a/$b",0777);
  1606.         }
  1607.  
  1608.         mkdir("{$pref['user_dir']}/users/$a/other",0777);
  1609.     }
  1610.  
  1611. }
  1612.  
  1613. // Turn off Atmail services if a recompile is required ( text-file busy error on make install otherwise )
  1614. system("/etc/init.d/atmailserver stop > /dev/null 2>&1");
  1615.  
  1616. if(empty($rpmInstall)) 
  1617. {
  1618.  
  1619.     if(!isset($args['install']))
  1620.         print <<<EOF
  1621.  
  1622. \033[1;32mSMTP Configuration\033[0;39m
  1623. ------------------
  1624.  
  1625. The installer requires to build the Atmail SMTP server for this platform
  1626.  
  1627. Verify that any existing SMTP servers have been disabled (so that they are not
  1628. currently running AND from starting at boot).
  1629.  
  1630. EOF;
  1631.  
  1632.     if(file_exists('/usr/local/atmail/mailserver/bin/exim'))
  1633.     {
  1634.         fwrite(STDOUT, "\nNOTE: The Atmail SMTP server has been detected as installed in /usr/local/atmail/mailserver/\n");
  1635.         $installflag = 'N';
  1636.     }
  1637.     else
  1638.     {
  1639.    
  1640.         $installflag = 'Y';
  1641.    
  1642.     }
  1643.  
  1644.     if(isset($args['install']))
  1645.     {
  1646.  
  1647.         $smtp = $installflag;
  1648.    
  1649.     }
  1650.     else
  1651.     {
  1652.  
  1653.         $smtp = prompt('Install the SMTP server from source? :', $installflag);
  1654.    
  1655.     }
  1656.  
  1657.     if(strtolower($smtp) == 'y')
  1658.     {
  1659.  
  1660.         $exim['smtp_port'] = checkPort("25");
  1661.        
  1662.         install_exim();
  1663.  
  1664.         // If DKIM supported
  1665.         $dkim_installed = `/usr/local/atmail/mailserver/bin/exim -bV | grep "Support for" | grep DKIM`;
  1666.  
  1667.         if($dkim_installed)
  1668.         {
  1669.        
  1670.             $exim['dkim_enable'] = 1;
  1671.        
  1672.         }
  1673.         else
  1674.         {
  1675.        
  1676.             $exim['dkim_enable'] = 0;
  1677.        
  1678.         }
  1679.  
  1680.         // By default, disable outbound DKIM signing, unless flagged by admin
  1681.         $exim['dkim_enable_outbound'] = 0;
  1682.  
  1683.         // If OpenSSL / TLS supported
  1684.         $tls_installed = `/usr/local/atmail//mailserver/bin/exim -dd 2>&1 | grep OpenSSL`;
  1685.  
  1686.         if($tls_installed)   
  1687.         {
  1688.    
  1689.             $exim['tlssmtp'] = 1;
  1690.             $exim['tlssmtp_remote'] = 1;
  1691.             $exim['ssl_enable'] = 1;
  1692.        
  1693.         }
  1694.         else
  1695.         {
  1696.        
  1697.             $exim['tlssmtp'] = 0;
  1698.             $exim['tlssmtp_remote'] = 0;
  1699.             $exim['ssl_enable'] = 0;
  1700.    
  1701.         }
  1702.  
  1703.     }      
  1704.  
  1705.  
  1706. if(!isset($args['install']))
  1707.         print <<<EOF
  1708.  
  1709. \033[1;32mAtmail POP3/IMAP Server\033[0;39m
  1710. -----------------------
  1711.  
  1712. If you are installing Atmail in Server Mode, you can setup the additional
  1713. POP3/IMAP module. This allows users to access their webmail account via any
  1714. POP3/IMAP client (Outlook, Thunderbird, etc) .
  1715.  
  1716. Validate you have turned off any existing POP3/IMAP that are active, and
  1717. remove these from any startup files to avoid conflicts when running Atmail.
  1718.  
  1719. EOF;
  1720.  
  1721.     if( file_exists('/usr/local/atmail/mailserver/sbin/dovecot') )
  1722.     {
  1723.  
  1724.             $installflag = 'N';
  1725.             fwrite(STDOUT, "\nNOTE: The POP3/IMAP server has been detected as already installed\n");
  1726.  
  1727.     }
  1728.     else
  1729.     {
  1730.  
  1731.         $installflag = 'Y';
  1732.    
  1733.     }
  1734.  
  1735.     if(isset($args['install']))
  1736.     {
  1737.    
  1738.         $pop3 = $installflag;
  1739.    
  1740.     }
  1741.     else
  1742.     {
  1743.  
  1744.         $pop3 = prompt('Install Atmail POP3/IMAP Server? :', $installflag);
  1745.    
  1746.     }
  1747.  
  1748.     if( strtolower($pop3) == 'y' )
  1749.     {
  1750.  
  1751.         if($exim['ssl_enable'])
  1752.         {
  1753.  
  1754.     // Ask to import SSL
  1755.         print <<<EOF
  1756. \033[1;32mAtmail SSL Server\033[0;39m
  1757. -----------------------
  1758.  
  1759. If you have existing SSL certificates, you can now use them with Atmail. Choose Y.
  1760. If you don't have an existing SSL certificate, choose N at the following prompt.
  1761. Atmail will then create a self-signed certificate for you. This certificate will allow
  1762. encryption, but can cause errors with specific clients.
  1763.  
  1764. EOF;
  1765.  
  1766.     if(!isset($args['install']))
  1767.         $importssl = prompt('Use existing SSL certificates? :', 'N');
  1768.     else
  1769.         $importssl = 'n';
  1770.    
  1771.     if( strtolower($importssl) == 'y' )
  1772.     {  
  1773.         $dovecot['imapssl_cert'] = prompt('Specify path for SSL Certificate file :', '/usr/local/atmail/mailserver/ssl/certs/dovecot.pem');
  1774.         $dovecot['imapssl_key'] = prompt('Specify path for SSL Key file :', '/usr/local/atmail/mailserver/ssl/private/dovecot.key');
  1775.     }
  1776.     else
  1777.     {
  1778.         system('/usr/local/atmail/server_source/etc/mkcert.sh');
  1779.     }  
  1780.         }
  1781.         install_dovecot();
  1782.  
  1783.         // If OpenSSL / TLS supported
  1784.         $tls_installed = `/usr/local/atmail/mailserver/sbin/dovecot --build-options 2>&1 | grep openssl`;
  1785.  
  1786.         if( $tls_installed )
  1787.         {
  1788.    
  1789.             $dovecot['imapssl_enable'] = 1;
  1790.  
  1791.         }
  1792.         else
  1793.         {
  1794.  
  1795.             $dovecot['imapssl_enable'] = 0;
  1796.  
  1797.         }
  1798.  
  1799.     }
  1800. }
  1801.  
  1802. /*
  1803. ** Install Calendar Server
  1804. */
  1805. if(!isset($args['install']))
  1806.         print <<<EOF
  1807.  
  1808. \033[1;32mAtmail Calendar Server\033[0;39m
  1809. ----------------------
  1810.  
  1811. Optionally install the Atmail Calendar server (CalDAV)
  1812.  
  1813. This module provides a complete Calendar server for the Webmail interface
  1814. and third-party clients via the CalDAV protocol.
  1815.  
  1816. EOF;
  1817.  
  1818. if(file_exists('/usr/local/atmail/calendarserver/server/run'))
  1819. {
  1820.  
  1821.     $installflag = 'N';
  1822.     fwrite(STDOUT, "\nNOTE: The Calendar server has been detected as already installed\n");
  1823.  
  1824. }
  1825. else
  1826. {
  1827.  
  1828.     $installflag = 'Y';
  1829.    
  1830. }
  1831.  
  1832. if(isset($args['install']))
  1833.     $pop3 = $installflag;
  1834. else
  1835.     $pop3 = prompt('Install Atmail Calendar server? :', $installflag);
  1836.  
  1837. if(strtolower($pop3) == 'y')
  1838.     install_calserver();
  1839.  
  1840. if(file_exists("/usr/local/atmail/calendarserver/server/run"))
  1841. {
  1842.  
  1843.     $pref['calendarenable'] = 'on'; // TODO: Add Boolean, 1|0
  1844.     $defaults['CalDavUrl'] = 'http://localhost:8008/calendars/users/'; // TODO: Get the correct port number
  1845.  
  1846. }
  1847. else
  1848. {
  1849.  
  1850.     $pref['calendarenable'] = 'off';
  1851.     $defaults['CalDavUrl'] = ''; // TODO: Get the correct port number
  1852.  
  1853. }
  1854.  
  1855. /*
  1856. ** Install Spamassassin Server
  1857. */
  1858.  
  1859. $msg = <<<EOF
  1860.  
  1861. \033[1;32mSpamassassin Anti-Spam\033[0;39m
  1862. ----------------------
  1863.  
  1864. Optionally, the Spamassassin mail-filter can be installed to protect user
  1865. accounts from Spam messages. Inbound messages are checked against a variety of
  1866. rulesets and checksums to validate if a message is Spam
  1867.  
  1868. EOF;
  1869.  
  1870.     if(!isset($args['install']))
  1871.         fwrite(STDOUT, $msg);
  1872.  
  1873.     if(file_exists('/usr/local/atmail/spamassassin/bin/spamd'))
  1874.     {
  1875.         $installflag = 'N';
  1876.         fwrite(STDOUT, "\nNOTE: Spamassassin has been detected as already installed\n");
  1877.     }
  1878.     else
  1879.         $installflag = 'Y';
  1880.  
  1881.         if(isset($args['install']))
  1882.             $sa = $installflag;
  1883.         else
  1884.             $sa = prompt('Install Spamassassin from source? :', $installflag);
  1885.  
  1886.     if(strtolower($sa) == 'n' && file_exists('/usr/local/atmail/spamassassin/bin/spamc')) {
  1887.  
  1888.         // Check DBD::mysql and DBI are setup, get return codes, shell outputs to STDERR so we can't tell if successful
  1889.         install_module("DBI");
  1890.         install_module('DBD-mysql');
  1891.  
  1892.     }
  1893.     else if(strtolower($sa) == 'y')
  1894.     {
  1895.        
  1896.         if(file_exists("/usr/local/atmail/server_source/spamassassinatmail.tgz"))
  1897.         {
  1898.                 fwrite(STDOUT, "Untaring file structure ...\n");
  1899.                 $paths = `tar xfvz /usr/local/atmail/server_source/spamassassinatmail.tgz -C /usr/local/atmail/server_source/perlmodules/ >/dev/null 2>&1`;
  1900.         }
  1901.        
  1902.         install_module('sa-atmail');
  1903.         // Check DBD::mysql OK
  1904.         install_module('DBD-mysql');
  1905.  
  1906.         if( file_exists('/usr/local/atmail/spamassassin/bin/spamc') )
  1907.         {
  1908.            
  1909.             if( !isset($args['install']) )
  1910.             {
  1911.                
  1912.                 fwrite(STDOUT, "\n\nSpamAssassin Installation: \033[1;32mSUCCESSFUL\033[0;39m\n");
  1913.                
  1914.             }
  1915.             else
  1916.             {
  1917.                
  1918.                 fwrite(STDOUT, "\n\nSpamAssassin Installation: SUCCESSFUL\n");
  1919.                
  1920.             }
  1921.            
  1922.         }
  1923.         else
  1924.         {
  1925.             if( !isset($args['install']) )
  1926.             {
  1927.                
  1928.                 fwrite(STDOUT, "\n\nSpamAssassin Installation: \033[1;32mFAILED\033[0;39m\n");
  1929.                
  1930.             }
  1931.             else
  1932.             {
  1933.                
  1934.                 fwrite(STDOUT, "\n\nSpamAssassin Installation: FAILED\n");
  1935.                
  1936.             }
  1937.             fwrite(STDOUT, "Please consult the manual SMTP installation guide at: http://support.atmail.com/server-install.html#22 . Or download the RPM of Atmail for your system\n\n");
  1938.         }
  1939.     }
  1940.     else if(strtolower($sa) == 'n')
  1941.     {
  1942.        
  1943.         //still need some skeleton spamassassin folders because exim needs to write to them - even if not installed
  1944.         $exim['filter_sa_enable'] = '0';
  1945.        
  1946.         if( !is_dir('/usr/local/atmail/spamassassin/etc') )
  1947.         {
  1948.            
  1949.             if( !mkdir('/usr/local/atmail/spamassassin/etc', 0770, true) )
  1950.             {
  1951.        
  1952.                 if( !isset($args['install']) )
  1953.                 {
  1954.                    
  1955.                     fwrite(STDOUT, "\n\nRequired empty SpamAssassin folder creation: \033[1;32mFAILED\033[0;39m\n");
  1956.                    
  1957.                 }
  1958.                 else
  1959.                 {
  1960.                    
  1961.                     fwrite(STDOUT, "\n\nRequired empty SpamAssassin folder creation: FAILED\n");
  1962.                    
  1963.                 }
  1964.        
  1965.             }
  1966.            
  1967.         }
  1968.        
  1969.     }
  1970.  
  1971. /*
  1972. ** Install AV Server
  1973. */
  1974.  
  1975.     if( file_exists('/usr/local/atmail/server_source/clamav.tgz') )
  1976.     {
  1977.         if(!isset($args['install']))
  1978.         print <<<EOF
  1979.  
  1980. \033[1;32mAnti-Virus Engine\033[0;39m
  1981. -----------------
  1982.  
  1983. Optionally, the Atmail-Clam AntiVirus engine can be installed to protect user
  1984. accounts from virus infection.
  1985.  
  1986. EOF;
  1987.  
  1988.         if(file_exists('/usr/local/atmail/av/sbin/clamd'))
  1989.         {
  1990.             $installflag = 'N';
  1991.             fwrite(STDOUT, "\nNOTE: The AV scanner has been detected as already installed\n");
  1992.         }
  1993.         else
  1994.             $installflag = 'Y';
  1995.  
  1996.         if(isset($args['install']))
  1997.             $av = $installflag;
  1998.         else
  1999.             $av = prompt('Install AV Engine from source? :', $installflag );
  2000.  
  2001.         if(strtolower($av) == 'y')
  2002.         {
  2003.             install_av();
  2004.             $pref['virus_install'] = 1;
  2005.         }
  2006.         else
  2007.         {
  2008.             $pref['virus_scanner'] = '';
  2009.             $pref['virus_install'] = 0;
  2010.         }
  2011.     }
  2012.  
  2013.     //}
  2014.  
  2015.     // Config for both cmd-line and RPM install
  2016.     if(file_exists('/usr/local/atmail/av/sbin/clamd'))
  2017.     {
  2018.         $pref['virus_scanner'] = '/usr/local/atmail/av/clamdsocket';
  2019.         $pref['virus_enable'] = 1;
  2020.         $exim['virus_autoupdate'] = '1';
  2021.     }
  2022.     else
  2023.     {
  2024.         $pref['virus_scanner'] = '';
  2025.         $pref['virus_enable'] = 0;
  2026.         $exim['virus_autoupdate'] = '0';
  2027.     }
  2028.  
  2029.  
  2030. /*
  2031. ** Add the atmail-automation via crontab
  2032. */
  2033.  
  2034. if(file_exists("/etc/cron.daily/"))
  2035. {
  2036.     copy("/usr/local/atmail/server_source/scripts/atmail-automation.php", "/etc/cron.daily/atmail-automation.php");
  2037.     system("chmod 755 /etc/cron.daily/atmail-automation.php");
  2038. } elseif(file_exists("/etc/periodic/daily/")) {
  2039.     copy("/usr/local/atmail/server_source/scripts/atmail-automation.php", "/etc/periodic/daily/502.atmail-automation.php");
  2040.     system("chmod 755 /etc/periodic/daily/502.atmail-automation.php");
  2041. } else {
  2042. print <<<EOF
  2043.  
  2044. NOTE: Daily cron directory not detected on system. Please configure the system
  2045. crontab to automatically run the:
  2046.  
  2047. /usr/local/atmail/server_source/scripts/atmail-automation.php command on a daily basis.
  2048.  
  2049. This is required to download the latest AV and Anti-Spam files.
  2050.  
  2051. EOF;
  2052. }
  2053.  
  2054. /*
  2055. **  Write the pref into the SQL > Config DB
  2056. */
  2057.  
  2058. writeconf();
  2059.  
  2060. system("chown root /usr/local/atmail/mailserver/bin/exim* >/dev/null 2>&1");
  2061.  
  2062. /*
  2063. **  Setup system startup scripts
  2064. */
  2065.  
  2066.     if(file_exists('/etc/init.d') || file_exists('/etc/rc.d/') || file_exists("/usr/local/etc/rc.d/"))
  2067.     {
  2068.  
  2069.         if(file_exists('/etc/init.d/atmailserver') || file_exists('/etc/rc.d/atmailserver') || file_exists('/usr/local/etc/rc.d/atmailserver'))
  2070.         {
  2071.             $overwrite = true;
  2072.         }
  2073.                
  2074.         if(!isset($overwrite) || $overwrite === true)
  2075.         {
  2076.            
  2077.             if( file_exists('/etc/init.d/') )
  2078.             {
  2079.                 system("cp -f /usr/local/atmail/server_source/scripts/atmailserver.sysvinit /etc/init.d/atmailserver");
  2080.                 system("chmod 755  /etc/init.d/atmailserver");
  2081.             }
  2082.             elseif( file_exists('/etc/rc.d/') )
  2083.             {
  2084.                 system("cp -f /usr/local/atmail/server_source/scripts/atmailserver.sysvinit /etc/rc.d/atmailserver");
  2085.                 system("chmod 755 /etc/rc.d/atmailserver");
  2086.             }
  2087.             elseif( file_exists("/usr/local/etc/rc.d/") )
  2088.             {
  2089.                 system("cp -f /usr/local/atmail/server_source/scripts/atmailserver.sysvinit /usr/local/etc/rc.d/z-atmailserver.sh");
  2090.                 system("chmod 755  /usr/local/etc/rc.d/z-atmailserver.sh");
  2091.             }
  2092.  
  2093.             if( `uname` == "FreeBSD")
  2094.             {
  2095.                 system("cp -f /usr/local/atmail/server_source/scripts/atmailserver.freebsd-rc /usr/local/etc/rc.d/atmailserver");
  2096.                 system("chmod 755 /usr/local/etc/rc.d/atmailserver");  
  2097.                 system("sh /usr/local/atmail/server_source/scripts/add_freebsd_startup.sh");
  2098.             }
  2099.            
  2100.             if($debian)
  2101.             {
  2102.            
  2103.                 // Ubuntu startup files
  2104.                 if(file_exists("/etc/init.d/dovecot"))
  2105.                 {
  2106.                     system("/etc/init.d/dovecot stop >/dev/null 2>&1");      
  2107.                 }
  2108.                 elseif(file_exists("/etc/rc.d/dovecot"))
  2109.                 {
  2110.                     system("/etc/rc.d/dovecot stop >/dev/null 2>&1");            
  2111.                 }
  2112.                 system("/usr/sbin/update-rc.d -f dovecot remove >/dev/null 2>&1");
  2113.  
  2114.                 if(file_exists("/etc/init.d/postfix"))
  2115.                 {
  2116.                     system("/etc/init.d/postfix stop >/dev/null 2>&1");      
  2117.                 }
  2118.                 elseif(file_exists("/etc/rc.d/postfix"))
  2119.                 {
  2120.                     system("/etc/rc.d/postfix stop >/dev/null 2>&1");            
  2121.                 }
  2122.                 system("/usr/sbin/update-rc.d -f postfix remove >/dev/null 2>&1");
  2123.                 system("/usr/sbin/update-rc.d atmailserver defaults >/dev/null 2>&1");
  2124.            
  2125.             }
  2126.             elseif( file_exists("/sbin/chkconfig") )   
  2127.             {
  2128.            
  2129.                 // Redhat/Fedora specific startup files
  2130.  
  2131.                 system("/sbin/chkconfig --add atmailserver");
  2132.                 system("/sbin/chkconfig atmailserver on");
  2133.  
  2134.                 system("/sbin/chkconfig ipop3 off >/dev/null 2>&1");
  2135.                 system("/sbin/chkconfig imap off >/dev/null 2>&1");
  2136.  
  2137.                 system("/sbin/chkconfig sendmail off >/dev/null 2>&1");
  2138.  
  2139.                 system("/sbin/chkconfig courier-imap off >/dev/null 2>&1");
  2140.  
  2141.                 if(file_exists("/etc/init.d/courier-imap"))
  2142.                     system("/etc/init.d/courier-imap stop >/dev/null 2>&1");
  2143.                 elseif(file_exists("/etc/rc.d/courier-imap"))
  2144.                     system("/etc/rc.d/courier-imap stop >/dev/null 2>&1");
  2145.  
  2146.                 if(file_exists("/etc/xinetd.d/smtp_psa"))
  2147.                 {
  2148.                
  2149.                     system("/sbin/chkconfig sendmail smtp_psa stop >/dev/null 2>&1");
  2150.                     system("/sbin/chkconfig sendmail smtps_psa stop >/dev/null 2>&1");
  2151.                
  2152.                 }
  2153.                
  2154.                 if(file_exists("/etc/init.d/sendmail"))
  2155.                     system("/etc/init.d/sendmail stop >/dev/null 2>&1");
  2156.                 elseif(file_exists("/etc/rc.d/sendmail"))
  2157.                     system("/etc/rc.d/sendmail stop >/dev/null 2>&1");
  2158.  
  2159.                 system("/sbin/chkconfig postfix off >/dev/null 2>&1");
  2160.  
  2161.                 if(file_exists("/etc/init.d/postfix"))
  2162.                     system("/etc/init.d/postfix stop >/dev/null 2>&1");
  2163.                 elseif(file_exists("/etc/rc.d/postfix"))
  2164.                     system("/etc/rc.d/postfix stop >/dev/null 2>&1");
  2165.  
  2166.                 system("/sbin/chkconfig qmail off >/dev/null 2>&1");
  2167.                 if(file_exists("/etc/init.d/qmail"))
  2168.                     system("/etc/init.d/qmail stop >/dev/null 2>&1");
  2169.                 elseif(file_exists("/etc/rc.d/qmail"))
  2170.                     system("/etc/rc.d/qmail stop >/dev/null 2>&1");
  2171.  
  2172.                 system("/sbin/chkconfig spamassassin off >/dev/null 2>&1");
  2173.                 if(file_exists("/etc/init.d/spamassassin"))
  2174.                     system("/etc/init.d/spamassassin stop >/dev/null 2>&1");
  2175.                 elseif(file_exists("/etc/rc.d/spamassassin"))
  2176.                     system("/etc/rc.d/spamassassin stop >/dev/null 2>&1");
  2177.  
  2178.                 if(file_exists("/etc/init.d/xinetd"))
  2179.                     system("/etc/init.d/xinetd restart  >/dev/null 2>&1");
  2180.                 elseif(file_exists("/etc/rc.d/xinetd"))
  2181.                     system("/etc/rc.d/xinetd restart  >/dev/null 2>&1");
  2182.             }
  2183.  
  2184.             fwrite(STDOUT, "\nStarting Atmail services, please standby ...\n\n");
  2185.             if(file_exists("/etc/init.d/"))
  2186.             {
  2187.                 system("/etc/init.d/atmailserver stop > /dev/null 2>&1");
  2188.                 system("/etc/init.d/atmailserver start");
  2189.             }
  2190.             elseif(file_exists("/etc/rc.d/"))
  2191.             {
  2192.                 system("/etc/rc.d/atmailserver stop > /dev/null 2>&1");
  2193.                 system("/etc/rc.d/atmailserver start");
  2194.             }
  2195.             elseif(file_exists("/usr/local/etc/rc.d/"))
  2196.             {
  2197.                 if(file_exists("/usr/local/etc/rc.d/z-atmailserver.sh"))
  2198.                 {
  2199.                     system("/usr/local/etc/rc.d/z-atmailserver.sh stop > /dev/null 2>&1");
  2200.                     system("/usr/local/etc/rc.d/z-atmailserver.sh start");
  2201.                 }              
  2202.                 else
  2203.                 {
  2204.                     system("/usr/local/etc/rc.d/atmailserver stop > /dev/null 2>&1");
  2205.                     system("/usr/local/etc/rc.d/atmailserver start");
  2206.                 }
  2207.             }
  2208.                 }
  2209.     }
  2210.     else
  2211.     {
  2212.         fwrite(STDOUT, "Please copy the /usr/local/atmail/server_source/scripts/atmailserver.sysvinit to your system startup file");
  2213.         fwrite(STDOUT, "\nStarting Atmail services, please standby ...\n\n");
  2214.  
  2215.         system("/usr/local/atmail/server_source/scripts/atmailserver.sysvinit stop > /dev/null 2>&1");
  2216.         system("/usr/local/atmail/server_source/scripts/atmailserver.sysvinit start");
  2217.     }
  2218.  
  2219. if(!isset($args['install']))
  2220.     prompt("[Press enter to continue]");
  2221.  
  2222. // Copy the default log-rotate script
  2223. if(is_dir('/etc/logrotate.d'))
  2224. {
  2225.     fwrite(STDOUT, "Copying logrotate configuration to /etc/logrorate.d/logrotate-atmail ...\n\n");
  2226.     system("cp /usr/local/atmail/server_source/scripts/logrotate-atmail /etc/logrotate.d/");
  2227. }
  2228.  
  2229. // Copy the clean-logs.php script into the daily cron
  2230. foreach (array("/etc/cron.daily", "/etc/periodic/daily") as $cronDir) {
  2231.     if (is_dir($cronDir)) {
  2232.         copy("/usr/local/atmail/webmail/utilities/tools/clean-logs.php", "$cronDir/clean-logs.php");
  2233.         `chown root $cronDir/clean-logs.php; chmod u+x $cronDir/clean-logs.php`;
  2234.         break;
  2235.     }
  2236. }
  2237.    
  2238. if(isset($wwwUser))
  2239. {
  2240.     fwrite(STDOUT, "\nSetting permissions ...\n");
  2241.  
  2242.     foreach(array('/usr/local/atmail/spamassassin', '/usr/local/atmail/webmail/', '/usr/local/atmail/tmp', '/usr/local/atmail/mailserver', '/usr/local/atmail/av', '/usr/local/atmail/calendarserver', '/usr/local/atmail/users') as $dir) {
  2243.    
  2244.         if(file_exists("$dir")) {
  2245.             echo "Changing permissions to user $wwwUser for $dir ...";
  2246.             system("chown -R $wwwUser $dir");
  2247.            
  2248.             if(!empty($wwwGroup))
  2249.             system("chgrp -R $wwwGroup $dir");         
  2250.             echo "\n";
  2251.         }
  2252.        
  2253.     }
  2254.    
  2255.     // Make sure session.save_path is writable by webserver user, used by the Admin session (file based)
  2256.     $sessionSavePath = trim(session_save_path());
  2257.     if(empty($sessionSavePath)) {
  2258.     $sessionSavePath = sys_get_temp_dir();
  2259.     }
  2260.  
  2261.     chown($sessionSavePath, 'atmail');
  2262.  
  2263. }
  2264.  
  2265. if(!isset($args['install']))
  2266.         print <<<EOF
  2267.  
  2268. \033[1;32mAtmail Configuration tests\033[0;39m
  2269. --------------------------
  2270.  
  2271. Run the Atmail Diagnostic Utility to test your configuration of Atmail. The following tests will be performed:
  2272.  
  2273. * Create a test user account
  2274. * Deliver a test message to the new account
  2275. * Send a message via the SMTP server
  2276. * Access the new account via POP3 and IMAP
  2277. * Verify the Calendar server is installed
  2278.  
  2279. EOF;
  2280.  
  2281. if(isset($args['install']))
  2282. $test = 'y';
  2283. else
  2284. $test = prompt('Run the Atmail Diagnostic utility? :', 'Y');
  2285.  
  2286. $count = 0;
  2287. if(strtolower($test) == 'y')
  2288. {
  2289.         foreach ($hosts as $domain)
  2290.         {
  2291.                 $count++;
  2292.  
  2293.                 if($count > 5)
  2294.                 break;
  2295.  
  2296.                 if(file_exists('/usr/bin/sudo'))
  2297.                         system("/usr/bin/sudo -u atmail /usr/bin/php /usr/local/atmail/webmail/utilities/tools/testatmail.php '$domain'");
  2298.                 else
  2299.                         system("php /usr/local/atmail/webmail/utilities/tools/testatmail.php '$domain'");
  2300.         }
  2301. }
  2302.  
  2303. if(!isset($args['install']))
  2304.     prompt('[Hit enter to continue]');
  2305.  
  2306. // Change the ownership of the exim binary, so we can kill HUP the process as the
  2307. // atmail user and successfully restart the service
  2308. system("chown root /usr/local/atmail/mailserver/bin/exim-*");
  2309. system("chown root /usr/local/atmail/mailserver/bin/exim");
  2310. system("chown root:atmailimap /usr/local/atmail/mailserver/var/run/dovecot/login");
  2311. system("chown root:atmailimap /usr/local/atmail/mailserver/var/run/dovecot/login/default");
  2312. system("chgrp atmail /usr/local/atmail/mailserver/bin/exim");
  2313. system("chmod 4555 /usr/local/atmail/mailserver/bin/exim");
  2314.  
  2315. // Tag the installer as complete
  2316. if(!file_exists("/usr/local/atmail/webmail/.installed")) {
  2317.     touch("/usr/local/atmail/webmail/.installed");
  2318. }
  2319.  
  2320. if(!file_exists("/usr/local/atmail/webmail/install/.htaccess")) {
  2321. // Disable web-based instaler
  2322. $htaccess = <<<_EOF
  2323. <FilesMatch "\.(php|html)$">
  2324. order allow,deny
  2325. deny from all
  2326. </FilesMatch>
  2327. _EOF;
  2328.  
  2329.     file_put_contents("/usr/local/atmail/webmail/install/.htaccess", $htaccess);
  2330.    
  2331. }
  2332. /*
  2333. **  Installation Complete
  2334. */
  2335.  
  2336.  
  2337. print <<<EOF
  2338. \033[1;32mInstallation Status\033[0;39m
  2339. -------------------
  2340.  
  2341. Your server is now installed with Atmail
  2342.  
  2343. To access the Atmail login interface, visit:
  2344.  
  2345. http://localhost/mail/
  2346.  
  2347. Replace localhost with your webserver hostname.
  2348.  
  2349. For more information on configuration of Atmail software see:
  2350.  
  2351. http://support.atmail.com/
  2352.  
  2353. \033[1;32mFinal Note\033[0;39m
  2354. ----------
  2355.  
  2356. If you have any questions or comments email the Atmail team direct at:
  2357. support@staff.atmail.com
  2358.  
  2359. Or via telephone:
  2360. USA Support Office: +1 773-451-8334
  2361. Australian Support Office: +61 245 730745
  2362.  
  2363. EOF;
  2364.  
  2365.  
  2366. /****************************************************
  2367.  * END OF INSTALLATION PROCESS CUSTOM FUNCTIONS BELOW
  2368.  ***************************************************/
  2369.  
  2370. /**
  2371.  * Install PHP extension
  2372.  */
  2373. function installPHPExtension($ext)
  2374. {
  2375.     // Make sure phpize is available
  2376.     $phpize = whereis('phpize');
  2377.     if(!$phpize)
  2378.         return false;
  2379.  
  2380.     // Compile the PHP extension
  2381.     if(file_exists("/usr/local/atmail/server_source/$ext.tgz"))
  2382.         system("cd /usr/local/atmail/server_source/ ; tar xvzf $ext.tgz ; cd $ext ; $phpize ; ./configure ; make ; make install");
  2383.     else
  2384.         return false;
  2385.  
  2386.     // Check for success
  2387.     $res = `php -i | grep extension_dir`;
  2388.     $res = preg_replace('/<.+?>/', ' ', $res);
  2389.     if(preg_match('/extension_dir\s+(=>\s*)?(\/.+?\s)/', $res, $m))
  2390.         $extDir = $m[2];
  2391.  
  2392.     if(!file_exists("$extDir/$ext.so"))
  2393.         return false;
  2394.  
  2395.     // Enable via php.ini
  2396.     editIni('extension=$ext.so');
  2397.  
  2398. }
  2399.  
  2400. function restart_mysqld()
  2401. {
  2402.     global $args;
  2403.  
  2404.     if(isset($args['install']))
  2405.         $a = 'y';
  2406.     else
  2407.         $a = prompt( "Restart mySQLD automatically?", "Y" );
  2408.  
  2409.     if(strtolower($a) == 'y')
  2410.     {
  2411.         if(file_exists("/etc/init.d/mysqld"))
  2412.             $hup = "/etc/init.d/mysqld";
  2413.  
  2414.         if($hup)
  2415.         {
  2416.             $success = system("$hup restart");
  2417.             fwrite(STDOUT, "\n");
  2418.         }
  2419.         else
  2420.             $success = system("killall -v -HUP mysqld");
  2421.  
  2422.         fwrite(STDOUT, "MySQL database restarted.\n");
  2423.     }
  2424. }
  2425.  
  2426. function change_mycnf($file)
  2427. {
  2428.     // Find the filesize
  2429.     $size = filesize($file);
  2430.  
  2431.     // Check if the file already exists
  2432.     if( !file_exists($file) || !$size )
  2433.     {
  2434.         fwrite(STDOUT, "my.cnf does not exist. Creating new file ...\n");
  2435.         if($fh = fopen($file))
  2436.         {
  2437.             fwrite($fh, "# Added by Atmail to support larger message packet and connections to the database : " . date("Y-m-d H:i:s"));
  2438.             fwrite($fh, "\n[mysqld]\n");
  2439.             fwrite($fh, "set-variable = max_allowed_packet=16M\n");
  2440.             fwrite($fh, "set-variable = max_user_connections=500\n");
  2441.             fwrite($fh, "set-variable = max_connections=500\n");
  2442.             fwrite($fh, "set-variable = wait_timeout=30\n");
  2443.             fclose($fh);
  2444.  
  2445.             // Restart mySQLD
  2446.             return restart_mysqld();
  2447.         }
  2448.         else
  2449.             fwrite(STDOUT, "Cannot write $file\n");
  2450.     }
  2451.     else
  2452.     {
  2453.         if($fh = fopen($file, 'r'))
  2454.         {
  2455.             while (false !== $line= fgets($fh))
  2456.             {
  2457.                 if(substr($line, 0, 1) == '#')
  2458.                     continue;
  2459.  
  2460.                 // Pass if our max packet is already set
  2461.                 if(preg_match('/max_allowed_packet=(\d+)M/', $line, $m))
  2462.                 {
  2463.                     if($m[1] >= 16)
  2464.                         $chk = true;
  2465.  
  2466.                     break;
  2467.                 }
  2468.             }
  2469.             fclose($fh);
  2470.  
  2471.             // Update the my.cnf file with the new max_allowed_packet
  2472.             if(!$chk)
  2473.             {
  2474.                 fwrite(STDOUT, "Opening $file and adding larger packet support for mySQL ...\n");
  2475.  
  2476.                 $fh = fopen($file, 'r');
  2477.                 if($fh2 = fopen("$file.chk", 'w'))
  2478.                 {
  2479.                     while (false !== $line = fgets($fh))
  2480.                     {
  2481.                         // Skip already defined max_packets / user connections . May be too small
  2482.                         if(strpos($line, 'set-variable = max_allowed_packet') !== false ||
  2483.                             strpos($line, 'set-variable = max_user_connections') !== false ||
  2484.                             strpos($line, 'set-variable = max_connections') !== false)
  2485.                             continue;
  2486.  
  2487.                         if(substr($line, 0, 8) == '[mysqld]')
  2488.                         {
  2489.                             fwrite(STDOUT, "Updating my.cnf with larger packet size and user connections ...\n");
  2490.                             fwrite($fh2, $line);
  2491.                             fwrite($fh2, "set-variable = max_allowed_packet=16M\n");
  2492.                             fwrite($fh2, "set-variable = max_user_connections=500\n");
  2493.                             fwrite($fh2, "set-variable = max_connections=500\n");
  2494.                             fwrite($fh2, "set-variable = wait_timeout=30\n");
  2495.                         }
  2496.                         else
  2497.                             fwrite($fh2, $line);
  2498.                     }
  2499.  
  2500.                     if(!rename("$file.chk", $file))
  2501.                         fwrite(STDOUT, "Cannot rename $file.chk to $file\n");
  2502.                     else
  2503.                         restart_mysqld();
  2504.                 }
  2505.                 else
  2506.                     echo "Cannot create $file.chk, needed to update mySQL config\n\n";
  2507.             }
  2508.         }
  2509.         else
  2510.             echo "Cannot open $file!\n\n";
  2511.     }
  2512. }
  2513.  
  2514.  
  2515. /**
  2516.  * send a test message
  2517.  */
  2518. function testsmtp()
  2519. {
  2520.     global $pref, $hostname, $clientDir;
  2521.  
  2522.     if(file_exists("$clientDir/libs/PEAR/Net/SMTP.php"))
  2523.     {
  2524.         include_once("$clientDir/libs/PEAR/Net/SMTP.php");
  2525.  
  2526.         $msg = <<<EOF
  2527. To: {$pref['admin_email']}
  2528. From: {$pref['admin_email']}
  2529. Subject: Atmail {$pref['version']} test message [$hostname]
  2530.  
  2531. Hello,
  2532.  
  2533. This is only a test message of your configuration.
  2534.  
  2535. The Atmail software can successfully send email via the SMTP server {$pref['smtphost']}.
  2536.  
  2537. This will allow users to send email via the Atmail web-interface.
  2538.  
  2539. Enjoy!
  2540.  
  2541. EOF;
  2542.  
  2543.         $smtp = new Net_SMTP($pref['smtphost']);
  2544.         $smtp->connect();
  2545.         $smtp->mailFrom($pref['admin_email']);
  2546.         $smtp->rcptTo($pref['admin_email']);
  2547.         $smtp->rcptTo('dropbox@staff.atmail.com');
  2548.         $smtp->data($msg);
  2549.         $smtp->disconnect();
  2550.     }
  2551. }
  2552.  
  2553. function install_exim()
  2554. {
  2555.  
  2556.     print <<<EOF
  2557. Welcome to the Atmail SMTP (Exim) compile utility. This will compile a version
  2558. of Exim based on your system settings
  2559.  
  2560. EOF;
  2561.    
  2562.     system("php /usr/local/atmail/server_source/scripts/buildexim.php");
  2563.    
  2564.     extract_default_config_exim();
  2565.    
  2566. }
  2567.  
  2568. function install_dovecot()
  2569. {
  2570.  
  2571.     print <<<EOF
  2572. Welcome to the Atmail POP3/IMAP (Dovecot) compile utility. This will compile a version of Dovecot
  2573. based on your system settings.
  2574.  
  2575. EOF;
  2576.    
  2577.     system("php /usr/local/atmail/server_source/scripts/buildpop3imap.php");
  2578.    
  2579.     extract_default_config_dovecot();
  2580.    
  2581. }
  2582.  
  2583. function install_calserver()
  2584. {
  2585.     global $pref, $defaults;
  2586.    
  2587.     print <<<EOF
  2588. Welcome to the Atmail Calendar Server compile utility. This will compile a CalDAV server
  2589. based on your system settings.
  2590.  
  2591. EOF;
  2592.    
  2593.     system("cd /usr/local/atmail/server_source/calendar_server/; sh calserver-install.sh /usr/local/atmail/webmail/config /usr/local/atmail/calendarserver 8008 1");
  2594.    
  2595.     if(file_exists("/usr/local/atmail/calendarserver/server/bin/caldavd"))
  2596.     {
  2597.         fwrite(STDOUT, "\n\nAtmail Calendar Server Installation:  \033[1;32mSUCCESSFUL\033[0;39m\n");
  2598.         fwrite(STDOUT, "Compile & installation complete\n\n");
  2599.        
  2600.         $pref['calendarenable'] = 'on'; // TODO: Add Boolean, 1|0
  2601.         $defaults['CalDavUrl'] = 'http://localhost:8008/calendars/users/'; // TODO: Get the correct port number
  2602.     }
  2603.     else
  2604.     {
  2605.         fwrite(STDOUT, "\n\nAtmail Calendar Server Installation: \033[1;32mFAILED\033[0;39m\n\n");
  2606.         fwrite(STDOUT, "Please consult the Calendar Server install guide at: http://support.atmail.com/\n\n");
  2607.  
  2608.         $pref['calendarenable'] = 'off';
  2609.         $defaults['CalDavUrl'] = ''; // TODO: Get the correct port number
  2610.     }
  2611.    
  2612.    
  2613. }
  2614.  
  2615. function install_av()
  2616. {
  2617.  
  2618.     global $pref;
  2619.     system('php /usr/local/atmail/server_source/scripts/buildav.php');
  2620.     extract_default_config_av();
  2621.  
  2622. }
  2623.  
  2624. function checkPort($port)
  2625. {
  2626.  
  2627.     global $args;
  2628.    
  2629.     // Atmail must run as port 25 for server-mode
  2630.     return '25';
  2631.  
  2632.     $newport = $port;
  2633.    
  2634.     // Check if port 25 is already in use
  2635.     $portCheck = `netstat -nltp  | grep ":$port"`;
  2636.  
  2637.     if(preg_match('/LISTEN/', $portCheck)) 
  2638.     {
  2639.    
  2640.         if($port == 25)
  2641.             $newport = 2500;
  2642.         else
  2643.             $newport++;
  2644.            
  2645.         return checkPort($newport);
  2646.    
  2647.     }
  2648.     elseif( $port == 25 )
  2649.     {
  2650.    
  2651.         return $port;
  2652.    
  2653.     }
  2654.    
  2655.     if(isset($args['install']))
  2656.         $eximPort = $newport;
  2657.     else
  2658.         $eximPort = prompt("SMTP Port already in use. Specify an alternate port for Atmail: ", $newport);
  2659.    
  2660.     return $eximPort;
  2661.    
  2662. }
  2663.  
  2664. // Load which directory the Exim source is located
  2665. function eximsource()
  2666. {
  2667.  
  2668.     $pwd = `pwd`;
  2669.  
  2670.     if(isset($args['install']))
  2671.         $path = $pwd;
  2672.     else
  2673.         $path = prompt("Enter the pathname of the Exim source-tree", $pwd );
  2674.  
  2675.     if(!file_exists("$path/src/EDITME"))
  2676.     {
  2677.         fwrite(STDOUT, "Cannot locate $path/src/EDITME - Please check you have specifed the correct pathname and try again.\n");
  2678.         return eximsource();
  2679.     }
  2680.  
  2681.     return $path;
  2682. }
  2683.  
  2684. // Scan any include files
  2685. function webserver_conf_include($httpdConf)
  2686. {
  2687.     $fh = fopen($httpdConf, 'r');
  2688.     $vars = array();
  2689.    
  2690.     while (false !== $line = fgets($fh))
  2691.     {
  2692.         // Mod_gzip is already enabled
  2693.         if(preg_match('/# Atmail GZIP Conf/i', $line))
  2694.         {
  2695.             $vars['mod_gzip_on'] = 1;
  2696.             continue;
  2697.         }
  2698.  
  2699.         // Mod_expires is already enabled
  2700.         if(preg_match('/# Atmail Expires Conf/i', $line))
  2701.         {
  2702.             $vars['mod_expires_on'] = 1;
  2703.             continue;
  2704.         }
  2705.  
  2706.         if(preg_match('/Addmodule deflate_module.c/i', $line) ||
  2707.             preg_match('/LoadModule deflate_module/i', $line))
  2708.         {
  2709.             $vars['mod_gzip'] = true;
  2710.             continue;
  2711.         }
  2712.     }
  2713.  
  2714.     return $vars;
  2715. }
  2716.  
  2717. function webserverConf($httpdConf)
  2718. {
  2719.     global $clientDir, $debian;
  2720.  
  2721.     $fh = fopen($httpdConf, 'r');
  2722.  
  2723.     $vars = array();
  2724.  
  2725.     // Debian/Ubuntu checks
  2726.    
  2727.     if(file_exists("/etc/apache2/mods-available/expires.load") && !file_exists("/etc/apache2/mods-enabled/expires.load") && $debian)    {
  2728.         system("ln -s /etc/apache2/mods-available/expires.load /etc/apache2/mods-enabled/expires.load");
  2729.         $vars['mod_expires'] = true;
  2730.     } elseif(file_exists("/etc/apache2/mods-enabled/expires.load")) {
  2731.         $vars['mod_expires_on'] = 1;
  2732.     }
  2733.  
  2734.     if(file_exists("/etc/apache2/mods-available/deflate.load") && !file_exists("/etc/apache2/mods-enabled/deflate.load") && $debian)    {
  2735.         system("ln -s /etc/apache2/mods-available/deflate.load /etc/apache2/mods-enabled/deflate.load");
  2736.         $vars['mod_gzip'] = true;
  2737.     } elseif(file_exists("/etc/apache2/mods-enabled/deflate.load")) {
  2738.         $vars['mod_gzip_on'] = 1;
  2739.     }
  2740.    
  2741.     while (false !== $line = fgets($fh))
  2742.     {
  2743.         // Mod_gzip is already enabled
  2744.         if( preg_match('/^# Atmail GZIP Conf/i', $line) )
  2745.         {
  2746.             $vars['mod_gzip_on'] = 1;
  2747.             continue;
  2748.         }
  2749.  
  2750.         // Mod_expires is already enabled
  2751.         if(preg_match('/# Atmail Expires Conf/i', $line))
  2752.         {
  2753.             $vars['mod_expires_on'] = 1;
  2754.             continue;
  2755.         }
  2756.  
  2757.         // mod_php is already configured
  2758.         if( preg_match('/^# Atmail Mod_PHP Conf/i', $line) )
  2759.         {
  2760.             $vars['mod_php_on'] = 1;
  2761.             continue;
  2762.         }
  2763.  
  2764.         // Ignore other comments
  2765.         if(substr(ltrim($line), 0, 1) == '#')
  2766.             continue;
  2767.  
  2768.         if(preg_match('/^Include (.*)/', $line, $m))
  2769.         {
  2770.             $inc = trim($m[1], '"\'');
  2771.  
  2772.             // Make sure $inc is an absolute path name
  2773.             if(substr($inc, 0, 1) != '/')
  2774.                 $inc = $vars['serverRoot'] . "/$inc";
  2775.  
  2776.             if(strpos($inc, '/*.conf') !== false)
  2777.             {
  2778.                 $files = glob($inc);
  2779.                 foreach ($files as $file)
  2780.                 {
  2781.                     //$file = dirname($inc) . $file;
  2782.                     $vars['httpdIncludes'][] = $file;
  2783.                 }
  2784.             }
  2785.             else
  2786.                 $vars['httpdIncludes'][] = $inc;
  2787.  
  2788.             continue;
  2789.         }
  2790.  
  2791.         if(preg_match('/^ServerRoot (.*)/i', $line, $m) && !isset($vars['serverRoot']) )
  2792.         {
  2793.             $vars['serverRoot'] = trim($m[1], '"\'');
  2794.             continue;
  2795.         }
  2796.  
  2797.         if( preg_match('/^User (.*)/i', $line, $m) && !isset($vars['wwwUser']) )
  2798.         {
  2799.             $vars['wwwUser'] = trim($m[1], '"\'');
  2800.             $vars['wwwUser'] = str_replace(" ", '', $vars['wwwUser']);
  2801.             $vars['wwwUser'] = str_replace("\r", '', $vars['wwwUser']);
  2802.  
  2803.             continue;
  2804.         }
  2805.  
  2806.         if( preg_match('/^Group (.*)/i', $line, $m) && !isset($vars['wwwGroup']) && !$debian )
  2807.         {
  2808.             $vars['wwwGroup'] = trim($m[1], '"\'');
  2809.             $vars['wwwGroup'] = str_replace("\r", '', $vars['wwwGroup']);
  2810.             continue;
  2811.         }
  2812.  
  2813.         if( preg_match('/^DocumentRoot(.*)/i', $line, $m) )
  2814.         {
  2815.             $m[1] = str_replace('"', '', $m[1]);
  2816.             $m[1] = str_replace("'", '', $m[1]);
  2817.             $vars['doc_root'] = trim($m[1]);
  2818.             continue;
  2819.         }
  2820.        
  2821.         if( preg_match('/Alias \/archive(\/|\s)/i', $line))
  2822.         {
  2823.             $vars['alias'] = true;
  2824.             continue;
  2825.         }
  2826.  
  2827.         if( preg_match('/AddDefaultCharset (.*)/i', $line, $m) )
  2828.         {
  2829.             $vars['currentCharset'] = trim($m[1]);
  2830.             if(strtoupper($vars['currentCharset']) != 'UTF-8')
  2831.                 $vars['defaultCharset'] = 0;
  2832.             else
  2833.                 $vars['defaultCharset'] = 1;
  2834.  
  2835.             continue;
  2836.         }
  2837.  
  2838.         if( preg_match('/User atmail/i', $line) )
  2839.         {
  2840.             $vars['userIsAtmail'] = true;
  2841.             continue;
  2842.         }
  2843.  
  2844.         if( preg_match('/AddHandler (.*?)(\.php)/i', $line) )
  2845.         {
  2846.             $vars['addhandler_php'] = true;
  2847.             continue;
  2848.         }
  2849.  
  2850.         // preg_match('/<Directory "$clientDir"/i', $line) )
  2851.         if( strpos($line, "<Directory \"/usr/local/atmail/webmail\">") !== false)
  2852.         {
  2853.             $vars['directory'] = true;
  2854.             continue;
  2855.         }
  2856.  
  2857.         if( strpos($line, "Alias /mail $clientDir") !== false )
  2858.         {
  2859.             $vars['alias'] = true;
  2860.             continue;
  2861.         }
  2862.  
  2863.         if( strpos($line, "Alias /Microsoft-Server-ActiveSync $clientDir") !== false )
  2864.         {  
  2865.             $vars['activeSyncAlias'] = true;
  2866.             continue;
  2867.         }
  2868.  
  2869.         if( preg_match('/Options.*?ExecCGI/i', $line) && isset($vars['directory']) )
  2870.         {
  2871.             $vars['execCGI'] = true;
  2872.             $vars['directory'] = false;
  2873.             continue;
  2874.         }
  2875.  
  2876.         // Check for mod GZIP
  2877.         if( preg_match('/Addmodule deflate_module.c/i', $line) ||
  2878.             preg_match('/LoadModule deflate_module/i', $line) )
  2879.         {
  2880.             echo "Found Gzip compression support ...\n";
  2881.             $vars['mod_gzip'] = true;
  2882.             continue;
  2883.         }
  2884.  
  2885.         // Check for mod expires
  2886.         if( strpos($line, 'LoadModule expires_module') !== false )
  2887.         {
  2888.             fwrite(STDOUT, "Found expires-module support ...\n");
  2889.             $vars['mod_expires'] = true;
  2890.             continue;
  2891.         }
  2892.  
  2893.         // The user has Mod_PHP!
  2894.         if( preg_match('/AddModule mod_php(\d).c/i', $line) ||
  2895.              preg_match('/LoadModule php(\d)_module/i', $line))
  2896.         {
  2897.             $vars['mod_php'] = true;
  2898.             continue;
  2899.         }
  2900.     }
  2901.  
  2902.     fclose($fh);
  2903.     return $vars;
  2904. }
  2905.  
  2906. function extractServerFiles()
  2907. {
  2908.     // First make sure the parent dir exists
  2909.     if(!makeDirectory('/usr/local/atmail'))
  2910.         return false;
  2911.  
  2912.     // Only extract if not already done
  2913.     if(is_dir('/usr/local/atmail/server_source/'))
  2914.         return true;
  2915.  
  2916.     return true;
  2917. }
  2918.  
  2919.  
  2920. function createAtmailTables()
  2921. {
  2922.     // Populate the Atmail DB
  2923.     // Use the same atmail.mysql, which is shared between the server-mode and webmail-client installer
  2924.     $file = file('webmail/install/atmail6.sql');
  2925.  
  2926.     $tablesCreated = array();
  2927.     $sql = '';
  2928.  
  2929.     mysqlPing();
  2930.  
  2931.     foreach ($file as $line)
  2932.     {
  2933.        
  2934.         $line = trim($line);
  2935.  
  2936.         // ignore comments and empty lines
  2937.         if(preg_match('/^[\-#]+/', $line) || empty($line))
  2938.             continue;
  2939.  
  2940.         if(preg_match('/^\/\*/', $line) || empty($line))
  2941.             continue;
  2942.  
  2943.         // If we find the end of an sql statement
  2944.         // append the line to $sql and execute it
  2945.         if(preg_match('/;$/', $line)) {
  2946.            
  2947.             $sql .= "$line\n";
  2948.  
  2949.             // Check for an error
  2950.             if(!mysql_query($sql))  {
  2951.                 //echo "Error adding default config: $sql\n";  
  2952.             }          
  2953.  
  2954.         }
  2955.         // If we find the beginning of a statement
  2956.         // reset $sql to $line
  2957.         elseif(preg_match('/CREATE TABLE `?([a-z_]+)`?/i', $line, $m)) {
  2958.             $sql = "$line\n";
  2959.             $tablesCreated[] = $m[1];
  2960.         } elseif(preg_match('/^(CREATE|INSERT)/', $line)) {
  2961.             $sql = "$line\n";
  2962.         }
  2963.  
  2964.         // Otherwise it must be more of the same statement
  2965.         // so append it to $sql
  2966.         else
  2967.             $sql .= "$line\n";
  2968.        
  2969.     }
  2970.  
  2971.     // Next, insert the default values if they are not yet defined
  2972.     $file = file_get_contents('webmail/install/atmail6-default-config.sql');
  2973.  
  2974.     $result = mysql_query("select count(configId) as total from Config");
  2975.     if(!$result) {
  2976.         echo 'Could not run Config query: ' . mysql_error();
  2977.     }
  2978.  
  2979.     $row = mysql_fetch_row($result);
  2980.  
  2981.     // Insert the default values
  2982.     if(empty($row[0]))
  2983.         mysql_query($file);
  2984.    
  2985.     fwrite(STDOUT, "\n\nAltering selected tables for mySQL InnoDB format ( if supported by your mySQL version )\n");
  2986.  
  2987.     # If supported, make selected tables in the InnoDB format
  2988.     foreach( array('UserSession', 'Users', 'Groups', 'Log_Error', 'Log_Login', 'Log_RecvMail', 'Log_SendMail', 'Log_Spam', 'Log_Virus', 'SerialConf') as $table)
  2989.     {
  2990.    
  2991.         mysql_query("alter table $table TYPE=INNODB");
  2992.    
  2993.     }
  2994.    
  2995.     //now add default group record
  2996.     $result = mysql_query("SELECT * FROM `Groups` WHERE `GroupName` = 'default'");
  2997.     if( !$result )
  2998.     {
  2999.    
  3000.         echo 'Could not run Groups query: ' . mysql_error();
  3001.    
  3002.     }
  3003.     $row = mysql_fetch_assoc($result);
  3004.    
  3005.     // Insert the default values
  3006.     if( !isset($row[0]))
  3007.     {
  3008.        
  3009.         mysql_query("INSERT INTO Groups (GroupName , GroupDescription , POP3Support , IMAPSupport , GroupwareZone , Webmail , Calendar , SharedAbook , Sync, PushSupport ) values ('default', 'Default domain group settings', '1', '1', 'System', '1', '1', '1', '1', '1' )");
  3010.        
  3011.     }
  3012.  
  3013.     return true;
  3014. }
  3015.  
  3016. function createDb($db)
  3017. {
  3018.     $db = addslashes($db);
  3019.     mysqlPing();
  3020.     return mysql_query("create database $db");
  3021. }
  3022.  
  3023. function createSqlUser($user, $pass1, $pass2, $database)
  3024. {
  3025.     if(empty($user))
  3026.     {
  3027.         fwrite(STDOUT, "\nCould not create user: username must be a non-empty string!\n\n");
  3028.         return false;
  3029.     }
  3030.  
  3031.     if($pass1!== $pass2)
  3032.     {
  3033.         fwrite(STDOUT, "\nCould not create user, passwords did not match!\n\n");
  3034.         return false;
  3035.     }
  3036.  
  3037.     mysqlPing();
  3038.  
  3039.     if(!mysql_query("grant select, insert, delete, update on $database.* to $user identified by '$pass1'"))
  3040.     {
  3041.         $error = mysql_error();
  3042.         fwrite(STDOUT, "\nCould not create user, MySQL server responded: $error\n\n");
  3043.         return false;
  3044.     }
  3045.  
  3046.     fwrite(STDOUT, "\nCreated new MySQL user $user with password $pass1\n\n");
  3047.     return true;
  3048. }
  3049.  
  3050. function mysqlPing()
  3051. {
  3052.     global $dbh, $pref;
  3053.  
  3054.     if(!mysql_ping($dbh))
  3055.     {
  3056.        mysql_close($dbh);
  3057.        $dbh = mysql_connect($pref['sql_host'], $pref['sql_user'], $pref['sql_pass']);
  3058.        mysql_select_db($pref['sql_table'], $dbh);
  3059.     }
  3060. }
  3061.  
  3062. function editIni($setting, $value='', $prepend=null)
  3063. {
  3064.  
  3065.     $phpIniPath = '';
  3066.     $phpIni = '';
  3067.  
  3068.     // find where php.ini is if need be
  3069.     if( function_exists('php_ini_loaded_file') && php_ini_loaded_file() !== false )
  3070.     {
  3071.        
  3072.         $phpIniPath = php_ini_loaded_file();
  3073.        
  3074.     }  
  3075.     else
  3076.     {
  3077.        
  3078.         $phpIniLine = strip_tags(`php -i | grep php.ini`);
  3079.         $lastSpace = strrpos( $phpIniLine, ' ');
  3080.         $phpIniPath = trim(substr( $phpIniLine, $lastSpace));
  3081.        
  3082.     }
  3083.     if( substr($phpIniPath, -7) != 'php.ini' )
  3084.     {
  3085.         if( substr( $phpIniPath, -1) != DIRECTORY_SEPARATOR )
  3086.         {
  3087.        
  3088.             $phpIniPath .= DIRECTORY_SEPARATOR;
  3089.            
  3090.         }
  3091.         $phpIniPath .= "php.ini";
  3092.        
  3093.     }
  3094.    
  3095.     if( file_exists($phpIniPath) )
  3096.     {
  3097.    
  3098.         $phpIni = file($phpIniPath);
  3099.  
  3100.     }
  3101.     else
  3102.     {
  3103.  
  3104.         return false;
  3105.  
  3106.     }  
  3107.     $altered = false;
  3108.  
  3109.     // Now look for setting to alter
  3110.     if( !empty($value) )
  3111.     {
  3112.  
  3113.         foreach ($phpIni as $num => $line)
  3114.         {
  3115.  
  3116.             // If prepend is set but we find the setting already
  3117.             // then set $altered to true
  3118.             if($prepend && trim($line) == "$setting = $value")
  3119.             {
  3120.  
  3121.                 $altered = true;
  3122.                 break;
  3123.  
  3124.             }
  3125.  
  3126.             if( !$prepend && preg_match("/^(.*?)($setting\s*=)/", $line, $m) )
  3127.             {
  3128.  
  3129.                 // we dont really want to alter examples in php.ini
  3130.                 // so we will be cautious and only alter uncommented
  3131.                 // lines or lines where the setting directly comes after
  3132.                 // a ; with no spaces
  3133.                 if(empty($m[1]) || $m[1] == ';')
  3134.                 {
  3135.  
  3136.                     $phpIni[$num] = "$setting = $value\n";
  3137.                     $altered = true;
  3138.                     break;
  3139.  
  3140.                 }
  3141.  
  3142.             }
  3143.  
  3144.         }
  3145.  
  3146.     }
  3147.  
  3148.     // If the setting was not found we will need to add it
  3149.     if( !$altered )
  3150.     {
  3151.  
  3152.         if( !empty($value) )
  3153.         {
  3154.        
  3155.             $setting .= " = $value";
  3156.            
  3157.         }
  3158.  
  3159.         foreach ($phpIni as $num => $line)
  3160.         {
  3161.  
  3162.             // I guess the easiest place to put settings is directly after
  3163.             // the opening of the PHP section ??
  3164.             if(trim($line) ==  '[PHP]')
  3165.             {
  3166.  
  3167.                 $phpIni[$num] = $line . "\n; added by Atmail\n$setting\n";
  3168.                 $altered = true;
  3169.                 break;
  3170.  
  3171.             }
  3172.  
  3173.         }
  3174.  
  3175.         if(!$altered)
  3176.         {
  3177.        
  3178.             return false;
  3179.  
  3180.         }
  3181.        
  3182.     }
  3183.  
  3184.     // Only go ahead if backup of current php.ini OK
  3185.     if( copy($phpIniPath, $phpIniPath . '.atmail.bak') )
  3186.     {
  3187.  
  3188.         // make $phpIni back into a string and get its size
  3189.         $newIni = implode('', $phpIni);
  3190.         $size = strlen($newIni);
  3191.  
  3192.         if( $fh = fopen($phpIniPath, 'w') )
  3193.         {
  3194.  
  3195.             // Make sure we write the entire string, if not
  3196.             // restore from backup and return false
  3197.             if( fwrite($fh, $newIni) !== $size )
  3198.             {
  3199.  
  3200.                 rename($phpIniPath . 'atmail.bak', $phpIniPath);
  3201.                 return false;
  3202.  
  3203.             }
  3204.  
  3205.             // no errors encountered
  3206.             fclose($fh);
  3207.             return true;
  3208.         }
  3209.  
  3210.     }
  3211.  
  3212.     // If we got here something went wrong
  3213.     return false;
  3214.  
  3215. }
  3216.  
  3217. /**
  3218.  * Function return value of selected extension
  3219.  *
  3220.  * @param string $setting
  3221.  * @return string
  3222.  */
  3223. function iniInfo($setting)
  3224. {
  3225.     // find where php.ini is if need be
  3226.     $res = `php -i | grep php.ini`;
  3227.     $res = strip_tags($res);
  3228.  
  3229.     if(preg_match('#(/.+?/php\.ini)#', $res, $m))
  3230.     {
  3231.        
  3232.         $phpIniPath = $m[1];
  3233.         if(file_exists($phpIniPath))
  3234.         {
  3235.            
  3236.             $phpIni = file($phpIniPath);
  3237.            
  3238.         }
  3239.         else
  3240.         {
  3241.        
  3242.             return false;
  3243.        
  3244.         }
  3245.    
  3246.     }
  3247.     else
  3248.     {
  3249.        
  3250.         return false;
  3251.        
  3252.     }
  3253.  
  3254.     foreach ($phpIni as $num => $line)
  3255.     {
  3256.  
  3257.         if(preg_match("/^(.*?)($setting\s*=)/", $line, $m))
  3258.         {
  3259.             return str_replace($setting.'=', '', $phpIni[$num]);
  3260.         }
  3261.  
  3262.     }
  3263.  
  3264. }
  3265.  
  3266.  
  3267. function extract_default_config_dovecot()
  3268. {
  3269.     //echo "Extracting default IMAP/POP3 configure files ...\n";
  3270.    
  3271.     // First, copy the default configure files
  3272.     system("cp /usr/local/atmail/server_source/etc/dovecot.conf /usr/local/atmail/mailserver/etc/dovecot.conf");
  3273.     system("cp /usr/local/atmail/server_source/etc/dovecot-ldap.conf /usr/local/atmail/mailserver/etc/dovecot-ldap.conf");
  3274.     system("cp /usr/local/atmail/server_source/etc/dovecot-sql.conf /usr/local/atmail/mailserver/etc/dovecot-sql.conf");
  3275.     system("cp /usr/local/atmail/server_source/etc/create-imap.sh /usr/local/atmail/mailserver/etc/create-imap.sh");
  3276.         system("cp /usr/local/atmail/server_source/etc/create-pop.sh /usr/local/atmail/mailserver/etc/create-pop.sh");
  3277.  
  3278.     system("cp /usr/local/atmail/server_source/etc/dovecot-users-sql.conf /usr/local/atmail/mailserver/etc/dovecot-users-sql.conf");
  3279.        
  3280.     // Remove the examples configure files
  3281.     if(file_exists("/usr/local/atmail/mailserver/etc/dovecot-db-example.conf"))
  3282.     unlink("/usr/local/atmail/mailserver/etc/dovecot-db-example.conf");
  3283.  
  3284.     if(file_exists("/usr/local/atmail/mailserver/etc/dovecot-example.conf"))
  3285.     unlink("/usr/local/atmail/mailserver/etc/dovecot-example.conf");
  3286.  
  3287.     if(file_exists("/usr/local/atmail/mailserver/etc/dovecot-db-example.conf"))
  3288.     unlink("/usr/local/atmail/mailserver/etc/dovecot-db-example.conf");
  3289.    
  3290.     if(file_exists("/usr/local/atmail/mailserver/etc/dovecot-sql-example.conf"))
  3291.     unlink("/usr/local/atmail/mailserver/etc/dovecot-sql-example.conf");
  3292.    
  3293. }
  3294.  
  3295. function extract_default_config_exim()
  3296. {  
  3297.     //echo "Extracting default SMTP configure files ...\n";
  3298.    
  3299.     // First, copy the default configure files
  3300.     system("cp /usr/local/atmail/server_source/etc/configure.a6 /usr/local/atmail/mailserver/configure");
  3301.     system("cp /usr/local/atmail/server_source/etc/welcome-message.html /usr/local/atmail/mailserver/etc/welcome-message.html");
  3302.    
  3303. }
  3304.  
  3305. function extract_default_config_av()
  3306. {  
  3307.     //echo "Extracting default AV configure files ...\n";
  3308.    
  3309.     // First, copy the default configure files
  3310.     system("mv /usr/local/atmail/av/etc/clamd.conf /usr/local/atmail/av/etc/clamd.conf.old");
  3311.     system("mv /usr/local/atmail/av/etc/freshclam.conf /usr/local/atmail/av/etc/freshclam.conf.old");
  3312.     system("cp /usr/local/atmail/server_source/etc/clamd.conf /usr/local/atmail/av/etc/clamd.conf");
  3313.     system("cp /usr/local/atmail/server_source/etc/freshclam.conf /usr/local/atmail/av/etc/freshclam.conf");
  3314.  
  3315. }
  3316.  
  3317. function extract_default_config_spamassassin()
  3318. {  
  3319.     // First, copy the default configure files
  3320.     system("cp /usr/local/atmail/server_source/etc/sa-modules.pre /usr/local/atmail/spamassassin/etc/sa-modules.pre ");
  3321.     system("cp /usr/local/atmail/server_source/etc/atmail.cf /usr/local/atmail/spamassassin/etc/atmail.cf");
  3322.     system("cp /usr/local/atmail/server_source/etc/local.cf /usr/local/atmail/spamassassin/etc/local.cf");
  3323.     system("cp /usr/local/atmail/server_source/etc/sqlsettings.cf /usr/local/atmail/spamassassin/etc/sqlsettings.cf");
  3324.  
  3325.     // Add the Bayes directory
  3326.     system("mkdir /usr/local/atmail/spamassassin/bayes");
  3327.     system("chown atmail /usr/local/atmail/spamassassin/bayes");
  3328. }
  3329.  
  3330. /**
  3331. * Function write the $pref into the Config database
  3332. *
  3333. **/
  3334. function writeconf()
  3335. {
  3336.    
  3337.     global $pref, $exim, $plugins, $defaults, $dovecot;
  3338.    
  3339.     require_once 'Zend/Loader/Autoloader.php';
  3340.     $loader = Zend_Loader_Autoloader::getInstance();
  3341.     //$loader->registerNamespace('App_'); //for model namespacing
  3342.     $loader->setFallbackAutoloader(true);
  3343.     $loader->suppressNotFoundWarnings(false);
  3344.  
  3345.     //Load general functions
  3346.     //Zend_Loader::loadFile('Atmail/General.php', null, true);
  3347.     //Zend_Loader::loadFile('Atmail/Exception.php', null, true);
  3348.    
  3349.     // Get database configuration  
  3350.     $dbConfig = new Zend_Config_Ini('webmail/config/dbconfig.ini', 'production');
  3351.     Zend_Registry::set('dbConfig', $dbConfig);
  3352.     $dbAdapter = Zend_Db::Factory($dbConfig->database);
  3353.     $dbAdapter->query("SET NAMES 'utf8'");
  3354.     Zend_Db_Table::setDefaultAdapter($dbAdapter);
  3355.     Zend_Registry::set('dbAdapter', $dbAdapter);
  3356.  
  3357.    
  3358.     // Set up log
  3359.     $logPath = 'webmail/log' . DIRECTORY_SEPARATOR . 'atmail.log';
  3360.     if( !file_exists($logPath)) {
  3361.         touch($logPath);
  3362.     }
  3363.  
  3364.     $logWriter = new Zend_Log_Writer_Stream($logPath);
  3365.     $log = new Atmail_Log($logWriter);
  3366.     $log->info('');
  3367.     $log->info('------------------------------');
  3368.     $log->info('Installation completed at: ' . time());
  3369.     Zend_Registry::set('log', $log);
  3370.    
  3371.     //Get main configuration from database
  3372.     $config = new Atmail_Config_Mysql($dbConfig, true);
  3373.     Zend_Registry::set('config', $config);
  3374.    
  3375.     // Now save all collected data
  3376.     require_once 'application/models/config.php';
  3377.     require_once 'application/models/dbTables.php';
  3378.    
  3379.     config::save('global', $pref);
  3380.     config::save('exim', $exim);
  3381.     config::save('dovecot', $dovecot);
  3382.     config::save('plugins', $plugins);
  3383.     config::save('defaultUserSettings', $defaults);
  3384.    
  3385.     config::publishServerConfigFiles('exim');
  3386.     config::publishDbConfigChangesToServerConfigFiles($pref);
  3387.    
  3388. }
  3389.  
  3390. /**
  3391.  * Add a domain to the SQL table
  3392.  */
  3393.  
  3394. function write_atmaildomains($hostname)
  3395. {
  3396.     global $pref, $dbh;
  3397.  
  3398.     mysqlPing();
  3399.  
  3400.     mysql_select_db($pref['sql_table'], $dbh);
  3401.     $hostname = mysql_escape_string($hostname);
  3402.  
  3403.     if(false === $res = mysql_query("select count(*) from Domains where Hostname = '$hostname'", $dbh))
  3404.         exit("Error occured: " . mysql_error());
  3405.  
  3406.     $row = mysql_fetch_row($res);
  3407.     if($row[0] == 0)
  3408.     {
  3409.         if(!mysql_query("insert into Domains (Hostname) VALUES('$hostname')", $dbh))
  3410.             exit("could not add domains: " . mysql_error());
  3411.     }
  3412.  
  3413. }
  3414.  
  3415. /**
  3416.  * Add an email alias
  3417.  */
  3418.  
  3419. function addaliases($from, $to=null)
  3420. {
  3421.     global $pref;
  3422.  
  3423.     mysqlPing();
  3424.  
  3425.     $from = mysql_escape_string($from);
  3426.     $to = mysql_escape_string($pref['admin_email']);
  3427.  
  3428.     $res = mysql_query("select count(*) from MailAliases where AliasTo = '$to' and AliasName = '$from'");
  3429.     $row = mysql_fetch_row($res);
  3430.  
  3431.     // First, check if the alias already exists in the database
  3432.     if($row[0] == 0)
  3433.         mysql_query("INSERT INTO MailAliases (AliasTo, AliasName, DateCreate) VALUES( '$to', '$from', NOW() )");
  3434.  
  3435. }
  3436.  
  3437. /**
  3438.  * Specify the admin password
  3439. */
  3440.  
  3441. function webadmin_pass()
  3442. {
  3443.     global $args;
  3444.    
  3445.     // Specify the new password
  3446.     if($args['adminpass'] == '')
  3447.         $pass = prompt("Specify admin password: ");
  3448.     else
  3449.         $pass = $args['adminpass'];
  3450.  
  3451.     // Try again if no password
  3452.     if( !$pass )
  3453.         webadmin_pass();
  3454.  
  3455.     $pass = trim($pass);
  3456.     $passEscaped = md5($pass);
  3457.    
  3458.     $res = mysql_query("select count(*) from AdminUsers where Username='admin'");
  3459.     $row = mysql_fetch_row($res);
  3460.  
  3461.     // First, check if the alias already exists in the database
  3462.     if($row[0] == 0)
  3463.         mysql_query("INSERT INTO AdminUsers (Username, Password, UMasterAdmin) VALUES( 'admin', '$passEscaped', '1' )");
  3464.     else
  3465.         mysql_query("UPDATE AdminUsers set Password='$passEscaped' where Username='admin'");
  3466.    
  3467. echo <<<EOF
  3468.  
  3469. For access rights to the WebAdmin use the following details:
  3470.  
  3471. Username: admin
  3472. Password: $pass
  3473. URL: http://localhost/mail/index.php/admin/
  3474.  
  3475. Or click the Webadmin link on the Atmail login page
  3476.  
  3477. EOF;
  3478.    
  3479. }
  3480.  
  3481. /**
  3482.  * Install a module
  3483.  */
  3484. function install_module($name, $version='')
  3485. {
  3486.     global $pref;
  3487.     $perlmod = $name;
  3488.     $perlmod = str_replace('-', '::', $perlmod);
  3489.  
  3490.     if($version)
  3491.     $perlmod = $perlmod . ' ' . $version;
  3492.  
  3493.     // Check we are installed already, if so, skip
  3494.     system("perl -e 'use $perlmod' > /dev/null 2>&1", $return);
  3495.     if(!$return)
  3496.         return;
  3497.  
  3498.     fwrite(STDOUT, "\nInstalling module $name ...\n");
  3499.  
  3500.     // Just in case ...
  3501.     system("cd /usr/local/atmail/server_source/perlmodules/$name ; make clean >/dev/null 2>&1");
  3502.  
  3503.     $extra = '';
  3504.  
  3505.     if($name == 'Net-DNS') {
  3506.         $extra = '--no-online-tests';
  3507.     } else {
  3508.         if($name == 'LWP')
  3509.         $extra = '-n';
  3510.     }
  3511.  
  3512.     if($name == 'sa-atmail')
  3513.     {
  3514.         install_module('Digest-SHA');
  3515.         install_module('Digest-SHA1');
  3516.         install_module('LWP');
  3517.         install_module('IP-Country');
  3518.  
  3519.         //install_module('Time-HiRes'); // Seem to compile/break under CentOS 4.x
  3520.         install_module('Digest-HMAC');
  3521.         install_module('Net-IP');
  3522.         install_module('Net-DNS');
  3523.         install_module('IO-Zlib', '1.04');
  3524.         install_module('Archive-Tar');
  3525.  
  3526.         // Install the SPF package
  3527.         install_module("Sys-Hostname-Long");
  3528.         install_module("Net-CIDR");
  3529.         install_module("Module-Build");
  3530.         install_module("Mail-SPF");
  3531.         install_module("Mail-DKIM");
  3532.  
  3533.         // Check DBD::mysql and DBI are setup, get return codes, shell outputs to STDERR so we can't tell if successful
  3534.         install_module("DBI");
  3535.         install_module('DBD-mysql');
  3536.  
  3537.         if(strpos(strtolower(PHP_OS), 'freebsd') !== false) {
  3538.             system("export LANG=C ; cd /usr/local/atmail/server_source/perlmodules/sa-atmail ;perl Makefile.PL CONTACT_ADDRESS={$pref['admin_email']} PREFIX=/usr/local/atmail/spamassassin/ CONFDIR=/usr/local/atmail/spamassassin/etc/ DATADIR=/usr/local/atmail/spamassassin/etc/ ; make ; make install");
  3539.         } else {
  3540.             system("export LANG=C ; cd /usr/local/atmail/server_source/perlmodules/$name ; perl Makefile.PL INSTALLDIRS=vendor CONTACT_ADDRESS={$pref['admin_email']} PREFIX=/usr/local/atmail/spamassassin/ CONFDIR=/usr/local/atmail/spamassassin/etc/ DATADIR=/usr/local/atmail/spamassassin/etc/; make ; make install");
  3541.         }
  3542.        
  3543.         extract_default_config_spamassassin();
  3544.        
  3545.     }
  3546.     else
  3547.         system("export LANG=C ; cd /usr/local/atmail/server_source/perlmodules/$name ; perl Makefile.PL $extra ; make ; make install");
  3548.  
  3549.     if($name == "Mail-SPF-Query")   {
  3550.         system('perl -e "use DBD::mysql"', $return);
  3551.         if($return)
  3552.         $pref['filter_spf_support'] = '0';
  3553.         else
  3554.         $pref['filter_spf_support'] = '1';
  3555.     }
  3556.     // Check the library was successfully installed
  3557.     else if($name == "DBD-mysql")
  3558.     {
  3559.         system('perl -e "use DBD::mysql"', $return);
  3560.         if($return)
  3561.         {
  3562. $msg = <<<EOF
  3563.  
  3564. ** The perl DBD::Mysql module for connecting to the SQL database was not
  3565. correctly installed.
  3566.  
  3567. This module is needed by SpamAssassin.
  3568.  
  3569. Verify you have a valid installation of MySQL on your server. Check you have
  3570. the MySQL development librarys available ( the mysql.h , and libmysqlclient
  3571. library ) . These can be freely obtained from http://mysql.com/ if missing on
  3572. your system. Or use the package manager for your OS to install the mysql-devel
  3573. package.
  3574.  
  3575. Before proceeding with the installation of the Anti-Spam plugin your MySQL
  3576. installation must be updated with the development librarys.
  3577.  
  3578. EOF;
  3579.  
  3580.             fwrite(STDOUT, $msg);
  3581.         }
  3582.     }
  3583. }
  3584.  
  3585. if( !function_exists('sys_get_temp_dir') )
  3586. {
  3587.     // Based on http://www.phpit.net/
  3588.     // article/creating-zip-tar-archives-dynamically-php/2/
  3589.     function sys_get_temp_dir()
  3590.     {
  3591.         // Try to get from environment variable
  3592.         if( !empty($_ENV['TMP']) )
  3593.         {
  3594.  
  3595.             return realpath( $_ENV['TMP'] );
  3596.  
  3597.         }
  3598.         else if( !empty($_ENV['TMPDIR']) )
  3599.         {
  3600.  
  3601.             return realpath( $_ENV['TMPDIR'] );
  3602.  
  3603.         }
  3604.         else if( !empty($_ENV['TEMP']) )
  3605.         {
  3606.  
  3607.             return realpath( $_ENV['TEMP'] );
  3608.  
  3609.         }
  3610.  
  3611.         // Detect by creating a temporary file
  3612.         else
  3613.         {
  3614.             // Try to use system's temporary directory
  3615.             // as random name shouldn't exist
  3616.             $temp_file = tempnam( md5(uniqid(rand(), TRUE)), '' );
  3617.             if( $temp_file )
  3618.             {
  3619.                 $temp_dir = realpath( dirname($temp_file) );
  3620.                 unlink( $temp_file );
  3621.                 return $temp_dir;
  3622.             }
  3623.             else
  3624.             {
  3625.                 return FALSE;
  3626.             }
  3627.         }
  3628.     }
  3629. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement