Marius Cramer
2015-08-06 37b29231e47a0c4458dc1c15d98588f16f07e1e2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
<?php
 
class nginx_reverseproxy_plugin {
 
    var $plugin_name = 'nginx_reverseproxy_plugin';
    var $class_name = 'nginx_reverseproxy_plugin';
 
    // private variables
    var $action = '';
 
    //* This function is called during ispconfig installation to determine
    //  if a symlink shall be created for this plugin.
    function onInstall() {
        global $conf;
 
        if(isset($conf['services']['proxy']) && $conf['services']['proxy'] == true && isset($conf['nginx']['installed']) && $conf['nginx']['installed'] == true) {
            return true;
        } else {
            return false;
        }
 
    }
 
 
    /*
         This function is called when the plugin is loaded
    */
 
    function onLoad() {
        global $app;
 
        /*
        Register for the events
        */
 
        $app->plugins->registerEvent('web_domain_insert', $this->plugin_name, 'ssl');
        $app->plugins->registerEvent('web_domain_update', $this->plugin_name, 'ssl');
        $app->plugins->registerEvent('web_domain_delete', $this->plugin_name, 'ssl');
 
        $app->plugins->registerEvent('web_domain_insert', $this->plugin_name, 'insert');
        $app->plugins->registerEvent('web_domain_update', $this->plugin_name, 'update');
        $app->plugins->registerEvent('web_domain_delete', $this->plugin_name, 'delete');
 
        // $app->plugins->registerEvent('proxy_reverse_insert',$this->plugin_name,'rewrite_insert');
        // $app->plugins->registerEvent('proxy_reverse_update',$this->plugin_name,'rewrite_update');
        // $app->plugins->registerEvent('proxy_reverse_delete',$this->plugin_name,'rewrite_delete');
 
 
 
    }
 
 
    function insert($event_name, $data) {
        global $app, $conf;
 
        // just run the update function
        $this->update($event_name, $data);
    }
 
 
    function update($event_name, $data) {
        global $app, $conf;
 
        if($this->action != 'insert') $this->action = 'update';
 
        if($data['new']['type'] != 'vhost' && $data['new']['type'] != 'vhostsubdomain' && $data['new']['type'] != 'vhostalias' && $data['new']['parent_domain_id'] > 0) {
 
            $old_parent_domain_id = intval($data['old']['parent_domain_id']);
            $new_parent_domain_id = intval($data['new']['parent_domain_id']);
 
            // If the parent_domain_id has been chenged, we will have to update the old site as well.
            if($this->action == 'update' && $data['new']['parent_domain_id'] != $data['old']['parent_domain_id']) {
                $tmp = $app->dbmaster->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ? AND active = 'y'", $old_parent_domain_id);
                $data['new'] = $tmp;
                $data['old'] = $tmp;
                $this->action = 'update';
                $this->update($event_name, $data);
            }
 
            // This is not a vhost, so we need to update the parent record instead.
            $tmp = $app->dbmaster->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ? AND active = 'y'", $new_parent_domain_id);
            $data['new'] = $tmp;
            $data['old'] = $tmp;
            $this->action = 'update';
        }
 
 
 
 
        // load the server configuration options
        $app->uses('getconf');
        $nginx_config = $app->getconf->get_server_config($conf['server_id'], 'web');
 
        // Create group and user, if not exist
        $app->uses('system');
 
        //* Create the vhost config file
        $app->load('tpl');
 
        $tpl = new tpl();
        $tpl->newTemplate('nginx_reverseproxy_vhost.conf.master');
 
        $vhost_data = $data['new'];
        $vhost_data['config_dir'] = $config['nginx']['config_dir'];
 
        $vhost_data['ssl_domain'] = $data['new']['ssl_domain'];
        // Check if a SSL cert exists
        $ssl_dir = $config['nginx']['config_dir'].'/ssl';
        $domain = $data['new']['ssl_domain'];
        $key_file = $ssl_dir.'/'.$domain.'.key';
        $crt_file = $ssl_dir.'/'.$domain.'.crt';
        $bundle_file = $ssl_dir.'/'.$domain.'.bundle';
 
        $vhost_data['nginx_directives'] = preg_replace("/\[IP\]/", $vhost_data['ip_address'], $vhost_data['nginx_directives']);
 
 
        if($data['new']['ssl'] == 'y' && @is_file($crt_file) && @is_file($key_file)) {
            $vhost_data['ssl_enabled'] = 1;
            $app->log('Enable SSL for: '.$domain, LOGLEVEL_DEBUG);
        } else {
            $vhost_data['ssl_enabled'] = 0;
            $app->log('Disable SSL for: '.$domain, LOGLEVEL_DEBUG);
        }
 
        if(@is_file($bundle_file)) $vhost_data['has_bundle_cert'] = 1;
 
 
        $tpl->setVar($vhost_data);
 
 
 
        // get alias domains (co-domains and subdomains)
        $aliases = $app->dbmaster->queryAllRecords("SELECT * FROM web_domain WHERE parent_domain_id = ? AND (type != 'vhostsubdomain' OR type != 'vhostalias') AND active = 'y'", $data['new']['domain_id']);
        $server_alias = array();
        switch($data['new']['subdomain']) {
        case 'www':
            $server_alias[] .= 'www.'.$data['new']['domain'].' ';
            break;
        case '*':
            $server_alias[] .= '*.'.$data['new']['domain'].' ';
            break;
        }
        if(is_array($aliases)) {
            foreach($aliases as $alias) {
                switch($alias['subdomain']) {
                case 'www':
                    $server_alias[] .= 'www.'.$alias['domain'].' '.$alias['domain'].' ';
                    break;
                case '*':
                    $server_alias[] .= '*.'.$alias['domain'].' '.$alias['domain'].' ';
                    break;
                default:
                    $server_alias[] .= $alias['domain'].' ';
                    break;
                }
                $app->log('Add server alias: '.$alias['domain'], LOGLEVEL_DEBUG);
 
            }
        }
 
        //* If we have some alias records
        if(count($server_alias) > 0) {
            $server_alias_str = '';
            $n = 0;
 
            // begin a new ServerAlias line after 30 alias domains
            foreach($server_alias as $tmp_alias) {
                if($n % 30 == 0) $server_alias_str .= " ";
                $server_alias_str .= $tmp_alias;
            }
            unset($tmp_alias);
 
            $tpl->setVar('alias', trim($server_alias_str));
        } else {
            $tpl->setVar('alias', '');
        }
 
 
        $vhost_file = escapeshellcmd($nginx_config['nginx_vhost_conf_dir'].'/'.$data['new']['domain'].'.vhost');
        //* Make a backup copy of vhost file
        copy($vhost_file, $vhost_file.'~');
 
        //* Write vhost file
        file_put_contents($vhost_file, $tpl->grab());
        $app->log('Writing the vhost file: '.$vhost_file, LOGLEVEL_DEBUG);
        unset($tpl);
 
 
        // Set the symlink to enable the vhost
        $vhost_symlink = escapeshellcmd($nginx_config['nginx_vhost_conf_enabled_dir'].'/'.$data['new']['domain'].'.vhost');
        if($data['new']['active'] == 'y' && !is_link($vhost_symlink)) {
            symlink($vhost_file, $vhost_symlink);
            $app->log('Creating symlink: '.$vhost_symlink.'->'.$vhost_file, LOGLEVEL_DEBUG);
        }
 
        // Remove the symlink, if site is inactive
        if($data['new']['active'] == 'n' && is_link($vhost_symlink)) {
            unlink($vhost_symlink);
            $app->log('Removing symlink: '.$vhost_symlink.'->'.$vhost_file, LOGLEVEL_DEBUG);
        }
 
        if(!is_dir('/var/log/ispconfig/nginx/'.$data['new']['domain'])) exec('mkdir -p /var/log/ispconfig/nginx/'.$data['new']['domain']);
 
        // remove old symlink and vhost file, if domain name of the site has changed
        if($this->action == 'update' && $data['old']['domain'] != '' && $data['new']['domain'] != $data['old']['domain']) {
            $vhost_symlink = escapeshellcmd($nginx_config['nginx_vhost_conf_enabled_dir'].'/'.$data['old']['domain'].'.vhost');
            unlink($vhost_symlink);
            $app->log('Removing symlink: '.$vhost_symlink.'->'.$vhost_file, LOGLEVEL_DEBUG);
            $vhost_file = escapeshellcmd($nginx_config['nginx_vhost_conf_dir'].'/'.$data['old']['domain'].'.vhost');
            unlink($vhost_file);
            $app->log('Removing file: '.$vhost_file, LOGLEVEL_DEBUG);
 
            if(is_dir('/var/log/ispconfig/nginx/'.$data['old']['domain'])) exec('rm -rf /var/log/ispconfig/nginx/'.$data['old']['domain']);
        }
 
        // request a httpd reload when all records have been processed
        $app->services->restartServiceDelayed('nginx', 'restart');
 
        // Remove the backup copy of the config file.
        if(@is_file($vhost_file.'~')) unlink($vhost_file.'~');
 
 
        //* Unset action to clean it for next processed vhost.
        $this->action = '';
 
    }
 
 
 
 
    // Handle the creation of SSL certificates
    function ssl($event_name, $data) {
        global $app, $conf;
 
        if(!is_dir($conf['nginx']['config_dir'].'/ssl')) exec('mkdir -p '.$conf['nginx']['config_dir'].'/ssl');
        $ssl_dir = $conf['nginx']['config_dir'].'/ssl';
        $domain = $data['new']['ssl_domain'];
        $key_file = $ssl_dir.'/'.$domain.'.key.org';
        $key_file2 = $ssl_dir.'/'.$domain.'.key';
        $csr_file = $ssl_dir.'/'.$domain.'.csr';
        $crt_file = $ssl_dir.'/'.$domain.'.crt';
 
 
        //* Save a SSL certificate to disk
        if($data["new"]["ssl_action"] == 'save') {
            $web = $app->masterdb->queryOneRecord("select wd.document_root, sp.ip_address from web_domain wd INNER JOIN server_ip sp USING(server_id) WHERE domain = ?", $data['new']['domain']);
 
            $src_ssl_dir = $web["document_root"]."/ssl";
            //$domain = $data["new"]["ssl_domain"];
            //$csr_file = $ssl_dir.'/'.$domain.".csr";
            //$crt_file = $ssl_dir.'/'.$domain.".crt";
            //$bundle_file = $ssl_dir.'/'.$domain.".bundle";
            $this->_exec('rsync -v -e ssh root@'.$web['ip_address'].':~/$src_ssl_dir '.$ssl_dir);
 
            $app->log('Syncing SSL Cert for: '.$domain, LOGLEVEL_DEBUG);
        }
 
        //* Delete a SSL certificate
        if($data['new']['ssl_action'] == 'del') {
            //$ssl_dir = $data['new']['document_root'].'/ssl';
            $domain = $data['new']['ssl_domain'];
            $csr_file = $ssl_dir.'/'.$domain.'.csr';
            $crt_file = $ssl_dir.'/'.$domain.'.crt';
            $bundle_file = $ssl_dir.'/'.$domain.'.bundle';
            unlink($csr_file);
            unlink($crt_file);
            unlink($bundle_file);
            $app->log('Deleting SSL Cert for: '.$domain, LOGLEVEL_DEBUG);
        }
 
 
    }
 
 
    function delete($event_name, $data) {
        global $app, $conf;
 
        // load the server configuration options
        $app->uses('getconf');
        $nginx_config = $app->getconf->get_server_config($conf['server_id'], 'web');
 
 
        if($data['old']['type'] == 'vhost' || $data['old']['type'] == 'vhostsubdomain' || $data['old']['type'] == 'vhostalias') {
 
            //* This is a website
            // Deleting the vhost file, symlink and the data directory
            $vhost_symlink = escapeshellcmd($nginx_config['nginx_vhost_conf_enabled_dir'].'/'.$data['old']['domain'].'.vhost');
            unlink($vhost_symlink);
            $app->log('Removing symlink: '.$vhost_symlink.'->'.$vhost_file, LOGLEVEL_DEBUG);
 
            $vhost_file = escapeshellcmd($nginx_config['nginx_vhost_conf_dir'].'/'.$data['old']['domain'].'.vhost');
            unlink($vhost_file);
            $app->log('Removing vhost file: '.$vhost_file, LOGLEVEL_DEBUG);
 
 
 
            // Delete the log file directory
            $vhost_logfile_dir = escapeshellcmd('/var/log/ispconfig/nginx/'.$data['old']['domain']);
            if($data['old']['domain'] != '' && !stristr($vhost_logfile_dir, '..')) exec('rm -rf '.$vhost_logfile_dir);
            $app->log('Removing website logfile directory: '.$vhost_logfile_dir, LOGLEVEL_DEBUG);
 
        }
    }
 
    //* Wrapper for exec function for easier debugging
    private function _exec($command) {
        global $app;
        $app->log('exec: '.$command, LOGLEVEL_DEBUG);
        exec($command);
    }
 
    function rewrite_insert($event_name, $data) {
        global $app, $conf;
 
        // just run the update function
        $this->update($event_name, $data);
    }
 
    function rewrite_update($event_name, $data) {
        global $app, $conf;
 
        $rules = $this->_getRewriteRules($app);
 
        $app->uses('getconf');
        $nginx_config = $app->getconf->get_server_config($conf['server_id'], 'web');
 
        $app->load('tpl');
        $tpl = new tpl();
        $tpl->newTemplate("nginx_reverseproxy_rewrites.conf.master");
        if (!empty($rules))$tpl->setLoop('nginx_rewrite_rules', $rules);
 
        $rewrites_file = escapeshellcmd($nginx_config['nginx_vhost_conf_dir'].'/default.rewrites.conf');
        //* Make a backup copy of vhost file
        copy($rewrites_file, $rewrites_file.'~');
 
        //* Write vhost file
        file_put_contents($rewrites_file, $tpl->grab());
        $app->log('Writing the nginx rewrites file: '.$rewrites_file, LOGLEVEL_DEBUG);
        unset($tpl);
 
 
        // Set the symlink to enable the vhost
        $rewrite_symlink = escapeshellcmd($nginx_config['nginx_vhost_conf_enabled_dir'].'/default.rewrites.conf');
 
        if(!is_link($rewrite_symlink)) {
            symlink($rewrites_file, $rewrite_symlink);
            $app->log('Creating symlink for nginx rewrites: '.$rewrite_symlink.'->'.$rewrites_file, LOGLEVEL_DEBUG);
        }
    }
 
    function rewrite_delete($event_name, $data) {
        global $app, $conf;
 
        // just run the update function
        $this->rewrite_update($event_name, $data);
    }
 
 
    function _getRewriteRules($app)
    {
        $rules = array();
        $rules = $app->db->queryAllRecords("SELECT rewrite_url_src, rewrite_url_dst FROM proxy_reverse ORDER BY rewrite_id ASC");
        return $rules;
    }
 
} // end class
 
?>