source: trunk/bureau/class/m_dom.php @ 927

Revision 927, 31.1 KB checked in by nahuel, 7 years ago (diff)

On rajoute un test lors de l'ajout d'un domaine, on regarde si un sous domaine n'existe pas déjà
Closes: 312

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    $db->query("insert into sub_domaines (compte,domaine,sub,valeur,type) values ('$cuid','$domain','','http://www.".$domain."',1);");
261    $db->query("insert into sub_domaines (compte,domaine,sub,valeur,type) values ('$cuid','$domain','www','/',0);");
262    $db->query("insert into sub_domaines (compte,domaine,sub,valeur,type) values ('$cuid','$domain','mail','',3);");
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 "info":
317      $serveur="whois.afilias.net";
318      break;
319    case "ca":
320      $serveur="whois.cira.ca";
321      break;
322    case "cx":
323      $serveur="whois.nic.cx";
324      break;
325    case "it":
326      $serveur="whois.nic.it";
327      break;
328    case "fr":
329      $serveur="whois.nic.fr";
330      break;
331    case "biz":
332      $serveur="whois.nic.biz";
333      break;
334    case "name":
335      $serveur="whois.nic.name";
336      break;
337    case "ws":
338      $serveur="whois.samoanic.ws";
339      break;
340    default:
341      $err->raise("dom",7);
342      return false;
343      break;
344    }
345    // pour ajouter un nouveau TLD, utiliser le code ci-dessous.
346    //  echo "serveur : $serveur <br />";
347    if (($fp=fsockopen($serveur, 43))>0) {
348      fputs($fp, "$egal$domain\r\n");
349      $found = false;
350      $state=0;
351      while (!feof($fp)) {
352        $ligne = fgets($fp,128);
353        // pour ajouter un nouveau TLD, utiliser le code ci-dessous.
354        //      echo "| $ligne<br />";
355        switch($ext) {
356        case "org":
357        case "com":
358        case "net":
359        case "info":
360        case "biz":
361        case "name":
362          if (ereg("Name Server:", $ligne)) {
363            $found = true;
364            $tmp=strtolower(ereg_replace(chr(10), "",ereg_replace(chr(13),"",ereg_replace(" ","", ereg_replace("Name Server:","", $ligne)))));
365            if ($tmp)
366              $server[]=$tmp;
367          }
368          break;
369        case "cx":
370          $ligne = ereg_replace(chr(10), "",ereg_replace(chr(13),"",ereg_replace(" ","", $ligne)));
371          if ($ligne=="" && $state==1)
372            $state=2;
373          if ($state==1)
374            $server[]=strtolower($ligne);
375          if ($ligne=="Nameservers:" && $state==0) {
376            $state=1;
377            $found = true;
378          }
379          break;
380        case "ca":
381          $ligne=ereg_replace(chr(10), "",ereg_replace(chr(13),"",ereg_replace(" ","", $ligne)));
382          if ($ligne=="Status:EXIST")
383            $found=true;
384          if (ereg("NS.-Hostname:", $ligne)) {
385            $tmp=strtolower(ereg_replace("NS.-Hostname:","", $ligne));
386            if ($tmp)
387              $server[]=$tmp;
388          }
389          break;
390        case "be":
391          $ligne=ereg_replace(chr(10), "",ereg_replace(chr(13),"",ereg_replace(" ","", $ligne)));
392          if($found)
393             $tmp = trim($ligne);
394          if ($tmp)
395             $server[]=$tmp;
396          if ($ligne=="Nameservers:") {
397            $state=1;
398            $found=true;
399          }
400          break;
401        case "it":
402          if (ereg("nserver:", $ligne)) {
403            $found=true;
404            $tmp=strtolower(preg_replace("/nserver:\s*[^ ]*\s*([^\s]*)$/","\\1", $ligne));
405            if ($tmp)
406              $server[]=$tmp;
407          }
408          break;
409        case "fr":
410          if (ereg("nserver:", $ligne)) {
411            $found=true;
412            $tmp=strtolower(preg_replace("/nserver:\s*([^\s]*)\s*.*$/","\\1", $ligne));
413            if ($tmp)
414              $server[]=$tmp;
415          }
416          break;
417        case "ws";
418/* e.g.
419Welcome to the .WS Whois Server
420
421Use of this service for any purpose other
422than determining the availability of a domain
423in the .WS TLD to be registered is strictly
424prohibited.
425
426  Domain Name: DRONE.WS
427
428  Registrant: Registered through Go Daddy Software, Inc. (GoDaddy.com
429
430  Domain created on 2005-01-11 08:56:25
431  Domain last updated on 2005-01-11 08:56:25
432
433  Name servers:
434
435    ns2.koumbit.net
436    ns1.koumbit.net
437*/
438
439/*
440failure:
441
442Welcome to the .WS Whois Server
443
444Use of this service for any purpose other
445than determining the availability of a domain
446in the .WS TLD to be registered is strictly
447prohibited.
448
449No match for "dronefdasfsa.ws".
450
451*/
452          if (ereg('^[[:space:]]*Name servers:[[:space:]]*$', $ligne)) {
453                // found the server
454                $state = 1;
455          } elseif ($state) {
456                if ($ligne = ereg_replace('[[:space:]]', "", $ligne)) {
457                  // first non-whitespace line is considered to be the nameservers themselves
458                  $found = true;
459                  $server[] = $ligne;
460                }
461          }
462          break;
463        } // switch
464      } // while
465      fclose($fp);
466    } else {
467      $err->raise("dom",11);
468      return false;
469    }
470
471    if ($found) {
472      return $server;
473    } else {
474      $err->raise("dom",12);
475      return false;
476    }
477  } // whois
478
479  /* ----------------------------------------------------------------- */
480  /**
481   *  retourne TOUTES les infos d'un domaine
482   *
483   * <b>Note</b> : si le domaine est en attente (présent dans
484   *  domaines_standby), une erreur est retournée
485   *
486   * @param string $dom Domaine dont on souhaite les informations
487   * @return array Retourne toutes les infos du domaine sous la forme d'un
488   * tableau associatif comme suit :<br /><pre>
489   *  $r["name"] =  Nom fqdn
490   *  $r["dns"]  =  Gestion du dns ou pas ?
491   *  $r["mx"]   =  Valeur du champs MX si "dns"=true
492   *  $r["mail"] =  Heberge-t-on le mail ou pas ? (si "dns"=false)
493   *  $r["nsub"] =  Nombre de sous-domaines
494   *  $r["sub"]  =  tableau associatif des sous-domaines
495   *  $r["sub"][0-(nsub-1)]["name"] = nom du sous-domaine (NON-complet)
496   *  $r["sub"][0-(nsub-1)]["dest"] = Destination (url, ip, local ...)
497   *  $r["sub"][0-(nsub-1)]["type"] = Type (0-n) de la redirection.
498   *  </pre>
499   *  Retourne FALSE si une erreur s'est produite.
500   *
501   */
502  function get_domain_all($dom) {
503    global $db,$err,$cuid;
504    $err->log("dom","get_domain_all",$dom);
505    // Locked ?
506    if (!$this->islocked) {
507      $err->raise("dom",3);
508      return false;
509    }
510    $t=checkfqdn($dom);
511    if ($t) {
512      $err->raise("dom",3+$t);
513      return false;
514    }
515    $r["name"]=$dom;
516    $db->query("select * from domaines_standby where compte='$cuid' and domaine='$dom'");
517    if ($db->num_rows()>0) {
518      $err->raise("dom",13);
519      return false;
520    }
521    $db->query("select * from domaines where compte='$cuid' and domaine='$dom'");
522    if ($db->num_rows()==0) {
523      $err->raise("dom",1,$dom);
524      return false;
525    }
526    $db->next_record();
527    $r["dns"]=$db->Record["gesdns"];
528    $r["mail"]=$db->Record["gesmx"];
529    $r["mx"]=$db->Record["mx"];
530    $r[noerase]=$db->Record[noerase];
531    $db->free();
532    $db->query("select count(*) as cnt from sub_domaines where compte='$cuid' and domaine='$dom'");
533    $db->next_record();
534    $r["nsub"]=$db->Record["cnt"];
535    $db->free();
536    $db->query("select * from sub_domaines where compte='$cuid' and domaine='$dom'");
537    // Pas de webmail, on le cochera si on le trouve.
538    $this->webmail=0;
539    for($i=0;$i<$r["nsub"];$i++) {
540      $db->next_record();
541      $r["sub"][$i]=array();
542      $r["sub"][$i]["name"]=$db->Record["sub"];
543      $r["sub"][$i]["dest"]=$db->Record["valeur"];
544      $r["sub"][$i]["type"]=$db->Record["type"];
545      if ($db->Record["type"]==3) { // Webmail
546        $this->webmail=1;
547        $r["sub"][$i]["dest"]=_("Webmail access");
548      }
549    }
550    $db->free();
551    return $r;
552  } // get_domain_all
553
554  /* ----------------------------------------------------------------- */
555  /**
556   * Retourne TOUTES les infos d'un sous domaine du compte courant.
557   *
558   * @param string $dom Domaine fqdn concerné
559   * @param string $sub Sous-domaine dont on souhaite les informations
560   * @return arrray Retourne un tableau associatif contenant les
561   *  informations du sous-domaine demandé.<pre>
562   *  $r["name"]= nom du sous-domaine (NON-complet)
563   *  $r["dest"]= Destination (url, ip, local ...)
564   *  </pre>
565   *  $r["type"]= Type (0-n) de la redirection.
566   *  Retourne FALSE si une erreur s'est produite.
567   */
568  function get_sub_domain_all($dom,$sub) {
569    global $db,$err,$cuid;
570    $err->log("dom","get_sub_domain_all",$dom."/".$sub);
571    // Locked ?
572    if (!$this->islocked) {
573      $err->raise("dom",3);
574      return false;
575    }
576    $t=checkfqdn($dom);
577    if ($t) {
578      $err->raise("dom",3+$t);
579      return false;
580    }
581    $db->query("select * from sub_domaines where compte='$cuid' and domaine='$dom' and sub='$sub'");
582    if ($db->num_rows()==0) {
583      $err->raise("dom",14);
584      return false;
585    }
586    $db->next_record();
587    $r=array();
588    $r["name"]=$db->Record["sub"];
589    $r["dest"]=$db->Record["valeur"];
590    $r["type"]=$db->Record["type"];
591    $db->free();
592    return $r;
593  } // get_sub_domain_all
594
595  /* ----------------------------------------------------------------- */
596  /**
597   * Modifier les information du sous-domaine demandé.
598   *
599   * <b>Note</b> : si le sous-domaine $sub.$dom n'existe pas, il est créé.<br />
600   * <b>Note : TODO</b> : vérification de concordance de $dest<br />
601   *
602   * @param string $dom Domaine dont on souhaite modifier/ajouter un sous domaine
603   * @param string $subk Sous domaine à modifier / créer
604   * @param integer $type Type de sous-domaine (local, ip, url ...)
605   * @param string $action Action : vaut "add" ou "edit" selon que l'on
606   *  Crée (add) ou Modifie (edit) le sous-domaine
607   * @param string $dest Destination du sous-domaine, dépend de la valeur
608   *  de $type (url, ip, dossier...)
609   * @return boolean Retourne FALSE si une erreur s'est produite, TRUE sinon.
610   */
611  function set_sub_domain($dom,$sub,$type,$action,$dest) {
612    global $db,$err,$cuid;
613    $err->log("dom","set_sub_domain",$dom."/".$sub);
614    // Locked ?
615    if (!$this->islocked) {
616      $err->raise("dom",3);
617      return false;
618    }
619    $dest=trim($dest);
620    $dom=strtolower($dom);
621    $sub=strtolower($sub);
622    if ($sub != '*' && $sub != '' && preg_match('`[^a-z0-9-]`', $sub)) {
623      $err->raise("dom",24);
624      return false;
625    }
626    if ($type==2) { // IP
627      if (!checkip($dest)) {
628        $err->raise("dom",19);
629        return false;
630      }
631    }
632    if ($type==1) { // URL
633      if (!checkurl($dest)) {
634        $err->raise("dom",20);
635        return false;
636      }
637    }
638    if ($type==0) { // LOCAL
639      if (substr($dest,0,1)!="/") {
640        $dest="/".$dest;
641      }
642      if (!checkuserpath($dest)) {
643        $err->raise("dom",21);
644        return false;
645      }
646    }
647    // On a épuré $dir des problèmes eventuels ... On est en DESSOUS du dossier de l'utilisateur.
648    $t=checkfqdn($dom);
649    if ($t) {
650      $err->raise("dom",3+$t);
651      return false;
652    }
653    if (!$r=$this->get_sub_domain_all($dom,$sub)) {
654      // Le sous-domaine n'existe pas, on le crée seulement si $action vaut add
655      if ($action=="add") {
656        $db->query("insert into sub_domaines (compte,domaine,sub,valeur,type) values ('$cuid','$dom','$sub','$dest',$type);");
657        $db->query("delete from sub_domaines_standby where domaine='$dom' and sub='$sub';");
658        $db->query("insert into sub_domaines_standby (compte,domaine,sub,valeur,type,action) values ('$cuid','$dom','$sub','$dest','$type',0);"); // INSERT
659      } else {
660        $err->raise("dom",14);
661        return false;
662      }
663    } else {
664      if ($action=="edit") {
665        // On vérifie que des modifications ont bien eu lieu :)
666        if ($r["type"]==$type && $r["dest"]==$dest) {
667          $err->raise("dom",15);
668          return false;
669        }
670        // OK, des modifs ont été faites, on valide :
671        $db->query("update sub_domaines set type='$type', valeur='$dest' where domaine='$dom' and sub='$sub'");
672        $db->query("delete from sub_domaines_standby where domaine='$dom' and sub='$sub'");
673        $db->query("insert into sub_domaines_standby (compte,domaine,sub,valeur,type,action) values ('$cuid','$dom','$sub','$dest','$type',1);"); // UPDATE
674      } else {
675        $err->raise("dom",16);
676        return false;
677      }
678    }
679    return true;
680  } // set_sub_domain
681
682  /* ----------------------------------------------------------------- */
683  /**
684   *  Supprime le sous-domaine demandé
685   *
686   * @param string $dom Domaine dont on souhaite supprimer un sous-domaine
687   * @param string $sub Sous-domaine que l'on souhaite supprimer
688   * @return boolean Retourne FALSE si une erreur s'est produite, TRUE sinon.
689   *
690   */
691  function del_sub_domain($dom,$sub) {
692    global $db,$err,$cuid;
693    $err->log("dom","del_sub_domain",$dom."/".$sub);
694    // Locked ?
695    if (!$this->islocked) {
696      $err->raise("dom",3);
697      return false;
698    }
699    $t=checkfqdn($dom);
700    if ($t) {
701      $err->raise("dom",3+$t);
702      return false;
703    }
704    if (!$r=$this->get_sub_domain_all($dom,$sub)) {
705      // Le sous-domaine n'existe pas, erreur
706      $err->raise("dom",14);
707      return false;
708    } else {
709      // OK, on valide :
710      $db->query("delete from sub_domaines where domaine='$dom' and sub='$sub'");
711      $db->query("delete from sub_domaines_standby where domaine='$dom' and sub='$sub'");
712      $db->query("insert into sub_domaines_standby (compte,domaine,sub,valeur,type,action) values ('$cuid','$dom','$sub','".$r["dest"]."','".$r["type"]."',2);"); // DELETE
713    }
714    return true;
715  } // del_sub_domain
716
717  /* ----------------------------------------------------------------- */
718  /**
719   * Modifie les information du domaine précisé.
720   *
721   * @param string $dom Domaine du compte courant que l'on souhaite modifier
722   * @param integer $dns Vaut 1 ou 0 pour héberger ou pas le DNS du domaine
723   * @param integer $mx Nom fqdn du serveur mx, si le mx local est précisé,
724   *  on héberge alors les mails du domaine.
725   * @return boolean appelle $mail->add_dom ou $ma->del_dom si besoin, en
726   *  fonction du champs MX. Retourne FALSE si une erreur s'est produite,
727   *  TRUE sinon.
728   *
729   */
730  function edit_domain($dom,$dns,$mx) {
731    global $db,$err,$L_MX,$classes,$cuid;
732    $err->log("dom","edit_domain",$dom);
733    // Locked ?
734    if (!$this->islocked) {
735      $err->raise("dom",3);
736      return false;
737    }
738    $t=checkfqdn($dom);
739    if ($t) {
740      $err->raise("dom",3+$t);
741      return false;
742    }
743    if (!$r=$this->get_domain_all($dom)) {
744      // Le domaine n'existe pas, Failure
745      $err->raise("dom",4,$dom);
746      return false;
747    }
748    if ($dns!="1") $dns="0";
749    // On vérifie que des modifications ont bien eu lieu :)
750    if ($r["dns"]==$dns && $r["mx"]==$mx) {
751      $err->raise("dom",15);
752      return false;
753    }
754    // MX ?
755    if ($mx==$L_MX)
756      $gesmx="1";
757    else
758      $gesmx="0";
759    // OK, des modifs ont été faites, on valide :
760    // DEPENDANCE :
761    if ($gesmx && !$r["mail"]) { // on a associé le MX : on cree donc l'entree dans LDAP
762      // Lancement de add_dom sur les classes domain_sensitive :
763      foreach($classes as $c) {
764        if (method_exists($GLOBALS[$c],"alternc_add_mx_domain")) {
765        $GLOBALS[$c]->alternc_add_mx_domain($dom);
766        }
767      }
768    }
769   
770    if (!$gesmx && $r["mail"]) { // on a dissocié le MX : on détruit donc l'entree dans LDAP
771      // Lancement de del_dom sur les classes domain_sensitive :
772      foreach($classes as $c) {
773        if (method_exists($GLOBALS[$c],"alternc_del_mx_domain")) {
774          $GLOBALS[$c]->alternc_del_mx_domain($dom);
775        }
776      }
777    }
778   
779    $db->query("update domaines set gesdns='$dns', mx='$mx', gesmx='$gesmx' where domaine='$dom'");
780    $db->query("insert into domaines_standby (compte,domaine,mx,gesdns,gesmx,action) values ('$cuid','$dom','$mx','$dns','$gesmx',1);"); 
781    // UPDATE
782    return true;
783  } // edit_domain
784 
785
786
787  /****************************/
788  /*  Slave dns ip managment  */
789  /****************************/
790  /* ----------------------------------------------------------------- */
791  /**
792   * Return the list of ip addresses and classes that are allowed access to domain list
793   * through AXFR Transfers from the bind server.
794   */
795  function enum_slave_ip() {
796        global $db,$err;
797        $db->query("SELECT * FROM slaveip;");
798        if (!$db->next_record()) {
799          return false;
800        }
801        do {
802          $res[]=$db->Record;
803        } while ($db->next_record());
804        return $res;
805  }
806
807  /* ----------------------------------------------------------------- */
808  /**
809   * Add an ip address (or a ip class) to the list of allowed slave ip access list.
810   */
811  function add_slave_ip($ip,$class="32") {
812        global $db,$err;
813        if (!checkip($ip)) {
814                $err->raise("dom",19);
815                return false;
816        }
817        $class=intval($class);
818        if ($class<8 || $class>32) $class=32;
819        $db->query("SELECT * FROM slaveip WHERE ip='$ip' AND class='$class';");
820        if ($db->next_record()) {
821          $err->raise("err",22);
822          return false;
823        }
824        $db->query("INSERT INTO slaveip (ip,class) VALUES ('$ip','$class');");
825        $f=fopen(SLAVE_FLAG,"w");
826        fputs($f,"yopla");
827        fclose($f);     
828        return true;
829  }
830
831  /* ----------------------------------------------------------------- */
832  /**
833   * Remove an ip address (or a ip class) from the list of allowed slave ip access list.
834   */
835  function del_slave_ip($ip) {
836        global $db,$err;
837        if (!checkip($ip)) {
838                $err->raise("dom",19);
839                return false;
840        }
841        $db->query("DELETE FROM slaveip WHERE ip='$ip'");
842        $f=fopen(SLAVE_FLAG,"w");
843        fputs($f,"yopla");
844        fclose($f);     
845        return true;
846  }
847
848
849
850  /* ----------------------------------------------------------------- */
851  /**
852   * Check for a slave account
853   */
854  function check_slave_account($login,$pass) {
855        global $db,$err;
856        $db->query("SELECT * FROM slaveaccount WHERE login='$login' AND pass='$pass';");
857        if ($db->next_record()) { 
858                return true;
859        }
860        return false;
861  }
862
863  /* ----------------------------------------------------------------- */
864  /**
865   * Out (echo) the complete hosted domain list :
866   */
867  function echo_domain_list() {
868        global $db,$err;
869        $db->query("SELECT domaine FROM domaines WHERE gesdns=1 ORDER BY domaine");
870        while ($db->next_record()) {
871                echo $db->f("domaine")."\n";
872        }
873        return true;
874  }
875
876  /* ----------------------------------------------------------------- */
877  /**
878   * Return the list of allowed slave accounts
879   */
880  function enum_slave_account() {
881        global $db,$err;
882        $db->query("SELECT * FROM slaveaccount;");
883        $res=array();
884        while ($db->next_record()) {
885                $res[]=$db->Record;
886        }
887        if (!count($res)) return false;
888        return $res;
889  }
890
891  /* ----------------------------------------------------------------- */
892  /**
893   * Add a slave account that will be allowed to access the domain list
894   */
895  function add_slave_account($login,$pass) {
896        global $db,$err;
897        $db->query("SELECT * FROM slaveaccount WHERE login='$login'");
898        if ($db->next_record()) {
899          $err->raise("err",23);
900          return false;
901        }
902        $db->query("INSERT INTO slaveaccount (login,pass) VALUES ('$login','$pass')");
903        return true;
904  }
905
906  /* ----------------------------------------------------------------- */
907  /**
908   * Remove a slave account
909   */
910  function del_slave_account($login) {
911        global $db,$err;
912        $db->query("DELETE FROM slaveaccount WHERE login='$login'");
913        return true;
914  }
915
916  /*************/
917  /*  Private  */
918  /*************/
919
920
921  /* ----------------------------------------------------------------- */
922  /**
923   * Lock tente de verrouiller le fichier lock du cron. Si tout va bien (toujours?)
924   * retourne True, sinon retourne False
925   * NOTE : le systeme de lock est asymétrique, si on a un fichier CRONLOCK, on
926   * attends (que le cron ait fini son execution).
927   * @access private
928   */
929  function lock() {
930    global $db,$err;
931    $err->log("dom","lock");
932    if ($this->islocked) {
933      $err->raise("dom",17);
934    }
935    while (file_exists($this->fic_lock_cron)) {
936      sleep(2);
937    }
938    $this->islocked=true;
939    return true;
940  }
941
942  /* ----------------------------------------------------------------- */
943  /**
944   * unlock déverrouille le fichier lock du cron. Si tout va bien (toujours?)
945   * retourne True, sinon retourne False
946   * NOTE : actuellement, vu le système de lock asymetrique, on ne fait rien ;)
947   * @access private
948   */
949  function unlock() {
950    global $db,$err;
951    $err->log("dom","unlock");
952    if (!$this->islocked) {
953      $err->raise("dom",3);
954    }
955    $this->islocked=false;
956    return true;
957  }
958
959  /* ----------------------------------------------------------------- */
960  /**
961   * Efface un compte (tous ses domaines)
962   */
963  function alternc_del_member() {
964    global $err;
965    $err->log("dom","alternc_del_member");
966    $li=$this->enum_domains();
967    foreach($li as $dom) {
968      $this->del_domain($dom);
969    }
970    return true;
971  }
972
973  /* ----------------------------------------------------------------- */
974  /**
975   * Returns the used quota for the $name service for the current user.
976   * @param $name string name of the quota
977   * @return integer the number of service used or false if an error occured
978   * @access private
979   */
980  function alternc_get_quota($name) {
981    global $db,$err,$cuid;
982    if ($name=="dom") {
983      $err->log("dom","get_quota");
984      $db->query("SELECT COUNT(*) AS cnt FROM domaines WHERE compte='$cuid'");
985      $db->next_record();
986      return $db->f("cnt");
987    } else return false;
988  }
989
990
991  /* ----------------------------------------------------------------- */
992  /**
993   * Exporte toutes les informations domaine du compte.
994   * @access private
995   * EXPERIMENTAL 'sid' function ;)
996   */
997  function alternc_export() {
998    global $db,$err;
999    $err->log("dom","export");
1000    $this->enum_domains();
1001    $str="<dom>\n";
1002    foreach ($this->domains as $d) {
1003      $str.="  <domain>\n    <name>".xml_entities($d)."</name>\n";
1004      $s=$this->get_domain_all($d);
1005      $str.="    <hasdns>".xml_entities($s[dns])."</hasdns>\n";
1006      $str.="    <hasmx>".xml_entities($s[mx])."</hasmx>\n";
1007      $str.="    <mx>".xml_entities($s[mail])."</mx>\n";
1008      if (is_array($s[sub])) {
1009        foreach ($s[sub] as $sub) {
1010          $str.="    <subdomain>";
1011          $str.="<name>".xml_entities($sub[name])."</name>";
1012          $str.="<dest>".xml_entities($sub[dest])."</dest>";
1013          $str.="<type>".xml_entities($sub[type])."</type>";
1014          $str.="</subdomain>\n";
1015        }
1016      }
1017      $str.="  </domain>\n";
1018    }
1019    $str.="</dom>\n";
1020    return $str;
1021  }
1022
1023
1024} /* Class m_domains */
1025
1026?>
Note: See TracBrowser for help on using the repository browser.