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