source: alternc/trunk/bureau/class/m_dom.php @ 1670

Revision 1670, 31.5 KB checked in by anarcat, 7 years ago (diff)

modification cosmétique: utiliser set_sub_domain() pour régler les sous-domaine à la création pour éviter la duplication de code et clarifier le code

Line 
1<?php
2/*
3 $Id: m_dom.php,v 1.27 2006/02/17 18:34:30 olivier Exp $
4 ----------------------------------------------------------------------
5 LICENSE
6
7 This program is free software; you can redistribute it and/or
8 modify it under the terms of the GNU General Public License (GPL)
9 as published by the Free Software Foundation; either version 2
10 of the License, or (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 To read the license please visit http://www.gnu.org/copyleft/gpl.html
18 ----------------------------------------------------------------------
19 Original Author of file: Benjamin Sonntag
20 Purpose of file: PHP Class that manage domain names installed on the server
21 ----------------------------------------------------------------------
22*/
23
24define('SLAVE_FLAG', "/var/run/alternc/refresh_slave");
25
26/**
27* Classe de gestion des domaines de l'hébergé.
28*
29* Cette classe permet de gérer les domaines / sous-domaines, redirections
30* dns et mx des domaines d'un membre hébergé.<br />
31* Copyleft {@link http://alternc.net/ AlternC Team}
32*
33* @copyright    AlternC-Team 2002-11-01 http://alternc.net/
34*
35*/
36class m_dom {
37
38  /** $domains : Cache des domaines du membre
39   * @access private
40   */
41  var $domains;
42
43  /** $dns : Liste des dns trouvés par la fonction whois
44   * @access private
45   */
46  var $dns;
47
48  /** Flag : a-t-on trouvé un sous-domaine Webmail pour ce domaine ?
49   * @access private
50   */
51  var $webmail;
52
53  /**
54   * Système de verrouillage du cron
55   * Ce fichier permet de verrouiller le cron en attendant la validation
56   * du domaine par update_domains.sh
57   * @access private
58   */
59  var $fic_lock_cron="/var/run/alternc/cron.lock";
60
61  /**
62   * Le cron a-t-il été bloqué ?
63   * Il faut appeler les fonctions privées lock et unlock entre les
64   * appels aux domaines.
65   * @access private
66   */
67  var $islocked=false;
68
69  var $type_local = "0";
70  var $type_url = "1";
71  var $type_ip = "2";
72  var $type_webmail = "3";
73
74  var $action_insert = "0";
75  var $action_update= "1";
76  var $action_delete = "2";
77
78  /* ----------------------------------------------------------------- */
79  /**
80   * Constructeur
81   */
82  function m_dom() {
83  }
84
85  /* ----------------------------------------------------------------- */
86  /**
87   * Quota name
88   */
89  function alternc_quota_names() {
90    return "dom";
91  }
92
93  /* ----------------------------------------------------------------- */
94  /**
95   * Retourne un tableau contenant les domaines d'un membre.
96   *
97   * @return array retourne un tableau indexé contenant la liste des
98   *  domaines hébergés sur le compte courant. Retourne FALSE si une
99   *  erreur s'est produite.
100   */
101  function enum_domains() {
102    global $db,$err,$cuid;
103    $err->log("dom","enum_domains");
104    $db->query("select * from domaines where compte='$cuid';");
105    $this->domains=array();
106    if ($db->num_rows()>0) {
107      while ($db->next_record()) {
108        $this->domains[]=$db->f("domaine");
109      }
110    }
111    return $this->domains;
112  }
113
114  /* ----------------------------------------------------------------- */
115  /**
116   *  Efface un domaine du membre courant, et tous ses sous-domaines
117   *
118   * Cette fonction efface un domaine et tous ses sous-domaines, ainsi que
119   * les autres services attachés à celui-ci. Elle appelle donc les autres
120   * classe. Chaque classe peut déclarer une fonction del_dom qui sera
121   * appellée lors de la destruction d'un domaine.
122   *
123   * @param string $dom nom de domaine à effacer
124   * @return boolean Retourne FALSE si une erreur s'est produite, TRUE sinon.
125   */
126  function del_domain($dom) {
127    global $db,$err,$classes,$cuid;
128    $err->log("dom","del_domain",$dom);
129    $dom=strtolower($dom);
130    $db->query("SELECT * FROM domaines WHERE domaine='$dom';");
131    if ($db->num_rows()==0) {
132      $err->raise("dom",1,$dom);
133      return false;
134    }
135    $db->next_record();
136    if ($db->f("compte")!=$cuid) {
137      $err->raise("dom",2,$dom);
138      return false;
139    }
140    $db->query("INSERT INTO domaines_standby (compte,domaine,mx,gesdns,gesmx,action) SELECT compte,domaine,mx,gesdns,gesmx,2 FROM domaines WHERE domaine='$dom'"); // DELETE
141    $db->query("DELETE FROM domaines WHERE domaine='$dom';");
142    $db->query("DELETE FROM sub_domaines WHERE domaine='$dom';");
143
144    // DEPENDANCE :
145    // Lancement de del_dom sur les classes domain_sensitive :
146    // Declenchons les autres classes.
147    foreach($classes as $c) {
148      if (method_exists($GLOBALS[$c],"alternc_del_domain")) {
149        $GLOBALS[$c]->alternc_del_domain($dom);
150      }
151    }
152    foreach($classes as $c) {
153      if (method_exists($GLOBALS[$c],"alternc_del_mx_domain")) {
154        $GLOBALS[$c]->alternc_del_mx_domain($dom);
155      }
156    }
157    return true;
158  }
159
160  /* ----------------------------------------------------------------- */
161  /**
162   *  Installe un domaine sur le compte courant.
163   *
164   * <p>Si le domaine existe déjà ou est interdit, ou est celui du serveur,
165   * l'installation est refusée. Si l'hébergement DNS est demandé, la fonction
166   * checkhostallow vérifiera que le domaine peut être installé conformément
167   * aux demandes des super-admin.
168   * Si le dns n'est pas demandé, le domaine peut être installé s'il est en
169   * seconde main d'un tld (exemple : test.eu.org ou test.com, mais pas
170   * toto.test.org ou test.test.asso.fr)</p>
171   * <p>Chaque classe peut définir une fonction add_dom($dom) qui sera
172   * appellée lors de l'installation d'un nouveau domaine.</p>
173   *
174   * @param string $dom nom fqdn du domaine à installer
175   * @param integer $dns 1 ou 0 pour héberger le DNS du domaine ou pas.
176   * @param integer $noerase 1 ou 0 pour rendre le domaine inamovible ou non
177   * @param integer $force 1 ou 0, si 1, n'effectue pas les tests de DNS.
178   *  force ne devrait être utilisé que par le super-admin.
179   $ @return boolean Retourne FALSE si une erreur s'est produite, TRUE sinon.
180  */
181  function add_domain($domain,$dns,$noerase=0,$force=0) {
182    global $db,$err,$quota,$classes,$L_MX,$L_FQDN,$tld,$cuid;
183    $err->log("dom","add_domain",$domain);
184    $mx="1";
185    // Locked ?
186    if (!$this->islocked) {
187      $err->raise("dom",3);
188      return false;
189    }
190    // Verifie que le domaine est rfc-compliant
191    $domain=strtolower($domain);
192    $t=checkfqdn($domain);
193    if ($t) {
194      $err->raise("dom",3+$t);
195      return false;
196    }
197    // Interdit les domaines clés (table forbidden_domains) sauf en cas FORCE
198    $db->query("select domain from forbidden_domains where domain='$domain'");
199    if ($db->num_rows() && !$force) {
200      $err->raise("dom",22);
201      return false;
202    }
203    if ($domain==$L_FQDN || $domain=="www.$L_FQDN") {
204      $err->raise("dom",18);
205      return false;
206    }
207    $db->query("SELECT compte FROM domaines WHERE domaine='$domain';");
208    if ($db->num_rows()) {
209      $err->raise("dom",8);
210      return false;
211    }
212    $db->query("SELECT compte FROM `sub_domaines` WHERE sub != \"\" AND concat( sub, \".\", domaine )='$domain' OR domaine='$domain';");
213    if ($db->num_rows()) {
214      $err->raise("dom",8);
215      return false;
216    }
217    $db->query("select compte from domaines_standby where domaine='$domain';");
218    if ($db->num_rows()!=0) {
219      $err->raise("dom",9);
220      return false;
221    }
222    $this->dns=$this->whois($domain);
223    if (!$force) {
224      $v=checkhostallow($domain,$this->dns);
225      if ($v==-1) {
226        $err->raise("dom",7);   // TLD interdit
227        return false;
228      }
229      if ($dns && $v==-2) {
230        $err->raise("dom",12);  // Domaine non trouvé dans le whois
231        return false;
232      }
233      if ($dns && $v==-3) {
234        $err->raise("dom",23);  // Domaine non trouvé dans le whois
235        return false;
236      }
237
238      if ($dns) $dns="1"; else $dns="0";
239
240      // mode 5 : force DNS to NO.
241      if ($tld[$v]==5) $dns=0;
242      // It must be a real domain (no subdomain)
243      if (!$dns) {
244        $v=checkhostallow_nodns($domain);
245        if ($v) {
246          $err->raise("dom",22);
247          return false;
248        }
249      }
250    }
251    // Check the quota :
252    if (!$quota->cancreate("dom")) {
253      $err->raise("dom",10);
254      return false;
255    }
256    if ($noerase) $noerase="1"; else $noerase="0";
257    $db->query("insert into domaines (compte,domaine,mx,gesdns,gesmx,noerase) values ('$cuid','$domain','$L_MX','$dns','$mx','$noerase');");
258    $db->query("insert into domaines_standby (compte,domaine,mx,gesdns,gesmx,action) values ('$cuid','$domain','$L_MX','$dns','$mx',0);"); // INSERT
259    // Creation des 3 sous-domaines par défaut : Vide, www et mail
260    $this->set_sub_domain($domain, '',     $this->type_url,     'add', 'http://www.'.$domain);
261    $this->set_sub_domain($domain, 'www',  $this->type_local,   'add', '/');
262    $this->set_sub_domain($domain, 'mail', $this->type_webmail, 'add', '');
263    // DEPENDANCE :
264    // Lancement de add_dom sur les classes domain_sensitive :
265     // Declenchons les autres classes.   
266    foreach($classes as $c) {
267      if (method_exists($GLOBALS[$c],"alternc_add_domain")) {
268        $GLOBALS[$c]->alternc_add_domain($domain);
269      }
270    }
271    foreach($classes as $c) {
272      if (method_exists($GLOBALS[$c],"alternc_add_mx_domain")) {
273        $GLOBALS[$c]->alternc_add_mx_domain($domain);
274      }
275    }
276   return true;
277  }
278
279  /* ----------------------------------------------------------------- */
280  /**
281   * Retourne les entrées DNS du domaine $domain issues du WHOIS.
282   *
283   * Cette fonction effectue un appel WHOIS($domain) sur Internet,
284   * et extrait du whois les serveurs DNS du domaine demandé. En fonction
285   * du TLD, on sait (ou pas) faire le whois correspondant.
286   * Actuellement, les tld suivants sont supportés :
287   * .com .net .org .be .info .ca .cx .fr .biz .name
288   *
289   * @param string $domain Domaine fqdn dont on souhaite les serveurs DNS
290   * @return array Retourne un tableau indexé avec les NOMS fqdn des dns
291   *   du domaine demandé. Retourne FALSE si une erreur s'est produite.
292   *
293   */
294  function whois($domain) {
295    global $db,$err;
296    $err->log("dom","whois",$domain);
297    // pour ajouter un nouveau TLD, utiliser le code ci-dessous.
298    //  echo "whois : $domain<br />";
299    ereg(".*\.([^\.]*)",$domain,$out);
300    $ext=$out[1];
301    // pour ajouter un nouveau TLD, utiliser le code ci-dessous.
302    //  echo "ext: $ext<br />";
303    $egal="";
304    switch($ext) {
305    case "com":
306    case "net":
307      $serveur="rs.internic.net";
308      $egal="=";
309      break;
310    case "org":
311      $serveur="whois.pir.org";
312      break;
313    case "be":
314      $serveur="whois.dns.be";
315      break;
316    case "eu":
317      $serveur="das.eu";
318      break;
319    case "info":
320      $serveur="whois.afilias.net";
321      break;
322    case "ca":
323      $serveur="whois.cira.ca";
324      break;
325    case "cx":
326      $serveur="whois.nic.cx";
327      break;
328    case "it":
329      $serveur="whois.nic.it";
330      break;
331    case "fr":
332      $serveur="whois.nic.fr";
333      break;
334    case "biz":
335      $serveur="whois.nic.biz";
336      break;
337    case "name":
338      $serveur="whois.nic.name";
339      break;
340    case "ws":
341      $serveur="whois.samoanic.ws";
342      break;
343    default:
344      $err->raise("dom",7);
345      return false;
346      break;
347    }
348    // pour ajouter un nouveau TLD, utiliser le code ci-dessous.
349    //  echo "serveur : $serveur <br />";
350    if (($fp=fsockopen($serveur, 43))>0) {
351      fputs($fp, "$egal$domain\r\n");
352      $found = false;
353      $state=0;
354      while (!feof($fp)) {
355        $ligne = fgets($fp,128);
356        // pour ajouter un nouveau TLD, utiliser le code ci-dessous.
357        //      echo "| $ligne<br />";
358        switch($ext) {
359        case "org":
360        case "com":
361        case "net":
362        case "info":
363        case "biz":
364        case "name":
365          if (ereg("Name Server:", $ligne)) {
366            $found = true;
367            $tmp=strtolower(ereg_replace(chr(10), "",ereg_replace(chr(13),"",ereg_replace(" ","", ereg_replace("Name Server:","", $ligne)))));
368            if ($tmp)
369              $server[]=$tmp;
370          }
371          break;
372        case "cx":
373          $ligne = ereg_replace(chr(10), "",ereg_replace(chr(13),"",ereg_replace(" ","", $ligne)));
374          if ($ligne=="" && $state==1)
375            $state=2;
376          if ($state==1)
377            $server[]=strtolower($ligne);
378          if ($ligne=="Nameservers:" && $state==0) {
379            $state=1;
380            $found = true;
381          }
382          break;
383        case "ca":
384          $ligne=ereg_replace(chr(10), "",ereg_replace(chr(13),"",ereg_replace(" ","", $ligne)));
385          if ($ligne=="Status:EXIST")
386            $found=true;
387          if (ereg("NS.-Hostname:", $ligne)) {
388            $tmp=strtolower(ereg_replace("NS.-Hostname:","", $ligne));
389            if ($tmp)
390              $server[]=$tmp;
391          }
392          break;
393        case "eu":
394        case "be":
395          $ligne=ereg_replace(chr(10), "",ereg_replace(chr(13),"",ereg_replace(" ","", $ligne)));
396          if($found)
397             $tmp = trim($ligne);
398          if ($tmp)
399             $server[]=$tmp;
400          if ($ligne=="Nameservers:") {
401            $state=1;
402            $found=true;
403          }
404          break;
405        case "it":
406          if (ereg("nserver:", $ligne)) {
407            $found=true;
408            $tmp=strtolower(preg_replace("/nserver:\s*[^ ]*\s*([^\s]*)$/","\\1", $ligne));
409            if ($tmp)
410              $server[]=$tmp;
411          }
412          break;
413        case "fr":
414          if (ereg("nserver:", $ligne)) {
415            $found=true;
416            $tmp=strtolower(preg_replace("/nserver:\s*([^\s]*)\s*.*$/","\\1", $ligne));
417            if ($tmp)
418              $server[]=$tmp;
419          }
420          break;
421        case "ws";
422/* e.g.
423Welcome to the .WS Whois Server
424
425Use of this service for any purpose other
426than determining the availability of a domain
427in the .WS TLD to be registered is strictly
428prohibited.
429
430  Domain Name: DRONE.WS
431
432  Registrant: Registered through Go Daddy Software, Inc. (GoDaddy.com
433
434  Domain created on 2005-01-11 08:56:25
435  Domain last updated on 2005-01-11 08:56:25
436
437  Name servers:
438
439    ns2.koumbit.net
440    ns1.koumbit.net
441*/
442
443/*
444failure:
445
446Welcome to the .WS Whois Server
447
448Use of this service for any purpose other
449than determining the availability of a domain
450in the .WS TLD to be registered is strictly
451prohibited.
452
453No match for "dronefdasfsa.ws".
454
455*/
456          if (ereg('^[[:space:]]*Name servers:[[:space:]]*$', $ligne)) {
457                // found the server
458                $state = 1;
459          } elseif ($state) {
460                if ($ligne = ereg_replace('[[:space:]]', "", $ligne)) {
461                  // first non-whitespace line is considered to be the nameservers themselves
462                  $found = true;
463                  $server[] = $ligne;
464                }
465          }
466          break;
467        } // switch
468      } // while
469      fclose($fp);
470    } else {
471      $err->raise("dom",11);
472      return false;
473    }
474
475    if ($found) {
476      return $server;
477    } else {
478      $err->raise("dom",12);
479      return false;
480    }
481  } // whois
482
483  /* ----------------------------------------------------------------- */
484  /**
485   *  retourne TOUTES les infos d'un domaine
486   *
487   * <b>Note</b> : si le domaine est en attente (présent dans
488   *  domaines_standby), une erreur est retournée
489   *
490   * @param string $dom Domaine dont on souhaite les informations
491   * @return array Retourne toutes les infos du domaine sous la forme d'un
492   * tableau associatif comme suit :<br /><pre>
493   *  $r["name"] =  Nom fqdn
494   *  $r["dns"]  =  Gestion du dns ou pas ?
495   *  $r["mx"]   =  Valeur du champs MX si "dns"=true
496   *  $r["mail"] =  Heberge-t-on le mail ou pas ? (si "dns"=false)
497   *  $r["nsub"] =  Nombre de sous-domaines
498   *  $r["sub"]  =  tableau associatif des sous-domaines
499   *  $r["sub"][0-(nsub-1)]["name"] = nom du sous-domaine (NON-complet)
500   *  $r["sub"][0-(nsub-1)]["dest"] = Destination (url, ip, local ...)
501   *  $r["sub"][0-(nsub-1)]["type"] = Type (0-n) de la redirection.
502   *  </pre>
503   *  Retourne FALSE si une erreur s'est produite.
504   *
505   */
506  function get_domain_all($dom) {
507    global $db,$err,$cuid;
508    $err->log("dom","get_domain_all",$dom);
509    // Locked ?
510    if (!$this->islocked) {
511      $err->raise("dom",3);
512      return false;
513    }
514    $t=checkfqdn($dom);
515    if ($t) {
516      $err->raise("dom",3+$t);
517      return false;
518    }
519    $r["name"]=$dom;
520    $db->query("select * from domaines_standby where compte='$cuid' and domaine='$dom'");
521    if ($db->num_rows()>0) {
522      $err->raise("dom",13);
523      return false;
524    }
525    $db->query("select * from domaines where compte='$cuid' and domaine='$dom'");
526    if ($db->num_rows()==0) {
527      $err->raise("dom",1,$dom);
528      return false;
529    }
530    $db->next_record();
531    $r["dns"]=$db->Record["gesdns"];
532    $r["mail"]=$db->Record["gesmx"];
533    $r["mx"]=$db->Record["mx"];
534    $r[noerase]=$db->Record[noerase];
535    $db->free();
536    $db->query("select count(*) as cnt from sub_domaines where compte='$cuid' and domaine='$dom'");
537    $db->next_record();
538    $r["nsub"]=$db->Record["cnt"];
539    $db->free();
540    $db->query("select * from sub_domaines where compte='$cuid' and domaine='$dom'");
541    // Pas de webmail, on le cochera si on le trouve.
542    $this->webmail=0;
543    for($i=0;$i<$r["nsub"];$i++) {
544      $db->next_record();
545      $r["sub"][$i]=array();
546      $r["sub"][$i]["name"]=$db->Record["sub"];
547      $r["sub"][$i]["dest"]=$db->Record["valeur"];
548      $r["sub"][$i]["type"]=$db->Record["type"];
549      if ($db->Record["type"]==3) { // Webmail
550        $this->webmail=1;
551        $r["sub"][$i]["dest"]=_("Webmail access");
552      }
553    }
554    $db->free();
555    return $r;
556  } // get_domain_all
557
558  /* ----------------------------------------------------------------- */
559  /**
560   * Retourne TOUTES les infos d'un sous domaine du compte courant.
561   *
562   * @param string $dom Domaine fqdn concerné
563   * @param string $sub Sous-domaine dont on souhaite les informations
564   * @return arrray Retourne un tableau associatif contenant les
565   *  informations du sous-domaine demandé.<pre>
566   *  $r["name"]= nom du sous-domaine (NON-complet)
567   *  $r["dest"]= Destination (url, ip, local ...)
568   *  </pre>
569   *  $r["type"]= Type (0-n) de la redirection.
570   *  Retourne FALSE si une erreur s'est produite.
571   */
572  function get_sub_domain_all($dom,$sub) {
573    global $db,$err,$cuid;
574    $err->log("dom","get_sub_domain_all",$dom."/".$sub);
575    // Locked ?
576    if (!$this->islocked) {
577      $err->raise("dom",3);
578      return false;
579    }
580    $t=checkfqdn($dom);
581    if ($t) {
582      $err->raise("dom",3+$t);
583      return false;
584    }
585    $db->query("select * from sub_domaines where compte='$cuid' and domaine='$dom' and sub='$sub'");
586    if ($db->num_rows()==0) {
587      $err->raise("dom",14);
588      return false;
589    }
590    $db->next_record();
591    $r=array();
592    $r["name"]=$db->Record["sub"];
593    $r["dest"]=$db->Record["valeur"];
594    $r["type"]=$db->Record["type"];
595    $db->free();
596    return $r;
597  } // get_sub_domain_all
598
599  /* ----------------------------------------------------------------- */
600  /**
601   * Modifier les information du sous-domaine demandé.
602   *
603   * <b>Note</b> : si le sous-domaine $sub.$dom n'existe pas, il est créé.<br />
604   * <b>Note : TODO</b> : vérification de concordance de $dest<br />
605   *
606   * @param string $dom Domaine dont on souhaite modifier/ajouter un sous domaine
607   * @param string $subk Sous domaine à modifier / créer
608   * @param integer $type Type de sous-domaine (local, ip, url ...)
609   * @param string $action Action : vaut "add" ou "edit" selon que l'on
610   *  Crée (add) ou Modifie (edit) le sous-domaine
611   * @param string $dest Destination du sous-domaine, dépend de la valeur
612   *  de $type (url, ip, dossier...)
613   * @return boolean Retourne FALSE si une erreur s'est produite, TRUE sinon.
614   */
615  function set_sub_domain($dom,$sub,$type,$action,$dest) {
616    global $db,$err,$cuid;
617    $err->log("dom","set_sub_domain",$dom."/".$sub);
618    // Locked ?
619    if (!$this->islocked) {
620      $err->raise("dom",3);
621      return false;
622    }
623    $dest=trim($dest);
624    $dom=strtolower($dom);
625    $sub=strtolower($sub);
626    if ($sub != '*' && $sub != '' && preg_match('`[^a-z0-9-]`', $sub)) {
627      $err->raise("dom",24);
628      return false;
629    }
630    if ($type==2) { // IP
631      if (!checkip($dest)) {
632        $err->raise("dom",19);
633        return false;
634      }
635    }
636    if ($type==1) { // URL
637      if (!checkurl($dest)) {
638        $err->raise("dom",20);
639        return false;
640      }
641    }
642    if ($type==0) { // LOCAL
643      if (substr($dest,0,1)!="/") {
644        $dest="/".$dest;
645      }
646      if (!checkuserpath($dest)) {
647        $err->raise("dom",21);
648        return false;
649      }
650    }
651    // On a épuré $dir des problèmes eventuels ... On est en DESSOUS du dossier de l'utilisateur.
652    $t=checkfqdn($dom);
653    if ($t) {
654      $err->raise("dom",3+$t);
655      return false;
656    }
657    if (!$r=$this->get_sub_domain_all($dom,$sub)) {
658      // Le sous-domaine n'existe pas, on le crée seulement si $action vaut add
659      if ($action=="add") {
660        $db->query("insert into sub_domaines (compte,domaine,sub,valeur,type) values ('$cuid','$dom','$sub','$dest',$type);");
661        $db->query("delete from sub_domaines_standby where domaine='$dom' and sub='$sub';");
662        $db->query("insert into sub_domaines_standby (compte,domaine,sub,valeur,type,action) values ('$cuid','$dom','$sub','$dest','$type',0);"); // INSERT
663      } else {
664        $err->raise("dom",14);
665        return false;
666      }
667    } else {
668      if ($action=="edit") {
669        // On vérifie que des modifications ont bien eu lieu :)
670        if ($r["type"]==$type && $r["dest"]==$dest) {
671          $err->raise("dom",15);
672          return false;
673        }
674        // OK, des modifs ont été faites, on valide :
675        $db->query("update sub_domaines set type='$type', valeur='$dest' where domaine='$dom' and sub='$sub'");
676        $db->query("delete from sub_domaines_standby where domaine='$dom' and sub='$sub'");
677        $db->query("insert into sub_domaines_standby (compte,domaine,sub,valeur,type,action) values ('$cuid','$dom','$sub','$dest','$type',1);"); // UPDATE
678      } else {
679        $err->raise("dom",16);
680        return false;
681      }
682    }
683    return true;
684  } // set_sub_domain
685
686  /* ----------------------------------------------------------------- */
687  /**
688   *  Supprime le sous-domaine demandé
689   *
690   * @param string $dom Domaine dont on souhaite supprimer un sous-domaine
691   * @param string $sub Sous-domaine que l'on souhaite supprimer
692   * @return boolean Retourne FALSE si une erreur s'est produite, TRUE sinon.
693   *
694   */
695  function del_sub_domain($dom,$sub) {
696    global $db,$err,$cuid;
697    $err->log("dom","del_sub_domain",$dom."/".$sub);
698    // Locked ?
699    if (!$this->islocked) {
700      $err->raise("dom",3);
701      return false;
702    }
703    $t=checkfqdn($dom);
704    if ($t) {
705      $err->raise("dom",3+$t);
706      return false;
707    }
708    if (!$r=$this->get_sub_domain_all($dom,$sub)) {
709      // Le sous-domaine n'existe pas, erreur
710      $err->raise("dom",14);
711      return false;
712    } else {
713      // OK, on valide :
714      $db->query("delete from sub_domaines where domaine='$dom' and sub='$sub'");
715      $db->query("delete from sub_domaines_standby where domaine='$dom' and sub='$sub'");
716      $db->query("insert into sub_domaines_standby (compte,domaine,sub,valeur,type,action) values ('$cuid','$dom','$sub','".$r["dest"]."','".$r["type"]."',2);"); // DELETE
717    }
718    return true;
719  } // del_sub_domain
720
721  /* ----------------------------------------------------------------- */
722  /**
723   * Modifie les information du domaine précisé.
724   *
725   * @param string $dom Domaine du compte courant que l'on souhaite modifier
726   * @param integer $dns Vaut 1 ou 0 pour héberger ou pas le DNS du domaine
727   * @param integer $mx Nom fqdn du serveur mx, si le mx local est précisé,
728   *  on héberge alors les mails du domaine.
729   * @return boolean appelle $mail->add_dom ou $ma->del_dom si besoin, en
730   *  fonction du champs MX. Retourne FALSE si une erreur s'est produite,
731   *  TRUE sinon.
732   *
733   */
734  function edit_domain($dom,$dns,$mx) {
735    global $db,$err,$L_MX,$classes,$cuid;
736    $err->log("dom","edit_domain",$dom);
737    // Locked ?
738    if (!$this->islocked) {
739      $err->raise("dom",3);
740      return false;
741    }
742    if ($dns == 1) {
743      $this->dns=$this->whois($dom);
744      $v=checkhostallow($dom,$this->dns);
745      if ($v==-1) {
746        $err->raise("dom",7);   // TLD interdit
747        return false;
748      }
749      if ($dns && $v==-2) {
750        $err->raise("dom",12);  // Domaine non trouvé dans le whois
751        return false;
752      }
753      if ($dns && $v==-3) {
754        $err->raise("dom",23);  // Domaine non trouvé dans le whois
755        return false;
756      }
757    }
758    $t=checkfqdn($dom);
759    if ($t) {
760      $err->raise("dom",3+$t);
761      return false;
762    }
763    if (!$r=$this->get_domain_all($dom)) {
764      // Le domaine n'existe pas, Failure
765      $err->raise("dom",4,$dom);
766      return false;
767    }
768    if ($dns!="1") $dns="0";
769    // On vérifie que des modifications ont bien eu lieu :)
770    if ($r["dns"]==$dns && $r["mx"]==$mx) {
771      $err->raise("dom",15);
772      return false;
773    }
774    // MX ?
775    if ($mx==$L_MX)
776      $gesmx="1";
777    else
778      $gesmx="0";
779    // OK, des modifs ont été faites, on valide :
780    // DEPENDANCE :
781    if ($gesmx && !$r["mail"]) { // on a associé le MX : on cree donc l'entree dans LDAP
782      // Lancement de add_dom sur les classes domain_sensitive :
783      foreach($classes as $c) {
784        if (method_exists($GLOBALS[$c],"alternc_add_mx_domain")) {
785        $GLOBALS[$c]->alternc_add_mx_domain($dom);
786        }
787      }
788    }
789   
790    if (!$gesmx && $r["mail"]) { // on a dissocié le MX : on détruit donc l'entree dans LDAP
791      // Lancement de del_dom sur les classes domain_sensitive :
792      foreach($classes as $c) {
793        if (method_exists($GLOBALS[$c],"alternc_del_mx_domain")) {
794          $GLOBALS[$c]->alternc_del_mx_domain($dom);
795        }
796      }
797    }
798   
799    $db->query("update domaines set gesdns='$dns', mx='$mx', gesmx='$gesmx' where domaine='$dom'");
800    $db->query("insert into domaines_standby (compte,domaine,mx,gesdns,gesmx,action) values ('$cuid','$dom','$mx','$dns','$gesmx',1);"); 
801    // UPDATE
802    return true;
803  } // edit_domain
804 
805
806
807  /****************************/
808  /*  Slave dns ip managment  */
809  /****************************/
810  /* ----------------------------------------------------------------- */
811  /**
812   * Return the list of ip addresses and classes that are allowed access to domain list
813   * through AXFR Transfers from the bind server.
814   */
815  function enum_slave_ip() {
816        global $db,$err;
817        $db->query("SELECT * FROM slaveip;");
818        if (!$db->next_record()) {
819          return false;
820        }
821        do {
822          $res[]=$db->Record;
823        } while ($db->next_record());
824        return $res;
825  }
826
827  /* ----------------------------------------------------------------- */
828  /**
829   * Add an ip address (or a ip class) to the list of allowed slave ip access list.
830   */
831  function add_slave_ip($ip,$class="32") {
832        global $db,$err;
833        if (!checkip($ip)) {
834                $err->raise("dom",19);
835                return false;
836        }
837        $class=intval($class);
838        if ($class<8 || $class>32) $class=32;
839        $db->query("SELECT * FROM slaveip WHERE ip='$ip' AND class='$class';");
840        if ($db->next_record()) {
841          $err->raise("err",22);
842          return false;
843        }
844        $db->query("INSERT INTO slaveip (ip,class) VALUES ('$ip','$class');");
845        $f=fopen(SLAVE_FLAG,"w");
846        fputs($f,"yopla");
847        fclose($f);     
848        return true;
849  }
850
851  /* ----------------------------------------------------------------- */
852  /**
853   * Remove an ip address (or a ip class) from the list of allowed slave ip access list.
854   */
855  function del_slave_ip($ip) {
856        global $db,$err;
857        if (!checkip($ip)) {
858                $err->raise("dom",19);
859                return false;
860        }
861        $db->query("DELETE FROM slaveip WHERE ip='$ip'");
862        $f=fopen(SLAVE_FLAG,"w");
863        fputs($f,"yopla");
864        fclose($f);     
865        return true;
866  }
867
868
869
870  /* ----------------------------------------------------------------- */
871  /**
872   * Check for a slave account
873   */
874  function check_slave_account($login,$pass) {
875        global $db,$err;
876        $db->query("SELECT * FROM slaveaccount WHERE login='$login' AND pass='$pass';");
877        if ($db->next_record()) { 
878                return true;
879        }
880        return false;
881  }
882
883  /* ----------------------------------------------------------------- */
884  /**
885   * Out (echo) the complete hosted domain list :
886   */
887  function echo_domain_list() {
888        global $db,$err;
889        $db->query("SELECT domaine FROM domaines WHERE gesdns=1 ORDER BY domaine");
890        while ($db->next_record()) {
891                echo $db->f("domaine")."\n";
892        }
893        return true;
894  }
895
896  /* ----------------------------------------------------------------- */
897  /**
898   * Return the list of allowed slave accounts
899   */
900  function enum_slave_account() {
901        global $db,$err;
902        $db->query("SELECT * FROM slaveaccount;");
903        $res=array();
904        while ($db->next_record()) {
905                $res[]=$db->Record;
906        }
907        if (!count($res)) return false;
908        return $res;
909  }
910
911  /* ----------------------------------------------------------------- */
912  /**
913   * Add a slave account that will be allowed to access the domain list
914   */
915  function add_slave_account($login,$pass) {
916        global $db,$err;
917        $db->query("SELECT * FROM slaveaccount WHERE login='$login'");
918        if ($db->next_record()) {
919          $err->raise("err",23);
920          return false;
921        }
922        $db->query("INSERT INTO slaveaccount (login,pass) VALUES ('$login','$pass')");
923        return true;
924  }
925
926  /* ----------------------------------------------------------------- */
927  /**
928   * Remove a slave account
929   */
930  function del_slave_account($login) {
931        global $db,$err;
932        $db->query("DELETE FROM slaveaccount WHERE login='$login'");
933        return true;
934  }
935
936  /*************/
937  /*  Private  */
938  /*************/
939
940
941  /* ----------------------------------------------------------------- */
942  /**
943   * Lock tente de verrouiller le fichier lock du cron. Si tout va bien (toujours?)
944   * retourne True, sinon retourne False
945   * NOTE : le systeme de lock est asymétrique, si on a un fichier CRONLOCK, on
946   * attends (que le cron ait fini son execution).
947   * @access private
948   */
949  function lock() {
950    global $db,$err;
951    $err->log("dom","lock");
952    if ($this->islocked) {
953      $err->raise("dom",17);
954    }
955    while (file_exists($this->fic_lock_cron)) {
956      sleep(2);
957    }
958    $this->islocked=true;
959    return true;
960  }
961
962  /* ----------------------------------------------------------------- */
963  /**
964   * unlock déverrouille le fichier lock du cron. Si tout va bien (toujours?)
965   * retourne True, sinon retourne False
966   * NOTE : actuellement, vu le système de lock asymetrique, on ne fait rien ;)
967   * @access private
968   */
969  function unlock() {
970    global $db,$err;
971    $err->log("dom","unlock");
972    if (!$this->islocked) {
973      $err->raise("dom",3);
974    }
975    $this->islocked=false;
976    return true;
977  }
978
979  /* ----------------------------------------------------------------- */
980  /**
981   * Efface un compte (tous ses domaines)
982   */
983  function alternc_del_member() {
984    global $err;
985    $err->log("dom","alternc_del_member");
986    $li=$this->enum_domains();
987    foreach($li as $dom) {
988      $this->del_domain($dom);
989    }
990    return true;
991  }
992
993  /* ----------------------------------------------------------------- */
994  /**
995   * Returns the used quota for the $name service for the current user.
996   * @param $name string name of the quota
997   * @return integer the number of service used or false if an error occured
998   * @access private
999   */
1000  function alternc_get_quota($name) {
1001    global $db,$err,$cuid;
1002    if ($name=="dom") {
1003      $err->log("dom","get_quota");
1004      $db->query("SELECT COUNT(*) AS cnt FROM domaines WHERE compte='$cuid'");
1005      $db->next_record();
1006      return $db->f("cnt");
1007    } else return false;
1008  }
1009
1010
1011  /* ----------------------------------------------------------------- */
1012  /**
1013   * Exporte toutes les informations domaine du compte.
1014   * @access private
1015   * EXPERIMENTAL 'sid' function ;)
1016   */
1017  function alternc_export() {
1018    global $db,$err;
1019    $err->log("dom","export");
1020    $this->enum_domains();
1021    $str="<dom>\n";
1022    foreach ($this->domains as $d) {
1023      $str.="  <domain>\n    <name>".xml_entities($d)."</name>\n";
1024      $s=$this->get_domain_all($d);
1025      $str.="    <hasdns>".xml_entities($s[dns])."</hasdns>\n";
1026      $str.="    <hasmx>".xml_entities($s[mx])."</hasmx>\n";
1027      $str.="    <mx>".xml_entities($s[mail])."</mx>\n";
1028      if (is_array($s[sub])) {
1029        foreach ($s[sub] as $sub) {
1030          $str.="    <subdomain>";
1031          $str.="<name>".xml_entities($sub[name])."</name>";
1032          $str.="<dest>".xml_entities($sub[dest])."</dest>";
1033          $str.="<type>".xml_entities($sub[type])."</type>";
1034          $str.="</subdomain>\n";
1035        }
1036      }
1037      $str.="  </domain>\n";
1038    }
1039    $str.="</dom>\n";
1040    return $str;
1041  }
1042
1043
1044} /* Class m_domains */
1045
1046?>
Note: See TracBrowser for help on using the repository browser.