Code

940da119d8d0a9bfaa0d6e82b66ed036019ca4d6
[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     }
130     if(!$this->DNSenabled){
131       $this->DNS_is_account = false;
132       return;
133     }
135     if($this->DNSenabled){
137       /* Get Zones  
138        */
139       $this->Zones        = DNS::getAvailableZones($config);
141       /* Get Entry 
142        */
143       $this->dnsEntry     = DNS::getDNSHostEntries($config,$this->OrigCn);
145       /* Remove A record which equals $this->ipHostNumber
146        */
147       $ptr = $this->get_pTRRecord();
148       foreach($this->dnsEntry['RECORDS'] as $key => $rec){
149         if(($rec['type'] == "aRecord") && ($rec['value'] == $this->ipHostNumber)){
150           unset($this->dnsEntry['RECORDS'][$key]);
151         }
152         if(($rec['type'] == "pTRRecord") && ($rec['value'] == $ptr)){
153           unset($this->dnsEntry['RECORDS'][$key]);
154         }
155       }
157       /* Get Record types 
158        */
159       $this->RecordTypes  = DNS::getDnsRecordTypes();
161       /* If there is at least one entry in this -> types, we have DNS enabled 
162        */
163       if($this->dnsEntry['exists']){
164         $this->DNS_is_account = true;
165       }else{
166         $this->DNS_is_account = false;
167       }
168     }
170     /* Create a list of used mac and ip addresses.
172        ! We use this optically huge amount of code to fetch all 
173        Mac and IP addresses, because a simple search for mac and IP
174        over the whole ldap server was 10 to 20 times slower.
175      */
176     $deps  = array();
177     $ou = preg_replace("/,.*$/","",get_ou("systemsou"));
178     $a_ous = array(get_ou("serverou"),
179                   get_ou("terminalou"),
180                   get_ou("workstationou"),
181                   get_ou("printerou"),
182                   get_ou("phoneou"),
183                   get_ou("componentou"));
184   
185     $ldap = $this->config->get_ldap_link();
186     $ldap->cd($this->config->current['BASE']);
187     $ldap->search("(&(objectClass=organizationalUnit)(".$ou."))",array("dn"));
188     while($attrs = $ldap->fetch()){
189       foreach($a_ous as $allowed){
190         $deps[] = $allowed.$attrs['dn'];
191       }
192     }
194     foreach($deps as $dep){
195       $ldap->cd($dep);
196       $ldap->search("(|(macAddress=*)(ipHostNumber=*))",array("macAddress","ipHostNumber"));
197       while($attrs = $ldap->fetch()){
198         if(isset($attrs['ipHostNumber'][0])){
199           $this->used_ip_mac["ip:".$attrs['ipHostNumber'][0]] = "ip:".$attrs['ipHostNumber'][0];
200         }
201         if(isset($attrs['macAddress'][0])){
202           $this->used_ip_mac["mac:".$attrs['macAddress'][0]] = "mac:".$attrs['macAddress'][0];
203         }
204       } 
205     }
207     /* Save initial ip and mac values, to be able 
208         check if the used values are already in use */ 
209     $this->orig_ipHostNumber   = $this->ipHostNumber;  
210     $this->orig_macAddress     = $this->macAddress;
211  
212     /* Store initally account settings 
213      */
214     $this->initially_was_account = $this->DNS_is_account;
216     if($this->DNS_is_account){
217       new log("view","unknown/".get_class($this),$this->dn);
218     }
219   }
222   function netmaskIsCoherent($idZone) 
223   {
224     $netmask = DNS::FlipIp(str_replace(".in-addr.arpa","",DNS::getNameFromMix($idZone)));
225     if(!strstr($this->ipHostNumber, $netmask)){
226       return false;
227     }else{
228       return true;
229     }
230   }
233   function getVarsForSaving($attrs) 
234   {
235     foreach($this->attributes as $attr){
236       if(!empty($this->$attr)){
237         $attrs[$attr] = $this->$attr;
238       }
239     }
240     return($attrs); 
241   }
243   function execute()
244   {
245           /* Call parent execute */
246     $smarty= get_smarty();
248     $tmp = $this->plInfo();
249     foreach($tmp['plProvidedAcls'] as $name => $translation){
250       $smarty->assign($name."ACL",$this->getacl($name));
251     }
253     $display= "";
255     /**********
256      * Additional ipHostNumber handling 
257      **********/
258       
259     /* Add a new one */
260     foreach($_POST as $name => $value){
261       if(preg_match("/^additionalHostNumbers_add/",$name)){
262         $this->additionalHostNumbers[] = "";
263         break;
264       }
265     
266       /* Delete given entry */
267       if(preg_match("/^additionalHostNumbers_del_/",$name)){
268         $id = preg_replace("/^^additionalHostNumbers_del_([0-9]*)_.*/","\\1",$name);
269         if(isset($this->additionalHostNumbers[$id])){
270           unset($this->additionalHostNumbers[$id]);
271           $this->additionalHostNumbers = array_values($this->additionalHostNumbers);
272         }
273         break;
274       } 
275     }
276  
277     $smarty->assign("additionalHostNumbers",$this->additionalHostNumbers);
278     $smarty->assign("staticAddress", ""); 
279  
280     /**********
281      * Autonet completion
282      **********/
283  
284     /* Check for autonet button */
285     if (isset($_POST['autonet'])){
286       $d= new gosaSupportDaemon(TRUE, 0.5);
287       $res= $d->_send("<xml><header>gosa_network_completition</header><source>GOSA</source><target>GOSA</target><hostname>".$this->cn."</hostname></xml>", TRUE);
288       if (isset($res['XML']['IP'])){
289         $this->ipHostNumber= $res['XML']['IP'];
290       }
291       if (isset($res['XML']['MAC'])){
292         $this->macAddress= $res['XML']['MAC'];
293       }
294     }
296   
297     /**********
298      * DHCP Handling
299      **********/
300  
301     if(isset($_POST['dhcpEditOptions'])){
303       if(count($this->dhcpHostEntry) == 0){
304         $this->dialog = new dhcpHost($this->dhcpParentNode,TRUE);
305       }else{
306         $this->dialog = new dhcpHost($this->dhcpHostEntry,TRUE);
307       }
308       $this->dialog->cn = $this->cn; 
309       $this->dialog->dhcpHWAddress = "ethernet ".$this->macAddress; 
310       if(!empty($this->ipHostNumber)){
311         $this->dialog->statements['fixed-address'] = $this->ipHostNumber; 
312       }
313     }
315     if(isset($_POST['cancel_dhcp'])){
316       $this->dialog = FALSE; 
317     }
319     if(isset($_POST['save_dhcp'])){
320       $this->dialog->save_object();
321       
322       $msgs = $this->dialog->check(array());
323       if(count($msgs)){
324         foreach($msgs as $msg){
325           msg_dialog::display(_("Error"), $msg, ERROR_DIALOG);
326         }
327       }else{
328         $this->dhcpHostEntry = $this->dialog->save();
329         $this->dialog = FALSE; 
330       }
331     }
333     if(is_object($this->dialog)){
334       $this->dialog->save_object();
335       return($this->dialog->execute());
336     }
337  
338     $smarty->assign("dhcpEnabled",    $this->dhcpEnabled);
339     $smarty->assign("dhcp_is_Account",$this->dhcp_is_Account);
340     $smarty->assign("dhcpParentNode", $this->dhcpParentNode);
341     $smarty->assign("dhcpParentNodes",$this->dhcpParentNodes);
342     $smarty->assign("dhcpParentNodeCnt",count($this->dhcpParentNodes));
345     /**********
346      * DNS Handling
347      **********/
349     /* There is no dns available
350      */
351     $smarty->assign("DNS_is_account",$this->DNS_is_account);
352     $smarty->assign("DNSenabled",$this->DNSenabled);
353     if($this->DNSenabled == false){
355       /* Is IP address must ? */
356 #      $smarty->assign("DNS_is_account",false);
357       $smarty->assign("IPisMust",(($this->IPisMust)||($this->DNS_is_account)));
359       /* Assign smarty all non DNs attributes */
360       foreach($this->attributes as $attr){
361         $smarty->assign($attr,$this->$attr);
362       }
363       $smarty->assign("staticAddress","<font class=\"must\">*</font>");
365       $display.= $smarty->fetch(get_template_path('network.tpl', TRUE));
366     }else{
367  #     $smarty->assign("DNS_is_account",true);
369       /* Add new empty array to our record list */
370       if(isset($_POST['AddNewRecord'])){
371         $this->dnsEntry['RECORDS'][]  =array("type"=>"aRecord","value"=>"");
372       }
374       /* propose_ip */
375       if(isset($_POST['propose_ip'])){
376         foreach($this->Zones as $key => $name){
377           if($name == $this->dnsEntry['zoneName']){
378             $net = DNS::FlipIp(str_replace(".in-addr.arpa","",DNS::getNameFromMix($key)));
379             $this->ipHostNumber = $this->generateRandomIp($net);
380           }
381         }
382       }
384       /* Handle all posts */
385       $only_once =true;
386       foreach($_POST as $name => $value){
388         /* Check if we have to delete a record entry */
389         if((preg_match("/RemoveRecord_/",$name))&&($only_once)) {
391           /* Avoid performing this once again */
392           $only_once = false;
394           /* Extract id for specified entry */
395           $id = preg_replace("/RemoveRecord_/","",$name);
396           $id = preg_replace("/_.*$/","",$id);
398           /* Delete this record, mark edited entries to be able to delete them */
399           if(isset($this->dnsEntry['RECORDS'][$id])){
400             unset($this->dnsEntry['RECORDS'][$id]);
401           }
402         }
403       }
404       /* Assign smarty all non DNs attributes */
405       foreach($this->attributes as $attr){
406         $smarty->assign($attr,$this->$attr);
407       }
409       /* Assign smarty all DNS attributes */
410       foreach($this->DNSattributes as $attr){
411         $smarty->assign($attr,$this->dnsEntry[$attr]);
412       }
414       /* Assign all needed vars */
415  #     $smarty->assign("DNSAccount",$this->DNS_is_account);
416       $smarty->assign("hide_dns_check_box",$this->hide_dns_check_box);
417   
418       $smarty->assign("Zones",$this->Zones);
419       $smarty->assign("ZoneCnt",count($this->Zones));
420       $smarty->assign("ZoneKeys",($this->Zones));
421       $smarty->assign("IPisMust",(($this->IPisMust)||($this->DNS_is_account)));
423       /* Create zone array */
424       $idZones = array();
425       foreach($this->Zones as $id => $zone){
426         if($this->netmaskIsCoherent($id)) {
427           $idZones[$id] = $zone;
428         }else{
429           $idZones[$id] = $zone."&nbsp;("._("Not matching").")";
430         }
431       }
432       $smarty->assign("Zones",$idZones);
433       $smarty->assign("ZoneKeys", $this->Zones);
435       $tmp = $this->generateRecordsList();
437       $changeStateForRecords = $tmp['changeStateForRecords'];
439       $smarty->assign("records",$tmp['str']);
440       $smarty->assign("changeStateForRecords",$changeStateForRecords);
441       $smarty->assign("staticAddress","<font class=\"must\">*</font>");
443       $display.= $smarty->fetch(get_template_path('network.tpl', TRUE));
444     }
446     return($display);
447   }
450   function remove_from_parent()
451   {
452     if($this->initially_was_account){
454       $ldap = $this->config->get_ldap_link();
456       $tmp = array();
457       $this->dnsEntry['exists'] = false;
458       $tmp = DNS::getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
459   
460       /* Delete dns */
461       foreach($tmp['del'] as $dn => $del){
462         $ldap->cd($dn);
463         $ldap->rmdir_recursive($dn);
464         new log("remove","unknown/".get_class($this),$dn);
465         if (!$ldap->success()){
466           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_DEL, get_class()));
467         }
468       }
469     }
470   }
473   /* Save data to object */
474   function save_object()
475   {
477     if(isset($_POST['network_tpl_posted'])){
479       /* Save all posted vars */
480       plugin::save_object();
482       /******
483         Additional IP Host Numbers 
484        ******/
485   
486       /* Get posts for all additionally added ipHostNumbers */
487       foreach($this->additionalHostNumbers as $id => $value){
488         if(isset($_POST['additionalHostNumbers_'.$id])){
489           $this->additionalHostNumbers[$id] = get_post('additionalHostNumbers_'.$id);
490         }
491       } 
494       /******
495         DHCP posts
496        ******/
498       if($this->dhcpEnabled && isset($_POST['network_tpl_posted'])){
499         foreach($this->dhcpAttributes as $attr){
500           if(isset($_POST[$attr])){
501             $this->$attr = $_POST[$attr];
502           }
503         }
504         if(isset($_POST['dhcp_is_Account'])){
505           $this->dhcp_is_Account = TRUE;
506         }else{
507           $this->dhcp_is_Account = FALSE;
508         }
509       }
511       /* Ge all non dns attributes (IP/MAC)*/
512       foreach($this->attributes as $attr){
513         if(isset($_POST[$attr]) && $this->acl_is_writeable($attr)){
514           $this->$attr = $_POST[$attr];
515         }
516       }
519       /******
520         DNS posts
521        ******/
523       /* Check if DNS should be enabled / disabled */
524       if($this->DNS_is_account && $this->acl_is_removeable() && !isset($_POST['DNS_is_account'])){
525         $this->DNS_is_account = false;
526       }elseif(!$this->DNS_is_account && $this->acl_is_createable() && isset($_POST['DNS_is_account'])){
527         $this->DNS_is_account = true;
528       }
530       /* Get dns attributes */
531       if(($this->DNSenabled) && (isset($_POST['network_tpl_posted']))){
533         /* Check for posted record changes */
534         if(is_array($this->dnsEntry['RECORDS']) && $this->acl_is_writeable("Records")){
535           foreach($this->dnsEntry['RECORDS'] as $key => $value){
537             /* Check if type has changed */
538             if(isset($_POST['RecordTypeSelectedFor_'.$key])){
539               $this->dnsEntry['RECORDS'][$key]['type'] = $_POST['RecordTypeSelectedFor_'.$key];
540             }
541             /* Check if value has changed */
542             if(isset($_POST['RecordValue_'.$key])){
543               $this->dnsEntry['RECORDS'][$key]['value'] = $_POST['RecordValue_'.$key];
544             }
545           }
546         }
547         /* Get all basic DNS attributes (TTL, Clas ..)*/
548         foreach($this->DNSattributes as $attr){
549           if(isset($_POST[$attr]) && $this->acl_is_writeable($attr)){
550             $this->dnsEntry[$attr] = $_POST[$attr];
551           }
552         }
555       }
556       if($this->hide_dns_check_box){
557         $this->DNS_is_account = true;
558       }
559     }
560   }
563   /* Check supplied data */
564   function check()
565   {
566     /* Call common method to give check the hook */
567     $message= plugin::check();
569     /******
570       check additional IP Host Numbers 
571      ******/
573     foreach($this->additionalHostNumbers as $id => $value){
574       if(!tests::is_ip($value)){
575         $message[]= msgPool::invalid(sprintf(_("IP address #%s"),($id +2)), "", "", "192.168.1.10");
576       }
577     }
580     /* Check if mac and ip are already used */
581     if(!empty($this->ipHostNumber) && $this->DNS_is_account && 
582         $this->ipHostNumber != $this->orig_ipHostNumber && 
583         in_array("ip:".$this->ipHostNumber,$this->used_ip_mac)){
584       $message[]= msgPool::duplicated(_("IP address"));
585     }
586     if(!empty($this->macAddress) && $this->dhcp_is_Account && 
587         $this->macAddress != $this->orig_macAddress && 
588         in_array("mac:".$this->macAddress,$this->used_ip_mac)){
589       $message[]= msgPool::duplicated(_("MAC address"));
590     }
592     /* Check if ip must be given
593      */  
594     if(($this->IPisMust)||($this->DNS_is_account)){
595       if (empty($this->ipHostNumber)){
596         $message[]= msgPool::required(_("IP address"));
597       }
599       if (!tests::is_ip($this->ipHostNumber)){
600         $message[]= msgPool::invalid(_("IP address"), "", "", "192.168.1.10");
601       }
602     }
604     /* Check if mac is empty 
605      */
606     if ($this->macAddress == "" ){
607       $message[]= msgPool::required(_("IP address"));
608     }
609     if(!tests::is_mac($this->macAddress)){
610       $message[]= msgPool::invalid(_("MAC address"), "", "", "00:0C:7F:31:33:F1");
611     }
613     /* only perfrom this checks if this is a valid DNS account */
614     if($this->DNS_is_account){
616       $checkArray = array();
617       $onlyOnce   = array();
619       //  $onlyOnce['cNAMERecord'] = 0;
620        $tmp = array_flip($this->Zones);
621        $tmp2 = $tmp[$this->dnsEntry['zoneName']];
622        if(!$this->netmaskIsCoherent($tmp2)){ //this->dnsEntry['zoneName'])){
623          $tmp2 = preg_replace("/^.*\//","",$tmp2);
624          $message[] =sprintf(_("The IP address '%s' is not part of the selected reverse zone '%s'!"),$this->ipHostNumber,$tmp2);
625        }
627       /* Walk through all entries and detect duplicates or mismatches
628        */  
629       foreach($this->dnsEntry['RECORDS'] as $name => $values){
631         /* Count record values, to detect duplicate entries for a specific record
632          */
633         if(!isset($checkArray[$values['type']][$values['value']])){
634           $checkArray[$values['type']][$values['value']] = 0;
635         }else{
636           $message[] = sprintf(_("Record type '%s' is duplicated!"),$values['type']);
637         }
639         /* Check if given entries in $onlyOnce are used more than once
640          */
641         if(isset($onlyOnce[$values['type']])){
642           $onlyOnce[$values['type']] ++;
643           if($onlyOnce[$values['type']] > 1){
644             $message[] = sprintf(_("Uniq record type '%s' is duplicated!"),$values['type']);
645           }
646         }
648         /* Skip txt record ... 
649          */
650         if($values['type'] == "tXTRecord") continue;
652         /* Check if there is an aRecord defined which uses the same IP as used in IPhostAddress 
653          */
654         if(($values['type'] == "aRecord")&&($values['value'] == $this->ipHostNumber)){
655           #TODO: Where's the problem here?
656           $message[]=sprintf(_("The IP address '%s' will be added as 'A Record', this will be done automatically, please remove the record."), 
657                $this->ipHostNumber);
658         }
660         /* only lower-case is allowed in record entries ... 
661          */
662         if($values['value'] != strtolower($values['value'])){
663           #TODO: What's in values['value']? Something for a propper message?
664           $message[] = sprintf(_("Only lowercase records are allowed, please check your '%ss'."),$values['type']);
665         }
666       }
667     }
668     return ($message);
669   }
672   /* Save to LDAP */
673   function save()
674   {
675     $ldap= $this->config->get_ldap_link();
676   
677     $dn = $this->parent->dn;
678  
679     /*******************/ 
680     /* IP-MAC HANDLING */
681     /*******************/ 
683     /* $dn was posted as parameter */
684     $this->dn = $dn;
685     
686     /* Save DNS setting & ip/Mac*/
687     plugin::save();
689     /* Add all additional ipHostNumbers now 
690      */
691     if(!empty($this->ipHostNumber)){
692       $this->attrs['ipHostNumber'] = array($this->ipHostNumber);
693     }
694     foreach($this->additionalHostNumbers as $value){
695       $this->attrs['ipHostNumber'][] = $value;
696     }
698     /* Write back to ldap */
699     $ldap->cd($this->dn);
700     $this->cleanup();
701     $ldap->modify ($this->attrs); 
703     /****************/ 
704     /* DHCP HANDLING */
705     /****************/ 
706   
707     /* New entry */
708     if($this->dhcpEnabled){
710       if(count($this->dhcpHostEntry) == 0){
711         $this->dialog = new dhcpHost($this->dhcpParentNode,TRUE);
712         $this->dialog->cn = $this->cn;
713         $this->dialog->dhcpHWAddress = "ethernet ".$this->macAddress;
714         if(!empty($this->ipHostNumber)){
715           $this->dialog->statements['fixed-address'] = $this->ipHostNumber;
716         }
717         $this->dialog->execute();
718         $this->dialog->save_object(); 
719         $this->dhcpHostEntry = $this->dialog->save();
720         if(count($this->dhcpHostEntry['dhcpOption']) == 0){
721           $this->dhcpHostEntry['dhcpOption']= array("host-name ".$this->cn);
722         }
723       }
725       /* Write mac address to dhcp settings */
726       if($this->dhcp_is_Account){
727         if(!isset($this->dhcpHostEntry['dhcpHWAddress'][0]) || 
728             !preg_match("/ethernet ".$this->macAddress."/",$this->dhcpHostEntry['dhcpHWAddress'][0])){
729           $this->dhcpHostEntry['dhcpHWAddress'] = array("ethernet ".$this->macAddress);
730           $this->dhcpHostEntry['MODIFIED'] = TRUE;
731         }
732       }
734       /* Updated IP host number */
735       if($this->dhcp_is_Account){
736         foreach($this->dhcpHostEntry['dhcpStatements'] as $id => $value){
737           if(preg_match("/^fixed-address/",$value)){
738             $this->dhcpHostEntry['dhcpStatements'][$id] = "fixed-address ".$this->ipHostNumber; 
739             $this->dhcpHostEntry['MODIFIED'] = TRUE;
740           }
741         }
742       }
744       /* Unset dhcpStatements if this attribute is empty  */
745       if(isset($this->dhcpHostEntry['dhcpStatements']) && 
746           ($this->dhcpHostEntry['dhcpStatements'] == "" || count($this->dhcpHostEntry['dhcpStatements']) == 0) ){
747         unset($this->dhcpHostEntry['dhcpStatements']);
748       }
749   
750       /* DHCP removed */
751       if($this->initial_dhcp_is_Account && !$this->dhcp_is_Account){
752         $ldap->rmdir_recursive($this->dhcpHostEntry['dn']);
753         if (!$ldap->success()){
754           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dhcpHostEntry['dn'], LDAP_DEL, get_class()));
755         }
757         $tmp = new servdhcp($this->config,$this->dhcpParentNode);
758         $tmp->handle_post_events("remove");
759       }
761       /* DHCP Added */
762       if(!$this->initial_dhcp_is_Account && $this->dhcp_is_Account){
763         $attrs = $this->dhcpHostEntry;
764         unset($attrs['MODIFIED']);
765         unset($attrs['dn']);
766         $ldap->cd("cn=".$this->cn.",".$this->dhcpParentNode);
767         $res = $ldap->add($attrs);
769         $tmp = new servdhcp($this->config,$this->dhcpParentNode);
770         $tmp->handle_post_events("add");
772         if (!$ldap->success()){
773           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=".$this->cn.",".$this->dhcpParentNode, LDAP_ADD, get_class()));
774         }
775       }
777       /* DHCP still activated */
778       if($this->initial_dhcp_is_Account && $this->dhcp_is_Account){
780         /* DHCP node changed */
781         if(($this->initial_dhcpParentNode != $this->dhcpParentNode) || 
782            ($this->cn != $this->OrigCn)){
783           $attrs = $this->dhcpHostEntry;
784           $attrs['cn'] = $this->cn;
785           unset($attrs['dn']);
786           unset($attrs['MODIFIED']);
787           $ldap->cd("cn=".$this->cn.",".$this->dhcpParentNode);
788           $res = $ldap->add($attrs);
790           $tmp = new servdhcp($this->config,$this->dhcpParentNode);
791           $tmp->handle_post_events("modify");
793           if (!$ldap->success()){
794             msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=".$this->cn.",".$this->dhcpParentNode, LDAP_ADD, get_class()));
795           }
796           if($res){
797             $ldap->rmdir_recursive($this->dhcpHostEntry['dn']);
798             if (!$ldap->success()){
799               msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dhcpHostEntry['dn'], LDAP_DEL, get_class()));
800             }
801           }
802         }
803          
804         /* SAME node but modified */ 
805         if(isset($this->dhcpHostEntry['MODIFIED']) && $this->dhcpHostEntry['MODIFIED'] == 1  && 
806             $this->initial_dhcpParentNode == $this->dhcpParentNode){
807           $attrs = $this->dhcpHostEntry;
808           unset($attrs['dn']);
809           unset($attrs['MODIFIED']);
810           $ldap->cd($this->dhcpHostEntry['dn']);
811           $ldap->modify($attrs);
812           
813           $tmp = new servdhcp($this->config,$this->dhcpParentNode);
814           $tmp->handle_post_events("modify");
816           if (!$ldap->success()){
817             msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dhcpHostEntry['dn'], LDAP_MOD, get_class()));
818           }
819         }    
820       }
821     }
822     $this->dialog = FALSE; 
824     /****************/ 
825     /* DNS HANDLING */
826     /****************/ 
828     /* If isn't DNS account but initially was DNS account 
829        remove all DNS entries 
830      */ 
831     if((!$this->DNSenabled) || ((!$this->DNS_is_account)&&(!$this->initially_was_account))){
832       return;
833     }else{
835       /* Add ipHostNumber to aRecords
836        */
837       $backup_dnsEntry = $this->dnsEntry;
838       if(!empty($this->ipHostNumber)){
839         $this->dnsEntry['RECORDS'][] = array("type"=>"aRecord","value"=>$this->ipHostNumber);
840         $ptr = $this->get_pTRRecord();
841         if(!empty($ptr)){
842           $this->dnsEntry['RECORDS'][] = array("type"=>"pTRRecord","value"=>$ptr);
843         } 
844       }
846       /* Create diff and follow instructions 
847        * If Account was disabled, remove account by setting exists to false
848        */
849       if((!$this->DNS_is_account)&&($this->initially_was_account)){  
850         $this->dnsEntry['exists'] = false;
851         $tmp = DNS::getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
852       }else{
853         $this->dnsEntry['exists'] = $this->DNS_is_account;
854         $tmp = DNS::getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
855       }   
857       /* move follwoing entries 
858        */
859       foreach($tmp['move'] as $src => $dst){
860         $this->recursive_move($src,$dst);
861       }
863       /* Delete dns */
864       foreach($tmp['del'] as $dn => $del){
865         $ldap->cd($dn);
866         $ldap->rmdir_recursive($dn);
867         new log("modify","unknown/".get_class($this),$dn,array("*"),$ldap->get_error());
868       }
870       /* Add || Update new DNS entries 
871        */
872       foreach($tmp['add'] as $dn => $attrs){
873         $ldap->cd($dn);
874         $ldap->cat($dn, array('dn'));
875         if(count($ldap->fetch())){
876           $ldap->cd($dn);
877           $ldap->modify ($attrs); 
878         }else{
879           $ldap->cd($dn);
880           $ldap->add($attrs);
881         }
882         new log("modify","unknown/".get_class($this),$dn,array_keys($attrs),$ldap->get_error());
883       }
886       /* Display errors 
887        */
888       if (!$ldap->success()){
889         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, 0, get_class()));
890       }
892       $tmp2 = new servdns($this->config,$this->dn);
893       $tmp2->handle_post_events("modify");
895       $this->dnsEntry =  $backup_dnsEntry;
896     }
897   }
899   /*  Create html table with all used record types
900    */
901   function generateRecordsList()
902   {
903     $changeStateForRecords = "";
904     
905     if(!$this->DNS_is_account) {
906       $str = "<input type='submit' value='"._("Add")."' name='AddNewRecord' id='AddNewRecord' disabled='disabled'>";
907       return(array("str" => $str, "changeStateForRecords"=> ""));
908     }
909  
910     $str = "<table summary='' width='100%'>";
911     foreach($this->dnsEntry['RECORDS'] as $key => $entry){
913         $changeStateForRecords.= "changeState('RecordTypeSelectedFor_".$key."');\n";
914         $changeStateForRecords.= "changeState('RecordValue_".$key."');\n";
915         $changeStateForRecords.= "changeState('RemoveRecord_".$key."');\n";
917         $str.=" <tr>".
918           "   <td>".$this->generateRecordListBox($entry['type'],"RecordTypeSelectedFor_".$key)."</td>".
919           "   <td><input type='text' value='".$entry['value']."' name='RecordValue_".$key."' id='RecordValue_".$key."'></td>".
920           "   <td><input type='submit' name='RemoveRecord_".$key."' value='"._("Delete")."' id='RemoveRecord_".$key."'></td>".
921           "</tr>";
922     }
924     $str.= "  <tr>".
925            "    <td colspan=2 width='50%'></td><td>".
926            "      <input type='submit' value='"._("Add")."' name='AddNewRecord' id='AddNewRecord'>".
927            "    </td>".
928            "  </tr>".
929            "</table>";
930      $ret =  array("str" => $str, "changeStateForRecords" => $changeStateForRecords);
931     return($ret);
932   }
935   /* Create a html select box which allows us to select different types of records 
936    */
937   function generateRecordListBox($selected,$name)
938   {
939     $str = "<select name='".$name."' id='".$name."'>";
940     foreach($this->RecordTypes as $type => $value){
941       $use = "";
942       if($type == $selected){
943         $use = " selected ";
944       }
945       $str.="\n <option value='".$type."' ".$use.">".strtoupper(preg_replace("/record/i","",$type))."</option>";
946     }
947     $str.="</select>";
948     return($str); 
949   }
952   /* Return plugin informations for acl handling  */ 
953   static function plInfo()
954   {
955     $tmp =  array(
956         "plShortName"   => _("DNS"),
957         "plDescription" => _("DNS settings"),
958         "plSelfModify"  => FALSE,
959         "plDepends"     => array(),
960         "plPriority"    => 5,
961         "plSection"     => array("administration"),
962         "plCategory"    => array("workstation","terminal","phone","server","component","printer","winworkstation"),
964         "plProvidedAcls"=> array(
965           "ipHostNumber"  => _("IP address"),
966           "macAddress"    => _("MAC address"))
967         );
969     /* Hide all dns specific code, if dns is not available
970      */
971     $config = session::get('config');
972     foreach($config->data['TABS']['SERVERSERVICE'] as $tab){
973       if(preg_match("/^servdns$/",$tab['CLASS'])){
974         $tmp['plProvidedAcls']["Records"]        = _("DNS records");
975         $tmp['plProvidedAcls']["zoneName"]       = _("Zone name");
976         $tmp['plProvidedAcls']["dNSTTL"]         = _("TTL");
977         break;
978       }
979     }
980     return($tmp);
981   }
983   
984   function get_dhcp_host_entry()
985   {
986     $attrs = array();
987     $dn = $this->get_dhcp_host_entry_dn();
988     if($dn){
989       $ldap = $this->config->get_ldap_link();
990       $ldap->cd($this->config->current['BASE']);
991       $ldap->cat($dn,array("*"));
992       if($ldap->count()){
993         $attrs = $ldap->fetch();
994         foreach($attrs as $key => $value){
995           if(is_numeric($key) || ($key == "count")){
996             unset($attrs[$key]);
997           }
998           if(is_array($value) && isset($value['count'])){
999             unset($attrs[$key]['count']);
1000           }
1001         }
1002       }
1003     }
1004     return($attrs);
1005   }
1008   function get_dhcp_host_entry_dn()
1009   {
1010     $ldap = $this->config->get_ldap_link();
1011     $ldap->cd($this->config->current['BASE']);
1012     $ldap->search ("(&(objectClass=dhcpHost)(cn=".$this->cn."))",array("cn","dn"));
1014     if($ldap->count()){
1015       $attr = $ldap->fetch();
1016       return($attr['dn']);
1017     }else{
1018       return("");
1019     }
1020   }  
1023   function get_dhcp_parent_node()
1024   {
1025     return(preg_replace("/^cn=".normalizePreg($this->cn).",/","",$this->get_dhcp_host_entry_dn()));
1026   }
1029   function get_dhcp_parent_nodes()
1030   {
1031     $ldap = $this->config->get_ldap_link();
1032     $ldap->cd($this->config->current['BASE']);
1033     $ldap->search("(objectClass=dhcpService)",array("dhcpPrimaryDN"));
1034     
1035     $dhcp_dns = array();
1036     while($attr = $ldap->fetch()){
1037       $dhcp_dns[$attr['dn']] = $attr['dhcpPrimaryDN'][0];
1038     }
1039  
1040     foreach($dhcp_dns as $key => $pri_dns){
1041       $ldap->cat($pri_dns,array("cn"));
1042       $tmp = $ldap->fetch();
1043       if(isset($tmp['cn'][0])){
1044         $dhcp_dns[$key] = $tmp['cn'][0];
1045       }else{
1046         unset($dhcp_dns[$key]);
1047       }
1048     }
1050     $tmp = $tmp2 = array();
1051     foreach($dhcp_dns as $dn => $cn){
1052       $ldap->cd($dn);
1053       $ldap->search("(|(objectClass=dhcpService)(objectClass=dhcpGroup)".
1054                     "(objectClass=dhcpSubnet)(objectClass=dhcpSharedNetwork))",array("cn"));
1055       while($attr = $ldap->fetch()){
1056         $tmp[$attr['dn']] = $attr['cn'][0];
1057       }
1058       $tmp2 = array_merge($tmp2,$this->create_tree($tmp,preg_replace("/^[^,]+,/i","",$dn),"(".$cn.")&nbsp;"));
1059     }
1060     return($tmp2);
1061   }
1063   
1064   /* this function returns the default ptr record entry */
1065   function get_pTRRecord()
1066   {
1067     if(!empty($this->ipHostNumber) && isset($this->dnsEntry['zoneName']) && !empty($this->dnsEntry['zoneName'])){
1068       $ldap = $this->config->get_ldap_link();
1069       $ldap->cat(DNS::getDNSZoneDN($this->config,$this->dnsEntry['zoneName']));
1070       $attrs = $ldap->fetch();
1071       $tmp = array_flip($this->Zones);
1072       $tmp = preg_replace("/^[^\/]*+\//","",$tmp[$this->dnsEntry['zoneName']]);
1073       $tmp = trim(preg_replace("/\.in-addr.arpa$/","",$tmp));
1074       $ptr = preg_replace("/^".normalizePreg(DNS::FlipIp($tmp))."\./","",$this->ipHostNumber);
1075       return($ptr);
1076     }else{
1077       return(FALSE);
1078     }
1079   }
1081   
1082   function generateRandomIP($net = "")
1083   {
1084     $str = $net;
1085     $cnt = 4;
1086     while(substr_count($str,".") < 3 && $cnt > 0){
1087       $str .= ".".rand(0,255);
1088       $str = preg_replace("/\.\.*/",".",$str);
1089       $str = trim($str,". ");
1090       $cnt --;
1091     }
1092     return($str);
1093   }
1095   
1096   function create_tree($arr,$base,$current = "")
1097   {
1098     $ret = array();
1099     foreach($arr as $r => $name){
1100       $base_part = str_replace($base,"",$r);
1101       if(preg_match("/^[a-z]*=".normalizePreg($name)."(|,)$/i",$base_part)){
1102         $ret[$r] = $current.$name;
1103         $tmp = $this->create_tree($arr,$r,$current.".&nbsp;");
1104         foreach($tmp as $sub_key => $sub_name){
1105           $ret[$sub_key] = $sub_name;
1106         }
1107       } 
1108     }
1109     return($ret);
1110   }
1112   function force_dns()
1113   {
1114     if($this->DNSenabled){
1116       /* Only force DNS account, if we have at least on dns Zone */
1117       if(count($this->Zones)){
1118         $this->DNS_is_account  = TRUE;
1119         $this->hide_dns_check_box = TRUE;
1120       }
1121     }
1122   }
1125 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1126 ?>