Code

d5249a25d1d6d6b8ef3d2ff5f2b0a3ad6dafa51d
[gosa.git] / gosa-plugins / systems / admin / systems / class_termDNS.inc
1 <?php
2 /*
3  * This code is part of GOsa (http://www.gosa-project.org)
4  * Copyright (C) 2003-2008 GONICUS GmbH
5  *
6  * ID: $$Id$$
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
23 class termDNS extends plugin
24 {
25   /* attribute list for save action */
26   var $ignore_account = true;
28   /* Basic informations 
29    */
30   var $attributes     = array("ipHostNumber","macAddress");
31   var $objectclasses  = array("whatever");
33   var $ipHostNumber          = "";    // IP address 
34   var $additionalHostNumbers = array();
35   var $macAddress            = "";    // Mac address 
37   var $orig_ipHostNumber   = "";    // IP address 
38   var $orig_macAddress     = "";    // Mac address 
40   var $cn             = "";    // CN of currently edited device 
41   var $OrigCn         = "";    // Initial cn
42   var $IPisMust       = false;
43   var $MACisMust      = false;
44   var $dialog         = false;
46   /* DCHP Attributes 
47    */
48   var $dhcpAttributes           = array("dhcpParentNode");
49   var $dhcpEnabled              = FALSE;
50   var $dhcp_is_Account          = FALSE;
51   var $dhcpParentNodes          = array();
52   var $dhcpParentNode           = "";
53   var $dhcpHostEntry            = array();
54   var $initial_dhcpParentNode   = "";
55   var $initial_dhcpHostEntry    = array();
56   var $initial_dhcp_is_Account  = FALSE;
58   var $used_ip_mac              = array();  
60   /* DNS attributes  
61    */
62   var $DNSattributes            = array("dNSClass","zoneName","dNSTTL");
63   var $DNS_is_account           = false;
64   var $initially_was_account = false;
65   var $dnsEntry                 = array();
66   var $DNSenabled               = false;
67   var $hide_dns_check_box       = FALSE;
69   /*  Terminal dns 
70    */
71   function termDNS (&$config, $parent,$objectClasses,$IPisMust = false)
72   {
73     /* We need to know which objectClasses are used, to store the ip/mac
74      * Because of different type of devices   
75      */ 
76     $this->parent         = $parent;
77     $this->objectclasses  =  $objectClasses;
78     $this->IPisMust       = $IPisMust;
80     plugin::plugin ($config, $parent->dn);
82     if(isset($this->attrs['cn'][0])){
83       $this->OrigCn = preg_replace("/\\\$\$/","",$this->attrs['cn'][0]);
84       $this->cn = preg_replace("/\\\$\$/","",$this->attrs['cn'][0]);
85     }
87     /* Create list of additional ipHostNumber.
88      */
89     $this->additionalHostNumbers = array();
90     if(isset($this->attrs['ipHostNumber']) && $this->attrs['ipHostNumber']['count'] > 1){
91       for($i = 1 ; $i < $this->attrs['ipHostNumber']['count']; $i ++){
92         $this->additionalHostNumbers[] = $this->attrs['ipHostNumber'][$i];
93       }
94     }
95  
96     /************
97      * DHCP 
98      ************/
100     /* Hide all dhcp specific code, if dhcp plugin is not present in config */
101     $dhcpEnabled = FALSE;
102     if($this->config->search("servdhcp","class",array("tabs"))){
103       $this->dhcpEnabled = TRUE;
104     }
105     if($this->dhcpEnabled){
106       $this->dhcpParentNodes = $this->get_dhcp_parent_nodes();
107       $this->dhcpParentNode  = $this->get_dhcp_parent_node();
108       if($this->dhcpParentNode){
109         $this->dhcp_is_Account = TRUE;
110         $this->initial_dhcp_is_Account = TRUE;
111         $this->dhcpHostEntry  = $this->get_dhcp_host_entry();    
112       }
113       $this->initial_dhcpHostEntry = $this->dhcpHostEntry;
114       $this->initial_dhcpParentNode= $this->dhcpParentNode;
115     }
118     /************
119      * DNS
120      ************/
121  
122     /* Hide all dns specific code, if dns is not available 
123      */
124     $DNSenabled = false;
125     foreach($this->config->data['TABS']['SERVERSERVICE'] as $tab){
126       if(preg_match("/^servdns$/",$tab['CLASS'])){
127         $this->DNSenabled = true;
128       }
129     }
131     if(!class_available("DNS")){
132       $this->DNSenabled = FALSE;
133     }
134   
135     if(!$this->DNSenabled){
136       $this->DNS_is_account = false;
137       return;
138     }
140     if($this->DNSenabled){
142       /* Get Zones  
143        */
144       $this->Zones        = DNS::getAvailableZones($config);
146       /* Get Entry 
147        */
148       $this->dnsEntry     = DNS::getDNSHostEntries($config,$this->OrigCn);
150       /* Remove A record which equals $this->ipHostNumber
151        */
152       $ptr = $this->get_pTRRecord();
153       foreach($this->dnsEntry['RECORDS'] as $key => $rec){
154         if(($rec['type'] == "aRecord") && ($rec['value'] == $this->ipHostNumber)){
155           unset($this->dnsEntry['RECORDS'][$key]);
156         }
157         if(($rec['type'] == "pTRRecord") && ($rec['value'] == $ptr)){
158           unset($this->dnsEntry['RECORDS'][$key]);
159         }
160       }
162       /* Get Record types 
163        */
164       $this->RecordTypes  = DNS::getDnsRecordTypes();
166       /* If there is at least one entry in this -> types, we have DNS enabled 
167        */
168       if($this->dnsEntry['exists']){
169         $this->DNS_is_account = true;
170       }else{
171         $this->DNS_is_account = false;
172       }
173     }
175     /* Create a list of used mac and ip addresses.
177        ! We use this optically huge amount of code to fetch all 
178        Mac and IP addresses, because a simple search for mac and IP
179        over the whole ldap server was 10 to 20 times slower.
180      */
181     $deps  = array();
182     $ou = preg_replace("/,.*$/","",get_ou("systemsou"));
183     $a_ous = array(get_ou("serverou"),
184                   get_ou("terminalou"),
185                   get_ou("workstationou"),
186                   get_ou("printerou"),
187                   get_ou("phoneou"),
188                   get_ou("componentou"));
189   
190     $ldap = $this->config->get_ldap_link();
191     $ldap->cd($this->config->current['BASE']);
192     $ldap->search("(&(objectClass=organizationalUnit)(".$ou."))",array("dn"));
193     while($attrs = $ldap->fetch()){
194       foreach($a_ous as $allowed){
195         $deps[] = $allowed.$attrs['dn'];
196       }
197     }
199     foreach($deps as $dep){
200       $ldap->cd($dep);
201       $ldap->search("(|(macAddress=*)(ipHostNumber=*))",array("macAddress","ipHostNumber"));
202       while($attrs = $ldap->fetch()){
203         if(isset($attrs['ipHostNumber'][0])){
204           $this->used_ip_mac["ip:".$attrs['ipHostNumber'][0]] = "ip:".$attrs['ipHostNumber'][0];
205         }
206         if(isset($attrs['macAddress'][0])){
207           $this->used_ip_mac["mac:".$attrs['macAddress'][0]] = "mac:".$attrs['macAddress'][0];
208         }
209       } 
210     }
212     /* Save initial ip and mac values, to be able 
213         check if the used values are already in use */ 
214     $this->orig_ipHostNumber   = $this->ipHostNumber;  
215     $this->orig_macAddress     = $this->macAddress;
216  
217     /* Store initally account settings 
218      */
219     $this->initially_was_account = $this->DNS_is_account;
221     if($this->DNS_is_account){
222       new log("view","unknown/".get_class($this),$this->dn);
223     }
224   }
227   function netmaskIsCoherent($idZone) 
228   {
229     $netmask = DNS::FlipIp(str_replace(".in-addr.arpa","",DNS::getNameFromMix($idZone)));
230     if(!strstr($this->ipHostNumber, $netmask)){
231       return false;
232     }else{
233       return true;
234     }
235   }
238   function getVarsForSaving($attrs) 
239   {
240     foreach($this->attributes as $attr){
241       if(!empty($this->$attr)){
242         $attrs[$attr] = $this->$attr;
243       }
244     }
245     return($attrs); 
246   }
248   function execute()
249   {
250           /* Call parent execute */
251     $smarty= get_smarty();
253     $tmp = $this->plInfo();
254     foreach($tmp['plProvidedAcls'] as $name => $translation){
255       $smarty->assign($name."ACL",$this->getacl($name));
256     }
258     $display= "";
260     /**********
261      * Additional ipHostNumber handling 
262      **********/
263       
264     /* Add a new one */
265     foreach($_POST as $name => $value){
266       if(preg_match("/^additionalHostNumbers_add/",$name)){
267         $this->additionalHostNumbers[] = "";
268         break;
269       }
270     
271       /* Delete given entry */
272       if(preg_match("/^additionalHostNumbers_del_/",$name)){
273         $id = preg_replace("/^^additionalHostNumbers_del_([0-9]*)_.*/","\\1",$name);
274         if(isset($this->additionalHostNumbers[$id])){
275           unset($this->additionalHostNumbers[$id]);
276           $this->additionalHostNumbers = array_values($this->additionalHostNumbers);
277         }
278         break;
279       } 
280     }
281  
282     $smarty->assign("additionalHostNumbers",$this->additionalHostNumbers);
283     $smarty->assign("staticAddress", ""); 
284  
285     /**********
286      * Autonet completion
287      **********/
288  
289     /* Check for autonet button */
290     if (isset($_POST['autonet'])){
291       $d= new gosaSupportDaemon(TRUE, 0.5);
292       $res= $d->_send("<xml><header>gosa_network_completition</header><source>GOSA</source><target>GOSA</target><hostname>".$this->cn."</hostname></xml>", TRUE);
293       if (isset($res['XML']['IP'])){
294         $this->ipHostNumber= $res['XML']['IP'];
295       }
296       if (isset($res['XML']['MAC'])){
297         $this->macAddress= $res['XML']['MAC'];
298       }
299     }
301   
302     /**********
303      * DHCP Handling
304      **********/
305  
306     if(isset($_POST['dhcpEditOptions'])){
308       if(count($this->dhcpHostEntry) == 0){
309         $this->dialog = new dhcpHost($this->dhcpParentNode,TRUE);
310       }else{
311         $this->dialog = new dhcpHost($this->dhcpHostEntry,TRUE);
312       }
313       $this->dialog->cn = $this->cn; 
314       $this->dialog->dhcpHWAddress = "ethernet ".$this->macAddress; 
315       if(!empty($this->ipHostNumber)){
316         $this->dialog->statements['fixed-address'] = $this->ipHostNumber; 
317       }
318     }
320     if(isset($_POST['cancel_dhcp'])){
321       $this->dialog = FALSE; 
322     }
324     if(isset($_POST['save_dhcp'])){
325       $this->dialog->save_object();
326       
327       $msgs = $this->dialog->check(array());
328       if(count($msgs)){
329         foreach($msgs as $msg){
330           msg_dialog::display(_("Error"), $msg, ERROR_DIALOG);
331         }
332       }else{
333         $this->dhcpHostEntry = $this->dialog->save();
334         $this->dialog = FALSE; 
335       }
336     }
338     if(is_object($this->dialog)){
339       $this->dialog->save_object();
340       return($this->dialog->execute());
341     }
342  
343     $smarty->assign("dhcpEnabled",    $this->dhcpEnabled);
344     $smarty->assign("dhcp_is_Account",$this->dhcp_is_Account);
345     $smarty->assign("dhcpParentNode", $this->dhcpParentNode);
346     $smarty->assign("dhcpParentNodes",$this->dhcpParentNodes);
347     $smarty->assign("dhcpParentNodeCnt",count($this->dhcpParentNodes));
350     /**********
351      * DNS Handling
352      **********/
354     /* There is no dns available
355      */
356     $smarty->assign("DNS_is_account",$this->DNS_is_account);
357     $smarty->assign("DNSenabled",$this->DNSenabled);
358     if($this->DNSenabled == false){
360       /* Is IP address must ? */
361 #      $smarty->assign("DNS_is_account",false);
362       $smarty->assign("IPisMust",(($this->IPisMust)||($this->DNS_is_account)));
364       /* Assign smarty all non DNs attributes */
365       foreach($this->attributes as $attr){
366         $smarty->assign($attr,$this->$attr);
367       }
368       $smarty->assign("staticAddress","<font class=\"must\">*</font>");
370       $display.= $smarty->fetch(get_template_path('network.tpl', TRUE));
371     }else{
372  #     $smarty->assign("DNS_is_account",true);
374       /* Add new empty array to our record list */
375       if(isset($_POST['AddNewRecord'])){
376         $this->dnsEntry['RECORDS'][]  =array("type"=>"aRecord","value"=>"");
377       }
379       /* propose_ip */
380       if(isset($_POST['propose_ip'])){
381         foreach($this->Zones as $key => $name){
382           if($name == $this->dnsEntry['zoneName']){
383             $net = DNS::FlipIp(str_replace(".in-addr.arpa","",DNS::getNameFromMix($key)));
384             $this->ipHostNumber = $this->generateRandomIp($net);
385           }
386         }
387       }
389       /* Handle all posts */
390       $only_once =true;
391       foreach($_POST as $name => $value){
393         /* Check if we have to delete a record entry */
394         if((preg_match("/RemoveRecord_/",$name))&&($only_once)) {
396           /* Avoid performing this once again */
397           $only_once = false;
399           /* Extract id for specified entry */
400           $id = preg_replace("/RemoveRecord_/","",$name);
401           $id = preg_replace("/_.*$/","",$id);
403           /* Delete this record, mark edited entries to be able to delete them */
404           if(isset($this->dnsEntry['RECORDS'][$id])){
405             unset($this->dnsEntry['RECORDS'][$id]);
406           }
407         }
408       }
409       /* Assign smarty all non DNs attributes */
410       foreach($this->attributes as $attr){
411         $smarty->assign($attr,$this->$attr);
412       }
414       /* Assign smarty all DNS attributes */
415       foreach($this->DNSattributes as $attr){
416         $smarty->assign($attr,$this->dnsEntry[$attr]);
417       }
419       /* Assign all needed vars */
420  #     $smarty->assign("DNSAccount",$this->DNS_is_account);
421       $smarty->assign("hide_dns_check_box",$this->hide_dns_check_box);
422   
423       $smarty->assign("Zones",$this->Zones);
424       $smarty->assign("ZoneCnt",count($this->Zones));
425       $smarty->assign("ZoneKeys",($this->Zones));
426       $smarty->assign("IPisMust",(($this->IPisMust)||($this->DNS_is_account)));
428       /* Create zone array */
429       $idZones = array();
430       foreach($this->Zones as $id => $zone){
431         if($this->netmaskIsCoherent($id)) {
432           $idZones[$id] = $zone;
433         }else{
434           $idZones[$id] = $zone."&nbsp;("._("Not matching").")";
435         }
436       }
437       $smarty->assign("Zones",$idZones);
438       $smarty->assign("ZoneKeys", $this->Zones);
440       $tmp = $this->generateRecordsList();
442       $changeStateForRecords = $tmp['changeStateForRecords'];
444       $smarty->assign("records",$tmp['str']);
445       $smarty->assign("changeStateForRecords",$changeStateForRecords);
446       $smarty->assign("staticAddress","<font class=\"must\">*</font>");
448       $display.= $smarty->fetch(get_template_path('network.tpl', TRUE));
449     }
451     return($display);
452   }
455   function remove_from_parent()
456   {
457     if($this->initially_was_account){
459       $ldap = $this->config->get_ldap_link();
461       $tmp = array();
462       $this->dnsEntry['exists'] = false;
463       $tmp = DNS::getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
464   
465       /* Delete dns */
466       foreach($tmp['del'] as $dn => $del){
467         $ldap->cd($dn);
468         $ldap->rmdir_recursive($dn);
469         new log("remove","unknown/".get_class($this),$dn);
470         if (!$ldap->success()){
471           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_DEL, get_class()));
472         }
473       }
474     }
475   }
478   /* Save data to object */
479   function save_object()
480   {
482     if(isset($_POST['network_tpl_posted'])){
484       /* Save all posted vars */
485       plugin::save_object();
487       /******
488         Additional IP Host Numbers 
489        ******/
490   
491       /* Get posts for all additionally added ipHostNumbers */
492       foreach($this->additionalHostNumbers as $id => $value){
493         if(isset($_POST['additionalHostNumbers_'.$id])){
494           $this->additionalHostNumbers[$id] = get_post('additionalHostNumbers_'.$id);
495         }
496       } 
499       /******
500         DHCP posts
501        ******/
503       if($this->dhcpEnabled && isset($_POST['network_tpl_posted'])){
504         foreach($this->dhcpAttributes as $attr){
505           if(isset($_POST[$attr])){
506             $this->$attr = $_POST[$attr];
507           }
508         }
509         if(isset($_POST['dhcp_is_Account'])){
510           $this->dhcp_is_Account = TRUE;
511         }else{
512           $this->dhcp_is_Account = FALSE;
513         }
514       }
516       /* Ge all non dns attributes (IP/MAC)*/
517       foreach($this->attributes as $attr){
518         if(isset($_POST[$attr]) && $this->acl_is_writeable($attr)){
519           $this->$attr = $_POST[$attr];
520         }
521       }
524       /******
525         DNS posts
526        ******/
528       /* Check if DNS should be enabled / disabled */
529       if($this->DNS_is_account && $this->acl_is_removeable() && !isset($_POST['DNS_is_account'])){
530         $this->DNS_is_account = false;
531       }elseif(!$this->DNS_is_account && $this->acl_is_createable() && isset($_POST['DNS_is_account'])){
532         $this->DNS_is_account = true;
533       }
535       /* Get dns attributes */
536       if(($this->DNSenabled) && (isset($_POST['network_tpl_posted']))){
538         /* Check for posted record changes */
539         if(is_array($this->dnsEntry['RECORDS']) && $this->acl_is_writeable("Records")){
540           foreach($this->dnsEntry['RECORDS'] as $key => $value){
542             /* Check if type has changed */
543             if(isset($_POST['RecordTypeSelectedFor_'.$key])){
544               $this->dnsEntry['RECORDS'][$key]['type'] = $_POST['RecordTypeSelectedFor_'.$key];
545             }
546             /* Check if value has changed */
547             if(isset($_POST['RecordValue_'.$key])){
548               $this->dnsEntry['RECORDS'][$key]['value'] = $_POST['RecordValue_'.$key];
549             }
550           }
551         }
552         /* Get all basic DNS attributes (TTL, Clas ..)*/
553         foreach($this->DNSattributes as $attr){
554           if(isset($_POST[$attr]) && $this->acl_is_writeable($attr)){
555             $this->dnsEntry[$attr] = $_POST[$attr];
556           }
557         }
560       }
561       if($this->hide_dns_check_box){
562         $this->DNS_is_account = true;
563       }
564     }
565   }
568   /* Check supplied data */
569   function check()
570   {
571     /* Call common method to give check the hook */
572     $message= plugin::check();
574     /******
575       check additional IP Host Numbers 
576      ******/
578     foreach($this->additionalHostNumbers as $id => $value){
579       if(!tests::is_ip($value)){
580         $message[]= msgPool::invalid(sprintf(_("IP address #%s"),($id +2)), "", "", "192.168.1.10");
581       }
582     }
585     /* Check if mac and ip are already used */
586     if(!empty($this->ipHostNumber) && $this->DNS_is_account && 
587         $this->ipHostNumber != $this->orig_ipHostNumber && 
588         in_array("ip:".$this->ipHostNumber,$this->used_ip_mac)){
589       $message[]= msgPool::duplicated(_("IP address"));
590     }
591     if(!empty($this->macAddress) && $this->dhcp_is_Account && 
592         $this->macAddress != $this->orig_macAddress && 
593         in_array("mac:".$this->macAddress,$this->used_ip_mac)){
594       $message[]= msgPool::duplicated(_("MAC address"));
595     }
597     /* Check if ip must be given
598      */  
599     if(($this->IPisMust)||($this->DNS_is_account)){
600       if (empty($this->ipHostNumber)){
601         $message[]= msgPool::required(_("IP address"));
602       }elseif (!tests::is_ip($this->ipHostNumber)){
603         $message[]= msgPool::invalid(_("IP address"), "", "", "192.168.1.10");
604       }
605     }
607     /* Check if mac is empty 
608      */
609     if ($this->macAddress == "" ){
610       $message[]= msgPool::required(_("MAC address"));
611     }elseif(!tests::is_mac($this->macAddress)){
612       $message[]= msgPool::invalid(_("MAC address"), "", "", "00:0C:7F:31:33:F1");
613     }
615     /* only perfrom this checks if this is a valid DNS account */
616     if($this->DNS_is_account){
618       $checkArray = array();
619       $onlyOnce   = array();
621       //  $onlyOnce['cNAMERecord'] = 0;
622        $tmp = array_flip($this->Zones);
623        $tmp2 = $tmp[$this->dnsEntry['zoneName']];
624        if(!$this->netmaskIsCoherent($tmp2)){ //this->dnsEntry['zoneName'])){
625          $tmp2 = preg_replace("/^.*\//","",$tmp2);
626          $message[] =sprintf(_("The IP address '%s' is not part of the selected reverse zone '%s'!"),$this->ipHostNumber,$tmp2);
627        }
629       /* Walk through all entries and detect duplicates or mismatches
630        */  
631       foreach($this->dnsEntry['RECORDS'] as $name => $values){
633         /* Count record values, to detect duplicate entries for a specific record
634          */
635         if(!isset($checkArray[$values['type']][$values['value']])){
636           $checkArray[$values['type']][$values['value']] = 0;
637         }else{
638           $message[] = sprintf(_("Record type '%s' is duplicated!"),$values['type']);
639         }
641         /* Check if given entries in $onlyOnce are used more than once
642          */
643         if(isset($onlyOnce[$values['type']])){
644           $onlyOnce[$values['type']] ++;
645           if($onlyOnce[$values['type']] > 1){
646             $message[] = sprintf(_("Uniq record type '%s' is duplicated!"),$values['type']);
647           }
648         }
650         /* Skip txt record ... 
651          */
652         if($values['type'] == "tXTRecord") continue;
654         /* Check if there is an aRecord defined which uses the same IP as used in IPhostAddress 
655          */
656         if(($values['type'] == "aRecord")&&($values['value'] == $this->ipHostNumber)){
657           #TODO: Where's the problem here?
658           $message[]=sprintf(_("The IP address '%s' will be added as 'A Record', this will be done automatically, please remove the record."), 
659                $this->ipHostNumber);
660         }
662         /* only lower-case is allowed in record entries ... 
663          */
664         if($values['value'] != strtolower($values['value'])){
665           #TODO: What's in values['value']? Something for a propper message?
666           $message[] = sprintf(_("Only lowercase records are allowed, please check your '%ss'."),$values['type']);
667         }
668       }
669     }
670     return ($message);
671   }
674   /* Save to LDAP */
675   function save()
676   {
677     $ldap= $this->config->get_ldap_link();
678   
679     $dn = $this->parent->dn;
680  
681     /*******************/ 
682     /* IP-MAC HANDLING */
683     /*******************/ 
685     /* $dn was posted as parameter */
686     $this->dn = $dn;
687     
688     /* Save DNS setting & ip/Mac*/
689     plugin::save();
691     /* Add all additional ipHostNumbers now 
692      */
693     if(!empty($this->ipHostNumber)){
694       $this->attrs['ipHostNumber'] = array($this->ipHostNumber);
695     }
696     foreach($this->additionalHostNumbers as $value){
697       $this->attrs['ipHostNumber'][] = $value;
698     }
700     /* Write back to ldap */
701     $ldap->cd($this->dn);
702     $this->cleanup();
703     $ldap->modify ($this->attrs); 
705     /****************/ 
706     /* DHCP HANDLING */
707     /****************/ 
708   
709     /* New entry */
710     if($this->dhcpEnabled){
712       if(count($this->dhcpHostEntry) == 0){
713         $this->dialog = new dhcpHost($this->dhcpParentNode,TRUE);
714         $this->dialog->cn = $this->cn;
715         $this->dialog->dhcpHWAddress = "ethernet ".$this->macAddress;
716         if(!empty($this->ipHostNumber)){
717           $this->dialog->statements['fixed-address'] = $this->ipHostNumber;
718         }
719         $this->dialog->execute();
720         $this->dialog->save_object(); 
721         $this->dhcpHostEntry = $this->dialog->save();
722         if(count($this->dhcpHostEntry['dhcpOption']) == 0){
723           $this->dhcpHostEntry['dhcpOption']= array("host-name ".$this->cn);
724         }
725       }
727       /* Write mac address to dhcp settings */
728       if($this->dhcp_is_Account){
729         if(!isset($this->dhcpHostEntry['dhcpHWAddress'][0]) || 
730             !preg_match("/ethernet ".$this->macAddress."/",$this->dhcpHostEntry['dhcpHWAddress'][0])){
731           $this->dhcpHostEntry['dhcpHWAddress'] = array("ethernet ".$this->macAddress);
732           $this->dhcpHostEntry['MODIFIED'] = TRUE;
733         }
734       }
736       /* Updated IP host number */
737       if($this->dhcp_is_Account){
738         foreach($this->dhcpHostEntry['dhcpStatements'] as $id => $value){
739           if(preg_match("/^fixed-address/",$value)){
740             $this->dhcpHostEntry['dhcpStatements'][$id] = "fixed-address ".$this->ipHostNumber; 
741             $this->dhcpHostEntry['MODIFIED'] = TRUE;
742           }
743         }
744       }
746       /* Unset dhcpStatements if this attribute is empty  */
747       if(isset($this->dhcpHostEntry['dhcpStatements']) && 
748           ($this->dhcpHostEntry['dhcpStatements'] == "" || count($this->dhcpHostEntry['dhcpStatements']) == 0) ){
749         unset($this->dhcpHostEntry['dhcpStatements']);
750       }
751   
752       /* DHCP removed */
753       if($this->initial_dhcp_is_Account && !$this->dhcp_is_Account){
754         $ldap->rmdir_recursive($this->dhcpHostEntry['dn']);
755         if (!$ldap->success()){
756           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dhcpHostEntry['dn'], LDAP_DEL, get_class()));
757         }
759         $tmp = new servdhcp($this->config,$this->dhcpParentNode);
760         $tmp->handle_post_events("remove");
761       }
763       /* DHCP Added */
764       if(!$this->initial_dhcp_is_Account && $this->dhcp_is_Account){
765         $attrs = $this->dhcpHostEntry;
766         unset($attrs['MODIFIED']);
767         unset($attrs['dn']);
768         $ldap->cd("cn=".$this->cn.",".$this->dhcpParentNode);
769         $res = $ldap->add($attrs);
771         $tmp = new servdhcp($this->config,$this->dhcpParentNode);
772         $tmp->handle_post_events("add");
774         if (!$ldap->success()){
775           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=".$this->cn.",".$this->dhcpParentNode, LDAP_ADD, get_class()));
776         }
777       }
779       /* DHCP still activated */
780       if($this->initial_dhcp_is_Account && $this->dhcp_is_Account){
782         /* DHCP node changed */
783         if(($this->initial_dhcpParentNode != $this->dhcpParentNode) || 
784            ($this->cn != $this->OrigCn)){
785           $attrs = $this->dhcpHostEntry;
786           $attrs['cn'] = $this->cn;
787           unset($attrs['dn']);
788           unset($attrs['MODIFIED']);
789           $ldap->cd("cn=".$this->cn.",".$this->dhcpParentNode);
790           $res = $ldap->add($attrs);
792           $tmp = new servdhcp($this->config,$this->dhcpParentNode);
793           $tmp->handle_post_events("modify");
795           if (!$ldap->success()){
796             msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=".$this->cn.",".$this->dhcpParentNode, LDAP_ADD, get_class()));
797           }
798           if($res){
799             $ldap->rmdir_recursive($this->dhcpHostEntry['dn']);
800             if (!$ldap->success()){
801               msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dhcpHostEntry['dn'], LDAP_DEL, get_class()));
802             }
803           }
804         }
805          
806         /* SAME node but modified */ 
807         if(isset($this->dhcpHostEntry['MODIFIED']) && $this->dhcpHostEntry['MODIFIED'] == 1  && 
808             $this->initial_dhcpParentNode == $this->dhcpParentNode){
809           $attrs = $this->dhcpHostEntry;
810           unset($attrs['dn']);
811           unset($attrs['MODIFIED']);
812           $ldap->cd($this->dhcpHostEntry['dn']);
813           $ldap->modify($attrs);
814           
815           $tmp = new servdhcp($this->config,$this->dhcpParentNode);
816           $tmp->handle_post_events("modify");
818           if (!$ldap->success()){
819             msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dhcpHostEntry['dn'], LDAP_MOD, get_class()));
820           }
821         }    
822       }
823     }
824     $this->dialog = FALSE; 
826     /****************/ 
827     /* DNS HANDLING */
828     /****************/ 
830     /* If isn't DNS account but initially was DNS account 
831        remove all DNS entries 
832      */ 
833     if((!$this->DNSenabled) || ((!$this->DNS_is_account)&&(!$this->initially_was_account))){
834       return;
835     }else{
837       /* Add ipHostNumber to aRecords
838        */
839       $backup_dnsEntry = $this->dnsEntry;
840       if(!empty($this->ipHostNumber)){
841         $this->dnsEntry['RECORDS'][] = array("type"=>"aRecord","value"=>$this->ipHostNumber);
842         $ptr = $this->get_pTRRecord();
843         if(!empty($ptr)){
844           $this->dnsEntry['RECORDS'][] = array("type"=>"pTRRecord","value"=>$ptr);
845         } 
846       }
848       /* Create diff and follow instructions 
849        * If Account was disabled, remove account by setting exists to false
850        */
851       if((!$this->DNS_is_account)&&($this->initially_was_account)){  
852         $this->dnsEntry['exists'] = false;
853         $tmp = DNS::getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
854       }else{
855         $this->dnsEntry['exists'] = $this->DNS_is_account;
856         $tmp = DNS::getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
857       }   
859       /* move follwoing entries 
860        */
861       foreach($tmp['move'] as $src => $dst){
862         $this->recursive_move($src,$dst);
863       }
865       /* Delete dns */
866       foreach($tmp['del'] as $dn => $del){
867         $ldap->cd($dn);
868         $ldap->rmdir_recursive($dn);
869         new log("modify","unknown/".get_class($this),$dn,array("*"),$ldap->get_error());
870       }
872       /* Add || Update new DNS entries 
873        */
874       foreach($tmp['add'] as $dn => $attrs){
875         $ldap->cd($dn);
876         $ldap->cat($dn, array('dn'));
877         if(count($ldap->fetch())){
878           $ldap->cd($dn);
879           $ldap->modify ($attrs); 
880         }else{
881           $ldap->cd($dn);
882           $ldap->add($attrs);
883         }
884         new log("modify","unknown/".get_class($this),$dn,array_keys($attrs),$ldap->get_error());
885       }
888       /* Display errors 
889        */
890       if (!$ldap->success()){
891         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, 0, get_class()));
892       }
894       $tmp2 = new servdns($this->config,$this->dn);
895       $tmp2->handle_post_events("modify");
897       $this->dnsEntry =  $backup_dnsEntry;
898     }
899   }
901   /*  Create html table with all used record types
902    */
903   function generateRecordsList()
904   {
905     $changeStateForRecords = "";
906     
907     if(!$this->DNS_is_account) {
908       $str = "<input type='submit' value='"._("Add")."' name='AddNewRecord' id='AddNewRecord' disabled='disabled'>";
909       return(array("str" => $str, "changeStateForRecords"=> ""));
910     }
911  
912     $str = "<table summary='' width='100%'>";
913     foreach($this->dnsEntry['RECORDS'] as $key => $entry){
915         $changeStateForRecords.= "changeState('RecordTypeSelectedFor_".$key."');\n";
916         $changeStateForRecords.= "changeState('RecordValue_".$key."');\n";
917         $changeStateForRecords.= "changeState('RemoveRecord_".$key."');\n";
919         $str.=" <tr>".
920           "   <td>".$this->generateRecordListBox($entry['type'],"RecordTypeSelectedFor_".$key)."</td>".
921           "   <td><input type='text' value='".$entry['value']."' name='RecordValue_".$key."' id='RecordValue_".$key."'></td>".
922           "   <td><input type='submit' name='RemoveRecord_".$key."' value='"._("Delete")."' id='RemoveRecord_".$key."'></td>".
923           "</tr>";
924     }
926     $str.= "  <tr>".
927            "    <td colspan=2 width='50%'></td><td>".
928            "      <input type='submit' value='"._("Add")."' name='AddNewRecord' id='AddNewRecord'>".
929            "    </td>".
930            "  </tr>".
931            "</table>";
932      $ret =  array("str" => $str, "changeStateForRecords" => $changeStateForRecords);
933     return($ret);
934   }
937   /* Create a html select box which allows us to select different types of records 
938    */
939   function generateRecordListBox($selected,$name)
940   {
941     $str = "<select name='".$name."' id='".$name."'>";
942     foreach($this->RecordTypes as $type => $value){
943       $use = "";
944       if($type == $selected){
945         $use = " selected ";
946       }
947       $str.="\n <option value='".$type."' ".$use.">".strtoupper(preg_replace("/record/i","",$type))."</option>";
948     }
949     $str.="</select>";
950     return($str); 
951   }
954   /* Return plugin informations for acl handling  */ 
955   static function plInfo()
956   {
957     $tmp =  array(
958         "plShortName"   => _("DNS"),
959         "plDescription" => _("DNS settings"),
960         "plSelfModify"  => FALSE,
961         "plDepends"     => array(),
962         "plPriority"    => 5,
963         "plSection"     => array("administration"),
964         "plCategory"    => array("workstation","terminal","phone","server","component","printer","winworkstation"),
966         "plProvidedAcls"=> array(
967           "ipHostNumber"  => _("IP address"),
968           "macAddress"    => _("MAC address"))
969         );
971     /* Hide all dns specific code, if dns is not available
972      */
973     $config = session::get('config');
974     foreach($config->data['TABS']['SERVERSERVICE'] as $tab){
975       if(preg_match("/^servdns$/",$tab['CLASS'])){
976         $tmp['plProvidedAcls']["Records"]        = _("DNS records");
977         $tmp['plProvidedAcls']["zoneName"]       = _("Zone name");
978         $tmp['plProvidedAcls']["dNSTTL"]         = _("TTL");
979         break;
980       }
981     }
982     return($tmp);
983   }
985   
986   function get_dhcp_host_entry()
987   {
988     $attrs = array();
989     $dn = $this->get_dhcp_host_entry_dn();
990     if($dn){
991       $ldap = $this->config->get_ldap_link();
992       $ldap->cd($this->config->current['BASE']);
993       $ldap->cat($dn,array("*"));
994       if($ldap->count()){
995         $attrs = $ldap->fetch();
996         foreach($attrs as $key => $value){
997           if(is_numeric($key) || ($key == "count")){
998             unset($attrs[$key]);
999           }
1000           if(is_array($value) && isset($value['count'])){
1001             unset($attrs[$key]['count']);
1002           }
1003         }
1004       }
1005     }
1006     return($attrs);
1007   }
1010   function get_dhcp_host_entry_dn()
1011   {
1012     $ldap = $this->config->get_ldap_link();
1013     $ldap->cd($this->config->current['BASE']);
1014     $ldap->search ("(&(objectClass=dhcpHost)(cn=".$this->cn."))",array("cn","dn"));
1016     if($ldap->count()){
1017       $attr = $ldap->fetch();
1018       return($attr['dn']);
1019     }else{
1020       return("");
1021     }
1022   }  
1025   function get_dhcp_parent_node()
1026   {
1027     return(preg_replace("/^cn=".normalizePreg($this->cn).",/","",$this->get_dhcp_host_entry_dn()));
1028   }
1031   function get_dhcp_parent_nodes()
1032   {
1033     $ldap = $this->config->get_ldap_link();
1034     $ldap->cd($this->config->current['BASE']);
1035     $ldap->search("(objectClass=dhcpService)",array("dhcpPrimaryDN"));
1036     
1037     $dhcp_dns = array();
1038     while($attr = $ldap->fetch()){
1039       $dhcp_dns[$attr['dn']] = $attr['dhcpPrimaryDN'][0];
1040     }
1041  
1042     foreach($dhcp_dns as $key => $pri_dns){
1043       $ldap->cat($pri_dns,array("cn"));
1044       $tmp = $ldap->fetch();
1045       if(isset($tmp['cn'][0])){
1046         $dhcp_dns[$key] = $tmp['cn'][0];
1047       }else{
1048         unset($dhcp_dns[$key]);
1049       }
1050     }
1052     $tmp = $tmp2 = array();
1053     foreach($dhcp_dns as $dn => $cn){
1054       $ldap->cd($dn);
1055       $ldap->search("(|(objectClass=dhcpService)(objectClass=dhcpGroup)".
1056                     "(objectClass=dhcpSubnet)(objectClass=dhcpSharedNetwork))",array("cn"));
1057       while($attr = $ldap->fetch()){
1058         $tmp[$attr['dn']] = $attr['cn'][0];
1059       }
1060       $tmp2 = array_merge($tmp2,$this->create_tree($tmp,preg_replace("/^[^,]+,/i","",$dn),"(".$cn.")&nbsp;"));
1061     }
1062     return($tmp2);
1063   }
1065   
1066   /* this function returns the default ptr record entry */
1067   function get_pTRRecord()
1068   {
1069     if(!empty($this->ipHostNumber) && isset($this->dnsEntry['zoneName']) && !empty($this->dnsEntry['zoneName'])){
1070       $ldap = $this->config->get_ldap_link();
1071       $ldap->cat(DNS::getDNSZoneDN($this->config,$this->dnsEntry['zoneName']));
1072       $attrs = $ldap->fetch();
1073       $tmp = array_flip($this->Zones);
1074       $tmp = preg_replace("/^[^\/]*+\//","",$tmp[$this->dnsEntry['zoneName']]);
1075       $tmp = trim(preg_replace("/\.in-addr.arpa$/","",$tmp));
1076       $ptr = preg_replace("/^".normalizePreg(DNS::FlipIp($tmp))."\./","",$this->ipHostNumber);
1077       return($ptr);
1078     }else{
1079       return(FALSE);
1080     }
1081   }
1083   
1084   function generateRandomIP($net = "")
1085   {
1086     $str = $net;
1087     $cnt = 4;
1088     while(substr_count($str,".") < 3 && $cnt > 0){
1089       $str .= ".".rand(0,255);
1090       $str = preg_replace("/\.\.*/",".",$str);
1091       $str = trim($str,". ");
1092       $cnt --;
1093     }
1094     return($str);
1095   }
1097   
1098   function create_tree($arr,$base,$current = "")
1099   {
1100     $ret = array();
1101     foreach($arr as $r => $name){
1102       $base_part = str_replace($base,"",$r);
1103       if(preg_match("/^[a-z]*=".normalizePreg($name)."(|,)$/i",$base_part)){
1104         $ret[$r] = $current.$name;
1105         $tmp = $this->create_tree($arr,$r,$current.".&nbsp;");
1106         foreach($tmp as $sub_key => $sub_name){
1107           $ret[$sub_key] = $sub_name;
1108         }
1109       } 
1110     }
1111     return($ret);
1112   }
1114   function force_dns()
1115   {
1116     if($this->DNSenabled){
1118       /* Only force DNS account, if we have at least on dns Zone */
1119       if(count($this->Zones)){
1120         $this->DNS_is_account  = TRUE;
1121         $this->hide_dns_check_box = TRUE;
1122       }
1123     }
1124   }
1127 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1128 ?>