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