ftimme
2011-09-28 ca0b77f95a10f7d81714667557d4946ce5b50a9e
commit | author | age
532ae5 1 <?php
L 2
3 /*
4 Copyright (c) 2007-2010, Till Brehm, projektfarm Gmbh
5 All rights reserved.
6
7 Redistribution and use in source and binary forms, with or without modification,
8 are permitted provided that the following conditions are met:
9
10     * Redistributions of source code must retain the above copyright notice,
11       this list of conditions and the following disclaimer.
12     * Redistributions in binary form must reproduce the above copyright notice,
13       this list of conditions and the following disclaimer in the documentation
14       and/or other materials provided with the distribution.
15     * Neither the name of ISPConfig nor the names of its contributors
16       may be used to endorse or promote products derived from this software without
17       specific prior written permission.
18
19 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
20 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
23 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
24 BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
26 OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
27 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
28 EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30
31 class installer_base {
32
33     var $wb = array();
34     var $language = 'en';
35     var $db;
36     public $conf;
37     public $install_ispconfig_interface = true;
38     public $is_update = false; // true if it is an update, falsi if it is a new install
39
40
41     public function __construct() {
42         global $conf; //TODO: maybe $conf  should be passed to constructor
43         //$this->conf = $conf;
44     }
45
46     //: TODO  Implement the translation function and language files for the installer.
47     public function lng($text) {
48         return $text;
49     }
50
51     public function error($msg) {
52         die('ERROR: '.$msg."\n");
53     }
54
55     public function warning($msg) {
56         echo('WARNING: '.$msg."\n");
57     }
58     
59     public function simple_query($query, $answers, $default) {
60         $finished = false;
61         do {
62             $answers_str = implode(',', $answers);
63             swrite($this->lng($query).' ('.$answers_str.') ['.$default.']: ');
64             $input = sread();
65
66             //* Stop the installation
67             if($input == 'quit') {
68                 swriteln($this->lng("Installation terminated by user.\n"));
69                 die();
70             }
71
72             //* Select the default
73             if($input == '') {
74                 $answer = $default;
75                 $finished = true;
76             }
77
78             //* Set answer id valid
79             if(in_array($input, $answers)) {
80                 $answer = $input;
81                 $finished = true;
82             }
83
84         } while ($finished == false);
85         swriteln();
86         return $answer;
87     }
88
89     public function free_query($query,$default) {
90         swrite($this->lng($query).' ['.$default.']: ');
91         $input = sread();
92
93         //* Stop the installation
94         if($input == 'quit') {
95             swriteln($this->lng("Installation terminated by user.\n"));
96             die();
97         }
98
99         $answer =  ($input == '') ? $default : $input;
100         swriteln();
101         return $answer;
102     }
103
104     /*
105     // TODO: this function is not used atmo I think - pedro
106     function request_language(){
107         
108         swriteln(lng('Enter your language'));
109         swriteln(lng('de, en'));
110         
111     }
112     */
113
114     //** Detect installed applications
115     public function find_installed_apps() {
116         global $conf;
117
118         if(is_installed('mysql') || is_installed('mysqld')) $conf['mysql']['installed'] = true;
119         if(is_installed('postfix')) $conf['postfix']['installed'] = true;
120         if(is_installed('mailman')) $conf['mailman']['installed'] = true;
e09a27 121         if(is_installed('apache') || is_installed('apache2') || is_installed('httpd') || is_installed('httpd2')) $conf['apache']['installed'] = true;
532ae5 122         if(is_installed('getmail')) $conf['getmail']['installed'] = true;
1ca823 123         if(is_installed('courierlogger')) $conf['courier']['installed'] = true;
532ae5 124         if(is_installed('dovecot')) $conf['dovecot']['installed'] = true;
74d2dc 125         if(is_installed('saslauthd')) $conf['saslauthd']['installed'] = true;
ac28b5 126         if(is_installed('amavisd-new') || is_installed('amavisd')) $conf['amavis']['installed'] = true;
532ae5 127         if(is_installed('clamdscan')) $conf['clamav']['installed'] = true;
L 128         if(is_installed('pure-ftpd') || is_installed('pure-ftpd-wrapper')) $conf['pureftpd']['installed'] = true;
129         if(is_installed('mydns') || is_installed('mydns-ng')) $conf['mydns']['installed'] = true;
130         if(is_installed('jk_chrootsh')) $conf['jailkit']['installed'] = true;
131         if(is_installed('pdns_server') || is_installed('pdns_control')) $conf['powerdns']['installed'] = true;
132         if(is_installed('named') || is_installed('bind') || is_installed('bind9')) $conf['bind']['installed'] = true;
80e3c9 133         if(is_installed('squid')) $conf['squid']['installed'] = true;
T 134         if(is_installed('nginx')) $conf['nginx']['installed'] = true;
c91bdc 135         // if(is_installed('iptables') && is_installed('ufw')) $conf['ufw']['installed'] = true;
5eb43f 136         if(is_installed('fail2ban-server')) $conf['fail2ban']['installed'] = true;
522ef8 137         if(is_installed('vzctl')) $conf['openvz']['installed'] = true;
80e3c9 138         if(is_dir("/etc/Bastille")) $conf['bastille']['installed'] = true;
T 139         
d7cfd7 140         if ($conf['services']['web'] && (($conf['apache']['installed'] && is_file($conf['apache']["vhost_conf_enabled_dir"]."/000-ispconfig.vhost")) || ($conf['nginx']['installed'] && is_file($conf['nginx']["vhost_conf_enabled_dir"]."/000-ispconfig.vhost")))) $this->ispconfig_interface_installed = true;
532ae5 141     }
L 142
143     /** Create the database for ISPConfig */
144     public function configure_database() {
145         global $conf;
146
147         //** Create the database
148         if(!$this->db->query('CREATE DATABASE IF NOT EXISTS '.$conf['mysql']['database'].' DEFAULT CHARACTER SET '.$conf['mysql']['charset'])) {
149             $this->error('Unable to create MySQL database: '.$conf['mysql']['database'].'.');
150         }
151
152         //* Set the database name in the DB library
153         $this->db->dbName = $conf['mysql']['database'];
154
155         //* Load the database dump into the database, if database contains no tables
156         $db_tables = $this->db->getTables();
157         if(count($db_tables) > 0) {
158             $this->error('Stopped: Database already contains some tables.');
159         } else {
160             if($conf['mysql']['admin_password'] == '') {
161                 caselog("mysql --default-character-set=".$conf['mysql']['charset']." -h '".$conf['mysql']['host']."' -u '".$conf['mysql']['admin_user']."' '".$conf['mysql']['database']."' < '".ISPC_INSTALL_ROOT."/install/sql/ispconfig3.sql' &> /dev/null",
162                         __FILE__, __LINE__, 'read in ispconfig3.sql', 'could not read in ispconfig3.sql');
163             } else {
164                 caselog("mysql --default-character-set=".$conf['mysql']['charset']." -h '".$conf['mysql']['host']."' -u '".$conf['mysql']['admin_user']."' -p'".$conf['mysql']['admin_password']."' '".$conf['mysql']['database']."' < '".ISPC_INSTALL_ROOT."/install/sql/ispconfig3.sql' &> /dev/null",
165                         __FILE__, __LINE__, 'read in ispconfig3.sql', 'could not read in ispconfig3.sql');
166             }
167             $db_tables = $this->db->getTables();
168             if(count($db_tables) == 0) {
169                 $this->error('Unable to load SQL-Dump into database table.');
170             }
171
172             //* Load system.ini into the sys_ini table
173             $system_ini = $this->db->quote(rf('tpl/system.ini.master'));
174             $this->db->query("UPDATE sys_ini SET config = '$system_ini' WHERE sysini_id = 1");
175
176         }
177     }
178
179     //** Create the server record in the database
180     public function add_database_server_record() {
181
182         global $conf;
183
184         if($conf['mysql']['host'] == 'localhost') {
185             $from_host = 'localhost';
186         } else {
187             $from_host = $conf['hostname'];
188         }
189
190         // Delete ISPConfig user in the local database, in case that it exists
191         $this->db->query("DELETE FROM mysql.user WHERE User = '".$conf['mysql']['ispconfig_user']."' AND Host = '".$from_host."';");
192         $this->db->query("DELETE FROM mysql.db WHERE Db = '".$conf['mysql']['database']."' AND Host = '".$from_host."';");
193         $this->db->query('FLUSH PRIVILEGES;');
194
195         //* Create the ISPConfig database user in the local database
196         $query = 'GRANT SELECT, INSERT, UPDATE, DELETE ON '.$conf['mysql']['database'].".* "
197                 ."TO '".$conf['mysql']['ispconfig_user']."'@'".$from_host."' "
198                 ."IDENTIFIED BY '".$conf['mysql']['ispconfig_password']."';";
199         if(!$this->db->query($query)) {
200             $this->error('Unable to create database user: '.$conf['mysql']['ispconfig_user'].' Error: '.$this->db->errorMessage);
201         }
202
203         //* Reload database privelages
204         $this->db->query('FLUSH PRIVILEGES;');
205
206         //* Set the database name in the DB library
207         $this->db->dbName = $conf['mysql']['database'];
208
209         $tpl_ini_array = ini_to_array(rf('tpl/server.ini.master'));
210
211         //* Update further distribution specific parameters for server config here
212         //* HINT: Every line added here has to be added in update.lib.php too!!
213         $tpl_ini_array['web']['vhost_conf_dir'] = $conf['apache']['vhost_conf_dir'];
214         $tpl_ini_array['web']['vhost_conf_enabled_dir'] = $conf['apache']['vhost_conf_enabled_dir'];
215         $tpl_ini_array['jailkit']['jailkit_chroot_app_programs'] = $conf['jailkit']['jailkit_chroot_app_programs'];
216         $tpl_ini_array['fastcgi']['fastcgi_phpini_path'] = $conf['fastcgi']['fastcgi_phpini_path'];
217         $tpl_ini_array['fastcgi']['fastcgi_starter_path'] = $conf['fastcgi']['fastcgi_starter_path'];
218         $tpl_ini_array['server']['hostname'] = $conf['hostname'];
219         $tpl_ini_array['server']['ip_address'] = @gethostbyname($conf['hostname']);
220         $tpl_ini_array['web']['website_basedir'] = $conf['web']['website_basedir'];
221         $tpl_ini_array['web']['website_path'] = $conf['web']['website_path'];
222         $tpl_ini_array['web']['website_symlinks'] = $conf['web']['website_symlinks'];
223         $tpl_ini_array['cron']['crontab_dir'] = $conf['cron']['crontab_dir'];
224         $tpl_ini_array['web']['security_level'] = 20;
225         $tpl_ini_array['web']['user'] = $conf['apache']['user'];
226         $tpl_ini_array['web']['group'] = $conf['apache']['group'];
227         $tpl_ini_array['web']['php_ini_path_apache'] = $conf['apache']['php_ini_path_apache'];
228         $tpl_ini_array['web']['php_ini_path_cgi'] = $conf['apache']['php_ini_path_cgi'];
229         $tpl_ini_array['mail']['pop3_imap_daemon'] = ($conf['dovecot']['installed'] == true)?'dovecot':'courier';
230         $tpl_ini_array['mail']['mail_filter_syntax'] = ($conf['dovecot']['installed'] == true)?'sieve':'maildrop';
231         $tpl_ini_array['dns']['bind_user'] = $conf['bind']['bind_user'];
232         $tpl_ini_array['dns']['bind_group'] = $conf['bind']['bind_group'];
233         $tpl_ini_array['dns']['bind_zonefiles_dir'] = $conf['bind']['bind_zonefiles_dir'];
234         $tpl_ini_array['dns']['named_conf_path'] = $conf['bind']['named_conf_path'];
235         $tpl_ini_array['dns']['named_conf_local_path'] = $conf['bind']['named_conf_local_path'];
236         
dba68f 237         $tpl_ini_array['web']['nginx_vhost_conf_dir'] = $conf['nginx']['vhost_conf_dir'];
T 238         $tpl_ini_array['web']['nginx_vhost_conf_enabled_dir'] = $conf['nginx']['vhost_conf_enabled_dir'];
239         $tpl_ini_array['web']['nginx_user'] = $conf['nginx']['user'];
240         $tpl_ini_array['web']['nginx_group'] = $conf['nginx']['group'];
241         $tpl_ini_array['web']['nginx_cgi_socket'] = $conf['nginx']['cgi_socket'];
242         $tpl_ini_array['web']['php_fpm_init_script'] = $conf['nginx']['php_fpm_init_script'];
243         $tpl_ini_array['web']['php_fpm_ini_path'] = $conf['nginx']['php_fpm_ini_path'];
244         $tpl_ini_array['web']['php_fpm_pool_dir'] = $conf['nginx']['php_fpm_pool_dir'];
245         $tpl_ini_array['web']['php_fpm_start_port'] = $conf['nginx']['php_fpm_start_port'];
246         $tpl_ini_array['web']['php_fpm_socket_dir'] = $conf['nginx']['php_fpm_socket_dir'];
247         
80e3c9 248         if ($conf['nginx']['installed'] == true) {
4ffb51 249             $tpl_ini_array['web']['server_type'] = 'nginx';
F 250             $tpl_ini_array['global']['webserver'] = 'nginx';
80e3c9 251         }
T 252         
532ae5 253         if (array_key_exists('awstats', $conf)) {
L 254             foreach ($conf['awstats'] as $aw_sett => $aw_value) {
255                 $tpl_ini_array['web']['awstats_'.$aw_sett] = $aw_value;
256             }
257         }
258
259         $server_ini_content = array_to_ini($tpl_ini_array);
260         $server_ini_content = mysql_real_escape_string($server_ini_content);
261
262         $mail_server_enabled = ($conf['services']['mail'])?1:0;
263         $web_server_enabled = ($conf['services']['web'])?1:0;
264         $dns_server_enabled = ($conf['services']['dns'])?1:0;
265         $file_server_enabled = ($conf['services']['file'])?1:0;
266         $db_server_enabled = ($conf['services']['db'])?1:0;
522ef8 267         $vserver_server_enabled = ($conf['openvz']['installed'])?1:0;
c91bdc 268         $proxy_server_enabled = (isset($conf['services']['proxy']) && $conf['services']['proxy'])?1:0;
T 269         $firewall_server_enabled = (isset($conf['services']['firewall']) && $conf['services']['firewall'])?1:0;
532ae5 270         
L 271         //** Get the database version number based on the patchfiles
272         $found = true;
273         $current_db_version = 1;
274         while($found == true) {
275             $next_db_version = intval($current_db_version + 1);
276             $patch_filename = realpath(dirname(__FILE__).'/../').'/sql/incremental/upd_'.str_pad($next_db_version, 4, '0', STR_PAD_LEFT).'.sql';
277             if(is_file($patch_filename)) {
278                 $current_db_version = $next_db_version;
279             } else {
280                 $found = false;
281             }
282         }
283         $current_db_version = intval($current_db_version);
284
285
286         if($conf['mysql']['master_slave_setup'] == 'y') {
287
288             //* Insert the server record in master DB
80e3c9 289             $sql = "INSERT INTO `server` (`sys_userid`, `sys_groupid`, `sys_perm_user`, `sys_perm_group`, `sys_perm_other`, `server_name`, `mail_server`, `web_server`, `dns_server`, `file_server`, `db_server`, `vserver_server`, `config`, `updated`, `active`, `dbversion`,`firewall_server`,`proxy_server`) VALUES (1, 1, 'riud', 'riud', 'r', '".$conf['hostname']."', '$mail_server_enabled', '$web_server_enabled', '$dns_server_enabled', '$file_server_enabled', '$db_server_enabled', '$vserver_server_enabled', '$server_ini_content', 0, 1, $current_db_version, $proxy_server_enabled, $firewall_server_enabled);";
532ae5 290             $this->dbmaster->query($sql);
L 291             $conf['server_id'] = $this->dbmaster->insertID();
292             $conf['server_id'] = $conf['server_id'];
293
294             //* Insert the same record in the local DB
80e3c9 295             $sql = "INSERT INTO `server` (`server_id`, `sys_userid`, `sys_groupid`, `sys_perm_user`, `sys_perm_group`, `sys_perm_other`, `server_name`, `mail_server`, `web_server`, `dns_server`, `file_server`, `db_server`, `vserver_server`, `config`, `updated`, `active`, `dbversion`,`firewall_server`,`proxy_server`) VALUES ('".$conf['server_id']."',1, 1, 'riud', 'riud', 'r', '".$conf['hostname']."', '$mail_server_enabled', '$web_server_enabled', '$dns_server_enabled', '$file_server_enabled', '$db_server_enabled', '$vserver_server_enabled', '$server_ini_content', 0, 1, $current_db_version, $proxy_server_enabled, $firewall_server_enabled);";
532ae5 296             $this->db->query($sql);
L 297
298             //* username for the ispconfig user
299             $conf['mysql']['master_ispconfig_user'] = 'ispcsrv'.$conf['server_id'];
300
301             $this->grant_master_database_rights();
302
303         } else {
304             //* Insert the server, if its not a mster / slave setup
80e3c9 305             $sql = "INSERT INTO `server` (`sys_userid`, `sys_groupid`, `sys_perm_user`, `sys_perm_group`, `sys_perm_other`, `server_name`, `mail_server`, `web_server`, `dns_server`, `file_server`, `db_server`, `vserver_server`, `config`, `updated`, `active`, `dbversion`,`firewall_server`,`proxy_server`) VALUES (1, 1, 'riud', 'riud', 'r', '".$conf['hostname']."', '$mail_server_enabled', '$web_server_enabled', '$dns_server_enabled', '$file_server_enabled', '$db_server_enabled', '$vserver_server_enabled', '$server_ini_content', 0, 1, $current_db_version, $proxy_server_enabled, $firewall_server_enabled);";
532ae5 306             $this->db->query($sql);
L 307             $conf['server_id'] = $this->db->insertID();
308             $conf['server_id'] = $conf['server_id'];
309         }
310
311
312     }
313
100d41 314     public function grant_master_database_rights($verbose = false) {
532ae5 315         global $conf;
L 316
317         /*
318          * The following code is a little bit tricky:
319          * * If we HAVE a master-slave - Setup then the client has to grant the rights for himself
320          *   at the master.
321          * * If we DO NOT have a master-slave - Setup then we have two possibilities
322          *   1) it is a single server
323          *   2) it is the MASTER of n clients
324         */
325         $hosts = array();
326         
327         if($conf['mysql']['master_slave_setup'] == 'y') {
328             /*
329              * it is a master-slave - Setup so the slave has to grant its rights in the master
330              * database
331              */
332
333             //* insert the ispconfig user in the remote server
334             $from_host = $conf['hostname'];
335             $from_ip = gethostbyname($conf['hostname']);
336             
337             $hosts[$from_host]['user'] = $conf['mysql']['master_ispconfig_user'];
338             $hosts[$from_host]['db'] = $conf['mysql']['master_database'];
339             $hosts[$from_host]['pwd'] = $conf['mysql']['master_ispconfig_password'];
340
341             $hosts[$from_ip]['user'] = $conf['mysql']['master_ispconfig_user'];
342             $hosts[$from_ip]['db'] = $conf['mysql']['master_database'];
343             $hosts[$from_ip]['pwd'] = $conf['mysql']['master_ispconfig_password'];
344         } else{
345             /*
346              * it is NOT a master-slave - Setup so we have to find out all clients and their
347              * host
348              */
349             $query = "SELECT Host, User FROM mysql.user WHERE User like 'ispcsrv%' ORDER BY User, Host";
350             $data = $this->dbmaster->queryAllRecords($query);
351             if($data === false) {
352                 $this->error('Unable to get the user rights: '.$value['db'].' Error: '.$this->dbmaster->errorMessage);
353             }
354             foreach ($data as $item){
355                 $hosts[$item['Host']]['user'] = $item['User'];
356                 $hosts[$item['Host']]['db'] = $conf['mysql']['master_database'];
357                 $hosts[$item['Host']]['pwd'] = ''; // the user already exists, so we need no pwd!
358             }
359         }
360         
361         if(count($hosts) > 0) {
362         foreach($hosts as $host => $value) {
363             /*
364              * If a pwd exists, this means, we have to add the new user (and his pwd).
365              * if not, the user already exists and we do not need the pwd
366              */
367             if ($value['pwd'] != ''){
368                 $query = "CREATE USER '".$value['user']."'@'".$host."' IDENTIFIED BY '" . $value['pwd'] . "'";
100d41 369                 if ($verbose){
V 370                     echo "\n\n" . $query ."\n";
371                 }
532ae5 372                 $this->dbmaster->query($query); // ignore the error
L 373             }
374
375             /*
376              *  Try to delete all rights of the user in case that it exists.
377              *  In Case that it will not exist, do nothing (ignore the error!)
378              */
379             $query = "REVOKE ALL PRIVILEGES, GRANT OPTION FROM '".$value['user']."'@'".$host."' ";
100d41 380             if ($verbose){
V 381                     echo "\n\n" . $query ."\n";
382             }
532ae5 383             $this->dbmaster->query($query); // ignore the error
L 384
385             //* Create the ISPConfig database user in the remote database
386             $query = "GRANT SELECT ON ".$value['db'].".`server` TO '".$value['user']."'@'".$host."' ";
100d41 387             if ($verbose){
V 388                 echo $query ."\n";
389             }
532ae5 390             if(!$this->dbmaster->query($query)) {
L 391                 $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
392             }
393
394             $query = "GRANT SELECT, INSERT ON ".$value['db'].".`sys_log` TO '".$value['user']."'@'".$host."' ";
100d41 395             if ($verbose){
V 396                 echo $query ."\n";
397             }
532ae5 398             if(!$this->dbmaster->query($query)) {
L 399                 $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
400             }
401
402             $query = "GRANT SELECT, UPDATE(`status`) ON ".$value['db'].".`sys_datalog` TO '".$value['user']."'@'".$host."' ";
100d41 403             if ($verbose){
V 404                 echo $query ."\n";
405             }
532ae5 406             if(!$this->dbmaster->query($query)) {
L 407                 $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
408             }
409
410             $query = "GRANT SELECT, UPDATE(`status`) ON ".$value['db'].".`software_update_inst` TO '".$value['user']."'@'".$host."' ";
100d41 411             if ($verbose){
V 412                 echo $query ."\n";
413             }
532ae5 414             if(!$this->dbmaster->query($query)) {
L 415                 $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
416             }
417
418             $query = "GRANT SELECT, UPDATE(`updated`) ON ".$value['db'].".`server` TO '".$value['user']."'@'".$host."' ";
100d41 419             if ($verbose){
V 420                 echo $query ."\n";
421             }
532ae5 422             if(!$this->dbmaster->query($query)) {
L 423                 $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
424             }
425
426             $query = "GRANT SELECT, UPDATE (`ssl_request`, `ssl_cert`, `ssl_action`) ON ".$value['db'].".`web_domain` TO '".$value['user']."'@'".$host."' ";
100d41 427             if ($verbose){
V 428                 echo $query ."\n";
429             }
532ae5 430             if(!$this->dbmaster->query($query)) {
L 431                 $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
432             }
433
434             $query = "GRANT SELECT ON ".$value['db'].".`sys_group` TO '".$value['user']."'@'".$host."' ";
100d41 435             if ($verbose){
V 436                 echo $query ."\n";
437             }
532ae5 438             if(!$this->dbmaster->query($query)) {
L 439                 $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
440             }
441
442             $query = "GRANT SELECT, UPDATE (`action_state`, `response`) ON ".$value['db'].".`sys_remoteaction` TO '".$value['user']."'@'".$host."' ";
100d41 443             if ($verbose){
V 444                 echo $query ."\n";
445             }
532ae5 446             if(!$this->dbmaster->query($query)) {
L 447                 $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
448             }
449
450             $query = "GRANT SELECT, INSERT , DELETE ON ".$value['db'].".`monitor_data` TO '".$value['user']."'@'".$host."' ";
100d41 451             if ($verbose){
V 452                 echo $query ."\n";
453             }
532ae5 454             if(!$this->dbmaster->query($query)) {
L 455                 $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
456             }
457
458             $query = "GRANT SELECT, INSERT, UPDATE ON ".$value['db'].".`mail_traffic` TO '".$value['user']."'@'".$host."' ";
100d41 459             if ($verbose){
V 460                 echo $query ."\n";
461             }
532ae5 462             if(!$this->dbmaster->query($query)) {
L 463                 $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
464             }
465
466             $query = "GRANT SELECT, INSERT, UPDATE ON ".$value['db'].".`web_traffic` TO '".$value['user']."'@'".$host."' ";
100d41 467             if ($verbose){
V 468                 echo $query ."\n";
469             }
532ae5 470             if(!$this->dbmaster->query($query)) {
L 471                 $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
472             }
473         }
474
475         /*
476          * It is all done. Relod the rights...
477          */
478         $this->dbmaster->query('FLUSH PRIVILEGES;');
479         }
480
481     }
482
483     //** writes postfix configuration files
484     public function process_postfix_config($configfile) {
485         global $conf;
486
487         $config_dir = $conf['postfix']['config_dir'].'/';
488         $full_file_name = $config_dir.$configfile;
489         //* Backup exiting file
490         if(is_file($full_file_name)) {
491             copy($full_file_name, $config_dir.$configfile.'~');
492         }
493         $content = rf('tpl/'.$configfile.'.master');
494         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
495         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
496         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
497         $content = str_replace('{mysql_server_ip}', $conf['mysql']['ip'], $content);
498         $content = str_replace('{server_id}', $conf['server_id'], $content);
499         wf($full_file_name, $content);
500     }
501
502     public function configure_jailkit() {
503         global $conf;
504
505         $cf = $conf['jailkit'];
506         $config_dir = $cf['config_dir'];
507         $jk_init = $cf['jk_init'];
508         $jk_chrootsh = $cf['jk_chrootsh'];
509
510         if (is_dir($config_dir)) {
511             if(is_file($config_dir.'/'.$jk_init)) copy($config_dir.'/'.$jk_init, $config_dir.'/'.$jk_init.'~');
512             if(is_file($config_dir.'/'.$jk_chrootsh.'.master')) copy($config_dir.'/'.$jk_chrootsh.'.master', $config_dir.'/'.$jk_chrootsh.'~');
513
514             copy('tpl/'.$jk_init.'.master', $config_dir.'/'.$jk_init);
515             copy('tpl/'.$jk_chrootsh.'.master', $config_dir.'/'.$jk_chrootsh);
516         }
517
518     }
519     
520     public function configure_mailman($status = 'insert') {
521         global $conf;
522
523         $config_dir = $conf['mailman']['config_dir'].'/';
524         $full_file_name = $config_dir.'mm_cfg.py';
525         //* Backup exiting file
526         if(is_file($full_file_name)) {
527             copy($full_file_name, $config_dir.'mm_cfg.py~');
528         }
529         
530         // load files
531         $content = rf('tpl/mm_cfg.py.master');
532         $old_file = rf($full_file_name);
533         
534         $old_options = array();
535         $lines = explode("\n", $old_file); 
536         foreach ($lines as $line)
537         {
8fe9ab 538             if (trim($line) != '' && substr($line, 0, 1) != '#')
532ae5 539             {
8fe9ab 540                 @list($key, $value) = @explode("=", $line);
532ae5 541                 if (!empty($value))
L 542                 {
543                     $key = rtrim($key);
544                     $old_options[$key] = trim($value);
545                 }
546             }
547         }
548         
549         $virtual_domains = '';
550         if($status == 'update')
551         {
552             // create virtual_domains list
553             $domainAll = $this->db->queryAllRecords("SELECT domain FROM mail_mailinglist GROUP BY domain");
554             
8fe9ab 555             if(is_array($domainAll)) {
532ae5 556             foreach($domainAll as $domain)
L 557             {
558                 if ($domainAll[0]['domain'] == $domain['domain'])
559                     $virtual_domains .= "'".$domain['domain']."'";
560                 else
561                     $virtual_domains .= ", '".$domain['domain']."'";
562             }
8fe9ab 563             }
532ae5 564         }
L 565         else
566             $virtual_domains = "' '";
567             
568         $content = str_replace('{hostname}', $conf['hostname'], $content);
46c775 569         if(!isset($old_options['DEFAULT_SERVER_LANGUAGE'])) $old_options['DEFAULT_SERVER_LANGUAGE'] = '';
532ae5 570         $content = str_replace('{default_language}', $old_options['DEFAULT_SERVER_LANGUAGE'], $content);
L 571         $content = str_replace('{virtual_domains}', $virtual_domains, $content);
572
573         wf($full_file_name, $content);
574     }
575
576     public function configure_postfix($options = '') {
577         global $conf;
578         $cf = $conf['postfix'];
579         $config_dir = $cf['config_dir'];
580
581         if(!is_dir($config_dir)) {
582             $this->error("The postfix configuration directory '$config_dir' does not exist.");
583         }
584
585         //* mysql-virtual_domains.cf
586         $this->process_postfix_config('mysql-virtual_domains.cf');
587
588         //* mysql-virtual_forwardings.cf
589         $this->process_postfix_config('mysql-virtual_forwardings.cf');
590
591         //* mysql-virtual_mailboxes.cf
592         $this->process_postfix_config('mysql-virtual_mailboxes.cf');
593
594         //* mysql-virtual_email2email.cf
595         $this->process_postfix_config('mysql-virtual_email2email.cf');
596
597         //* mysql-virtual_transports.cf
598         $this->process_postfix_config('mysql-virtual_transports.cf');
599
600         //* mysql-virtual_recipient.cf
601         $this->process_postfix_config('mysql-virtual_recipient.cf');
602
603         //* mysql-virtual_sender.cf
604         $this->process_postfix_config('mysql-virtual_sender.cf');
605
606         //* mysql-virtual_client.cf
607         $this->process_postfix_config('mysql-virtual_client.cf');
608
609         //* mysql-virtual_relaydomains.cf
610         $this->process_postfix_config('mysql-virtual_relaydomains.cf');
611
612         //* mysql-virtual_relayrecipientmaps.cf
613         $this->process_postfix_config('mysql-virtual_relayrecipientmaps.cf');
614
615         //* Changing mode and group of the new created config files.
616         caselog('chmod o= '.$config_dir.'/mysql-virtual_*.cf* &> /dev/null',
617                 __FILE__, __LINE__, 'chmod on mysql-virtual_*.cf*', 'chmod on mysql-virtual_*.cf* failed');
618         caselog('chgrp '.$cf['group'].' '.$config_dir.'/mysql-virtual_*.cf* &> /dev/null',
619                 __FILE__, __LINE__, 'chgrp on mysql-virtual_*.cf*', 'chgrp on mysql-virtual_*.cf* failed');
620
621         //* Creating virtual mail user and group
622         $command = 'groupadd -g '.$cf['vmail_groupid'].' '.$cf['vmail_groupname'];
623         if(!is_group($cf['vmail_groupname'])) caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
624
625         $command = 'useradd -g '.$cf['vmail_groupname'].' -u '.$cf['vmail_userid'].' '.$cf['vmail_username'].' -d '.$cf['vmail_mailbox_base'].' -m';
626         if(!is_user($cf['vmail_username'])) caselog("$command &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
627
628         $postconf_commands = array (
629                 'myhostname = '.$conf['hostname'],
630                 'mydestination = '.$conf['hostname'].', localhost, localhost.localdomain',
631                 'mynetworks = 127.0.0.0/8 [::1]/128',
632                 'alias_maps = hash:/etc/aliases, hash:/var/lib/mailman/data/aliases',
633                 'alias_database = hash:/etc/aliases, hash:/var/lib/mailman/data/aliases',
634                 'virtual_alias_domains =',
635                 'virtual_alias_maps = proxy:mysql:'.$config_dir.'/mysql-virtual_forwardings.cf, proxy:mysql:'.$config_dir.'/mysql-virtual_email2email.cf, hash:/var/lib/mailman/data/virtual-mailman',
636                 'virtual_mailbox_domains = proxy:mysql:'.$config_dir.'/mysql-virtual_domains.cf',
637                 'virtual_mailbox_maps = proxy:mysql:'.$config_dir.'/mysql-virtual_mailboxes.cf',
638                 'virtual_mailbox_base = '.$cf['vmail_mailbox_base'],
639                 'virtual_uid_maps = static:'.$cf['vmail_userid'],
640                 'virtual_gid_maps = static:'.$cf['vmail_groupid'],
641                 'smtpd_sasl_auth_enable = yes',
642                 'broken_sasl_auth_clients = yes',
643                 'smtpd_sasl_authenticated_header = yes',
644                 'smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, check_recipient_access mysql:'.$config_dir.'/mysql-virtual_recipient.cf, reject_unauth_destination',
645                 'smtpd_use_tls = yes',
646                 'smtpd_tls_security_level = may',
647                 'smtpd_tls_cert_file = '.$config_dir.'/smtpd.cert',
648                 'smtpd_tls_key_file = '.$config_dir.'/smtpd.key',
649                 'transport_maps = proxy:mysql:'.$config_dir.'/mysql-virtual_transports.cf',
650                 'relay_domains = mysql:'.$config_dir.'/mysql-virtual_relaydomains.cf',
651                 'relay_recipient_maps = mysql:'.$config_dir.'/mysql-virtual_relayrecipientmaps.cf',
652                 'proxy_read_maps = $local_recipient_maps $mydestination $virtual_alias_maps $virtual_alias_domains $virtual_mailbox_maps $virtual_mailbox_domains $relay_recipient_maps $relay_domains $canonical_maps $sender_canonical_maps $recipient_canonical_maps $relocated_maps $transport_maps $mynetworks $virtual_mailbox_limit_maps',
653                 'smtpd_sender_restrictions = check_sender_access mysql:'.$config_dir.'/mysql-virtual_sender.cf',
654                 'smtpd_client_restrictions = check_client_access mysql:'.$config_dir.'/mysql-virtual_client.cf',
77c68a 655                 'smtpd_client_message_rate_limit = 100',
532ae5 656                 'maildrop_destination_concurrency_limit = 1',
L 657                 'maildrop_destination_recipient_limit   = 1',
658                 'virtual_transport = maildrop',
659                 'header_checks = regexp:'.$config_dir.'/header_checks',
660                 'mime_header_checks = regexp:'.$config_dir.'/mime_header_checks',
661                 'nested_header_checks = regexp:'.$config_dir.'/nested_header_checks',
662                 'body_checks = regexp:'.$config_dir.'/body_checks',
663                 'owner_request_special = no'
664         );
665
666         //* Create the header and body check files
667         touch($config_dir.'/header_checks');
668         touch($config_dir.'/mime_header_checks');
669         touch($config_dir.'/nested_header_checks');
670         touch($config_dir.'/body_checks');
671         
672         //* Create the mailman files
673         exec('mkdir -p /var/lib/mailman/data');
5378e9 674         if(!is_file('/var/lib/mailman/data/aliases')) touch('/var/lib/mailman/data/aliases');
T 675         exec('postalias /var/lib/mailman/data/aliases');
676         if(!is_file('/var/lib/mailman/data/virtual-mailman')) touch('/var/lib/mailman/data/virtual-mailman');
d4d965 677         exec('postmap /var/lib/mailman/data/virtual-mailman');
532ae5 678
L 679         //* Make a backup copy of the main.cf file
680         copy($config_dir.'/main.cf', $config_dir.'/main.cf~');
681
682         //* Executing the postconf commands
683         foreach($postconf_commands as $cmd) {
684             $command = "postconf -e '$cmd'";
685             caselog($command." &> /dev/null", __FILE__, __LINE__, 'EXECUTED: '.$command, 'Failed to execute the command '.$command);
686         }
687
688         if(!stristr($options,'dont-create-certs')) {
689             //* Create the SSL certificate
690             $command = 'cd '.$config_dir.'; '
1ca823 691                     .'openssl req -new -outform PEM -out smtpd.cert -newkey rsa:2048 -nodes -keyout smtpd.key -keyform PEM -days 3650 -x509';
532ae5 692             exec($command);
L 693
694             $command = 'chmod o= '.$config_dir.'/smtpd.key';
695             caselog($command.' &> /dev/null', __FILE__, __LINE__, 'EXECUTED: '.$command, 'Failed to execute the command '.$command);
696         }
697
698         //** We have to change the permissions of the courier authdaemon directory to make it accessible for maildrop.
699         $command = 'chmod 755  /var/run/courier/authdaemon/';
700         if(is_file('/var/run/courier/authdaemon/')) caselog($command.' &> /dev/null', __FILE__, __LINE__, 'EXECUTED: '.$command, 'Failed to execute the command '.$command);
701
702         //* Changing maildrop lines in posfix master.cf
703         if(is_file($config_dir.'/master.cf')) {
704             copy($config_dir.'/master.cf', $config_dir.'/master.cf~');
705         }
706         if(is_file($config_dir.'/master.cf~')) {
707             chmod($config_dir.'/master.cf~', 0400);
708         }
709         $configfile = $config_dir.'/master.cf';
710         $content = rf($configfile);
711         $content = str_replace('flags=DRhu user=vmail argv=/usr/bin/maildrop -d ${recipient}',
712                 'flags=DRhu user='.$cf['vmail_username'].' argv=/usr/bin/maildrop -d '.$cf['vmail_username'].' ${extension} ${recipient} ${user} ${nexthop} ${sender}',
713                 $content);
714         wf($configfile, $content);
715
716         //* Writing the Maildrop mailfilter file
717         $configfile = 'mailfilter';
718         if(is_file($cf['vmail_mailbox_base'].'/.'.$configfile)) {
719             copy($cf['vmail_mailbox_base'].'/.'.$configfile, $cf['vmail_mailbox_base'].'/.'.$configfile.'~');
720         }
721         $content = rf('tpl/'.$configfile.'.master');
722         $content = str_replace('{dist_postfix_vmail_mailbox_base}', $cf['vmail_mailbox_base'], $content);
723         wf($cf['vmail_mailbox_base'].'/.'.$configfile, $content);
724
725         //* Create the directory for the custom mailfilters
726         if(!is_dir($cf['vmail_mailbox_base'].'/mailfilters')) {
727             $command = 'mkdir '.$cf['vmail_mailbox_base'].'/mailfilters';
728             caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
729         }
730
731         //* Chmod and chown the .mailfilter file
419eb7 732         $command = 'chown '.$cf['vmail_username'].':'.$cf['vmail_groupname'].' '.$cf['vmail_mailbox_base'].'/.mailfilter';
532ae5 733         caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
L 734
419eb7 735         $command = 'chmod 600 '.$cf['vmail_mailbox_base'].'/.mailfilter';
532ae5 736         caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
L 737
738     }
739
740     public function configure_saslauthd() {
741         global $conf;
742
743
744         $configfile = 'sasl_smtpd.conf';
745         if(is_file($conf['postfix']['config_dir'].'/sasl/smtpd.conf')) copy($conf['postfix']['config_dir'].'/sasl/smtpd.conf',$conf['postfix']['config_dir'].'/sasl/smtpd.conf~');
746         if(is_file($conf['postfix']['config_dir'].'/sasl/smtpd.conf~')) chmod($conf['postfix']['config_dir'].'/sasl/smtpd.conf~', 0400);
747         $content = rf('tpl/'.$configfile.'.master');
748         $content = str_replace('{mysql_server_ispconfig_user}',$conf['mysql']['ispconfig_user'],$content);
749         $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content);
750         $content = str_replace('{mysql_server_database}',$conf['mysql']['database'],$content);
751         $content = str_replace('{mysql_server_ip}',$conf['mysql']['ip'],$content);
752         wf($conf['postfix']['config_dir'].'/sasl/smtpd.conf',$content);
753
754         // TODO: Chmod and chown on the config file
755
756
757         // Recursively create the spool directory
758         if(!@is_dir('/var/spool/postfix/var/run/saslauthd')) mkdir('/var/spool/postfix/var/run/saslauthd', 0755, true);
759
760         // Edit the file /etc/default/saslauthd
761         $configfile = $conf['saslauthd']['config'];
762         if(is_file($configfile)) copy($configfile,$configfile.'~');
763         if(is_file($configfile.'~')) chmod($configfile.'~', 0400);
764         $content = rf($configfile);
765         $content = str_replace('START=no','START=yes',$content);
766         // Debian
767         $content = str_replace('OPTIONS="-c"','OPTIONS="-m /var/spool/postfix/var/run/saslauthd -r"',$content);
768         // Ubuntu
769         $content = str_replace('OPTIONS="-c -m /var/run/saslauthd"','OPTIONS="-c -m /var/spool/postfix/var/run/saslauthd -r"',$content);
770         wf($configfile,$content);
771
772         // Edit the file /etc/init.d/saslauthd
773         $configfile = $conf['init_scripts'].'/'.$conf['saslauthd']['init_script'];
774         $content = rf($configfile);
775         $content = str_replace('PIDFILE=$RUN_DIR/saslauthd.pid','PIDFILE="/var/spool/postfix/var/run/${NAME}/saslauthd.pid"',$content);
776         wf($configfile,$content);
777
778         // add the postfix user to the sasl group (at least necessary for Ubuntu 8.04 and most likely Debian Lenny as well.
779         exec('adduser postfix sasl');
780
781
782     }
783
784     public function configure_pam() {
785         global $conf;
786         $pam = $conf['pam'];
787         //* configure pam for SMTP authentication agains the ispconfig database
788         $configfile = 'pamd_smtp';
789         if(is_file($pam.'/smtp'))    copy($pam.'/smtp', $pam.'/smtp~');
790         if(is_file($pam.'/smtp~'))   chmod($pam.'/smtp~', 0400);
791
792         $content = rf('tpl/'.$configfile.'.master');
793         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
794         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
795         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
796         $content = str_replace('{mysql_server_ip}', $conf['mysql']['ip'], $content);
797         wf($pam.'/smtp', $content);
798         // On some OSes smtp is world readable which allows for reading database information.  Removing world readable rights should have no effect.
799         if(is_file($pam.'/smtp'))    exec("chmod o= $pam/smtp");
800         chmod($pam.'/smtp', 0660);
801         chown($pam.'/smtp', 'daemon');
802         chgrp($pam.'/smtp', 'daemon');
803
804     }
805
806     public function configure_courier() {
807         global $conf;
808         $config_dir = $conf['courier']['config_dir'];
809         //* authmysqlrc
810         $configfile = 'authmysqlrc';
811         if(is_file($config_dir.'/'.$configfile)) {
812             copy($config_dir.'/'.$configfile, $config_dir.'/'.$configfile.'~');
813         }
814         chmod($config_dir.'/'.$configfile.'~', 0400);
815         $content = rf('tpl/'.$configfile.'.master');
816         $content = str_replace('{mysql_server_ispconfig_user}',$conf['mysql']['ispconfig_user'],$content);
817         $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content);
818         $content = str_replace('{mysql_server_database}',$conf['mysql']['database'],$content);
819         $content = str_replace('{mysql_server_host}',$conf['mysql']['host'],$content);
820         wf($config_dir.'/'.$configfile, $content);
821
822         chmod($config_dir.'/'.$configfile, 0660);
823         chown($config_dir.'/'.$configfile, 'daemon');
824         chgrp($config_dir.'/'.$configfile, 'daemon');
825
826         //* authdaemonrc
827         $configfile = $config_dir.'/authdaemonrc';
828         if(is_file($configfile)) {
829             copy($configfile, $configfile.'~');
830         }
831         if(is_file($configfile.'~')) {
832             chmod($configfile.'~', 0400);
833         }
834         $content = rf($configfile);
835         $content = str_replace('authmodulelist="authpam"', 'authmodulelist="authmysql"', $content);
836         wf($configfile, $content);
837     }
838
839     public function configure_dovecot() {
840         global $conf;
841
842         $config_dir = $conf['dovecot']['config_dir'];
843
844         //* Configure master.cf and add a line for deliver
845         if(is_file($conf['postfix']['config_dir'].'/master.cf')) {
846             copy($conf['postfix']['config_dir'].'/master.cf', $conf['postfix']['config_dir'].'/master.cf~2');
847         }
848         if(is_file($conf['postfix']['config_dir'].'/master.cf~')) {
849             chmod($conf['postfix']['config_dir'].'/master.cf~2', 0400);
850         }
851         $content = rf($conf['postfix']['config_dir'].'/master.cf');
852         // Only add the content if we had not addded it before
853         if(!stristr($content,'dovecot/deliver')) {
854             $deliver_content = 'dovecot   unix  -       n       n       -       -       pipe'."\n".'  flags=DRhu user=vmail:vmail argv=/usr/lib/dovecot/deliver -f ${sender} -d ${user}@${nexthop}';
855             af($conf['postfix']['config_dir'].'/master.cf',$deliver_content);
856         }
857         unset($content);
858         unset($deliver_content);
859
860
861         //* Reconfigure postfix to use dovecot authentication
862         // Adding the amavisd commands to the postfix configuration
863         $postconf_commands = array (
864                 'dovecot_destination_recipient_limit = 1',
865                 'virtual_transport = dovecot',
866                 'smtpd_sasl_type = dovecot',
867                 'smtpd_sasl_path = private/auth'
868         );
869
870         // Make a backup copy of the main.cf file
871         copy($conf['postfix']['config_dir'].'/main.cf',$conf['postfix']['config_dir'].'/main.cf~3');
872
873         // Executing the postconf commands
874         foreach($postconf_commands as $cmd) {
875             $command = "postconf -e '$cmd'";
876             caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
877         }
878
879         //* copy dovecot.conf
880         $configfile = 'dovecot.conf';
881         if(is_file($config_dir.'/'.$configfile)) {
882             copy($config_dir.'/'.$configfile, $config_dir.'/'.$configfile.'~');
883         }
884         copy('tpl/debian_dovecot.conf.master',$config_dir.'/'.$configfile);
885
886         //* dovecot-sql.conf
887         $configfile = 'dovecot-sql.conf';
888         if(is_file($config_dir.'/'.$configfile)) {
889             copy($config_dir.'/'.$configfile, $config_dir.'/'.$configfile.'~');
890         }
891         chmod($config_dir.'/'.$configfile.'~', 0400);
892         $content = rf('tpl/debian_dovecot-sql.conf.master');
893         $content = str_replace('{mysql_server_ispconfig_user}',$conf['mysql']['ispconfig_user'],$content);
894         $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content);
895         $content = str_replace('{mysql_server_database}',$conf['mysql']['database'],$content);
896         $content = str_replace('{mysql_server_host}',$conf['mysql']['host'],$content);
897         wf($config_dir.'/'.$configfile, $content);
898
899         chmod($config_dir.'/'.$configfile, 0600);
900         chown($config_dir.'/'.$configfile, 'root');
901         chgrp($config_dir.'/'.$configfile, 'root');
902
903     }
904
905     public function configure_amavis() {
906         global $conf;
907
908         // amavisd user config file
909         $configfile = 'amavisd_user_config';
910         if(is_file($conf['amavis']['config_dir'].'/conf.d/50-user')) copy($conf['amavis']['config_dir'].'/conf.d/50-user',$conf['amavis']['config_dir'].'/50-user~');
911         if(is_file($conf['amavis']['config_dir'].'/conf.d/50-user~')) chmod($conf['amavis']['config_dir'].'/conf.d/50-user~', 0400);
912         $content = rf('tpl/'.$configfile.'.master');
913         $content = str_replace('{mysql_server_ispconfig_user}',$conf['mysql']['ispconfig_user'],$content);
914         $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content);
915         $content = str_replace('{mysql_server_database}',$conf['mysql']['database'],$content);
916         $content = str_replace('{mysql_server_port}',$conf['mysql']['port'],$content);
917         $content = str_replace('{mysql_server_ip}',$conf['mysql']['ip'],$content);
918         wf($conf['amavis']['config_dir'].'/conf.d/50-user',$content);
919
920         // TODO: chmod and chown on the config file
921
922
923         // Adding the amavisd commands to the postfix configuration
864ee2 924         // Add array for no error in foreach and maybe future options
X 925         $postconf_commands = array ();
926         
927         // Check for amavisd -> pure webserver with postfix for mailing without antispam
ac28b5 928         if ($conf['amavis']['installed']) {
864ee2 929             $postconf_commands[] = 'content_filter = amavis:[127.0.0.1]:10024';
X 930             $postconf_commands[] = 'receive_override_options = no_address_mappings';
931         }
532ae5 932
L 933         // Make a backup copy of the main.cf file
934         copy($conf['postfix']['config_dir'].'/main.cf',$conf['postfix']['config_dir'].'/main.cf~2');
935
936         // Executing the postconf commands
937         foreach($postconf_commands as $cmd) {
938             $command = "postconf -e '$cmd'";
939             caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
940         }
941
942         // Append the configuration for amavisd to the master.cf file
943         if(is_file($conf['postfix']['config_dir'].'/master.cf')) copy($conf['postfix']['config_dir'].'/master.cf',$conf['postfix']['config_dir'].'/master.cf~');
944         $content = rf($conf['postfix']['config_dir'].'/master.cf');
945         // Only add the content if we had not addded it before
946         if(!stristr($content,'127.0.0.1:10025')) {
947             unset($content);
948             $content = rf('tpl/master_cf_amavis.master');
949             af($conf['postfix']['config_dir'].'/master.cf',$content);
950         }
951         unset($content);
952
953         // Add the clamav user to the amavis group
954         exec('adduser clamav amavis');
955
956
957     }
958
959     public function configure_spamassassin() {
960         global $conf;
961
962         //* Enable spamasasssin on debian and ubuntu
963         $configfile = '/etc/default/spamassassin';
964         if(is_file($configfile)) {
965             copy($configfile, $configfile.'~');
966         }
967         $content = rf($configfile);
968         $content = str_replace('ENABLED=0', 'ENABLED=1', $content);
969         wf($configfile, $content);
970     }
971
972     public function configure_getmail() {
973         global $conf;
974
975         $config_dir = $conf['getmail']['config_dir'];
976
977         if(!@is_dir($config_dir)) mkdir(escapeshellcmd($config_dir), 0700, true);
978
979         $command = 'useradd -d '.$config_dir.' getmail';
980         if(!is_user('getmail')) caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
981
982         $command = "chown -R getmail $config_dir";
983         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
984
985         $command = "chmod -R 700 $config_dir";
986         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
987     }
988
989
990     public function configure_pureftpd() {
991         global $conf;
992
993         $config_dir = $conf['pureftpd']['config_dir'];
994
995         //* configure pure-ftpd for MySQL authentication against the ispconfig database
996         $configfile = 'db/mysql.conf';
997         if(is_file($config_dir.'/'.$configfile)) {
998             copy($config_dir.'/'.$configfile, $config_dir.'/'.$configfile.'~');
999         }
1000         if(is_file($config_dir.'/'.$configfile.'~')) {
1001             chmod($config_dir.'/'.$configfile.'~', 0400);
1002         }
1003         $content = rf('tpl/pureftpd_mysql.conf.master');
1004         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
1005         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1006         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
1007         $content = str_replace('{mysql_server_ip}', $conf['mysql']['ip'], $content);
1008         $content = str_replace('{server_id}', $conf['server_id'], $content);
1009         wf($config_dir.'/'.$configfile, $content);
1010         chmod($config_dir.'/'.$configfile, 0600);
1011         chown($config_dir.'/'.$configfile, 'root');
1012         chgrp($config_dir.'/'.$configfile, 'root');
1013         // **enable chrooting
1014         //exec('mkdir -p '.$config_dir.'/conf/ChrootEveryone');
1015         exec('echo "yes" > '.$config_dir.'/conf/ChrootEveryone');
1016         exec('echo "yes" > '.$config_dir.'/conf/BrokenClientsCompatibility');
1017         exec('echo "yes" > '.$config_dir.'/conf/DisplayDotFiles');
1018
1019         if(is_file('/etc/default/pure-ftpd-common')) {
1020             replaceLine('/etc/default/pure-ftpd-common','STANDALONE_OR_INETD=inetd','STANDALONE_OR_INETD=standalone',1,0);
1021             replaceLine('/etc/default/pure-ftpd-common','VIRTUALCHROOT=false','VIRTUALCHROOT=true',1,0);
1022         }
1023
1024         if(is_file('/etc/inetd.conf')) {
1025             replaceLine('/etc/inetd.conf','/usr/sbin/pure-ftpd-wrapper','#ftp     stream  tcp     nowait  root    /usr/sbin/tcpd /usr/sbin/pure-ftpd-wrapper',0,0);
1026             if(is_file($conf['init_scripts'].'/'.'openbsd-inetd')) exec($conf['init_scripts'].'/'.'openbsd-inetd restart');
1027         }
1028
1029         if(!is_file('/etc/pure-ftpd/conf/DontResolve')) exec('echo "yes" > /etc/pure-ftpd/conf/DontResolve');
1030     }
1031
1032     public function configure_mydns() {
1033         global $conf;
1034
1035         // configure pam for SMTP authentication agains the ispconfig database
1036         $configfile = 'mydns.conf';
1037         if(is_file($conf['mydns']['config_dir'].'/'.$configfile)) copy($conf['mydns']['config_dir'].'/'.$configfile,$conf['mydns']['config_dir'].'/'.$configfile.'~');
1038         if(is_file($conf['mydns']['config_dir'].'/'.$configfile.'~')) chmod($conf['mydns']['config_dir'].'/'.$configfile.'~', 0400);
1039         $content = rf('tpl/'.$configfile.'.master');
1040         $content = str_replace('{mysql_server_ispconfig_user}',$conf['mysql']['ispconfig_user'],$content);
1041         $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content);
1042         $content = str_replace('{mysql_server_database}',$conf['mysql']['database'],$content);
1043         $content = str_replace('{mysql_server_host}',$conf['mysql']['host'],$content);
1044         $content = str_replace('{server_id}',$conf['server_id'],$content);
1045         wf($conf['mydns']['config_dir'].'/'.$configfile,$content);
1046         chmod($conf['mydns']['config_dir'].'/'.$configfile, 0600);
1047         chown($conf['mydns']['config_dir'].'/'.$configfile, 'root');
1048         chgrp($conf['mydns']['config_dir'].'/'.$configfile, 'root');
1049
1050     }
1051
1052     public function configure_powerdns() {
1053         global $conf;
1054
1055         //* Create the database
1056         if(!$this->db->query('CREATE DATABASE IF NOT EXISTS '.$conf['powerdns']['database'].' DEFAULT CHARACTER SET '.$conf['mysql']['charset'])) {
1057             $this->error('Unable to create MySQL database: '.$conf['powerdns']['database'].'.');
1058         }
1059
1060         //* Create the ISPConfig database user in the local database
1061         $query = "GRANT ALL ON `".$conf['powerdns']['database']."` . * TO '".$conf['mysql']['ispconfig_user']."'@'localhost';";
1062         if(!$this->db->query($query)) {
1063             $this->error('Unable to create user for powerdns database Error: '.$this->db->errorMessage);
1064         }
1065
1066         //* Reload database privelages
1067         $this->db->query('FLUSH PRIVILEGES;');
1068
1069         //* load the powerdns databse dump
1070         if($conf['mysql']['admin_password'] == '') {
1071             caselog("mysql --default-character-set=".$conf['mysql']['charset']." -h '".$conf['mysql']['host']."' -u '".$conf['mysql']['admin_user']."' '".$conf['powerdns']['database']."' < '".ISPC_INSTALL_ROOT."/install/sql/powerdns.sql' &> /dev/null",
1072                     __FILE__, __LINE__, 'read in ispconfig3.sql', 'could not read in powerdns.sql');
1073         } else {
1074             caselog("mysql --default-character-set=".$conf['mysql']['charset']." -h '".$conf['mysql']['host']."' -u '".$conf['mysql']['admin_user']."' -p'".$conf['mysql']['admin_password']."' '".$conf['powerdns']['database']."' < '".ISPC_INSTALL_ROOT."/install/sql/powerdns.sql' &> /dev/null",
1075                     __FILE__, __LINE__, 'read in ispconfig3.sql', 'could not read in powerdns.sql');
1076         }
1077
1078         //* Create the powerdns config file
1079         $configfile = 'pdns.local';
1080         if(is_file($conf['powerdns']['config_dir'].'/'.$configfile)) copy($conf['powerdns']['config_dir'].'/'.$configfile,$conf['powerdns']['config_dir'].'/'.$configfile.'~');
1081         if(is_file($conf['powerdns']['config_dir'].'/'.$configfile.'~')) chmod($conf['powerdns']['config_dir'].'/'.$configfile.'~', 0400);
1082         $content = rf('tpl/'.$configfile.'.master');
1083         $content = str_replace('{mysql_server_ispconfig_user}',$conf['mysql']['ispconfig_user'],$content);
1084         $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content);
1085         $content = str_replace('{powerdns_database}',$conf['powerdns']['database'],$content);
1086         $content = str_replace('{mysql_server_host}',$conf['mysql']['host'],$content);
1087         wf($conf['powerdns']['config_dir'].'/'.$configfile,$content);
1088         chmod($conf['powerdns']['config_dir'].'/'.$configfile, 0600);
1089         chown($conf['powerdns']['config_dir'].'/'.$configfile, 'root');
1090         chgrp($conf['powerdns']['config_dir'].'/'.$configfile, 'root');
1091
1092
1093     }
1094
1095     public function configure_bind() {
1096         global $conf;
1097
1098         //* Check if the zonefile directory has a slash at the end
1099         $content=$conf['bind']['bind_zonefiles_dir'];
1100         if(substr($content,-1,1) != '/') {
1101             $content .= '/';
1102         }
1103
1104         //* Create the slave subdirectory
1105         $content .= 'slave';
1106         if(!@is_dir($content)) mkdir($content, 0770, true);
1107
1108         //* Chown the slave subdirectory to $conf['bind']['bind_user']
1109         chown($content, $conf['bind']['bind_user']);
1110         chgrp($content, $conf['bind']['bind_group']);
1111
1112     }
1113
1114
1115
1116     public function configure_apache() {
1117         global $conf;
1118
4ffb51 1119         if($conf['apache']['installed'] == false) return;
532ae5 1120         //* Create the logging directory for the vhost logfiles
L 1121         if(!@is_dir($conf['ispconfig_log_dir'].'/httpd')) mkdir($conf['ispconfig_log_dir'].'/httpd', 0755, true);
1122
1123         if(is_file('/etc/suphp/suphp.conf')) {
1124             replaceLine('/etc/suphp/suphp.conf','php=php:/usr/bin','x-httpd-suphp="php:/usr/bin/php-cgi"',0);
1125             //replaceLine('/etc/suphp/suphp.conf','docroot=','docroot=/var/clients',0);
1126             replaceLine('/etc/suphp/suphp.conf','umask=0077','umask=0022',0);
1127         }
1128
1129         if(is_file('/etc/apache2/sites-enabled/000-default')) {
1130             replaceLine('/etc/apache2/sites-available/000-default','NameVirtualHost *','NameVirtualHost *:80',1,0);
1131             replaceLine('/etc/apache2/sites-available/000-default','<VirtualHost *>','<VirtualHost *:80>',1,0);
1132         }
1133
1134         if(is_file('/etc/apache2/ports.conf')) {
1135             // add a line "Listen 443" to ports conf if line does not exist
1136             replaceLine('/etc/apache2/ports.conf','Listen 443','Listen 443',1);
1137         }
1138
1139
1140         //* Copy the ISPConfig configuration include
1141         $vhost_conf_dir = $conf['apache']['vhost_conf_dir'];
1142         $vhost_conf_enabled_dir = $conf['apache']['vhost_conf_enabled_dir'];
1143
1144         // copy('tpl/apache_ispconfig.conf.master',$vhost_conf_dir.'/ispconfig.conf');
a2156e 1145         
532ae5 1146         $content = rf('tpl/apache_ispconfig.conf.master');
L 1147         $records = $this->db->queryAllRecords('SELECT * FROM '.$conf['mysql']['master_database'].'.server_ip WHERE server_id = '.$conf['server_id']." AND virtualhost = 'y'");
a2156e 1148
532ae5 1149         if(is_array($records) && count($records) > 0) {
L 1150             foreach($records as $rec) {
a2156e 1151                 if($rec['ip_type'] == 'IPv6') {
T 1152                     $ip_address = '['.$rec['ip_address'].']';
1153                 } else {
1154                     $ip_address = $rec['ip_address'];
1155                 }
1156                 $ports = explode(',',$rec['virtualhost_port']);
1157                 if(is_array($ports)) {
1158                     foreach($ports as $port) {
1159                         $port = intval($port);
1160                         if($port > 0 && $port < 65536 && $ip_address != '') {
1161                             $content .= 'NameVirtualHost '.$ip_address.":".$port."\n";
1162                         }
1163                     }
1164                 }
532ae5 1165             }
L 1166         }
a2156e 1167         
532ae5 1168         $content .= "\n";
L 1169         wf($vhost_conf_dir.'/ispconfig.conf',$content);
1170
1171         if(!@is_link($vhost_conf_enabled_dir.'/000-ispconfig.conf')) {
1172             symlink($vhost_conf_dir.'/ispconfig.conf',$vhost_conf_enabled_dir.'/000-ispconfig.conf');
1173         }
1174
1175         //* make sure that webalizer finds its config file when it is directly in /etc
1176         if(@is_file('/etc/webalizer.conf') && !@is_dir('/etc/webalizer')) {
1177             mkdir('/etc/webalizer');
1178             symlink('/etc/webalizer.conf','/etc/webalizer/webalizer.conf');
1179         }
1180
1181         if(is_file('/etc/webalizer/webalizer.conf')) {
1182             // Change webalizer mode to incremental
1183             replaceLine('/etc/webalizer/webalizer.conf','#IncrementalName','IncrementalName webalizer.current',0,0);
1184             replaceLine('/etc/webalizer/webalizer.conf','#Incremental','Incremental     yes',0,0);
1185             replaceLine('/etc/webalizer/webalizer.conf','#HistoryName','HistoryName     webalizer.hist',0,0);
1186         }
1187         
1188         // Check the awsatst script
1189         if(!is_dir('/usr/share/awstats/tools')) exec('mkdir -p /usr/share/awstats/tools');
1190         if(!file_exists('/usr/share/awstats/tools/awstats_buildstaticpages.pl') && file_exists('/usr/share/doc/awstats/examples/awstats_buildstaticpages.pl')) symlink('/usr/share/doc/awstats/examples/awstats_buildstaticpages.pl','/usr/share/awstats/tools/awstats_buildstaticpages.pl');
1ca823 1191         if(file_exists('/etc/awstats/awstats.conf.local')) replaceLine('/etc/awstats/awstats.conf.local','LogFormat=4','LogFormat=1',0,1);
T 1192         
532ae5 1193         //* add a sshusers group
L 1194         $command = 'groupadd sshusers';
1195         if(!is_group('sshusers')) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1196
1197     }
80e3c9 1198     
4ffb51 1199     public function configure_nginx(){
80e3c9 1200         global $conf;
4ffb51 1201         
F 1202         if($conf['nginx']['installed'] == false) return;
1203         //* Create the logging directory for the vhost logfiles
1204         if(!@is_dir($conf['ispconfig_log_dir'].'/httpd')) mkdir($conf['ispconfig_log_dir'].'/httpd', 0755, true);
1205
1206         //* make sure that webalizer finds its config file when it is directly in /etc
1207         if(@is_file('/etc/webalizer.conf') && !@is_dir('/etc/webalizer')) {
1208             mkdir('/etc/webalizer');
1209             symlink('/etc/webalizer.conf','/etc/webalizer/webalizer.conf');
1210         }
1211
1212         if(is_file('/etc/webalizer/webalizer.conf')) {
1213             // Change webalizer mode to incremental
1214             replaceLine('/etc/webalizer/webalizer.conf','#IncrementalName','IncrementalName webalizer.current',0,0);
1215             replaceLine('/etc/webalizer/webalizer.conf','#Incremental','Incremental     yes',0,0);
1216             replaceLine('/etc/webalizer/webalizer.conf','#HistoryName','HistoryName     webalizer.hist',0,0);
1217         }
1218         
1219         // Check the awsatst script
1220         if(!is_dir('/usr/share/awstats/tools')) exec('mkdir -p /usr/share/awstats/tools');
1221         if(!file_exists('/usr/share/awstats/tools/awstats_buildstaticpages.pl') && file_exists('/usr/share/doc/awstats/examples/awstats_buildstaticpages.pl')) symlink('/usr/share/doc/awstats/examples/awstats_buildstaticpages.pl','/usr/share/awstats/tools/awstats_buildstaticpages.pl');
1222         if(file_exists('/etc/awstats/awstats.conf.local')) replaceLine('/etc/awstats/awstats.conf.local','LogFormat=4','LogFormat=1',0,1);
1223         
1224         //* add a sshusers group
1225         $command = 'groupadd sshusers';
1226         if(!is_group('sshusers')) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1227         
1228         /*
80e3c9 1229         $row = $this->db->queryOneRecord("SELECT server_name FROM server WHERE server_id = ".$conf["server_id"]."");
T 1230         $ip_address = gethostbyname($row["server_name"]);
1231         $server_name = $row["server_name"];
1232
1233         //setup proxy.conf
1234         $configfile = 'proxy.conf';
1235         if(is_file($conf["nginx"]["config_dir"].'/'.$configfile)) copy($conf["nginx"]["config_dir"].'/'.$configfile,$conf["nginx"]["config_dir"].'/'.$configfile.'~');
1236         if(is_file($conf["nginx"]["config_dir"].'/'.$configfile.'~')) exec('chmod 400 '.$conf["nginx"]["config_dir"].'/'.$configfile.'~');
1237         $content = rf("tpl/nginx_".$configfile.".master");
1238         wf($conf["nginx"]["config_dir"].'/'.$configfile,$content);
1239         exec('chmod 600 '.$conf["nginx"]["config_dir"].'/'.$configfile);
1240         exec('chown root:root '.$conf["nginx"]["config_dir"].'/'.$configfile);
1241
1242         //setup conf.d/cache.conf
1243         $configfile = 'cache.conf';
1244         if(is_file($conf["nginx"]["config_dir"].'/conf.d/'.$configfile)) copy($conf["nginx"]["config_dir"].'/conf.d/'.$configfile,$conf["nginx"]["config_dir"].'/conf.d/'.$configfile.'~');
1245         if(is_file($conf["nginx"]["config_dir"].'/conf.d/'.$configfile.'~')) exec('chmod 400 '.$conf["nginx"]["config_dir"].'/conf.d/'.$configfile.'~');
1246         $content = rf("tpl/nginx_".$configfile.".master");
1247         wf($conf["nginx"]["config_dir"].'/conf.d/'.$configfile,$content);
1248         exec('chmod 600 '.$conf["nginx"]["config_dir"].'/conf.d/'.$configfile);
1249         exec('chown root:root '.$conf["nginx"]["config_dir"].'/conf.d/'.$configfile);
1250
1251         //setup cache directories
1252         mkdir('/var/cache/nginx/cache');
1253         exec('chown www-data:www-data /var/cache/nginx/cache');
1254         mkdir('/var/cache/nginx/temp');
1255         exec('chown www-data:www-data /var/cache/nginx/temp');
4ffb51 1256         */
80e3c9 1257     }
T 1258     
d083f2 1259     public function configure_fail2ban() {
F 1260         // To Do
1261     }
1262     
80e3c9 1263     public function configure_squid()
T 1264     {
1265         global $conf;
1266         $row = $this->db->queryOneRecord("SELECT server_name FROM server WHERE server_id = ".$conf["server_id"]."");
1267         $ip_address = gethostbyname($row["server_name"]);
1268         $server_name = $row["server_name"];
1269         
1270         $configfile = 'squid.conf';
1271         if(is_file($conf["squid"]["config_dir"].'/'.$configfile)) copy($conf["squid"]["config_dir"].'/'.$configfile,$conf["squid"]["config_dir"].'/'.$configfile.'~');
1272         if(is_file($conf["squid"]["config_dir"].'/'.$configfile.'~')) exec('chmod 400 '.$conf["squid"]["config_dir"].'/'.$configfile.'~');
1273         $content = rf("tpl/".$configfile.".master");
1274         $content = str_replace('{server_name}',$server_name,$content);
1275         $content = str_replace('{ip_address}',$ip_address, $content);
1276         $content = str_replace('{config_dir}',$conf['squid']['config_dir'], $content);
1277         wf($conf["squid"]["config_dir"].'/'.$configfile,$content);
1278         exec('chmod 600 '.$conf["squid"]["config_dir"].'/'.$configfile);
1279         exec('chown root:root '.$conf["squid"]["config_dir"].'/'.$configfile);
1280     }
1281     
c91bdc 1282     /*
80e3c9 1283     public function configure_ufw_firewall()
T 1284     {
1285         $configfile = 'ufw.conf';
1286         if(is_file('/etc/ufw/ufw.conf')) copy('/etc/ufw/ufw.conf','/etc/ufw/ufw.conf~');
1287         $content = rf("tpl/".$configfile.".master");
1288         wf('/etc/ufw/ufw.conf',$content);
1289         exec('chmod 600 /etc/ufw/ufw.conf');
1290         exec('chown root:root /etc/ufw/ufw.conf');    
1291     }
c91bdc 1292     */
532ae5 1293
L 1294     public function configure_firewall() {
1295         global $conf;
1296
1297         $dist_init_scripts = $conf['init_scripts'];
1298
1299         if(is_dir('/etc/Bastille.backup')) caselog('rm -rf /etc/Bastille.backup', __FILE__, __LINE__);
1300         if(is_dir('/etc/Bastille')) caselog('mv -f /etc/Bastille /etc/Bastille.backup', __FILE__, __LINE__);
1301         @mkdir('/etc/Bastille', 0700);
1302         if(is_dir('/etc/Bastille.backup/firewall.d')) caselog('cp -pfr /etc/Bastille.backup/firewall.d /etc/Bastille/', __FILE__, __LINE__);
1303         caselog('cp -f tpl/bastille-firewall.cfg.master /etc/Bastille/bastille-firewall.cfg', __FILE__, __LINE__);
1304         caselog('chmod 644 /etc/Bastille/bastille-firewall.cfg', __FILE__, __LINE__);
1305         $content = rf('/etc/Bastille/bastille-firewall.cfg');
1306         $content = str_replace('{DNS_SERVERS}', '', $content);
1307
1308         $tcp_public_services = '';
1309         $udp_public_services = '';
1310
1311         $row = $this->db->queryOneRecord('SELECT * FROM '.$conf["mysql"]["database"].'.firewall WHERE server_id = '.intval($conf['server_id']));
1312
1313         if(trim($row['tcp_port']) != '' || trim($row['udp_port']) != '') {
1314             $tcp_public_services = trim(str_replace(',',' ',$row['tcp_port']));
1315             $udp_public_services = trim(str_replace(',',' ',$row['udp_port']));
1316         } else {
1317             $tcp_public_services = '21 22 25 53 80 110 143 443 3306 8080 10000';
1318             $udp_public_services = '53';
1319         }
1320
1321         if(!stristr($tcp_public_services, $conf['apache']['vhost_port'])) {
1322             $tcp_public_services .= ' '.intval($conf['apache']['vhost_port']);
1323             if($row['tcp_port'] != '') $this->db->query("UPDATE firewall SET tcp_port = tcp_port + ',".intval($conf['apache']['vhost_port'])."' WHERE server_id = ".intval($conf['server_id']));
1324         }
1325
1326         $content = str_replace('{TCP_PUBLIC_SERVICES}', $tcp_public_services, $content);
1327         $content = str_replace('{UDP_PUBLIC_SERVICES}', $udp_public_services, $content);
1328
1329         wf('/etc/Bastille/bastille-firewall.cfg', $content);
1330
1331         if(is_file($dist_init_scripts.'/bastille-firewall')) caselog('mv -f '.$dist_init_scripts.'/bastille-firewall '.$dist_init_scripts.'/bastille-firewall.backup', __FILE__, __LINE__);
1332         caselog('cp -f apps/bastille-firewall '.$dist_init_scripts, __FILE__, __LINE__);
1333         caselog('chmod 700 '.$dist_init_scripts.'/bastille-firewall', __FILE__, __LINE__);
1334
1335         if(is_file('/sbin/bastille-ipchains')) caselog('mv -f /sbin/bastille-ipchains /sbin/bastille-ipchains.backup', __FILE__, __LINE__);
1336         caselog('cp -f apps/bastille-ipchains /sbin', __FILE__, __LINE__);
1337         caselog('chmod 700 /sbin/bastille-ipchains', __FILE__, __LINE__);
1338
1339         if(is_file('/sbin/bastille-netfilter')) caselog('mv -f /sbin/bastille-netfilter /sbin/bastille-netfilter.backup', __FILE__, __LINE__);
1340         caselog('cp -f apps/bastille-netfilter /sbin', __FILE__, __LINE__);
1341         caselog('chmod 700 /sbin/bastille-netfilter', __FILE__, __LINE__);
1342
1343         if(!@is_dir('/var/lock/subsys')) caselog('mkdir /var/lock/subsys', __FILE__, __LINE__);
1344
1345         exec('which ipchains &> /dev/null', $ipchains_location, $ret_val);
1346         if(!is_file('/sbin/ipchains') && !is_link('/sbin/ipchains') && $ret_val == 0) phpcaselog(@symlink(shell_exec('which ipchains'), '/sbin/ipchains'), 'create symlink', __FILE__, __LINE__);
1347         unset($ipchains_location);
1348         exec('which iptables &> /dev/null', $iptables_location, $ret_val);
1349         if(!is_file('/sbin/iptables') && !is_link('/sbin/iptables') && $ret_val == 0) phpcaselog(@symlink(trim(shell_exec('which iptables')), '/sbin/iptables'), 'create symlink', __FILE__, __LINE__);
1350         unset($iptables_location);
1351
1352     }
1353
1354     public function configure_vlogger() {
1355         global $conf;
1356
1357         //** Configure vlogger to use traffic logging to mysql (master) db
1358         $configfile = 'vlogger-dbi.conf';
1359         if(is_file($conf['vlogger']['config_dir'].'/'.$configfile)) copy($conf['vlogger']['config_dir'].'/'.$configfile,$conf['vlogger']['config_dir'].'/'.$configfile.'~');
1360         if(is_file($conf['vlogger']['config_dir'].'/'.$configfile.'~')) chmod($conf['vlogger']['config_dir'].'/'.$configfile.'~', 0400);
1361         $content = rf('tpl/'.$configfile.'.master');
1362         if($conf['mysql']['master_slave_setup'] == 'y') {
1363             $content = str_replace('{mysql_server_ispconfig_user}',$conf['mysql']['master_ispconfig_user'],$content);
1364             $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['master_ispconfig_password'], $content);
1365             $content = str_replace('{mysql_server_database}',$conf['mysql']['master_database'],$content);
1366             $content = str_replace('{mysql_server_ip}',$conf['mysql']['master_host'],$content);
1367         } else {
1368             $content = str_replace('{mysql_server_ispconfig_user}',$conf['mysql']['ispconfig_user'],$content);
1369             $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content);
1370             $content = str_replace('{mysql_server_database}',$conf['mysql']['database'],$content);
1371             $content = str_replace('{mysql_server_ip}',$conf['mysql']['host'],$content);
1372         }
1373         wf($conf['vlogger']['config_dir'].'/'.$configfile,$content);
1374         chmod($conf['vlogger']['config_dir'].'/'.$configfile, 0600);
1375         chown($conf['vlogger']['config_dir'].'/'.$configfile, 'root');
1376         chgrp($conf['vlogger']['config_dir'].'/'.$configfile, 'root');
1377
1378     }
1379
1380     public function configure_apps_vhost() {
1381         global $conf;
1382
1383         //* Create the ispconfig apps vhost user and group
4ffb51 1384         if($conf['apache']['installed'] == true){
F 1385             $apps_vhost_user = escapeshellcmd($conf['web']['apps_vhost_user']);
1386             $apps_vhost_group = escapeshellcmd($conf['web']['apps_vhost_group']);
1387             $install_dir = escapeshellcmd($conf['web']['website_basedir'].'/apps');
532ae5 1388
4ffb51 1389             $command = 'groupadd '.$apps_vhost_user;
F 1390             if(!is_group($apps_vhost_group)) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
532ae5 1391
4ffb51 1392             $command = 'useradd -g '.$apps_vhost_group.' -d '.$install_dir.' '.$apps_vhost_group;
F 1393             if(!is_user($apps_vhost_user)) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
532ae5 1394
L 1395
4ffb51 1396             $command = 'adduser '.$conf['apache']['user'].' '.$apps_vhost_group;
F 1397             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
532ae5 1398
4ffb51 1399             if(!@is_dir($install_dir)) mkdir($install_dir, 0755, true);
F 1400             chown($install_dir, $apps_vhost_user);
1401             chgrp($install_dir, $apps_vhost_group);
532ae5 1402
4ffb51 1403             //* Copy the apps vhost file
F 1404             $vhost_conf_dir = $conf['apache']['vhost_conf_dir'];
1405             $vhost_conf_enabled_dir = $conf['apache']['vhost_conf_enabled_dir'];
1406             $apps_vhost_servername = ($conf['web']['apps_vhost_servername'] == '')?'':'ServerName '.$conf['web']['apps_vhost_servername'];
532ae5 1407
4ffb51 1408             // Dont just copy over the virtualhost template but add some custom settings
F 1409             $content = rf('tpl/apache_apps.vhost.master');
532ae5 1410
4ffb51 1411             $content = str_replace('{apps_vhost_ip}', $conf['web']['apps_vhost_ip'], $content);
F 1412             $content = str_replace('{apps_vhost_port}', $conf['web']['apps_vhost_port'], $content);
1413             $content = str_replace('{apps_vhost_dir}', $conf['web']['website_basedir'].'/apps', $content);
1414             $content = str_replace('{website_basedir}', $conf['web']['website_basedir'], $content);
1415             $content = str_replace('{apps_vhost_servername}', $apps_vhost_servername, $content);
532ae5 1416
L 1417
4ffb51 1418             // comment out the listen directive if port is 80 or 443
F 1419             if($conf['web']['apps_vhost_ip'] == 80 or $conf['web']['apps_vhost_ip'] == 443) {
1420                 $content = str_replace('{vhost_port_listen}', '#', $content);
1421             } else {
1422                 $content = str_replace('{vhost_port_listen}', '', $content);
1423             }
532ae5 1424
4ffb51 1425             wf($vhost_conf_dir.'/apps.vhost', $content);
532ae5 1426
4ffb51 1427             //copy('tpl/apache_ispconfig.vhost.master', "$vhost_conf_dir/ispconfig.vhost");
F 1428             //* and create the symlink
1429             if($this->install_ispconfig_interface == true) {
1430                 if(@is_link($vhost_conf_enabled_dir.'/apps.vhost')) unlink($vhost_conf_enabled_dir.'/apps.vhost');
1431                 if(!@is_link($vhost_conf_enabled_dir.'/000-apps.vhost')) {
1432                     symlink($vhost_conf_dir.'/apps.vhost',$vhost_conf_enabled_dir.'/000-apps.vhost');
1433                 }
1434             }
1435             if(!is_file($conf['web']['website_basedir'].'/php-fcgi-scripts/apps/.php-fcgi-starter')) {
1436                 mkdir($conf['web']['website_basedir'].'/php-fcgi-scripts/apps', 0755, true);
1437                 copy('tpl/apache_apps_fcgi_starter.master',$conf['web']['website_basedir'].'/php-fcgi-scripts/apps/.php-fcgi-starter');
1438                 exec('chmod +x '.$conf['web']['website_basedir'].'/php-fcgi-scripts/apps/.php-fcgi-starter');
1439                 exec('chown -R ispapps:ispapps '.$conf['web']['website_basedir'].'/php-fcgi-scripts/apps');
1440
532ae5 1441             }
L 1442         }
4ffb51 1443         if($conf['nginx']['installed'] == true){
F 1444             $apps_vhost_user = escapeshellcmd($conf['web']['apps_vhost_user']);
1445             $apps_vhost_group = escapeshellcmd($conf['web']['apps_vhost_group']);
1446             $install_dir = escapeshellcmd($conf['web']['website_basedir'].'/apps');
532ae5 1447
4ffb51 1448             $command = 'groupadd '.$apps_vhost_user;
F 1449             if(!is_group($apps_vhost_group)) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1450
1451             $command = 'useradd -g '.$apps_vhost_group.' -d '.$install_dir.' '.$apps_vhost_group;
1452             if(!is_user($apps_vhost_user)) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1453
1454
1455             $command = 'adduser '.$conf['nginx']['user'].' '.$apps_vhost_group;
1456             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1457
1458             if(!@is_dir($install_dir)) mkdir($install_dir, 0755, true);
1459             chown($install_dir, $apps_vhost_user);
1460             chgrp($install_dir, $apps_vhost_group);
1461
1462             //* Copy the apps vhost file
1463             $vhost_conf_dir = $conf['nginx']['vhost_conf_dir'];
1464             $vhost_conf_enabled_dir = $conf['nginx']['vhost_conf_enabled_dir'];
1465             $apps_vhost_servername = ($conf['web']['apps_vhost_servername'] == '')?'_':$conf['web']['apps_vhost_servername'];
1466
1467             // Dont just copy over the virtualhost template but add some custom settings
1468             $content = rf('tpl/nginx_apps.vhost.master');
1469             
1470             if($conf['web']['apps_vhost_ip'] == '_default_'){
1471                 $apps_vhost_ip = '';
1472             } else {
1473                 $apps_vhost_ip = $conf['web']['apps_vhost_ip'].':';
1474             }
ca0b77 1475             
F 1476             $socket_dir = escapeshellcmd($conf['nginx']['php_fpm_socket_dir']);
1477             if(substr($socket_dir,-1) != '/') $socket_dir .= '/';
1478             if(!is_dir($socket_dir)) exec('mkdir -p '.$socket_dir);
1479             $fpm_socket = $socket_dir.'apps.sock';
4ffb51 1480
F 1481             $content = str_replace('{apps_vhost_ip}', $apps_vhost_ip, $content);
1482             $content = str_replace('{apps_vhost_port}', $conf['web']['apps_vhost_port'], $content);
1483             $content = str_replace('{apps_vhost_dir}', $conf['web']['website_basedir'].'/apps', $content);
1484             $content = str_replace('{apps_vhost_servername}', $apps_vhost_servername, $content);
ca0b77 1485             //$content = str_replace('{fpm_port}', ($conf['nginx']['php_fpm_start_port']+1), $content);
F 1486             $content = str_replace('{fpm_socket}', $fpm_socket, $content);
4ffb51 1487
F 1488             wf($vhost_conf_dir.'/apps.vhost', $content);
fbb24a 1489             
F 1490             // PHP-FPM
1491             // Dont just copy over the php-fpm pool template but add some custom settings
f19eb6 1492             $content = rf('tpl/apps_php_fpm_pool.conf.master');
fbb24a 1493             $content = str_replace('{fpm_pool}', 'apps', $content);
ca0b77 1494             //$content = str_replace('{fpm_port}', ($conf['nginx']['php_fpm_start_port']+1), $content);
F 1495             $content = str_replace('{fpm_socket}', $fpm_socket, $content);
fbb24a 1496             $content = str_replace('{fpm_user}', $apps_vhost_user, $content);
F 1497             $content = str_replace('{fpm_group}', $apps_vhost_group, $content);
1498             wf($conf['nginx']['php_fpm_pool_dir'].'/apps.conf', $content);
4ffb51 1499
F 1500             //copy('tpl/nginx_ispconfig.vhost.master', "$vhost_conf_dir/ispconfig.vhost");
1501             //* and create the symlink
1502             if($this->install_ispconfig_interface == true) {
1503                 if(@is_link($vhost_conf_enabled_dir.'/apps.vhost')) unlink($vhost_conf_enabled_dir.'/apps.vhost');
1504                 if(!@is_link($vhost_conf_enabled_dir.'/000-apps.vhost')) {
1505                     symlink($vhost_conf_dir.'/apps.vhost',$vhost_conf_enabled_dir.'/000-apps.vhost');
1506                 }
1507             }
532ae5 1508         }
L 1509     }
1510     
1511     public function make_ispconfig_ssl_cert() {
1512         global $conf;
1513
1514         $install_dir = $conf['ispconfig_install_dir'];
1515         
1516         $ssl_crt_file = $install_dir.'/interface/ssl/ispserver.crt';
1517         $ssl_csr_file = $install_dir.'/interface/ssl/ispserver.csr';
1518         $ssl_key_file = $install_dir.'/interface/ssl/ispserver.key';
1519         
1520         if(!@is_dir($install_dir.'/interface/ssl')) mkdir($install_dir.'/interface/ssl', 0755, true);
1521         
1522         $ssl_pw = substr(md5(mt_rand()),0,6);
1523         exec("openssl genrsa -des3 -passout pass:$ssl_pw -out $ssl_key_file 4096");
1524         exec("openssl req -new -passin pass:$ssl_pw -passout pass:$ssl_pw -key $ssl_key_file -out $ssl_csr_file");
1525         exec("openssl req -x509 -passin pass:$ssl_pw -passout pass:$ssl_pw -key $ssl_key_file -in $ssl_csr_file -out $ssl_crt_file -days 3650");
1526         exec("openssl rsa -passin pass:$ssl_pw -in $ssl_key_file -out $ssl_key_file.insecure");
1527         rename($ssl_key_file,$ssl_key_file.'.secure');
1528         rename($ssl_key_file.'.insecure',$ssl_key_file);
1529         
1530     }
1531
1532     public function install_ispconfig() {
1533         global $conf;
1534
1535         $install_dir = $conf['ispconfig_install_dir'];
1536
1537         //* Create the ISPConfig installation directory
1538         if(!@is_dir($install_dir)) {
1539             $command = "mkdir $install_dir";
1540             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1541         }
1542
1543         //* Create a ISPConfig user and group
1544         $command = 'groupadd ispconfig';
1545         if(!is_group('ispconfig')) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1546
1547         $command = 'useradd -g ispconfig -d '.$install_dir.' ispconfig';
1548         if(!is_user('ispconfig')) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1549
1550         //* copy the ISPConfig interface part
1551         $command = 'cp -rf ../interface '.$install_dir;
1552         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1553
1554         //* copy the ISPConfig server part
1555         $command = 'cp -rf ../server '.$install_dir;
1556         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1557
1558         //* Create a symlink, so ISPConfig is accessible via web
1559         // Replaced by a separate vhost definition for port 8080
1560         // $command = "ln -s $install_dir/interface/web/ /var/www/ispconfig";
1561         // caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1562
1563         //* Create the config file for ISPConfig interface
1564         $configfile = 'config.inc.php';
1565         if(is_file($install_dir.'/interface/lib/'.$configfile)) {
1566             copy($install_dir.'/interface/lib/'.$configfile, $install_dir.'/interface/lib/'.$configfile.'~');
1567         }
1568         $content = rf('tpl/'.$configfile.'.master');
1569         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
1570         $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content);
1571         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
1572         $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content);
1573
1574         $content = str_replace('{mysql_master_server_ispconfig_user}', $conf['mysql']['master_ispconfig_user'], $content);
1575         $content = str_replace('{mysql_master_server_ispconfig_password}', $conf['mysql']['master_ispconfig_password'], $content);
1576         $content = str_replace('{mysql_master_server_database}', $conf['mysql']['master_database'], $content);
1577         $content = str_replace('{mysql_master_server_host}', $conf['mysql']['master_host'], $content);
1578
1579         $content = str_replace('{server_id}', $conf['server_id'], $content);
1580         $content = str_replace('{ispconfig_log_priority}', $conf['ispconfig_log_priority'], $content);
b63764 1581         $content = str_replace('{language}', $conf['language'], $content);
L 1582
532ae5 1583         wf($install_dir.'/interface/lib/'.$configfile, $content);
L 1584
1585         //* Create the config file for ISPConfig server
1586         $configfile = 'config.inc.php';
1587         if(is_file($install_dir.'/server/lib/'.$configfile)) {
1588             copy($install_dir.'/server/lib/'.$configfile, $install_dir.'/interface/lib/'.$configfile.'~');
1589         }
1590         $content = rf('tpl/'.$configfile.'.master');
1591         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
1592         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1593         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
1594         $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content);
1595
1596         $content = str_replace('{mysql_master_server_ispconfig_user}', $conf['mysql']['master_ispconfig_user'], $content);
1597         $content = str_replace('{mysql_master_server_ispconfig_password}', $conf['mysql']['master_ispconfig_password'], $content);
1598         $content = str_replace('{mysql_master_server_database}', $conf['mysql']['master_database'], $content);
1599         $content = str_replace('{mysql_master_server_host}', $conf['mysql']['master_host'], $content);
1600
1601         $content = str_replace('{server_id}', $conf['server_id'], $content);
1602         $content = str_replace('{ispconfig_log_priority}', $conf['ispconfig_log_priority'], $content);
1603         $content = str_replace('{language}', $conf['language'], $content);
1604
1605         wf($install_dir.'/server/lib/'.$configfile, $content);
1606
1607         //* Create the config file for remote-actions (but only, if it does not exist, because
1608         //  the value is a autoinc-value and so changed by the remoteaction_core_module
1609         if (!file_exists($install_dir.'/server/lib/remote_action.inc.php')) {
1610             $content = '<?php' . "\n" . '$maxid_remote_action = 0;' . "\n" . '?>';
1611             wf($install_dir.'/server/lib/remote_action.inc.php', $content);
1612         }
1613
1614         //* Enable the server modules and plugins.
1615         // TODO: Implement a selector which modules and plugins shall be enabled.
1616         $dir = $install_dir.'/server/mods-available/';
1617         if (is_dir($dir)) {
1618             if ($dh = opendir($dir)) {
1619                 while (($file = readdir($dh)) !== false) {
1620                     if($file != '.' && $file != '..' && substr($file,-8,8) == '.inc.php') {
1621                         include_once($install_dir.'/server/mods-available/'.$file);
1622                         $module_name = substr($file,0,-8);
1623                         $tmp = new $module_name;
1624                         if($tmp->onInstall()) {
1625                             if(!@is_link($install_dir.'/server/mods-enabled/'.$file)) {
1626                                 @symlink($install_dir.'/server/mods-available/'.$file, $install_dir.'/server/mods-enabled/'.$file);
1627                                 // @symlink($install_dir.'/server/mods-available/'.$file, '../mods-enabled/'.$file);
1628                             }
1629                             if (strpos($file, '_core_module') !== false) {
1630                                 if(!@is_link($install_dir.'/server/mods-core/'.$file)) {
1631                                     @symlink($install_dir.'/server/mods-available/'.$file, $install_dir.'/server/mods-core/'.$file);
1632                                     // @symlink($install_dir.'/server/mods-available/'.$file, '../mods-core/'.$file);
1633                                 }
1634                             }
1635                         }
1636                         unset($tmp);
1637                     }
1638                 }
1639                 closedir($dh);
1640             }
1641         }
1642
1643         $dir = $install_dir.'/server/plugins-available/';
1644         if (is_dir($dir)) {
1645             if ($dh = opendir($dir)) {
1646                 while (($file = readdir($dh)) !== false) {
4ffb51 1647                     if($conf['apache']['installed'] == true && $file == 'nginx_plugin.inc.php') continue;
F 1648                     if($conf['nginx']['installed'] == true && $file == 'apache2_plugin.inc.php') continue;
532ae5 1649                     if($file != '.' && $file != '..' && substr($file,-8,8) == '.inc.php') {
L 1650                         include_once($install_dir.'/server/plugins-available/'.$file);
1651                         $plugin_name = substr($file,0,-8);
1652                         $tmp = new $plugin_name;
1653                         if(method_exists($tmp,'onInstall') && $tmp->onInstall()) {
1654                             if(!@is_link($install_dir.'/server/plugins-enabled/'.$file)) {
1655                                 @symlink($install_dir.'/server/plugins-available/'.$file, $install_dir.'/server/plugins-enabled/'.$file);
1656                                 //@symlink($install_dir.'/server/plugins-available/'.$file, '../plugins-enabled/'.$file);
1657                             }
1658                             if (strpos($file, '_core_plugin') !== false) {
1659                                 if(!@is_link($install_dir.'/server/plugins-core/'.$file)) {
1660                                     @symlink($install_dir.'/server/plugins-available/'.$file, $install_dir.'/server/plugins-core/'.$file);
1661                                     //@symlink($install_dir.'/server/plugins-available/'.$file, '../plugins-core/'.$file);
1662                                 }
1663                             }
1664                         }
1665                         unset($tmp);
1666                     }
1667                 }
1668                 closedir($dh);
1669             }
1670         }
1671
1672         // Update the server config
1673         $mail_server_enabled = ($conf['services']['mail'])?1:0;
1674         $web_server_enabled = ($conf['services']['web'])?1:0;
1675         $dns_server_enabled = ($conf['services']['dns'])?1:0;
1676         $file_server_enabled = ($conf['services']['file'])?1:0;
1677         $db_server_enabled = ($conf['services']['db'])?1:0;
1678         $vserver_server_enabled = ($conf['services']['vserver'])?1:0;
80e3c9 1679         $proxy_server_enabled = ($conf['services']['proxy'])?1:0;
T 1680         $firewall_server_enabled = ($conf['services']['firewall'])?1:0;
532ae5 1681
L 1682
1683
1684
1685
80e3c9 1686         $sql = "UPDATE `server` SET mail_server = '$mail_server_enabled', web_server = '$web_server_enabled', dns_server = '$dns_server_enabled', file_server = '$file_server_enabled', db_server = '$db_server_enabled', vserver_server = '$vserver_server_enabled', proxy_server = '$proxy_server_enabled', firewall_server = '$firewall_server_enabled' WHERE server_id = ".intval($conf['server_id']);
532ae5 1687
L 1688         if($conf['mysql']['master_slave_setup'] == 'y') {
1689             $this->dbmaster->query($sql);
1690             $this->db->query($sql);
1691         } else {
1692             $this->db->query($sql);
1693         }
1694
1695
1696         //* Chmod the files
1697         $command = 'chmod -R 750 '.$install_dir;
1698         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1699
1700         //* chown the files to the ispconfig user and group
1701         $command = 'chown -R ispconfig:ispconfig '.$install_dir;
1702         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1703
1704         //* Make the global language file directory group writable
1705         exec("chmod -R 770 $install_dir/interface/lib/lang");
1706
1707         //* Make the temp directory for language file exports writable
1708         if(is_dir($install_dir.'/interface/web/temp')) exec("chmod -R 770 $install_dir/interface/web/temp");
1709
1710         //* Make all interface language file directories group writable
1711         $handle = @opendir($install_dir.'/interface/web');
1712         while ($file = @readdir ($handle)) {
1713             if ($file != '.' && $file != '..') {
1714                 if(@is_dir($install_dir.'/interface/web'.'/'.$file.'/lib/lang')) {
1715                     $handle2 = opendir($install_dir.'/interface/web'.'/'.$file.'/lib/lang');
1716                     chmod($install_dir.'/interface/web'.'/'.$file.'/lib/lang',0770);
1717                     while ($lang_file = @readdir ($handle2)) {
1718                         if ($lang_file != '.' && $lang_file != '..') {
1719                             chmod($install_dir.'/interface/web'.'/'.$file.'/lib/lang/'.$lang_file,0770);
1720                         }
1721                     }
1722                 }
1723             }
1724         }
1725
1726         //* make sure that the server config file (not the interface one) is only readable by the root user
1727         chmod($install_dir.'/server/lib/'.$configfile, 0600);
1728         chown($install_dir.'/server/lib/'.$configfile, 'root');
1729         chgrp($install_dir.'/server/lib/'.$configfile, 'root');
1730
1731         chmod($install_dir.'/server/lib/remote_action.inc.php', 0600);
1732         chown($install_dir.'/server/lib/remote_action.inc.php', 'root');
1733         chgrp($install_dir.'/server/lib/remote_action.inc.php', 'root');
1734
1735         if(@is_file($install_dir.'/server/lib/mysql_clientdb.conf')) {
1736             chmod($install_dir.'/server/lib/mysql_clientdb.conf', 0600);
1737             chown($install_dir.'/server/lib/mysql_clientdb.conf', 'root');
1738             chgrp($install_dir.'/server/lib/mysql_clientdb.conf', 'root');
1739         }
1740
1741         // TODO: FIXME: add the www-data user to the ispconfig group. This is just for testing
1742         // and must be fixed as this will allow the apache user to read the ispconfig files.
1743         // Later this must run as own apache server or via suexec!
63b369 1744         if($conf['apache']['installed'] == true){
F 1745             $command = 'adduser '.$conf['apache']['user'].' ispconfig';
1746             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1747         }
1748         if($conf['nginx']['installed'] == true){
1749             $command = 'adduser '.$conf['nginx']['user'].' ispconfig';
1750             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1751         }
532ae5 1752
L 1753         //* Make the shell scripts executable
1754         $command = "chmod +x $install_dir/server/scripts/*.sh";
1755         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1756
4ffb51 1757         if($conf['apache']['installed'] == true){
F 1758             //* Copy the ISPConfig vhost for the controlpanel
1759             $vhost_conf_dir = $conf['apache']['vhost_conf_dir'];
1760             $vhost_conf_enabled_dir = $conf['apache']['vhost_conf_enabled_dir'];
532ae5 1761
4ffb51 1762             // Dont just copy over the virtualhost template but add some custom settings
F 1763             $content = rf('tpl/apache_ispconfig.vhost.master');
1764             $content = str_replace('{vhost_port}', $conf['apache']['vhost_port'], $content);
532ae5 1765
4ffb51 1766             // comment out the listen directive if port is 80 or 443
F 1767             if($conf['apache']['vhost_port'] == 80 or $conf['apache']['vhost_port'] == 443) {
1768                 $content = str_replace('{vhost_port_listen}', '#', $content);
1769             } else {
1770                 $content = str_replace('{vhost_port_listen}', '', $content);
1771             }
532ae5 1772         
4ffb51 1773             if(is_file($install_dir.'/interface/ssl/ispserver.crt') && is_file($install_dir.'/interface/ssl/ispserver.key')) {
F 1774                 $content = str_replace('{ssl_comment}', '', $content);
1775             } else {
1776                 $content = str_replace('{ssl_comment}', '#', $content);
1777             }
532ae5 1778
4ffb51 1779             wf($vhost_conf_dir.'/ispconfig.vhost', $content);
532ae5 1780
4ffb51 1781             //copy('tpl/apache_ispconfig.vhost.master', $vhost_conf_dir.'/ispconfig.vhost');
F 1782             //* and create the symlink
1783             if($this->install_ispconfig_interface == true && $this->is_update == false) {
1784                 if(@is_link($vhost_conf_enabled_dir.'/ispconfig.vhost')) unlink($vhost_conf_enabled_dir.'/ispconfig.vhost');
1785                 if(!@is_link($vhost_conf_enabled_dir.'/000-ispconfig.vhost')) {
1786                     symlink($vhost_conf_dir.'/ispconfig.vhost',$vhost_conf_enabled_dir.'/000-ispconfig.vhost');
1787                 }
1788             }
1789             if(!is_file('/var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter')) {
1790                 mkdir('/var/www/php-fcgi-scripts/ispconfig', 0755, true);
1791                 copy('tpl/apache_ispconfig_fcgi_starter.master','/var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter');
1792                 exec('chmod +x /var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter');
1793                 symlink($install_dir.'/interface/web','/var/www/ispconfig');
1794                 exec('chown -R ispconfig:ispconfig /var/www/php-fcgi-scripts/ispconfig');
1795
532ae5 1796             }
L 1797         }
4ffb51 1798         
F 1799         if($conf['nginx']['installed'] == true){
1800             //* Copy the ISPConfig vhost for the controlpanel
1801             $vhost_conf_dir = $conf['nginx']['vhost_conf_dir'];
1802             $vhost_conf_enabled_dir = $conf['nginx']['vhost_conf_enabled_dir'];
532ae5 1803
4ffb51 1804             // Dont just copy over the virtualhost template but add some custom settings
F 1805             $content = rf('tpl/nginx_ispconfig.vhost.master');
1806             $content = str_replace('{vhost_port}', $conf['nginx']['vhost_port'], $content);
1807         
1808             if(is_file($install_dir.'/interface/ssl/ispserver.crt') && is_file($install_dir.'/interface/ssl/ispserver.key')) {
1809                 $content = str_replace('{ssl_on}', ' ssl', $content);
1810                 $content = str_replace('{ssl_comment}', '', $content);
1811                 $content = str_replace('{fastcgi_ssl}', 'on', $content);
1812             } else {
1813                 $content = str_replace('{ssl_on}', '', $content);
1814                 $content = str_replace('{ssl_comment}', '#', $content);
1815                 $content = str_replace('{fastcgi_ssl}', 'off', $content);
1816             }
1817             
ca0b77 1818             $socket_dir = escapeshellcmd($conf['nginx']['php_fpm_socket_dir']);
F 1819             if(substr($socket_dir,-1) != '/') $socket_dir .= '/';
1820             if(!is_dir($socket_dir)) exec('mkdir -p '.$socket_dir);
1821             $fpm_socket = $socket_dir.'ispconfig.sock';
1822             
1823             //$content = str_replace('{fpm_port}', $conf['nginx']['php_fpm_start_port'], $content);
1824             $content = str_replace('{fpm_socket}', $fpm_socket, $content);
1825             
4ffb51 1826             wf($vhost_conf_dir.'/ispconfig.vhost', $content);
F 1827             
1828             unset($content);
1829             
1830             // PHP-FPM
1831             // Dont just copy over the php-fpm pool template but add some custom settings
1832             $content = rf('tpl/php_fpm_pool.conf.master');
1833             $content = str_replace('{fpm_pool}', 'ispconfig', $content);
ca0b77 1834             //$content = str_replace('{fpm_port}', $conf['nginx']['php_fpm_start_port'], $content);
F 1835             $content = str_replace('{fpm_socket}', $fpm_socket, $content);
4ffb51 1836             $content = str_replace('{fpm_user}', 'ispconfig', $content);
F 1837             $content = str_replace('{fpm_group}', 'ispconfig', $content);
1838             wf($conf['nginx']['php_fpm_pool_dir'].'/ispconfig.conf', $content);
1839
1840             //copy('tpl/nginx_ispconfig.vhost.master', $vhost_conf_dir.'/ispconfig.vhost');
1841             //* and create the symlink
1842             if($this->install_ispconfig_interface == true && $this->is_update == false) {
1843                 if(@is_link($vhost_conf_enabled_dir.'/ispconfig.vhost')) unlink($vhost_conf_enabled_dir.'/ispconfig.vhost');
1844                 if(!@is_link($vhost_conf_enabled_dir.'/000-ispconfig.vhost')) {
1845                     symlink($vhost_conf_dir.'/ispconfig.vhost',$vhost_conf_enabled_dir.'/000-ispconfig.vhost');
1846                 }
1847             }
532ae5 1848         }
L 1849
1850         //* Install the update script
1851         if(is_file('/usr/local/bin/ispconfig_update_from_svn.sh')) unlink('/usr/local/bin/ispconfig_update_from_svn.sh');
1852         chown($install_dir.'/server/scripts/update_from_svn.sh', 'root');
1853         chmod($install_dir.'/server/scripts/update_from_svn.sh', 0700);
1854         chown($install_dir.'/server/scripts/update_from_tgz.sh', 'root');
1855         chmod($install_dir.'/server/scripts/update_from_tgz.sh', 0700);
1856         chown($install_dir.'/server/scripts/ispconfig_update.sh', 'root');
1857         chmod($install_dir.'/server/scripts/ispconfig_update.sh', 0700);
1858         if(!is_link('/usr/local/bin/ispconfig_update_from_svn.sh')) symlink($install_dir.'/server/scripts/ispconfig_update.sh','/usr/local/bin/ispconfig_update_from_svn.sh');
1859         if(!is_link('/usr/local/bin/ispconfig_update.sh')) symlink($install_dir.'/server/scripts/ispconfig_update.sh','/usr/local/bin/ispconfig_update.sh');
1860
1861         //* Make the logs readable for the ispconfig user
1862         if(@is_file('/var/log/mail.log')) exec('chmod +r /var/log/mail.log');
1863         if(@is_file('/var/log/mail.warn')) exec('chmod +r /var/log/mail.warn');
1864         if(@is_file('/var/log/mail.err')) exec('chmod +r /var/log/mail.err');
1865         if(@is_file('/var/log/messages')) exec('chmod +r /var/log/messages');
1866         if(@is_file('/var/log/clamav/clamav.log')) exec('chmod +r /var/log/clamav/clamav.log');
1867         if(@is_file('/var/log/clamav/freshclam.log')) exec('chmod +r /var/log/clamav/freshclam.log');
1868
1869         //* Create the ispconfig log file and directory
1870         if(!is_file($conf['ispconfig_log_dir'].'/ispconfig.log')) {
1871             if(!is_dir($conf['ispconfig_log_dir'])) mkdir($conf['ispconfig_log_dir'], 0755);
1872             touch($conf['ispconfig_log_dir'].'/ispconfig.log');
1873         }
0c5b42 1874         
T 1875         if(is_user('getmail')) {
1876             rename($install_dir.'/server/scripts/run-getmail.sh','/usr/local/bin/run-getmail.sh');
1877             if(is_user('getmail')) chown('/usr/local/bin/run-getmail.sh', 'getmail');
1878             chmod('/usr/local/bin/run-getmail.sh', 0744);
1879         }
532ae5 1880
L 1881         //* Add Log-Rotation
1882         if (is_dir('/etc/logrotate.d')) {
1883             @unlink('/etc/logrotate.d/logispc3'); // ignore, if the file is not there
1884             /* We rotate these logs in cron_daily.php
1885             $fh = fopen('/etc/logrotate.d/logispc3', 'w');
1886             fwrite($fh,
1887                     "$conf['ispconfig_log_dir']/ispconfig.log { \n" .
1888                     "    weekly \n" .
1889                     "    missingok \n" .
1890                     "    rotate 4 \n" .
1891                     "    compress \n" .
1892                     "    delaycompress \n" .
1893                     "} \n" .
1894                     "$conf['ispconfig_log_dir']/cron.log { \n" .
1895                     "    weekly \n" .
1896                     "    missingok \n" .
1897                     "    rotate 4 \n" .
1898                     "    compress \n" .
1899                     "    delaycompress \n" .
1900                     "}");
1901             fclose($fh);
1902             */
1903         }
1904     }
1905
1906     public function configure_dbserver() {
1907         global $conf;
1908
1909         //* If this server shall act as database server for client DB's, we configure this here
1910         $install_dir = $conf['ispconfig_install_dir'];
1911
1912         // Create a file with the database login details which
1913         // are used to create the client databases.
1914
1915         if(!is_dir($install_dir.'/server/lib')) {
1916             $command = "mkdir $install_dir/server/lib";
1917             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1918         }
1919
1920         $content = rf('tpl/mysql_clientdb.conf.master');
1921         $content = str_replace('{username}',$conf['mysql']['admin_user'],$content);
1922         $content = str_replace('{password}',$conf['mysql']['admin_password'], $content);
1923         wf($install_dir.'/server/lib/mysql_clientdb.conf',$content);
1924         chmod($install_dir.'/server/lib/mysql_clientdb.conf', 0600);
1925         chown($install_dir.'/server/lib/mysql_clientdb.conf', 'root');
1926         chgrp($install_dir.'/server/lib/mysql_clientdb.conf', 'root');
1927
1928     }
1929
1930     public function install_crontab() {
1931         global $conf;
1932
1933         $install_dir = $conf['ispconfig_install_dir'];
1934
1935         //* Root Crontab
1936         exec('crontab -u root -l > crontab.txt');
1937         $existing_root_cron_jobs = file('crontab.txt');
1938
1939         // remove existing ispconfig cronjobs, in case the syntax has changed
1940         foreach($existing_root_cron_jobs as $key => $val) {
1941             if(stristr($val,$install_dir)) unset($existing_root_cron_jobs[$key]);
1942         }
1943
1944         $root_cron_jobs = array(
1945                 "* * * * * ".$install_dir."/server/server.sh > /dev/null 2>> ".$conf['ispconfig_log_dir']."/cron.log",
1946                 "30 00 * * * ".$install_dir."/server/cron_daily.sh > /dev/null 2>> ".$conf['ispconfig_log_dir']."/cron.log"
1947         );
b6a10a 1948         
F 1949         if ($conf['nginx']['installed'] == true) {
1950             $root_cron_jobs[] = "0 0 * * * ".$install_dir."/server/scripts/create_daily_nginx_access_logs.sh &> /dev/null";
1951         }
1952         
532ae5 1953         foreach($root_cron_jobs as $cron_job) {
L 1954             if(!in_array($cron_job."\n", $existing_root_cron_jobs)) {
1955                 $existing_root_cron_jobs[] = $cron_job."\n";
1956             }
1957         }
1958         file_put_contents('crontab.txt', $existing_root_cron_jobs);
1959         exec('crontab -u root crontab.txt &> /dev/null');
1960         unlink('crontab.txt');
1961
1962         //* Getmail crontab
1963         if(is_user('getmail')) {
1964             $cf = $conf['getmail'];
1965             exec('crontab -u getmail -l > crontab.txt');
1966             $existing_cron_jobs = file('crontab.txt');
1967
1968             $cron_jobs = array(
1969                     '*/5 * * * * /usr/local/bin/run-getmail.sh > /dev/null 2>> '.$conf['ispconfig_log_dir'].'/cron.log'
1970             );
1971
1972             // remove existing ispconfig cronjobs, in case the syntax has changed
1973             foreach($existing_cron_jobs as $key => $val) {
1974                 if(stristr($val,'getmail')) unset($existing_cron_jobs[$key]);
1975             }
1976
1977             foreach($cron_jobs as $cron_job) {
1978                 if(!in_array($cron_job."\n", $existing_cron_jobs)) {
1979                     $existing_cron_jobs[] = $cron_job."\n";
1980                 }
1981             }
1982             file_put_contents('crontab.txt', $existing_cron_jobs);
1983             exec('crontab -u getmail crontab.txt &> /dev/null');
1984             unlink('crontab.txt');
1985         }
1986
1987         touch($conf['ispconfig_log_dir'].'/cron.log');
1988         chmod($conf['ispconfig_log_dir'].'/cron.log', 0666);
1989
1990     }
1991
1992     /**
1993      * Helper function - get the path to a template file based on
1994      * the local part of the filename. Checks first for the existence
1995      * of a distribution specific file and if not found looks in the
1996      * base template folder. Optionally the behaviour can be changed
1997      * by setting the 2nd parameter which will fetch the contents
1998      * of the template file and return it instead of the path. The 3rd
1999      * parameter further extends this behaviour by filtering the contents
2000      * by inserting the ispconfig database credentials using the {} placeholders.
2001      *
2002      * @param string $tLocal local part of filename
2003      * @param bool $tRf
2004      * @param bool $tDBCred
2005      * @return string Relative path to the chosen template file
2006      */
2007     protected function get_template_file($tLocal, $tRf=false, $tDBCred=false) {
2008         global $conf, $dist;
2009
2010         $final_path = '';
2011         $dist_template = 'dist/tpl/'.strtolower($dist['name'])."/$tLocal.master";
2012         if (file_exists($dist_template)) {
2013             $final_path = $dist_template;
2014         } else {
2015             $final_path = "tpl/$tLocal.master";
2016         }
2017
2018         if (!$tRf) {
2019             return $final_path;
2020         } else {
2021             return (!$tDBCred) ? rf($final_path) : $this->insert_db_credentials(rf($final_path));
2022         }
2023     }
2024
2025     /**
2026      * Helper function - writes the contents to a config file
2027      * and performs a backup if the file exist. Additionally
2028      * if the file exists the new file will be given the
2029      * same rights and ownership as the original. Optionally the
2030      * rights and/or ownership can be overriden by appending umask,
2031      * user and group to the parameters. Providing only uid and gid
2032      * values will result in only a chown.
2033      *
2034      * @param $tConf
2035      * @param $tContents
2036      * @return bool
2037      */
2038     protected function write_config_file($tConf, $tContents) {
2039         // Backup config file before writing new contents and stat file
2040         if ( is_file($tConf) ) {
2041             $stat = exec('stat -c \'%a %U %G\' '.escapeshellarg($tConf), $output, $res);
2042             if ($res == 0) { // stat successfull
2043                 list($access, $user, $group) = split(" ", $stat);
2044             }
2045
2046             if ( copy($tConf, $tConf.'~') ) {
2047                 chmod($tConf.'~', 0400);
2048             }
2049         }
2050
2051         wf($tConf, $tContents); // write file
2052
2053         if (func_num_args() >= 4) // override rights and/or ownership
2054         {
2055             $args = func_get_args();
2056             $output = array_slice($args, 2);
2057
2058             switch (sizeof($output)) {
2059                 case 3:
2060                     $umask = array_shift($output);
2061                     if (is_numeric($umask) && preg_match('/^0?[0-7]{3}$/', $umask)) {
2062                         $access = $umask;
2063                     }
2064                 case 2:
2065                     if (is_user($output[0]) && is_group($output[1])) {
2066                         list($user,$group) = $output;
2067                     }
2068                     break;
2069             }
2070         }
2071
2072         if (!empty($user) && !empty($group)) {
2073             chown($tConf, $user);
2074             chgrp($tConf, $group);
2075         }
2076
2077         if (!empty($access)) {
2078             exec("chmod $access $tConf");
2079         }
2080     }
2081
2082     /**
2083      * Helper function - filter the contents of a config
2084      * file by inserting the common ispconfig database
2085      * credentials.
2086      *
2087      * @param $tContents
2088      * @return string
2089      */
2090     protected function insert_db_credentials($tContents) {
2091         global $conf;
2092
2093         $tContents = str_replace('{mysql_server_ispconfig_user}', $conf["mysql"]["ispconfig_user"], $tContents);
2094         $tContents = str_replace('{mysql_server_ispconfig_password}', $conf["mysql"]["ispconfig_password"], $tContents);
2095         $tContents = str_replace('{mysql_server_database}', $conf["mysql"]["database"], $tContents);
2096         $tContents = str_replace('{mysql_server_ip}', $conf["mysql"]["ip"], $tContents);
2097         $tContents = str_replace('{mysql_server_host}',$conf['mysql']['host'], $tContents);
2098         $tContents = str_replace('{mysql_server_port}',$conf["mysql"]["port"], $tContents);
2099
2100         return $tContents;
2101     }
2102 }
2103
5eb43f 2104 ?>