m_dom.php 81.3 KB
Newer Older
1
<?php
alban's avatar
alban committed
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

/*
  ----------------------------------------------------------------------
  AlternC - Web Hosting System
  Copyright (C) 2000-2012 by the AlternC Development Team.
  https://alternc.org/
  ----------------------------------------------------------------------
  LICENSE

  This program is free software; you can redistribute it and/or
  modify it under the terms of the GNU General Public License (GPL)
  as published by the Free Software Foundation; either version 2
  of the License, or (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  To read the license please visit http://www.gnu.org/copyleft/gpl.html
  ----------------------------------------------------------------------
  Purpose of file: PHP Class that manage domain names installed on the server
  ----------------------------------------------------------------------
 */
26
27
28
29

define('SLAVE_FLAG', "/var/run/alternc/refresh_slave");

/**
Alan Garcia's avatar
Alan Garcia committed
30
 * Classe de gestion des domaines de l'hébergé.
alban's avatar
alban committed
31
 * 
Alan Garcia's avatar
Alan Garcia committed
32
33
 * Cette classe permet de gérer les domaines / sous-domaines, redirections
 * dns et mx des domaines d'un membre hébergé.<br />
alban's avatar
alban committed
34
 */
35
36
class m_dom {

alban's avatar
alban committed
37
38
39
40
41
    /** $domains : Cache des domaines du membre
     * @access private
     */
    var $domains;

Alan Garcia's avatar
Alan Garcia committed
42
    /** $dns : Liste des dns trouvés par la fonction whois
alban's avatar
alban committed
43
44
45
46
     * @access private
     */
    var $dns;

Alan Garcia's avatar
Alan Garcia committed
47
    /** Flag : a-t-on trouvé un sous-domaine Webmail pour ce domaine ?
alban's avatar
alban committed
48
49
50
51
52
     * @access private
     */
    var $webmail;

    /**
Alan Garcia's avatar
Alan Garcia committed
53
     * Systéme de verrouillage du cron
alban's avatar
alban committed
54
55
56
57
58
59
60
     * Ce fichier permet de verrouiller le cron en attendant la validation
     * du domaine par update_domains.sh
     * @access private
     */
    var $fic_lock_cron = "/var/run/alternc/cron.lock";

    /**
Alan Garcia's avatar
Alan Garcia committed
61
62
     * Le cron a-t-il été bloqué ?
     * Il faut appeler les fonctions privées lock et unlock entre les
alban's avatar
alban committed
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
     * appels aux domaines.
     * @access private
     */
    var $islocked = false;
    var $type_local = "VHOST";
    var $type_url = "URL";
    var $type_ip = "IP";
    var $type_webmail = "WEBMAIL";
    var $type_ipv6 = "IPV6";
    var $type_cname = "CNAME";
    var $type_txt = "TXT";
    var $type_defmx = "DEFMX";
    var $type_defmx2 = "DEFMX2";
    var $action_insert = "0";
    var $action_update = "1";
    var $action_delete = "2";
    var $tld_no_check_at_all = "1";
    var $cache_domains_type_lst = false;

    /* ----------------------------------------------------------------- */

    /**
     * Constructeur
     */
    function m_dom() {
Alan Garcia's avatar
Alan Garcia committed
88
89
        $this->tld_no_check_at_all = variable_get('tld_no_check_at_all', 0, 'Disable ALL check on the TLD (users will be able to add any domain)', array('desc' => 'Disabled', 'type' => 'boolean'));
        variable_get('mailname_bounce', '%%FQDN%%', 'FQDN of the mail server, used to create vhost virtual mail_adress.', array('desc' => 'FQDN', 'type' => 'string'));
alban's avatar
alban committed
90
91
92
93
94
95
96
97
98
99
100
101
102
    }

    function get_panel_url_list() {
        global $db, $err;
        $err->log("dom", "get_panel_url_list");
        $db->query("SELECT sd.id as sub_id, if(length(sd.sub)>0,concat_ws('.',sd.sub,sd.domaine),sd.domaine) as fqdn from sub_domaines sd where type = 'PANEL';");
        $t = array();
        while ($db->next_record()) {
            $t[intval($db->f('sub_id'))] = $db->f('fqdn');
        }
        return $t;
    }

fufroma's avatar
fufroma committed
103
104
105
    /**
     * @param string $fqdn
     */
alban's avatar
alban committed
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
    function get_sub_domain_id_and_member_by_name($fqdn) {
        global $db, $err, $cuid;
        $err->log("dom", "get_sub_domain_by_name");
        $fqdn = mysql_real_escape_string($fqdn);
        $db->query("select sd.* from sub_domaines sd where if(length(sd.sub)>0,concat_ws('.',sd.sub,sd.domaine),sd.domaine) = '$fqdn';");
        if (!$db->next_record())
            return false;
        return array('sub_id' => intval($db->f('id')), 'member_id' => intval($db->f('compte')));
    }

    function hook_menu() {
        global $quota;
        $obj = array(
            'title' => _("Domains"),
            'ico' => 'images/dom.png',
            'link' => 'toggle',
            'pos' => 20,
            'links' => array(),
                );

        if ($quota->cancreate("dom")) {
            $obj['links'][] =
                    array(
                        'ico' => 'images/new.png',
                        'txt' => _("Add a domain"),
                        'url' => "dom_add.php",
            );
        }

        foreach ($this->enum_domains() as $d) {
            $obj['links'][] =
                    array(
                        'txt' => htmlentities($d),
                        'url' => "dom_edit.php?domain=" . urlencode($d),
            );
        }

        return $obj;
    }

    /* ----------------------------------------------------------------- */

    /**
     * Retourne un tableau contenant les types de domaines
     *
Alan Garcia's avatar
Alan Garcia committed
151
152
     * @return array retourne un tableau indexé contenant la liste types de domaines 
     *  authorisé. Retourne FALSE si une erreur s'est produite.
alban's avatar
alban committed
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
     */
    function domains_type_lst() {
        global $db, $err;
        $err->log("dom", "domains_type_lst");
        if (empty($this->cache_domains_type_lst)) {
            $db->query("select * from domaines_type order by advanced;");
            $this->cache_domains_type_lst = array();
            while ($db->next_record()) {
                $this->cache_domains_type_lst[strtolower($db->Record["name"])] = $db->Record;
            }
        }
        return $this->cache_domains_type_lst;
    }

    function domains_type_enable_values() {
        global $db, $err, $cuid;
        $err->log("dom", "domains_type_target_values");
        $db->query("desc domaines_type;");
        $r = array();
        while ($db->next_record()) {
            if ($db->f('Field') == 'enable') {
                $tab = explode(",", substr($db->f('Type'), 5, -1));
                foreach ($tab as $t) {
                    $r[] = substr($t, 1, -1);
                }
            }
        }
        return $r;
    }

Alan Garcia's avatar
Alan Garcia committed
183
184
185
    /**
     * @param integer $type
     */
alban's avatar
alban committed
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
    function domains_type_target_values($type = null) {
        global $db, $err, $cuid;
        $err->log("dom", "domains_type_target_values");
        if (is_null($type)) {
            $db->query("desc domaines_type;");
            $r = array();
            while ($db->next_record()) {
                if ($db->f('Field') == 'target') {
                    $tab = explode(",", substr($db->f('Type'), 5, -1));
                    foreach ($tab as $t) {
                        $r[] = substr($t, 1, -1);
                    }
                }
            }
            return $r;
201
        } else {
alban's avatar
alban committed
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
            $db->query("select target from domaines_type where name='$type';");
            if (!$db->next_record())
                return false;
            return $db->f('target');
        }
    }

    function import_manual_dns_zone($zone, $domain, $detect_redirect = true, $save = false) {
        global $err;
        if ($save) {
            if (!$this->import_manual_dns_prep_zone($domain)) {
                $err->raise('dom', _("Err: failed to prepare the zone"));
                return false;
            }
        }

        $val = array();
        foreach (explode("\n", $zone) as $z) {
            $z = trim($z);
            if (empty($z))
                continue;
            $val[] = $this->import_manual_dns_entry($z, $domain, $detect_redirect, $save);
        }
        return $val;
    }

fufroma's avatar
fufroma committed
228
229
230
    /**
     * @param string $zone
     */
alban's avatar
alban committed
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
    function import_manual_dns_entry($zone, $domain, $detect_redirect = true, $save = false) {
        global $cuid, $err;
        $err->log("dom", "import_manual_dns_entry");
        $zone = trim($zone);
        if (empty($zone))
            return false;

        $domain = trim($domain);
        if (empty($domain)) {
            $err->raise("dom", _("Missing domain name"));
            return false;
        }

        $val = array(
            'status' => 'err', // can be 'ok', 'err', 'warn'
            'comment' => 'no val',
            'entry_old' => $zone,
            'entry_new' => array('domain' => $domain),
        );

        // Examples:
        // ; hello comment
        if (preg_match('/^;/', $zone, $ret)) {
            $val['status'] = 'ok';
            $val['comment'] = 'Just a comment, do not import';
        } else
        // Examples:
        // $TTL 86400'
        if (preg_match('/^\$TTL\h+(?P<ttl>[\dMHDmhd]+)/', $zone, $ret)) {
            $val['status'] = 'ok';
            $val['comment'] = 'Set TTL to ' . $ret['ttl'];
            $val['entry_new']['type'] = 'set_ttl';
            $val['entry_new']['value'] = $ret['ttl'];
        } else

        // Examples:
        // @ IN AAAA 127.2.1.5
        // reseau IN AAAA 145.214.44.55
        if (preg_match('/^(?P<sub>[\w\.@\-]*)\h*(?P<ttl>\d*)\h*IN\h+AAAA\h+(?P<target>[0-9A-F:]{2,40})/i', $zone, $ret)) {

            // Check if it is just a redirect
            if (substr($ret['sub'], -1) == '.') { // if ending by a "." it is allready a FQDN
                $url = "http://" . $ret['sub'];
            } else {
                if ($ret['sub'] == '@' || empty($ret['sub'])) {
                    $url = "http://" . $domain;
                } else {
                    $url = "http://" . $ret['sub'] . "." . $domain;
                }
            }
            if ($detect_redirect && $dst_url = $this->is_it_a_redirect($url)) {
                $val['status'] = 'warn';
                $val['comment'] = "Became a redirect to $dst_url";
                $val['entry_new']['type'] = 'URL';
                $val['entry_new']['sub'] = $ret['sub'];
                $val['entry_new']['value'] = $dst_url;
            } else {
                $val['status'] = 'ok';
                $val['comment'] = "Create entry AAAA with " . $ret['sub'] . " go to " . $ret['target'] . " with ttl " . $ret['ttl'];
                $val['entry_new']['type'] = 'IPV6';
                $val['entry_new']['sub'] = $ret['sub'];
                $val['entry_new']['value'] = $ret['target'];
            }
        } else


        // Examples:
        // @ IN A 127.2.1.5
        // reseau IN A 145.214.44.55
        if (preg_match('/^(?P<sub>[\w\.@\-]*)\h*(?P<ttl>\d*)\h*IN\h+A\h+(?P<target>\d+\.\d+\.\d+\.\d+)/i', $zone, $ret)) {
            // Check if it is just a redirect
            if (substr($ret['sub'], -1) == '.') { // if ending by a "." it is allready a FQDN
                $url = "http://" . $ret['sub'];
            } else {
                if ($ret['sub'] == '@' || empty($ret['sub'])) {
                    $url = "http://" . $domain;
                } else {
                    $url = "http://" . $ret['sub'] . "." . $domain;
                }
            }
            if ($detect_redirect && $dst_url = $this->is_it_a_redirect($url)) {
                $val['status'] = 'warn';
                $val['comment'] = "Became a redirect to $dst_url";
                $val['entry_new']['type'] = 'URL';
                $val['entry_new']['sub'] = $ret['sub'];
                $val['entry_new']['value'] = $dst_url;
            } else {
                $val['status'] = 'ok';
                $val['comment'] = "Create entry A with " . $ret['sub'] . " go to " . $ret['target'] . " with ttl " . $ret['ttl'];
                $val['entry_new']['type'] = 'IP';
                $val['entry_new']['sub'] = $ret['sub'];
                $val['entry_new']['value'] = $ret['target'];
            }
        } else

        // Examples:
        // @ IN NS ns.example.tld.
        // ns 3600 IN NS 145.214.44.55
        if (preg_match('/^(?P<sub>[\-\w\.@]*)\h*(?P<ttl>\d*)\h*IN\h+NS\h+(?P<target>[\w\.\-]+)/i', $zone, $ret)) {
            if (empty($ret['sub']) || $ret['sub'] == '@') {
                $val['status'] = 'warn';
                $val['comment'] = "Won't migrate it, there will get a new value";
            } else {
                $val['status'] = 'ok';
                $val['comment'] = "Create entry NS with " . $ret['sub'] . " go to " . $ret['target'] . " with ttl " . $ret['ttl'];
                $val['entry_new']['type'] = 'FIXME-NS';
                $val['entry_new']['sub'] = $ret['sub'];
                $val['entry_new']['value'] = $ret['target'];
            }
        } else

        // Examples:
        // agenda IN CNAME ghs.google.com.
        // www 3600 IN CNAME @
        if (preg_match('/^(?P<sub>[\-\w\.@]*)\h*(?P<ttl>\d*)\h*IN\h+CNAME\h+(?P<target>[@\w+\.\-]+)/i', $zone, $ret)) {
            if (substr($ret['sub'], -1) == '.') { // if ending by a "." it is allready a FQDN
                $url = "http://" . $ret['sub'];
            } else {
                if ($ret['sub'] == '@' || empty($ret['sub'])) {
                    $url = "http://" . $domain;
                } else {
                    $url = "http://" . $ret['sub'] . "." . $domain;
                }
            }
            if ($detect_redirect && $dst_url = $this->is_it_a_redirect($url)) {
                $val['status'] = 'warn';
                $val['comment'] = "Became a redirect to $dst_url";
                $val['entry_new']['type'] = 'URL';
                $val['entry_new']['sub'] = $ret['sub'];
                $val['entry_new']['value'] = $dst_url;
            } else {
                $val['status'] = 'ok';
                $val['comment'] = "Create entry CNAME with " . $ret['sub'] . " go to " . $ret['target'] . " with ttl " . $ret['ttl'];
                $val['entry_new']['type'] = 'CNAME';
                $val['entry_new']['sub'] = $ret['sub'];
                $val['entry_new']['value'] = $ret['target'];
            }
        } else

        // Examples:
        // @ IN MX 10 aspmx.l.google.com.
        // arf 3600 IN MX 20 pouet.fr.
        if (preg_match('/^(?P<sub>[\-\w\.@]*)\h*(?P<ttl>\d*)\h*IN\h+MX\h+(?P<weight>\d+)\h+(?P<target>[@\w+\.\-]+)/i', $zone, $ret)) {
            $val['status'] = 'warn';
            $val['comment'] = "Create entry MX with " . $ret['sub'] . " go to " . $ret['target'] . " with ttl " . $ret['ttl'] . " and weight 5 (initial weight was " . $ret['weight'] . ")";
            $val['entry_new']['type'] = 'MX';
            $val['entry_new']['sub'] = $ret['sub'];
            $val['entry_new']['value'] = $ret['target'];
        } else

        // Examples:
        // _sip._tcp  IN      SRV             1 100 5061 sip.example.tld.
        if (preg_match('/^(?P<sub>[\_\w\.@\-]+)\h+(?P<ttl>\d*)\h*IN\h+SRV\h+/i', $zone, $ret)) {
            $val['status'] = 'err';
            $val['comment'] = "Please add yourself the entry $zone";
        } else

        // Examples:
        // @       IN      TXT             "google-site-verification=jjjjjjjjjjjjjjjjjjjjjjjjsdsdjlksjdljdslgNj5"
        if (preg_match('/^(?P<sub>[\_\w\.@\-]*)\h*(?P<ttl>\d*)\h*IN\h+TXT\h+\"(?P<target>.+)\"/i', $zone, $ret)) {
            $val['status'] = 'ok';
            $val['comment'] = "Create TXT entry with " . $ret['sub'] . " go to " . $ret['target'];
            $val['entry_new']['type'] = 'TXT';
            $val['entry_new']['sub'] = $ret['sub'];
            $val['entry_new']['value'] = $ret['target'];
396
        } else {
alban's avatar
alban committed
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442

            // WTF can it be ?
            $val['comment'] = "Unknow: $zone";
        }

        if ($save) {
            return $this->import_manual_dns_entry_doit($val);
        }

        return $val;
    }

    private function import_manual_dns_entry_doit($entry) {
        global $err;
        $entry['did_it'] = 0;
        if ($entry['status'] == 'err') {
            return $entry;
        }

        $val = $entry['entry_new'];

        if (empty($val['type']))
            return false;

        switch ($val['type']) {
            case "set_ttl":
                $entry['did_it'] = $this->set_ttl($this->get_domain_byname($val['domain']), $val['value']);
                return $entry;
                break;
        }

        // If it is an unknown domains type
        if (!array_key_exists(strtolower($val['type']), $this->domains_type_lst())) {
            echo "what is this shit ?\n";
            print_r($entry);
            return $entry;
        }

        // If the subdomain is @, we want an empty subdomain
        if ($val['sub'] == '@')
            $val['sub'] = '';

        $this->lock();
        $entry['did_it'] = $this->set_sub_domain($val['domain'], $val['sub'], $val['type'], $val['value']);
        $this->unlock();

443
444
445
        return $entry;
    }

alban's avatar
alban committed
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
    private function import_manual_dns_prep_zone($domain) {
        global $err;
        // Prepare a domain to be importer : 
        // * create the domain
        // * delete all automatic subdomain
        // * set no mx
        $this->lock();

        // function add_domain($domain,$dns,$noerase=0,$force=0,$isslave=0,$slavedom="") 
        if (!$this->add_domain($domain, true, false, true)) {
            $err->raise('dom', "Error adding domain");
            return false;
        }

        // Set no mx
        $this->edit_domain($domain, true, false);

        $d = $this->get_domain_all($domain);
        foreach ($d['sub'] as $sd) {
            $this->del_sub_domain($sd['id']);
        }

        $this->unlock();

        return true;
    }

    // Take an URL, and return FALSE is there is no redirection,
    // and the target URL if there is one (HTTP CODE 301 & 302)
    // CURL is needed
fufroma's avatar
fufroma committed
476
477
478
479

    /**
     * @param string $url
     */
alban's avatar
alban committed
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
    function is_it_a_redirect($url) {
        try {
            $params = array('http' => array(
                    'method' => 'HEAD',
                    'ignore_errors' => true
            ));

            $context = stream_context_create($params);
            $fp = @fopen($url, 'rb', false, $context);
            $result = @stream_get_contents($fp);

            if ($result === false) {
                throw new Exception("Could not read data from {$url}");
                return false;
            }
            if (strstr($http_response_header[0], '301') || strstr($http_response_header[0], '302')) {
                // This is a redirection
                if (preg_match('/Location:\h+(?P<target>[\-\w:\/.\?\=.]+)/', implode("\n", $http_response_header), $ret)) {
                    // check if it is a redirection to himself
                    preg_match('/\/\/(?P<host>[\w\.\-]+)\//', ( substr($url, -1) == '/' ? $url : $url . '/'), $original_cname);
                    preg_match('/\/\/(?P<host>[\w\.\-]+)\//', $ret['target'], $target_url);
                    if (isset($target_url['host']) && ( $target_url['host'] == $original_cname['host'] )) { // if it's a redirection to himself (sub pages, http to https...)
                        return false; // do not do a redirection (we must point to the server)
                    }

                    // If it is a redirection to a sub directory
                    // (we know it is a redirection to a sub directory because it's not a complete URI)
                    if (substr($ret['target'], 0, 4) != 'http') {
                        return 'http://' . $original_cname['host'] . '/' . $ret['target'];
                    }
                    return $ret['target'];
                }
            } else { // it isn't a redirection 
                return false;
            }
        } catch (Exception $e) {
            return false;
        }
    }

    function domains_type_regenerate($name) {
        global $db, $err, $cuid;
        $name = mysql_real_escape_string($name);
        $db->query("update sub_domaines set web_action='UPDATE' where lower(type) = lower('$name') ;");
        $db->query("update domaines d, sub_domaines sd set d.dns_action = 'UPDATE' where lower(sd.type)=lower('$name');");
        return true;
    }

    function domains_type_get($name) {
        global $db, $err, $cuid;
        $name = mysql_real_escape_string($name);
        $db->query("select * from domaines_type where name='$name' ;");
        $db->next_record();
        return $db->Record;
    }

    function domains_type_del($name) {
        global $db, $err, $cuid;
        $name = mysql_real_escape_string($name);
        $db->query("delete domaines_type where name='$name';");
        return true;
    }

    function domains_type_update($name, $description, $target, $entry, $compatibility, $enable, $only_dns, $need_dns, $advanced, $create_tmpdir, $create_targetdir) {
        global $err, $cuid, $db;
        // The name MUST contain only letter and digits, it's an identifier after all ...
        if (!preg_match("#^[a-z0-9]+$#", $name)) {
            $err->raise("dom", _("The name MUST contain only letter and digits"));
            return false;
        }
        $name = mysql_real_escape_string($name);
        $description = mysql_real_escape_string($description);
        $target = mysql_real_escape_string($target);
        $entry = mysql_real_escape_string($entry);
        $compatibility = mysql_real_escape_string($compatibility);
        $enable = mysql_real_escape_string($enable);
        $only_dns = intval($only_dns);
        $need_dns = intval($need_dns);
        $advanced = intval($advanced);
        $create_tmpdir = intval($create_tmpdir);
        $create_targetdir = intval($create_targetdir);
        $db->query("UPDATE domaines_type SET description='$description', target='$target', entry='$entry', compatibility='$compatibility', enable='$enable', need_dns=$need_dns, only_dns=$only_dns, advanced='$advanced',create_tmpdir=$create_tmpdir,create_targetdir=$create_targetdir where name='$name';");
        return true;
563
564
    }

alban's avatar
alban committed
565
566
567
568
569
570
571
    function sub_domain_change_status($sub_id, $status) {
        global $db, $err, $cuid;
        $err->log("dom", "sub_domain_change_status");
        $sub_id = intval($sub_id);
        $status = strtoupper($status);
        if (!in_array($status, array('ENABLE', 'DISABLE')))
            return false;
572

alban's avatar
alban committed
573
574
575
576
577
578
579
        $jh = $this->get_sub_domain_all($sub_id);
        if ($status == 'ENABLE') { // check compatibility with existing sub_domains
            if (!$this->can_create_subdomain($jh['domain'], $jh['name'], $jh['type'], $sub_id)) {
                $err->raise("dom", _("The parameters for this subdomain and domain type are invalid. Please check for subdomain entries incompatibility"));
                return false;
            }
        }
580

alban's avatar
alban committed
581
582
        $db->query("update sub_domaines set enable='$status' where id = '" . intval($sub_id) . "';");
        $this->set_dns_action($jh['domain'], 'UPDATE');
583

alban's avatar
alban committed
584
585
        return true;
    }
586

alban's avatar
alban committed
587
588
589
590
    /* ----------------------------------------------------------------- */

    /**
     * Retourne un tableau contenant les domaines d'un membre.
Alan Garcia's avatar
Alan Garcia committed
591
     * Par défaut le membre connecté
alban's avatar
alban committed
592
     *
Alan Garcia's avatar
Alan Garcia committed
593
594
     * @return array retourne un tableau indexé contenant la liste des
     *  domaines hébergés sur le compte courant. Retourne FALSE si une
alban's avatar
alban committed
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
     *  erreur s'est produite.
     */
    function enum_domains($uid = -1) {
        global $db, $err, $cuid;
        $err->log("dom", "enum_domains");
        if ($uid == -1) {
            $uid = $cuid;
        }
        $db->query("SELECT * FROM domaines WHERE compte='{$uid}' ORDER BY domaine ASC;");
        $this->domains = array();
        if ($db->num_rows() > 0) {
            while ($db->next_record()) {
                $this->domains[] = $db->f("domaine");
            }
        }
        return $this->domains;
611
612
    }

alban's avatar
alban committed
613
614
615
616
617
618
    function del_domain_cancel($dom) {
        global $db, $err, $classes, $cuid;
        $err->log("dom", "del_domaini_canl", $dom);
        $dom = strtolower($dom);
        $db->query("UPDATE sub_domaines SET web_action='UPDATE'  WHERE domaine='$dom';");
        $this->set_dns_action($dom, 'UPDATE');
619

alban's avatar
alban committed
620
621
622
        # TODO : some work with domain sensitive classes

        return true;
623
624
    }

alban's avatar
alban committed
625
626
627
628
629
630
    /* ----------------------------------------------------------------- */

    /**
     *  Efface un domaine du membre courant, et tous ses sous-domaines
     *
     * Cette fonction efface un domaine et tous ses sous-domaines, ainsi que
Alan Garcia's avatar
Alan Garcia committed
631
632
633
     * les autres services attachés é celui-ci. Elle appelle donc les autres
     * classe. Chaque classe peut déclarer une fonction del_dom qui sera
     * appellée lors de la destruction d'un domaine.
alban's avatar
alban committed
634
     *
Alan Garcia's avatar
Alan Garcia committed
635
     * @param string $dom nom de domaine é effacer
alban's avatar
alban committed
636
637
638
639
640
641
642
643
644
645
646
647
     * @return boolean Retourne FALSE si une erreur s'est produite, TRUE sinon.
     */
    function del_domain($dom) {
        global $db, $err, $classes, $cuid, $hooks;
        $err->log("dom", "del_domain", $dom);
        $dom = strtolower($dom);

        $this->lock();
        if (!$r = $this->get_domain_all($dom)) {
            return false;
        }
        $this->unlock();
648

alban's avatar
alban committed
649
650
651
652
653
654
655
        // Call Hooks to delete the domain and the MX management:
        // TODO : the 2 calls below are using an OLD hook call, FIXME: remove them when unused
        $hooks->invoke("alternc_del_domain", array($dom));
        $hooks->invoke("alternc_del_mx_domain", array($dom));
        // New hook calls: 
        $hooks->invoke("hook_dom_del_domain", array($r["id"]));
        $hooks->invoke("hook_dom_del_mx_domain", array($r["id"]));
656

alban's avatar
alban committed
657
658
659
        // Now mark the domain for deletion:
        $db->query("UPDATE sub_domaines SET web_action='DELETE'  WHERE domaine='$dom';");
        $this->set_dns_action($dom, 'DELETE');
660

alban's avatar
alban committed
661
662
663
664
665
666
667
668
669
670
671
672
        return true;
    }

    function domshort($dom, $sub = "") {
        return str_replace("-", "", str_replace(".", "", empty($sub) ? "" : "$sub.") . $dom);
    }

    /* ----------------------------------------------------------------- */

    /**
     *  Installe un domaine sur le compte courant.
     *
Alan Garcia's avatar
Alan Garcia committed
673
674
675
     * <p>Si le domaine existe déjé ou est interdit, ou est celui du serveur,
     * l'installation est refusée. Si l'hébergement DNS est demandé, la fonction
     * checkhostallow vérifiera que le domaine peut étre installé conformément
alban's avatar
alban committed
676
     * aux demandes des super-admin.
Alan Garcia's avatar
Alan Garcia committed
677
     * Si le dns n'est pas demandé, le domaine peut étre installé s'il est en
alban's avatar
alban committed
678
679
     * seconde main d'un tld (exemple : test.eu.org ou test.com, mais pas
     * toto.test.org ou test.test.asso.fr)</p>
Alan Garcia's avatar
Alan Garcia committed
680
681
     * <p>Chaque classe peut définir une fonction add_dom($dom) qui sera
     * appellée lors de l'installation d'un nouveau domaine.</p>
alban's avatar
alban committed
682
     *
Alan Garcia's avatar
Alan Garcia committed
683
     * @param boolean $dns 1 ou 0 pour héberger le DNS du domaine ou pas.
alban's avatar
alban committed
684
685
     * @param boolean $noerase 1 ou 0 pour rendre le domaine inamovible ou non
     * @param boolean $force 1 ou 0, si 1, n'effectue pas les tests de DNS.
Alan Garcia's avatar
Alan Garcia committed
686
     *  force ne devrait étre utilisé que par le super-admin.
alban's avatar
alban committed
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
      $ @return boolean Retourne FALSE si une erreur s'est produite, TRUE sinon.
     */
    function add_domain($domain, $dns, $noerase = false, $force = false, $isslave = false, $slavedom = "") {
        global $db, $err, $quota, $classes, $L_MX, $L_FQDN, $tld, $cuid, $bro, $hooks;
        $err->log("dom", "add_domain", $domain);

        // Locked ?
        if (!$this->islocked) {
            $err->raise("dom", _("--- Program error --- No lock on the domains!"));
            return false;
        }
        // Verifie que le domaine est rfc-compliant
        $domain = strtolower($domain);
        $t = checkfqdn($domain);
        if ($t) {
            $err->raise("dom", _("The domain name is syntaxically incorrect"));
            return false;
        }
Alan Garcia's avatar
Alan Garcia committed
705
        // Interdit les domaines clés (table forbidden_domains) sauf en cas FORCE
alban's avatar
alban committed
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
        $db->query("SELECT domain FROM forbidden_domains WHERE domain='$domain'");
        if ($db->num_rows() && !$force) {
            $err->raise("dom", _("The requested domain is forbidden in this server, please contact the administrator"));
            return false;
        }
        if ($domain == $L_FQDN || $domain == "www.$L_FQDN") {
            $err->raise("dom", _("This domain is the server's domain! You cannot host it on your account!"));
            return false;
        }
        $db->query("SELECT compte FROM domaines WHERE domaine='$domain';");
        if ($db->num_rows()) {
            $err->raise("dom", _("The domain already exist"));
            return false;
        }
        $db->query("SELECT compte FROM `sub_domaines` WHERE sub != \"\" AND concat( sub, \".\", domaine )='$domain' OR domaine='$domain';");
        if ($db->num_rows()) {
            $err->raise("dom", _("The domain already exist"));
            return false;
        }
        $this->dns = $this->whois($domain);
        if (!$force) {
            $v = checkhostallow($domain, $this->dns);
            if ($v == -1) {
                $err->raise("dom", _("The last member of the domain name is incorrect or cannot be hosted in that server"));
                return false;
            }
            if ($dns && $v == -2) {
                $err->raise("dom", _("The domain cannot be found in the whois database"));
                return false;
            }
            if ($dns && $v == -3) {
                $err->raise("dom", _("The domain cannot be found in the whois database"));
                return false;
            }

            if ($dns)
                $dns = "1";
            else
                $dns = "0";

            // mode 5 : force DNS to NO.
            if ($tld[$v] == 5)
                $dns = 0;
            // It must be a real domain (no subdomain)
            if (!$dns) {
                $v = checkhostallow_nodns($domain);
                if ($v) {
                    $err->raise("dom", _("The requested domain is forbidden in this server, please contact the administrator"));
                    return false;
                }
            }
        }
        // Check the quota :
        if (!$quota->cancreate("dom")) {
            $err->raise("dom", _("Your domain quota is over, you cannot create more domain names"));
            return false;
        }
        if ($noerase)
            $noerase = "1";
        else
            $noerase = "0";
        if ($dns)
            $gesmx = "1";
        else
            $gesmx = "0"; // do not host mx by default if not hosting the DNS
        $db->query("INSERT INTO domaines (compte,domaine,gesdns,gesmx,noerase,dns_action) VALUES ('$cuid','$domain','$dns','$gesmx','$noerase','UPDATE');");
        if (!($id = $db->lastid())) {
            $err->raise("dom", _("An unexpected error occured when creating the domain"));
            return false;
        }

        if ($isslave) {
            $isslave = true;
            $db->query("SELECT domaine FROM domaines WHERE compte='$cuid' AND domaine='$slavedom';");
            $db->next_record();
            if (!$db->Record["domaine"]) {
                $err->raise("dom", _("Domain '%s' not found"), $slavedom);
                $isslave = false;
            }
            // Point to the master domain : 
            $this->create_default_subdomains($domain, $slavedom);
        }
        if (!$isslave) {
            $this->create_default_subdomains($domain);
        }

        // TODO: Old hooks, FIXME: when unused remove them
        $hooks->invoke("alternc_add_domain", array($domain));
        if ($isslave) {
            $hooks->invoke("alternc_add_slave_domain", array($domain));
        }
        // New Hooks: 
        $hooks->invoke("hook_dom_add_domain", array($id));
        if ($gesmx)
            $hooks->invoke("hook_dom_add_mx_domain", array($id));
        if ($isslave) {
            $hooks->invoke("hook_dom_add_slave_domain", array($id, $slavedom));
        }
        return true;
    }

fufroma's avatar
fufroma committed
807
808
809
    /**
     * @param string $domain
     */
alban's avatar
alban committed
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
    function create_default_subdomains($domain, $target_domain = "") {
        global $db, $err;
        $err->log("dom", "create_default_subdomains", $domain);
        $query = "SELECT sub, domain_type, domain_type_parameter FROM default_subdomains WHERE (concerned = 'SLAVE' or concerned = 'BOTH') and enabled=1;";
        if (empty($target_domain)) {
            $query = "SELECT sub, domain_type, domain_type_parameter FROM default_subdomains WHERE (concerned = 'MAIN' or concerned = 'BOTH') and enabled=1;";
        }
        $domaindir = $this->domdefaultdir($domain);
        $db->query($query);
        $jj = array();
        while ($db->next_record()) {
            $jj[] = Array("domain_type_parameter" => $db->f('domain_type_parameter'), "sub" => $db->f('sub'), "domain_type" => $db->f('domain_type'));
        }
        $src_var = array("%%SUB%%", "%%DOMAIN%%", "%%DOMAINDIR%%", "%%TARGETDOM%%");
        foreach ($jj as $j) {
            $trg_var = array($j['sub'], $domain, $domaindir, $target_domain);
            $domain_type_parameter = str_ireplace($src_var, $trg_var, $j['domain_type_parameter']);
            $this->set_sub_domain($domain, $j['sub'], strtolower($j['domain_type']), $domain_type_parameter);
        }
    }

Alan Garcia's avatar
Alan Garcia committed
831
832
833
    /**
     * @param string $domain
     */
alban's avatar
alban committed
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
    function domdefaultdir($domain) {
        global $bro, $cuid;
        $dest_root = $bro->get_userid_root($cuid);
        #  return $dest_root."/www/".$this->domshort($domain);
        return "/www/" . $this->domshort($domain);
    }

    function dump_axfr($domain, $ns = 'localhost') {
        exec('/usr/bin/dig AXFR "' . escapeshellcmd($domain) . '" @"' . escapeshellcmd($ns) . '"', $axfr);
        return $axfr;
    }

    function lst_default_subdomains() {
        global $db, $err;
        $err->log("dom", "lst_default_subdomains");
        $c = array();
        $db->query("select * from default_subdomains;");

        while ($db->next_record()) {
            $c[] = array('id' => $db->f('id'),
                'sub' => $db->f('sub'),
                'domain_type' => $db->f('domain_type'),
                'domain_type_parameter' => $db->f('domain_type_parameter'),
                'concerned' => $db->f('concerned'),
                'enabled' => $db->f('enabled')
                    );
        }

        return $c;
    }

    function update_default_subdomains($arr) {
        global $err;
        $err->log("dom", "update_default_subdomains");
        $ok = true;
        foreach ($arr as $a) {
            if (!isset($a['id']))
                $a['id'] = null;
            if (!empty($a['sub']) || !empty($a['domain_type_parameter'])) {

                if (!isset($a['enabled']))
                    $a['enabled'] = 0;
                if (!$this->update_one_default($a['domain_type'], $a['sub'], $a['domain_type_parameter'], $a['concerned'], $a['enabled'], $a['id'])) {
                    $ok = false;
                }
            }
        }
        return $ok;
    }

    function update_one_default($domain_type, $sub, $domain_type_parameter, $concerned, $enabled, $id = null) {
        global $db, $err;
        $err->log("dom", "update_one_default");

        if ($id == null)
            $db->query("INSERT INTO default_subdomains values ('','" . addslashes($sub) . "','" . addslashes($domain_type) . "','" . addslashes($domain_type_parameter) . "','" . addslashes($concerned) . "','" . addslashes($enabled) . "');");
        else
            $db->query("UPDATE default_subdomains set sub='" . addslashes($sub) . "', domain_type='" . addslashes($domain_type) . "',domain_type_parameter='" . addslashes($domain_type_parameter) . "',concerned='" . addslashes($concerned) . "',enabled='" . addslashes($enabled) . "' where id=" . addslashes($id) . ";");
        return true;
        //update
    }

    function del_default_type($id) {
        global $err, $db;
        $err->log("dom", "del_default_type");

        if (!$db->query("delete from default_subdomains where id=$id;")) {
            $err->raise("dom", _("Could not delete default type"));
            return false;
        }

        return true;
    }

    /* ----------------------------------------------------------------- */

    /**
Alan Garcia's avatar
Alan Garcia committed
911
     * Retourne les entrées DNS du domaine $domain issues du WHOIS.
alban's avatar
alban committed
912
913
     *
     * Cette fonction effectue un appel WHOIS($domain) sur Internet,
Alan Garcia's avatar
Alan Garcia committed
914
     * et extrait du whois les serveurs DNS du domaine demandé. En fonction
alban's avatar
alban committed
915
     * du TLD, on sait (ou pas) faire le whois correspondant.
Alan Garcia's avatar
Alan Garcia committed
916
     * Actuellement, les tld suivants sont supportés :
alban's avatar
alban committed
917
918
919
     * .com .net .org .be .info .ca .cx .fr .biz .name
     *
     * @param string $domain Domaine fqdn dont on souhaite les serveurs DNS
Alan Garcia's avatar
Alan Garcia committed
920
921
     * @return array Retourne un tableau indexé avec les NOMS fqdn des dns
     *   du domaine demandé. Retourne FALSE si une erreur s'est produite.
alban's avatar
alban committed
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
     *
     */
    function whois($domain) {
        global $db, $err;
        $err->log("dom", "whois", $domain);
        // pour ajouter un nouveau TLD, utiliser le code ci-dessous.
        //  echo "whois : $domain<br />";
        preg_match("#.*\.([^\.]*)#", $domain, $out);
        $ext = $out[1];
        // pour ajouter un nouveau TLD, utiliser le code ci-dessous.
        //  echo "ext: $ext<br />";

        $serveur = "";
        if (($fp = @fsockopen("whois.iana.org", 43)) > 0) {
            fputs($fp, "$domain\r\n");
            $found = false;
            $state = 0;
            while (!feof($fp)) {
                $ligne = fgets($fp, 128);
                if (preg_match('#^whois:#', $ligne)) {
                    $serveur = preg_replace('/whois:\ */', '', $ligne, 1);
                }
            }
        }
        $serveur = str_replace(array(" ", "\n"), "", $serveur);

        $egal = "";
        switch ($ext) {
            case "net":
                $egal = "=";
                break;
            case "name":
                $egal = "domain = ";
                break;
        }
alban's avatar
alban committed
957
        $serveurList = array();
alban's avatar
alban committed
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
        // pour ajouter un nouveau TLD, utiliser le code ci-dessous.
        //  echo "serveur : $serveur <br />";
        if (($fp = @fsockopen($serveur, 43)) > 0) {
            fputs($fp, "$egal$domain\r\n");
            $found = false;
            $state = 0;
            while (!feof($fp)) {
                $ligne = fgets($fp, 128);
                // pour ajouter un nouveau TLD, utiliser le code ci-dessous.
                //  echo "| $ligne<br />";
                switch ($ext) {
                    case "org":
                    case "com":
                    case "net":
                    case "info":
                    case "biz":
                    case "name":
                    case "cc":
                        if (preg_match("#Name Server:#", $ligne)) {
                            $found = true;
                            $tmp = strtolower(str_replace(chr(10), "", str_replace(chr(13), "", str_replace(" ", "", str_replace("Name Server:", "", $ligne)))));
                            if ($tmp)
alban's avatar
alban committed
980
                                $serveurList[] = $tmp;
alban's avatar
alban committed
981
982
983
984
985
986
987
                        }
                        break;
                    case "cx":
                        $ligne = str_replace(chr(10), "", str_replace(chr(13), "", str_replace(" ", "", $ligne)));
                        if ($ligne == "" && $state == 1)
                            $state = 2;
                        if ($state == 1)
alban's avatar
alban committed
988
                            $serveurList[] = strtolower($ligne);
alban's avatar
alban committed
989
990
991
992
993
994
995
996
997
998
999
                        if ($ligne == "Nameservers:" && $state == 0) {
                            $state = 1;
                            $found = true;
                        }
                        break;
                    case "eu":
                    case "be":
                        $ligne = preg_replace("/^ *([^ ]*) \(.*\)$/", "\\1", trim($ligne));
                        if ($found)
                            $tmp = trim($ligne);
                        if ($tmp)
alban's avatar
alban committed
1000
                            $serveurList[] = $tmp;
alban's avatar
alban committed
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
                        if ($ligne == "Nameservers:") {
                            $state = 1;
                            $found = true;
                        }
                        break;
                    case "im":
                        if (preg_match('/Name Server:/', $ligne)) {
                            $found = true;
                            // weird regexp (trailing garbage after name server), but I could not make it work otherwise
                            $tmp = strtolower(preg_replace('/Name Server: ([^ ]+)\..$/', "\\1", $ligne));
                            $tmp = preg_replace('/[^-_a-z0-9\.]/', '', $tmp);
                            if ($tmp)
alban's avatar
alban committed
1013
                                $serveurList[] = $tmp;
alban's avatar
alban committed
1014
1015
1016
1017
1018
1019
1020
                        }
                        break;
                    case "it":
                        if (preg_match("#nserver:#", $ligne)) {
                            $found = true;
                            $tmp = strtolower(preg_replace("/nserver:\s*[^ ]*\s*([^\s]*)$/", "\\1", $ligne));
                            if ($tmp)
alban's avatar
alban committed
1021
                                $serveurList[] = $tmp;
alban's avatar
alban committed
1022
1023
1024
1025
1026
1027
1028
1029
                        }
                        break;
                    case "fr":
                    case "re":
                        if (preg_match("#nserver:#", $ligne)) {
                            $found = true;
                            $tmp = strtolower(preg_replace("#nserver:\s*([^\s]*)\s*.*$#", "\\1", $ligne));
                            if ($tmp)
alban's avatar
alban committed
1030
                                $serveurList[] = $tmp;
alban's avatar
alban committed
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
                        }
                        break;
                    case "ca":
                    case "ws";
                        if (preg_match('#Name servers#', $ligne)) {
                            // found the server
                            $state = 1;
                        } elseif ($state) {
                            if (preg_match('#^[^%]#', $ligne) && $ligne = preg_replace('#[[:space:]]#', "", $ligne)) {
                                // first non-whitespace line is considered to be the nameservers themselves
                                $found = true;
alban's avatar
alban committed
1042
                                $serveurList[] = $ligne;
alban's avatar
alban committed
1043
1044
1045
1046
1047
1048
                            }
                        }
                        break;
                    case "coop":
                        if (preg_match('#Host Name:\s*([^\s]+)#', $ligne, $matches)) {
                            $found = true;
alban's avatar
alban committed
1049
                            $serveurList[] = $matches[1];
alban's avatar
alban committed
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
                        }
                } // switch
            } // while
            fclose($fp);
        } else {
            $err->raise("dom", _("The Whois database is unavailable, please try again later"));
            return false;
        }

        if ($found) {
alban's avatar
alban committed
1060
            return $serveurList;
alban's avatar
alban committed
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
        } else {
            $err->raise("dom", _("The domain cannot be found in the Whois database"));
            return false;
        }
    }

// whois


    /* ----------------------------------------------------------------- */

    /**
Alan Garcia's avatar
Alan Garcia committed
1073
1074
     *  vérifie la presence d'un champs mx valide sur un serveur DNS
     * $domaine est le domaine dont on veux véririfer les MX
alban's avatar
alban committed
1075
     * $ref_domaine est le domaine avec lequel on veux comparer les MX
Alan Garcia's avatar
Alan Garcia committed
1076
     *              si $ref_domaine == '', on prend les MX par default
alban's avatar
alban committed
1077
     *
fufroma's avatar
fufroma committed
1078
     * @param string $domaine
alban's avatar
alban committed
1079
     */
Alan Garcia's avatar
Alan Garcia committed
1080
    function checkmx($domaine, $ref_domain = '') {
alban's avatar
alban committed
1081
1082
        global $L_DEFAULT_MX, $L_DEFAULT_SECONDARY_MX;

Alan Garcia's avatar
Alan Garcia committed
1083
        if (!empty($ref_domain)) {
alban's avatar
alban committed
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
            getmxrr($ref_domain, $ref_mx);
        } else {
            $ref_mx = array($L_DEFAULT_MX, $L_DEFAULT_SECONDARY_MX);
        }

        if (empty($ref_mx)) {
            // No reference mx
            return 3;
        }

Alan Garcia's avatar
Alan Garcia committed
1094
        //récupére les champs mx
alban's avatar
alban committed
1095
        if (!getmxrr($domaine, $mxhosts)) {
Alan Garcia's avatar
Alan Garcia committed
1096
            //aucun héte mx spécifié
alban's avatar
alban committed
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
            return 1;
        }

        if (empty($mxhosts)) {
            // no mx on the target domaine
            return 1;
        }

        $intersect = array_intersect($mxhosts, $ref_mx);

        if (empty($intersect)) {
            // no shared mx server
            return 2;
        }

        return 0;
    }

//checkmx


    /* ----------------------------------------------------------------- */

    /**
     *  retourne TOUTES les infos d'un domaine
     *
     * @param string $dom Domaine dont on souhaite les informations
     * @return array Retourne toutes les infos du domaine sous la forme d'un
     * tableau associatif comme suit :<br /><pre>
     *  $r["name"] =  Nom fqdn
     *  $r["dns"]  =  Gestion du dns ou pas ?
     *  $r["mx"]   =  Valeur du champs MX si "dns"=true
     *  $r["mail"] =  Heberge-t-on le mail ou pas ? (si "dns"=false)
     *  $r["nsub"] =  Nombre de sous-domaines
     *  $r["sub"]  =  tableau associatif des sous-domaines
     *  $r["sub"][0-(nsub-1)]["name"] = nom du sous-domaine (NON-complet)
     *  $r["sub"][0-(nsub-1)]["dest"] = Destination (url, ip, local ...)
     *  $r["sub"][0-(nsub-1)]["type"] = Type (0-n) de la redirection.
     *  </pre>
     *  Retourne FALSE si une erreur s'est produite.
     *
     */
    function get_domain_all($dom) {
        global $db, $err, $cuid;
        $err->log("dom", "get_domain_all", $dom);
        // Locked ?
        if (!$this->islocked) {
            $err->raise("dom", _("--- Program error --- No lock on the domains!"));
            return false;
        }
        $t = checkfqdn($dom);
        if ($t) {
            $err->raise("dom", _("The domain name is syntaxically incorrect"));
            return false;
        }
        $r = array();
        $r["name"] = $dom;
        $db->query("SELECT * FROM domaines WHERE compte='$cuid' AND domaine='$dom'");
        if ($db->num_rows() == 0) {
            $err->raise("dom", sprintf(_("Domain '%s' not found"), $dom));
            return false;
        }
        $db->next_record();
        $r["id"] = $db->Record["id"];
        $r["dns"] = $db->Record["gesdns"];
        $r["dns_action"] = $db->Record["dns_action"];
        $r["dns_result"] = $db->Record["dns_result"];
        $r["mail"] = $db->Record["gesmx"];
        $r["zonettl"] = $db->Record["zonettl"];
        $r['noerase'] = $db->Record['noerase'];
        $db->free();
        $db->query("SELECT COUNT(*) AS cnt FROM sub_domaines WHERE compte='$cuid' AND domaine='$dom'");
        $db->next_record();
        $r["nsub"] = $db->Record["cnt"];
        $db->free();
        #$db->query("SELECT sd.*, dt.description AS type_desc, dt.only_dns FROM sub_domaines sd, domaines_type dt WHERE compte='$cuid' AND domaine='$dom' AND UPPER(dt.name)=UPPER(sd.type) ORDER BY sd.sub,sd.type");
        $db->query("SELECT sd.*, dt.description AS type_desc, dt.only_dns FROM sub_domaines sd LEFT JOIN domaines_type dt on  UPPER(dt.name)=UPPER(sd.type) WHERE compte='$cuid' AND domaine='$dom'  ORDER BY sd.sub,sd.type ;");
        // Pas de webmail, on le cochera si on le trouve.
        $r["sub"] = array();
        for ($i = 0; $i < $r["nsub"]; $i++) {
            $db->next_record();
            $r["sub"][$i] = array();
            $r["sub"][$i]["id"] = $db->Record["id"];
            $r["sub"][$i]["name"] = $db->Record["sub"];
            $r["sub"][$i]["dest"] = $db->Record["valeur"];
            $r["sub"][$i]["type"] = $db->Record["type"];
            $r["sub"][$i]["enable"] = $db->Record["enable"];
            $r["sub"][$i]["type_desc"] = $db->Record["type_desc"];
            $r["sub"][$i]["only_dns"] = $db->Record["only_dns"];
            $r["sub"][$i]["web_action"] = $db->Record["web_action"];
            $r["sub"][$i]["fqdn"] = ((!empty($r["sub"][$i]["name"])) ? $r["sub"][$i]["name"] . "." : "") . $r["name"];
        }
        $db->free();
        return $r;
    }

// get_domain_all


    /* ----------------------------------------------------------------- */

    /**
     * Retourne TOUTES les infos d'un sous domaine du compte courant.
     *
     * @param integer sub_domain_id id du subdomain
fufroma's avatar
fufroma committed
1202
     * @return array Retourne un tableau associatif contenant les
Alan Garcia's avatar
Alan Garcia committed
1203
     *  informations du sous-domaine demandé.<pre>
alban's avatar
alban committed
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
     *  $r["name"]= nom du sous-domaine (NON-complet)
     *  $r["dest"]= Destination (url, ip, local ...)
     *  </pre>
     *  $r["type"]= Type (0-n) de la redirection.
     *  Retourne FALSE si une erreur s'est produite.
     */
    function get_sub_domain_all($sub_domain_id) {
        global $db, $err, $cuid;
        $err->log("dom", "get_sub_domain_all", $sub_domain_id);
        // Locked ?
        if (!$this->islocked) {
            $err->raise("dom", _("--- Program error --- No lock on the domains!"));
            return false;
        }
        $db->query("select sd.*, dt.description as type_desc, dt.only_dns from sub_domaines sd, domaines_type dt where compte='$cuid' and sd.id='$sub_domain_id'  and upper(dt.name)=upper(sd.type);");
        if ($db->num_rows() == 0) {
            $err->raise("dom", _("The sub-domain does not exist"));
            return false;
        }
        $db->next_record();
        $r = array();
        $r["id"] = $db->Record["id"];
        $r["name"] = $db->Record["sub"];
        $r["domain"] = $db->Record["domaine"];
        $r["dest"] = $db->Record["valeur"];
        $r["enable"] = $db->Record["enable"];
        $r["type"] = $db->Record["type"];
        $r["type_desc"] = $db->Record["type_desc"];
        $r["only_dns"] = $db->Record["only_dns"];
        $r["web_action"] = $db->Record["web_action"];
        $db->free();
        return $r;
    }

// get_sub_domain_all

fufroma's avatar
fufroma committed
1240
1241
1242
1243
    /**
     * @param integer $type
     * @param string $value
     */
alban's avatar
alban committed
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
    function check_type_value($type, $value) {
        global $db, $err, $cuid;

        // check the type we can have in domaines_type.target
        switch ($this->domains_type_target_values($type)) {
            case 'NONE':
                if (empty($value) or is_null($value)) {
                    return true;
                }
                break;
            case 'URL':
                if ($value == strval($value)) {
                    if (filter_var($value, FILTER_VALIDATE_URL)) {
                        return true;
                    } else {
                        $err->raise("dom", _("invalid url"));
                        return false;
                    }
                }
                break;
            case 'DIRECTORY':
                if (substr($value, 0, 1) != "/") {
                    $value = "/" . $value;
                }
                if (!checkuserpath($value)) {
                    $err->raise("dom", _("The folder you entered is incorrect or does not exist"));
                    return false;
                }
                return true;
                break;
            case 'IP':
                if (checkip($value)) {
                    return true;
                } else {
                    $err->raise("dom", _("The ip address is invalid"));
                    return false;
                }
                break;
            case 'IPV6':
                if (checkipv6($value)) {
                    return true;
                } else {
                    $err->raise("dom", _("The ip address is invalid"));
                    return false;
                }
                break;
            case 'DOMAIN':
                if (checkcname($value)) {
                    return true;
                } else {
                    $err->raise("dom", _("The name you entered is incorrect"));
                    return false;
                }
                break;
            case 'TXT':
                if ($value == strval($value)) {
                    return true;
                } else {
                    $err->raise("dom", _("The TXT value you entered is incorrect"));
                    return false;
                }
                break;
            default:
                $err->raise("dom", _("Invalid domain type selected, please check"));
                return false;
                break;
        }
Alan Garcia's avatar
Alan Garcia committed
1311
        return false;
alban's avatar
alban committed
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
    }

//check_type_value


    /* ----------------------------------------------------------------- */

    /**
     * Check the compatibility of the POSTed parameters with the chosen
     * domain type
     *
     * @param string $dom FQDN of the domain name
     * @param string $sub SUBdomain 
     * @return boolean tell you if the subdomain can be installed there 
     */
    function can_create_subdomain($dom, $sub, $type, $sub_domain_id = 'null') {
        global $db, $err, $cuid;
        $err->log("dom", "can_create_subdomain", $dom . "/" . $sub);

        // Get the compatibility list for this domain type
        $db->query("select upper(compatibility) as compatibility from domaines_type where upper(name)=upper('$type');");
        if (!$db->next_record())
            return false;
        $compatibility_lst = explode(",", $db->f('compatibility'));

        // Get the list of type of subdomains already here who have the same name
        $db->query("select * from sub_domaines where sub='$sub' and domaine='$dom' and not id = $sub_domain_id and web_action != 'DELETE' and enabled not in ('DISABLED', 'DISABLE') ");
        #$db->query("select * from sub_domaines where sub='$sub' and domaine='$dom';");
        while ($db->next_record()) {
            // And if there is a domain with a incompatible type, return false
            if (!in_array(strtoupper($db->f('type')), $compatibility_lst))
                return false;
        }

        // All is right, go ! Create ur domain !
        return true;
    }

    /* ----------------------------------------------------------------- */

    /**
Alan Garcia's avatar
Alan Garcia committed
1353
     * Modifier les information du sous-domaine demandé.
alban's avatar
alban committed
1354
     *
Alan Garcia's avatar
Alan Garcia committed
1355
1356
     * <b>Note</b> : si le sous-domaine $sub.$dom n'existe pas, il est créé.<br />
     * <b>Note : TODO</b> : vérification de concordance de $dest<br />
alban's avatar
alban committed
1357
1358
     *
     * @param string $dom Domaine dont on souhaite modifier/ajouter un sous domaine
fufroma's avatar
fufroma committed
1359
     * @param string $sub Sous domaine é modifier / créer
alban's avatar
alban committed
1360
     * @param integer $type Type de sous-domaine (local, ip, url ...)
Alan Garcia's avatar
Alan Garcia committed
1361
     * @param string $dest Destination du sous-domaine, dépend de la valeur
alban's avatar
alban committed
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
     *  de $type (url, ip, dossier...)
     * @return boolean Retourne FALSE si une erreur s'est produite, TRUE sinon.
     */
    function set_sub_domain($dom, $sub, $type, $dest, $sub_domain_id = null) {
        global $db, $err, $cuid, $bro;
        $err->log("dom", "set_sub_domain", $dom . "/" . $sub . "/" . $type . "/" . $dest);
        // Locked ?
        if (!$this->islocked) {
            $err->raise("dom", _("--- Program error --- No lock on the domains!"));
            return false;
        }
        $dest = trim($dest);
        $sub = trim(trim($sub), ".");
        $dom = strtolower($dom);
        $sub = strtolower($sub);

        //    if (!(($sub == '*') || ($sub=="") || (preg_match('/([a-z0-9][\.\-a-z0-9]*)?[a-z0-9]/', $sub)))) {
        $fqdn = checkfqdn($sub);
        // Special cases : * (all subdomains at once) and '' empty subdomain are allowed.
        if (($sub != '*' && $sub != '') && !($fqdn == 0 || $fqdn == 4)) {
            $err->raise("dom", _("There is some forbidden characters in the sub domain (only A-Z 0-9 and - are allowed)"));
            return false;
        }

        if (!$this->check_type_value($type, $dest)) {
Alan Garcia's avatar
Alan Garcia committed
1387
            //plutot verifier si la chaine d'erreur est vide avant de raise sinon sa veut dire que l(erruer est deja remonté
alban's avatar
alban committed
1388
1389
1390
1391
            #$err->raise("dom",_("Invalid domain type selected, please check"));
            return false;
        }

Alan Garcia's avatar
Alan Garcia committed
1392
        // On a épuré $dir des problémes eventuels ... On est en DESSOUS du dossier de l'utilisateur.
alban's avatar
alban committed
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
        if ($t = checkfqdn($dom)) {
            $err->raise("dom", _("The domain name is syntaxically incorrect"));
            return false;
        }

        if (!$this->can_create_subdomain($dom, $sub, $type, $sub_domain_id)) {
            $err->raise("dom", _("The parameters for this subdomain and domain type are invalid. Please check for subdomain entries incompatibility"));
            return false;
        }

        if (!is_null($sub_domain_id)) { // It's not a creation, it's an edit. Delete the old one
            $this->del_sub_domain($sub_domain_id);
        }

        // Re-create the one we want
        if (!$db->query("replace into sub_domaines (compte,domaine,sub,valeur,type,web_action) values ('$cuid','$dom','$sub','$dest','$type','UPDATE');")) {
            echo "query failed: " . $db->Error;
            return false;
        }

        // Create TMP dir and TARGET dir if needed by the domains_type
        $dest_root = $bro->get_userid_root($cuid);
        $domshort = $this->domshort($dom, $sub);
        $db->query("select create_tmpdir, create_targetdir from domaines_type where name = '$type';");
        $db->next_record();
        if ($db->f('create_tmpdir')) {
            if (!is_dir($dest_root . "/tmp")) {
                if (!@mkdir($dest_root . "/tmp", 0777, true)) {
                    $err->raise("dom", _("Cannot write to the destination folder"));
                }
            }
        }
        if ($db->f('create_targetdir')) {
            $dirr = $dest_root . $dest;
            $dirr = str_replace('//', '/', $dirr);

            if (!is_dir($dirr)) {
                $old = umask(0);
                if (!@mkdir($dirr, 0770, true)) {
                    $err->raise("dom", _("Cannot write to the destination folder"));
                }
                umask($old);
            }
        }

        // Tell to update the DNS file
        $db->query("update domaines set dns_action='UPDATE' where domaine='$dom';");

        return true;
    }

// set_sub_domain


    /* ----------------------------------------------------------------- */

    /**
Alan Garcia's avatar
Alan Garcia committed
1450
     *  Supprime le sous-domaine demandé
alban's avatar
alban committed
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
     *
     * @return boolean Retourne FALSE si une erreur s'est produite, TRUE sinon.
     *
     */
    function del_sub_domain($sub_domain_id) {
        global $db, $err, $cuid;
        $err->log("dom", "del_sub_domain", $sub_domain_id);
        // Locked ?
        if (!$this->islocked) {
            $err->raise("dom", _("--- Program error --- No lock on the domains!"));
            return false;
        }
        if (!$r = $this->get_sub_domain_all($sub_domain_id)) {
            $err->raise("dom", _("The sub-domain does not exist"));
            return false;
        } else {
            $db->query("update sub_domaines set web_action='DELETE' where id='$sub_domain_id'; ");
            $db->query("update domaines set dns_action='UPDATE' where domaine='" . $r['domain'] . "';");
        }
        return true;
    }

// del_sub_domain

fufroma's avatar
fufroma committed
1475
1476
1477
    /**
     * @param integer $dom_id
     */
alban's avatar
alban committed
1478
1479
1480
1481
1482
1483
1484
    function set_ttl($dom_id, $ttl) {
        global $err;
        $err->log("dom", "set_ttl", "$dom_id / $ttl");
        $this->lock();
        $domaine = $this->get_domain_byid($dom_id);
        $d = $this->get_domain_all($domaine);

Alan Garcia's avatar
Alan Garcia committed
1485
        $j = $this->edit_domain($domaine, $d['dns'], $d['mail'], false, $ttl);
alban's avatar
alban committed
1486
1487
1488
1489
1490
1491
1492
        $this->unlock();
        return $j;
    }

    /* ----------------------------------------------------------------- */

    /**
Alan Garcia's avatar
Alan Garcia committed
1493
     * Modifie les information du domaine précisé.
alban's avatar
alban committed
1494
1495
     *
     * @param string $dom Domaine du compte courant que l'on souhaite modifier
Alan Garcia's avatar
Alan Garcia committed
1496
1497
     * @param boolean $dns Vaut 1 ou 0 pour héberger ou pas le DNS du domaine
     * @param boolean $gesmx Héberge-t-on le emails du domaines sur ce serveur ?
alban's avatar
alban committed
1498
1499
1500
1501
1502
1503
     * @param boolean $force Faut-il passer les checks DNS ou MX ? (admin only)
     * @return boolean appelle $mail->add_dom ou $ma->del_dom si besoin, en
     *  fonction du champs MX. Retourne FALSE si une erreur s'est produite,
     *  TRUE sinon.
     *
     */
fufroma's avatar
fufroma committed
1504
    function edit_domain($dom, $dns, $gesmx, $force = false, $ttl = 86400) {
alban's avatar
alban committed
1505
1506
1507
1508
1509
1510
1511
        global $db, $err, $L_MX, $classes, $cuid, $hooks;
        $err->log("dom", "edit_domain", $dom . "/" . $dns . "/" . $gesmx);
        // Locked ?
        if (!$this->islocked && !$force) {
            $err->raise("dom", _("--- Program error --- No lock on the domains!"));
            return false;
        }
Alan Garcia's avatar
Alan Garcia committed
1512
        if ($dns == true && !$force) {
alban's avatar
alban committed
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
            $this->dns = $this->whois($dom);
            $v = checkhostallow($dom, $this->dns);
            if ($v == -1) {
                $err->raise("dom", _("The last member of the domain name is incorrect or cannot be hosted in that server"));
                return false;
            }
            if ($dns && $v == -2) {
                $err->raise("dom", _("The domain cannot be found in the Whois database"));
                return false;
            }
            if ($dns && $v == -3) {
                $err->raise("dom", _("The DNS of this domain do not match the server's DNS. Please change your domain's DNS before you install it again"));
                return false;
            }
        }

        # Can't have ttl == 0. There is also a check in function_dns
        if ($ttl == 0) {
            $ttl = 86400;
        }

        $t = checkfqdn($dom);
        if ($t) {
            $err->raise("dom", _("The domain name is syntaxically incorrect"));
            return false;
        }
        if (!$r = $this->get_domain_all($dom)) {
            // Le domaine n'existe pas, Failure
            $err->raise("dom", _("The domain name %s does not exist"), $dom);
            return false;
        }
        if ($dns != "1")
            $dns = "0";
Alan Garcia's avatar
Alan Garcia committed
1546
        // On vérifie que des modifications ont bien eu lieu :)
alban's avatar
alban committed
1547
1548
        if ($r["dns"] == $dns && $r["mail"] == $gesmx && $r["zonettl"] == $ttl) {
            $err->raise("dom", _("No change has been requested..."));
Steven Mondji-Lerider's avatar
Steven Mondji-Lerider committed
1549
            return true;
alban's avatar
alban committed
1550
1551
        }

Alan Garcia's avatar
Alan Garcia committed
1552
        //si gestion mx uniquement, vérification du dns externe
alban's avatar
alban committed
1553
1554
1555
1556
1557
1558
1559
        if ($dns == "0" && $gesmx == "1" && !$force) {
            $vmx = $this->checkmx($dom);
            if ($vmx == 1) {
                $err->raise("dom", _("There is no MX record pointing to this server, and you are asking us to host the mail here. Make sure to update your MX entries or no mail will be received"));
            }

            if ($vmx == 2) {
Alan Garcia's avatar
Alan Garcia committed
1560
                // Serveur non spécifié parmi les champx mx
alban's avatar
alban committed
1561
1562
1563
1564
1565
1566
1567
1568
                $err->raise("dom", _("There is no MX record pointing to this server, and you are asking us to host the mail here. Make sure to update your MX entries or no mail will be received"));
            }
        }

        if ($gesmx && !$r["mail"]) {
            $hooks->invoke("hook_dom_add_mx_domain", array($r["id"]));
        }

Alan Garcia's avatar
Alan Garcia committed
1569
        if (!$gesmx && $r["mail"]) { // on a dissocié le MX : on détruit donc l'entree dans LDAP
alban's avatar
alban committed
1570
1571
1572
1573
            $hooks->invoke("hook_dom_del_mx_domain", array($r["id"]));
        }

        $db->query("UPDATE domaines SET gesdns='$dns', gesmx='$gesmx', zonettl='$ttl' WHERE domaine='$dom'");
Alan Garcia's avatar
Alan Garcia committed
1574
        $this->set_dns_action($dom, 'UPDATE');
alban's avatar
alban committed
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612

        return true;
    }

// edit_domain


    /*     * ************************* */
    /*  Slave dns ip managment  */
    /*     * ************************* */


    /* ----------------------------------------------------------------- */

    /** Return the list of ip addresses and classes that are allowed access to domain list
     * through AXFR Transfers from the bind server.
     */
    function enum_slave_ip() {
        global $db, $err;
        $db->query("SELECT * FROM slaveip;");
        if (!$db->next_record()) {
            return false;
        }
        $res = array();
        do {
            $res[] = $db->Record;
        } while ($db->next_record());
        return $res;
    }

    /* ----------------------------------------------------------------- */

    /** Add an ip address (or a ip class) to the list of allowed slave ip access list.
     */
    function add_slave_ip($ip, $class = "32") {
        global $db, $err;
        if (!checkip($ip)) {
            $err->raise("dom", _("The IP address you entered is incorrect"));
Steven Mondji-Lerider's avatar
Steven Mondji-Lerider committed
1613
1614
            return false;
        }
alban's avatar
alban committed
1615
1616
1617
1618
1619
1620
1621
        $class = intval($class);
        if ($class < 8 || $class > 32)
            $class = 32;
        $db->query("SELECT * FROM slaveip WHERE ip='$ip' AND class='$class';");
        if ($db->next_record()) {
            $err->raise("err", _("The requested domain is forbidden in this server, please contact the administrator"));
            return false;
1622
        }
alban's avatar
alban committed
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
        $db->query("INSERT INTO slaveip (ip,class) VALUES ('$ip','$class');");
        $f = fopen(SLAVE_FLAG, "w");
        fputs($f, "yopla");
        fclose($f);
        return true;
    }

    /* ----------------------------------------------------------------- */

    /** Remove an ip address (or a ip class) from the list of allowed slave ip access list.
     */
    function del_slave_ip($ip) {
        global $db, $err;
        if (!checkip($ip)) {
            $err->raise("dom", _("The IP address you entered is incorrect"));
            return false;
1639
        }
alban's avatar
alban committed
1640
1641
1642
1643
        $db->query("DELETE FROM slaveip WHERE ip='$ip'");
        $f = fopen(SLAVE_FLAG, "w");
        fputs($f, "yopla");
        fclose($f);
1644
        return true;
alban's avatar
alban committed
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
    }

    /* ----------------------------------------------------------------- */

    /** Check for a slave account
     */
    function check_slave_account($login, $pass) {
        global $db, $err;
        $db->query("SELECT * FROM slaveaccount WHERE login='$login' AND pass='$pass';");
        if ($db->next_record()) {
            return true;
        }
1657
        return false;
1658
    }
1659

alban's avatar
alban committed
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
    /* ----------------------------------------------------------------- */

    /** Out (echo) the complete hosted domain list : 
     */
    function echo_domain_list($integrity = false) {
        global $db, $err;
        $db->query("SELECT domaine FROM domaines WHERE gesdns=1 ORDER BY domaine");
        $tt = "";
        while ($db->next_record()) {
            #echo $db->f("domaine")."\n";
            $tt.=$db->f("domaine") . "\n";
        }
        echo $tt;
        if ($integrity) {
            echo md5($tt) . "\n";
        }
        return true;
    }

    /* ----------------------------------------------------------------- */

    /** Returns the complete hosted domain list : 
     */
    function get_domain_list($uid = -1) {
        global $db, $err;
        $uid = intval($uid);
        $res = array();
Alan Garcia's avatar
Alan Garcia committed
1687
        $sql = "";
alban's avatar
alban committed
1688
        if ($uid != -1) {
Alan Garcia's avatar
Alan Garcia committed
1689
            $sql .= " AND compte='$uid' ";
alban's avatar
alban committed
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
        }
        $db->query("SELECT domaine FROM domaines WHERE gesdns=1 $sql ORDER BY domaine");
        while ($db->next_record()) {
            $res[] = $db->f("domaine");
        }
        return $res;
    }

    /**
     * 
     * @return array
     */
    function get_domain_all_summary() {
        global $db, $err;
        $res = array();
        $db->query("SELECT domaine, gesdns, gesmx, dns_action, zonettl FROM domaines ORDER BY domaine");
        while ($db->next_record()) {
            $res[$db->f("domaine")] = array(
                "gesdns" => $db->f("gesdns"),
                "gesmx" => $db->f("gesmx"),
                "dns_action" => $db->f("dns_action"),
                "zonettl" => $db->f("zonettl"),
            );
        }
        return $res;
    }

    /* ----------------------------------------------------------------- */

    /** Returns the name of a domain for the current user, from it's domain_id
     * @param $dom_id integer the domain_id to search for
     * @return string the domain name, or false with an error raised.
     */
    function get_domain_byid($dom_id) {
        global $db, $err, $cuid;
        $dom_id = intval($dom_id);
        $db->query("SELECT domaine FROM domaines WHERE id=$dom_id AND compte=$cuid;");
        if ($db->next_record()) {
            $domain = $db->f("domaine");
            if (!$domain) {
                $err->raise("dom", _("This domain is not installed in your account"));
                return false;
            } else {
                return $domain;
            }
        } else {
            $err->raise("dom", _("This domain is not installed in your account"));
            return false;
        }
    }

    /* ----------------------------------------------------------------- */

    /** Returns the id of a domain for the current user, from it's domain name
     * @param $domain string the domain name to search for
     * @return integer the domain id, or false with an error raised.
     */
    function get_domain_byname($domain) {
        global $db, $err, $cuid;
        $domain = trim($domain);
        $db->query("SELECT id FROM domaines WHERE domaine='" . addslashes($domain) . "' AND compte=$cuid;");
        if ($db->next_record()) {
            $id = $db->f("id");
            if (!$id) {
                $err->raise("dom", _("This domain is not installed in your account"));
                return false;
            } else {
                return $id;
            }
        } else {
            $err->raise("dom", _("This domain is not installed in your account"));
            return false;
        }
    }

    /* ----------------------------------------------------------------- */

    /** Count all domains, for all users
     */
    function count_domains_all() {
        global $db, $err, $cuid;
        $db->query("SELECT COUNT(*) AS count FROM domaines;");
        if ($db->next_record()) {
            return $db->f('count');
        } else {
            return 0;
        }
    }

    /* ----------------------------------------------------------------- */

    /** Return the list of allowed slave accounts 
     */
    function enum_slave_account() {
        global $db, $err;
        $db->query("SELECT * FROM slaveaccount;");
        $res = array();
        while ($db->next_record()) {
            $res[] = $db->Record;
        }
        if (!count($res))
            return false;
        return $res;
    }

    /* ----------------------------------------------------------------- */

    /** Add a slave account that will be allowed to access the domain list
     */
    function add_slave_account($login, $pass) {
        global $db, $err;
        $db->query("SELECT * FROM slaveaccount WHERE login='$login'");
        if ($db->next_record()) {
            $err->raise("dom", _("The specified slave account already exists"));
            return false;
        }
        $db->query("INSERT INTO slaveaccount (login,pass) VALUES ('$login','$pass')");
        return true;
    }

    /* ----------------------------------------------------------------- */

    /** Remove a slave account
     */
    function del_slave_account($login) {
        global $db, $err;
        $db->query("DELETE FROM slaveaccount WHERE login='$login'");
        return true;
    }

    /*     * ********** */
    /*  Private  */
    /*     * ********** */


    /* ----------------------------------------------------------------- */

    /** Try to lock a domain
     * @access private
     */
    function lock() {
        global $db, $err;
        $err->log("dom", "lock");
        if ($this->islocked) {
            $err->raise("dom", _("--- Program error --- Lock already obtained!"));
        }
        while (file_exists($this->fic_lock_cron)) {
            sleep(2);
        }
        $this->islocked = true;
        return true;
    }

    /* ----------------------------------------------------------------- */

    /** Unlock the cron for domain management
     * return true
     * @access private
     */
    function unlock() {
        global $db, $err;
        $err->log("dom", "unlock");
        if (!$this->islocked) {
            $err->raise("dom", _("--- Program error --- No lock on the domains!"));
        }
        $this->islocked = false;
        return true;
    }

    /* ----------------------------------------------------------------- */

    /** Declare that a domain's emails are hosted in this server : 
     * This adds 2 MX entries in this domain (if required)
     */
    function hook_dom_add_mx_domain($dom_id) {
        global $err;
        $domain = $this->get_domain_byid($dom_id);
        $err->log("dom", "hook_dom_add_mx_domain");
        $this->set_sub_domain($domain, '', $this->type_defmx, '');
        if (!empty($GLOBALS['L_DEFAULT_SECONDARY_MX'])) {
            $this->set_sub_domain($domain, '', $this->type_defmx2, '');
        }
        return true;
    }

    /* ----------------------------------------------------------------- */

    /**
     * Delete an account (all his domains)
     */
    function hook_admin_del_member() {
        global $err;
        $err->log("dom", "alternc_del_member");
        $li = $this->enum_domains();
        foreach ($li as $dom) {
            $this->del_domain($dom);
        }
        return true;
    }

    /* ----------------------------------------------------------------- */

    /** Returns the used quota for the $name service for the current user.
     * @param $name string name of the quota
     * @return integer the number of service used or false if an error occured
     * @access private
     */
    function hook_quota_get() {
        global $db, $err, $cuid;
        $err->log("dom", "get_quota");
        $q = Array("name" => "dom", "description" => _("Domain name"), "used" => 0);
        $db->query("SELECT COUNT(*) AS cnt FROM domaines WHERE compte='$cuid'");
        if ($db->next_record()) {
            $q['used'] = $db->f("cnt");
        }
        return $q;
    }

    /* --------------------------------------------------------------------- */

    /** Returns the global domain(s) configuration(s) of a particular user
     * No parameters needed 
     * */
    function alternc_export_conf() {
        global $db, $err;
        $err->log("dom", "export");
        $this->enum_domains();
Alan Garcia's avatar
Alan Garcia committed
1917
        $str="";
alban's avatar
alban committed
1918
        foreach ($this->domains as $d) {
Alan Garcia's avatar
Alan Garcia committed
1919
            $str.= "  <domaines>\n";
alban's avatar
alban committed
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
            $str.="   <nom>" . $d . "</nom>\n";
            $this->lock();
            $s = $this->get_domain_all($d);
            $this->unlock();
            if (empty($s["dns"])) {
                $s["dns"] = "non";
            } else {
                $s["dns"] = "oui";
            }
            $str.="   <dns>" . $s["dns"] . "</dns>\n";

            if (empty($s["mx"])) {
                $s["mx"] = "non";
            } else {
                $s["mx"] = "oui";
            }

            $str.="   <mx>" . $s["mx"] . "</mx>\n";

            if (empty($s["mail"])) {
                $s["mail"] = "non";
            }
            $str.="   <mail>" . $s["mail"] . "</mail>\n";
            if (is_array($s["sub"])) {
                foreach ($s["sub"] as $sub) {
                    $str.="     <subdomain>\n";
                    $str.="       <enabled>" . $sub["enable"] . " </enabled>\n";
                    $str.="       <destination>" . $sub["dest"] . " </destination>\n";
                    $str.="       <type>" . $sub["type"] . " </type>\n";
                    $str.="     </subdomain>\n";
                }
            }
            $str.=" </domaines>\n";
        }
        return $str;
    }

    /**
     * Return an array with all the needed parameters to generate conf 
     * of a vhost.
     * If no parameters, return the parameters for ALL the vhost.
     * Optionnal parameters: id of the sub_domaines
     *
     * */
    function generation_parameters($id = null, $only_apache = true) {
        global $db, $err;
        $err->log("dom", "generation_parameters");
        $params = "";
        if (!is_null($id) && intval($id) == $id) {
            $id = intval($id);
            $params = " AND sd.id = $id ";
        }
        if ($only_apache) {
            $params.=" and dt.only_dns is false ";
        }
1975
1976
// BUG BUG BUG FIXME
// Suppression de comptes -> membres existe pas -> domaines a supprimer ne sont pas lister
alban's avatar
alban committed
1977
        $db->query("
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
select 
  sd.id as sub_id, 
  lower(sd.type) as type, 
  m.login, 
  m.uid as uid, 
  if(length(sd.sub)>0,concat_ws('.',sd.sub,sd.domaine),sd.domaine) as fqdn, 
  concat_ws('@',m.login,v.value) as mail, 
  sd.valeur  
from 
  sub_domaines sd left join membres m on sd.compte=m.uid,
  variable v, 
  domaines_type dt 
where 
  v.name='mailname_bounce' 
  and lower(dt.name) = lower(sd.type) 
  $params 
order by 
  m.login, 
  sd.domaine, 
  sd.sub 
;");
alban's avatar
alban committed
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
        $r = array();
        while ($db->next_record()) {
            $r[