Till Brehm
2014-10-23 67fedede3887d97078862e9b58524dc71162ba24
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) {
7fe908 56         echo 'WARNING: '.$msg."\n";
532ae5 57     }
a8ccf6 58
b04e82 59     public function simple_query($query, $answers, $default, $name = '') {
TB 60         global $autoinstall;
532ae5 61         $finished = false;
L 62         do {
b04e82 63             if($name != '' && $autoinstall[$name] != '') {
TB 64                 if($autoinstall[$name] == 'default') {
65                     $input = $default;
66                 } else {
67                     $input = $autoinstall[$name];
68                 }
69             } else {
70                 $answers_str = implode(',', $answers);
71                 swrite($this->lng($query).' ('.$answers_str.') ['.$default.']: ');
72                 $input = sread();
73             }
532ae5 74
L 75             //* Stop the installation
76             if($input == 'quit') {
77                 swriteln($this->lng("Installation terminated by user.\n"));
78                 die();
79             }
80
81             //* Select the default
82             if($input == '') {
83                 $answer = $default;
84                 $finished = true;
85             }
86
87             //* Set answer id valid
88             if(in_array($input, $answers)) {
89                 $answer = $input;
90                 $finished = true;
91             }
92
93         } while ($finished == false);
94         swriteln();
95         return $answer;
96     }
97
b04e82 98     public function free_query($query, $default, $name = '') {
TB 99         global $autoinstall;
100         if($name != '' && $autoinstall[$name] != '') {
101             if($autoinstall[$name] == 'default') {
102                 $input = $default;
103             } else {
104                 $input = $autoinstall[$name];
105             }
106         } else {
107             swrite($this->lng($query).' ['.$default.']: ');
108             $input = sread();
109         }
532ae5 110
L 111         //* Stop the installation
112         if($input == 'quit') {
113             swriteln($this->lng("Installation terminated by user.\n"));
114             die();
115         }
116
117         $answer =  ($input == '') ? $default : $input;
118         swriteln();
119         return $answer;
120     }
121
122     /*
123     // TODO: this function is not used atmo I think - pedro
124     function request_language(){
a8ccf6 125
532ae5 126         swriteln(lng('Enter your language'));
L 127         swriteln(lng('de, en'));
a8ccf6 128
532ae5 129     }
L 130     */
131
132     //** Detect installed applications
133     public function find_installed_apps() {
134         global $conf;
135
136         if(is_installed('mysql') || is_installed('mysqld')) $conf['mysql']['installed'] = true;
137         if(is_installed('postfix')) $conf['postfix']['installed'] = true;
138         if(is_installed('mailman')) $conf['mailman']['installed'] = true;
e09a27 139         if(is_installed('apache') || is_installed('apache2') || is_installed('httpd') || is_installed('httpd2')) $conf['apache']['installed'] = true;
532ae5 140         if(is_installed('getmail')) $conf['getmail']['installed'] = true;
1ca823 141         if(is_installed('courierlogger')) $conf['courier']['installed'] = true;
532ae5 142         if(is_installed('dovecot')) $conf['dovecot']['installed'] = true;
74d2dc 143         if(is_installed('saslauthd')) $conf['saslauthd']['installed'] = true;
ac28b5 144         if(is_installed('amavisd-new') || is_installed('amavisd')) $conf['amavis']['installed'] = true;
532ae5 145         if(is_installed('clamdscan')) $conf['clamav']['installed'] = true;
L 146         if(is_installed('pure-ftpd') || is_installed('pure-ftpd-wrapper')) $conf['pureftpd']['installed'] = true;
147         if(is_installed('mydns') || is_installed('mydns-ng')) $conf['mydns']['installed'] = true;
148         if(is_installed('jk_chrootsh')) $conf['jailkit']['installed'] = true;
149         if(is_installed('pdns_server') || is_installed('pdns_control')) $conf['powerdns']['installed'] = true;
150         if(is_installed('named') || is_installed('bind') || is_installed('bind9')) $conf['bind']['installed'] = true;
80e3c9 151         if(is_installed('squid')) $conf['squid']['installed'] = true;
T 152         if(is_installed('nginx')) $conf['nginx']['installed'] = true;
992797 153         // if(is_installed('iptables') && is_installed('ufw')) $conf['ufw']['installed'] = true;
5eb43f 154         if(is_installed('fail2ban-server')) $conf['fail2ban']['installed'] = true;
522ef8 155         if(is_installed('vzctl')) $conf['openvz']['installed'] = true;
80e3c9 156         if(is_dir("/etc/Bastille")) $conf['bastille']['installed'] = true;
a8ccf6 157
d7cfd7 158         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 159     }
L 160
161     /** Create the database for ISPConfig */
7fe908 162
MC 163
532ae5 164     public function configure_database() {
L 165         global $conf;
166
167         //** Create the database
168         if(!$this->db->query('CREATE DATABASE IF NOT EXISTS '.$conf['mysql']['database'].' DEFAULT CHARACTER SET '.$conf['mysql']['charset'])) {
169             $this->error('Unable to create MySQL database: '.$conf['mysql']['database'].'.');
170         }
171
172         //* Set the database name in the DB library
173         $this->db->dbName = $conf['mysql']['database'];
174
175         //* Load the database dump into the database, if database contains no tables
176         $db_tables = $this->db->getTables();
177         if(count($db_tables) > 0) {
178             $this->error('Stopped: Database already contains some tables.');
179         } else {
180             if($conf['mysql']['admin_password'] == '') {
02bf99 181                 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",
7fe908 182                     __FILE__, __LINE__, 'read in ispconfig3.sql', 'could not read in ispconfig3.sql');
532ae5 183             } else {
02bf99 184                 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",
7fe908 185                     __FILE__, __LINE__, 'read in ispconfig3.sql', 'could not read in ispconfig3.sql');
532ae5 186             }
L 187             $db_tables = $this->db->getTables();
188             if(count($db_tables) == 0) {
189                 $this->error('Unable to load SQL-Dump into database table.');
190             }
191
192             //* Load system.ini into the sys_ini table
193             $system_ini = $this->db->quote(rf('tpl/system.ini.master'));
194             $this->db->query("UPDATE sys_ini SET config = '$system_ini' WHERE sysini_id = 1");
195
196         }
197     }
198
199     //** Create the server record in the database
200     public function add_database_server_record() {
201
202         global $conf;
203
204         if($conf['mysql']['host'] == 'localhost') {
205             $from_host = 'localhost';
206         } else {
207             $from_host = $conf['hostname'];
208         }
209
210         // Delete ISPConfig user in the local database, in case that it exists
211         $this->db->query("DELETE FROM mysql.user WHERE User = '".$conf['mysql']['ispconfig_user']."' AND Host = '".$from_host."';");
212         $this->db->query("DELETE FROM mysql.db WHERE Db = '".$conf['mysql']['database']."' AND Host = '".$from_host."';");
213         $this->db->query('FLUSH PRIVILEGES;');
214
215         //* Create the ISPConfig database user in the local database
216         $query = 'GRANT SELECT, INSERT, UPDATE, DELETE ON '.$conf['mysql']['database'].".* "
7fe908 217             ."TO '".$conf['mysql']['ispconfig_user']."'@'".$from_host."' "
MC 218             ."IDENTIFIED BY '".$conf['mysql']['ispconfig_password']."';";
532ae5 219         if(!$this->db->query($query)) {
L 220             $this->error('Unable to create database user: '.$conf['mysql']['ispconfig_user'].' Error: '.$this->db->errorMessage);
221         }
222
223         //* Reload database privelages
224         $this->db->query('FLUSH PRIVILEGES;');
225
226         //* Set the database name in the DB library
227         $this->db->dbName = $conf['mysql']['database'];
228
229         $tpl_ini_array = ini_to_array(rf('tpl/server.ini.master'));
230
231         //* Update further distribution specific parameters for server config here
232         //* HINT: Every line added here has to be added in update.lib.php too!!
233         $tpl_ini_array['web']['vhost_conf_dir'] = $conf['apache']['vhost_conf_dir'];
234         $tpl_ini_array['web']['vhost_conf_enabled_dir'] = $conf['apache']['vhost_conf_enabled_dir'];
235         $tpl_ini_array['jailkit']['jailkit_chroot_app_programs'] = $conf['jailkit']['jailkit_chroot_app_programs'];
236         $tpl_ini_array['fastcgi']['fastcgi_phpini_path'] = $conf['fastcgi']['fastcgi_phpini_path'];
237         $tpl_ini_array['fastcgi']['fastcgi_starter_path'] = $conf['fastcgi']['fastcgi_starter_path'];
526b99 238         $tpl_ini_array['fastcgi']['fastcgi_bin'] = $conf['fastcgi']['fastcgi_bin'];
532ae5 239         $tpl_ini_array['server']['hostname'] = $conf['hostname'];
L 240         $tpl_ini_array['server']['ip_address'] = @gethostbyname($conf['hostname']);
241         $tpl_ini_array['web']['website_basedir'] = $conf['web']['website_basedir'];
242         $tpl_ini_array['web']['website_path'] = $conf['web']['website_path'];
243         $tpl_ini_array['web']['website_symlinks'] = $conf['web']['website_symlinks'];
244         $tpl_ini_array['cron']['crontab_dir'] = $conf['cron']['crontab_dir'];
245         $tpl_ini_array['web']['security_level'] = 20;
246         $tpl_ini_array['web']['user'] = $conf['apache']['user'];
247         $tpl_ini_array['web']['group'] = $conf['apache']['group'];
248         $tpl_ini_array['web']['php_ini_path_apache'] = $conf['apache']['php_ini_path_apache'];
249         $tpl_ini_array['web']['php_ini_path_cgi'] = $conf['apache']['php_ini_path_cgi'];
250         $tpl_ini_array['mail']['pop3_imap_daemon'] = ($conf['dovecot']['installed'] == true)?'dovecot':'courier';
251         $tpl_ini_array['mail']['mail_filter_syntax'] = ($conf['dovecot']['installed'] == true)?'sieve':'maildrop';
252         $tpl_ini_array['dns']['bind_user'] = $conf['bind']['bind_user'];
253         $tpl_ini_array['dns']['bind_group'] = $conf['bind']['bind_group'];
254         $tpl_ini_array['dns']['bind_zonefiles_dir'] = $conf['bind']['bind_zonefiles_dir'];
255         $tpl_ini_array['dns']['named_conf_path'] = $conf['bind']['named_conf_path'];
256         $tpl_ini_array['dns']['named_conf_local_path'] = $conf['bind']['named_conf_local_path'];
a8ccf6 257
dba68f 258         $tpl_ini_array['web']['nginx_vhost_conf_dir'] = $conf['nginx']['vhost_conf_dir'];
T 259         $tpl_ini_array['web']['nginx_vhost_conf_enabled_dir'] = $conf['nginx']['vhost_conf_enabled_dir'];
260         $tpl_ini_array['web']['nginx_user'] = $conf['nginx']['user'];
261         $tpl_ini_array['web']['nginx_group'] = $conf['nginx']['group'];
262         $tpl_ini_array['web']['nginx_cgi_socket'] = $conf['nginx']['cgi_socket'];
263         $tpl_ini_array['web']['php_fpm_init_script'] = $conf['nginx']['php_fpm_init_script'];
264         $tpl_ini_array['web']['php_fpm_ini_path'] = $conf['nginx']['php_fpm_ini_path'];
265         $tpl_ini_array['web']['php_fpm_pool_dir'] = $conf['nginx']['php_fpm_pool_dir'];
266         $tpl_ini_array['web']['php_fpm_start_port'] = $conf['nginx']['php_fpm_start_port'];
267         $tpl_ini_array['web']['php_fpm_socket_dir'] = $conf['nginx']['php_fpm_socket_dir'];
a8ccf6 268
80e3c9 269         if ($conf['nginx']['installed'] == true) {
4ffb51 270             $tpl_ini_array['web']['server_type'] = 'nginx';
F 271             $tpl_ini_array['global']['webserver'] = 'nginx';
80e3c9 272         }
a8ccf6 273
532ae5 274         if (array_key_exists('awstats', $conf)) {
L 275             foreach ($conf['awstats'] as $aw_sett => $aw_value) {
276                 $tpl_ini_array['web']['awstats_'.$aw_sett] = $aw_value;
277             }
278         }
279
280         $server_ini_content = array_to_ini($tpl_ini_array);
281         $server_ini_content = mysql_real_escape_string($server_ini_content);
282
283         $mail_server_enabled = ($conf['services']['mail'])?1:0;
284         $web_server_enabled = ($conf['services']['web'])?1:0;
285         $dns_server_enabled = ($conf['services']['dns'])?1:0;
286         $file_server_enabled = ($conf['services']['file'])?1:0;
287         $db_server_enabled = ($conf['services']['db'])?1:0;
522ef8 288         $vserver_server_enabled = ($conf['openvz']['installed'])?1:0;
c91bdc 289         $proxy_server_enabled = (isset($conf['services']['proxy']) && $conf['services']['proxy'])?1:0;
T 290         $firewall_server_enabled = (isset($conf['services']['firewall']) && $conf['services']['firewall'])?1:0;
a8ccf6 291
532ae5 292         //** Get the database version number based on the patchfiles
L 293         $found = true;
294         $current_db_version = 1;
295         while($found == true) {
296             $next_db_version = intval($current_db_version + 1);
297             $patch_filename = realpath(dirname(__FILE__).'/../').'/sql/incremental/upd_'.str_pad($next_db_version, 4, '0', STR_PAD_LEFT).'.sql';
298             if(is_file($patch_filename)) {
299                 $current_db_version = $next_db_version;
300             } else {
301                 $found = false;
302             }
303         }
304         $current_db_version = intval($current_db_version);
305
306
307         if($conf['mysql']['master_slave_setup'] == 'y') {
308
309             //* Insert the server record in master DB
80e3c9 310             $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 311             $this->dbmaster->query($sql);
L 312             $conf['server_id'] = $this->dbmaster->insertID();
313             $conf['server_id'] = $conf['server_id'];
314
315             //* Insert the same record in the local DB
80e3c9 316             $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 317             $this->db->query($sql);
L 318
319             //* username for the ispconfig user
320             $conf['mysql']['master_ispconfig_user'] = 'ispcsrv'.$conf['server_id'];
321
322             $this->grant_master_database_rights();
323
324         } else {
325             //* Insert the server, if its not a mster / slave setup
80e3c9 326             $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 327             $this->db->query($sql);
L 328             $conf['server_id'] = $this->db->insertID();
329             $conf['server_id'] = $conf['server_id'];
330         }
331
332
333     }
334
100d41 335     public function grant_master_database_rights($verbose = false) {
532ae5 336         global $conf;
L 337
338         /*
339          * The following code is a little bit tricky:
340          * * If we HAVE a master-slave - Setup then the client has to grant the rights for himself
341          *   at the master.
342          * * If we DO NOT have a master-slave - Setup then we have two possibilities
343          *   1) it is a single server
344          *   2) it is the MASTER of n clients
345         */
346         $hosts = array();
a8ccf6 347
532ae5 348         if($conf['mysql']['master_slave_setup'] == 'y') {
L 349             /*
350              * it is a master-slave - Setup so the slave has to grant its rights in the master
351              * database
352              */
353
354             //* insert the ispconfig user in the remote server
355             $from_host = $conf['hostname'];
356             $from_ip = gethostbyname($conf['hostname']);
a8ccf6 357
532ae5 358             $hosts[$from_host]['user'] = $conf['mysql']['master_ispconfig_user'];
L 359             $hosts[$from_host]['db'] = $conf['mysql']['master_database'];
360             $hosts[$from_host]['pwd'] = $conf['mysql']['master_ispconfig_password'];
361
362             $hosts[$from_ip]['user'] = $conf['mysql']['master_ispconfig_user'];
363             $hosts[$from_ip]['db'] = $conf['mysql']['master_database'];
364             $hosts[$from_ip]['pwd'] = $conf['mysql']['master_ispconfig_password'];
365         } else{
366             /*
367              * it is NOT a master-slave - Setup so we have to find out all clients and their
368              * host
369              */
370             $query = "SELECT Host, User FROM mysql.user WHERE User like 'ispcsrv%' ORDER BY User, Host";
371             $data = $this->dbmaster->queryAllRecords($query);
372             if($data === false) {
373                 $this->error('Unable to get the user rights: '.$value['db'].' Error: '.$this->dbmaster->errorMessage);
374             }
375             foreach ($data as $item){
376                 $hosts[$item['Host']]['user'] = $item['User'];
377                 $hosts[$item['Host']]['db'] = $conf['mysql']['master_database'];
378                 $hosts[$item['Host']]['pwd'] = ''; // the user already exists, so we need no pwd!
379             }
380         }
a8ccf6 381
532ae5 382         if(count($hosts) > 0) {
7fe908 383             foreach($hosts as $host => $value) {
MC 384                 /*
532ae5 385              * If a pwd exists, this means, we have to add the new user (and his pwd).
L 386              * if not, the user already exists and we do not need the pwd
387              */
7fe908 388                 if ($value['pwd'] != ''){
MC 389                     $query = "CREATE USER '".$value['user']."'@'".$host."' IDENTIFIED BY '" . $value['pwd'] . "'";
390                     if ($verbose){
391                         echo "\n\n" . $query ."\n";
392                     }
393                     $this->dbmaster->query($query); // ignore the error
394                 }
395
396                 /*
397              *  Try to delete all rights of the user in case that it exists.
398              *  In Case that it will not exist, do nothing (ignore the error!)
399              */
400                 $query = "REVOKE ALL PRIVILEGES, GRANT OPTION FROM '".$value['user']."'@'".$host."' ";
100d41 401                 if ($verbose){
V 402                     echo "\n\n" . $query ."\n";
403                 }
532ae5 404                 $this->dbmaster->query($query); // ignore the error
7fe908 405
MC 406                 //* Create the ISPConfig database user in the remote database
407                 $query = "GRANT SELECT ON ".$value['db'].".`server` TO '".$value['user']."'@'".$host."' ";
408                 if ($verbose){
409                     echo $query ."\n";
410                 }
411                 if(!$this->dbmaster->query($query)) {
412                     $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
413                 }
414
415                 $query = "GRANT SELECT, INSERT ON ".$value['db'].".`sys_log` TO '".$value['user']."'@'".$host."' ";
416                 if ($verbose){
417                     echo $query ."\n";
418                 }
419                 if(!$this->dbmaster->query($query)) {
420                     $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
421                 }
422
423                 $query = "GRANT SELECT, UPDATE(`status`, `error`) ON ".$value['db'].".`sys_datalog` TO '".$value['user']."'@'".$host."' ";
424                 if ($verbose){
425                     echo $query ."\n";
426                 }
427                 if(!$this->dbmaster->query($query)) {
428                     $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
429                 }
430
431                 $query = "GRANT SELECT, UPDATE(`status`) ON ".$value['db'].".`software_update_inst` TO '".$value['user']."'@'".$host."' ";
432                 if ($verbose){
433                     echo $query ."\n";
434                 }
435                 if(!$this->dbmaster->query($query)) {
436                     $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
437                 }
438
439                 $query = "GRANT SELECT, UPDATE(`updated`) ON ".$value['db'].".`server` TO '".$value['user']."'@'".$host."' ";
440                 if ($verbose){
441                     echo $query ."\n";
442                 }
443                 if(!$this->dbmaster->query($query)) {
444                     $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
445                 }
446
447                 $query = "GRANT SELECT, UPDATE (`ssl_request`, `ssl_cert`, `ssl_action`, `ssl_key`) ON ".$value['db'].".`web_domain` TO '".$value['user']."'@'".$host."' ";
448                 if ($verbose){
449                     echo $query ."\n";
450                 }
451                 if(!$this->dbmaster->query($query)) {
452                     $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
453                 }
454
455                 $query = "GRANT SELECT ON ".$value['db'].".`sys_group` TO '".$value['user']."'@'".$host."' ";
456                 if ($verbose){
457                     echo $query ."\n";
458                 }
459                 if(!$this->dbmaster->query($query)) {
460                     $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
461                 }
462
463                 $query = "GRANT SELECT, UPDATE (`action_state`, `response`) ON ".$value['db'].".`sys_remoteaction` TO '".$value['user']."'@'".$host."' ";
464                 if ($verbose){
465                     echo $query ."\n";
466                 }
467                 if(!$this->dbmaster->query($query)) {
468                     $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
469                 }
470
471                 $query = "GRANT SELECT, INSERT , DELETE ON ".$value['db'].".`monitor_data` TO '".$value['user']."'@'".$host."' ";
472                 if ($verbose){
473                     echo $query ."\n";
474                 }
475                 if(!$this->dbmaster->query($query)) {
476                     $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
477                 }
478
479                 $query = "GRANT SELECT, INSERT, UPDATE ON ".$value['db'].".`mail_traffic` TO '".$value['user']."'@'".$host."' ";
480                 if ($verbose){
481                     echo $query ."\n";
482                 }
483                 if(!$this->dbmaster->query($query)) {
484                     $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
485                 }
486
487                 $query = "GRANT SELECT, INSERT, UPDATE ON ".$value['db'].".`web_traffic` TO '".$value['user']."'@'".$host."' ";
488                 if ($verbose){
489                     echo $query ."\n";
490                 }
491                 if(!$this->dbmaster->query($query)) {
492                     $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
493                 }
494
e92eda 495                 $query = "GRANT SELECT, UPDATE, DELETE ON ".$value['db'].".`aps_instances` TO '".$value['user']."'@'".$host."' ";
TB 496                 if ($verbose){
497                     echo $query ."\n";
498                 }
499                 if(!$this->dbmaster->query($query)) {
500                     $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
501                 }
502                 
503                 $query = "GRANT SELECT, DELETE ON ".$value['db'].".`aps_instances_settings` TO '".$value['user']."'@'".$host."' ";
7fe908 504                 if ($verbose){
MC 505                     echo $query ."\n";
506                 }
507                 if(!$this->dbmaster->query($query)) {
508                     $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
509                 }
510
511                 $query = "GRANT SELECT, INSERT, DELETE ON ".$value['db'].".`web_backup` TO '".$value['user']."'@'".$host."' ";
512                 if ($verbose){
513                     echo $query ."\n";
514                 }
515                 if(!$this->dbmaster->query($query)) {
516                     $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
517                 }
518
532ae5 519             }
L 520
521             /*
522          * It is all done. Relod the rights...
523          */
7fe908 524             $this->dbmaster->query('FLUSH PRIVILEGES;');
532ae5 525         }
L 526
527     }
528
529     //** writes postfix configuration files
530     public function process_postfix_config($configfile) {
531         global $conf;
532
533         $config_dir = $conf['postfix']['config_dir'].'/';
534         $full_file_name = $config_dir.$configfile;
535         //* Backup exiting file
536         if(is_file($full_file_name)) {
537             copy($full_file_name, $config_dir.$configfile.'~');
538         }
615a0a 539         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
532ae5 540         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
L 541         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
542         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
543         $content = str_replace('{mysql_server_ip}', $conf['mysql']['ip'], $content);
544         $content = str_replace('{server_id}', $conf['server_id'], $content);
545         wf($full_file_name, $content);
546     }
547
548     public function configure_jailkit() {
549         global $conf;
550
551         $cf = $conf['jailkit'];
552         $config_dir = $cf['config_dir'];
553         $jk_init = $cf['jk_init'];
554         $jk_chrootsh = $cf['jk_chrootsh'];
555
556         if (is_dir($config_dir)) {
557             if(is_file($config_dir.'/'.$jk_init)) copy($config_dir.'/'.$jk_init, $config_dir.'/'.$jk_init.'~');
558             if(is_file($config_dir.'/'.$jk_chrootsh.'.master')) copy($config_dir.'/'.$jk_chrootsh.'.master', $config_dir.'/'.$jk_chrootsh.'~');
7fe908 559
MC 560             if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$jk_init.'.master')) {
561                 copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$jk_init.'.master', $config_dir.'/'.$jk_init);
562             } else {
563                 copy('tpl/'.$jk_init.'.master', $config_dir.'/'.$jk_init);
564             }
565             if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$jk_chrootsh.'.master')) {
566                 copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$jk_chrootsh.'.master', $config_dir.'/'.$jk_chrootsh);
567             } else {
568                 copy('tpl/'.$jk_chrootsh.'.master', $config_dir.'/'.$jk_chrootsh);
569             }
532ae5 570         }
a8ccf6 571
edf806 572         //* help jailkit fo find its ini files
T 573         if(!is_link('/usr/jk_socketd.ini')) exec('ln -s /etc/jailkit/jk_socketd.ini /usr/jk_socketd.ini');
574         if(!is_link('/usr/jk_init.ini')) exec('ln -s /etc/jailkit/jk_init.ini /usr/jk_init.ini');
532ae5 575
L 576     }
a8ccf6 577
532ae5 578     public function configure_mailman($status = 'insert') {
L 579         global $conf;
580
581         $config_dir = $conf['mailman']['config_dir'].'/';
582         $full_file_name = $config_dir.'mm_cfg.py';
583         //* Backup exiting file
584         if(is_file($full_file_name)) {
585             copy($full_file_name, $config_dir.'mm_cfg.py~');
586         }
a8ccf6 587
532ae5 588         // load files
615a0a 589         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/mm_cfg.py.master', 'tpl/mm_cfg.py.master');
532ae5 590         $old_file = rf($full_file_name);
a8ccf6 591
532ae5 592         $old_options = array();
a8ccf6 593         $lines = explode("\n", $old_file);
532ae5 594         foreach ($lines as $line)
L 595         {
8fe9ab 596             if (trim($line) != '' && substr($line, 0, 1) != '#')
532ae5 597             {
8fe9ab 598                 @list($key, $value) = @explode("=", $line);
532ae5 599                 if (!empty($value))
L 600                 {
601                     $key = rtrim($key);
602                     $old_options[$key] = trim($value);
603                 }
604             }
605         }
a8ccf6 606
532ae5 607         $virtual_domains = '';
L 608         if($status == 'update')
609         {
610             // create virtual_domains list
611             $domainAll = $this->db->queryAllRecords("SELECT domain FROM mail_mailinglist GROUP BY domain");
a8ccf6 612
8fe9ab 613             if(is_array($domainAll)) {
7fe908 614                 foreach($domainAll as $domain)
MC 615                 {
616                     if ($domainAll[0]['domain'] == $domain['domain'])
617                         $virtual_domains .= "'".$domain['domain']."'";
618                     else
619                         $virtual_domains .= ", '".$domain['domain']."'";
620                 }
8fe9ab 621             }
532ae5 622         }
L 623         else
624             $virtual_domains = "' '";
a8ccf6 625
532ae5 626         $content = str_replace('{hostname}', $conf['hostname'], $content);
46c775 627         if(!isset($old_options['DEFAULT_SERVER_LANGUAGE'])) $old_options['DEFAULT_SERVER_LANGUAGE'] = '';
532ae5 628         $content = str_replace('{default_language}', $old_options['DEFAULT_SERVER_LANGUAGE'], $content);
L 629         $content = str_replace('{virtual_domains}', $virtual_domains, $content);
7fe908 630
532ae5 631         wf($full_file_name, $content);
7fe908 632
cc6568 633         //* Write virtual_to_transport.sh script
H 634         $config_dir = $conf['mailman']['config_dir'].'/';
635         $full_file_name = $config_dir.'virtual_to_transport.sh';
7fe908 636
cc6568 637         //* Backup exiting virtual_to_transport.sh script
H 638         if(is_file($full_file_name)) {
639             copy($full_file_name, $config_dir.'virtual_to_transport.sh~');
640         }
7fe908 641
cc6568 642         if(is_dir('/etc/mailman')) {
615a0a 643             if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/mailman-virtual_to_transport.sh')) {
7fe908 644                 copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/mailman-virtual_to_transport.sh', $full_file_name);
MC 645             } else {
646                 copy('tpl/mailman-virtual_to_transport.sh', $full_file_name);
647             }
648             chgrp($full_file_name, 'list');
d22542 649             chmod($full_file_name, 0755);
cc6568 650         }
7fe908 651
cc6568 652         //* Create aliasaes
H 653         exec('/usr/lib/mailman/bin/genaliases 2>/dev/null');
5afa9d 654         if(is_file('/var/lib/mailman/data/virtual-mailman')) exec('postmap /var/lib/mailman/data/virtual-mailman');
7fe908 655
532ae5 656     }
L 657
658     public function configure_postfix($options = '') {
b04e82 659         global $conf,$autoinstall;
532ae5 660         $cf = $conf['postfix'];
L 661         $config_dir = $cf['config_dir'];
662
663         if(!is_dir($config_dir)) {
664             $this->error("The postfix configuration directory '$config_dir' does not exist.");
665         }
666
667         //* mysql-virtual_domains.cf
668         $this->process_postfix_config('mysql-virtual_domains.cf');
669
670         //* mysql-virtual_forwardings.cf
671         $this->process_postfix_config('mysql-virtual_forwardings.cf');
672
673         //* mysql-virtual_mailboxes.cf
674         $this->process_postfix_config('mysql-virtual_mailboxes.cf');
675
676         //* mysql-virtual_email2email.cf
677         $this->process_postfix_config('mysql-virtual_email2email.cf');
678
679         //* mysql-virtual_transports.cf
680         $this->process_postfix_config('mysql-virtual_transports.cf');
681
682         //* mysql-virtual_recipient.cf
683         $this->process_postfix_config('mysql-virtual_recipient.cf');
684
685         //* mysql-virtual_sender.cf
686         $this->process_postfix_config('mysql-virtual_sender.cf');
687
688         //* mysql-virtual_client.cf
689         $this->process_postfix_config('mysql-virtual_client.cf');
690
691         //* mysql-virtual_relaydomains.cf
692         $this->process_postfix_config('mysql-virtual_relaydomains.cf');
693
694         //* mysql-virtual_relayrecipientmaps.cf
695         $this->process_postfix_config('mysql-virtual_relayrecipientmaps.cf');
696
697         //* Changing mode and group of the new created config files.
698         caselog('chmod o= '.$config_dir.'/mysql-virtual_*.cf* &> /dev/null',
7fe908 699             __FILE__, __LINE__, 'chmod on mysql-virtual_*.cf*', 'chmod on mysql-virtual_*.cf* failed');
532ae5 700         caselog('chgrp '.$cf['group'].' '.$config_dir.'/mysql-virtual_*.cf* &> /dev/null',
7fe908 701             __FILE__, __LINE__, 'chgrp on mysql-virtual_*.cf*', 'chgrp on mysql-virtual_*.cf* failed');
532ae5 702
L 703         //* Creating virtual mail user and group
704         $command = 'groupadd -g '.$cf['vmail_groupid'].' '.$cf['vmail_groupname'];
705         if(!is_group($cf['vmail_groupname'])) caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
706
707         $command = 'useradd -g '.$cf['vmail_groupname'].' -u '.$cf['vmail_userid'].' '.$cf['vmail_username'].' -d '.$cf['vmail_mailbox_base'].' -m';
708         if(!is_user($cf['vmail_username'])) caselog("$command &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
a8ccf6 709
b67344 710         //* These postconf commands will be executed on installation and update
4ed035 711         $server_ini_rec = $this->db->queryOneRecord("SELECT config FROM `" . $this->db->quote($conf["mysql"]["database"]) . "`.`server` WHERE server_id = ".$conf['server_id']);
a296ae 712         $server_ini_array = ini_to_array(stripslashes($server_ini_rec['config']));
M 713         unset($server_ini_rec);
714
715         //* If there are RBL's defined, format the list and add them to smtp_recipient_restrictions to prevent removeal after an update
716         $rbl_list = '';
6882ab 717         if (@isset($server_ini_array['mail']['realtime_blackhole_list']) && $server_ini_array['mail']['realtime_blackhole_list'] != '') {
7fe908 718             $rbl_hosts = explode(",", str_replace(" ", "", $server_ini_array['mail']['realtime_blackhole_list']));
a296ae 719             foreach ($rbl_hosts as $key => $value) {
M 720                 $rbl_list .= ", reject_rbl_client ". $value;
721             }
722         }
723         unset($rbl_hosts);
724         unset($server_ini_array);
7fe908 725
MC 726         $postconf_placeholders = array('{config_dir}' => $config_dir,
727             '{vmail_mailbox_base}' => $cf['vmail_mailbox_base'],
728             '{vmail_userid}' => $cf['vmail_userid'],
729             '{vmail_groupid}' => $cf['vmail_groupid'],
730             '{rbl_list}' => $rbl_list);
731
732         $postconf_tpl = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian_postfix.conf.master', 'tpl/debian_postfix.conf.master');
733         $postconf_tpl = strtr($postconf_tpl, $postconf_placeholders);
734         $postconf_commands = array_filter(explode("\n", $postconf_tpl)); // read and remove empty lines
a8ccf6 735
b67344 736         //* These postconf commands will be executed on installation only
T 737         if($this->is_update == false) {
7fe908 738             $postconf_commands = array_merge($postconf_commands, array(
MC 739                     'myhostname = '.$conf['hostname'],
740                     'mydestination = '.$conf['hostname'].', localhost, localhost.localdomain',
741                     'mynetworks = 127.0.0.0/8 [::1]/128'
742                 ));
b67344 743         }
532ae5 744
L 745         //* Create the header and body check files
746         touch($config_dir.'/header_checks');
747         touch($config_dir.'/mime_header_checks');
748         touch($config_dir.'/nested_header_checks');
749         touch($config_dir.'/body_checks');
a8ccf6 750
532ae5 751         //* Create the mailman files
cc6568 752         if(!is_dir('/var/lib/mailman/data')) exec('mkdir -p /var/lib/mailman/data');
5378e9 753         if(!is_file('/var/lib/mailman/data/aliases')) touch('/var/lib/mailman/data/aliases');
T 754         exec('postalias /var/lib/mailman/data/aliases');
755         if(!is_file('/var/lib/mailman/data/virtual-mailman')) touch('/var/lib/mailman/data/virtual-mailman');
d4d965 756         exec('postmap /var/lib/mailman/data/virtual-mailman');
cc6568 757         if(!is_file('/var/lib/mailman/data/transport-mailman')) touch('/var/lib/mailman/data/transport-mailman');
H 758         exec('/usr/sbin/postmap /var/lib/mailman/data/transport-mailman');
532ae5 759
L 760         //* Make a backup copy of the main.cf file
761         copy($config_dir.'/main.cf', $config_dir.'/main.cf~');
762
763         //* Executing the postconf commands
764         foreach($postconf_commands as $cmd) {
765             $command = "postconf -e '$cmd'";
766             caselog($command." &> /dev/null", __FILE__, __LINE__, 'EXECUTED: '.$command, 'Failed to execute the command '.$command);
767         }
768
7fe908 769         if(!stristr($options, 'dont-create-certs')) {
532ae5 770             //* Create the SSL certificate
b04e82 771             if(AUTOINSTALL){
bcd725 772                 $command = 'cd '.$config_dir.'; '
b04e82 773                     ."openssl req -new -subj '/C=".escapeshellcmd($autoinstall['ssl_cert_country'])."/ST=".escapeshellcmd($autoinstall['ssl_cert_state'])."/L=".escapeshellcmd($autoinstall['ssl_cert_locality'])."/O=".escapeshellcmd($autoinstall['ssl_cert_organisation'])."/OU=".escapeshellcmd($autoinstall['ssl_cert_organisation_unit'])."/CN=".escapeshellcmd($autoinstall['ssl_cert_common_name'])."' -outform PEM -out smtpd.cert -newkey rsa:4096 -nodes -keyout smtpd.key -keyform PEM -days 3650 -x509";
bcd725 774             } else {
FT 775                 $command = 'cd '.$config_dir.'; '
776                     .'openssl req -new -outform PEM -out smtpd.cert -newkey rsa:4096 -nodes -keyout smtpd.key -keyform PEM -days 3650 -x509';
777             }
532ae5 778             exec($command);
L 779
780             $command = 'chmod o= '.$config_dir.'/smtpd.key';
781             caselog($command.' &> /dev/null', __FILE__, __LINE__, 'EXECUTED: '.$command, 'Failed to execute the command '.$command);
782         }
783
784         //** We have to change the permissions of the courier authdaemon directory to make it accessible for maildrop.
785         $command = 'chmod 755  /var/run/courier/authdaemon/';
786         if(is_file('/var/run/courier/authdaemon/')) caselog($command.' &> /dev/null', __FILE__, __LINE__, 'EXECUTED: '.$command, 'Failed to execute the command '.$command);
787
788         //* Changing maildrop lines in posfix master.cf
789         if(is_file($config_dir.'/master.cf')) {
790             copy($config_dir.'/master.cf', $config_dir.'/master.cf~');
791         }
792         if(is_file($config_dir.'/master.cf~')) {
793             chmod($config_dir.'/master.cf~', 0400);
794         }
795         $configfile = $config_dir.'/master.cf';
796         $content = rf($configfile);
797         $content = str_replace('flags=DRhu user=vmail argv=/usr/bin/maildrop -d ${recipient}',
7fe908 798             'flags=DRhu user='.$cf['vmail_username'].' argv=/usr/bin/maildrop -d '.$cf['vmail_username'].' ${extension} ${recipient} ${user} ${nexthop} ${sender}',
MC 799             $content);
532ae5 800         wf($configfile, $content);
L 801
802         //* Writing the Maildrop mailfilter file
803         $configfile = 'mailfilter';
804         if(is_file($cf['vmail_mailbox_base'].'/.'.$configfile)) {
805             copy($cf['vmail_mailbox_base'].'/.'.$configfile, $cf['vmail_mailbox_base'].'/.'.$configfile.'~');
806         }
615a0a 807         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
532ae5 808         $content = str_replace('{dist_postfix_vmail_mailbox_base}', $cf['vmail_mailbox_base'], $content);
L 809         wf($cf['vmail_mailbox_base'].'/.'.$configfile, $content);
810
811         //* Create the directory for the custom mailfilters
812         if(!is_dir($cf['vmail_mailbox_base'].'/mailfilters')) {
813             $command = 'mkdir '.$cf['vmail_mailbox_base'].'/mailfilters';
814             caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
815         }
816
817         //* Chmod and chown the .mailfilter file
419eb7 818         $command = 'chown '.$cf['vmail_username'].':'.$cf['vmail_groupname'].' '.$cf['vmail_mailbox_base'].'/.mailfilter';
532ae5 819         caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
L 820
419eb7 821         $command = 'chmod 600 '.$cf['vmail_mailbox_base'].'/.mailfilter';
532ae5 822         caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
L 823
824     }
825
826     public function configure_saslauthd() {
827         global $conf;
a8ccf6 828
26c0fc 829         //* Get saslsauthd version
7fe908 830         exec('saslauthd -v 2>&1', $out);
MC 831         $parts = explode(' ', $out[0]);
26c0fc 832         $saslversion = $parts[1];
T 833         unset($parts);
834         unset($out);
532ae5 835
26c0fc 836         if(version_compare($saslversion , '2.1.23') > 0) {
T 837             //* Configfile for saslauthd versions 2.1.24 and newer
838             $configfile = 'sasl_smtpd2.conf';
839         } else {
840             //* Configfile for saslauthd versions up to 2.1.23
841             $configfile = 'sasl_smtpd.conf';
842         }
a8ccf6 843
7fe908 844         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~');
532ae5 845         if(is_file($conf['postfix']['config_dir'].'/sasl/smtpd.conf~')) chmod($conf['postfix']['config_dir'].'/sasl/smtpd.conf~', 0400);
615a0a 846         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
7fe908 847         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
MC 848         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
849         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
850         $content = str_replace('{mysql_server_ip}', $conf['mysql']['ip'], $content);
851         wf($conf['postfix']['config_dir'].'/sasl/smtpd.conf', $content);
532ae5 852
L 853         // TODO: Chmod and chown on the config file
854
855
856         // Recursively create the spool directory
857         if(!@is_dir('/var/spool/postfix/var/run/saslauthd')) mkdir('/var/spool/postfix/var/run/saslauthd', 0755, true);
858
859         // Edit the file /etc/default/saslauthd
860         $configfile = $conf['saslauthd']['config'];
7fe908 861         if(is_file($configfile)) copy($configfile, $configfile.'~');
532ae5 862         if(is_file($configfile.'~')) chmod($configfile.'~', 0400);
L 863         $content = rf($configfile);
7fe908 864         $content = str_replace('START=no', 'START=yes', $content);
532ae5 865         // Debian
7fe908 866         $content = str_replace('OPTIONS="-c"', 'OPTIONS="-m /var/spool/postfix/var/run/saslauthd -r"', $content);
532ae5 867         // Ubuntu
7fe908 868         $content = str_replace('OPTIONS="-c -m /var/run/saslauthd"', 'OPTIONS="-c -m /var/spool/postfix/var/run/saslauthd -r"', $content);
MC 869         wf($configfile, $content);
532ae5 870
L 871         // Edit the file /etc/init.d/saslauthd
872         $configfile = $conf['init_scripts'].'/'.$conf['saslauthd']['init_script'];
873         $content = rf($configfile);
7fe908 874         $content = str_replace('PIDFILE=$RUN_DIR/saslauthd.pid', 'PIDFILE="/var/spool/postfix/var/run/${NAME}/saslauthd.pid"', $content);
MC 875         wf($configfile, $content);
532ae5 876
L 877         // add the postfix user to the sasl group (at least necessary for Ubuntu 8.04 and most likely Debian Lenny as well.
878         exec('adduser postfix sasl');
879
880
881     }
882
883     public function configure_pam() {
884         global $conf;
885         $pam = $conf['pam'];
886         //* configure pam for SMTP authentication agains the ispconfig database
887         $configfile = 'pamd_smtp';
888         if(is_file($pam.'/smtp'))    copy($pam.'/smtp', $pam.'/smtp~');
889         if(is_file($pam.'/smtp~'))   chmod($pam.'/smtp~', 0400);
890
615a0a 891         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
532ae5 892         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
L 893         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
894         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
895         $content = str_replace('{mysql_server_ip}', $conf['mysql']['ip'], $content);
896         wf($pam.'/smtp', $content);
897         // On some OSes smtp is world readable which allows for reading database information.  Removing world readable rights should have no effect.
898         if(is_file($pam.'/smtp'))    exec("chmod o= $pam/smtp");
899         chmod($pam.'/smtp', 0660);
900         chown($pam.'/smtp', 'daemon');
901         chgrp($pam.'/smtp', 'daemon');
902
903     }
904
905     public function configure_courier() {
906         global $conf;
907         $config_dir = $conf['courier']['config_dir'];
908         //* authmysqlrc
909         $configfile = 'authmysqlrc';
910         if(is_file($config_dir.'/'.$configfile)) {
911             copy($config_dir.'/'.$configfile, $config_dir.'/'.$configfile.'~');
912         }
913         chmod($config_dir.'/'.$configfile.'~', 0400);
615a0a 914         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
7fe908 915         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
MC 916         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
917         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
918         $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content);
532ae5 919         wf($config_dir.'/'.$configfile, $content);
L 920
921         chmod($config_dir.'/'.$configfile, 0660);
922         chown($config_dir.'/'.$configfile, 'daemon');
923         chgrp($config_dir.'/'.$configfile, 'daemon');
924
925         //* authdaemonrc
926         $configfile = $config_dir.'/authdaemonrc';
927         if(is_file($configfile)) {
928             copy($configfile, $configfile.'~');
929         }
930         if(is_file($configfile.'~')) {
931             chmod($configfile.'~', 0400);
932         }
933         $content = rf($configfile);
934         $content = str_replace('authmodulelist="authpam"', 'authmodulelist="authmysql"', $content);
935         wf($configfile, $content);
936     }
937
938     public function configure_dovecot() {
939         global $conf;
940
941         $config_dir = $conf['dovecot']['config_dir'];
942
943         //* Configure master.cf and add a line for deliver
944         if(is_file($conf['postfix']['config_dir'].'/master.cf')) {
945             copy($conf['postfix']['config_dir'].'/master.cf', $conf['postfix']['config_dir'].'/master.cf~2');
946         }
947         if(is_file($conf['postfix']['config_dir'].'/master.cf~')) {
948             chmod($conf['postfix']['config_dir'].'/master.cf~2', 0400);
949         }
950         $content = rf($conf['postfix']['config_dir'].'/master.cf');
951         // Only add the content if we had not addded it before
7fe908 952         if(!stristr($content, 'dovecot/deliver')) {
013ae4 953             $deliver_content = 'dovecot   unix  -       n       n       -       -       pipe'."\n".'  flags=DROhu user=vmail:vmail argv=/usr/lib/dovecot/deliver -f ${sender} -d ${user}@${nexthop}';
7fe908 954             af($conf['postfix']['config_dir'].'/master.cf', $deliver_content);
532ae5 955         }
L 956         unset($content);
957         unset($deliver_content);
958
959
960         //* Reconfigure postfix to use dovecot authentication
961         // Adding the amavisd commands to the postfix configuration
962         $postconf_commands = array (
7fe908 963             'dovecot_destination_recipient_limit = 1',
MC 964             'virtual_transport = dovecot',
965             'smtpd_sasl_type = dovecot',
966             'smtpd_sasl_path = private/auth'
532ae5 967         );
L 968
969         // Make a backup copy of the main.cf file
7fe908 970         copy($conf['postfix']['config_dir'].'/main.cf', $conf['postfix']['config_dir'].'/main.cf~3');
532ae5 971
L 972         // Executing the postconf commands
973         foreach($postconf_commands as $cmd) {
974             $command = "postconf -e '$cmd'";
975             caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
976         }
977
31e0d1 978         //* backup dovecot.conf
532ae5 979         $configfile = 'dovecot.conf';
L 980         if(is_file($config_dir.'/'.$configfile)) {
981             copy($config_dir.'/'.$configfile, $config_dir.'/'.$configfile.'~');
982         }
a8ccf6 983
31e0d1 984         //* Get the dovecot version
7fe908 985         exec('dovecot --version', $tmp);
1fc360 986         $dovecot_version = $tmp[0];
31e0d1 987         unset($tmp);
a8ccf6 988
31e0d1 989         //* Copy dovecot configuration file
1fc360 990         if(version_compare($dovecot_version,2) >= 0) {
7fe908 991             if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian_dovecot2.conf.master')) {
MC 992                 copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian_dovecot2.conf.master', $config_dir.'/'.$configfile);
993             } else {
994                 copy('tpl/debian_dovecot2.conf.master', $config_dir.'/'.$configfile);
995             }
65576f 996             replaceLine($config_dir.'/'.$configfile, 'postmaster_address = postmaster@example.com', 'postmaster_address = postmaster@'.$conf['hostname'], 1, 0);
1fc360 997             if(version_compare($dovecot_version,2.1) < 0) {
TB 998                 removeLine($config_dir.'/'.$configfile, 'ssl_protocols =');
999             }
31e0d1 1000         } else {
7fe908 1001             if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian_dovecot.conf.master')) {
MC 1002                 copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian_dovecot.conf.master', $config_dir.'/'.$configfile);
1003             } else {
1004                 copy('tpl/debian_dovecot.conf.master', $config_dir.'/'.$configfile);
1005             }
31e0d1 1006         }
532ae5 1007
L 1008         //* dovecot-sql.conf
1009         $configfile = 'dovecot-sql.conf';
1010         if(is_file($config_dir.'/'.$configfile)) {
1011             copy($config_dir.'/'.$configfile, $config_dir.'/'.$configfile.'~');
1012         }
edf806 1013         if(is_file($config_dir.'/'.$configfile.'~')) chmod($config_dir.'/'.$configfile.'~', 0400);
615a0a 1014         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian_dovecot-sql.conf.master', 'tpl/debian_dovecot-sql.conf.master');
7fe908 1015         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
MC 1016         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1017         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
1018         $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content);
032b86 1019         $content = str_replace('{server_id}', $conf['server_id'], $content);
532ae5 1020         wf($config_dir.'/'.$configfile, $content);
L 1021
1022         chmod($config_dir.'/'.$configfile, 0600);
1023         chown($config_dir.'/'.$configfile, 'root');
1024         chgrp($config_dir.'/'.$configfile, 'root');
5e7306 1025         
TB 1026         // Dovecot shall ignore mounts in website directory
7db4cd 1027         if(is_installed('doveadm')) exec("doveadm mount add '/var/www/*' ignore > /dev/null 2> /dev/null");
532ae5 1028
L 1029     }
1030
1031     public function configure_amavis() {
1032         global $conf;
1033
1034         // amavisd user config file
1035         $configfile = 'amavisd_user_config';
7fe908 1036         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~');
532ae5 1037         if(is_file($conf['amavis']['config_dir'].'/conf.d/50-user~')) chmod($conf['amavis']['config_dir'].'/conf.d/50-user~', 0400);
615a0a 1038         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
7fe908 1039         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
MC 1040         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1041         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
1042         $content = str_replace('{mysql_server_port}', $conf['mysql']['port'], $content);
1043         $content = str_replace('{mysql_server_ip}', $conf['mysql']['ip'], $content);
1044         wf($conf['amavis']['config_dir'].'/conf.d/50-user', $content);
532ae5 1045
L 1046         // TODO: chmod and chown on the config file
1047
1048
1049         // Adding the amavisd commands to the postfix configuration
864ee2 1050         // Add array for no error in foreach and maybe future options
X 1051         $postconf_commands = array ();
a8ccf6 1052
864ee2 1053         // Check for amavisd -> pure webserver with postfix for mailing without antispam
ac28b5 1054         if ($conf['amavis']['installed']) {
864ee2 1055             $postconf_commands[] = 'content_filter = amavis:[127.0.0.1]:10024';
X 1056             $postconf_commands[] = 'receive_override_options = no_address_mappings';
1057         }
532ae5 1058
L 1059         // Make a backup copy of the main.cf file
7fe908 1060         copy($conf['postfix']['config_dir'].'/main.cf', $conf['postfix']['config_dir'].'/main.cf~2');
532ae5 1061
L 1062         // Executing the postconf commands
1063         foreach($postconf_commands as $cmd) {
1064             $command = "postconf -e '$cmd'";
1065             caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1066         }
1067
1068         // Append the configuration for amavisd to the master.cf file
7fe908 1069         if(is_file($conf['postfix']['config_dir'].'/master.cf')) copy($conf['postfix']['config_dir'].'/master.cf', $conf['postfix']['config_dir'].'/master.cf~');
532ae5 1070         $content = rf($conf['postfix']['config_dir'].'/master.cf');
L 1071         // Only add the content if we had not addded it before
7fe908 1072         if(!stristr($content, '127.0.0.1:10025')) {
532ae5 1073             unset($content);
615a0a 1074             $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/master_cf_amavis.master', 'tpl/master_cf_amavis.master');
7fe908 1075             af($conf['postfix']['config_dir'].'/master.cf', $content);
532ae5 1076         }
L 1077         unset($content);
1078
1079         // Add the clamav user to the amavis group
1080         exec('adduser clamav amavis');
1081
1082
1083     }
1084
1085     public function configure_spamassassin() {
1086         global $conf;
1087
1088         //* Enable spamasasssin on debian and ubuntu
1089         $configfile = '/etc/default/spamassassin';
1090         if(is_file($configfile)) {
1091             copy($configfile, $configfile.'~');
1092         }
1093         $content = rf($configfile);
1094         $content = str_replace('ENABLED=0', 'ENABLED=1', $content);
1095         wf($configfile, $content);
1096     }
1097
1098     public function configure_getmail() {
1099         global $conf;
1100
1101         $config_dir = $conf['getmail']['config_dir'];
1102
1103         if(!@is_dir($config_dir)) mkdir(escapeshellcmd($config_dir), 0700, true);
1104
1105         $command = 'useradd -d '.$config_dir.' getmail';
1106         if(!is_user('getmail')) caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1107
1108         $command = "chown -R getmail $config_dir";
1109         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1110
1111         $command = "chmod -R 700 $config_dir";
1112         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1113     }
1114
1115
1116     public function configure_pureftpd() {
acdd7a 1117         global $conf;
532ae5 1118
L 1119         $config_dir = $conf['pureftpd']['config_dir'];
1120
1121         //* configure pure-ftpd for MySQL authentication against the ispconfig database
1122         $configfile = 'db/mysql.conf';
1123         if(is_file($config_dir.'/'.$configfile)) {
1124             copy($config_dir.'/'.$configfile, $config_dir.'/'.$configfile.'~');
1125         }
1126         if(is_file($config_dir.'/'.$configfile.'~')) {
1127             chmod($config_dir.'/'.$configfile.'~', 0400);
1128         }
615a0a 1129         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/pureftpd_mysql.conf.master', 'tpl/pureftpd_mysql.conf.master');
532ae5 1130         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
L 1131         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1132         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
1133         $content = str_replace('{mysql_server_ip}', $conf['mysql']['ip'], $content);
1134         $content = str_replace('{server_id}', $conf['server_id'], $content);
1135         wf($config_dir.'/'.$configfile, $content);
1136         chmod($config_dir.'/'.$configfile, 0600);
1137         chown($config_dir.'/'.$configfile, 'root');
1138         chgrp($config_dir.'/'.$configfile, 'root');
1139         // **enable chrooting
1140         //exec('mkdir -p '.$config_dir.'/conf/ChrootEveryone');
1141         exec('echo "yes" > '.$config_dir.'/conf/ChrootEveryone');
1142         exec('echo "yes" > '.$config_dir.'/conf/BrokenClientsCompatibility');
1143         exec('echo "yes" > '.$config_dir.'/conf/DisplayDotFiles');
1144
1145         if(is_file('/etc/default/pure-ftpd-common')) {
7fe908 1146             replaceLine('/etc/default/pure-ftpd-common', 'STANDALONE_OR_INETD=inetd', 'STANDALONE_OR_INETD=standalone', 1, 0);
MC 1147             replaceLine('/etc/default/pure-ftpd-common', 'VIRTUALCHROOT=false', 'VIRTUALCHROOT=true', 1, 0);
532ae5 1148         }
L 1149
1150         if(is_file('/etc/inetd.conf')) {
7fe908 1151             replaceLine('/etc/inetd.conf', '/usr/sbin/pure-ftpd-wrapper', '#ftp     stream  tcp     nowait  root    /usr/sbin/tcpd /usr/sbin/pure-ftpd-wrapper', 0, 0);
acdd7a 1152             exec($this->getinitcommand('openbsd-inetd', 'restart'));
33bcd0 1153             //if(is_file($conf['init_scripts'].'/'.'openbsd-inetd')) exec($conf['init_scripts'].'/'.'openbsd-inetd restart');
532ae5 1154         }
L 1155
1156         if(!is_file('/etc/pure-ftpd/conf/DontResolve')) exec('echo "yes" > /etc/pure-ftpd/conf/DontResolve');
1157     }
1158
1159     public function configure_mydns() {
1160         global $conf;
1161
1162         // configure pam for SMTP authentication agains the ispconfig database
1163         $configfile = 'mydns.conf';
7fe908 1164         if(is_file($conf['mydns']['config_dir'].'/'.$configfile)) copy($conf['mydns']['config_dir'].'/'.$configfile, $conf['mydns']['config_dir'].'/'.$configfile.'~');
532ae5 1165         if(is_file($conf['mydns']['config_dir'].'/'.$configfile.'~')) chmod($conf['mydns']['config_dir'].'/'.$configfile.'~', 0400);
615a0a 1166         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
7fe908 1167         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
MC 1168         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1169         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
1170         $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content);
1171         $content = str_replace('{server_id}', $conf['server_id'], $content);
1172         wf($conf['mydns']['config_dir'].'/'.$configfile, $content);
532ae5 1173         chmod($conf['mydns']['config_dir'].'/'.$configfile, 0600);
L 1174         chown($conf['mydns']['config_dir'].'/'.$configfile, 'root');
1175         chgrp($conf['mydns']['config_dir'].'/'.$configfile, 'root');
1176
1177     }
1178
1179     public function configure_powerdns() {
1180         global $conf;
1181
1182         //* Create the database
1183         if(!$this->db->query('CREATE DATABASE IF NOT EXISTS '.$conf['powerdns']['database'].' DEFAULT CHARACTER SET '.$conf['mysql']['charset'])) {
1184             $this->error('Unable to create MySQL database: '.$conf['powerdns']['database'].'.');
1185         }
1186
1187         //* Create the ISPConfig database user in the local database
1188         $query = "GRANT ALL ON `".$conf['powerdns']['database']."` . * TO '".$conf['mysql']['ispconfig_user']."'@'localhost';";
1189         if(!$this->db->query($query)) {
1190             $this->error('Unable to create user for powerdns database Error: '.$this->db->errorMessage);
1191         }
1192
1193         //* Reload database privelages
1194         $this->db->query('FLUSH PRIVILEGES;');
1195
1196         //* load the powerdns databse dump
1197         if($conf['mysql']['admin_password'] == '') {
1198             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",
7fe908 1199                 __FILE__, __LINE__, 'read in ispconfig3.sql', 'could not read in powerdns.sql');
532ae5 1200         } else {
L 1201             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",
7fe908 1202                 __FILE__, __LINE__, 'read in ispconfig3.sql', 'could not read in powerdns.sql');
532ae5 1203         }
L 1204
1205         //* Create the powerdns config file
1206         $configfile = 'pdns.local';
7fe908 1207         if(is_file($conf['powerdns']['config_dir'].'/'.$configfile)) copy($conf['powerdns']['config_dir'].'/'.$configfile, $conf['powerdns']['config_dir'].'/'.$configfile.'~');
532ae5 1208         if(is_file($conf['powerdns']['config_dir'].'/'.$configfile.'~')) chmod($conf['powerdns']['config_dir'].'/'.$configfile.'~', 0400);
615a0a 1209         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
7fe908 1210         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
MC 1211         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1212         $content = str_replace('{powerdns_database}', $conf['powerdns']['database'], $content);
1213         $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content);
1214         wf($conf['powerdns']['config_dir'].'/'.$configfile, $content);
532ae5 1215         chmod($conf['powerdns']['config_dir'].'/'.$configfile, 0600);
L 1216         chown($conf['powerdns']['config_dir'].'/'.$configfile, 'root');
1217         chgrp($conf['powerdns']['config_dir'].'/'.$configfile, 'root');
1218
1219
1220     }
1221
1222     public function configure_bind() {
1223         global $conf;
1224
7fe908 1225         //* Check if the zonefile directory has a slash at the end
MC 1226         $content=$conf['bind']['bind_zonefiles_dir'];
1227         if(substr($content, -1, 1) != '/') {
1228             $content .= '/';
532ae5 1229         }
L 1230
1231         //* Create the slave subdirectory
7fe908 1232         $content .= 'slave';
MC 1233         if(!@is_dir($content)) mkdir($content, 0770, true);
532ae5 1234
7fe908 1235         //* Chown the slave subdirectory to $conf['bind']['bind_user']
MC 1236         chown($content, $conf['bind']['bind_user']);
1237         chgrp($content, $conf['bind']['bind_group']);
532ae5 1238
L 1239     }
1240
1241
1242
1243     public function configure_apache() {
1244         global $conf;
1245
4ffb51 1246         if($conf['apache']['installed'] == false) return;
532ae5 1247         //* Create the logging directory for the vhost logfiles
L 1248         if(!@is_dir($conf['ispconfig_log_dir'].'/httpd')) mkdir($conf['ispconfig_log_dir'].'/httpd', 0755, true);
1249
1250         if(is_file('/etc/suphp/suphp.conf')) {
7fe908 1251             replaceLine('/etc/suphp/suphp.conf', 'php=php:/usr/bin', 'x-httpd-suphp="php:/usr/bin/php-cgi"', 0);
532ae5 1252             //replaceLine('/etc/suphp/suphp.conf','docroot=','docroot=/var/clients',0);
7fe908 1253             replaceLine('/etc/suphp/suphp.conf', 'umask=0077', 'umask=0022', 0);
532ae5 1254         }
L 1255
1256         if(is_file('/etc/apache2/sites-enabled/000-default')) {
7fe908 1257             replaceLine('/etc/apache2/sites-available/000-default', 'NameVirtualHost *', 'NameVirtualHost *:80', 1, 0);
MC 1258             replaceLine('/etc/apache2/sites-available/000-default', '<VirtualHost *>', '<VirtualHost *:80>', 1, 0);
532ae5 1259         }
L 1260
1261         if(is_file('/etc/apache2/ports.conf')) {
1262             // add a line "Listen 443" to ports conf if line does not exist
7fe908 1263             replaceLine('/etc/apache2/ports.conf', 'Listen 443', 'Listen 443', 1);
14001d 1264             
TB 1265             // Comment out the namevirtualhost lines, as they were added by ispconfig in ispconfig.conf file again
1266             replaceLine('/etc/apache2/ports.conf', 'NameVirtualHost *:80', '# NameVirtualHost *:80', 1);
1267             replaceLine('/etc/apache2/ports.conf', 'NameVirtualHost *:443', '# NameVirtualHost *:443', 1);
532ae5 1268         }
L 1269
8eca28 1270         if(is_file('/etc/apache2/apache.conf')) {
MC 1271             if(hasLine('/etc/apache2/apache.conf', 'Include sites-enabled/', 1) == false) {
39e5f0 1272                 if(hasLine('/etc/apache2/apache.conf', 'IncludeOptional sites-enabled/*.conf', 1) == false && hasLine('/etc/apache2/apache.conf', 'IncludeOptional sites-enabled/', 1) == false) {
8eca28 1273                     replaceLine('/etc/apache2/apache.conf', 'Include sites-enabled/', 'Include sites-enabled/', 1, 1);
MC 1274                 } elseif(hasLine('/etc/apache2/apache.conf', 'IncludeOptional sites-enabled/*.vhost', 1) == false) {
39e5f0 1275                     replaceLine('/etc/apache2/apache.conf', 'IncludeOptional sites-enabled/*.vhost', 'IncludeOptional sites-enabled/', 1, 1);
TB 1276                 }
1277             }
1278         }
1279         
1280         if(is_file('/etc/apache2/apache2.conf')) {
1281             if(hasLine('/etc/apache2/apache2.conf', 'Include sites-enabled/', 1) == false && hasLine('/etc/apache2/apache2.conf', 'IncludeOptional sites-enabled/', 1) == false) {
d10d15 1282                 if(hasLine('/etc/apache2/apache2.conf', 'Include sites-enabled/*.conf', 1) == true) {
TB 1283                     replaceLine('/etc/apache2/apache2.conf', 'Include sites-enabled/*.conf', 'Include sites-enabled/', 1, 1);
39e5f0 1284                 } elseif(hasLine('/etc/apache2/apache2.conf', 'IncludeOptional sites-enabled/*.conf', 1) == true) {
TB 1285                     replaceLine('/etc/apache2/apache2.conf', 'IncludeOptional sites-enabled/*.conf', 'IncludeOptional sites-enabled/', 1, 1);
8eca28 1286                 }
MC 1287             }
1288         }
532ae5 1289
L 1290         //* Copy the ISPConfig configuration include
1291         $vhost_conf_dir = $conf['apache']['vhost_conf_dir'];
1292         $vhost_conf_enabled_dir = $conf['apache']['vhost_conf_enabled_dir'];
1293
ccbf14 1294         $tpl = new tpl('apache_ispconfig.conf.master');
TB 1295         $tpl->setVar('apache_version',getapacheversion());
1296         
532ae5 1297         $records = $this->db->queryAllRecords('SELECT * FROM '.$conf['mysql']['master_database'].'.server_ip WHERE server_id = '.$conf['server_id']." AND virtualhost = 'y'");
ccbf14 1298         $ip_addresses = array();
TB 1299         
532ae5 1300         if(is_array($records) && count($records) > 0) {
L 1301             foreach($records as $rec) {
a2156e 1302                 if($rec['ip_type'] == 'IPv6') {
T 1303                     $ip_address = '['.$rec['ip_address'].']';
1304                 } else {
1305                     $ip_address = $rec['ip_address'];
1306                 }
7fe908 1307                 $ports = explode(',', $rec['virtualhost_port']);
a2156e 1308                 if(is_array($ports)) {
T 1309                     foreach($ports as $port) {
1310                         $port = intval($port);
1311                         if($port > 0 && $port < 65536 && $ip_address != '') {
ccbf14 1312                             $ip_addresses[] = array('ip_address' => $ip_address, 'port' => $port);
a2156e 1313                         }
T 1314                     }
1315                 }
532ae5 1316             }
L 1317         }
855547 1318         
3de838 1319         if(count($ip_addresses) > 0) $tpl->setLoop('ip_adresses',$ip_addresses);
855547 1320         
ccbf14 1321         wf($vhost_conf_dir.'/ispconfig.conf', $tpl->grab());
TB 1322         unset($tpl);
532ae5 1323
L 1324         if(!@is_link($vhost_conf_enabled_dir.'/000-ispconfig.conf')) {
7fe908 1325             symlink($vhost_conf_dir.'/ispconfig.conf', $vhost_conf_enabled_dir.'/000-ispconfig.conf');
532ae5 1326         }
L 1327
1328         //* make sure that webalizer finds its config file when it is directly in /etc
1329         if(@is_file('/etc/webalizer.conf') && !@is_dir('/etc/webalizer')) {
1330             mkdir('/etc/webalizer');
7fe908 1331             symlink('/etc/webalizer.conf', '/etc/webalizer/webalizer.conf');
532ae5 1332         }
L 1333
1334         if(is_file('/etc/webalizer/webalizer.conf')) {
1335             // Change webalizer mode to incremental
7fe908 1336             replaceLine('/etc/webalizer/webalizer.conf', '#IncrementalName', 'IncrementalName webalizer.current', 0, 0);
MC 1337             replaceLine('/etc/webalizer/webalizer.conf', '#Incremental', 'Incremental     yes', 0, 0);
1338             replaceLine('/etc/webalizer/webalizer.conf', '#HistoryName', 'HistoryName     webalizer.hist', 0, 0);
532ae5 1339         }
a8ccf6 1340
532ae5 1341         // Check the awsatst script
L 1342         if(!is_dir('/usr/share/awstats/tools')) exec('mkdir -p /usr/share/awstats/tools');
7fe908 1343         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');
MC 1344         if(file_exists('/etc/awstats/awstats.conf.local')) replaceLine('/etc/awstats/awstats.conf.local', 'LogFormat=4', 'LogFormat=1', 0, 1);
a8ccf6 1345
532ae5 1346         //* add a sshusers group
L 1347         $command = 'groupadd sshusers';
1348         if(!is_group('sshusers')) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1349
1350     }
a8ccf6 1351
4ffb51 1352     public function configure_nginx(){
80e3c9 1353         global $conf;
a8ccf6 1354
4ffb51 1355         if($conf['nginx']['installed'] == false) return;
F 1356         //* Create the logging directory for the vhost logfiles
1357         if(!@is_dir($conf['ispconfig_log_dir'].'/httpd')) mkdir($conf['ispconfig_log_dir'].'/httpd', 0755, true);
1358
1359         //* make sure that webalizer finds its config file when it is directly in /etc
1360         if(@is_file('/etc/webalizer.conf') && !@is_dir('/etc/webalizer')) {
1361             mkdir('/etc/webalizer');
7fe908 1362             symlink('/etc/webalizer.conf', '/etc/webalizer/webalizer.conf');
4ffb51 1363         }
F 1364
1365         if(is_file('/etc/webalizer/webalizer.conf')) {
1366             // Change webalizer mode to incremental
7fe908 1367             replaceLine('/etc/webalizer/webalizer.conf', '#IncrementalName', 'IncrementalName webalizer.current', 0, 0);
MC 1368             replaceLine('/etc/webalizer/webalizer.conf', '#Incremental', 'Incremental     yes', 0, 0);
1369             replaceLine('/etc/webalizer/webalizer.conf', '#HistoryName', 'HistoryName     webalizer.hist', 0, 0);
4ffb51 1370         }
a8ccf6 1371
4ffb51 1372         // Check the awsatst script
F 1373         if(!is_dir('/usr/share/awstats/tools')) exec('mkdir -p /usr/share/awstats/tools');
7fe908 1374         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');
MC 1375         if(file_exists('/etc/awstats/awstats.conf.local')) replaceLine('/etc/awstats/awstats.conf.local', 'LogFormat=4', 'LogFormat=1', 0, 1);
a8ccf6 1376
4ffb51 1377         //* add a sshusers group
F 1378         $command = 'groupadd sshusers';
1379         if(!is_group('sshusers')) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
a8ccf6 1380
4ffb51 1381         /*
80e3c9 1382         $row = $this->db->queryOneRecord("SELECT server_name FROM server WHERE server_id = ".$conf["server_id"]."");
T 1383         $ip_address = gethostbyname($row["server_name"]);
1384         $server_name = $row["server_name"];
1385
1386         //setup proxy.conf
1387         $configfile = 'proxy.conf';
1388         if(is_file($conf["nginx"]["config_dir"].'/'.$configfile)) copy($conf["nginx"]["config_dir"].'/'.$configfile,$conf["nginx"]["config_dir"].'/'.$configfile.'~');
1389         if(is_file($conf["nginx"]["config_dir"].'/'.$configfile.'~')) exec('chmod 400 '.$conf["nginx"]["config_dir"].'/'.$configfile.'~');
1390         $content = rf("tpl/nginx_".$configfile.".master");
1391         wf($conf["nginx"]["config_dir"].'/'.$configfile,$content);
1392         exec('chmod 600 '.$conf["nginx"]["config_dir"].'/'.$configfile);
1393         exec('chown root:root '.$conf["nginx"]["config_dir"].'/'.$configfile);
1394
1395         //setup conf.d/cache.conf
1396         $configfile = 'cache.conf';
1397         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.'~');
1398         if(is_file($conf["nginx"]["config_dir"].'/conf.d/'.$configfile.'~')) exec('chmod 400 '.$conf["nginx"]["config_dir"].'/conf.d/'.$configfile.'~');
1399         $content = rf("tpl/nginx_".$configfile.".master");
1400         wf($conf["nginx"]["config_dir"].'/conf.d/'.$configfile,$content);
1401         exec('chmod 600 '.$conf["nginx"]["config_dir"].'/conf.d/'.$configfile);
1402         exec('chown root:root '.$conf["nginx"]["config_dir"].'/conf.d/'.$configfile);
1403
1404         //setup cache directories
1405         mkdir('/var/cache/nginx/cache');
1406         exec('chown www-data:www-data /var/cache/nginx/cache');
1407         mkdir('/var/cache/nginx/temp');
1408         exec('chown www-data:www-data /var/cache/nginx/temp');
4ffb51 1409         */
80e3c9 1410     }
a8ccf6 1411
d083f2 1412     public function configure_fail2ban() {
7fe908 1413         // To Do
MC 1414     }
a8ccf6 1415
80e3c9 1416     public function configure_squid()
T 1417     {
1418         global $conf;
1419         $row = $this->db->queryOneRecord("SELECT server_name FROM server WHERE server_id = ".$conf["server_id"]."");
1420         $ip_address = gethostbyname($row["server_name"]);
1421         $server_name = $row["server_name"];
a8ccf6 1422
80e3c9 1423         $configfile = 'squid.conf';
7fe908 1424         if(is_file($conf["squid"]["config_dir"].'/'.$configfile)) copy($conf["squid"]["config_dir"].'/'.$configfile, $conf["squid"]["config_dir"].'/'.$configfile.'~');
80e3c9 1425         if(is_file($conf["squid"]["config_dir"].'/'.$configfile.'~')) exec('chmod 400 '.$conf["squid"]["config_dir"].'/'.$configfile.'~');
615a0a 1426         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', "tpl/".$configfile.".master");
7fe908 1427         $content = str_replace('{server_name}', $server_name, $content);
MC 1428         $content = str_replace('{ip_address}', $ip_address, $content);
1429         $content = str_replace('{config_dir}', $conf['squid']['config_dir'], $content);
1430         wf($conf["squid"]["config_dir"].'/'.$configfile, $content);
80e3c9 1431         exec('chmod 600 '.$conf["squid"]["config_dir"].'/'.$configfile);
T 1432         exec('chown root:root '.$conf["squid"]["config_dir"].'/'.$configfile);
1433     }
a8ccf6 1434
992797 1435     /*
80e3c9 1436     public function configure_ufw_firewall()
T 1437     {
1438         $configfile = 'ufw.conf';
1439         if(is_file('/etc/ufw/ufw.conf')) copy('/etc/ufw/ufw.conf','/etc/ufw/ufw.conf~');
1440         $content = rf("tpl/".$configfile.".master");
1441         wf('/etc/ufw/ufw.conf',$content);
1442         exec('chmod 600 /etc/ufw/ufw.conf');
a8ccf6 1443         exec('chown root:root /etc/ufw/ufw.conf');
80e3c9 1444     }
992797 1445     */
532ae5 1446
992797 1447     public function configure_firewall() {
532ae5 1448         global $conf;
L 1449
1450         $dist_init_scripts = $conf['init_scripts'];
1451
1452         if(is_dir('/etc/Bastille.backup')) caselog('rm -rf /etc/Bastille.backup', __FILE__, __LINE__);
1453         if(is_dir('/etc/Bastille')) caselog('mv -f /etc/Bastille /etc/Bastille.backup', __FILE__, __LINE__);
1454         @mkdir('/etc/Bastille', 0700);
1455         if(is_dir('/etc/Bastille.backup/firewall.d')) caselog('cp -pfr /etc/Bastille.backup/firewall.d /etc/Bastille/', __FILE__, __LINE__);
615a0a 1456         if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/bastille-firewall.cfg.master')) {
7fe908 1457             caselog('cp -f ' . $conf['ispconfig_install_dir'].'/server/conf-custom/install/bastille-firewall.cfg.master /etc/Bastille/bastille-firewall.cfg', __FILE__, __LINE__);
MC 1458         } else {
1459             caselog('cp -f tpl/bastille-firewall.cfg.master /etc/Bastille/bastille-firewall.cfg', __FILE__, __LINE__);
1460         }
532ae5 1461         caselog('chmod 644 /etc/Bastille/bastille-firewall.cfg', __FILE__, __LINE__);
L 1462         $content = rf('/etc/Bastille/bastille-firewall.cfg');
1463         $content = str_replace('{DNS_SERVERS}', '', $content);
1464
1465         $tcp_public_services = '';
1466         $udp_public_services = '';
1467
1468         $row = $this->db->queryOneRecord('SELECT * FROM '.$conf["mysql"]["database"].'.firewall WHERE server_id = '.intval($conf['server_id']));
1469
1470         if(trim($row['tcp_port']) != '' || trim($row['udp_port']) != '') {
7fe908 1471             $tcp_public_services = trim(str_replace(',', ' ', $row['tcp_port']));
MC 1472             $udp_public_services = trim(str_replace(',', ' ', $row['udp_port']));
532ae5 1473         } else {
L 1474             $tcp_public_services = '21 22 25 53 80 110 143 443 3306 8080 10000';
1475             $udp_public_services = '53';
1476         }
1477
1478         if(!stristr($tcp_public_services, $conf['apache']['vhost_port'])) {
1479             $tcp_public_services .= ' '.intval($conf['apache']['vhost_port']);
1480             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']));
1481         }
1482
1483         $content = str_replace('{TCP_PUBLIC_SERVICES}', $tcp_public_services, $content);
1484         $content = str_replace('{UDP_PUBLIC_SERVICES}', $udp_public_services, $content);
1485
1486         wf('/etc/Bastille/bastille-firewall.cfg', $content);
1487
1488         if(is_file($dist_init_scripts.'/bastille-firewall')) caselog('mv -f '.$dist_init_scripts.'/bastille-firewall '.$dist_init_scripts.'/bastille-firewall.backup', __FILE__, __LINE__);
1489         caselog('cp -f apps/bastille-firewall '.$dist_init_scripts, __FILE__, __LINE__);
1490         caselog('chmod 700 '.$dist_init_scripts.'/bastille-firewall', __FILE__, __LINE__);
1491
1492         if(is_file('/sbin/bastille-ipchains')) caselog('mv -f /sbin/bastille-ipchains /sbin/bastille-ipchains.backup', __FILE__, __LINE__);
1493         caselog('cp -f apps/bastille-ipchains /sbin', __FILE__, __LINE__);
1494         caselog('chmod 700 /sbin/bastille-ipchains', __FILE__, __LINE__);
1495
1496         if(is_file('/sbin/bastille-netfilter')) caselog('mv -f /sbin/bastille-netfilter /sbin/bastille-netfilter.backup', __FILE__, __LINE__);
1497         caselog('cp -f apps/bastille-netfilter /sbin', __FILE__, __LINE__);
1498         caselog('chmod 700 /sbin/bastille-netfilter', __FILE__, __LINE__);
1499
1500         if(!@is_dir('/var/lock/subsys')) caselog('mkdir /var/lock/subsys', __FILE__, __LINE__);
1501
1502         exec('which ipchains &> /dev/null', $ipchains_location, $ret_val);
1503         if(!is_file('/sbin/ipchains') && !is_link('/sbin/ipchains') && $ret_val == 0) phpcaselog(@symlink(shell_exec('which ipchains'), '/sbin/ipchains'), 'create symlink', __FILE__, __LINE__);
1504         unset($ipchains_location);
1505         exec('which iptables &> /dev/null', $iptables_location, $ret_val);
1506         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__);
1507         unset($iptables_location);
1508
1509     }
1510
1511     public function configure_vlogger() {
1512         global $conf;
1513
1514         //** Configure vlogger to use traffic logging to mysql (master) db
1515         $configfile = 'vlogger-dbi.conf';
7fe908 1516         if(is_file($conf['vlogger']['config_dir'].'/'.$configfile)) copy($conf['vlogger']['config_dir'].'/'.$configfile, $conf['vlogger']['config_dir'].'/'.$configfile.'~');
532ae5 1517         if(is_file($conf['vlogger']['config_dir'].'/'.$configfile.'~')) chmod($conf['vlogger']['config_dir'].'/'.$configfile.'~', 0400);
615a0a 1518         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
532ae5 1519         if($conf['mysql']['master_slave_setup'] == 'y') {
7fe908 1520             $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['master_ispconfig_user'], $content);
MC 1521             $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['master_ispconfig_password'], $content);
1522             $content = str_replace('{mysql_server_database}', $conf['mysql']['master_database'], $content);
1523             $content = str_replace('{mysql_server_ip}', $conf['mysql']['master_host'], $content);
532ae5 1524         } else {
7fe908 1525             $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
MC 1526             $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1527             $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
1528             $content = str_replace('{mysql_server_ip}', $conf['mysql']['ip'], $content);
532ae5 1529         }
7fe908 1530         wf($conf['vlogger']['config_dir'].'/'.$configfile, $content);
532ae5 1531         chmod($conf['vlogger']['config_dir'].'/'.$configfile, 0600);
L 1532         chown($conf['vlogger']['config_dir'].'/'.$configfile, 'root');
1533         chgrp($conf['vlogger']['config_dir'].'/'.$configfile, 'root');
1534
1535     }
1536
1537     public function configure_apps_vhost() {
1538         global $conf;
1539
1540         //* Create the ispconfig apps vhost user and group
165152 1541         if($conf['apache']['installed'] == true){
4ffb51 1542             $apps_vhost_user = escapeshellcmd($conf['web']['apps_vhost_user']);
F 1543             $apps_vhost_group = escapeshellcmd($conf['web']['apps_vhost_group']);
1544             $install_dir = escapeshellcmd($conf['web']['website_basedir'].'/apps');
532ae5 1545
4ffb51 1546             $command = 'groupadd '.$apps_vhost_user;
F 1547             if(!is_group($apps_vhost_group)) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
532ae5 1548
4ffb51 1549             $command = 'useradd -g '.$apps_vhost_group.' -d '.$install_dir.' '.$apps_vhost_group;
F 1550             if(!is_user($apps_vhost_user)) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
532ae5 1551
L 1552
5edf40 1553             //$command = 'adduser '.$conf['apache']['user'].' '.$apps_vhost_group;
TB 1554             $command = 'usermod -a -G '.$apps_vhost_group.' '.$conf['apache']['user'];
4ffb51 1555             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
532ae5 1556
99b55b 1557             if(!@is_dir($install_dir)){
F 1558                 mkdir($install_dir, 0755, true);
1559             } else {
1560                 chmod($install_dir, 0755);
1561             }
4ffb51 1562             chown($install_dir, $apps_vhost_user);
F 1563             chgrp($install_dir, $apps_vhost_group);
532ae5 1564
4ffb51 1565             //* Copy the apps vhost file
F 1566             $vhost_conf_dir = $conf['apache']['vhost_conf_dir'];
1567             $vhost_conf_enabled_dir = $conf['apache']['vhost_conf_enabled_dir'];
1568             $apps_vhost_servername = ($conf['web']['apps_vhost_servername'] == '')?'':'ServerName '.$conf['web']['apps_vhost_servername'];
d0356f 1569             
TB 1570             //* Get the apps vhost port
1571             if($this->is_update == true) {
1572                 $conf['web']['apps_vhost_port'] = get_apps_vhost_port_number();
1573             }
532ae5 1574
4ffb51 1575             // Dont just copy over the virtualhost template but add some custom settings
ccbf14 1576             $tpl = new tpl('apache_apps.vhost.master');
TB 1577             $tpl->setVar('apps_vhost_ip',$conf['web']['apps_vhost_ip']);
1578             $tpl->setVar('apps_vhost_port',$conf['web']['apps_vhost_port']);
1579             $tpl->setVar('apps_vhost_dir',$conf['web']['website_basedir'].'/apps');
1580             $tpl->setVar('apps_vhost_basedir',$conf['web']['website_basedir']);
1581             $tpl->setVar('apps_vhost_servername',$apps_vhost_servername);
1582             $tpl->setVar('apache_version',getapacheversion());
532ae5 1583
L 1584
4ffb51 1585             // comment out the listen directive if port is 80 or 443
F 1586             if($conf['web']['apps_vhost_ip'] == 80 or $conf['web']['apps_vhost_ip'] == 443) {
ccbf14 1587                 $tpl->setVar('vhost_port_listen','#');
4ffb51 1588             } else {
ccbf14 1589                 $tpl->setVar('vhost_port_listen','');
4ffb51 1590             }
532ae5 1591
ccbf14 1592             wf($vhost_conf_dir.'/apps.vhost', $tpl->grab());
TB 1593             unset($tpl);
532ae5 1594
4ffb51 1595             //copy('tpl/apache_ispconfig.vhost.master', "$vhost_conf_dir/ispconfig.vhost");
F 1596             //* and create the symlink
7e1cfb 1597             if(@is_link($vhost_conf_enabled_dir.'/apps.vhost')) unlink($vhost_conf_enabled_dir.'/apps.vhost');
F 1598             if(!@is_link($vhost_conf_enabled_dir.'/000-apps.vhost')) {
7fe908 1599                 symlink($vhost_conf_dir.'/apps.vhost', $vhost_conf_enabled_dir.'/000-apps.vhost');
4ffb51 1600             }
a8ccf6 1601
4ffb51 1602             if(!is_file($conf['web']['website_basedir'].'/php-fcgi-scripts/apps/.php-fcgi-starter')) {
615a0a 1603                 $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/apache_apps_fcgi_starter.master', 'tpl/apache_apps_fcgi_starter.master');
526b99 1604                 $content = str_replace('{fastcgi_bin}', $conf['fastcgi']['fastcgi_bin'], $content);
T 1605                 $content = str_replace('{fastcgi_phpini_path}', $conf['fastcgi']['fastcgi_phpini_path'], $content);
4ffb51 1606                 mkdir($conf['web']['website_basedir'].'/php-fcgi-scripts/apps', 0755, true);
526b99 1607                 //copy('tpl/apache_apps_fcgi_starter.master',$conf['web']['website_basedir'].'/php-fcgi-scripts/apps/.php-fcgi-starter');
T 1608                 wf($conf['web']['website_basedir'].'/php-fcgi-scripts/apps/.php-fcgi-starter', $content);
4ffb51 1609                 exec('chmod +x '.$conf['web']['website_basedir'].'/php-fcgi-scripts/apps/.php-fcgi-starter');
F 1610                 exec('chown -R ispapps:ispapps '.$conf['web']['website_basedir'].'/php-fcgi-scripts/apps');
1611
7fe908 1612             }
532ae5 1613         }
165152 1614         if($conf['nginx']['installed'] == true){
4ffb51 1615             $apps_vhost_user = escapeshellcmd($conf['web']['apps_vhost_user']);
F 1616             $apps_vhost_group = escapeshellcmd($conf['web']['apps_vhost_group']);
1617             $install_dir = escapeshellcmd($conf['web']['website_basedir'].'/apps');
532ae5 1618
4ffb51 1619             $command = 'groupadd '.$apps_vhost_user;
F 1620             if(!is_group($apps_vhost_group)) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1621
1622             $command = 'useradd -g '.$apps_vhost_group.' -d '.$install_dir.' '.$apps_vhost_group;
1623             if(!is_user($apps_vhost_user)) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1624
1625
11f2ad 1626             //$command = 'adduser '.$conf['nginx']['user'].' '.$apps_vhost_group;
TB 1627             $command = 'usermod -a -G '.$apps_vhost_group.' '.$conf['nginx']['user'];
4ffb51 1628             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
F 1629
6e2d48 1630             if(!@is_dir($install_dir)){
F 1631                 mkdir($install_dir, 0755, true);
1632             } else {
1633                 chmod($install_dir, 0755);
1634             }
4ffb51 1635             chown($install_dir, $apps_vhost_user);
F 1636             chgrp($install_dir, $apps_vhost_group);
1637
1638             //* Copy the apps vhost file
1639             $vhost_conf_dir = $conf['nginx']['vhost_conf_dir'];
1640             $vhost_conf_enabled_dir = $conf['nginx']['vhost_conf_enabled_dir'];
1641             $apps_vhost_servername = ($conf['web']['apps_vhost_servername'] == '')?'_':$conf['web']['apps_vhost_servername'];
1642
1643             // Dont just copy over the virtualhost template but add some custom settings
615a0a 1644             $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/nginx_apps.vhost.master', 'tpl/nginx_apps.vhost.master');
a8ccf6 1645
4ffb51 1646             if($conf['web']['apps_vhost_ip'] == '_default_'){
F 1647                 $apps_vhost_ip = '';
1648             } else {
1649                 $apps_vhost_ip = $conf['web']['apps_vhost_ip'].':';
1650             }
a8ccf6 1651
ca0b77 1652             $socket_dir = escapeshellcmd($conf['nginx']['php_fpm_socket_dir']);
7fe908 1653             if(substr($socket_dir, -1) != '/') $socket_dir .= '/';
ca0b77 1654             if(!is_dir($socket_dir)) exec('mkdir -p '.$socket_dir);
F 1655             $fpm_socket = $socket_dir.'apps.sock';
8ab3cd 1656             $cgi_socket = escapeshellcmd($conf['nginx']['cgi_socket']);
4ffb51 1657
F 1658             $content = str_replace('{apps_vhost_ip}', $apps_vhost_ip, $content);
1659             $content = str_replace('{apps_vhost_port}', $conf['web']['apps_vhost_port'], $content);
1660             $content = str_replace('{apps_vhost_dir}', $conf['web']['website_basedir'].'/apps', $content);
1661             $content = str_replace('{apps_vhost_servername}', $apps_vhost_servername, $content);
ca0b77 1662             //$content = str_replace('{fpm_port}', ($conf['nginx']['php_fpm_start_port']+1), $content);
F 1663             $content = str_replace('{fpm_socket}', $fpm_socket, $content);
8ab3cd 1664             $content = str_replace('{cgi_socket}', $cgi_socket, $content);
7fe908 1665
183c47 1666             if(file_exists('/var/run/php5-fpm.sock')){
F 1667                 $use_tcp = '#';
1668                 $use_socket = '';
1669             } else {
1670                 $use_tcp = '';
1671                 $use_socket = '#';
1672             }
1673             $content = str_replace('{use_tcp}', $use_tcp, $content);
1674             $content = str_replace('{use_socket}', $use_socket, $content);
4ffb51 1675
F 1676             wf($vhost_conf_dir.'/apps.vhost', $content);
a8ccf6 1677
fbb24a 1678             // PHP-FPM
F 1679             // Dont just copy over the php-fpm pool template but add some custom settings
615a0a 1680             $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/apps_php_fpm_pool.conf.master', 'tpl/apps_php_fpm_pool.conf.master');
fbb24a 1681             $content = str_replace('{fpm_pool}', 'apps', $content);
ca0b77 1682             //$content = str_replace('{fpm_port}', ($conf['nginx']['php_fpm_start_port']+1), $content);
F 1683             $content = str_replace('{fpm_socket}', $fpm_socket, $content);
fbb24a 1684             $content = str_replace('{fpm_user}', $apps_vhost_user, $content);
F 1685             $content = str_replace('{fpm_group}', $apps_vhost_group, $content);
1686             wf($conf['nginx']['php_fpm_pool_dir'].'/apps.conf', $content);
4ffb51 1687
F 1688             //copy('tpl/nginx_ispconfig.vhost.master', "$vhost_conf_dir/ispconfig.vhost");
1689             //* and create the symlink
7e1cfb 1690             if(@is_link($vhost_conf_enabled_dir.'/apps.vhost')) unlink($vhost_conf_enabled_dir.'/apps.vhost');
F 1691             if(!@is_link($vhost_conf_enabled_dir.'/000-apps.vhost')) {
7fe908 1692                 symlink($vhost_conf_dir.'/apps.vhost', $vhost_conf_enabled_dir.'/000-apps.vhost');
4ffb51 1693             }
a8ccf6 1694
532ae5 1695         }
L 1696     }
a8ccf6 1697
532ae5 1698     public function make_ispconfig_ssl_cert() {
b04e82 1699         global $conf,$autoinstall;
532ae5 1700
L 1701         $install_dir = $conf['ispconfig_install_dir'];
a8ccf6 1702
532ae5 1703         $ssl_crt_file = $install_dir.'/interface/ssl/ispserver.crt';
L 1704         $ssl_csr_file = $install_dir.'/interface/ssl/ispserver.csr';
1705         $ssl_key_file = $install_dir.'/interface/ssl/ispserver.key';
a8ccf6 1706
532ae5 1707         if(!@is_dir($install_dir.'/interface/ssl')) mkdir($install_dir.'/interface/ssl', 0755, true);
a8ccf6 1708
7fe908 1709         $ssl_pw = substr(md5(mt_rand()), 0, 6);
532ae5 1710         exec("openssl genrsa -des3 -passout pass:$ssl_pw -out $ssl_key_file 4096");
b04e82 1711         if(AUTOINSTALL){
TB 1712             exec("openssl req -new -passin pass:$ssl_pw -passout pass:$ssl_pw -subj '/C=".escapeshellcmd($autoinstall['ssl_cert_country'])."/ST=".escapeshellcmd($autoinstall['ssl_cert_state'])."/L=".escapeshellcmd($autoinstall['ssl_cert_locality'])."/O=".escapeshellcmd($autoinstall['ssl_cert_organisation'])."/OU=".escapeshellcmd($autoinstall['ssl_cert_organisation_unit'])."/CN=".escapeshellcmd($autoinstall['ssl_cert_common_name'])."' -key $ssl_key_file -out $ssl_csr_file");
bcd725 1713         } else {
FT 1714             exec("openssl req -new -passin pass:$ssl_pw -passout pass:$ssl_pw -key $ssl_key_file -out $ssl_csr_file");
1715         }
532ae5 1716         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");
L 1717         exec("openssl rsa -passin pass:$ssl_pw -in $ssl_key_file -out $ssl_key_file.insecure");
7fe908 1718         rename($ssl_key_file, $ssl_key_file.'.secure');
MC 1719         rename($ssl_key_file.'.insecure', $ssl_key_file);
980485 1720         
TB 1721         exec('chown -R root:root /usr/local/ispconfig/interface/ssl');
a8ccf6 1722
532ae5 1723     }
L 1724
1725     public function install_ispconfig() {
1726         global $conf;
1727
1728         $install_dir = $conf['ispconfig_install_dir'];
1729
1730         //* Create the ISPConfig installation directory
1731         if(!@is_dir($install_dir)) {
1732             $command = "mkdir $install_dir";
1733             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1734         }
1735
1736         //* Create a ISPConfig user and group
1737         $command = 'groupadd ispconfig';
1738         if(!is_group('ispconfig')) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1739
1740         $command = 'useradd -g ispconfig -d '.$install_dir.' ispconfig';
1741         if(!is_user('ispconfig')) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1742
1743         //* copy the ISPConfig interface part
1744         $command = 'cp -rf ../interface '.$install_dir;
1745         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1746
1747         //* copy the ISPConfig server part
1748         $command = 'cp -rf ../server '.$install_dir;
1749         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
a13af2 1750         
fb6c56 1751         //* Make a backup of the security settings
TB 1752         if(is_file('/usr/local/ispconfig/security/security_settings.ini')) copy('/usr/local/ispconfig/security/security_settings.ini','/usr/local/ispconfig/security/security_settings.ini~');
1753         
a13af2 1754         //* copy the ISPConfig security part
TB 1755         $command = 'cp -rf ../security '.$install_dir;
1756         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
fb6c56 1757         
TB 1758         //* Apply changed security_settings.ini values to new security_settings.ini file
1759         if(is_file('/usr/local/ispconfig/security/security_settings.ini~')) {
1760             $security_settings_old = ini_to_array(file_get_contents('/usr/local/ispconfig/security/security_settings.ini~'));
1761             $security_settings_new = ini_to_array(file_get_contents('/usr/local/ispconfig/security/security_settings.ini'));
1762             if(is_array($security_settings_new) && is_array($security_settings_old)) {
1763                 foreach($security_settings_new as $section => $sval) {
1764                     if(is_array($sval)) {
1765                         foreach($sval as $key => $val) {
1766                             if(isset($security_settings_old[$section]) && isset($security_settings_old[$section][$key])) {
1767                                 $security_settings_new[$section][$key] = $security_settings_old[$section][$key];
1768                             }
1769                         }
1770                     }
1771                 }
1772                 file_put_contents('/usr/local/ispconfig/security/security_settings.ini',array_to_ini($security_settings_new));
1773             }
1774         }
532ae5 1775
L 1776         //* Create a symlink, so ISPConfig is accessible via web
1777         // Replaced by a separate vhost definition for port 8080
1778         // $command = "ln -s $install_dir/interface/web/ /var/www/ispconfig";
1779         // caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1780
1781         //* Create the config file for ISPConfig interface
1782         $configfile = 'config.inc.php';
1783         if(is_file($install_dir.'/interface/lib/'.$configfile)) {
1784             copy($install_dir.'/interface/lib/'.$configfile, $install_dir.'/interface/lib/'.$configfile.'~');
1785         }
615a0a 1786         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
532ae5 1787         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
7fe908 1788         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
532ae5 1789         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
L 1790         $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content);
1791
1792         $content = str_replace('{mysql_master_server_ispconfig_user}', $conf['mysql']['master_ispconfig_user'], $content);
1793         $content = str_replace('{mysql_master_server_ispconfig_password}', $conf['mysql']['master_ispconfig_password'], $content);
1794         $content = str_replace('{mysql_master_server_database}', $conf['mysql']['master_database'], $content);
1795         $content = str_replace('{mysql_master_server_host}', $conf['mysql']['master_host'], $content);
1796
1797         $content = str_replace('{server_id}', $conf['server_id'], $content);
1798         $content = str_replace('{ispconfig_log_priority}', $conf['ispconfig_log_priority'], $content);
b63764 1799         $content = str_replace('{language}', $conf['language'], $content);
8cf78b 1800         $content = str_replace('{timezone}', $conf['timezone'], $content);
f598b0 1801         $content = str_replace('{theme}', $conf['theme'], $content);
992797 1802         $content = str_replace('{language_file_import_enabled}', ($conf['language_file_import_enabled'] == true)?'true':'false', $content);
b63764 1803
532ae5 1804         wf($install_dir.'/interface/lib/'.$configfile, $content);
L 1805
1806         //* Create the config file for ISPConfig server
1807         $configfile = 'config.inc.php';
1808         if(is_file($install_dir.'/server/lib/'.$configfile)) {
1809             copy($install_dir.'/server/lib/'.$configfile, $install_dir.'/interface/lib/'.$configfile.'~');
1810         }
615a0a 1811         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
532ae5 1812         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
L 1813         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1814         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
1815         $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content);
1816
1817         $content = str_replace('{mysql_master_server_ispconfig_user}', $conf['mysql']['master_ispconfig_user'], $content);
1818         $content = str_replace('{mysql_master_server_ispconfig_password}', $conf['mysql']['master_ispconfig_password'], $content);
1819         $content = str_replace('{mysql_master_server_database}', $conf['mysql']['master_database'], $content);
1820         $content = str_replace('{mysql_master_server_host}', $conf['mysql']['master_host'], $content);
1821
1822         $content = str_replace('{server_id}', $conf['server_id'], $content);
1823         $content = str_replace('{ispconfig_log_priority}', $conf['ispconfig_log_priority'], $content);
1824         $content = str_replace('{language}', $conf['language'], $content);
8cf78b 1825         $content = str_replace('{timezone}', $conf['timezone'], $content);
f598b0 1826         $content = str_replace('{theme}', $conf['theme'], $content);
992797 1827         $content = str_replace('{language_file_import_enabled}', ($conf['language_file_import_enabled'] == true)?'true':'false', $content);
532ae5 1828
L 1829         wf($install_dir.'/server/lib/'.$configfile, $content);
1830
1831         //* Create the config file for remote-actions (but only, if it does not exist, because
1832         //  the value is a autoinc-value and so changed by the remoteaction_core_module
1833         if (!file_exists($install_dir.'/server/lib/remote_action.inc.php')) {
1834             $content = '<?php' . "\n" . '$maxid_remote_action = 0;' . "\n" . '?>';
1835             wf($install_dir.'/server/lib/remote_action.inc.php', $content);
1836         }
1837
1838         //* Enable the server modules and plugins.
1839         // TODO: Implement a selector which modules and plugins shall be enabled.
1840         $dir = $install_dir.'/server/mods-available/';
1841         if (is_dir($dir)) {
1842             if ($dh = opendir($dir)) {
1843                 while (($file = readdir($dh)) !== false) {
7fe908 1844                     if($file != '.' && $file != '..' && substr($file, -8, 8) == '.inc.php') {
MC 1845                         include_once $install_dir.'/server/mods-available/'.$file;
1846                         $module_name = substr($file, 0, -8);
532ae5 1847                         $tmp = new $module_name;
L 1848                         if($tmp->onInstall()) {
1849                             if(!@is_link($install_dir.'/server/mods-enabled/'.$file)) {
1850                                 @symlink($install_dir.'/server/mods-available/'.$file, $install_dir.'/server/mods-enabled/'.$file);
1851                                 // @symlink($install_dir.'/server/mods-available/'.$file, '../mods-enabled/'.$file);
1852                             }
1853                             if (strpos($file, '_core_module') !== false) {
1854                                 if(!@is_link($install_dir.'/server/mods-core/'.$file)) {
1855                                     @symlink($install_dir.'/server/mods-available/'.$file, $install_dir.'/server/mods-core/'.$file);
1856                                     // @symlink($install_dir.'/server/mods-available/'.$file, '../mods-core/'.$file);
1857                                 }
1858                             }
1859                         }
1860                         unset($tmp);
1861                     }
1862                 }
1863                 closedir($dh);
1864             }
1865         }
1866
1867         $dir = $install_dir.'/server/plugins-available/';
1868         if (is_dir($dir)) {
1869             if ($dh = opendir($dir)) {
1870                 while (($file = readdir($dh)) !== false) {
4ffb51 1871                     if($conf['apache']['installed'] == true && $file == 'nginx_plugin.inc.php') continue;
F 1872                     if($conf['nginx']['installed'] == true && $file == 'apache2_plugin.inc.php') continue;
7fe908 1873                     if($file != '.' && $file != '..' && substr($file, -8, 8) == '.inc.php') {
MC 1874                         include_once $install_dir.'/server/plugins-available/'.$file;
1875                         $plugin_name = substr($file, 0, -8);
532ae5 1876                         $tmp = new $plugin_name;
7fe908 1877                         if(method_exists($tmp, 'onInstall') && $tmp->onInstall()) {
532ae5 1878                             if(!@is_link($install_dir.'/server/plugins-enabled/'.$file)) {
L 1879                                 @symlink($install_dir.'/server/plugins-available/'.$file, $install_dir.'/server/plugins-enabled/'.$file);
1880                                 //@symlink($install_dir.'/server/plugins-available/'.$file, '../plugins-enabled/'.$file);
1881                             }
1882                             if (strpos($file, '_core_plugin') !== false) {
1883                                 if(!@is_link($install_dir.'/server/plugins-core/'.$file)) {
1884                                     @symlink($install_dir.'/server/plugins-available/'.$file, $install_dir.'/server/plugins-core/'.$file);
1885                                     //@symlink($install_dir.'/server/plugins-available/'.$file, '../plugins-core/'.$file);
1886                                 }
1887                             }
1888                         }
1889                         unset($tmp);
1890                     }
1891                 }
1892                 closedir($dh);
1893             }
1894         }
1895
1896         // Update the server config
1897         $mail_server_enabled = ($conf['services']['mail'])?1:0;
1898         $web_server_enabled = ($conf['services']['web'])?1:0;
1899         $dns_server_enabled = ($conf['services']['dns'])?1:0;
1900         $file_server_enabled = ($conf['services']['file'])?1:0;
1901         $db_server_enabled = ($conf['services']['db'])?1:0;
8cf955 1902         $vserver_server_enabled = ($conf['openvz']['installed'])?1:0;
80e3c9 1903         $proxy_server_enabled = ($conf['services']['proxy'])?1:0;
T 1904         $firewall_server_enabled = ($conf['services']['firewall'])?1:0;
532ae5 1905
80e3c9 1906         $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 1907
L 1908         if($conf['mysql']['master_slave_setup'] == 'y') {
1909             $this->dbmaster->query($sql);
1910             $this->db->query($sql);
1911         } else {
1912             $this->db->query($sql);
1913         }
1914
1915
3e0fc8 1916         // chown install dir to root and chmod 755
TB 1917         $command = 'chown root:root '.$install_dir;
1918         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1919         $command = 'chmod 755 '.$install_dir;
532ae5 1920         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
L 1921
fa029b 1922         //* Chmod the files and directories in the install dir
3e0fc8 1923         $command = 'chmod -R 750 '.$install_dir.'/*';
TB 1924         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1925
1926         //* chown the interface files to the ispconfig user and group
1927         $command = 'chown -R ispconfig:ispconfig '.$install_dir.'/interface';
1928         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1929         
1930         //* chown the server files to the root user and group
1931         $command = 'chown -R root:root '.$install_dir.'/server';
532ae5 1932         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
fa029b 1933         
TB 1934         //* chown the security files to the root user and group
1935         $command = 'chown -R root:root '.$install_dir.'/security';
1936         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1937         
1938         //* chown the security directory and security_settings.ini to root:ispconfig
1939         $command = 'chown root:ispconfig '.$install_dir.'/security/security_settings.ini';
1940         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1941         $command = 'chown root:ispconfig '.$install_dir.'/security';
1942         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
cb1221 1943         $command = 'chown root:ispconfig '.$install_dir.'/security/ids.whitelist';
TB 1944         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1945         $command = 'chown root:ispconfig '.$install_dir.'/security/ids.htmlfield';
1946         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1947         $command = 'chown root:ispconfig '.$install_dir.'/security/apache_directives.blacklist';
1948         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
532ae5 1949
L 1950         //* Make the global language file directory group writable
1951         exec("chmod -R 770 $install_dir/interface/lib/lang");
1952
1953         //* Make the temp directory for language file exports writable
1954         if(is_dir($install_dir.'/interface/web/temp')) exec("chmod -R 770 $install_dir/interface/web/temp");
1955
1956         //* Make all interface language file directories group writable
1957         $handle = @opendir($install_dir.'/interface/web');
7fe908 1958         while ($file = @readdir($handle)) {
532ae5 1959             if ($file != '.' && $file != '..') {
L 1960                 if(@is_dir($install_dir.'/interface/web'.'/'.$file.'/lib/lang')) {
1961                     $handle2 = opendir($install_dir.'/interface/web'.'/'.$file.'/lib/lang');
7fe908 1962                     chmod($install_dir.'/interface/web'.'/'.$file.'/lib/lang', 0770);
MC 1963                     while ($lang_file = @readdir($handle2)) {
532ae5 1964                         if ($lang_file != '.' && $lang_file != '..') {
7fe908 1965                             chmod($install_dir.'/interface/web'.'/'.$file.'/lib/lang/'.$lang_file, 0770);
532ae5 1966                         }
L 1967                     }
1968                 }
1969             }
1970         }
a8ccf6 1971
477d4e 1972         //* Make the APS directories group writable
T 1973         exec("chmod -R 770 $install_dir/interface/web/sites/aps_meta_packages");
1974         exec("chmod -R 770 $install_dir/server/aps_packages");
532ae5 1975
L 1976         //* make sure that the server config file (not the interface one) is only readable by the root user
bfcdef 1977         chmod($install_dir.'/server/lib/config.inc.php', 0600);
T 1978         chown($install_dir.'/server/lib/config.inc.php', 'root');
1979         chgrp($install_dir.'/server/lib/config.inc.php', 'root');
7fe908 1980
bfcdef 1981         //* Make sure thet the interface config file is readable by user ispconfig only
T 1982         chmod($install_dir.'/interface/lib/config.inc.php', 0600);
1983         chown($install_dir.'/interface/lib/config.inc.php', 'ispconfig');
1984         chgrp($install_dir.'/interface/lib/config.inc.php', 'ispconfig');
532ae5 1985
L 1986         chmod($install_dir.'/server/lib/remote_action.inc.php', 0600);
1987         chown($install_dir.'/server/lib/remote_action.inc.php', 'root');
1988         chgrp($install_dir.'/server/lib/remote_action.inc.php', 'root');
1989
1990         if(@is_file($install_dir.'/server/lib/mysql_clientdb.conf')) {
1991             chmod($install_dir.'/server/lib/mysql_clientdb.conf', 0600);
1992             chown($install_dir.'/server/lib/mysql_clientdb.conf', 'root');
1993             chgrp($install_dir.'/server/lib/mysql_clientdb.conf', 'root');
1994         }
a8ccf6 1995
8cf78b 1996         if(is_dir($install_dir.'/interface/invoices')) {
e94a9f 1997             exec('chmod -R 770 '.escapeshellarg($install_dir.'/interface/invoices'));
T 1998             exec('chown -R ispconfig:ispconfig '.escapeshellarg($install_dir.'/interface/invoices'));
edf806 1999         }
980485 2000         
TB 2001         exec('chown -R root:root /usr/local/ispconfig/interface/ssl');
532ae5 2002
L 2003         // TODO: FIXME: add the www-data user to the ispconfig group. This is just for testing
2004         // and must be fixed as this will allow the apache user to read the ispconfig files.
2005         // Later this must run as own apache server or via suexec!
63b369 2006         if($conf['apache']['installed'] == true){
F 2007             $command = 'adduser '.$conf['apache']['user'].' ispconfig';
2008             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
272aec 2009             if(is_group('ispapps')){
F 2010                 $command = 'adduser '.$conf['apache']['user'].' ispapps';
2011                 caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
2012             }
63b369 2013         }
F 2014         if($conf['nginx']['installed'] == true){
2015             $command = 'adduser '.$conf['nginx']['user'].' ispconfig';
2016             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
272aec 2017             if(is_group('ispapps')){
F 2018                 $command = 'adduser '.$conf['nginx']['user'].' ispapps';
2019                 caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
2020             }
63b369 2021         }
532ae5 2022
L 2023         //* Make the shell scripts executable
2024         $command = "chmod +x $install_dir/server/scripts/*.sh";
2025         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
2026
7e1cfb 2027         if($conf['apache']['installed'] == true && $this->install_ispconfig_interface == true){
4ffb51 2028             //* Copy the ISPConfig vhost for the controlpanel
F 2029             $vhost_conf_dir = $conf['apache']['vhost_conf_dir'];
2030             $vhost_conf_enabled_dir = $conf['apache']['vhost_conf_enabled_dir'];
532ae5 2031
4ffb51 2032             // Dont just copy over the virtualhost template but add some custom settings
ccbf14 2033             $tpl = new tpl('apache_ispconfig.vhost.master');
TB 2034             $tpl->setVar('vhost_port',$conf['apache']['vhost_port']);
532ae5 2035
4ffb51 2036             // comment out the listen directive if port is 80 or 443
F 2037             if($conf['apache']['vhost_port'] == 80 or $conf['apache']['vhost_port'] == 443) {
ccbf14 2038                 $tpl->setVar('vhost_port_listen','#');
4ffb51 2039             } else {
ccbf14 2040                 $tpl->setVar('vhost_port_listen','');
4ffb51 2041             }
a8ccf6 2042
4ffb51 2043             if(is_file($install_dir.'/interface/ssl/ispserver.crt') && is_file($install_dir.'/interface/ssl/ispserver.key')) {
ccbf14 2044                 $tpl->setVar('ssl_comment','');
4ffb51 2045             } else {
ccbf14 2046                 $tpl->setVar('ssl_comment','#');
4ffb51 2047             }
10b4c8 2048             if(is_file($install_dir.'/interface/ssl/ispserver.crt') && is_file($install_dir.'/interface/ssl/ispserver.key') && is_file($install_dir.'/interface/ssl/ispserver.bundle')) {
ccbf14 2049                 $tpl->setVar('ssl_bundle_comment','');
10b4c8 2050             } else {
ccbf14 2051                 $tpl->setVar('ssl_bundle_comment','#');
10b4c8 2052             }
ccbf14 2053             
TB 2054             $tpl->setVar('apache_version',getapacheversion());
532ae5 2055
ccbf14 2056             wf($vhost_conf_dir.'/ispconfig.vhost', $tpl->grab());
532ae5 2057
4ffb51 2058             //* and create the symlink
7e1cfb 2059             if($this->is_update == false) {
4ffb51 2060                 if(@is_link($vhost_conf_enabled_dir.'/ispconfig.vhost')) unlink($vhost_conf_enabled_dir.'/ispconfig.vhost');
F 2061                 if(!@is_link($vhost_conf_enabled_dir.'/000-ispconfig.vhost')) {
7fe908 2062                     symlink($vhost_conf_dir.'/ispconfig.vhost', $vhost_conf_enabled_dir.'/000-ispconfig.vhost');
4ffb51 2063                 }
F 2064             }
cc6568 2065             //if(!is_file('/var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter')) {
7fe908 2066             $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/apache_ispconfig_fcgi_starter.master', 'tpl/apache_ispconfig_fcgi_starter.master');
MC 2067             $content = str_replace('{fastcgi_bin}', $conf['fastcgi']['fastcgi_bin'], $content);
2068             $content = str_replace('{fastcgi_phpini_path}', $conf['fastcgi']['fastcgi_phpini_path'], $content);
2069             @mkdir('/var/www/php-fcgi-scripts/ispconfig', 0755, true);
2070             wf('/var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter', $content);
2071             exec('chmod +x /var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter');
2072             @symlink($install_dir.'/interface/web', '/var/www/ispconfig');
2073             exec('chown -R ispconfig:ispconfig /var/www/php-fcgi-scripts/ispconfig');
cc6568 2074             //}
532ae5 2075         }
a8ccf6 2076
7e1cfb 2077         if($conf['nginx']['installed'] == true && $this->install_ispconfig_interface == true){
4ffb51 2078             //* Copy the ISPConfig vhost for the controlpanel
F 2079             $vhost_conf_dir = $conf['nginx']['vhost_conf_dir'];
2080             $vhost_conf_enabled_dir = $conf['nginx']['vhost_conf_enabled_dir'];
532ae5 2081
4ffb51 2082             // Dont just copy over the virtualhost template but add some custom settings
615a0a 2083             $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/nginx_ispconfig.vhost.master', 'tpl/nginx_ispconfig.vhost.master');
4ffb51 2084             $content = str_replace('{vhost_port}', $conf['nginx']['vhost_port'], $content);
a8ccf6 2085
4ffb51 2086             if(is_file($install_dir.'/interface/ssl/ispserver.crt') && is_file($install_dir.'/interface/ssl/ispserver.key')) {
f9b8d0 2087                 $content = str_replace('{ssl_on}', 'on', $content);
4ffb51 2088                 $content = str_replace('{ssl_comment}', '', $content);
F 2089                 $content = str_replace('{fastcgi_ssl}', 'on', $content);
2090             } else {
f9b8d0 2091                 $content = str_replace('{ssl_on}', 'off', $content);
4ffb51 2092                 $content = str_replace('{ssl_comment}', '#', $content);
F 2093                 $content = str_replace('{fastcgi_ssl}', 'off', $content);
2094             }
a8ccf6 2095
ca0b77 2096             $socket_dir = escapeshellcmd($conf['nginx']['php_fpm_socket_dir']);
7fe908 2097             if(substr($socket_dir, -1) != '/') $socket_dir .= '/';
ca0b77 2098             if(!is_dir($socket_dir)) exec('mkdir -p '.$socket_dir);
F 2099             $fpm_socket = $socket_dir.'ispconfig.sock';
a8ccf6 2100
ca0b77 2101             //$content = str_replace('{fpm_port}', $conf['nginx']['php_fpm_start_port'], $content);
F 2102             $content = str_replace('{fpm_socket}', $fpm_socket, $content);
a8ccf6 2103
4ffb51 2104             wf($vhost_conf_dir.'/ispconfig.vhost', $content);
a8ccf6 2105
4ffb51 2106             unset($content);
a8ccf6 2107
4ffb51 2108             // PHP-FPM
F 2109             // Dont just copy over the php-fpm pool template but add some custom settings
615a0a 2110             $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/php_fpm_pool.conf.master', 'tpl/php_fpm_pool.conf.master');
4ffb51 2111             $content = str_replace('{fpm_pool}', 'ispconfig', $content);
ca0b77 2112             //$content = str_replace('{fpm_port}', $conf['nginx']['php_fpm_start_port'], $content);
F 2113             $content = str_replace('{fpm_socket}', $fpm_socket, $content);
4ffb51 2114             $content = str_replace('{fpm_user}', 'ispconfig', $content);
F 2115             $content = str_replace('{fpm_group}', 'ispconfig', $content);
2116             wf($conf['nginx']['php_fpm_pool_dir'].'/ispconfig.conf', $content);
2117
2118             //copy('tpl/nginx_ispconfig.vhost.master', $vhost_conf_dir.'/ispconfig.vhost');
2119             //* and create the symlink
7e1cfb 2120             if($this->is_update == false) {
4ffb51 2121                 if(@is_link($vhost_conf_enabled_dir.'/ispconfig.vhost')) unlink($vhost_conf_enabled_dir.'/ispconfig.vhost');
F 2122                 if(!@is_link($vhost_conf_enabled_dir.'/000-ispconfig.vhost')) {
7fe908 2123                     symlink($vhost_conf_dir.'/ispconfig.vhost', $vhost_conf_enabled_dir.'/000-ispconfig.vhost');
4ffb51 2124                 }
F 2125             }
532ae5 2126         }
L 2127
2128         //* Install the update script
b34f99 2129         if(is_file('/usr/local/bin/ispconfig_update_from_dev.sh')) unlink('/usr/local/bin/ispconfig_update_from_dev.sh');
MC 2130         chown($install_dir.'/server/scripts/update_from_dev.sh', 'root');
2131         chmod($install_dir.'/server/scripts/update_from_dev.sh', 0700);
532ae5 2132         chown($install_dir.'/server/scripts/update_from_tgz.sh', 'root');
L 2133         chmod($install_dir.'/server/scripts/update_from_tgz.sh', 0700);
2134         chown($install_dir.'/server/scripts/ispconfig_update.sh', 'root');
2135         chmod($install_dir.'/server/scripts/ispconfig_update.sh', 0700);
b34f99 2136         if(!is_link('/usr/local/bin/ispconfig_update_from_dev.sh')) symlink($install_dir.'/server/scripts/ispconfig_update.sh', '/usr/local/bin/ispconfig_update_from_dev.sh');
7fe908 2137         if(!is_link('/usr/local/bin/ispconfig_update.sh')) symlink($install_dir.'/server/scripts/ispconfig_update.sh', '/usr/local/bin/ispconfig_update.sh');
532ae5 2138
L 2139         //* Make the logs readable for the ispconfig user
2140         if(@is_file('/var/log/mail.log')) exec('chmod +r /var/log/mail.log');
2141         if(@is_file('/var/log/mail.warn')) exec('chmod +r /var/log/mail.warn');
2142         if(@is_file('/var/log/mail.err')) exec('chmod +r /var/log/mail.err');
2143         if(@is_file('/var/log/messages')) exec('chmod +r /var/log/messages');
2144         if(@is_file('/var/log/clamav/clamav.log')) exec('chmod +r /var/log/clamav/clamav.log');
2145         if(@is_file('/var/log/clamav/freshclam.log')) exec('chmod +r /var/log/clamav/freshclam.log');
2146
2147         //* Create the ispconfig log file and directory
2148         if(!is_file($conf['ispconfig_log_dir'].'/ispconfig.log')) {
2149             if(!is_dir($conf['ispconfig_log_dir'])) mkdir($conf['ispconfig_log_dir'], 0755);
2150             touch($conf['ispconfig_log_dir'].'/ispconfig.log');
2151         }
a8ccf6 2152
99c89b 2153         //* Create the ispconfig auth log file and set uid/gid
a8ccf6 2154         if(!is_file($conf['ispconfig_log_dir'].'/auth.log')) {
99c89b 2155             touch($conf['ispconfig_log_dir'].'/auth.log');
a8ccf6 2156         }
0799f8 2157         exec('chown ispconfig:ispconfig '. $conf['ispconfig_log_dir'].'/auth.log');
T 2158         exec('chmod 660 '. $conf['ispconfig_log_dir'].'/auth.log');
a8ccf6 2159
0c5b42 2160         if(is_user('getmail')) {
7fe908 2161             rename($install_dir.'/server/scripts/run-getmail.sh', '/usr/local/bin/run-getmail.sh');
0c5b42 2162             if(is_user('getmail')) chown('/usr/local/bin/run-getmail.sh', 'getmail');
T 2163             chmod('/usr/local/bin/run-getmail.sh', 0744);
2164         }
532ae5 2165
L 2166         //* Add Log-Rotation
2167         if (is_dir('/etc/logrotate.d')) {
2168             @unlink('/etc/logrotate.d/logispc3'); // ignore, if the file is not there
2169             /* We rotate these logs in cron_daily.php
2170             $fh = fopen('/etc/logrotate.d/logispc3', 'w');
2171             fwrite($fh,
2172                     "$conf['ispconfig_log_dir']/ispconfig.log { \n" .
2173                     "    weekly \n" .
2174                     "    missingok \n" .
2175                     "    rotate 4 \n" .
2176                     "    compress \n" .
2177                     "    delaycompress \n" .
2178                     "} \n" .
2179                     "$conf['ispconfig_log_dir']/cron.log { \n" .
2180                     "    weekly \n" .
2181                     "    missingok \n" .
2182                     "    rotate 4 \n" .
2183                     "    compress \n" .
2184                     "    delaycompress \n" .
2185                     "}");
2186             fclose($fh);
2187             */
2188         }
7fe908 2189
d71bae 2190         //* Remove Domain module as its functions are available in the client module now
T 2191         if(@is_dir('/usr/local/ispconfig/interface/web/domain')) exec('rm -rf /usr/local/ispconfig/interface/web/domain');
f30628 2192         
TB 2193         //* Disable rkhunter run and update in debian cronjob as ispconfig is running and updating rkhunter
2194         if(is_file('/etc/default/rkhunter')) {
2195             replaceLine('/etc/default/rkhunter', 'CRON_DAILY_RUN="yes"', 'CRON_DAILY_RUN="no"', 1, 0);
2196             replaceLine('/etc/default/rkhunter', 'CRON_DB_UPDATE="yes"', 'CRON_DB_UPDATE="no"', 1, 0);
2197         }
2198         
021aec 2199         // Add symlink for patch tool
TB 2200         if(!is_link('/usr/local/bin/ispconfig_patch')) exec('ln -s /usr/local/ispconfig/server/scripts/ispconfig_patch /usr/local/bin/ispconfig_patch');
5b3f25 2201         
532ae5 2202     }
L 2203
2204     public function configure_dbserver() {
2205         global $conf;
2206
2207         //* If this server shall act as database server for client DB's, we configure this here
2208         $install_dir = $conf['ispconfig_install_dir'];
2209
2210         // Create a file with the database login details which
2211         // are used to create the client databases.
2212
2213         if(!is_dir($install_dir.'/server/lib')) {
2214             $command = "mkdir $install_dir/server/lib";
2215             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
2216         }
2217
615a0a 2218         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/mysql_clientdb.conf.master', 'tpl/mysql_clientdb.conf.master');
7fe908 2219         $content = str_replace('{hostname}', $conf['mysql']['host'], $content);
MC 2220         $content = str_replace('{username}', $conf['mysql']['admin_user'], $content);
67fede 2221         $content = str_replace('{password}', addslashes($conf['mysql']['admin_password']), $content);
7fe908 2222         wf($install_dir.'/server/lib/mysql_clientdb.conf', $content);
532ae5 2223         chmod($install_dir.'/server/lib/mysql_clientdb.conf', 0600);
L 2224         chown($install_dir.'/server/lib/mysql_clientdb.conf', 'root');
a8ccf6 2225         chgrp($install_dir.'/server/lib/mysql_clientdb.conf', 'root');
532ae5 2226
L 2227     }
2228
2229     public function install_crontab() {
2230         global $conf;
2231
2232         $install_dir = $conf['ispconfig_install_dir'];
2233
2234         //* Root Crontab
2235         exec('crontab -u root -l > crontab.txt');
2236         $existing_root_cron_jobs = file('crontab.txt');
2237
2238         // remove existing ispconfig cronjobs, in case the syntax has changed
2239         foreach($existing_root_cron_jobs as $key => $val) {
7fe908 2240             if(stristr($val, $install_dir)) unset($existing_root_cron_jobs[$key]);
532ae5 2241         }
L 2242
2243         $root_cron_jobs = array(
7fe908 2244             "* * * * * ".$install_dir."/server/server.sh 2>&1 > /dev/null | while read line; do echo `/bin/date` \"\$line\" >> ".$conf['ispconfig_log_dir']."/cron.log; done",
MC 2245             "30 00 * * * ".$install_dir."/server/cron_daily.sh 2>&1 > /dev/null | while read line; do echo `/bin/date` \"\$line\" >> ".$conf['ispconfig_log_dir']."/cron.log; done"
532ae5 2246         );
a8ccf6 2247
b6a10a 2248         if ($conf['nginx']['installed'] == true) {
F 2249             $root_cron_jobs[] = "0 0 * * * ".$install_dir."/server/scripts/create_daily_nginx_access_logs.sh &> /dev/null";
2250         }
a8ccf6 2251
532ae5 2252         foreach($root_cron_jobs as $cron_job) {
L 2253             if(!in_array($cron_job."\n", $existing_root_cron_jobs)) {
2254                 $existing_root_cron_jobs[] = $cron_job."\n";
2255             }
2256         }
2257         file_put_contents('crontab.txt', $existing_root_cron_jobs);
2258         exec('crontab -u root crontab.txt &> /dev/null');
2259         unlink('crontab.txt');
2260
2261         //* Getmail crontab
2262         if(is_user('getmail')) {
2263             $cf = $conf['getmail'];
2264             exec('crontab -u getmail -l > crontab.txt');
2265             $existing_cron_jobs = file('crontab.txt');
2266
2267             $cron_jobs = array(
7fe908 2268                 '*/5 * * * * /usr/local/bin/run-getmail.sh > /dev/null 2>> /dev/null'
532ae5 2269             );
L 2270
2271             // remove existing ispconfig cronjobs, in case the syntax has changed
2272             foreach($existing_cron_jobs as $key => $val) {
7fe908 2273                 if(stristr($val, 'getmail')) unset($existing_cron_jobs[$key]);
532ae5 2274             }
L 2275
2276             foreach($cron_jobs as $cron_job) {
2277                 if(!in_array($cron_job."\n", $existing_cron_jobs)) {
2278                     $existing_cron_jobs[] = $cron_job."\n";
2279                 }
2280             }
2281             file_put_contents('crontab.txt', $existing_cron_jobs);
2282             exec('crontab -u getmail crontab.txt &> /dev/null');
2283             unlink('crontab.txt');
2284         }
2285
2286         touch($conf['ispconfig_log_dir'].'/cron.log');
cc6568 2287         chmod($conf['ispconfig_log_dir'].'/cron.log', 0660);
532ae5 2288
L 2289     }
5b3f25 2290     
TB 2291     // This function is called at the end of the update process and contains code to clean up parts of old ISPCONfig releases
2292     public function cleanup_ispconfig() {
2293         global $app,$conf;
2294         
2295         // Remove directories recursively
2296         if(is_dir('/usr/local/ispconfig/interface/web/designer')) exec('rm -rf /usr/local/ispconfig/interface/web/designer');
4c3fcd 2297         if(is_dir('/usr/local/ispconfig/interface/web/themes/default-304')) exec('rm -rf /usr/local/ispconfig/interface/web/themes/default-304');
5b3f25 2298         
TB 2299         // Remove files
2300         if(is_file('/usr/local/ispconfig/interface/lib/classes/db_firebird.inc.php')) unlink('/usr/local/ispconfig/interface/lib/classes/db_firebird.inc.php');
2301         if(is_file('/usr/local/ispconfig/interface/lib/classes/form.inc.php')) unlink('/usr/local/ispconfig/interface/lib/classes/form.inc.php');
2302         
2303         
2304         
2305     }
7fe908 2306
33bcd0 2307     public function getinitcommand($servicename, $action, $init_script_directory = ''){
FT 2308         global $conf;
2309         // systemd
6061d5 2310         if(is_executable('/bin/systemd') || is_executable('/usr/bin/systemctl')){
33bcd0 2311             return 'systemctl '.$action.' '.$servicename.'.service';
FT 2312         }
2313         // upstart
2314         if(is_executable('/sbin/initctl')){
2315             exec('/sbin/initctl version 2>/dev/null | /bin/grep -q upstart', $retval['output'], $retval['retval']);
2316             if(intval($retval['retval']) == 0) return 'service '.$servicename.' '.$action;
2317         }
2318         // sysvinit
2319         if($init_script_directory == '') $init_script_directory = $conf['init_scripts'];
2320         if(substr($init_script_directory, -1) === '/') $init_script_directory = substr($init_script_directory, 0, -1);
2321         return $init_script_directory.'/'.$servicename.' '.$action;
2322     }
532ae5 2323
L 2324     /**
2325      * Helper function - get the path to a template file based on
2326      * the local part of the filename. Checks first for the existence
2327      * of a distribution specific file and if not found looks in the
2328      * base template folder. Optionally the behaviour can be changed
2329      * by setting the 2nd parameter which will fetch the contents
2330      * of the template file and return it instead of the path. The 3rd
2331      * parameter further extends this behaviour by filtering the contents
2332      * by inserting the ispconfig database credentials using the {} placeholders.
2333      *
2334      * @param string $tLocal local part of filename
2335      * @param bool $tRf
2336      * @param bool $tDBCred
2337      * @return string Relative path to the chosen template file
2338      */
2339     protected function get_template_file($tLocal, $tRf=false, $tDBCred=false) {
2340         global $conf, $dist;
2341
2342         $final_path = '';
7fe908 2343         $dist_template = $conf['ispconfig_install_dir'] . '/server/conf-custom/install/' . $tLocal . '.master';
MC 2344         if (file_exists($dist_template)) {
532ae5 2345             $final_path = $dist_template;
L 2346         } else {
7fe908 2347             $dist_template = 'dist/tpl/'.strtolower($dist['name'])."/$tLocal.master";
MC 2348             if (file_exists($dist_template)) {
2349                 $final_path = $dist_template;
2350             } else {
2351                 $final_path = "tpl/$tLocal.master";
2352             }
2353         }
532ae5 2354
L 2355         if (!$tRf) {
2356             return $final_path;
2357         } else {
2358             return (!$tDBCred) ? rf($final_path) : $this->insert_db_credentials(rf($final_path));
2359         }
2360     }
2361
2362     /**
2363      * Helper function - writes the contents to a config file
2364      * and performs a backup if the file exist. Additionally
2365      * if the file exists the new file will be given the
2366      * same rights and ownership as the original. Optionally the
2367      * rights and/or ownership can be overriden by appending umask,
2368      * user and group to the parameters. Providing only uid and gid
2369      * values will result in only a chown.
2370      *
2371      * @param $tConf
2372      * @param $tContents
2373      * @return bool
2374      */
2375     protected function write_config_file($tConf, $tContents) {
2376         // Backup config file before writing new contents and stat file
2377         if ( is_file($tConf) ) {
2378             $stat = exec('stat -c \'%a %U %G\' '.escapeshellarg($tConf), $output, $res);
2379             if ($res == 0) { // stat successfull
8cddcd 2380                 list($access, $user, $group) = explode(" ", $stat);
532ae5 2381             }
L 2382
2383             if ( copy($tConf, $tConf.'~') ) {
2384                 chmod($tConf.'~', 0400);
2385             }
2386         }
2387
2388         wf($tConf, $tContents); // write file
2389
2390         if (func_num_args() >= 4) // override rights and/or ownership
7fe908 2391             {
532ae5 2392             $args = func_get_args();
L 2393             $output = array_slice($args, 2);
2394
2395             switch (sizeof($output)) {
7fe908 2396             case 3:
MC 2397                 $umask = array_shift($output);
2398                 if (is_numeric($umask) && preg_match('/^0?[0-7]{3}$/', $umask)) {
2399                     $access = $umask;
2400                 }
2401             case 2:
2402                 if (is_user($output[0]) && is_group($output[1])) {
2403                     list($user, $group) = $output;
2404                 }
2405                 break;
532ae5 2406             }
L 2407         }
2408
2409         if (!empty($user) && !empty($group)) {
2410             chown($tConf, $user);
2411             chgrp($tConf, $group);
2412         }
2413
2414         if (!empty($access)) {
2415             exec("chmod $access $tConf");
2416         }
2417     }
2418
2419     /**
2420      * Helper function - filter the contents of a config
2421      * file by inserting the common ispconfig database
2422      * credentials.
2423      *
2424      * @param $tContents
2425      * @return string
2426      */
2427     protected function insert_db_credentials($tContents) {
2428         global $conf;
2429
2430         $tContents = str_replace('{mysql_server_ispconfig_user}', $conf["mysql"]["ispconfig_user"], $tContents);
2431         $tContents = str_replace('{mysql_server_ispconfig_password}', $conf["mysql"]["ispconfig_password"], $tContents);
2432         $tContents = str_replace('{mysql_server_database}', $conf["mysql"]["database"], $tContents);
2433         $tContents = str_replace('{mysql_server_ip}', $conf["mysql"]["ip"], $tContents);
7fe908 2434         $tContents = str_replace('{mysql_server_host}', $conf['mysql']['host'], $tContents);
MC 2435         $tContents = str_replace('{mysql_server_port}', $conf["mysql"]["port"], $tContents);
532ae5 2436
L 2437         return $tContents;
2438     }
7fe908 2439
532ae5 2440 }
L 2441
e514ae 2442 ?>