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