Code

Updated translation, fixed some typo/errors
[gosa.git] / plugins / admin / systems / class_termDNS.inc
index d7d43acf769ce3f150001bb686689234a61f87f4..065a6e1129204b5aab84c4447748bf8400edd2cb 100644 (file)
 
 class termDNS extends plugin
 {
-  /* CLI vars */
-  var $cli_summary= "Manage server basic objects";
-  var $cli_description= "Some longer text\nfor help";
-  var $cli_parameters= array("eins" => "Eins ist toll", "zwei" => "Zwei ist noch besser");
-
   /* attribute list for save action */
-  var $ignore_account= TRUE;
-  var $DNSattributes   = array("dNSClass","zoneName","dNSTTL");
-  var $attributes= array("ipHostNumber","macAddress");
-  var $objectclasses= array("whatever");
+  var $ignore_account = true;
+  var $autonet        = false;
 
-  var $ipHostNumber ="";    // IP address 
-  var $macAddress   ="";    // Mac address 
-  var $cn           ="";    // CN of currently edited device 
+  /* Basic informations 
+   */
+  var $attributes     = array("ipHostNumber","macAddress");
+  var $objectclasses  = array("whatever");
+
+  var $ipHostNumber   = "";    // IP address 
+  var $macAddress     = "";    // Mac address 
+  var $cn             = "";    // CN of currently edited device 
+  var $OrigCn         = "";    // Initial cn
+  var $IPisMust       = false;
+  var $MACisMust      = false;
+  var $dialog;
+
+  /* DCHP Attributes 
+   */
+  var $dhcpAttributes           = array("dhcpParentNode");
+  var $dhcpEnabled              = FALSE;
+  var $dhcp_is_Account          = FALSE;
+  var $dhcpParentNodes          = array();
+  var $dhcpParentNode           = "";
+  var $dhcpHostEntry            = array();
+  var $initial_dhcpParentNode   = "";
+  var $initial_dhcpHostEntry    = array();
+  var $initial_dhcp_is_Account  = FALSE;
+
+
+  /* DNS attributes  
+   */
+  var $DNSattributes            = array("dNSClass","zoneName","dNSTTL");
+  var $DNS_is_Account           = false;
+  var $DNSinitially_was_account = false;
+  var $dnsEntry                 = array();
+  var $DNSenabled               = false;
 
-  var $Zones      = array();      // All Available Zones like array("3.2.1"=>"MyServer.de")
-  var $RecordTypes= array();      // Possible record types 
-    
-  var $dNSClass   = "IN";         // dNSClass name 
-  var $zoneName   = "";           // Used ZoneName 
-  var $dNSTTL     = 7200;         // TTL settings for the created entries 
+  /*  Terminal dns 
+   */
+  function termDNS ($config, $dn,$objectClasses,$IPisMust = false)
+  {
+    /* We need to know which objectClasses are used, to store the ip/mac
+     * Because of different type of devices   
+     */
+    $this->objectclasses  =  $objectClasses;
+    $this->IPisMust       = $IPisMust;
 
-  /* Used records */
-  var $types = array();
-  var $DNSinitially_was_account = false;
+    plugin::plugin ($config, $dn);
 
-  var $orig_dn     ="";
+    if(isset($this->attrs['cn'][0])){
+      $this->OrigCn = preg_replace("/\\\$\$/","",$this->attrs['cn'][0]);
+      $this->cn = preg_replace("/\\\$\$/","",$this->attrs['cn'][0]);
+    }
 
-  var $IPisMust = false;
-  var $MACisMust= false;
+    /************
+     * DHCP 
+     ************/
 
-  var $found = false;
+    /* Hide all dhcp specific code, if dhcp plugin is not present in config */
+    $dhcpEnabled = FALSE;
+    foreach($this->config->data['TABS']['SERVTABS'] as $tab){
+      if(preg_match("/^servdhcp$/",$tab['CLASS'])){
+        $this->dhcpEnabled = TRUE;
+      }
+    }
+    if($this->dhcpEnabled){
+      $this->dhcpParentNodes = $this->get_dhcp_parent_nodes();
+      $this->dhcpParentNode  = $this->get_dhcp_parent_node();
+      if($this->dhcpParentNode){
+        $this->dhcp_is_Account = TRUE;
+        $this->initial_dhcp_is_Account = TRUE;
+        $this->dhcpHostEntry  = $this->get_dhcp_host_entry();    
+      }
+      $this->initial_dhcpHostEntry = $this->dhcpHostEntry;
+      $this->initial_dhcpParentNode= $this->dhcpParentNode;
+    }
 
-  function termDNS ($config, $dn,$objectClasses,$IPisMust = false)
-  {
-    /* We need to know which objectClasses are used, to store the ip/mac*/
-    $this->objectclasses= $objectClasses;
-    plugin::plugin ($config, $dn);
 
-    $this->orig_dn= $dn;
+    /************
+     * Autonetwork hook 
+     ************/
  
-    $this->IPisMust = $IPisMust;
+    /* Do we have autonet support? */
+    if (isset($this->config->data['MAIN']['AUTO_NETWORK_HOOK'])){
+      $this->autonet= true;
+    }
+
 
+    /************
+     * DNS
+     ************/
     /* Hide all dns specific code, if dns is not available 
      */
-    $found = false;
+    $DNSenabled = false;
     foreach($this->config->data['TABS']['SERVTABS'] as $tab){
       if(preg_match("/^servdns$/",$tab['CLASS'])){
-        $found = true;
+        $this->DNSenabled = true;
       }
     }
-    $this->found = $found;
-    if(!$this->found){
+    if(!$this->DNSenabled){
       $this->DNS_is_account = false;
       return;
     }
 
-    /* All types with required attrs */
-    $this->RecordTypes['aRecord']       = "aRecord";           // ok
-    $this->RecordTypes['mDRecord']      = "mDRecord";          // ok
-    $this->RecordTypes['mXRecord']      = "mXRecord";          // ok
-    $this->RecordTypes['nSRecord']      = "nSRecord";          // ok 
-    $this->RecordTypes['pTRRecord']     = "relativeDomainName";// ok
-    $this->RecordTypes['hInfoRecord']   = "hInfoRecord";       // ok
-    $this->RecordTypes['mInfoRecord']   = "mInfoRecord";       // ok
-    $this->RecordTypes['cNAMERecord']   = "relativeDomainName";// ok
-    $this->RecordTypes['tXTRecord']     = "tXTRecord";         // ok
-    $this->RecordTypes['aFSDBRecord']   = "aFSDBRecord";       // ok
-    $this->RecordTypes['SigRecord']     = "SigRecord";         // ok
-    $this->RecordTypes['KeyRecord']     = "KeyRecord";         // ok 
-    $this->RecordTypes['aAAARecord']    = "aAAARecord";        // ok
-    $this->RecordTypes['LocRecord']     = "LocRecord";         // ok 
-    $this->RecordTypes['nXTRecord']     = "nXTRecord";         // ok
-    $this->RecordTypes['sRVRecord']     = "sRVRecord";         // ok
-    $this->RecordTypes['nAPTRRecord']   = "nAPTRRecord";       // ok
-    $this->RecordTypes['kXRecord']      = "kXRecord";          // ok
-    $this->RecordTypes['certRecord']    = "certRecord";        // ok
-    $this->RecordTypes['a6Record']      = "a6Record";          // ok
-    $this->RecordTypes['dSRecord']      = "dSRecord";          // ok
-    $this->RecordTypes['sSHFPRecord']   = "sSHFPRecord";       // ok
-    $this->RecordTypes['rRSIGRecord']   = "rRSIGRecord";       // ok
-    $this->RecordTypes['nSECRecord']    = "nSECRecord";        // ok 
-
-    /* Get all available zones */
-    if(empty($this->cn)&&(isset($this->attrs['cn'][0]))){ 
-      $this->cn = $this->attrs['cn'][0];
-    }
-    $this->Zones = $this->get_Zones();
-    $types = array();
-
-    /* Get all records */
-    $ldap = $this->config->get_ldap_link();
-    $ldap->cd($this->dn); 
-    $ldap->ls("(&(objectClass=dNSZone)(zoneName=*)(!(relativeDomainName=@)))",$this->dn,array("*"));
+    if($this->DNSenabled){
 
-    $found = false;
+      /* Get Zones  
+       */
+      $this->Zones        = getAvailableZones($config);
 
-    while($attrs = $ldap->fetch()){
-      /* If relative domainname == cn 
-       * Try to read dnsclass / TTl / zone 
+      /* Get Entry 
        */
+      $this->dnsEntry     = getDNSHostEntries($config,$this->OrigCn);
 
-      if($attrs['relativeDomainName'][0] == $this->cn){
-        /* Get class */
-        if(isset($attrs['dNSClass'][0])){
-          $this->dNSClass = $attrs['dNSClass'][0];
-          $found  = true;
-        }
-        /* Get Zone*/
-        if(isset($attrs['zoneName'][0])){
-          $this->zoneName = $attrs['zoneName'][0];
-          $found  = true;
+      /* Remove A record which equals $this->ipHostNumber
+       */
+      $ptr = $this->get_pTRRecord();
+      foreach($this->dnsEntry['RECORDS'] as $key => $rec){
+        if(($rec['type'] == "aRecord") && ($rec['value'] == $this->ipHostNumber)){
+          unset($this->dnsEntry['RECORDS'][$key]);
         }
-        /* Get ttl */
-        if(isset($attrs['dNSTTL'][0])){
-          $this->dNSTTL   = $attrs['dNSTTL'][0];
-          $found  = true;
+        if(($rec['type'] == "pTRRecord") && ($rec['value'] == $ptr)){
+          unset($this->dnsEntry['RECORDS'][$key]);
         }
       }
 
-      /* Create list with all used records */
-      foreach($this->RecordTypes as $name => $value){
-    
-        /* If there is a record attribute  */
-        if(isset($attrs[$name])){
-  
-          /* get all entries */
-          for($i = 0 ; $i < $attrs[$value]['count']; $i ++){
-            if(($value == "aRecord")&&($this->ipHostNumber==$attrs[$value][$i])){
-             continue; 
-            }
-            $types[] =array("type"=>$name,"inittype"=>$name,"value"=>$attrs[$value][$i],"status"=>"edited","dn"=>$attrs['dn']);
-          }
-        }
+      /* Get Record types 
+       */
+      $this->RecordTypes  = getDnsRecordTypes();
+
+      /* If there is at least one entry in this -> types, we have DNS enabled 
+       */
+      if($this->dnsEntry['exists']){
+        $this->DNS_is_account = true;
+      }else{
+        $this->DNS_is_account = false;
       }
+   
     }
+    /* Store initally account settings 
+     */
+    $this->DNSinitially_was_account = $this->DNS_is_account;
+  }
 
-    /* If there is at least one entry in this -> types, we have DNS enabled */
-    $this->types = $types;
-    if((count($this->types) == 0) &&($found == false)){
-      $this->DNS_is_account = false;
+
+  function netmaskIsCoherent($idZone) 
+  {
+    $netmask = FlipIp(str_replace(".in-addr.arpa","",getNameFromMix($idZone)));
+    if(!strstr($this->ipHostNumber, $netmask)){
+      return false;
     }else{
-      $this->DNS_is_account = true;
+      return true;
     }
-    
-    /* Store initally account settings */
-    $this->DNSinitially_was_account = $this->DNS_is_account;
+  }
+
+
+  function getVarsForSaving($attrs) 
+  {
+    foreach($this->attributes as $attr){
+      if(!empty($this->$attr)){
+        $attrs[$attr] = $this->$attr;
+      }
+    }
+    return($attrs); 
   }
 
   function execute()
@@ -160,89 +179,179 @@ class termDNS extends plugin
     $display= "";
 
     $smarty->assign("staticAddress", ""); 
+    $smarty->assign("autonet", $this->autonet);
  
+    /* Check for autonet button */
+    if ($this->autonet && isset($_POST['autonet'])){
+      $cmd= $this->config->data['MAIN']['AUTO_NETWORK_HOOK'];
+      if(!empty($cmd) && $this->cn != ""){
+        $res = shell_exec($cmd." ".$this->cn);
+        if(!$res){
+          print_red(sprintf(_("Can't execute specified AUTO_NETWORK_HOOK '%s'. Please check your gosa.conf."),$cmd));
+        } else {
+          $res= split(';', trim($res));
+          if (isset($res[0]) && $res[0] != ""){
+            $this->ipHostNumber= $res[0];
+          }
+          if (isset($res[1]) && $res[1] != ""){
+            $this->macAddress= $res[1];
+          }
+        }
+      }
+    }
+
+    
+  
+    /**********
+     * DHCP Handling
+     **********/
+    if(isset($_POST['dhcpEditOptions'])){
+
+      if(count($this->dhcpHostEntry) == 0){
+        $this->dialog = new dhcpHost($this->dhcpParentNode,TRUE);
+      }else{
+        $this->dialog = new dhcpHost($this->dhcpHostEntry,TRUE);
+      }
+      $this->dialog->cn = $this->cn; 
+      $this->dialog->dhcpHWAddress = $this->macAddress; 
+      if(!empty($this->ipHostNumber)){
+        $this->dialog->statements['fixed-address'] = $this->ipHostNumber; 
+      }
+    }
+
+    if(isset($_POST['cancel_dhcp'])){
+      $this->dialog = FALSE; 
+    }
+
+    if(isset($_POST['save_dhcp'])){
+      $this->dialog->save_object();
+      
+      $msgs = $this->dialog->check(array());
+      if(count($msgs)){
+        foreach($msgs as $msg){
+          print_red($msg);
+        }
+      }else{
+        $this->dhcpHostEntry = $this->dialog->save();
+        $this->dialog = FALSE; 
+      }
+    }
+
+    if(isset($this->dialog) && $this->dialog != FALSE){
+      $this->dialog->save_object();
+      return($this->dialog->execute());
+    }
+    $smarty->assign("dhcpEnabled",    $this->dhcpEnabled);
+    $smarty->assign("dhcp_is_Account",$this->dhcp_is_Account);
+    $smarty->assign("dhcpParentNode", $this->dhcpParentNode);
+    $smarty->assign("dhcpParentNodes",$this->dhcpParentNodes);
+    $smarty->assign("dhcpParentNodeCnt",count($this->dhcpParentNodes));
+
     /* There is no dns available 
      */
-    if($this->found == false){
-        
+    if($this->DNSenabled == false){
+       
+      /* Is IP address must ? */ 
       $smarty->assign("DNS_is_account",false);  
       $smarty->assign("IPisMust",(($this->IPisMust)||($this->DNS_is_account)));
     
       /* Assign smarty all non DNs attributes */
       foreach($this->attributes as $attr){
         $smarty->assign($attr,$this->$attr);
+        $smarty->assign($attr."ACL",chkacl($this->acl,$attr));
       }
-      $smarty->assign("staticAddress", "");
+      $smarty->assign("staticAddress","<font class=\"must\">*</font>");
+
       $display.= $smarty->fetch(get_template_path('network.tpl', TRUE));
-      return($display);
     }else{
       $smarty->assign("DNS_is_account",true); 
-    }
-    /* Add new empty array with status new, to our record list */
-    if(isset($_POST['AddNewRecord'])){
-      $this->types[]  =array("type"=>"aRecord","value"=>"","status"=>"new");
-    }
-   
-    /* Handle all posts */ 
-    $only_once =true;
-    foreach($_POST as $name => $value){
 
-      /* Check if we have to delete a record entry */
-      if((preg_match("/RemoveRecord_/",$name))&&($only_once)) {
-      
-        /* Avoid performing this once again */
-        $only_once = false;
+      /* Add new empty array to our record list */
+      if(isset($_POST['AddNewRecord'])){
+        $this->dnsEntry['RECORDS'][]  =array("type"=>"aRecord","value"=>"");
+      }
 
-        /* Extract id for specified entry */
-        $id = preg_replace("/RemoveRecord_/","",$name);
-        $id = preg_replace("/_.*$/","",$id);
-    
-        /* Delete this record, mark edited entries to be able to delete them */
-        if(isset($this->types[$id])){
-          if($this->types[$id]['status'] == "edited"){
-            $this->types[$id]['status'] = "deleted";
-          }else{    
-            unset($this->types[$id]);
+      /* Handle all posts */ 
+      $only_once =true;
+      foreach($_POST as $name => $value){
+
+        /* Check if we have to delete a record entry */
+        if((preg_match("/RemoveRecord_/",$name))&&($only_once)) {
+
+          /* Avoid performing this once again */
+          $only_once = false;
+
+          /* Extract id for specified entry */
+          $id = preg_replace("/RemoveRecord_/","",$name);
+          $id = preg_replace("/_.*$/","",$id);
+
+          /* Delete this record, mark edited entries to be able to delete them */
+          if(isset($this->dnsEntry['RECORDS'][$id])){
+            unset($this->dnsEntry['RECORDS'][$id]);
           }
         }
       }
-    }
 
-    /* Assign smarty all non DNs attributes */
-    foreach($this->attributes as $attr){
-      $smarty->assign($attr,$this->$attr);
-    }
+      /* Assign smarty all non DNs attributes */
+      foreach($this->attributes as $attr){
+        $smarty->assign($attr,$this->$attr);
+        $smarty->assign($attr."ACL",chkacl($this->acl,$attr));
+      }
+
+      /* Assign smarty all DNS attributes */
+      foreach($this->DNSattributes as $attr){
+        $smarty->assign($attr,$this->dnsEntry[$attr]);
+        $smarty->assign($attr."ACL",chkacl($this->acl,$attr));
+      }
+
+      /* Assign all needed vars */
+      $smarty->assign("DNSaccountACL",chkacl($this->acl,"termDNS"));
+
+      $smarty->assign("DNSAccount",$this->DNS_is_account);
+      $smarty->assign("Zones",$this->Zones);
+      $smarty->assign("ZoneCnt",count($this->Zones));
+      $smarty->assign("ZoneKeys",($this->Zones));
+      $smarty->assign("IPisMust",(($this->IPisMust)||($this->DNS_is_account)));
+
+      /* Create zone array */
+      $idZones = array();
+      foreach($this->Zones as $id => $zone){
+        if($this->netmaskIsCoherent($id)) {
+          $idZones[$id] = $zone;
+        }else{
+          $idZones[$id] = $zone."&nbsp;("._("Not matching").")";
+        }
+      }    
+      $smarty->assign("Zones",$idZones);
+      $smarty->assign("ZoneKeys", $this->Zones);
 
-    /* Assign smarty all DNS attributes */
-    foreach($this->DNSattributes as $attr){
-      $smarty->assign($attr,$this->$attr);
+      $tmp = $this->generateRecordsList();
+
+      $changeStateForRecords = $tmp['changeStateForRecords'];
+
+      $smarty->assign("records",$tmp['str']);
+      $smarty->assign("changeStateForRecords",$changeStateForRecords);
+      $smarty->assign("staticAddress","<font class=\"must\">*</font>");
+
+      $display.= $smarty->fetch(get_template_path('network.tpl', TRUE));
     }
-    
-    /* Assign all needed vars */
-    $smarty->assign("DNSAccount",$this->DNS_is_account);
-    $smarty->assign("Zones",$this->Zones);
-    $smarty->assign("ZoneKeys",($this->Zones));
-    $smarty->assign("IPisMust",(($this->IPisMust)||($this->DNS_is_account)));
-  
-    $tmp = $this->generateRecordsList();
-    $changeStateForRecords = $tmp['changeStateForRecords'];
-    $smarty->assign("records",$tmp['str']);
-    $smarty->assign("changeStateForRecords",$changeStateForRecords);
-    $smarty->assign("staticAddress","<font class=\"must\">*</font>");
-    $display.= $smarty->fetch(get_template_path('network.tpl', TRUE));
     return($display);
   }
 
   function remove_from_parent()
   {
+    /*
     $ldap = $this->config->get_ldap_link();
     $ldap->cd($this->orig_dn);
     $ldap->search("(&(objectClass=dNSZone)(zoneName=*)(!(relativeDomainName=@)))",array("relativeDomainName","zoneName"));
     while($attr = $ldap->fetch()){  
       $ldap->cd($attr['dn']);
       $ldap->rmDir($attr['dn']);
+      show_ldap_error("Record:".$ldap->get_error(), _("Removing terminal from DNS object failed")); 
     }
+    */
   }
 
   /* Save data to object */
@@ -250,34 +359,44 @@ class termDNS extends plugin
   {
     /* Save all posted vars */
     plugin::save_object();
-    
-    /* Ge all non dns attributes (IP/MAC)*/
-    foreach($this->attributes as $attr){
-      if(isset($_POST[$attr])){
-        $this->$attr = $_POST[$attr];
+  
+
+    /* Handle DHCP Posts*/ 
+    if($this->dhcpEnabled && isset($_POST['network_tpl_posted'])){
+      foreach($this->dhcpAttributes as $attr){
+        if(isset($_POST[$attr])){
+          $this->$attr = $_POST[$attr];
+        }
+      }
+      if(isset($_POST['dhcp_is_Account'])){
+        $this->dhcp_is_Account = TRUE;
+      }else{
+        $this->dhcp_is_Account = FALSE;
       }
     }
-
     /* Get dns attributes */
-    if(isset($_POST['network_tpl_posted'])){
+    if(($this->DNSenabled) && (isset($_POST['network_tpl_posted'])) && chkacl($this->acl,"termDNS") == ""){
 
       /* Check for posted record changes */
-      foreach($this->types as $key => $value){
-      
-        /* Check if type has changed */
-        if(isset($_POST['RecordTypeSelectedFor_'.$key])){
-          $this->types[$key]['type'] = $_POST['RecordTypeSelectedFor_'.$key];
-        }
-        /* Check if value has changed */
-        if(isset($_POST['RecordValue_'.$key])){
-          $this->types[$key]['value'] = $_POST['RecordValue_'.$key];
+      if(is_array($this->dnsEntry['RECORDS'])){
+        foreach($this->dnsEntry['RECORDS'] as $key => $value){
+
+          /* Check if type has changed */
+          if(isset($_POST['RecordTypeSelectedFor_'.$key])){
+            $this->dnsEntry['RECORDS'][$key]['type'] = $_POST['RecordTypeSelectedFor_'.$key];
+          }
+          /* Check if value has changed */
+          if(isset($_POST['RecordValue_'.$key])){
+            $this->dnsEntry['RECORDS'][$key]['value'] = $_POST['RecordValue_'.$key];
+          }
         }
       }
-      
       /* Get all basic DNS attributes (TTL, Clas ..)*/
       foreach($this->DNSattributes as $attr){
         if(isset($_POST[$attr])){
-          $this->$attr = $_POST[$attr];
+          $this->dnsEntry[$attr] = $_POST[$attr];
         }
       }
 
@@ -294,31 +413,40 @@ class termDNS extends plugin
   /* Check supplied data */
   function check()
   {
-    $message= array();
+    /* Call common method to give check the hook */
+    $message= plugin::check();
 
-    
+    if($this->dhcpEnabled && $this->dhcp_is_Account && $this->dhcpParentNode != "" && count($this->dhcpHostEntry) == 0){
+      $message[] =_("You have not configured your dhcp settings yet.");
+    }
+
+    /* Check if ip must be given
+     */  
     if(($this->IPisMust)||($this->DNS_is_account)){
-      /* Check if ip is empty */
+  
+      /* Check if ip is empty 
+       */
       if ($this->ipHostNumber == "" && chkacl ($this->acl, "ipHostNumber") == ""){
         $message[]= _("The required field 'IP-address' is not set.");
       }
 
-      /* check if given ip is valid ip*/
-      $num="(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])";
-      if (!preg_match("/^$num\\.$num\\.$num\\.$num$/", $this->ipHostNumber)){
-        $message[]= _("Wrong IP format in field IP-address.");
-      }
     }
 
-    /* Check if mac is empty */
+    /* check if given ip is valid ip */
+    if ($this->ipHostNumber != "" && !is_ip($this->ipHostNumber)){
+      $message[]= _("Wrong IP format in field IP-address.");
+    }
+
+    /* Check if mac is empty 
+     */
     if ($this->macAddress == "" && chkacl ($this->acl, "macAddress") == ""){
       $message[]= _("The required field 'MAC-address' is not set.");
     }
 
-    /* Check if given mac is valid mac */
-    $tr = count(split(":",$this->macAddress));
-    if($tr!=6){
-      $message[]=(_("The given macaddress is invalid. There must be 6 1byte segments seperated by ':'."));
+    /* Check if given mac is valid mac 
+     */
+    if(!is_mac($this->macAddress)){
+      $message[]=(_("The given macaddress is invalid. There must be 6 2byte segments seperated by ':'."));
     }
 
     /* only perfrom this checks if this is a valid DNS account */
@@ -326,16 +454,31 @@ class termDNS extends plugin
 
       $checkArray = array();
       $onlyOnce   = array();
-      $onlyOnce['cNAMERecord'] = 0;
-  
-      foreach($this->types as $name => $values){
 
+      $tmp = array_flip($this->Zones);
+      $tmp2 = $tmp[$this->dnsEntry['zoneName']];
+      if(!$this->netmaskIsCoherent($tmp2)){ //this->dnsEntry['zoneName'])){
+        $tmp2 = preg_replace("/^.*\//","",$tmp2);
+        $message[] =sprintf(_("The specified IP address '%s' is not matching the selected reverse zone entry '%s'."),$this->ipHostNumber,$tmp2);
+      }
+
+                       // There can be many CNAME records
+      //$onlyOnce['cNAMERecord'] = 0;
+
+      /* Walk through all entries and detect duplicates or mismatches
+       */  
+      foreach($this->dnsEntry['RECORDS'] as $name => $values){
+
+        /* Count record values, to detect duplicate entries for a specific record
+         */
         if(!isset($checkArray[$values['type']][$values['value']])){
           $checkArray[$values['type']][$values['value']] = 0;
         }else{
           $message[] = sprintf(_("Found duplicate value for record type '%s'."),$values['type']);
         }
 
+        /* Check if given entries in $onlyOnce are used more than once
+         */
         if(isset($onlyOnce[$values['type']])){
           $onlyOnce[$values['type']] ++;
           if($onlyOnce[$values['type']] > 1){
@@ -343,15 +486,19 @@ class termDNS extends plugin
           }
         }
 
+        /* Skip txt record ... 
+         */
         if($values['type'] == "tXTRecord") continue;
 
-        /* Check if there is an aRecord defined which uses the same IP as used in IPhostAddress */
-        if(($values['type'] == "aRecord")&&($values['value'] == $this->ipHostNumber)&&($values['status']!="deleted")){
+        /* Check if there is an aRecord defined which uses the same IP as used in IPhostAddress 
+         */
+        if(($values['type'] == "aRecord")&&($values['value'] == $this->ipHostNumber)){
           $message[]=sprintf(_("The device IP '%s' is added as 'A Record', this will be done automatically, please remove the record."), 
                $this->ipHostNumber);
         }
 
-        /* only lower-case is allowed in record entries ... */
+        /* only lower-case is allowed in record entries ... 
+         */
         if($values['value'] != strtolower($values['value'])){
           $message[] = sprintf(_("Only lowercase is allowed, please check your '%ss'."),$values['type']);
         }
@@ -379,8 +526,71 @@ class termDNS extends plugin
     /* Write back to ldap */
     $ldap->cd($this->dn);
     $this->cleanup();
-$ldap->modify ($this->attrs); 
+    $ldap->modify ($this->attrs); 
 
+    /****************/ 
+    /* DHCP HANDLING */
+    /****************/ 
+  
+    /* New entry */
+    if($this->dhcpEnabled){
+
+      /* Unset dhcpStatements if this attribute is empty  */
+      if(isset($this->dhcpHostEntry['dhcpStatements']) && 
+          ($this->dhcpHostEntry['dhcpStatements'] == "" || count($this->dhcpHostEntry['dhcpStatements']) == 0) ){
+        unset($this->dhcpHostEntry['dhcpStatements']);
+      }
+  
+      /* DHCP removed */
+      if($this->initial_dhcp_is_Account && !$this->dhcp_is_Account){
+        $ldap->rmdir_recursive($this->dhcpHostEntry['dn']);
+        show_ldap_error($ldap->get_error(),_("Removing dhcp entry for this object failed."));
+      }
+
+      /* DHCP Added */
+      if(!$this->initial_dhcp_is_Account && $this->dhcp_is_Account){
+        $attrs = $this->dhcpHostEntry;
+        unset($attrs['MODIFIED']);
+        unset($attrs['dn']);
+        $ldap->cd("cn=".$this->cn.",".$this->dhcpParentNode);
+        $res = $ldap->add($attrs);
+#        print_a($attrs);
+#        print("cn=".$this->cn.",".$this->dhcpParentNode);
+        show_ldap_error($ldap->get_error(),_("Tried to add new dhcp entry failed."));
+      }
+
+      /* DHCP still activated */
+      if($this->initial_dhcp_is_Account && $this->dhcp_is_Account){
+
+        /* DHCP node changed */
+        if(($this->initial_dhcpParentNode != $this->dhcpParentNode) || 
+           ($this->cn != $this->OrigCn)){
+          $attrs = $this->dhcpHostEntry;
+          $attrs['cn'] = $this->cn;
+          unset($attrs['dn']);
+          unset($attrs['MODIFIED']);
+          $ldap->cd("cn=".$this->cn.",".$this->dhcpParentNode);
+          $res = $ldap->add($attrs);
+          show_ldap_error($ldap->get_error(),_("Tried to add new dhcp entry failed."));
+          if($res){
+            $ldap->rmdir_recursive($this->dhcpHostEntry['dn']);
+            show_ldap_error($ldap->get_error(),_("Removing old dhcp entry failed."));
+          }
+        }
+         
+        /* SAME node but modified */ 
+        if(isset($this->dhcpHostEntry['MODIFIED']) && $this->dhcpHostEntry['MODIFIED'] == 1  && 
+            $this->initial_dhcpParentNode == $this->dhcpParentNode){
+          $attrs = $this->dhcpHostEntry;
+          unset($attrs['dn']);
+          unset($attrs['MODIFIED']);
+          $ldap->cd($this->dhcpHostEntry['dn']);
+          $ldap->modify($attrs);
+          show_ldap_error($ldap->get_error(),_("Modifying dhcp entry failed."));
+        }    
+      }
+    }
+      
 
     /****************/ 
     /* DNS HANDLING */
@@ -389,56 +599,63 @@ $ldap->modify ($this->attrs);
     /* If isn't DNS account but initially was DNS account 
        remove all DNS entries 
      */ 
-    if(!$this->DNS_is_account){
-      if($this->DNSinitially_was_account){
-        $tmp = array();
+    if((!$this->DNSenabled) || (!$this->DNS_is_account && !$this->DNSinitially_was_account)){
+      return;
+    }else{
 
-        $ldap->ls("(&(objectClass=dNSZone)(!(relativeDomainName=@)))",$this->dn,array("relativeDomainName"));
-        while($attrs = $ldap->fetch()){
-          $dn=$attrs['dn'];
-          $ldap->cd($dn);
-          $ldap->rmdir_recursive($dn);
+      /* Add ipHostNumber to aRecords
+       */
+      if(!empty($this->ipHostNumber)){
+        $this->dnsEntry['RECORDS'][] = array("type"=>"aRecord","value"=>$this->ipHostNumber);
+        $ptr = $this->get_pTRRecord();
+        if(!empty($ptr)){
+          $this->dnsEntry['RECORDS'][] = array("type"=>"pTRRecord","value"=>$ptr);
         }
       }
-    }else{
-    
-      /* DNS is enabled, check what we have to do */
-      $delete = array();
-  
-      /* Generate a list of new ldap entries, 
-          & $delete contains all dns which should be deleted 
+
+      /* Create diff and follow instructions 
+       * If Account was disabled, remove account by setting exists to false
        */
-      $tmp = $this->generate_LDAP_entries();      
+      if((!$this->DNS_is_account)&&($this->DNSinitially_was_account)){  
+        $this->dnsEntry['exists'] = false;
+        $tmp = getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
+      }else{
+        $this->dnsEntry['exists'] = $this->DNS_is_account;
+        $tmp = getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
+      }   
 
-      $entries  = $tmp['entries'];
-      $delete   = $tmp['delete'];
+      /* move follwoing entries 
+       */
+      foreach($tmp['move'] as $src => $dst){
+        $this->recursive_move($src,$dst);
+      }
 
       /* Delete dns */
-      foreach($delete as $dn => $del){
+      foreach($tmp['del'] as $dn => $del){
         $ldap->cd($dn);
-        $ldap->rmDir($dn);
+        $ldap->rmdir_recursive($dn);
       }
 
-      /* Add || Update new DNS entries */
-      foreach($entries as $dn => $attrs){
+      /* Add || Update new DNS entries 
+       */
+      foreach($tmp['add'] as $dn => $attrs){
         $ldap->cd($dn);
-        $ldap->cat($dn);
-        
+        $ldap->cat($dn, array('dn'));
         if(count($ldap->fetch())){
           $ldap->cd($dn);
-//          $this->cleanup();
           $ldap->modify ($attrs); 
-
         }else{
           $ldap->cd($dn);
           $ldap->add($attrs);
         }
       }
+
+      /* Display errors 
+       */
+      if($ldap->get_error() != "Success"){
+        show_ldap_error("Record:".$ldap->get_error(), _("Saving terminal to DNS object failed")); 
+      }
     }
-    if($ldap->get_error() != "Success"){
-      show_ldap_error($ldap->get_error()); 
-    }
-    
   }
 
   /*  Create html table with all used record types
@@ -448,13 +665,12 @@ $ldap->modify ($this->attrs);
     $changeStateForRecords = "";
     
     if(!$this->DNS_is_account) {
-      $str = "<input type='submit' value='"._("Add")."' name='AddNewRecord' id='AddNewRecord' disabled>";
+      $str = "<input type='submit' value='"._("Add")."' name='AddNewRecord' id='AddNewRecord' disabled='disabled'>";
       return $str;
     }
  
     $str = "<table summary='' width='100%'>";
-    foreach($this->types as $key => $entry){
-        if($entry['status'] == "deleted") continue;
+    foreach($this->dnsEntry['RECORDS'] as $key => $entry){
 
         $changeStateForRecords.= "changeState('RecordTypeSelectedFor_".$key."');\n";
         $changeStateForRecords.= "changeState('RecordValue_".$key."');\n";
@@ -462,14 +678,14 @@ $ldap->modify ($this->attrs);
 
         $str.=" <tr>".
           "   <td>".$this->generateRecordListBox($entry['type'],"RecordTypeSelectedFor_".$key)."</td>".
-          "   <td><input type='text' value='".$entry['value']."' name='RecordValue_".$key."' id='RecordValue_".$key."'></td>".
-          "   <td><input type='submit' name='RemoveRecord_".$key."' value='"._("Delete")."' id='RemoveRecord_".$key."'></td>".
+          "   <td><input ".chkacl($this->acl,"termDNS")." type='text' value='".$entry['value']."' name='RecordValue_".$key."' id='RecordValue_".$key."'></td>".
+          "   <td><input ".chkacl($this->acl,"termDNS")." type='submit' name='RemoveRecord_".$key."' value='"._("Delete")."' id='RemoveRecord_".$key."'></td>".
           "</tr>";
     }
 
     $str.= "  <tr>".
            "    <td colspan=2 width='50%'></td><td>".
-           "      <input type='submit' value='"._("Add")."' name='AddNewRecord'>".
+           "      <input type='submit' value='"._("Add")."' name='AddNewRecord' ".chkacl($this->acl,"termDNS")." >".
            "    </td>".
            "  </tr>".
            "</table>";
@@ -477,10 +693,12 @@ $ldap->modify ($this->attrs);
     return($ret);
   }
 
-  /* Create a html select box which allows us to select different types of records */
+
+  /* Create a html select box which allows us to select different types of records 
+   */
   function generateRecordListBox($selected,$name)
   {
-    $str = "<select name='".$name."' id='".$name."'>";
+    $str = "<select ".chkacl($this->acl,"termDNS")."  name='".$name."' id='".$name."'>";
     foreach($this->RecordTypes as $type => $value){
       $use = "";
       if($type == $selected){
@@ -492,177 +710,119 @@ $ldap->modify ($this->attrs);
     return($str); 
   }
 
-  /* return all Zone names */
-  function get_Zones()
+  
+  function get_dhcp_host_entry()
   {
-    $ret = array();
-    $ldap = $this->config->get_ldap_link();
-    $ldap-> cd ($this->config->current['BASE']);
-    $ldap->search("(&(objectClass=dNSZone)(sOARecord=*))",array("*"));
-    
-    while($at = $ldap->fetch()){
-      if(preg_match("/\.in\-addr\.arpa/",$at['zoneName'][0])){
-        $name = preg_replace("/^zoneName=/","",$at['tXTRecord'][0]);
-        $ret[$name]['addr']= $at['zoneName'][0];
-      }else{
-        $name = $at['zoneName'][0];
-        $ret[$name]['name']= $at['zoneName'][0];
+    $attrs = array();
+    $dn = $this->get_dhcp_host_entry_dn();
+    if($dn){
+      $ldap = $this->config->get_ldap_link();
+      $ldap->cd($this->config->current['BASE']);
+      $ldap->cat($dn,array("*"));
+      if($ldap->count()){
+        $attrs = $ldap->fetch();
+        foreach($attrs as $key => $value){
+          if(is_numeric($key) || ($key == "count")){
+            unset($attrs[$key]);
+          }
+          if(is_array($value) && isset($value['count'])){
+            unset($attrs[$key]['count']);
+          }
+        }
       }
     }
+    return($attrs);
+  }
 
-    $tmp  =array();
-    foreach($ret as $name => $entry){
-      if((isset($entry['addr']))&&(isset($entry['name']))){
-        $tmp[$entry['addr']]=$entry['name'];
-      }
-    }
-    $ret = $tmp;
-    return($ret); 
-  } 
 
-  /* this is used to generate ldap friendly output of our 
-     dns configuration
-  */
-  function generate_LDAP_entries()
+  function get_dhcp_host_entry_dn()
   {
-    $entries = array();    
-    $delete  = array();
-
-    /* Generate Main Entry */
-    $dn = "relativeDomainName=".$this->cn.",".$this->dn;
-    $entries[$dn]['dNSClass']           = $this->dNSClass;      
-    $entries[$dn]['zoneName']           = $this->zoneName;      
-    $entries[$dn]['dNSTTL']             = $this->dNSTTL;      
-    $entries[$dn]['relativeDomainName'] = $this->cn;      
-
-    /* Generate cNAMERecord */
-    $aRecords = array();
-    foreach($this->types as $type){
-      if($type['type'] == "cNAMERecord"){
-          
-        $Cdn = "relativeDomainName=".$type['value'].",".$this->dn;
-        if($type['status']=="deleted"){
-          $delete [$type['dn']] = $Cdn;
-        }else{
-          $entries[$Cdn] = $entries[$dn];
-          $entries[$Cdn]['relativeDomainName']  = $type['value'];
-          $entries[$Cdn]['cNAMERecord']         = $this->cn.".".$this->zoneName;
-        }
-      }
-    }
+    $ldap = $this->config->get_ldap_link();
+    $ldap->cd($this->config->current['BASE']);
+    $ldap->search ("(&(objectClass=dhcpHost)(cn=".$this->cn."))",array("cn","dn"));
 
-    /* Generate tXTRecord */
-    $aRecords = array();
-    foreach($this->types as $type){
-      if(($type['type'] == "tXTRecord")&&($type['status']!="deleted")){
-        $entries[$dn]['tXTRecord'][] = $type['value'];
-      }
+    if($ldap->count()){
+      $attr = $ldap->fetch();
+      return($attr['dn']);
+    }else{
+      return("");
     }
+  }  
 
-    /* Generate mDRecord */
-    $aRecords = array();
-    foreach($this->types as $type){
-      if(($type['type'] == "mDRecord")&&($type['status']!="deleted")){
-        $entries[$dn]['mDRecord'][] = $type['value'];
-      }
-    }
 
-    /* Generate mXRecord */
-    $aRecords = array();
-    foreach($this->types as $type){
-      if(($type['type'] == "mXRecord")&&($type['status']!="deleted")){
-        $entries[$dn]['mXRecord'][] = $type['value'];
-      }
-    }
-    /* Generate hInfoRecord */
-    $aRecords = array();
-    foreach($this->types as $type){
-      if(($type['type'] == "hInfoRecord")&&($type['status']!="deleted")){
-        $entries[$dn]['hInfoRecord'][] = $type['value'];
-      }
-    }
+  function get_dhcp_parent_node()
+  {
+    return(preg_replace("/^cn=".normalizePreg($this->cn).",/","",$this->get_dhcp_host_entry_dn()));
+  }
 
-    /* Generate mInfoRecord */
-    $aRecords = array();
-    foreach($this->types as $type){
-      if(($type['type'] == "mInfoRecord")&&($type['status']!="deleted")){
-        $entries[$dn]['mInfoRecord'][] = $type['value'];
-      }
-    }
-    /* Generate aFSDBRecord */
-    $aRecords = array();
-    foreach($this->types as $type){
-      if(($type['type'] == "aFSDBRecord")&&($type['status']!="deleted")){
-        $entries[$dn]['aFSDBRecord'][] = $type['value'];
-      }
-    }
-    /* Generate some attrs  */
-    $arr = array("SigRecord","KeyRecord","aAAARecord","nSRecord",
-        "LocRecord","nXTRecord","sRVRecord","nAPTRRecord","kXRecord","certRecord","a6Record","dSRecord","sSHFPRecord","rRSIGRecord","nSECRecord");
-    $aRecords = array();
-    foreach($arr as $ar){
-      foreach($this->types as $type){
-        if(($type['type'] == $ar)&&($type['status']!="deleted")){
-          $entries[$dn][$ar][] = $type['value'];
-        }
-      }
+
+  function get_dhcp_parent_nodes()
+  {
+    $ldap = $this->config->get_ldap_link();
+    $ldap->cd($this->config->current['BASE']);
+    $ldap->search("(objectClass=dhcpService)",array("dhcpPrimaryDN"));
+    
+    $dhcp_dns = array();
+    while($attr = $ldap->fetch()){
+      $dhcp_dns[$attr['dn']] = $attr['dhcpPrimaryDN'][0];
     }
  
-    /* Generate A Records (IP Address relation) */
-    $aRecords = array();
-    foreach($this->types as $type){
-      if(($type['type'] == "aRecord")&&($type['status']!="deleted")){
-        $aRecords[] = $type['value'];
-      }
-    }
-    if(count($aRecords)){
-      
-      /* Add ipHostNumber as default aRecord */
-      $aRecords[] = $this->ipHostNumber;
-
-      $dn = "relativeDomainName=".$this->cn.",".$this->dn;
-      foreach($aRecords as $rec){
-        $entries[$dn]['aRecord'][] = $rec;      
+    foreach($dhcp_dns as $key => $pri_dns){
+      $ldap->cat($pri_dns,array("cn"));
+      $tmp = $ldap->fetch();
+      if(isset($tmp['cn'][0])){
+        $dhcp_dns[$key] = $tmp['cn'][0];
+      }else{
+        unset($dhcp_dns[$key]);
       }
     }
 
-    /* Generate pTRRecord Records */
-    foreach($this->types as $type){
-      if($type['type'] == "pTRRecord"){
-        $PTRdn= "relativeDomainName=".$type['value'].",".$this->dn;
-        if($type['status']=="deleted"){        
-          $delete [$type['dn']] = $PTRdn;
-        }else{
-          $zones = array_flip($this->Zones);
-          $zone = $zones[$this->zoneName];  
-          $entries[$PTRdn]['relativeDomainName'] = $type['value'];
-          $entries[$PTRdn]['pTRRecord']         = $this->cn.".".$this->zoneName;
-          $entries[$PTRdn]['zoneName']            =  $zone;
-        }
+    $tmp = $tmp2 = array();
+    foreach($dhcp_dns as $dn => $cn){
+      $ldap->cd($dn);
+      $ldap->search("(|(objectClass=dhcpService)(objectClass=dhcpGroup)".
+                    "(objectClass=dhcpSubnet)(objectClass=dhcpSharedNetwork))",array("cn"));
+      while($attr = $ldap->fetch()){
+        $tmp[$attr['dn']] = $attr['cn'][0];
       }
+      $tmp2 = array_merge($tmp2,$this->create_tree($tmp,preg_replace("/^[^,]+,/i","",$dn),"(".$cn.")&nbsp;"));
     }
+    return($tmp2);
+  }
 
-    /* add ObjectClasses */
-    foreach($entries as $key => $entry ){
-      $entries[$key]['objectClass']=array("top","dNSZone");
-      $entries[$key] = array_reverse($entries[$key]);
+  
+  /* this function returns the default ptr record entry */
+  function get_pTRRecord()
+  {
+    if(!empty($this->ipHostNumber) && isset($this->dnsEntry['zoneName']) && !empty($this->dnsEntry['zoneName'])){
+      $ldap = $this->config->get_ldap_link();
+      $ldap->cat(getDNSZoneDN($this->config,$this->dnsEntry['zoneName']));
+      $attrs = $ldap->fetch();
+      $tmp = array_flip($this->Zones);
+      $tmp = preg_replace("/^[^\/]*+\//","",$tmp[$this->dnsEntry['zoneName']]);
+      $tmp = trim(preg_replace("/\.in-addr.arpa$/","",$tmp));
+      $ptr = preg_replace("/^".normalizePreg(FlipIp($tmp))."\./","",$this->ipHostNumber);
+      return($ptr);
+    }else{
+      return(FALSE);
     }
+  }
 
-    /* Check if record type has changed, and if we need to delete this record attribute from ldap entry */
-    foreach($this->types as $type){
-      if(isset($type['inittype'])){
-        if(!isset($entries[$dn][$type['inittype']])){
-          $entries[$dn][$type['inittype']] = array();
+  
+  function create_tree($arr,$base,$current = "")
+  {
+    $ret = array();
+    foreach($arr as $r => $name){
+      $base_part = str_replace($base,"",$r);
+      if(preg_match("/^[a-z]*=".normalizePreg($name)."(|,)$/i",$base_part)){
+        $ret[$r] = $current.$name;
+        $tmp = $this->create_tree($arr,$r,$current.".&nbsp;");
+        foreach($tmp as $sub_key => $sub_name){
+          $ret[$sub_key] = $sub_name;
         }
-      }
+      } 
     }
-
-    $ret = array("entries"=> $entries,"delete"=>$delete);
-    return($ret); 
+    return($ret);
   }
 }