tbrehm
2012-04-05 b2866973a4e79c99f7bc5e9a77c12cee9229babf
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'] == '') {
b28669 161                 caselog("mysql --default-character-set=".escapeshellarg($conf['mysql']['charset'])." -h ".escapeshellarg($conf['mysql']['host'])." -u ".escapeshellarg($conf['mysql']['admin_user'])." ".escapeshellarg($conf['mysql']['database'])." < '".ISPC_INSTALL_ROOT."/install/sql/ispconfig3.sql' &> /dev/null",
532ae5 162                         __FILE__, __LINE__, 'read in ispconfig3.sql', 'could not read in ispconfig3.sql');
L 163             } else {
b28669 164                 caselog("mysql --default-character-set=".escapeshellarg($conf['mysql']['charset'])." -h ".escapeshellarg($conf['mysql']['host'])." -u ".escapeshellarg($conf['mysql']['admin_user'])." -p".escapeshellarg($conf['mysql']['admin_password'])." ".escapeshellarg($conf['mysql']['database'])." < '".ISPC_INSTALL_ROOT."/install/sql/ispconfig3.sql' &> /dev/null",
532ae5 165                         __FILE__, __LINE__, 'read in ispconfig3.sql', 'could not read in ispconfig3.sql');
L 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         }
88273a 517         
T 518         //* help jailkit fo find its ini files
519         if(!is_link('/usr/jk_socketd.ini')) exec('ln -s /etc/jailkit/jk_socketd.ini /usr/jk_socketd.ini');
520         if(!is_link('/usr/jk_init.ini')) exec('ln -s /etc/jailkit/jk_init.ini /usr/jk_init.ini');
532ae5 521
L 522     }
523     
524     public function configure_mailman($status = 'insert') {
525         global $conf;
526
527         $config_dir = $conf['mailman']['config_dir'].'/';
528         $full_file_name = $config_dir.'mm_cfg.py';
529         //* Backup exiting file
530         if(is_file($full_file_name)) {
531             copy($full_file_name, $config_dir.'mm_cfg.py~');
532         }
533         
534         // load files
535         $content = rf('tpl/mm_cfg.py.master');
536         $old_file = rf($full_file_name);
537         
538         $old_options = array();
539         $lines = explode("\n", $old_file); 
540         foreach ($lines as $line)
541         {
8fe9ab 542             if (trim($line) != '' && substr($line, 0, 1) != '#')
532ae5 543             {
8fe9ab 544                 @list($key, $value) = @explode("=", $line);
532ae5 545                 if (!empty($value))
L 546                 {
547                     $key = rtrim($key);
548                     $old_options[$key] = trim($value);
549                 }
550             }
551         }
552         
553         $virtual_domains = '';
554         if($status == 'update')
555         {
556             // create virtual_domains list
557             $domainAll = $this->db->queryAllRecords("SELECT domain FROM mail_mailinglist GROUP BY domain");
558             
8fe9ab 559             if(is_array($domainAll)) {
532ae5 560             foreach($domainAll as $domain)
L 561             {
562                 if ($domainAll[0]['domain'] == $domain['domain'])
563                     $virtual_domains .= "'".$domain['domain']."'";
564                 else
565                     $virtual_domains .= ", '".$domain['domain']."'";
566             }
8fe9ab 567             }
532ae5 568         }
L 569         else
570             $virtual_domains = "' '";
571             
572         $content = str_replace('{hostname}', $conf['hostname'], $content);
46c775 573         if(!isset($old_options['DEFAULT_SERVER_LANGUAGE'])) $old_options['DEFAULT_SERVER_LANGUAGE'] = '';
532ae5 574         $content = str_replace('{default_language}', $old_options['DEFAULT_SERVER_LANGUAGE'], $content);
L 575         $content = str_replace('{virtual_domains}', $virtual_domains, $content);
576
577         wf($full_file_name, $content);
578     }
579
580     public function configure_postfix($options = '') {
581         global $conf;
582         $cf = $conf['postfix'];
583         $config_dir = $cf['config_dir'];
584
585         if(!is_dir($config_dir)) {
586             $this->error("The postfix configuration directory '$config_dir' does not exist.");
587         }
588
589         //* mysql-virtual_domains.cf
590         $this->process_postfix_config('mysql-virtual_domains.cf');
591
592         //* mysql-virtual_forwardings.cf
593         $this->process_postfix_config('mysql-virtual_forwardings.cf');
594
595         //* mysql-virtual_mailboxes.cf
596         $this->process_postfix_config('mysql-virtual_mailboxes.cf');
597
598         //* mysql-virtual_email2email.cf
599         $this->process_postfix_config('mysql-virtual_email2email.cf');
600
601         //* mysql-virtual_transports.cf
602         $this->process_postfix_config('mysql-virtual_transports.cf');
603
604         //* mysql-virtual_recipient.cf
605         $this->process_postfix_config('mysql-virtual_recipient.cf');
606
607         //* mysql-virtual_sender.cf
608         $this->process_postfix_config('mysql-virtual_sender.cf');
609
610         //* mysql-virtual_client.cf
611         $this->process_postfix_config('mysql-virtual_client.cf');
612
613         //* mysql-virtual_relaydomains.cf
614         $this->process_postfix_config('mysql-virtual_relaydomains.cf');
615
616         //* mysql-virtual_relayrecipientmaps.cf
617         $this->process_postfix_config('mysql-virtual_relayrecipientmaps.cf');
618
619         //* Changing mode and group of the new created config files.
620         caselog('chmod o= '.$config_dir.'/mysql-virtual_*.cf* &> /dev/null',
621                 __FILE__, __LINE__, 'chmod on mysql-virtual_*.cf*', 'chmod on mysql-virtual_*.cf* failed');
622         caselog('chgrp '.$cf['group'].' '.$config_dir.'/mysql-virtual_*.cf* &> /dev/null',
623                 __FILE__, __LINE__, 'chgrp on mysql-virtual_*.cf*', 'chgrp on mysql-virtual_*.cf* failed');
624
625         //* Creating virtual mail user and group
626         $command = 'groupadd -g '.$cf['vmail_groupid'].' '.$cf['vmail_groupname'];
627         if(!is_group($cf['vmail_groupname'])) caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
628
629         $command = 'useradd -g '.$cf['vmail_groupname'].' -u '.$cf['vmail_userid'].' '.$cf['vmail_username'].' -d '.$cf['vmail_mailbox_base'].' -m';
630         if(!is_user($cf['vmail_username'])) caselog("$command &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
a017a5 631         
T 632         //* These postconf commands will be executed on installation and update
532ae5 633         $postconf_commands = array (
L 634                 'alias_maps = hash:/etc/aliases, hash:/var/lib/mailman/data/aliases',
635                 'alias_database = hash:/etc/aliases, hash:/var/lib/mailman/data/aliases',
636                 'virtual_alias_domains =',
637                 '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',
638                 'virtual_mailbox_domains = proxy:mysql:'.$config_dir.'/mysql-virtual_domains.cf',
639                 'virtual_mailbox_maps = proxy:mysql:'.$config_dir.'/mysql-virtual_mailboxes.cf',
640                 'virtual_mailbox_base = '.$cf['vmail_mailbox_base'],
641                 'virtual_uid_maps = static:'.$cf['vmail_userid'],
642                 'virtual_gid_maps = static:'.$cf['vmail_groupid'],
643                 'smtpd_sasl_auth_enable = yes',
644                 'broken_sasl_auth_clients = yes',
645                 'smtpd_sasl_authenticated_header = yes',
646                 'smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, check_recipient_access mysql:'.$config_dir.'/mysql-virtual_recipient.cf, reject_unauth_destination',
647                 'smtpd_use_tls = yes',
648                 'smtpd_tls_security_level = may',
649                 'smtpd_tls_cert_file = '.$config_dir.'/smtpd.cert',
650                 'smtpd_tls_key_file = '.$config_dir.'/smtpd.key',
651                 'transport_maps = proxy:mysql:'.$config_dir.'/mysql-virtual_transports.cf',
652                 'relay_domains = mysql:'.$config_dir.'/mysql-virtual_relaydomains.cf',
653                 'relay_recipient_maps = mysql:'.$config_dir.'/mysql-virtual_relayrecipientmaps.cf',
654                 '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',
655                 'smtpd_sender_restrictions = check_sender_access mysql:'.$config_dir.'/mysql-virtual_sender.cf',
656                 'smtpd_client_restrictions = check_client_access mysql:'.$config_dir.'/mysql-virtual_client.cf',
77c68a 657                 'smtpd_client_message_rate_limit = 100',
532ae5 658                 'maildrop_destination_concurrency_limit = 1',
L 659                 'maildrop_destination_recipient_limit   = 1',
660                 'virtual_transport = maildrop',
661                 'header_checks = regexp:'.$config_dir.'/header_checks',
662                 'mime_header_checks = regexp:'.$config_dir.'/mime_header_checks',
663                 'nested_header_checks = regexp:'.$config_dir.'/nested_header_checks',
664                 'body_checks = regexp:'.$config_dir.'/body_checks',
665                 'owner_request_special = no'
666         );
a017a5 667         
T 668         //* These postconf commands will be executed on installation only
669         if($this->is_update == false) {
670             $postconf_commands = array_merge($postconf_commands,array(
671                 'myhostname = '.$conf['hostname'],
672                 'mydestination = '.$conf['hostname'].', localhost, localhost.localdomain',
673                 'mynetworks = 127.0.0.0/8 [::1]/128'
674             ));
675         }
532ae5 676
L 677         //* Create the header and body check files
678         touch($config_dir.'/header_checks');
679         touch($config_dir.'/mime_header_checks');
680         touch($config_dir.'/nested_header_checks');
681         touch($config_dir.'/body_checks');
682         
683         //* Create the mailman files
684         exec('mkdir -p /var/lib/mailman/data');
5378e9 685         if(!is_file('/var/lib/mailman/data/aliases')) touch('/var/lib/mailman/data/aliases');
T 686         exec('postalias /var/lib/mailman/data/aliases');
687         if(!is_file('/var/lib/mailman/data/virtual-mailman')) touch('/var/lib/mailman/data/virtual-mailman');
d4d965 688         exec('postmap /var/lib/mailman/data/virtual-mailman');
532ae5 689
L 690         //* Make a backup copy of the main.cf file
691         copy($config_dir.'/main.cf', $config_dir.'/main.cf~');
692
693         //* Executing the postconf commands
694         foreach($postconf_commands as $cmd) {
695             $command = "postconf -e '$cmd'";
696             caselog($command." &> /dev/null", __FILE__, __LINE__, 'EXECUTED: '.$command, 'Failed to execute the command '.$command);
697         }
698
699         if(!stristr($options,'dont-create-certs')) {
700             //* Create the SSL certificate
701             $command = 'cd '.$config_dir.'; '
1ca823 702                     .'openssl req -new -outform PEM -out smtpd.cert -newkey rsa:2048 -nodes -keyout smtpd.key -keyform PEM -days 3650 -x509';
532ae5 703             exec($command);
L 704
705             $command = 'chmod o= '.$config_dir.'/smtpd.key';
706             caselog($command.' &> /dev/null', __FILE__, __LINE__, 'EXECUTED: '.$command, 'Failed to execute the command '.$command);
707         }
708
709         //** We have to change the permissions of the courier authdaemon directory to make it accessible for maildrop.
710         $command = 'chmod 755  /var/run/courier/authdaemon/';
711         if(is_file('/var/run/courier/authdaemon/')) caselog($command.' &> /dev/null', __FILE__, __LINE__, 'EXECUTED: '.$command, 'Failed to execute the command '.$command);
712
713         //* Changing maildrop lines in posfix master.cf
714         if(is_file($config_dir.'/master.cf')) {
715             copy($config_dir.'/master.cf', $config_dir.'/master.cf~');
716         }
717         if(is_file($config_dir.'/master.cf~')) {
718             chmod($config_dir.'/master.cf~', 0400);
719         }
720         $configfile = $config_dir.'/master.cf';
721         $content = rf($configfile);
722         $content = str_replace('flags=DRhu user=vmail argv=/usr/bin/maildrop -d ${recipient}',
723                 'flags=DRhu user='.$cf['vmail_username'].' argv=/usr/bin/maildrop -d '.$cf['vmail_username'].' ${extension} ${recipient} ${user} ${nexthop} ${sender}',
724                 $content);
725         wf($configfile, $content);
726
727         //* Writing the Maildrop mailfilter file
728         $configfile = 'mailfilter';
729         if(is_file($cf['vmail_mailbox_base'].'/.'.$configfile)) {
730             copy($cf['vmail_mailbox_base'].'/.'.$configfile, $cf['vmail_mailbox_base'].'/.'.$configfile.'~');
731         }
732         $content = rf('tpl/'.$configfile.'.master');
733         $content = str_replace('{dist_postfix_vmail_mailbox_base}', $cf['vmail_mailbox_base'], $content);
734         wf($cf['vmail_mailbox_base'].'/.'.$configfile, $content);
735
736         //* Create the directory for the custom mailfilters
737         if(!is_dir($cf['vmail_mailbox_base'].'/mailfilters')) {
738             $command = 'mkdir '.$cf['vmail_mailbox_base'].'/mailfilters';
739             caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
740         }
741
742         //* Chmod and chown the .mailfilter file
419eb7 743         $command = 'chown '.$cf['vmail_username'].':'.$cf['vmail_groupname'].' '.$cf['vmail_mailbox_base'].'/.mailfilter';
532ae5 744         caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
L 745
419eb7 746         $command = 'chmod 600 '.$cf['vmail_mailbox_base'].'/.mailfilter';
532ae5 747         caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
L 748
749     }
750
751     public function configure_saslauthd() {
752         global $conf;
753
754
755         $configfile = 'sasl_smtpd.conf';
756         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~');
757         if(is_file($conf['postfix']['config_dir'].'/sasl/smtpd.conf~')) chmod($conf['postfix']['config_dir'].'/sasl/smtpd.conf~', 0400);
758         $content = rf('tpl/'.$configfile.'.master');
759         $content = str_replace('{mysql_server_ispconfig_user}',$conf['mysql']['ispconfig_user'],$content);
760         $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content);
761         $content = str_replace('{mysql_server_database}',$conf['mysql']['database'],$content);
762         $content = str_replace('{mysql_server_ip}',$conf['mysql']['ip'],$content);
763         wf($conf['postfix']['config_dir'].'/sasl/smtpd.conf',$content);
764
765         // TODO: Chmod and chown on the config file
766
767
768         // Recursively create the spool directory
769         if(!@is_dir('/var/spool/postfix/var/run/saslauthd')) mkdir('/var/spool/postfix/var/run/saslauthd', 0755, true);
770
771         // Edit the file /etc/default/saslauthd
772         $configfile = $conf['saslauthd']['config'];
773         if(is_file($configfile)) copy($configfile,$configfile.'~');
774         if(is_file($configfile.'~')) chmod($configfile.'~', 0400);
775         $content = rf($configfile);
776         $content = str_replace('START=no','START=yes',$content);
777         // Debian
778         $content = str_replace('OPTIONS="-c"','OPTIONS="-m /var/spool/postfix/var/run/saslauthd -r"',$content);
779         // Ubuntu
780         $content = str_replace('OPTIONS="-c -m /var/run/saslauthd"','OPTIONS="-c -m /var/spool/postfix/var/run/saslauthd -r"',$content);
781         wf($configfile,$content);
782
783         // Edit the file /etc/init.d/saslauthd
784         $configfile = $conf['init_scripts'].'/'.$conf['saslauthd']['init_script'];
785         $content = rf($configfile);
786         $content = str_replace('PIDFILE=$RUN_DIR/saslauthd.pid','PIDFILE="/var/spool/postfix/var/run/${NAME}/saslauthd.pid"',$content);
787         wf($configfile,$content);
788
789         // add the postfix user to the sasl group (at least necessary for Ubuntu 8.04 and most likely Debian Lenny as well.
790         exec('adduser postfix sasl');
791
792
793     }
794
795     public function configure_pam() {
796         global $conf;
797         $pam = $conf['pam'];
798         //* configure pam for SMTP authentication agains the ispconfig database
799         $configfile = 'pamd_smtp';
800         if(is_file($pam.'/smtp'))    copy($pam.'/smtp', $pam.'/smtp~');
801         if(is_file($pam.'/smtp~'))   chmod($pam.'/smtp~', 0400);
802
803         $content = rf('tpl/'.$configfile.'.master');
804         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
805         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
806         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
807         $content = str_replace('{mysql_server_ip}', $conf['mysql']['ip'], $content);
808         wf($pam.'/smtp', $content);
809         // On some OSes smtp is world readable which allows for reading database information.  Removing world readable rights should have no effect.
810         if(is_file($pam.'/smtp'))    exec("chmod o= $pam/smtp");
811         chmod($pam.'/smtp', 0660);
812         chown($pam.'/smtp', 'daemon');
813         chgrp($pam.'/smtp', 'daemon');
814
815     }
816
817     public function configure_courier() {
818         global $conf;
819         $config_dir = $conf['courier']['config_dir'];
820         //* authmysqlrc
821         $configfile = 'authmysqlrc';
822         if(is_file($config_dir.'/'.$configfile)) {
823             copy($config_dir.'/'.$configfile, $config_dir.'/'.$configfile.'~');
824         }
825         chmod($config_dir.'/'.$configfile.'~', 0400);
826         $content = rf('tpl/'.$configfile.'.master');
827         $content = str_replace('{mysql_server_ispconfig_user}',$conf['mysql']['ispconfig_user'],$content);
828         $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content);
829         $content = str_replace('{mysql_server_database}',$conf['mysql']['database'],$content);
830         $content = str_replace('{mysql_server_host}',$conf['mysql']['host'],$content);
831         wf($config_dir.'/'.$configfile, $content);
832
833         chmod($config_dir.'/'.$configfile, 0660);
834         chown($config_dir.'/'.$configfile, 'daemon');
835         chgrp($config_dir.'/'.$configfile, 'daemon');
836
837         //* authdaemonrc
838         $configfile = $config_dir.'/authdaemonrc';
839         if(is_file($configfile)) {
840             copy($configfile, $configfile.'~');
841         }
842         if(is_file($configfile.'~')) {
843             chmod($configfile.'~', 0400);
844         }
845         $content = rf($configfile);
846         $content = str_replace('authmodulelist="authpam"', 'authmodulelist="authmysql"', $content);
847         wf($configfile, $content);
848     }
849
850     public function configure_dovecot() {
851         global $conf;
852
853         $config_dir = $conf['dovecot']['config_dir'];
854
855         //* Configure master.cf and add a line for deliver
856         if(is_file($conf['postfix']['config_dir'].'/master.cf')) {
857             copy($conf['postfix']['config_dir'].'/master.cf', $conf['postfix']['config_dir'].'/master.cf~2');
858         }
859         if(is_file($conf['postfix']['config_dir'].'/master.cf~')) {
860             chmod($conf['postfix']['config_dir'].'/master.cf~2', 0400);
861         }
862         $content = rf($conf['postfix']['config_dir'].'/master.cf');
863         // Only add the content if we had not addded it before
864         if(!stristr($content,'dovecot/deliver')) {
865             $deliver_content = 'dovecot   unix  -       n       n       -       -       pipe'."\n".'  flags=DRhu user=vmail:vmail argv=/usr/lib/dovecot/deliver -f ${sender} -d ${user}@${nexthop}';
866             af($conf['postfix']['config_dir'].'/master.cf',$deliver_content);
867         }
868         unset($content);
869         unset($deliver_content);
870
871
872         //* Reconfigure postfix to use dovecot authentication
873         // Adding the amavisd commands to the postfix configuration
874         $postconf_commands = array (
875                 'dovecot_destination_recipient_limit = 1',
876                 'virtual_transport = dovecot',
877                 'smtpd_sasl_type = dovecot',
878                 'smtpd_sasl_path = private/auth'
879         );
880
881         // Make a backup copy of the main.cf file
882         copy($conf['postfix']['config_dir'].'/main.cf',$conf['postfix']['config_dir'].'/main.cf~3');
883
884         // Executing the postconf commands
885         foreach($postconf_commands as $cmd) {
886             $command = "postconf -e '$cmd'";
887             caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
888         }
889
6cab89 890         //* backup dovecot.conf
532ae5 891         $configfile = 'dovecot.conf';
L 892         if(is_file($config_dir.'/'.$configfile)) {
893             copy($config_dir.'/'.$configfile, $config_dir.'/'.$configfile.'~');
894         }
6cab89 895         
T 896         //* Get the dovecot version
897         exec('dovecot --version',$tmp);
898         $parts = explode('.',trim($tmp[0]));
899         $dovecot_version = $parts[0];
900         unset($tmp);
901         unset($parts);
902         
903         //* Copy dovecot configuration file
904         if($dovecot_version == 2) {
905             copy('tpl/debian_dovecot2.conf.master',$config_dir.'/'.$configfile);
906         } else {
907             copy('tpl/debian_dovecot.conf.master',$config_dir.'/'.$configfile);
908         }
532ae5 909
L 910         //* dovecot-sql.conf
911         $configfile = 'dovecot-sql.conf';
912         if(is_file($config_dir.'/'.$configfile)) {
913             copy($config_dir.'/'.$configfile, $config_dir.'/'.$configfile.'~');
914         }
6eeadd 915         if(is_file($config_dir.'/'.$configfile.'~')) chmod($config_dir.'/'.$configfile.'~', 0400);
532ae5 916         $content = rf('tpl/debian_dovecot-sql.conf.master');
L 917         $content = str_replace('{mysql_server_ispconfig_user}',$conf['mysql']['ispconfig_user'],$content);
918         $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content);
919         $content = str_replace('{mysql_server_database}',$conf['mysql']['database'],$content);
920         $content = str_replace('{mysql_server_host}',$conf['mysql']['host'],$content);
921         wf($config_dir.'/'.$configfile, $content);
922
923         chmod($config_dir.'/'.$configfile, 0600);
924         chown($config_dir.'/'.$configfile, 'root');
925         chgrp($config_dir.'/'.$configfile, 'root');
926
927     }
928
929     public function configure_amavis() {
930         global $conf;
931
932         // amavisd user config file
933         $configfile = 'amavisd_user_config';
934         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~');
935         if(is_file($conf['amavis']['config_dir'].'/conf.d/50-user~')) chmod($conf['amavis']['config_dir'].'/conf.d/50-user~', 0400);
936         $content = rf('tpl/'.$configfile.'.master');
937         $content = str_replace('{mysql_server_ispconfig_user}',$conf['mysql']['ispconfig_user'],$content);
938         $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content);
939         $content = str_replace('{mysql_server_database}',$conf['mysql']['database'],$content);
940         $content = str_replace('{mysql_server_port}',$conf['mysql']['port'],$content);
941         $content = str_replace('{mysql_server_ip}',$conf['mysql']['ip'],$content);
942         wf($conf['amavis']['config_dir'].'/conf.d/50-user',$content);
943
944         // TODO: chmod and chown on the config file
945
946
947         // Adding the amavisd commands to the postfix configuration
864ee2 948         // Add array for no error in foreach and maybe future options
X 949         $postconf_commands = array ();
950         
951         // Check for amavisd -> pure webserver with postfix for mailing without antispam
ac28b5 952         if ($conf['amavis']['installed']) {
864ee2 953             $postconf_commands[] = 'content_filter = amavis:[127.0.0.1]:10024';
X 954             $postconf_commands[] = 'receive_override_options = no_address_mappings';
955         }
532ae5 956
L 957         // Make a backup copy of the main.cf file
958         copy($conf['postfix']['config_dir'].'/main.cf',$conf['postfix']['config_dir'].'/main.cf~2');
959
960         // Executing the postconf commands
961         foreach($postconf_commands as $cmd) {
962             $command = "postconf -e '$cmd'";
963             caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
964         }
965
966         // Append the configuration for amavisd to the master.cf file
967         if(is_file($conf['postfix']['config_dir'].'/master.cf')) copy($conf['postfix']['config_dir'].'/master.cf',$conf['postfix']['config_dir'].'/master.cf~');
968         $content = rf($conf['postfix']['config_dir'].'/master.cf');
969         // Only add the content if we had not addded it before
970         if(!stristr($content,'127.0.0.1:10025')) {
971             unset($content);
972             $content = rf('tpl/master_cf_amavis.master');
973             af($conf['postfix']['config_dir'].'/master.cf',$content);
974         }
975         unset($content);
976
977         // Add the clamav user to the amavis group
978         exec('adduser clamav amavis');
979
980
981     }
982
983     public function configure_spamassassin() {
984         global $conf;
985
986         //* Enable spamasasssin on debian and ubuntu
987         $configfile = '/etc/default/spamassassin';
988         if(is_file($configfile)) {
989             copy($configfile, $configfile.'~');
990         }
991         $content = rf($configfile);
992         $content = str_replace('ENABLED=0', 'ENABLED=1', $content);
993         wf($configfile, $content);
994     }
995
996     public function configure_getmail() {
997         global $conf;
998
999         $config_dir = $conf['getmail']['config_dir'];
1000
1001         if(!@is_dir($config_dir)) mkdir(escapeshellcmd($config_dir), 0700, true);
1002
1003         $command = 'useradd -d '.$config_dir.' getmail';
1004         if(!is_user('getmail')) caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1005
1006         $command = "chown -R getmail $config_dir";
1007         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1008
1009         $command = "chmod -R 700 $config_dir";
1010         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1011     }
1012
1013
1014     public function configure_pureftpd() {
1015         global $conf;
1016
1017         $config_dir = $conf['pureftpd']['config_dir'];
1018
1019         //* configure pure-ftpd for MySQL authentication against the ispconfig database
1020         $configfile = 'db/mysql.conf';
1021         if(is_file($config_dir.'/'.$configfile)) {
1022             copy($config_dir.'/'.$configfile, $config_dir.'/'.$configfile.'~');
1023         }
1024         if(is_file($config_dir.'/'.$configfile.'~')) {
1025             chmod($config_dir.'/'.$configfile.'~', 0400);
1026         }
1027         $content = rf('tpl/pureftpd_mysql.conf.master');
1028         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
1029         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1030         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
1031         $content = str_replace('{mysql_server_ip}', $conf['mysql']['ip'], $content);
1032         $content = str_replace('{server_id}', $conf['server_id'], $content);
1033         wf($config_dir.'/'.$configfile, $content);
1034         chmod($config_dir.'/'.$configfile, 0600);
1035         chown($config_dir.'/'.$configfile, 'root');
1036         chgrp($config_dir.'/'.$configfile, 'root');
1037         // **enable chrooting
1038         //exec('mkdir -p '.$config_dir.'/conf/ChrootEveryone');
1039         exec('echo "yes" > '.$config_dir.'/conf/ChrootEveryone');
1040         exec('echo "yes" > '.$config_dir.'/conf/BrokenClientsCompatibility');
1041         exec('echo "yes" > '.$config_dir.'/conf/DisplayDotFiles');
1042
1043         if(is_file('/etc/default/pure-ftpd-common')) {
1044             replaceLine('/etc/default/pure-ftpd-common','STANDALONE_OR_INETD=inetd','STANDALONE_OR_INETD=standalone',1,0);
1045             replaceLine('/etc/default/pure-ftpd-common','VIRTUALCHROOT=false','VIRTUALCHROOT=true',1,0);
1046         }
1047
1048         if(is_file('/etc/inetd.conf')) {
1049             replaceLine('/etc/inetd.conf','/usr/sbin/pure-ftpd-wrapper','#ftp     stream  tcp     nowait  root    /usr/sbin/tcpd /usr/sbin/pure-ftpd-wrapper',0,0);
1050             if(is_file($conf['init_scripts'].'/'.'openbsd-inetd')) exec($conf['init_scripts'].'/'.'openbsd-inetd restart');
1051         }
1052
1053         if(!is_file('/etc/pure-ftpd/conf/DontResolve')) exec('echo "yes" > /etc/pure-ftpd/conf/DontResolve');
1054     }
1055
1056     public function configure_mydns() {
1057         global $conf;
1058
1059         // configure pam for SMTP authentication agains the ispconfig database
1060         $configfile = 'mydns.conf';
1061         if(is_file($conf['mydns']['config_dir'].'/'.$configfile)) copy($conf['mydns']['config_dir'].'/'.$configfile,$conf['mydns']['config_dir'].'/'.$configfile.'~');
1062         if(is_file($conf['mydns']['config_dir'].'/'.$configfile.'~')) chmod($conf['mydns']['config_dir'].'/'.$configfile.'~', 0400);
1063         $content = rf('tpl/'.$configfile.'.master');
1064         $content = str_replace('{mysql_server_ispconfig_user}',$conf['mysql']['ispconfig_user'],$content);
1065         $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content);
1066         $content = str_replace('{mysql_server_database}',$conf['mysql']['database'],$content);
1067         $content = str_replace('{mysql_server_host}',$conf['mysql']['host'],$content);
1068         $content = str_replace('{server_id}',$conf['server_id'],$content);
1069         wf($conf['mydns']['config_dir'].'/'.$configfile,$content);
1070         chmod($conf['mydns']['config_dir'].'/'.$configfile, 0600);
1071         chown($conf['mydns']['config_dir'].'/'.$configfile, 'root');
1072         chgrp($conf['mydns']['config_dir'].'/'.$configfile, 'root');
1073
1074     }
1075
1076     public function configure_powerdns() {
1077         global $conf;
1078
1079         //* Create the database
1080         if(!$this->db->query('CREATE DATABASE IF NOT EXISTS '.$conf['powerdns']['database'].' DEFAULT CHARACTER SET '.$conf['mysql']['charset'])) {
1081             $this->error('Unable to create MySQL database: '.$conf['powerdns']['database'].'.');
1082         }
1083
1084         //* Create the ISPConfig database user in the local database
1085         $query = "GRANT ALL ON `".$conf['powerdns']['database']."` . * TO '".$conf['mysql']['ispconfig_user']."'@'localhost';";
1086         if(!$this->db->query($query)) {
1087             $this->error('Unable to create user for powerdns database Error: '.$this->db->errorMessage);
1088         }
1089
1090         //* Reload database privelages
1091         $this->db->query('FLUSH PRIVILEGES;');
1092
1093         //* load the powerdns databse dump
1094         if($conf['mysql']['admin_password'] == '') {
1095             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",
1096                     __FILE__, __LINE__, 'read in ispconfig3.sql', 'could not read in powerdns.sql');
1097         } else {
1098             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",
1099                     __FILE__, __LINE__, 'read in ispconfig3.sql', 'could not read in powerdns.sql');
1100         }
1101
1102         //* Create the powerdns config file
1103         $configfile = 'pdns.local';
1104         if(is_file($conf['powerdns']['config_dir'].'/'.$configfile)) copy($conf['powerdns']['config_dir'].'/'.$configfile,$conf['powerdns']['config_dir'].'/'.$configfile.'~');
1105         if(is_file($conf['powerdns']['config_dir'].'/'.$configfile.'~')) chmod($conf['powerdns']['config_dir'].'/'.$configfile.'~', 0400);
1106         $content = rf('tpl/'.$configfile.'.master');
1107         $content = str_replace('{mysql_server_ispconfig_user}',$conf['mysql']['ispconfig_user'],$content);
1108         $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content);
1109         $content = str_replace('{powerdns_database}',$conf['powerdns']['database'],$content);
1110         $content = str_replace('{mysql_server_host}',$conf['mysql']['host'],$content);
1111         wf($conf['powerdns']['config_dir'].'/'.$configfile,$content);
1112         chmod($conf['powerdns']['config_dir'].'/'.$configfile, 0600);
1113         chown($conf['powerdns']['config_dir'].'/'.$configfile, 'root');
1114         chgrp($conf['powerdns']['config_dir'].'/'.$configfile, 'root');
1115
1116
1117     }
1118
1119     public function configure_bind() {
1120         global $conf;
1121
1122         //* Check if the zonefile directory has a slash at the end
1123         $content=$conf['bind']['bind_zonefiles_dir'];
1124         if(substr($content,-1,1) != '/') {
1125             $content .= '/';
1126         }
1127
1128         //* Create the slave subdirectory
1129         $content .= 'slave';
1130         if(!@is_dir($content)) mkdir($content, 0770, true);
1131
1132         //* Chown the slave subdirectory to $conf['bind']['bind_user']
1133         chown($content, $conf['bind']['bind_user']);
1134         chgrp($content, $conf['bind']['bind_group']);
1135
1136     }
1137
1138
1139
1140     public function configure_apache() {
1141         global $conf;
1142
4ffb51 1143         if($conf['apache']['installed'] == false) return;
532ae5 1144         //* Create the logging directory for the vhost logfiles
L 1145         if(!@is_dir($conf['ispconfig_log_dir'].'/httpd')) mkdir($conf['ispconfig_log_dir'].'/httpd', 0755, true);
1146
1147         if(is_file('/etc/suphp/suphp.conf')) {
1148             replaceLine('/etc/suphp/suphp.conf','php=php:/usr/bin','x-httpd-suphp="php:/usr/bin/php-cgi"',0);
1149             //replaceLine('/etc/suphp/suphp.conf','docroot=','docroot=/var/clients',0);
1150             replaceLine('/etc/suphp/suphp.conf','umask=0077','umask=0022',0);
1151         }
1152
1153         if(is_file('/etc/apache2/sites-enabled/000-default')) {
1154             replaceLine('/etc/apache2/sites-available/000-default','NameVirtualHost *','NameVirtualHost *:80',1,0);
1155             replaceLine('/etc/apache2/sites-available/000-default','<VirtualHost *>','<VirtualHost *:80>',1,0);
1156         }
1157
1158         if(is_file('/etc/apache2/ports.conf')) {
1159             // add a line "Listen 443" to ports conf if line does not exist
1160             replaceLine('/etc/apache2/ports.conf','Listen 443','Listen 443',1);
1161         }
1162
1163
1164         //* Copy the ISPConfig configuration include
1165         $vhost_conf_dir = $conf['apache']['vhost_conf_dir'];
1166         $vhost_conf_enabled_dir = $conf['apache']['vhost_conf_enabled_dir'];
1167
1168         // copy('tpl/apache_ispconfig.conf.master',$vhost_conf_dir.'/ispconfig.conf');
a2156e 1169         
532ae5 1170         $content = rf('tpl/apache_ispconfig.conf.master');
L 1171         $records = $this->db->queryAllRecords('SELECT * FROM '.$conf['mysql']['master_database'].'.server_ip WHERE server_id = '.$conf['server_id']." AND virtualhost = 'y'");
a2156e 1172
532ae5 1173         if(is_array($records) && count($records) > 0) {
L 1174             foreach($records as $rec) {
a2156e 1175                 if($rec['ip_type'] == 'IPv6') {
T 1176                     $ip_address = '['.$rec['ip_address'].']';
1177                 } else {
1178                     $ip_address = $rec['ip_address'];
1179                 }
1180                 $ports = explode(',',$rec['virtualhost_port']);
1181                 if(is_array($ports)) {
1182                     foreach($ports as $port) {
1183                         $port = intval($port);
1184                         if($port > 0 && $port < 65536 && $ip_address != '') {
1185                             $content .= 'NameVirtualHost '.$ip_address.":".$port."\n";
1186                         }
1187                     }
1188                 }
532ae5 1189             }
L 1190         }
a2156e 1191         
532ae5 1192         $content .= "\n";
L 1193         wf($vhost_conf_dir.'/ispconfig.conf',$content);
1194
1195         if(!@is_link($vhost_conf_enabled_dir.'/000-ispconfig.conf')) {
1196             symlink($vhost_conf_dir.'/ispconfig.conf',$vhost_conf_enabled_dir.'/000-ispconfig.conf');
1197         }
1198
1199         //* make sure that webalizer finds its config file when it is directly in /etc
1200         if(@is_file('/etc/webalizer.conf') && !@is_dir('/etc/webalizer')) {
1201             mkdir('/etc/webalizer');
1202             symlink('/etc/webalizer.conf','/etc/webalizer/webalizer.conf');
1203         }
1204
1205         if(is_file('/etc/webalizer/webalizer.conf')) {
1206             // Change webalizer mode to incremental
1207             replaceLine('/etc/webalizer/webalizer.conf','#IncrementalName','IncrementalName webalizer.current',0,0);
1208             replaceLine('/etc/webalizer/webalizer.conf','#Incremental','Incremental     yes',0,0);
1209             replaceLine('/etc/webalizer/webalizer.conf','#HistoryName','HistoryName     webalizer.hist',0,0);
1210         }
1211         
1212         // Check the awsatst script
1213         if(!is_dir('/usr/share/awstats/tools')) exec('mkdir -p /usr/share/awstats/tools');
1214         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 1215         if(file_exists('/etc/awstats/awstats.conf.local')) replaceLine('/etc/awstats/awstats.conf.local','LogFormat=4','LogFormat=1',0,1);
T 1216         
532ae5 1217         //* add a sshusers group
L 1218         $command = 'groupadd sshusers';
1219         if(!is_group('sshusers')) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1220
1221     }
80e3c9 1222     
4ffb51 1223     public function configure_nginx(){
80e3c9 1224         global $conf;
4ffb51 1225         
F 1226         if($conf['nginx']['installed'] == false) return;
1227         //* Create the logging directory for the vhost logfiles
1228         if(!@is_dir($conf['ispconfig_log_dir'].'/httpd')) mkdir($conf['ispconfig_log_dir'].'/httpd', 0755, true);
1229
1230         //* make sure that webalizer finds its config file when it is directly in /etc
1231         if(@is_file('/etc/webalizer.conf') && !@is_dir('/etc/webalizer')) {
1232             mkdir('/etc/webalizer');
1233             symlink('/etc/webalizer.conf','/etc/webalizer/webalizer.conf');
1234         }
1235
1236         if(is_file('/etc/webalizer/webalizer.conf')) {
1237             // Change webalizer mode to incremental
1238             replaceLine('/etc/webalizer/webalizer.conf','#IncrementalName','IncrementalName webalizer.current',0,0);
1239             replaceLine('/etc/webalizer/webalizer.conf','#Incremental','Incremental     yes',0,0);
1240             replaceLine('/etc/webalizer/webalizer.conf','#HistoryName','HistoryName     webalizer.hist',0,0);
1241         }
1242         
1243         // Check the awsatst script
1244         if(!is_dir('/usr/share/awstats/tools')) exec('mkdir -p /usr/share/awstats/tools');
1245         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');
1246         if(file_exists('/etc/awstats/awstats.conf.local')) replaceLine('/etc/awstats/awstats.conf.local','LogFormat=4','LogFormat=1',0,1);
1247         
1248         //* add a sshusers group
1249         $command = 'groupadd sshusers';
1250         if(!is_group('sshusers')) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1251         
1252         /*
80e3c9 1253         $row = $this->db->queryOneRecord("SELECT server_name FROM server WHERE server_id = ".$conf["server_id"]."");
T 1254         $ip_address = gethostbyname($row["server_name"]);
1255         $server_name = $row["server_name"];
1256
1257         //setup proxy.conf
1258         $configfile = 'proxy.conf';
1259         if(is_file($conf["nginx"]["config_dir"].'/'.$configfile)) copy($conf["nginx"]["config_dir"].'/'.$configfile,$conf["nginx"]["config_dir"].'/'.$configfile.'~');
1260         if(is_file($conf["nginx"]["config_dir"].'/'.$configfile.'~')) exec('chmod 400 '.$conf["nginx"]["config_dir"].'/'.$configfile.'~');
1261         $content = rf("tpl/nginx_".$configfile.".master");
1262         wf($conf["nginx"]["config_dir"].'/'.$configfile,$content);
1263         exec('chmod 600 '.$conf["nginx"]["config_dir"].'/'.$configfile);
1264         exec('chown root:root '.$conf["nginx"]["config_dir"].'/'.$configfile);
1265
1266         //setup conf.d/cache.conf
1267         $configfile = 'cache.conf';
1268         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.'~');
1269         if(is_file($conf["nginx"]["config_dir"].'/conf.d/'.$configfile.'~')) exec('chmod 400 '.$conf["nginx"]["config_dir"].'/conf.d/'.$configfile.'~');
1270         $content = rf("tpl/nginx_".$configfile.".master");
1271         wf($conf["nginx"]["config_dir"].'/conf.d/'.$configfile,$content);
1272         exec('chmod 600 '.$conf["nginx"]["config_dir"].'/conf.d/'.$configfile);
1273         exec('chown root:root '.$conf["nginx"]["config_dir"].'/conf.d/'.$configfile);
1274
1275         //setup cache directories
1276         mkdir('/var/cache/nginx/cache');
1277         exec('chown www-data:www-data /var/cache/nginx/cache');
1278         mkdir('/var/cache/nginx/temp');
1279         exec('chown www-data:www-data /var/cache/nginx/temp');
4ffb51 1280         */
80e3c9 1281     }
T 1282     
d083f2 1283     public function configure_fail2ban() {
F 1284         // To Do
1285     }
1286     
80e3c9 1287     public function configure_squid()
T 1288     {
1289         global $conf;
1290         $row = $this->db->queryOneRecord("SELECT server_name FROM server WHERE server_id = ".$conf["server_id"]."");
1291         $ip_address = gethostbyname($row["server_name"]);
1292         $server_name = $row["server_name"];
1293         
1294         $configfile = 'squid.conf';
1295         if(is_file($conf["squid"]["config_dir"].'/'.$configfile)) copy($conf["squid"]["config_dir"].'/'.$configfile,$conf["squid"]["config_dir"].'/'.$configfile.'~');
1296         if(is_file($conf["squid"]["config_dir"].'/'.$configfile.'~')) exec('chmod 400 '.$conf["squid"]["config_dir"].'/'.$configfile.'~');
1297         $content = rf("tpl/".$configfile.".master");
1298         $content = str_replace('{server_name}',$server_name,$content);
1299         $content = str_replace('{ip_address}',$ip_address, $content);
1300         $content = str_replace('{config_dir}',$conf['squid']['config_dir'], $content);
1301         wf($conf["squid"]["config_dir"].'/'.$configfile,$content);
1302         exec('chmod 600 '.$conf["squid"]["config_dir"].'/'.$configfile);
1303         exec('chown root:root '.$conf["squid"]["config_dir"].'/'.$configfile);
1304     }
1305     
c91bdc 1306     /*
80e3c9 1307     public function configure_ufw_firewall()
T 1308     {
1309         $configfile = 'ufw.conf';
1310         if(is_file('/etc/ufw/ufw.conf')) copy('/etc/ufw/ufw.conf','/etc/ufw/ufw.conf~');
1311         $content = rf("tpl/".$configfile.".master");
1312         wf('/etc/ufw/ufw.conf',$content);
1313         exec('chmod 600 /etc/ufw/ufw.conf');
1314         exec('chown root:root /etc/ufw/ufw.conf');    
1315     }
c91bdc 1316     */
532ae5 1317
L 1318     public function configure_firewall() {
1319         global $conf;
1320
1321         $dist_init_scripts = $conf['init_scripts'];
1322
1323         if(is_dir('/etc/Bastille.backup')) caselog('rm -rf /etc/Bastille.backup', __FILE__, __LINE__);
1324         if(is_dir('/etc/Bastille')) caselog('mv -f /etc/Bastille /etc/Bastille.backup', __FILE__, __LINE__);
1325         @mkdir('/etc/Bastille', 0700);
1326         if(is_dir('/etc/Bastille.backup/firewall.d')) caselog('cp -pfr /etc/Bastille.backup/firewall.d /etc/Bastille/', __FILE__, __LINE__);
1327         caselog('cp -f tpl/bastille-firewall.cfg.master /etc/Bastille/bastille-firewall.cfg', __FILE__, __LINE__);
1328         caselog('chmod 644 /etc/Bastille/bastille-firewall.cfg', __FILE__, __LINE__);
1329         $content = rf('/etc/Bastille/bastille-firewall.cfg');
1330         $content = str_replace('{DNS_SERVERS}', '', $content);
1331
1332         $tcp_public_services = '';
1333         $udp_public_services = '';
1334
1335         $row = $this->db->queryOneRecord('SELECT * FROM '.$conf["mysql"]["database"].'.firewall WHERE server_id = '.intval($conf['server_id']));
1336
1337         if(trim($row['tcp_port']) != '' || trim($row['udp_port']) != '') {
1338             $tcp_public_services = trim(str_replace(',',' ',$row['tcp_port']));
1339             $udp_public_services = trim(str_replace(',',' ',$row['udp_port']));
1340         } else {
1341             $tcp_public_services = '21 22 25 53 80 110 143 443 3306 8080 10000';
1342             $udp_public_services = '53';
1343         }
1344
1345         if(!stristr($tcp_public_services, $conf['apache']['vhost_port'])) {
1346             $tcp_public_services .= ' '.intval($conf['apache']['vhost_port']);
1347             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']));
1348         }
1349
1350         $content = str_replace('{TCP_PUBLIC_SERVICES}', $tcp_public_services, $content);
1351         $content = str_replace('{UDP_PUBLIC_SERVICES}', $udp_public_services, $content);
1352
1353         wf('/etc/Bastille/bastille-firewall.cfg', $content);
1354
1355         if(is_file($dist_init_scripts.'/bastille-firewall')) caselog('mv -f '.$dist_init_scripts.'/bastille-firewall '.$dist_init_scripts.'/bastille-firewall.backup', __FILE__, __LINE__);
1356         caselog('cp -f apps/bastille-firewall '.$dist_init_scripts, __FILE__, __LINE__);
1357         caselog('chmod 700 '.$dist_init_scripts.'/bastille-firewall', __FILE__, __LINE__);
1358
1359         if(is_file('/sbin/bastille-ipchains')) caselog('mv -f /sbin/bastille-ipchains /sbin/bastille-ipchains.backup', __FILE__, __LINE__);
1360         caselog('cp -f apps/bastille-ipchains /sbin', __FILE__, __LINE__);
1361         caselog('chmod 700 /sbin/bastille-ipchains', __FILE__, __LINE__);
1362
1363         if(is_file('/sbin/bastille-netfilter')) caselog('mv -f /sbin/bastille-netfilter /sbin/bastille-netfilter.backup', __FILE__, __LINE__);
1364         caselog('cp -f apps/bastille-netfilter /sbin', __FILE__, __LINE__);
1365         caselog('chmod 700 /sbin/bastille-netfilter', __FILE__, __LINE__);
1366
1367         if(!@is_dir('/var/lock/subsys')) caselog('mkdir /var/lock/subsys', __FILE__, __LINE__);
1368
1369         exec('which ipchains &> /dev/null', $ipchains_location, $ret_val);
1370         if(!is_file('/sbin/ipchains') && !is_link('/sbin/ipchains') && $ret_val == 0) phpcaselog(@symlink(shell_exec('which ipchains'), '/sbin/ipchains'), 'create symlink', __FILE__, __LINE__);
1371         unset($ipchains_location);
1372         exec('which iptables &> /dev/null', $iptables_location, $ret_val);
1373         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__);
1374         unset($iptables_location);
1375
1376     }
1377
1378     public function configure_vlogger() {
1379         global $conf;
1380
1381         //** Configure vlogger to use traffic logging to mysql (master) db
1382         $configfile = 'vlogger-dbi.conf';
1383         if(is_file($conf['vlogger']['config_dir'].'/'.$configfile)) copy($conf['vlogger']['config_dir'].'/'.$configfile,$conf['vlogger']['config_dir'].'/'.$configfile.'~');
1384         if(is_file($conf['vlogger']['config_dir'].'/'.$configfile.'~')) chmod($conf['vlogger']['config_dir'].'/'.$configfile.'~', 0400);
1385         $content = rf('tpl/'.$configfile.'.master');
1386         if($conf['mysql']['master_slave_setup'] == 'y') {
1387             $content = str_replace('{mysql_server_ispconfig_user}',$conf['mysql']['master_ispconfig_user'],$content);
1388             $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['master_ispconfig_password'], $content);
1389             $content = str_replace('{mysql_server_database}',$conf['mysql']['master_database'],$content);
1390             $content = str_replace('{mysql_server_ip}',$conf['mysql']['master_host'],$content);
1391         } else {
1392             $content = str_replace('{mysql_server_ispconfig_user}',$conf['mysql']['ispconfig_user'],$content);
1393             $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content);
1394             $content = str_replace('{mysql_server_database}',$conf['mysql']['database'],$content);
1395             $content = str_replace('{mysql_server_ip}',$conf['mysql']['host'],$content);
1396         }
1397         wf($conf['vlogger']['config_dir'].'/'.$configfile,$content);
1398         chmod($conf['vlogger']['config_dir'].'/'.$configfile, 0600);
1399         chown($conf['vlogger']['config_dir'].'/'.$configfile, 'root');
1400         chgrp($conf['vlogger']['config_dir'].'/'.$configfile, 'root');
1401
1402     }
1403
1404     public function configure_apps_vhost() {
1405         global $conf;
1406
1407         //* Create the ispconfig apps vhost user and group
4ffb51 1408         if($conf['apache']['installed'] == true){
F 1409             $apps_vhost_user = escapeshellcmd($conf['web']['apps_vhost_user']);
1410             $apps_vhost_group = escapeshellcmd($conf['web']['apps_vhost_group']);
1411             $install_dir = escapeshellcmd($conf['web']['website_basedir'].'/apps');
532ae5 1412
4ffb51 1413             $command = 'groupadd '.$apps_vhost_user;
F 1414             if(!is_group($apps_vhost_group)) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
532ae5 1415
4ffb51 1416             $command = 'useradd -g '.$apps_vhost_group.' -d '.$install_dir.' '.$apps_vhost_group;
F 1417             if(!is_user($apps_vhost_user)) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
532ae5 1418
L 1419
4ffb51 1420             $command = 'adduser '.$conf['apache']['user'].' '.$apps_vhost_group;
F 1421             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
532ae5 1422
99b55b 1423             if(!@is_dir($install_dir)){
F 1424                 mkdir($install_dir, 0755, true);
1425             } else {
1426                 chmod($install_dir, 0755);
1427             }
4ffb51 1428             chown($install_dir, $apps_vhost_user);
F 1429             chgrp($install_dir, $apps_vhost_group);
532ae5 1430
4ffb51 1431             //* Copy the apps vhost file
F 1432             $vhost_conf_dir = $conf['apache']['vhost_conf_dir'];
1433             $vhost_conf_enabled_dir = $conf['apache']['vhost_conf_enabled_dir'];
1434             $apps_vhost_servername = ($conf['web']['apps_vhost_servername'] == '')?'':'ServerName '.$conf['web']['apps_vhost_servername'];
532ae5 1435
4ffb51 1436             // Dont just copy over the virtualhost template but add some custom settings
F 1437             $content = rf('tpl/apache_apps.vhost.master');
532ae5 1438
4ffb51 1439             $content = str_replace('{apps_vhost_ip}', $conf['web']['apps_vhost_ip'], $content);
F 1440             $content = str_replace('{apps_vhost_port}', $conf['web']['apps_vhost_port'], $content);
1441             $content = str_replace('{apps_vhost_dir}', $conf['web']['website_basedir'].'/apps', $content);
1442             $content = str_replace('{website_basedir}', $conf['web']['website_basedir'], $content);
1443             $content = str_replace('{apps_vhost_servername}', $apps_vhost_servername, $content);
532ae5 1444
L 1445
4ffb51 1446             // comment out the listen directive if port is 80 or 443
F 1447             if($conf['web']['apps_vhost_ip'] == 80 or $conf['web']['apps_vhost_ip'] == 443) {
1448                 $content = str_replace('{vhost_port_listen}', '#', $content);
1449             } else {
1450                 $content = str_replace('{vhost_port_listen}', '', $content);
1451             }
532ae5 1452
4ffb51 1453             wf($vhost_conf_dir.'/apps.vhost', $content);
532ae5 1454
4ffb51 1455             //copy('tpl/apache_ispconfig.vhost.master', "$vhost_conf_dir/ispconfig.vhost");
F 1456             //* and create the symlink
1457             if($this->install_ispconfig_interface == true) {
1458                 if(@is_link($vhost_conf_enabled_dir.'/apps.vhost')) unlink($vhost_conf_enabled_dir.'/apps.vhost');
1459                 if(!@is_link($vhost_conf_enabled_dir.'/000-apps.vhost')) {
1460                     symlink($vhost_conf_dir.'/apps.vhost',$vhost_conf_enabled_dir.'/000-apps.vhost');
1461                 }
1462             }
1463             if(!is_file($conf['web']['website_basedir'].'/php-fcgi-scripts/apps/.php-fcgi-starter')) {
1464                 mkdir($conf['web']['website_basedir'].'/php-fcgi-scripts/apps', 0755, true);
1465                 copy('tpl/apache_apps_fcgi_starter.master',$conf['web']['website_basedir'].'/php-fcgi-scripts/apps/.php-fcgi-starter');
1466                 exec('chmod +x '.$conf['web']['website_basedir'].'/php-fcgi-scripts/apps/.php-fcgi-starter');
1467                 exec('chown -R ispapps:ispapps '.$conf['web']['website_basedir'].'/php-fcgi-scripts/apps');
1468
532ae5 1469             }
L 1470         }
4ffb51 1471         if($conf['nginx']['installed'] == true){
F 1472             $apps_vhost_user = escapeshellcmd($conf['web']['apps_vhost_user']);
1473             $apps_vhost_group = escapeshellcmd($conf['web']['apps_vhost_group']);
1474             $install_dir = escapeshellcmd($conf['web']['website_basedir'].'/apps');
532ae5 1475
4ffb51 1476             $command = 'groupadd '.$apps_vhost_user;
F 1477             if(!is_group($apps_vhost_group)) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1478
1479             $command = 'useradd -g '.$apps_vhost_group.' -d '.$install_dir.' '.$apps_vhost_group;
1480             if(!is_user($apps_vhost_user)) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1481
1482
1483             $command = 'adduser '.$conf['nginx']['user'].' '.$apps_vhost_group;
1484             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1485
6e2d48 1486             if(!@is_dir($install_dir)){
F 1487                 mkdir($install_dir, 0755, true);
1488             } else {
1489                 chmod($install_dir, 0755);
1490             }
4ffb51 1491             chown($install_dir, $apps_vhost_user);
F 1492             chgrp($install_dir, $apps_vhost_group);
1493
1494             //* Copy the apps vhost file
1495             $vhost_conf_dir = $conf['nginx']['vhost_conf_dir'];
1496             $vhost_conf_enabled_dir = $conf['nginx']['vhost_conf_enabled_dir'];
1497             $apps_vhost_servername = ($conf['web']['apps_vhost_servername'] == '')?'_':$conf['web']['apps_vhost_servername'];
1498
1499             // Dont just copy over the virtualhost template but add some custom settings
1500             $content = rf('tpl/nginx_apps.vhost.master');
1501             
1502             if($conf['web']['apps_vhost_ip'] == '_default_'){
1503                 $apps_vhost_ip = '';
1504             } else {
1505                 $apps_vhost_ip = $conf['web']['apps_vhost_ip'].':';
1506             }
ca0b77 1507             
F 1508             $socket_dir = escapeshellcmd($conf['nginx']['php_fpm_socket_dir']);
1509             if(substr($socket_dir,-1) != '/') $socket_dir .= '/';
1510             if(!is_dir($socket_dir)) exec('mkdir -p '.$socket_dir);
1511             $fpm_socket = $socket_dir.'apps.sock';
94a7e1 1512             $cgi_socket = escapeshellcmd($conf['nginx']['cgi_socket']);
4ffb51 1513
F 1514             $content = str_replace('{apps_vhost_ip}', $apps_vhost_ip, $content);
1515             $content = str_replace('{apps_vhost_port}', $conf['web']['apps_vhost_port'], $content);
1516             $content = str_replace('{apps_vhost_dir}', $conf['web']['website_basedir'].'/apps', $content);
1517             $content = str_replace('{apps_vhost_servername}', $apps_vhost_servername, $content);
ca0b77 1518             //$content = str_replace('{fpm_port}', ($conf['nginx']['php_fpm_start_port']+1), $content);
F 1519             $content = str_replace('{fpm_socket}', $fpm_socket, $content);
94a7e1 1520             $content = str_replace('{cgi_socket}', $cgi_socket, $content);
4ffb51 1521
F 1522             wf($vhost_conf_dir.'/apps.vhost', $content);
fbb24a 1523             
F 1524             // PHP-FPM
1525             // Dont just copy over the php-fpm pool template but add some custom settings
f19eb6 1526             $content = rf('tpl/apps_php_fpm_pool.conf.master');
fbb24a 1527             $content = str_replace('{fpm_pool}', 'apps', $content);
ca0b77 1528             //$content = str_replace('{fpm_port}', ($conf['nginx']['php_fpm_start_port']+1), $content);
F 1529             $content = str_replace('{fpm_socket}', $fpm_socket, $content);
fbb24a 1530             $content = str_replace('{fpm_user}', $apps_vhost_user, $content);
F 1531             $content = str_replace('{fpm_group}', $apps_vhost_group, $content);
1532             wf($conf['nginx']['php_fpm_pool_dir'].'/apps.conf', $content);
4ffb51 1533
F 1534             //copy('tpl/nginx_ispconfig.vhost.master', "$vhost_conf_dir/ispconfig.vhost");
1535             //* and create the symlink
1536             if($this->install_ispconfig_interface == true) {
1537                 if(@is_link($vhost_conf_enabled_dir.'/apps.vhost')) unlink($vhost_conf_enabled_dir.'/apps.vhost');
1538                 if(!@is_link($vhost_conf_enabled_dir.'/000-apps.vhost')) {
1539                     symlink($vhost_conf_dir.'/apps.vhost',$vhost_conf_enabled_dir.'/000-apps.vhost');
1540                 }
1541             }
532ae5 1542         }
L 1543     }
1544     
1545     public function make_ispconfig_ssl_cert() {
1546         global $conf;
1547
1548         $install_dir = $conf['ispconfig_install_dir'];
1549         
1550         $ssl_crt_file = $install_dir.'/interface/ssl/ispserver.crt';
1551         $ssl_csr_file = $install_dir.'/interface/ssl/ispserver.csr';
1552         $ssl_key_file = $install_dir.'/interface/ssl/ispserver.key';
1553         
1554         if(!@is_dir($install_dir.'/interface/ssl')) mkdir($install_dir.'/interface/ssl', 0755, true);
1555         
1556         $ssl_pw = substr(md5(mt_rand()),0,6);
1557         exec("openssl genrsa -des3 -passout pass:$ssl_pw -out $ssl_key_file 4096");
1558         exec("openssl req -new -passin pass:$ssl_pw -passout pass:$ssl_pw -key $ssl_key_file -out $ssl_csr_file");
1559         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");
1560         exec("openssl rsa -passin pass:$ssl_pw -in $ssl_key_file -out $ssl_key_file.insecure");
1561         rename($ssl_key_file,$ssl_key_file.'.secure');
1562         rename($ssl_key_file.'.insecure',$ssl_key_file);
1563         
1564     }
1565
1566     public function install_ispconfig() {
1567         global $conf;
1568
1569         $install_dir = $conf['ispconfig_install_dir'];
1570
1571         //* Create the ISPConfig installation directory
1572         if(!@is_dir($install_dir)) {
1573             $command = "mkdir $install_dir";
1574             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1575         }
1576
1577         //* Create a ISPConfig user and group
1578         $command = 'groupadd ispconfig';
1579         if(!is_group('ispconfig')) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1580
1581         $command = 'useradd -g ispconfig -d '.$install_dir.' ispconfig';
1582         if(!is_user('ispconfig')) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1583
1584         //* copy the ISPConfig interface part
1585         $command = 'cp -rf ../interface '.$install_dir;
1586         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1587
1588         //* copy the ISPConfig server part
1589         $command = 'cp -rf ../server '.$install_dir;
1590         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1591
1592         //* Create a symlink, so ISPConfig is accessible via web
1593         // Replaced by a separate vhost definition for port 8080
1594         // $command = "ln -s $install_dir/interface/web/ /var/www/ispconfig";
1595         // caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1596
1597         //* Create the config file for ISPConfig interface
1598         $configfile = 'config.inc.php';
1599         if(is_file($install_dir.'/interface/lib/'.$configfile)) {
1600             copy($install_dir.'/interface/lib/'.$configfile, $install_dir.'/interface/lib/'.$configfile.'~');
1601         }
1602         $content = rf('tpl/'.$configfile.'.master');
1603         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
1604         $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content);
1605         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
1606         $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content);
1607
1608         $content = str_replace('{mysql_master_server_ispconfig_user}', $conf['mysql']['master_ispconfig_user'], $content);
1609         $content = str_replace('{mysql_master_server_ispconfig_password}', $conf['mysql']['master_ispconfig_password'], $content);
1610         $content = str_replace('{mysql_master_server_database}', $conf['mysql']['master_database'], $content);
1611         $content = str_replace('{mysql_master_server_host}', $conf['mysql']['master_host'], $content);
1612
1613         $content = str_replace('{server_id}', $conf['server_id'], $content);
1614         $content = str_replace('{ispconfig_log_priority}', $conf['ispconfig_log_priority'], $content);
b63764 1615         $content = str_replace('{language}', $conf['language'], $content);
71ea2a 1616         $content = str_replace('{timezone}', $conf['timezone'], $content);
b63764 1617
532ae5 1618         wf($install_dir.'/interface/lib/'.$configfile, $content);
L 1619
1620         //* Create the config file for ISPConfig server
1621         $configfile = 'config.inc.php';
1622         if(is_file($install_dir.'/server/lib/'.$configfile)) {
1623             copy($install_dir.'/server/lib/'.$configfile, $install_dir.'/interface/lib/'.$configfile.'~');
1624         }
1625         $content = rf('tpl/'.$configfile.'.master');
1626         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
1627         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1628         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
1629         $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content);
1630
1631         $content = str_replace('{mysql_master_server_ispconfig_user}', $conf['mysql']['master_ispconfig_user'], $content);
1632         $content = str_replace('{mysql_master_server_ispconfig_password}', $conf['mysql']['master_ispconfig_password'], $content);
1633         $content = str_replace('{mysql_master_server_database}', $conf['mysql']['master_database'], $content);
1634         $content = str_replace('{mysql_master_server_host}', $conf['mysql']['master_host'], $content);
1635
1636         $content = str_replace('{server_id}', $conf['server_id'], $content);
1637         $content = str_replace('{ispconfig_log_priority}', $conf['ispconfig_log_priority'], $content);
1638         $content = str_replace('{language}', $conf['language'], $content);
71ea2a 1639         $content = str_replace('{timezone}', $conf['timezone'], $content);
532ae5 1640
L 1641         wf($install_dir.'/server/lib/'.$configfile, $content);
1642
1643         //* Create the config file for remote-actions (but only, if it does not exist, because
1644         //  the value is a autoinc-value and so changed by the remoteaction_core_module
1645         if (!file_exists($install_dir.'/server/lib/remote_action.inc.php')) {
1646             $content = '<?php' . "\n" . '$maxid_remote_action = 0;' . "\n" . '?>';
1647             wf($install_dir.'/server/lib/remote_action.inc.php', $content);
1648         }
1649
1650         //* Enable the server modules and plugins.
1651         // TODO: Implement a selector which modules and plugins shall be enabled.
1652         $dir = $install_dir.'/server/mods-available/';
1653         if (is_dir($dir)) {
1654             if ($dh = opendir($dir)) {
1655                 while (($file = readdir($dh)) !== false) {
1656                     if($file != '.' && $file != '..' && substr($file,-8,8) == '.inc.php') {
1657                         include_once($install_dir.'/server/mods-available/'.$file);
1658                         $module_name = substr($file,0,-8);
1659                         $tmp = new $module_name;
1660                         if($tmp->onInstall()) {
1661                             if(!@is_link($install_dir.'/server/mods-enabled/'.$file)) {
1662                                 @symlink($install_dir.'/server/mods-available/'.$file, $install_dir.'/server/mods-enabled/'.$file);
1663                                 // @symlink($install_dir.'/server/mods-available/'.$file, '../mods-enabled/'.$file);
1664                             }
1665                             if (strpos($file, '_core_module') !== false) {
1666                                 if(!@is_link($install_dir.'/server/mods-core/'.$file)) {
1667                                     @symlink($install_dir.'/server/mods-available/'.$file, $install_dir.'/server/mods-core/'.$file);
1668                                     // @symlink($install_dir.'/server/mods-available/'.$file, '../mods-core/'.$file);
1669                                 }
1670                             }
1671                         }
1672                         unset($tmp);
1673                     }
1674                 }
1675                 closedir($dh);
1676             }
1677         }
1678
1679         $dir = $install_dir.'/server/plugins-available/';
1680         if (is_dir($dir)) {
1681             if ($dh = opendir($dir)) {
1682                 while (($file = readdir($dh)) !== false) {
4ffb51 1683                     if($conf['apache']['installed'] == true && $file == 'nginx_plugin.inc.php') continue;
F 1684                     if($conf['nginx']['installed'] == true && $file == 'apache2_plugin.inc.php') continue;
532ae5 1685                     if($file != '.' && $file != '..' && substr($file,-8,8) == '.inc.php') {
L 1686                         include_once($install_dir.'/server/plugins-available/'.$file);
1687                         $plugin_name = substr($file,0,-8);
1688                         $tmp = new $plugin_name;
1689                         if(method_exists($tmp,'onInstall') && $tmp->onInstall()) {
1690                             if(!@is_link($install_dir.'/server/plugins-enabled/'.$file)) {
1691                                 @symlink($install_dir.'/server/plugins-available/'.$file, $install_dir.'/server/plugins-enabled/'.$file);
1692                                 //@symlink($install_dir.'/server/plugins-available/'.$file, '../plugins-enabled/'.$file);
1693                             }
1694                             if (strpos($file, '_core_plugin') !== false) {
1695                                 if(!@is_link($install_dir.'/server/plugins-core/'.$file)) {
1696                                     @symlink($install_dir.'/server/plugins-available/'.$file, $install_dir.'/server/plugins-core/'.$file);
1697                                     //@symlink($install_dir.'/server/plugins-available/'.$file, '../plugins-core/'.$file);
1698                                 }
1699                             }
1700                         }
1701                         unset($tmp);
1702                     }
1703                 }
1704                 closedir($dh);
1705             }
1706         }
1707
1708         // Update the server config
1709         $mail_server_enabled = ($conf['services']['mail'])?1:0;
1710         $web_server_enabled = ($conf['services']['web'])?1:0;
1711         $dns_server_enabled = ($conf['services']['dns'])?1:0;
1712         $file_server_enabled = ($conf['services']['file'])?1:0;
1713         $db_server_enabled = ($conf['services']['db'])?1:0;
8cf955 1714         $vserver_server_enabled = ($conf['openvz']['installed'])?1:0;
80e3c9 1715         $proxy_server_enabled = ($conf['services']['proxy'])?1:0;
T 1716         $firewall_server_enabled = ($conf['services']['firewall'])?1:0;
532ae5 1717
80e3c9 1718         $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 1719
L 1720         if($conf['mysql']['master_slave_setup'] == 'y') {
1721             $this->dbmaster->query($sql);
1722             $this->db->query($sql);
1723         } else {
1724             $this->db->query($sql);
1725         }
1726
1727
1728         //* Chmod the files
1729         $command = 'chmod -R 750 '.$install_dir;
1730         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1731
1732         //* chown the files to the ispconfig user and group
1733         $command = 'chown -R ispconfig:ispconfig '.$install_dir;
1734         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1735
1736         //* Make the global language file directory group writable
1737         exec("chmod -R 770 $install_dir/interface/lib/lang");
1738
1739         //* Make the temp directory for language file exports writable
1740         if(is_dir($install_dir.'/interface/web/temp')) exec("chmod -R 770 $install_dir/interface/web/temp");
1741
1742         //* Make all interface language file directories group writable
1743         $handle = @opendir($install_dir.'/interface/web');
1744         while ($file = @readdir ($handle)) {
1745             if ($file != '.' && $file != '..') {
1746                 if(@is_dir($install_dir.'/interface/web'.'/'.$file.'/lib/lang')) {
1747                     $handle2 = opendir($install_dir.'/interface/web'.'/'.$file.'/lib/lang');
1748                     chmod($install_dir.'/interface/web'.'/'.$file.'/lib/lang',0770);
1749                     while ($lang_file = @readdir ($handle2)) {
1750                         if ($lang_file != '.' && $lang_file != '..') {
1751                             chmod($install_dir.'/interface/web'.'/'.$file.'/lib/lang/'.$lang_file,0770);
1752                         }
1753                     }
1754                 }
1755             }
1756         }
1757
1758         //* make sure that the server config file (not the interface one) is only readable by the root user
1759         chmod($install_dir.'/server/lib/'.$configfile, 0600);
1760         chown($install_dir.'/server/lib/'.$configfile, 'root');
1761         chgrp($install_dir.'/server/lib/'.$configfile, 'root');
1762
1763         chmod($install_dir.'/server/lib/remote_action.inc.php', 0600);
1764         chown($install_dir.'/server/lib/remote_action.inc.php', 'root');
1765         chgrp($install_dir.'/server/lib/remote_action.inc.php', 'root');
1766
1767         if(@is_file($install_dir.'/server/lib/mysql_clientdb.conf')) {
1768             chmod($install_dir.'/server/lib/mysql_clientdb.conf', 0600);
1769             chown($install_dir.'/server/lib/mysql_clientdb.conf', 'root');
1770             chgrp($install_dir.'/server/lib/mysql_clientdb.conf', 'root');
1771         }
c749e5 1772         
e61ed8 1773         if(is_dir($install_dir.'/interface/invoices')) {
c749e5 1774             chmod($install_dir.'/interface/invoices', 0770);
T 1775             chown($install_dir.'/interface/invoices', 'ispconfig');
1776             chgrp($install_dir.'/interface/invoices', 'ispconfig');
1777         }
532ae5 1778
L 1779         // TODO: FIXME: add the www-data user to the ispconfig group. This is just for testing
1780         // and must be fixed as this will allow the apache user to read the ispconfig files.
1781         // Later this must run as own apache server or via suexec!
63b369 1782         if($conf['apache']['installed'] == true){
F 1783             $command = 'adduser '.$conf['apache']['user'].' ispconfig';
1784             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
272aec 1785             if(is_group('ispapps')){
F 1786                 $command = 'adduser '.$conf['apache']['user'].' ispapps';
1787                 caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1788             }
63b369 1789         }
F 1790         if($conf['nginx']['installed'] == true){
1791             $command = 'adduser '.$conf['nginx']['user'].' ispconfig';
1792             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
272aec 1793             if(is_group('ispapps')){
F 1794                 $command = 'adduser '.$conf['nginx']['user'].' ispapps';
1795                 caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1796             }
63b369 1797         }
532ae5 1798
L 1799         //* Make the shell scripts executable
1800         $command = "chmod +x $install_dir/server/scripts/*.sh";
1801         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1802
4ffb51 1803         if($conf['apache']['installed'] == true){
F 1804             //* Copy the ISPConfig vhost for the controlpanel
1805             $vhost_conf_dir = $conf['apache']['vhost_conf_dir'];
1806             $vhost_conf_enabled_dir = $conf['apache']['vhost_conf_enabled_dir'];
532ae5 1807
4ffb51 1808             // Dont just copy over the virtualhost template but add some custom settings
F 1809             $content = rf('tpl/apache_ispconfig.vhost.master');
1810             $content = str_replace('{vhost_port}', $conf['apache']['vhost_port'], $content);
532ae5 1811
4ffb51 1812             // comment out the listen directive if port is 80 or 443
F 1813             if($conf['apache']['vhost_port'] == 80 or $conf['apache']['vhost_port'] == 443) {
1814                 $content = str_replace('{vhost_port_listen}', '#', $content);
1815             } else {
1816                 $content = str_replace('{vhost_port_listen}', '', $content);
1817             }
532ae5 1818         
4ffb51 1819             if(is_file($install_dir.'/interface/ssl/ispserver.crt') && is_file($install_dir.'/interface/ssl/ispserver.key')) {
F 1820                 $content = str_replace('{ssl_comment}', '', $content);
1821             } else {
1822                 $content = str_replace('{ssl_comment}', '#', $content);
1823             }
532ae5 1824
4ffb51 1825             wf($vhost_conf_dir.'/ispconfig.vhost', $content);
532ae5 1826
4ffb51 1827             //copy('tpl/apache_ispconfig.vhost.master', $vhost_conf_dir.'/ispconfig.vhost');
F 1828             //* and create the symlink
1829             if($this->install_ispconfig_interface == true && $this->is_update == false) {
1830                 if(@is_link($vhost_conf_enabled_dir.'/ispconfig.vhost')) unlink($vhost_conf_enabled_dir.'/ispconfig.vhost');
1831                 if(!@is_link($vhost_conf_enabled_dir.'/000-ispconfig.vhost')) {
1832                     symlink($vhost_conf_dir.'/ispconfig.vhost',$vhost_conf_enabled_dir.'/000-ispconfig.vhost');
1833                 }
1834             }
1835             if(!is_file('/var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter')) {
1836                 mkdir('/var/www/php-fcgi-scripts/ispconfig', 0755, true);
1837                 copy('tpl/apache_ispconfig_fcgi_starter.master','/var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter');
1838                 exec('chmod +x /var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter');
1839                 symlink($install_dir.'/interface/web','/var/www/ispconfig');
1840                 exec('chown -R ispconfig:ispconfig /var/www/php-fcgi-scripts/ispconfig');
1841
532ae5 1842             }
L 1843         }
4ffb51 1844         
F 1845         if($conf['nginx']['installed'] == true){
1846             //* Copy the ISPConfig vhost for the controlpanel
1847             $vhost_conf_dir = $conf['nginx']['vhost_conf_dir'];
1848             $vhost_conf_enabled_dir = $conf['nginx']['vhost_conf_enabled_dir'];
532ae5 1849
4ffb51 1850             // Dont just copy over the virtualhost template but add some custom settings
F 1851             $content = rf('tpl/nginx_ispconfig.vhost.master');
1852             $content = str_replace('{vhost_port}', $conf['nginx']['vhost_port'], $content);
1853         
1854             if(is_file($install_dir.'/interface/ssl/ispserver.crt') && is_file($install_dir.'/interface/ssl/ispserver.key')) {
1855                 $content = str_replace('{ssl_on}', ' ssl', $content);
1856                 $content = str_replace('{ssl_comment}', '', $content);
1857                 $content = str_replace('{fastcgi_ssl}', 'on', $content);
1858             } else {
1859                 $content = str_replace('{ssl_on}', '', $content);
1860                 $content = str_replace('{ssl_comment}', '#', $content);
1861                 $content = str_replace('{fastcgi_ssl}', 'off', $content);
1862             }
1863             
ca0b77 1864             $socket_dir = escapeshellcmd($conf['nginx']['php_fpm_socket_dir']);
F 1865             if(substr($socket_dir,-1) != '/') $socket_dir .= '/';
1866             if(!is_dir($socket_dir)) exec('mkdir -p '.$socket_dir);
1867             $fpm_socket = $socket_dir.'ispconfig.sock';
1868             
1869             //$content = str_replace('{fpm_port}', $conf['nginx']['php_fpm_start_port'], $content);
1870             $content = str_replace('{fpm_socket}', $fpm_socket, $content);
1871             
4ffb51 1872             wf($vhost_conf_dir.'/ispconfig.vhost', $content);
F 1873             
1874             unset($content);
1875             
1876             // PHP-FPM
1877             // Dont just copy over the php-fpm pool template but add some custom settings
1878             $content = rf('tpl/php_fpm_pool.conf.master');
1879             $content = str_replace('{fpm_pool}', 'ispconfig', $content);
ca0b77 1880             //$content = str_replace('{fpm_port}', $conf['nginx']['php_fpm_start_port'], $content);
F 1881             $content = str_replace('{fpm_socket}', $fpm_socket, $content);
4ffb51 1882             $content = str_replace('{fpm_user}', 'ispconfig', $content);
F 1883             $content = str_replace('{fpm_group}', 'ispconfig', $content);
1884             wf($conf['nginx']['php_fpm_pool_dir'].'/ispconfig.conf', $content);
1885
1886             //copy('tpl/nginx_ispconfig.vhost.master', $vhost_conf_dir.'/ispconfig.vhost');
1887             //* and create the symlink
1888             if($this->install_ispconfig_interface == true && $this->is_update == false) {
1889                 if(@is_link($vhost_conf_enabled_dir.'/ispconfig.vhost')) unlink($vhost_conf_enabled_dir.'/ispconfig.vhost');
1890                 if(!@is_link($vhost_conf_enabled_dir.'/000-ispconfig.vhost')) {
1891                     symlink($vhost_conf_dir.'/ispconfig.vhost',$vhost_conf_enabled_dir.'/000-ispconfig.vhost');
1892                 }
1893             }
532ae5 1894         }
L 1895
1896         //* Install the update script
1897         if(is_file('/usr/local/bin/ispconfig_update_from_svn.sh')) unlink('/usr/local/bin/ispconfig_update_from_svn.sh');
1898         chown($install_dir.'/server/scripts/update_from_svn.sh', 'root');
1899         chmod($install_dir.'/server/scripts/update_from_svn.sh', 0700);
1900         chown($install_dir.'/server/scripts/update_from_tgz.sh', 'root');
1901         chmod($install_dir.'/server/scripts/update_from_tgz.sh', 0700);
1902         chown($install_dir.'/server/scripts/ispconfig_update.sh', 'root');
1903         chmod($install_dir.'/server/scripts/ispconfig_update.sh', 0700);
1904         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');
1905         if(!is_link('/usr/local/bin/ispconfig_update.sh')) symlink($install_dir.'/server/scripts/ispconfig_update.sh','/usr/local/bin/ispconfig_update.sh');
1906
1907         //* Make the logs readable for the ispconfig user
1908         if(@is_file('/var/log/mail.log')) exec('chmod +r /var/log/mail.log');
1909         if(@is_file('/var/log/mail.warn')) exec('chmod +r /var/log/mail.warn');
1910         if(@is_file('/var/log/mail.err')) exec('chmod +r /var/log/mail.err');
1911         if(@is_file('/var/log/messages')) exec('chmod +r /var/log/messages');
1912         if(@is_file('/var/log/clamav/clamav.log')) exec('chmod +r /var/log/clamav/clamav.log');
1913         if(@is_file('/var/log/clamav/freshclam.log')) exec('chmod +r /var/log/clamav/freshclam.log');
1914
1915         //* Create the ispconfig log file and directory
1916         if(!is_file($conf['ispconfig_log_dir'].'/ispconfig.log')) {
1917             if(!is_dir($conf['ispconfig_log_dir'])) mkdir($conf['ispconfig_log_dir'], 0755);
1918             touch($conf['ispconfig_log_dir'].'/ispconfig.log');
1919         }
0c5b42 1920         
T 1921         if(is_user('getmail')) {
1922             rename($install_dir.'/server/scripts/run-getmail.sh','/usr/local/bin/run-getmail.sh');
1923             if(is_user('getmail')) chown('/usr/local/bin/run-getmail.sh', 'getmail');
1924             chmod('/usr/local/bin/run-getmail.sh', 0744);
1925         }
532ae5 1926
L 1927         //* Add Log-Rotation
1928         if (is_dir('/etc/logrotate.d')) {
1929             @unlink('/etc/logrotate.d/logispc3'); // ignore, if the file is not there
1930             /* We rotate these logs in cron_daily.php
1931             $fh = fopen('/etc/logrotate.d/logispc3', 'w');
1932             fwrite($fh,
1933                     "$conf['ispconfig_log_dir']/ispconfig.log { \n" .
1934                     "    weekly \n" .
1935                     "    missingok \n" .
1936                     "    rotate 4 \n" .
1937                     "    compress \n" .
1938                     "    delaycompress \n" .
1939                     "} \n" .
1940                     "$conf['ispconfig_log_dir']/cron.log { \n" .
1941                     "    weekly \n" .
1942                     "    missingok \n" .
1943                     "    rotate 4 \n" .
1944                     "    compress \n" .
1945                     "    delaycompress \n" .
1946                     "}");
1947             fclose($fh);
1948             */
1949         }
1950     }
1951
1952     public function configure_dbserver() {
1953         global $conf;
1954
1955         //* If this server shall act as database server for client DB's, we configure this here
1956         $install_dir = $conf['ispconfig_install_dir'];
1957
1958         // Create a file with the database login details which
1959         // are used to create the client databases.
1960
1961         if(!is_dir($install_dir.'/server/lib')) {
1962             $command = "mkdir $install_dir/server/lib";
1963             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1964         }
1965
1966         $content = rf('tpl/mysql_clientdb.conf.master');
1967         $content = str_replace('{username}',$conf['mysql']['admin_user'],$content);
1968         $content = str_replace('{password}',$conf['mysql']['admin_password'], $content);
1969         wf($install_dir.'/server/lib/mysql_clientdb.conf',$content);
1970         chmod($install_dir.'/server/lib/mysql_clientdb.conf', 0600);
1971         chown($install_dir.'/server/lib/mysql_clientdb.conf', 'root');
c749e5 1972         chgrp($install_dir.'/server/lib/mysql_clientdb.conf', 'root');        
532ae5 1973
L 1974     }
1975
1976     public function install_crontab() {
1977         global $conf;
1978
1979         $install_dir = $conf['ispconfig_install_dir'];
1980
1981         //* Root Crontab
1982         exec('crontab -u root -l > crontab.txt');
1983         $existing_root_cron_jobs = file('crontab.txt');
1984
1985         // remove existing ispconfig cronjobs, in case the syntax has changed
1986         foreach($existing_root_cron_jobs as $key => $val) {
1987             if(stristr($val,$install_dir)) unset($existing_root_cron_jobs[$key]);
1988         }
1989
1990         $root_cron_jobs = array(
1991                 "* * * * * ".$install_dir."/server/server.sh > /dev/null 2>> ".$conf['ispconfig_log_dir']."/cron.log",
1992                 "30 00 * * * ".$install_dir."/server/cron_daily.sh > /dev/null 2>> ".$conf['ispconfig_log_dir']."/cron.log"
1993         );
b6a10a 1994         
F 1995         if ($conf['nginx']['installed'] == true) {
1996             $root_cron_jobs[] = "0 0 * * * ".$install_dir."/server/scripts/create_daily_nginx_access_logs.sh &> /dev/null";
1997         }
1998         
532ae5 1999         foreach($root_cron_jobs as $cron_job) {
L 2000             if(!in_array($cron_job."\n", $existing_root_cron_jobs)) {
2001                 $existing_root_cron_jobs[] = $cron_job."\n";
2002             }
2003         }
2004         file_put_contents('crontab.txt', $existing_root_cron_jobs);
2005         exec('crontab -u root crontab.txt &> /dev/null');
2006         unlink('crontab.txt');
2007
2008         //* Getmail crontab
2009         if(is_user('getmail')) {
2010             $cf = $conf['getmail'];
2011             exec('crontab -u getmail -l > crontab.txt');
2012             $existing_cron_jobs = file('crontab.txt');
2013
2014             $cron_jobs = array(
2015                     '*/5 * * * * /usr/local/bin/run-getmail.sh > /dev/null 2>> '.$conf['ispconfig_log_dir'].'/cron.log'
2016             );
2017
2018             // remove existing ispconfig cronjobs, in case the syntax has changed
2019             foreach($existing_cron_jobs as $key => $val) {
2020                 if(stristr($val,'getmail')) unset($existing_cron_jobs[$key]);
2021             }
2022
2023             foreach($cron_jobs as $cron_job) {
2024                 if(!in_array($cron_job."\n", $existing_cron_jobs)) {
2025                     $existing_cron_jobs[] = $cron_job."\n";
2026                 }
2027             }
2028             file_put_contents('crontab.txt', $existing_cron_jobs);
2029             exec('crontab -u getmail crontab.txt &> /dev/null');
2030             unlink('crontab.txt');
2031         }
2032
2033         touch($conf['ispconfig_log_dir'].'/cron.log');
2034         chmod($conf['ispconfig_log_dir'].'/cron.log', 0666);
2035
2036     }
2037
2038     /**
2039      * Helper function - get the path to a template file based on
2040      * the local part of the filename. Checks first for the existence
2041      * of a distribution specific file and if not found looks in the
2042      * base template folder. Optionally the behaviour can be changed
2043      * by setting the 2nd parameter which will fetch the contents
2044      * of the template file and return it instead of the path. The 3rd
2045      * parameter further extends this behaviour by filtering the contents
2046      * by inserting the ispconfig database credentials using the {} placeholders.
2047      *
2048      * @param string $tLocal local part of filename
2049      * @param bool $tRf
2050      * @param bool $tDBCred
2051      * @return string Relative path to the chosen template file
2052      */
2053     protected function get_template_file($tLocal, $tRf=false, $tDBCred=false) {
2054         global $conf, $dist;
2055
2056         $final_path = '';
2057         $dist_template = 'dist/tpl/'.strtolower($dist['name'])."/$tLocal.master";
2058         if (file_exists($dist_template)) {
2059             $final_path = $dist_template;
2060         } else {
2061             $final_path = "tpl/$tLocal.master";
2062         }
2063
2064         if (!$tRf) {
2065             return $final_path;
2066         } else {
2067             return (!$tDBCred) ? rf($final_path) : $this->insert_db_credentials(rf($final_path));
2068         }
2069     }
2070
2071     /**
2072      * Helper function - writes the contents to a config file
2073      * and performs a backup if the file exist. Additionally
2074      * if the file exists the new file will be given the
2075      * same rights and ownership as the original. Optionally the
2076      * rights and/or ownership can be overriden by appending umask,
2077      * user and group to the parameters. Providing only uid and gid
2078      * values will result in only a chown.
2079      *
2080      * @param $tConf
2081      * @param $tContents
2082      * @return bool
2083      */
2084     protected function write_config_file($tConf, $tContents) {
2085         // Backup config file before writing new contents and stat file
2086         if ( is_file($tConf) ) {
2087             $stat = exec('stat -c \'%a %U %G\' '.escapeshellarg($tConf), $output, $res);
2088             if ($res == 0) { // stat successfull
2089                 list($access, $user, $group) = split(" ", $stat);
2090             }
2091
2092             if ( copy($tConf, $tConf.'~') ) {
2093                 chmod($tConf.'~', 0400);
2094             }
2095         }
2096
2097         wf($tConf, $tContents); // write file
2098
2099         if (func_num_args() >= 4) // override rights and/or ownership
2100         {
2101             $args = func_get_args();
2102             $output = array_slice($args, 2);
2103
2104             switch (sizeof($output)) {
2105                 case 3:
2106                     $umask = array_shift($output);
2107                     if (is_numeric($umask) && preg_match('/^0?[0-7]{3}$/', $umask)) {
2108                         $access = $umask;
2109                     }
2110                 case 2:
2111                     if (is_user($output[0]) && is_group($output[1])) {
2112                         list($user,$group) = $output;
2113                     }
2114                     break;
2115             }
2116         }
2117
2118         if (!empty($user) && !empty($group)) {
2119             chown($tConf, $user);
2120             chgrp($tConf, $group);
2121         }
2122
2123         if (!empty($access)) {
2124             exec("chmod $access $tConf");
2125         }
2126     }
2127
2128     /**
2129      * Helper function - filter the contents of a config
2130      * file by inserting the common ispconfig database
2131      * credentials.
2132      *
2133      * @param $tContents
2134      * @return string
2135      */
2136     protected function insert_db_credentials($tContents) {
2137         global $conf;
2138
2139         $tContents = str_replace('{mysql_server_ispconfig_user}', $conf["mysql"]["ispconfig_user"], $tContents);
2140         $tContents = str_replace('{mysql_server_ispconfig_password}', $conf["mysql"]["ispconfig_password"], $tContents);
2141         $tContents = str_replace('{mysql_server_database}', $conf["mysql"]["database"], $tContents);
2142         $tContents = str_replace('{mysql_server_ip}', $conf["mysql"]["ip"], $tContents);
2143         $tContents = str_replace('{mysql_server_host}',$conf['mysql']['host'], $tContents);
2144         $tContents = str_replace('{mysql_server_port}',$conf["mysql"]["port"], $tContents);
2145
2146         return $tContents;
2147     }
2148 }
2149
5eb43f 2150 ?>