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