m_dom.php 69.6 KB
Newer Older
1
<?php
2
/* 
3
 ----------------------------------------------------------------------
4
5
6
7
 AlternC - Web Hosting System
 Copyright (C) 2000-2012 by the AlternC Development Team.
 https://alternc.org/
----------------------------------------------------------------------
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
 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
 ----------------------------------------------------------------------
*/

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

/**
* Classe de gestion des domaines de l'hberg.
* 
* Cette classe permet de grer les domaines / sous-domaines, redirections
* dns et mx des domaines d'un membre hberg.<br />
*/
class m_dom {

  /** $domains : Cache des domaines du membre
   * @access private
   */
  var $domains;

  /** $dns : Liste des dns trouvs par la fonction whois
   * @access private
   */
  var $dns;

  /** Flag : a-t-on trouv un sous-domaine Webmail pour ce domaine ?
   * @access private
   */
  var $webmail;

  /**
   * Systme de verrouillage du cron
   * 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";

  /**
   * Le cron a-t-il t bloqu ?
   * Il faut appeler les fonctions prives lock et unlock entre les
   * appels aux domaines.
   * @access private
   */
  var $islocked=false;

Alan Garcia's avatar
Alan Garcia committed
67
  var $type_local = "VHOST";
68
69
70
71
72
73
  var $type_url = "URL";
  var $type_ip = "IP";
  var $type_webmail = "WEBMAIL";
  var $type_ipv6 = "IPV6";
  var $type_cname = "CNAME";
  var $type_txt = "TXT";
74
75
  var $type_defmx = "DEFMX";
  var $type_defmx2 = "DEFMX2";
76
77
78
79
80

  var $action_insert = "0";
  var $action_update= "1";
  var $action_delete = "2";

Alan Garcia's avatar
Alan Garcia committed
81
  var $tld_no_check_at_all = "1";
Alan Garcia's avatar
Alan Garcia committed
82
83

  var $cache_domains_type_lst=false;
84
85
86
87
88
  /* ----------------------------------------------------------------- */
  /**
   * Constructeur
   */
  function m_dom() {
Alan Garcia's avatar
Alan Garcia committed
89
90
    $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(array('desc'=>'Disabled','type'=>'boolean')));
    variable_get('mailname_bounce', '%%FQDN%%','FQDN of the mail server, used to create vhost virtual mail_adress.', array(array('desc'=>'FQDN','type'=>'string')));
91
92
  }

93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
  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;
  }

  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') ));
  }

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
  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;
  }



Alan Garcia's avatar
Alan Garcia committed
145
146
147
148
149
150
151
152
  /* ----------------------------------------------------------------- */
  /**
   * Retourne un tableau contenant les types de domaines
   *
   * @return array retourne un tableau index contenant la liste types de domaines 
   *  authoris. Retourne FALSE si une erreur s'est produite.
   */
  function domains_type_lst() {
Alan Garcia's avatar
Alan Garcia committed
153
    global $db,$err;
Alan Garcia's avatar
Alan Garcia committed
154
    $err->log("dom","domains_type_lst");
Alan Garcia's avatar
Alan Garcia committed
155
156
157
158
159
160
    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;
      }
Alan Garcia's avatar
Alan Garcia committed
161
    }
Alan Garcia's avatar
Alan Garcia committed
162
    return $this->cache_domains_type_lst;
Alan Garcia's avatar
Alan Garcia committed
163
164
  }

Alan Garcia's avatar
Alan Garcia committed
165
166
167
168
169
170
171
172
173
174
175
176
177
178
  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;
  }

179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
  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;
    } else {
      $db->query("select target from domaines_type where name='$type';");
      if (! $db->next_record()) return false;
      return $db->f('target');
    }
  }

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
  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;
  }

  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

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
    // 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


282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
    // 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'];
301
        $val['entry_new']['value'] = $dst_url;
302
303
304
305
306
307
308
309
310
311
312
313
      } 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
Alban Crommer's avatar
Alban Crommer committed
314
    if ( preg_match('/^(?P<sub>[\-\w\.@]*)\h*(?P<ttl>\d*)\h*IN\h+NS\h+(?P<target>[\w\.\-]+)/i', $zone, $ret) ) {
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
      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 @
Alban Crommer's avatar
Alban Crommer committed
330
    if ( preg_match('/^(?P<sub>[\-\w\.@]*)\h*(?P<ttl>\d*)\h*IN\h+CNAME\h+(?P<target>[@\w+\.\-]+)/i', $zone, $ret) ) {
331
332
333
334
335
336
337
338
339
340
341
342
343
344
      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'];
345
        $val['entry_new']['value'] = $dst_url;
346
347
348
349
350
351
352
353
354
355
356
357
      } 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.
Alban Crommer's avatar
Alban Crommer committed
358
    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) ) {
359
360
      $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'].")";
361
362
363
364
365
366
367
      $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.
Alban Crommer's avatar
Alban Crommer committed
368
    if ( preg_match('/^(?P<sub>[\_\w\.@\-]+)\h+(?P<ttl>\d*)\h*IN\h+SRV\h+/i', $zone, $ret) ) {
369
370
371
372
373
374
      $val['status']='err';
      $val['comment'] = "Please add yourself the entry $zone";
    } else

    // Examples:
    // @       IN      TXT             "google-site-verification=jjjjjjjjjjjjjjjjjjjjjjjjsdsdjlksjdljdslgNj5"
Alban Crommer's avatar
Alban Crommer committed
375
    if ( preg_match('/^(?P<sub>[\_\w\.@\-]*)\h*(?P<ttl>\d*)\h*IN\h+TXT\h+\"(?P<target>.+)\"/i', $zone, $ret) ) {
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
      $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'];
    } else {

      // 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;
Alban Crommer's avatar
Alban Crommer committed
396
    $entry['did_it'] = 0;
397
398
399
    if ( $entry['status'] == 'err' ) {
      return $entry;
    }
400
401
402
403
404
405
406
407
408
409
410
411

    $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;
    }

Alan Garcia's avatar
Alan Garcia committed
412
    // If it is an unknown domains type
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
    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();

    return $entry;
  }

  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="") 
Alan Garcia's avatar
Alan Garcia committed
438
    if (! $this->add_domain($domain, true, false, true) ) {
439
440
441
442
443
444
445
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
      $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
  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
Alban Crommer's avatar
Alban Crommer committed
476
       if ( preg_match( '/Location:\h+(?P<target>[\-\w:\/.\?\=.]+)/', implode("\n",$http_response_header), $ret ) ) {
477
478
479
         // 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);
Alban Crommer's avatar
Alban Crommer committed
480
         if ( isset($target_url['host']) && ( $target_url['host'] == $original_cname['host'] ) ) { // if it's a redirection to himself (sub pages, http to https...)
481
482
           return false; // do not do a redirection (we must point to the server)
         }
Alban Crommer's avatar
Alban Crommer committed
483
484
485
486
487
488

         // 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'];
         }
489
490
491
492
493
494
495
496
497
498
         return $ret['target'];
       } 
      } else { // it isn't a redirection 
        return false;
      }
    } catch (Exception $e) {
      return false;
    }
  }

499
500
501
502
503
504
505
506
  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;
  }

507
  function domains_type_get($name) {
Alan Garcia's avatar
Alan Garcia committed
508
    global $db,$err,$cuid; 
509
510
    $name=mysql_real_escape_string($name);
    $db->query("select * from domaines_type where name='$name' ;");
Alan Garcia's avatar
Alan Garcia committed
511
512
513
514
    $db->next_record();
    return $db->Record;
  }

515
  function domains_type_del($name) {
Alan Garcia's avatar
Alan Garcia committed
516
    global $db,$err,$cuid;
517
518
    $name=mysql_real_escape_string($name);
    $db->query("delete domaines_type where name='$name';");
Alan Garcia's avatar
Alan Garcia committed
519
520
521
    return true;
  }

522
  function domains_type_update($name, $description, $target, $entry, $compatibility, $enable, $only_dns, $need_dns,$advanced,$create_tmpdir,$create_targetdir) {
Alan Garcia's avatar
Alan Garcia committed
523
    global $err,$cuid,$db;
524
525
    // The name MUST contain only letter and digits, it's an identifier after all ...
    if (!preg_match("#^[a-z0-9]+$#",$name)) {
526
      $err->raise("dom", _("The name MUST contain only letter and digits"));
527
528
      return false;
    }
529
530
    $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);
531
532
    $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';");
Alan Garcia's avatar
Alan Garcia committed
533
534
535
    return true;
  }   

536
  function sub_domain_change_status($sub_id,$status) {
Alan Garcia's avatar
Alan Garcia committed
537
538
    global $db,$err,$cuid;
    $err->log("dom","sub_domain_change_status");
539
    $sub_id=intval($sub_id);
Alan Garcia's avatar
Alan Garcia committed
540
541
    $status=strtoupper($status);
    if (! in_array($status,array('ENABLE', 'DISABLE'))) return false;
542

543
    $jh = $this->get_sub_domain_all($sub_id);
544
545
546
547
548
549
    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;
      }
    } 
Alan Garcia's avatar
Alan Garcia committed
550

551
    $db->query("update sub_domaines set enable='$status' where id = '".intval($sub_id)."';");
Alan Garcia's avatar
Alan Garcia committed
552
    $this->set_dns_action($jh['domain'], 'UPDATE');
Alan Garcia's avatar
Alan Garcia committed
553
554
555

    return true;
  } 
556
557
558
559

  /* ----------------------------------------------------------------- */
  /**
   * Retourne un tableau contenant les domaines d'un membre.
domi's avatar
domi committed
560
   * Par dfaut le membre connect
561
562
563
564
565
   *
   * @return array retourne un tableau index contenant la liste des
   *  domaines hbergs sur le compte courant. Retourne FALSE si une
   *  erreur s'est produite.
   */
domi's avatar
domi committed
566
  function enum_domains($uid=-1) {
567
568
    global $db,$err,$cuid;
    $err->log("dom","enum_domains");
domi's avatar
domi committed
569
570
    if ($uid == -1) { $uid = $cuid; }
    $db->query("SELECT * FROM domaines WHERE compte='{$uid}' ORDER BY domaine ASC;");
571
572
573
    $this->domains=array();
    if ($db->num_rows()>0) {
      while ($db->next_record()) {
Alan Garcia's avatar
Alan Garcia committed
574
      $this->domains[]=$db->f("domaine");
575
576
577
578
579
      }
    }
    return $this->domains;
  }

580
581
582
583
584
  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';");
Alan Garcia's avatar
Alan Garcia committed
585
    $this->set_dns_action($dom, 'UPDATE');
586

Alan Garcia's avatar
Alan Garcia committed
587
    # TODO : some work with domain sensitive classes
588
589
590
591

    return true;
  }

592
593
594
595
596
597
598
599
600
601
602
603
604
  /* ----------------------------------------------------------------- */
  /**
   *  Efface un domaine du membre courant, et tous ses sous-domaines
   *
   * Cette fonction efface un domaine et tous ses sous-domaines, ainsi que
   * les autres services attachs  celui-ci. Elle appelle donc les autres
   * classe. Chaque classe peut dclarer une fonction del_dom qui sera
   * appelle lors de la destruction d'un domaine.
   *
   * @param string $dom nom de domaine  effacer
   * @return boolean Retourne FALSE si une erreur s'est produite, TRUE sinon.
   */
  function del_domain($dom) {
605
    global $db,$err,$classes,$cuid,$hooks;
606
607
    $err->log("dom","del_domain",$dom);
    $dom=strtolower($dom);
608

609
    $this->lock();
610
    if (!$r=$this->get_domain_all($dom)) {
611
612
      return false;
    }
613
    $this->unlock();
614
615
616
617
618
619
620
621
622
623

    // 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"]));

    // Now mark the domain for deletion:
624
    $db->query("UPDATE sub_domaines SET web_action='DELETE'  WHERE domaine='$dom';");
Alan Garcia's avatar
Alan Garcia committed
625
    $this->set_dns_action($dom, 'DELETE');
626
627
628
629

    return true;
  }

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

634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
  /* ----------------------------------------------------------------- */
  /**
   *  Installe un domaine sur le compte courant.
   *
   * <p>Si le domaine existe dj ou est interdit, ou est celui du serveur,
   * l'installation est refuse. Si l'hbergement DNS est demand, la fonction
   * checkhostallow vrifiera que le domaine peut tre install conformment
   * aux demandes des super-admin.
   * Si le dns n'est pas demand, le domaine peut tre install s'il est en
   * seconde main d'un tld (exemple : test.eu.org ou test.com, mais pas
   * toto.test.org ou test.test.asso.fr)</p>
   * <p>Chaque classe peut dfinir une fonction add_dom($dom) qui sera
   * appelle lors de l'installation d'un nouveau domaine.</p>
   *
   * @param string $dom nom fqdn du domaine  installer
Alan Garcia's avatar
Alan Garcia committed
649
650
651
   * @param boolean $dns 1 ou 0 pour hberger le DNS du domaine ou pas.
   * @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.
652
653
654
   *  force ne devrait tre utilis que par le super-admin.
   $ @return boolean Retourne FALSE si une erreur s'est produite, TRUE sinon.
  */
Alan Garcia's avatar
Alan Garcia committed
655
  function add_domain($domain,$dns,$noerase=false,$force=false,$isslave=false,$slavedom="") {
656
    global $db,$err,$quota,$classes,$L_MX,$L_FQDN,$tld,$cuid,$bro,$hooks;
657
    $err->log("dom","add_domain",$domain);
658

659
660
    // Locked ?
    if (!$this->islocked) {
661
      $err->raise("dom",_("--- Program error --- No lock on the domains!"));
662
663
664
665
666
667
      return false;
    }
    // Verifie que le domaine est rfc-compliant
    $domain=strtolower($domain);
    $t=checkfqdn($domain);
    if ($t) {
668
      $err->raise("dom",_("The domain name is syntaxically incorrect"));
669
670
671
      return false;
    }
    // Interdit les domaines cls (table forbidden_domains) sauf en cas FORCE
672
    $db->query("SELECT domain FROM forbidden_domains WHERE domain='$domain'");
673
    if ($db->num_rows() && !$force) {
674
      $err->raise("dom",_("The requested domain is forbidden in this server, please contact the administrator"));
675
676
677
      return false;
    }
    if ($domain==$L_FQDN || $domain=="www.$L_FQDN") {
678
      $err->raise("dom",_("This domain is the server's domain! You cannot host it on your account!"));
679
680
681
682
      return false;
    }
    $db->query("SELECT compte FROM domaines WHERE domaine='$domain';");
    if ($db->num_rows()) {
683
      $err->raise("dom",_("The domain already exist"));
684
685
686
687
      return false;
    }
    $db->query("SELECT compte FROM `sub_domaines` WHERE sub != \"\" AND concat( sub, \".\", domaine )='$domain' OR domaine='$domain';");
    if ($db->num_rows()) {
688
      $err->raise("dom",_("The domain already exist"));
689
690
691
692
693
694
      return false;
    }
    $this->dns=$this->whois($domain);
    if (!$force) {
      $v=checkhostallow($domain,$this->dns);
      if ($v==-1) {
695
        $err->raise("dom",_("The last member of the domain name is incorrect or cannot be hosted in that server"));
Alan Garcia's avatar
Alan Garcia committed
696
        return false;
697
698
      }
      if ($dns && $v==-2) {
699
        $err->raise("dom",_("The domain cannot be found in the whois database")); 
Alan Garcia's avatar
Alan Garcia committed
700
        return false;
701
702
      }
      if ($dns && $v==-3) {
703
        $err->raise("dom",_("The domain cannot be found in the whois database"));
Alan Garcia's avatar
Alan Garcia committed
704
        return false;
705
706
707
708
709
710
711
712
      }

      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) {
Alan Garcia's avatar
Alan Garcia committed
713
714
         $v=checkhostallow_nodns($domain);
         if ($v) {
715
           $err->raise("dom",_("The requested domain is forbidden in this server, please contact the administrator"));
Alan Garcia's avatar
Alan Garcia committed
716
717
           return false;
         }
718
719
720
721
      }
    }
    // Check the quota :
    if (!$quota->cancreate("dom")) {
722
      $err->raise("dom",_("Your domain quota is over, you cannot create more domain names"));
723
724
725
      return false;
    }
    if ($noerase) $noerase="1"; else $noerase="0";
726
727
    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');");
728
729
730
731
    if (!($id=$db->lastid())) {
      $err->raise("dom",_("An unexpected error occured when creating the domain"));
      return false;
    }
732

733
734
735
736
737
    if ($isslave) {
      $isslave=true;
      $db->query("SELECT domaine FROM domaines WHERE compte='$cuid' AND domaine='$slavedom';");
      $db->next_record();
      if (!$db->Record["domaine"]) {
738
        $err->raise("dom",_("Domain '%s' not found"),$slavedom);
Alan Garcia's avatar
Alan Garcia committed
739
        $isslave=false;
740
741
      }
      // Point to the master domain : 
742
      $this->create_default_subdomains($domain, $slavedom);
743
744
    }
    if (!$isslave) {
745
      $this->create_default_subdomains($domain);
746
    }
Alan Garcia's avatar
Alan Garcia committed
747

748
749
750
751
    // 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));
752
    }
753
754
    // New Hooks: 
    $hooks->invoke("hook_dom_add_domain",array($id));
755
    if ($gesmx) $hooks->invoke("hook_dom_add_mx_domain",array($id));
756
    if ($isslave) {
757
      $hooks->invoke("hook_dom_add_slave_domain",array($id, $slavedom));
758
759
    }
    return true;
760
761
  }

762
  function create_default_subdomains($domain,$target_domain=""){
Axel ROGER's avatar
Axel ROGER committed
763
    global $db,$err;
764
    $err->log("dom","create_default_subdomains",$domain);
Alan Garcia's avatar
Alan Garcia committed
765
    $query="SELECT sub, domain_type, domain_type_parameter FROM default_subdomains WHERE (concerned = 'SLAVE' or concerned = 'BOTH') and enabled=1;";
766
    if(empty($target_domain)) {
Alan Garcia's avatar
Alan Garcia committed
767
      $query="SELECT sub, domain_type, domain_type_parameter FROM default_subdomains WHERE (concerned = 'MAIN' or concerned = 'BOTH') and enabled=1;";
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
    }
    $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);
    }
  }

  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);
  }
789

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

795
796
797

  function lst_default_subdomains(){
    global $db,$err;
798
    $err->log("dom","lst_default_subdomains");
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
    $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) {
817
818
    global $err;
    $err->log("dom","update_default_subdomains");
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
    $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;
835
    $err->log("dom","update_one_default");
836
837
    
    if($id==null)
838
      $db->query("INSERT INTO default_subdomains values ('','".addslashes($sub)."','".addslashes($domain_type)."','".addslashes($domain_type_parameter)."','".addslashes($concerned)."','".addslashes($enabled)."');");
839
    else
840
    $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).";");
841
842
843
844
    return true;
      //update
    

845
846
847
848
849
850
851
852
853
854
855
856
857
858
  }

  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;


859
860
  }

861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
  /* ----------------------------------------------------------------- */
  /**
   * Retourne les entres DNS du domaine $domain issues du WHOIS.
   *
   * Cette fonction effectue un appel WHOIS($domain) sur Internet,
   * et extrait du whois les serveurs DNS du domaine demand. En fonction
   * du TLD, on sait (ou pas) faire le whois correspondant.
   * Actuellement, les tld suivants sont supports :
   * .com .net .org .be .info .ca .cx .fr .biz .name
   *
   * @param string $domain Domaine fqdn dont on souhaite les serveurs DNS
   * @return array Retourne un tableau index avec les NOMS fqdn des dns
   *   du domaine demand. Retourne FALSE si une erreur s'est produite.
   *
   */
  function whois($domain) {
    global $db,$err;
    $err->log("dom","whois",$domain);
    // pour ajouter un nouveau TLD, utiliser le code ci-dessous.
Alan Garcia's avatar
Alan Garcia committed
880
    //  echo "whois : $domain<br />";
Benjamin Sonntag's avatar
   
Benjamin Sonntag committed
881
    preg_match("#.*\.([^\.]*)#",$domain,$out);
882
883
    $ext=$out[1];
    // pour ajouter un nouveau TLD, utiliser le code ci-dessous.
Alan Garcia's avatar
Alan Garcia committed
884
    //  echo "ext: $ext<br />";
Alan Garcia's avatar
Alan Garcia committed
885

886
    $serveur="";
Alan Garcia's avatar
Alan Garcia committed
887
888
889
890
891
892
    if (($fp=@fsockopen("whois.iana.org", 43))>0) {
      fputs($fp, "$domain\r\n");
      $found = false;
      $state=0;
      while (!feof($fp)) {
        $ligne = fgets($fp,128);
Benjamin Sonntag's avatar
   
Benjamin Sonntag committed
893
        if (preg_match('#^whois:#', $ligne)) { $serveur=preg_replace('/whois:\ */','',$ligne,1); }
Alan Garcia's avatar
Alan Garcia committed
894
895
      }
    }
896
    $serveur=str_replace(array(" ","\n"),"",$serveur);
Alan Garcia's avatar
Alan Garcia committed
897

898
899
900
901
902
903
    $egal="";
    switch($ext) {
    case "net":
      $egal="=";
      break;
    case "name":
904
      $egal="domain = ";
905
906
907
      break;
    }
    // pour ajouter un nouveau TLD, utiliser le code ci-dessous.
Alan Garcia's avatar
Alan Garcia committed
908
    //  echo "serveur : $serveur <br />";
909
    if (($fp=@fsockopen($serveur, 43))>0) {
910
911
912
913
      fputs($fp, "$egal$domain\r\n");
      $found = false;
      $state=0;
      while (!feof($fp)) {
Alan Garcia's avatar
Alan Garcia committed
914
915
916
917
918
919
920
921
922
923
924
  $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":
Benjamin Sonntag's avatar
   
Benjamin Sonntag committed
925
    if (preg_match("#Name Server:#", $ligne)) {
Alan Garcia's avatar
Alan Garcia committed
926
      $found = true;
Benjamin Sonntag's avatar
   
Benjamin Sonntag committed
927
      $tmp=strtolower(str_replace(chr(10), "",str_replace(chr(13),"",str_replace(" ","", str_replace("Name Server:","", $ligne)))));
Alan Garcia's avatar
Alan Garcia committed
928
929
930
931
932
      if ($tmp)
        $server[]=$tmp;
    }
    break;
  case "cx":
Benjamin Sonntag's avatar
   
Benjamin Sonntag committed
933
    $ligne = str_replace(chr(10), "",str_replace(chr(13),"",str_replace(" ","", $ligne)));
Alan Garcia's avatar
Alan Garcia committed
934
935
936
937
938
939
940
941
942
    if ($ligne=="" && $state==1)
      $state=2;
    if ($state==1)
      $server[]=strtolower($ligne);
    if ($ligne=="Nameservers:" && $state==0) {
      $state=1;
      $found = true;
    }
    break;
943
  case "eu":
Alan Garcia's avatar
Alan Garcia committed
944
  case "be":
945
          $ligne=preg_replace("/^ *([^ ]*) \(.*\)$/","\\1",trim($ligne));
946
947
948
949
950
951
952
953
954
          if($found)
             $tmp = trim($ligne);
          if ($tmp)
             $server[]=$tmp;
          if ($ligne=="Nameservers:") {
            $state=1;
            $found=true;
          }
          break;
955
956
957
958
959
960
961
962
963
964
965
    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)
              $server[]=$tmp;
          }
          break;
    case "it":
Benjamin Sonntag's avatar
   
Benjamin Sonntag committed
966
          if (preg_match("#nserver:#", $ligne)) {
967
968
969
970
971
972
            $found=true;
            $tmp=strtolower(preg_replace("/nserver:\s*[^ ]*\s*([^\s]*)$/","\\1", $ligne));
            if ($tmp)
              $server[]=$tmp;
          }
          break;
Alan Garcia's avatar
Alan Garcia committed
973
974
  case "fr":
  case "re":
Benjamin Sonntag's avatar
   
Benjamin Sonntag committed
975
          if (preg_match("#nserver:#", $ligne)) {
976
            $found=true;
Benjamin Sonntag's avatar
   
Benjamin Sonntag committed
977
            $tmp=strtolower(preg_replace("#nserver:\s*([^\s]*)\s*.*$#","\\1", $ligne));
978
979
980
981
            if ($tmp)
              $server[]=$tmp;
          }
          break;
Alan Garcia's avatar
Alan Garcia committed
982
983
  case "ca":
  case "ws";
Benjamin Sonntag's avatar
   
Benjamin Sonntag committed
984
    if (preg_match('#Name servers#', $ligne)) {
Alan Garcia's avatar
Alan Garcia committed
985
986
987
          // found the server
      $state = 1;
    } elseif ($state) {
Benjamin Sonntag's avatar
   
Benjamin Sonntag committed
988
      if (preg_match('#^[^%]#', $ligne) && $ligne = preg_replace('#[[:space:]]#', "", $ligne)) {
Alan Garcia's avatar
Alan Garcia committed
989
990
991
992
993
994
      // first non-whitespace line is considered to be the nameservers themselves
      $found = true;
      $server[] = $ligne;
    }
    }
    break;
mlutfy's avatar
mlutfy committed
995
        case "coop":
Benjamin Sonntag's avatar
   
Benjamin Sonntag committed
996
          if (preg_match('#Host Name:\s*([^\s]+)#', $ligne, $matches)) {
mlutfy's avatar
mlutfy committed
997
998
999
            $found = true;
            $server[] = $matches[1];
          }
Alan Garcia's avatar
Alan Garcia committed
1000
  } // switch
For faster browsing, not all history is shown. View entire blame