Code

Starting move
[gosa.git] / gosa-core / plugins / admin / systems / services / dns / class_termDNS.inc
1 <?php
3 class termDNS extends plugin
4 {
5   /* attribute list for save action */
6   var $ignore_account = true;
7   var $autonet        = false;
9   /* Basic informations 
10    */
11   var $attributes     = array("ipHostNumber","macAddress");
12   var $objectclasses  = array("whatever");
14   var $ipHostNumber   = "";    // IP address 
15   var $macAddress     = "";    // Mac address 
17   var $orig_ipHostNumber   = "";    // IP address 
18   var $orig_macAddress     = "";    // Mac address 
20   var $cn             = "";    // CN of currently edited device 
21   var $OrigCn         = "";    // Initial cn
22   var $IPisMust       = false;
23   var $MACisMust      = false;
24   var $dialog;
26   /* DCHP Attributes 
27    */
28   var $dhcpAttributes           = array("dhcpParentNode");
29   var $dhcpEnabled              = FALSE;
30   var $dhcp_is_Account          = FALSE;
31   var $dhcpParentNodes          = array();
32   var $dhcpParentNode           = "";
33   var $dhcpHostEntry            = array();
34   var $initial_dhcpParentNode   = "";
35   var $initial_dhcpHostEntry    = array();
36   var $initial_dhcp_is_Account  = FALSE;
38   var $used_ip_mac              = array();  
40   /* DNS attributes  
41    */
42   var $DNSattributes            = array("dNSClass","zoneName","dNSTTL");
43   var $DNS_is_account           = false;
44   var $initially_was_account = false;
45   var $dnsEntry                 = array();
46   var $DNSenabled               = false;
47   var $hide_dns_check_box       = FALSE;
49   /*  Terminal dns 
50    */
51   function termDNS (&$config, $parent,$objectClasses,$IPisMust = false)
52   {
53     /* We need to know which objectClasses are used, to store the ip/mac
54      * Because of different type of devices   
55      */ 
56     $this->parent         = $parent;
57     $this->objectclasses  =  $objectClasses;
58     $this->IPisMust       = $IPisMust;
60     plugin::plugin ($config, $parent->dn);
62     if(isset($this->attrs['cn'][0])){
63       $this->OrigCn = preg_replace("/\\\$\$/","",$this->attrs['cn'][0]);
64       $this->cn = preg_replace("/\\\$\$/","",$this->attrs['cn'][0]);
65     }
67  
68     /************
69      * DHCP 
70      ************/
72     /* Hide all dhcp specific code, if dhcp plugin is not present in config */
73     $dhcpEnabled = FALSE;
74     if($this->config->search("servdhcp","class",array("tabs"))){
75       $this->dhcpEnabled = TRUE;
76     }
77     if($this->dhcpEnabled){
78       $this->dhcpParentNodes = $this->get_dhcp_parent_nodes();
79       $this->dhcpParentNode  = $this->get_dhcp_parent_node();
80       if($this->dhcpParentNode){
81         $this->dhcp_is_Account = TRUE;
82         $this->initial_dhcp_is_Account = TRUE;
83         $this->dhcpHostEntry  = $this->get_dhcp_host_entry();    
84       }
85       $this->initial_dhcpHostEntry = $this->dhcpHostEntry;
86       $this->initial_dhcpParentNode= $this->dhcpParentNode;
87     }
90     /************
91      * Autonetwork hook 
92      ************/
93  
94     /* Do we have autonet support? */
95     if (isset($this->config->data['MAIN']['AUTO_NETWORK_HOOK'])){
96       $this->autonet= true;
97     }
100     /************
101      * DNS
102      ************/
103  
104     /* Hide all dns specific code, if dns is not available 
105      */
106     $DNSenabled = false;
107     foreach($this->config->data['TABS']['SERVERSERVICE'] as $tab){
108       if(preg_match("/^servdns$/",$tab['CLASS'])){
109         $this->DNSenabled = true;
110       }
111     }
112     if(!$this->DNSenabled){
113       $this->DNS_is_account = false;
114       return;
115     }
117     if($this->DNSenabled){
119       /* Get Zones  
120        */
121       $this->Zones        = getAvailableZones($config);
123       /* Get Entry 
124        */
125       $this->dnsEntry     = getDNSHostEntries($config,$this->OrigCn);
127       /* Remove A record which equals $this->ipHostNumber
128        */
129       $ptr = $this->get_pTRRecord();
130       foreach($this->dnsEntry['RECORDS'] as $key => $rec){
131         if(($rec['type'] == "aRecord") && ($rec['value'] == $this->ipHostNumber)){
132           unset($this->dnsEntry['RECORDS'][$key]);
133         }
134         if(($rec['type'] == "pTRRecord") && ($rec['value'] == $ptr)){
135           unset($this->dnsEntry['RECORDS'][$key]);
136         }
137       }
139       /* Get Record types 
140        */
141       $this->RecordTypes  = getDnsRecordTypes();
143       /* If there is at least one entry in this -> types, we have DNS enabled 
144        */
145       if($this->dnsEntry['exists']){
146         $this->DNS_is_account = true;
147       }else{
148         $this->DNS_is_account = false;
149       }
150     }
152     /* Create a list of used mac and ip addresses */
153     $ldap = $this->config->get_ldap_link();
154     $ldap->cd($this->config->current['BASE']);
155     $ldap->search("(|(macAddress=*)(ipHostNumber=*))",array("macAddress","ipHostNumber"));
156     while($attrs = $ldap->fetch()){
157       if(isset($attrs['ipHostNumber'][0])){
158         $this->used_ip_mac["ip:".$attrs['ipHostNumber'][0]] = "ip:".$attrs['ipHostNumber'][0];
159       }
160       if(isset($attrs['macAddress'][0])){
161         $this->used_ip_mac["mac:".$attrs['macAddress'][0]] = "mac:".$attrs['macAddress'][0];
162       }
163     } 
165     /* Save initial ip and mac values, to be able 
166         check if the used values are already in use */ 
167     $this->orig_ipHostNumber   = $this->ipHostNumber;  
168     $this->orig_macAddress     = $this->macAddress;
169  
170     /* Store initally account settings 
171      */
172     $this->initially_was_account = $this->DNS_is_account;
174     if($this->DNS_is_account){
175       new log("view","unknown/".get_class($this),$this->dn);
176     }
177   }
180   function netmaskIsCoherent($idZone) 
181   {
182     $netmask = FlipIp(str_replace(".in-addr.arpa","",getNameFromMix($idZone)));
183     if(!strstr($this->ipHostNumber, $netmask)){
184       return false;
185     }else{
186       return true;
187     }
188   }
191   function getVarsForSaving($attrs) 
192   {
193     foreach($this->attributes as $attr){
194       if(!empty($this->$attr)){
195         $attrs[$attr] = $this->$attr;
196       }
197     }
198     return($attrs); 
199   }
201   function execute()
202   {
203           /* Call parent execute */
204     $smarty= get_smarty();
206     $tmp = $this->plInfo();
207     foreach($tmp['plProvidedAcls'] as $name => $translation){
208       $smarty->assign($name."ACL",$this->getacl($name));
209     }
211     $display= "";
213     $smarty->assign("staticAddress", ""); 
214     $smarty->assign("autonet", $this->autonet);
215  
216     /* Check for autonet button */
217     if ($this->autonet && isset($_POST['autonet'])){
218       $cmd= $this->config->data['MAIN']['AUTO_NETWORK_HOOK'];
219       if(!empty($cmd) && $this->cn != ""){
220         $res = shell_exec($cmd." ".$this->cn);
221         if(!$res){
222           print_red(sprintf(_("Can't execute specified AUTO_NETWORK_HOOK '%s'. Please check your gosa.conf."),$cmd));
223         } else {
224           $res= split(';', trim($res));
225           if (isset($res[0]) && $res[0] != ""){
226             $this->ipHostNumber= $res[0];
227           }
228           if (isset($res[1]) && $res[1] != ""){
229             $this->macAddress= $res[1];
230           }
231         }
232       }
233     }
234     
235   
236     /**********
237      * DHCP Handling
238      **********/
239  
240     if(isset($_POST['dhcpEditOptions'])){
242       if(count($this->dhcpHostEntry) == 0){
243         $this->dialog = new dhcpHost($this->dhcpParentNode,TRUE);
244       }else{
245         $this->dialog = new dhcpHost($this->dhcpHostEntry,TRUE);
246       }
247       $this->dialog->cn = $this->cn; 
248       $this->dialog->dhcpHWAddress = "ethernet ".$this->macAddress; 
249       if(!empty($this->ipHostNumber)){
250         $this->dialog->statements['fixed-address'] = $this->ipHostNumber; 
251       }
252     }
254     if(isset($_POST['cancel_dhcp'])){
255       $this->dialog = FALSE; 
256     }
258     if(isset($_POST['save_dhcp'])){
259       $this->dialog->save_object();
260       
261       $msgs = $this->dialog->check(array());
262       if(count($msgs)){
263         foreach($msgs as $msg){
264           print_red($msg);
265         }
266       }else{
267         $this->dhcpHostEntry = $this->dialog->save();
268         $this->dialog = FALSE; 
269       }
270     }
272     if(is_object($this->dialog)){
273       $this->dialog->save_object();
274       return($this->dialog->execute());
275     }
276  
277     $smarty->assign("dhcpEnabled",    $this->dhcpEnabled);
278     $smarty->assign("dhcp_is_Account",$this->dhcp_is_Account);
279     $smarty->assign("dhcpParentNode", $this->dhcpParentNode);
280     $smarty->assign("dhcpParentNodes",$this->dhcpParentNodes);
281     $smarty->assign("dhcpParentNodeCnt",count($this->dhcpParentNodes));
284     /**********
285      * DNS Handling
286      **********/
288     /* There is no dns available
289      */
290     if($this->DNSenabled == false){
292       /* Is IP address must ? */
293       $smarty->assign("DNS_is_account",false);
294       $smarty->assign("IPisMust",(($this->IPisMust)||($this->DNS_is_account)));
296       /* Assign smarty all non DNs attributes */
297       foreach($this->attributes as $attr){
298         $smarty->assign($attr,$this->$attr);
299       }
300       $smarty->assign("staticAddress","<font class=\"must\">*</font>");
302       $display.= $smarty->fetch(get_template_path('network.tpl', TRUE));
303     }else{
304       $smarty->assign("DNS_is_account",true);
306       /* Add new empty array to our record list */
307       if(isset($_POST['AddNewRecord'])){
308         $this->dnsEntry['RECORDS'][]  =array("type"=>"aRecord","value"=>"");
309       }
311       /* propose_ip */
312       if(isset($_POST['propose_ip'])){
313         foreach($this->Zones as $key => $name){
314           if($name == $this->dnsEntry['zoneName']){
315             $net = FlipIp(str_replace(".in-addr.arpa","",getNameFromMix($key)));
316             $this->ipHostNumber = $this->generateRandomIp($net);
317           }
318         }
319       }
321       /* Handle all posts */
322       $only_once =true;
323       foreach($_POST as $name => $value){
325         /* Check if we have to delete a record entry */
326         if((preg_match("/RemoveRecord_/",$name))&&($only_once)) {
328           /* Avoid performing this once again */
329           $only_once = false;
331           /* Extract id for specified entry */
332           $id = preg_replace("/RemoveRecord_/","",$name);
333           $id = preg_replace("/_.*$/","",$id);
335           /* Delete this record, mark edited entries to be able to delete them */
336           if(isset($this->dnsEntry['RECORDS'][$id])){
337             unset($this->dnsEntry['RECORDS'][$id]);
338           }
339         }
340       }
341       /* Assign smarty all non DNs attributes */
342       foreach($this->attributes as $attr){
343         $smarty->assign($attr,$this->$attr);
344       }
346       /* Assign smarty all DNS attributes */
347       foreach($this->DNSattributes as $attr){
348         $smarty->assign($attr,$this->dnsEntry[$attr]);
349       }
351       /* Assign all needed vars */
352       $smarty->assign("DNSAccount",$this->DNS_is_account);
353       $smarty->assign("hide_dns_check_box",$this->hide_dns_check_box);
354   
355       $smarty->assign("Zones",$this->Zones);
356       $smarty->assign("ZoneCnt",count($this->Zones));
357       $smarty->assign("ZoneKeys",($this->Zones));
358       $smarty->assign("IPisMust",(($this->IPisMust)||($this->DNS_is_account)));
360       /* Create zone array */
361       $idZones = array();
362       foreach($this->Zones as $id => $zone){
363         if($this->netmaskIsCoherent($id)) {
364           $idZones[$id] = $zone;
365         }else{
366           $idZones[$id] = $zone."&nbsp;("._("Not matching").")";
367         }
368       }
369       $smarty->assign("Zones",$idZones);
370       $smarty->assign("ZoneKeys", $this->Zones);
372       $tmp = $this->generateRecordsList();
374       $changeStateForRecords = $tmp['changeStateForRecords'];
376       $smarty->assign("records",$tmp['str']);
377       $smarty->assign("changeStateForRecords",$changeStateForRecords);
378       $smarty->assign("staticAddress","<font class=\"must\">*</font>");
380       $display.= $smarty->fetch(get_template_path('network.tpl', TRUE));
381     }
382     return($display);
383   }
386   function remove_from_parent()
387   {
388     if($this->initially_was_account){
390       $ldap = $this->config->get_ldap_link();
392       $tmp = array();
393       $this->dnsEntry['exists'] = false;
394       $tmp = getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
396       /* Delete dns */
397       foreach($tmp['del'] as $dn => $del){
398         $ldap->cd($dn);
399         $ldap->rmdir_recursive($dn);
400         new log("remove","unknown/".get_class($this),$dn);
401       }
402     }
403   }
406   /* Save data to object */
407   function save_object()
408   {
410     if(isset($_POST['network_tpl_posted'])){
412       /* Save all posted vars */
413       plugin::save_object();
415       /* Handle DHCP Posts*/
416       if($this->dhcpEnabled && isset($_POST['network_tpl_posted'])){
417         foreach($this->dhcpAttributes as $attr){
418           if(isset($_POST[$attr])){
419             $this->$attr = $_POST[$attr];
420           }
421         }
422         if(isset($_POST['dhcp_is_Account'])){
423           $this->dhcp_is_Account = TRUE;
424         }else{
425           $this->dhcp_is_Account = FALSE;
426         }
427       }
429       /* Ge all non dns attributes (IP/MAC)*/
430       foreach($this->attributes as $attr){
431         if(isset($_POST[$attr]) && $this->acl_is_writeable($attr)){
432           $this->$attr = $_POST[$attr];
433         }
434       }
436       /* Check if DNS should be enabled / disabled */
437       if($this->DNS_is_account && $this->acl_is_removeable() && !isset($_POST['DNS_is_account'])){
438         $this->DNS_is_account = false;
439       }elseif(!$this->DNS_is_account && $this->acl_is_createable() && isset($_POST['DNS_is_account'])){
440         $this->DNS_is_account = true;
441       }
443       /* Get dns attributes */
444       if(($this->DNSenabled) && (isset($_POST['network_tpl_posted']))){
446         /* Check for posted record changes */
447         if(is_array($this->dnsEntry['RECORDS']) && $this->acl_is_writeable("Records")){
448           foreach($this->dnsEntry['RECORDS'] as $key => $value){
450             /* Check if type has changed */
451             if(isset($_POST['RecordTypeSelectedFor_'.$key])){
452               $this->dnsEntry['RECORDS'][$key]['type'] = $_POST['RecordTypeSelectedFor_'.$key];
453             }
454             /* Check if value has changed */
455             if(isset($_POST['RecordValue_'.$key])){
456               $this->dnsEntry['RECORDS'][$key]['value'] = $_POST['RecordValue_'.$key];
457             }
458           }
459         }
460         /* Get all basic DNS attributes (TTL, Clas ..)*/
461         foreach($this->DNSattributes as $attr){
462           if(isset($_POST[$attr]) && $this->acl_is_writeable($attr)){
463             $this->dnsEntry[$attr] = $_POST[$attr];
464           }
465         }
468       }
469       if($this->hide_dns_check_box){
470         $this->DNS_is_account = true;
471       }
472     }
473   }
476   /* Check supplied data */
477   function check()
478   {
479     /* Call common method to give check the hook */
480     $message= plugin::check();
482     if($this->dhcpEnabled && $this->dhcp_is_Account && $this->dhcpParentNode != "" && count($this->dhcpHostEntry) == 0){
483 #      $message[] =_("You have not configured your dhcp settings yet.");
484     }
485     
486     /* Check if mac and ip are already used */
487     if(!empty($this->ipHostNumber) && $this->DNS_is_account && 
488         $this->ipHostNumber != $this->orig_ipHostNumber && 
489         in_array("ip:".$this->ipHostNumber,$this->used_ip_mac)){
490       $message[] =_("The specified IP address is already in use.");
491     }
492     if(!empty($this->macAddress) && $this->dhcp_is_Account && 
493         $this->macAddress != $this->orig_macAddress && 
494         in_array("mac:".$this->macAddress,$this->used_ip_mac)){
495       print_red(sprintf(_("The specified MAC address '%s' for this system '%s' is already in use."),$this->macAddress,$this->cn));
496     }
498     /* Check if ip must be given
499      */  
500     if(($this->IPisMust)||($this->DNS_is_account)){
501       if (empty($this->ipHostNumber)){
502         $message[]= _("The required field 'IP-address' is not set.");
503       }
505       if (!is_ip($this->ipHostNumber)){
506         $message[]= _("Wrong IP format in field IP-address.");
507       }
508     }
510     /* Check if mac is empty 
511      */
512     if ($this->macAddress == "" ){
513       $message[]= _("The required field 'MAC-address' is not set.");
514     }
515     if(!is_mac($this->macAddress)){
516       $message[]=(_("The given macaddress is invalid. There must be 6 2byte segments seperated by ':'."));
517     }
519     /* only perfrom this checks if this is a valid DNS account */
520     if($this->DNS_is_account){
522       $checkArray = array();
523       $onlyOnce   = array();
525       //  $onlyOnce['cNAMERecord'] = 0;
526        $tmp = array_flip($this->Zones);
527        $tmp2 = $tmp[$this->dnsEntry['zoneName']];
528        if(!$this->netmaskIsCoherent($tmp2)){ //this->dnsEntry['zoneName'])){
529          $tmp2 = preg_replace("/^.*\//","",$tmp2);
530          $message[] =sprintf(_("The specified IP address '%s' is not matching the selected reverse zone entry '%s'."),$this->ipHostNumber,$tmp2);
531        }
533       /* Walk through all entries and detect duplicates or mismatches
534        */  
535       foreach($this->dnsEntry['RECORDS'] as $name => $values){
537         /* Count record values, to detect duplicate entries for a specific record
538          */
539         if(!isset($checkArray[$values['type']][$values['value']])){
540           $checkArray[$values['type']][$values['value']] = 0;
541         }else{
542           $message[] = sprintf(_("Found duplicate value for record type '%s'."),$values['type']);
543         }
545         /* Check if given entries in $onlyOnce are used more than once
546          */
547         if(isset($onlyOnce[$values['type']])){
548           $onlyOnce[$values['type']] ++;
549           if($onlyOnce[$values['type']] > 1){
550             $message[] = sprintf(_("Found more than one entry for the uniqe record type '%s'."),$values['type']);
551           }
552         }
554         /* Skip txt record ... 
555          */
556         if($values['type'] == "tXTRecord") continue;
558         /* Check if there is an aRecord defined which uses the same IP as used in IPhostAddress 
559          */
560         if(($values['type'] == "aRecord")&&($values['value'] == $this->ipHostNumber)){
561           $message[]=sprintf(_("The device IP '%s' is added as 'A Record', this will be done automatically, please remove the record."), 
562                $this->ipHostNumber);
563         }
565         /* only lower-case is allowed in record entries ... 
566          */
567         if($values['value'] != strtolower($values['value'])){
568           $message[] = sprintf(_("Only lowercase is allowed, please check your '%ss'."),$values['type']);
569         }
570       }
571     }
572     return ($message);
573   }
576   /* Save to LDAP */
577   function save()
578   {
579     $ldap= $this->config->get_ldap_link();
580   
581     $dn = $this->parent->dn;
582  
583     /*******************/ 
584     /* IP-MAC HANDLING */
585     /*******************/ 
587     /* $dn was posted as parameter */
588     $this->dn = $dn;
589     
590     /* Save DNS setting & ip/Mac*/
591     plugin::save();
593     /* Write back to ldap */
594     $ldap->cd($this->dn);
595     $this->cleanup();
596     $ldap->modify ($this->attrs); 
598     /****************/ 
599     /* DHCP HANDLING */
600     /****************/ 
601   
602     /* New entry */
603     if($this->dhcpEnabled){
605       if(count($this->dhcpHostEntry) == 0){
606         $this->dialog = new dhcpHost($this->dhcpParentNode,TRUE);
607         $this->dialog->cn = $this->cn;
608         $this->dialog->dhcpHWAddress = "ethernet ".$this->macAddress;
609         if(!empty($this->ipHostNumber)){
610           $this->dialog->statements['fixed-address'] = $this->ipHostNumber;
611         }
612         $this->dialog->execute();
613         $this->dialog->save_object(); 
614         $this->dhcpHostEntry = $this->dialog->save();
615         if(count($this->dhcpHostEntry['dhcpOption']) == 0){
616           $this->dhcpHostEntry['dhcpOption']= array("host-name ".$this->cn);
617         }
618       }
620       if(count($this->dhcpHostEntry) == 0){
621         $this->dialog = new dhcpHost($this->dhcpParentNode,TRUE);
622         $this->dialog->cn = $this->cn;
623         $this->dialog->dhcpHWAddress = "ethernet ".$this->macAddress;
624         if(!empty($this->ipHostNumber)){
625           $this->dialog->statements['fixed-address'] = $this->ipHostNumber;
626         }
627         $this->dialog->execute();
628         $this->dialog->save_object(); 
629         $this->dhcpHostEntry = $this->dialog->save();
630         if(count($this->dhcpHostEntry['dhcpOption']) == 0){
631           $this->dhcpHostEntry['dhcpOption']= array("host-name ".$this->cn);
632         }
633       }
635       /* Write mac address to dhcp settings */
636       if($this->dhcp_is_Account){
637         if(!isset($this->dhcpHostEntry['dhcpHWAddress'][0]) || 
638             !preg_match("/ethernet ".$this->macAddress."/",$this->dhcpHostEntry['dhcpHWAddress'][0])){
639           $this->dhcpHostEntry['dhcpHWAddress'] = array("ethernet ".$this->macAddress);
640           $this->dhcpHostEntry['MODIFIED'] = TRUE;
641         }
642       }
643   
645       /* Unset dhcpStatements if this attribute is empty  */
646       if(isset($this->dhcpHostEntry['dhcpStatements']) && 
647           ($this->dhcpHostEntry['dhcpStatements'] == "" || count($this->dhcpHostEntry['dhcpStatements']) == 0) ){
648         unset($this->dhcpHostEntry['dhcpStatements']);
649       }
650   
651       /* DHCP removed */
652       if($this->initial_dhcp_is_Account && !$this->dhcp_is_Account){
653         $ldap->rmdir_recursive($this->dhcpHostEntry['dn']);
654         show_ldap_error($ldap->get_error(),_("Removing dhcp entry for this object failed."));
656         $tmp = new servdhcp($this->config,$this->dhcpParentNode);
657         $tmp->handle_post_events("remove");
658       }
660       /* DHCP Added */
661       if(!$this->initial_dhcp_is_Account && $this->dhcp_is_Account){
662         $attrs = $this->dhcpHostEntry;
663         unset($attrs['MODIFIED']);
664         unset($attrs['dn']);
665         $ldap->cd("cn=".$this->cn.",".$this->dhcpParentNode);
666         $res = $ldap->add($attrs);
668         $tmp = new servdhcp($this->config,$this->dhcpParentNode);
669         $tmp->handle_post_events("add");
671         show_ldap_error($ldap->get_error(),_("Tried to add new dhcp entry failed."));
672       }
674       /* DHCP still activated */
675       if($this->initial_dhcp_is_Account && $this->dhcp_is_Account){
677         /* DHCP node changed */
678         if(($this->initial_dhcpParentNode != $this->dhcpParentNode) || 
679            ($this->cn != $this->OrigCn)){
680           $attrs = $this->dhcpHostEntry;
681           $attrs['cn'] = $this->cn;
682           unset($attrs['dn']);
683           unset($attrs['MODIFIED']);
684           $ldap->cd("cn=".$this->cn.",".$this->dhcpParentNode);
685           $res = $ldap->add($attrs);
687           $tmp = new servdhcp($this->config,$this->dhcpParentNode);
688           $tmp->handle_post_events("modify");
690           show_ldap_error($ldap->get_error(),_("Tried to add new dhcp entry failed."));
691           if($res){
692             $ldap->rmdir_recursive($this->dhcpHostEntry['dn']);
693             show_ldap_error($ldap->get_error(),_("Removing old dhcp entry failed."));
694           }
695         }
696          
697         /* SAME node but modified */ 
698         if(isset($this->dhcpHostEntry['MODIFIED']) && $this->dhcpHostEntry['MODIFIED'] == 1  && 
699             $this->initial_dhcpParentNode == $this->dhcpParentNode){
700           $attrs = $this->dhcpHostEntry;
701           unset($attrs['dn']);
702           unset($attrs['MODIFIED']);
703           $ldap->cd($this->dhcpHostEntry['dn']);
704           $ldap->modify($attrs);
705           
706           $tmp = new servdhcp($this->config,$this->dhcpParentNode);
707           $tmp->handle_post_events("modify");
709           show_ldap_error($ldap->get_error(),_("Modifying dhcp entry failed."));
710         }    
711       }
712     }
713       
715     /****************/ 
716     /* DNS HANDLING */
717     /****************/ 
719     /* If isn't DNS account but initially was DNS account 
720        remove all DNS entries 
721      */ 
722     if((!$this->DNSenabled) || ((!$this->DNS_is_account)&&(!$this->initially_was_account))){
723       return;
724     }else{
726       /* Add ipHostNumber to aRecords
727        */
728       $backup_dnsEntry = $this->dnsEntry;
729       if(!empty($this->ipHostNumber)){
730         $this->dnsEntry['RECORDS'][] = array("type"=>"aRecord","value"=>$this->ipHostNumber);
731         $ptr = $this->get_pTRRecord();
732         if(!empty($ptr)){
733           $this->dnsEntry['RECORDS'][] = array("type"=>"pTRRecord","value"=>$ptr);
734         } 
735       }
737       /* Create diff and follow instructions 
738        * If Account was disabled, remove account by setting exists to false
739        */
740       if((!$this->DNS_is_account)&&($this->initially_was_account)){  
741         $this->dnsEntry['exists'] = false;
742         $tmp = getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
743       }else{
744         $this->dnsEntry['exists'] = $this->DNS_is_account;
745         $tmp = getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
746       }   
748       /* move follwoing entries 
749        */
750       foreach($tmp['move'] as $src => $dst){
751         $this->recursive_move($src,$dst);
752       }
754       /* Delete dns */
755       foreach($tmp['del'] as $dn => $del){
756         $ldap->cd($dn);
757         $ldap->rmdir_recursive($dn);
758         new log("modify","unknown/".get_class($this),$dn,array("*"),$ldap->get_error());
759       }
761       /* Add || Update new DNS entries 
762        */
763       foreach($tmp['add'] as $dn => $attrs){
764         $ldap->cd($dn);
765         $ldap->cat($dn, array('dn'));
766         if(count($ldap->fetch())){
767           $ldap->cd($dn);
768           $ldap->modify ($attrs); 
769         }else{
770           $ldap->cd($dn);
771           $ldap->add($attrs);
772         }
773         new log("modify","unknown/".get_class($this),$dn,array_keys($attrs),$ldap->get_error());
774       }
777       /* Display errors 
778        */
779       if($ldap->get_error() != "Success"){
780         show_ldap_error($ldap->get_error(), sprintf(_("Saving of terminal/dns account with dn '%s' failed."),$this->dn));
781       }
783       $tmp2 = new servdns($this->config,$this->dn);
784       $tmp2->handle_post_events("modify");
786       $this->dnsEntry =  $backup_dnsEntry;
787     }
788   }
790   /*  Create html table with all used record types
791    */
792   function generateRecordsList()
793   {
794     $changeStateForRecords = "";
795     
796     if(!$this->DNS_is_account) {
797       $str = "<input type='submit' value='"._("Add")."' name='AddNewRecord' id='AddNewRecord' disabled='disabled'>";
798       return(array("str" => $str, "changeStateForRecords"=> ""));
799     }
800  
801     $str = "<table summary='' width='100%'>";
802     foreach($this->dnsEntry['RECORDS'] as $key => $entry){
804         $changeStateForRecords.= "changeState('RecordTypeSelectedFor_".$key."');\n";
805         $changeStateForRecords.= "changeState('RecordValue_".$key."');\n";
806         $changeStateForRecords.= "changeState('RemoveRecord_".$key."');\n";
808         $str.=" <tr>".
809           "   <td>".$this->generateRecordListBox($entry['type'],"RecordTypeSelectedFor_".$key)."</td>".
810           "   <td><input type='text' value='".$entry['value']."' name='RecordValue_".$key."' id='RecordValue_".$key."'></td>".
811           "   <td><input type='submit' name='RemoveRecord_".$key."' value='"._("Delete")."' id='RemoveRecord_".$key."'></td>".
812           "</tr>";
813     }
815     $str.= "  <tr>".
816            "    <td colspan=2 width='50%'></td><td>".
817            "      <input type='submit' value='"._("Add")."' name='AddNewRecord' id='AddNewRecord'>".
818            "    </td>".
819            "  </tr>".
820            "</table>";
821      $ret =  array("str" => $str, "changeStateForRecords" => $changeStateForRecords);
822     return($ret);
823   }
826   /* Create a html select box which allows us to select different types of records 
827    */
828   function generateRecordListBox($selected,$name)
829   {
830     $str = "<select name='".$name."' id='".$name."'>";
831     foreach($this->RecordTypes as $type => $value){
832       $use = "";
833       if($type == $selected){
834         $use = " selected ";
835       }
836       $str.="\n <option value='".$type."' ".$use.">".strtoupper(preg_replace("/record/i","",$type))."</option>";
837     }
838     $str.="</select>";
839     return($str); 
840   }
843   /* Return plugin informations for acl handling  */ 
844   static function plInfo()
845   {
846     $tmp =  array(
847         "plShortName"   => _("DNS"),
848         "plDescription" => _("DNS settings"),
849         "plSelfModify"  => FALSE,
850         "plDepends"     => array(),
851         "plPriority"    => 5,
852         "plSection"     => array("administration"),
853         "plCategory"    => array("workstation","terminal","phone","server","component","printer","winworkstation"),
855         "plProvidedAcls"=> array(
856           "ipHostNumber"  => _("IP address"),
857           "macAddress"    => _("MAC address"))
858         );
860     /* Hide all dns specific code, if dns is not available
861      */
862     foreach($_SESSION['config']->data['TABS']['SERVERSERVICE'] as $tab){
863       if(preg_match("/^servdns$/",$tab['CLASS'])){
864         $tmp['plProvidedAcls']["Records"]        = _("DNS records");
865         $tmp['plProvidedAcls']["zoneName"]       = _("Zone name");
866         $tmp['plProvidedAcls']["dNSTTL"]         = _("TTL");
867         break;
868       }
869     }
870     return($tmp);
871   }
873   
874   function get_dhcp_host_entry()
875   {
876     $attrs = array();
877     $dn = $this->get_dhcp_host_entry_dn();
878     if($dn){
879       $ldap = $this->config->get_ldap_link();
880       $ldap->cd($this->config->current['BASE']);
881       $ldap->cat($dn,array("*"));
882       if($ldap->count()){
883         $attrs = $ldap->fetch();
884         foreach($attrs as $key => $value){
885           if(is_numeric($key) || ($key == "count")){
886             unset($attrs[$key]);
887           }
888           if(is_array($value) && isset($value['count'])){
889             unset($attrs[$key]['count']);
890           }
891         }
892       }
893     }
894     return($attrs);
895   }
898   function get_dhcp_host_entry_dn()
899   {
900     $ldap = $this->config->get_ldap_link();
901     $ldap->cd($this->config->current['BASE']);
902     $ldap->search ("(&(objectClass=dhcpHost)(cn=".$this->cn."))",array("cn","dn"));
904     if($ldap->count()){
905       $attr = $ldap->fetch();
906       return($attr['dn']);
907     }else{
908       return("");
909     }
910   }  
913   function get_dhcp_parent_node()
914   {
915     return(preg_replace("/^cn=".normalizePreg($this->cn).",/","",$this->get_dhcp_host_entry_dn()));
916   }
919   function get_dhcp_parent_nodes()
920   {
921     $ldap = $this->config->get_ldap_link();
922     $ldap->cd($this->config->current['BASE']);
923     $ldap->search("(objectClass=dhcpService)",array("dhcpPrimaryDN"));
924     
925     $dhcp_dns = array();
926     while($attr = $ldap->fetch()){
927       $dhcp_dns[$attr['dn']] = $attr['dhcpPrimaryDN'][0];
928     }
929  
930     foreach($dhcp_dns as $key => $pri_dns){
931       $ldap->cat($pri_dns,array("cn"));
932       $tmp = $ldap->fetch();
933       if(isset($tmp['cn'][0])){
934         $dhcp_dns[$key] = $tmp['cn'][0];
935       }else{
936         unset($dhcp_dns[$key]);
937       }
938     }
940     $tmp = $tmp2 = array();
941     foreach($dhcp_dns as $dn => $cn){
942       $ldap->cd($dn);
943       $ldap->search("(|(objectClass=dhcpService)(objectClass=dhcpGroup)".
944                     "(objectClass=dhcpSubnet)(objectClass=dhcpSharedNetwork))",array("cn"));
945       while($attr = $ldap->fetch()){
946         $tmp[$attr['dn']] = $attr['cn'][0];
947       }
948       $tmp2 = array_merge($tmp2,$this->create_tree($tmp,preg_replace("/^[^,]+,/i","",$dn),"(".$cn.")&nbsp;"));
949     }
950     return($tmp2);
951   }
953   
954   /* this function returns the default ptr record entry */
955   function get_pTRRecord()
956   {
957     if(!empty($this->ipHostNumber) && isset($this->dnsEntry['zoneName']) && !empty($this->dnsEntry['zoneName'])){
958       $ldap = $this->config->get_ldap_link();
959       $ldap->cat(getDNSZoneDN($this->config,$this->dnsEntry['zoneName']));
960       $attrs = $ldap->fetch();
961       $tmp = array_flip($this->Zones);
962       $tmp = preg_replace("/^[^\/]*+\//","",$tmp[$this->dnsEntry['zoneName']]);
963       $tmp = trim(preg_replace("/\.in-addr.arpa$/","",$tmp));
964       $ptr = preg_replace("/^".normalizePreg(FlipIp($tmp))."\./","",$this->ipHostNumber);
965       return($ptr);
966     }else{
967       return(FALSE);
968     }
969   }
971   
972   function generateRandomIP($net = "")
973   {
974     $str = $net;
975     $cnt = 4;
976     while(substr_count($str,".") < 3 && $cnt > 0){
977       $str .= ".".rand(0,255);
978       $str = preg_replace("/\.\.*/",".",$str);
979       $str = trim($str,". ");
980       $cnt --;
981     }
982     return($str);
983   }
985   
986   function create_tree($arr,$base,$current = "")
987   {
988     $ret = array();
989     foreach($arr as $r => $name){
990       $base_part = str_replace($base,"",$r);
991       if(preg_match("/^[a-z]*=".normalizePreg($name)."(|,)$/i",$base_part)){
992         $ret[$r] = $current.$name;
993         $tmp = $this->create_tree($arr,$r,$current.".&nbsp;");
994         foreach($tmp as $sub_key => $sub_name){
995           $ret[$sub_key] = $sub_name;
996         }
997       } 
998     }
999     return($ret);
1000   }
1002   function force_dns()
1003   {
1004     if($this->DNSenabled){
1005       $this->DNS_is_account  = TRUE;
1006       $this->hide_dns_check_box = TRUE;
1007     }
1008   }
1011 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1012 ?>