Code

a0925d884a9d1a0427d530c594d0987ffe30053a
[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 $macAddress     = "";    // Mac address 
36   var $orig_ipHostNumber   = "";    // IP address 
37   var $orig_macAddress     = "";    // Mac address 
39   var $cn             = "";    // CN of currently edited device 
40   var $OrigCn         = "";    // Initial cn
41   var $IPisMust       = false;
42   var $MACisMust      = false;
43   var $dialog         = false;
45   /* DCHP Attributes 
46    */
47   var $dhcpAttributes           = array("dhcpParentNode");
48   var $dhcpEnabled              = FALSE;
49   var $dhcp_is_Account          = FALSE;
50   var $dhcpParentNodes          = array();
51   var $dhcpParentNode           = "";
52   var $dhcpHostEntry            = array();
53   var $initial_dhcpParentNode   = "";
54   var $initial_dhcpHostEntry    = array();
55   var $initial_dhcp_is_Account  = FALSE;
57   var $used_ip_mac              = array();  
59   /* DNS attributes  
60    */
61   var $DNSattributes            = array("dNSClass","zoneName","dNSTTL");
62   var $DNS_is_account           = false;
63   var $initially_was_account = false;
64   var $dnsEntry                 = array();
65   var $DNSenabled               = false;
66   var $hide_dns_check_box       = FALSE;
68   /*  Terminal dns 
69    */
70   function termDNS (&$config, $parent,$objectClasses,$IPisMust = false)
71   {
72     /* We need to know which objectClasses are used, to store the ip/mac
73      * Because of different type of devices   
74      */ 
75     $this->parent         = $parent;
76     $this->objectclasses  =  $objectClasses;
77     $this->IPisMust       = $IPisMust;
79     plugin::plugin ($config, $parent->dn);
81     if(isset($this->attrs['cn'][0])){
82       $this->OrigCn = preg_replace("/\\\$\$/","",$this->attrs['cn'][0]);
83       $this->cn = preg_replace("/\\\$\$/","",$this->attrs['cn'][0]);
84     }
86  
87     /************
88      * DHCP 
89      ************/
91     /* Hide all dhcp specific code, if dhcp plugin is not present in config */
92     $dhcpEnabled = FALSE;
93     if($this->config->search("servdhcp","class",array("tabs"))){
94       $this->dhcpEnabled = TRUE;
95     }
96     if($this->dhcpEnabled){
97       $this->dhcpParentNodes = $this->get_dhcp_parent_nodes();
98       $this->dhcpParentNode  = $this->get_dhcp_parent_node();
99       if($this->dhcpParentNode){
100         $this->dhcp_is_Account = TRUE;
101         $this->initial_dhcp_is_Account = TRUE;
102         $this->dhcpHostEntry  = $this->get_dhcp_host_entry();    
103       }
104       $this->initial_dhcpHostEntry = $this->dhcpHostEntry;
105       $this->initial_dhcpParentNode= $this->dhcpParentNode;
106     }
109     /************
110      * DNS
111      ************/
112  
113     /* Hide all dns specific code, if dns is not available 
114      */
115     $DNSenabled = false;
116     foreach($this->config->data['TABS']['SERVERSERVICE'] as $tab){
117       if(preg_match("/^servdns$/",$tab['CLASS'])){
118         $this->DNSenabled = true;
119       }
120     }
121     if(!$this->DNSenabled){
122       $this->DNS_is_account = false;
123       return;
124     }
126     if($this->DNSenabled){
128       /* Get Zones  
129        */
130       $this->Zones        = DNS::getAvailableZones($config);
132       /* Get Entry 
133        */
134       $this->dnsEntry     = DNS::getDNSHostEntries($config,$this->OrigCn);
136       /* Remove A record which equals $this->ipHostNumber
137        */
138       $ptr = $this->get_pTRRecord();
139       foreach($this->dnsEntry['RECORDS'] as $key => $rec){
140         if(($rec['type'] == "aRecord") && ($rec['value'] == $this->ipHostNumber)){
141           unset($this->dnsEntry['RECORDS'][$key]);
142         }
143         if(($rec['type'] == "pTRRecord") && ($rec['value'] == $ptr)){
144           unset($this->dnsEntry['RECORDS'][$key]);
145         }
146       }
148       /* Get Record types 
149        */
150       $this->RecordTypes  = DNS::getDnsRecordTypes();
152       /* If there is at least one entry in this -> types, we have DNS enabled 
153        */
154       if($this->dnsEntry['exists']){
155         $this->DNS_is_account = true;
156       }else{
157         $this->DNS_is_account = false;
158       }
159     }
161     /* Create a list of used mac and ip addresses.
163        ! We use this optically huge amount of code to fetch all 
164        Mac and IP addresses, because a simple search for mac and IP
165        over the whole ldap server was 10 to 20 times slower.
166      */
167     $deps  = array();
168     $ou = preg_replace("/,.*$/","",get_ou("systemsou"));
169     $a_ous = array(get_ou("serverou"),
170                   get_ou("terminalou"),
171                   get_ou("workstationou"),
172                   get_ou("printerou"),
173                   get_ou("phoneou"),
174                   get_ou("componentou"));
175   
176     $ldap = $this->config->get_ldap_link();
177     $ldap->cd($this->config->current['BASE']);
178     $ldap->search("(&(objectClass=organizationalUnit)(".$ou."))",array("dn"));
179     while($attrs = $ldap->fetch()){
180       foreach($a_ous as $allowed){
181         $deps[] = $allowed.$attrs['dn'];
182       }
183     }
185     foreach($deps as $dep){
186       $ldap->cd($dep);
187       $ldap->search("(|(macAddress=*)(ipHostNumber=*))",array("macAddress","ipHostNumber"));
188       while($attrs = $ldap->fetch()){
189         if(isset($attrs['ipHostNumber'][0])){
190           $this->used_ip_mac["ip:".$attrs['ipHostNumber'][0]] = "ip:".$attrs['ipHostNumber'][0];
191         }
192         if(isset($attrs['macAddress'][0])){
193           $this->used_ip_mac["mac:".$attrs['macAddress'][0]] = "mac:".$attrs['macAddress'][0];
194         }
195       } 
196     }
198     /* Save initial ip and mac values, to be able 
199         check if the used values are already in use */ 
200     $this->orig_ipHostNumber   = $this->ipHostNumber;  
201     $this->orig_macAddress     = $this->macAddress;
202  
203     /* Store initally account settings 
204      */
205     $this->initially_was_account = $this->DNS_is_account;
207     if($this->DNS_is_account){
208       new log("view","unknown/".get_class($this),$this->dn);
209     }
210   }
213   function netmaskIsCoherent($idZone) 
214   {
215     $netmask = DNS::FlipIp(str_replace(".in-addr.arpa","",DNS::getNameFromMix($idZone)));
216     if(!strstr($this->ipHostNumber, $netmask)){
217       return false;
218     }else{
219       return true;
220     }
221   }
224   function getVarsForSaving($attrs) 
225   {
226     foreach($this->attributes as $attr){
227       if(!empty($this->$attr)){
228         $attrs[$attr] = $this->$attr;
229       }
230     }
231     return($attrs); 
232   }
234   function execute()
235   {
236           /* Call parent execute */
237     $smarty= get_smarty();
239     $tmp = $this->plInfo();
240     foreach($tmp['plProvidedAcls'] as $name => $translation){
241       $smarty->assign($name."ACL",$this->getacl($name));
242     }
244     $display= "";
246     $smarty->assign("staticAddress", ""); 
247  
248     /* Check for autonet button */
249     if (isset($_POST['autonet'])){
250         $d= new gosaSupportDaemon(TRUE, 0.5);
251         $res= $d->_send("<xml><header>gosa_network_completition</header><source>GOSA</source><target>GOSA</target><hostname>".$this->cn."</hostname></xml>", TRUE);
252         if (isset($res['XML']['IP'])){
253                 $this->ipHostNumber= $res['XML']['IP'];
254         }
255         if (isset($res['XML']['MAC'])){
256                 $this->macAddress= $res['XML']['MAC'];
257         }
258     }
259     
260   
261     /**********
262      * DHCP Handling
263      **********/
264  
265     if(isset($_POST['dhcpEditOptions'])){
267       if(count($this->dhcpHostEntry) == 0){
268         $this->dialog = new dhcpHost($this->dhcpParentNode,TRUE);
269       }else{
270         $this->dialog = new dhcpHost($this->dhcpHostEntry,TRUE);
271       }
272       $this->dialog->cn = $this->cn; 
273       $this->dialog->dhcpHWAddress = "ethernet ".$this->macAddress; 
274       if(!empty($this->ipHostNumber)){
275         $this->dialog->statements['fixed-address'] = $this->ipHostNumber; 
276       }
277     }
279     if(isset($_POST['cancel_dhcp'])){
280       $this->dialog = FALSE; 
281     }
283     if(isset($_POST['save_dhcp'])){
284       $this->dialog->save_object();
285       
286       $msgs = $this->dialog->check(array());
287       if(count($msgs)){
288         foreach($msgs as $msg){
289           msg_dialog::display(_("Error"), $msg, ERROR_DIALOG);
290         }
291       }else{
292         $this->dhcpHostEntry = $this->dialog->save();
293         $this->dialog = FALSE; 
294       }
295     }
297     if(is_object($this->dialog)){
298       $this->dialog->save_object();
299       return($this->dialog->execute());
300     }
301  
302     $smarty->assign("dhcpEnabled",    $this->dhcpEnabled);
303     $smarty->assign("dhcp_is_Account",$this->dhcp_is_Account);
304     $smarty->assign("dhcpParentNode", $this->dhcpParentNode);
305     $smarty->assign("dhcpParentNodes",$this->dhcpParentNodes);
306     $smarty->assign("dhcpParentNodeCnt",count($this->dhcpParentNodes));
309     /**********
310      * DNS Handling
311      **********/
313     /* There is no dns available
314      */
315     $smarty->assign("DNS_is_account",$this->DNS_is_account);
316     $smarty->assign("DNSenabled",$this->DNSenabled);
317     if($this->DNSenabled == false){
319       /* Is IP address must ? */
320 #      $smarty->assign("DNS_is_account",false);
321       $smarty->assign("IPisMust",(($this->IPisMust)||($this->DNS_is_account)));
323       /* Assign smarty all non DNs attributes */
324       foreach($this->attributes as $attr){
325         $smarty->assign($attr,$this->$attr);
326       }
327       $smarty->assign("staticAddress","<font class=\"must\">*</font>");
329       $display.= $smarty->fetch(get_template_path('network.tpl', TRUE));
330     }else{
331  #     $smarty->assign("DNS_is_account",true);
333       /* Add new empty array to our record list */
334       if(isset($_POST['AddNewRecord'])){
335         $this->dnsEntry['RECORDS'][]  =array("type"=>"aRecord","value"=>"");
336       }
338       /* propose_ip */
339       if(isset($_POST['propose_ip'])){
340         foreach($this->Zones as $key => $name){
341           if($name == $this->dnsEntry['zoneName']){
342             $net = DNS::FlipIp(str_replace(".in-addr.arpa","",DNS::getNameFromMix($key)));
343             $this->ipHostNumber = $this->generateRandomIp($net);
344           }
345         }
346       }
348       /* Handle all posts */
349       $only_once =true;
350       foreach($_POST as $name => $value){
352         /* Check if we have to delete a record entry */
353         if((preg_match("/RemoveRecord_/",$name))&&($only_once)) {
355           /* Avoid performing this once again */
356           $only_once = false;
358           /* Extract id for specified entry */
359           $id = preg_replace("/RemoveRecord_/","",$name);
360           $id = preg_replace("/_.*$/","",$id);
362           /* Delete this record, mark edited entries to be able to delete them */
363           if(isset($this->dnsEntry['RECORDS'][$id])){
364             unset($this->dnsEntry['RECORDS'][$id]);
365           }
366         }
367       }
368       /* Assign smarty all non DNs attributes */
369       foreach($this->attributes as $attr){
370         $smarty->assign($attr,$this->$attr);
371       }
373       /* Assign smarty all DNS attributes */
374       foreach($this->DNSattributes as $attr){
375         $smarty->assign($attr,$this->dnsEntry[$attr]);
376       }
378       /* Assign all needed vars */
379  #     $smarty->assign("DNSAccount",$this->DNS_is_account);
380       $smarty->assign("hide_dns_check_box",$this->hide_dns_check_box);
381   
382       $smarty->assign("Zones",$this->Zones);
383       $smarty->assign("ZoneCnt",count($this->Zones));
384       $smarty->assign("ZoneKeys",($this->Zones));
385       $smarty->assign("IPisMust",(($this->IPisMust)||($this->DNS_is_account)));
387       /* Create zone array */
388       $idZones = array();
389       foreach($this->Zones as $id => $zone){
390         if($this->netmaskIsCoherent($id)) {
391           $idZones[$id] = $zone;
392         }else{
393           $idZones[$id] = $zone."&nbsp;("._("Not matching").")";
394         }
395       }
396       $smarty->assign("Zones",$idZones);
397       $smarty->assign("ZoneKeys", $this->Zones);
399       $tmp = $this->generateRecordsList();
401       $changeStateForRecords = $tmp['changeStateForRecords'];
403       $smarty->assign("records",$tmp['str']);
404       $smarty->assign("changeStateForRecords",$changeStateForRecords);
405       $smarty->assign("staticAddress","<font class=\"must\">*</font>");
407       $display.= $smarty->fetch(get_template_path('network.tpl', TRUE));
408     }
409     return($display);
410   }
413   function remove_from_parent()
414   {
415     if($this->initially_was_account){
417       $ldap = $this->config->get_ldap_link();
419       $tmp = array();
420       $this->dnsEntry['exists'] = false;
421       $tmp = DNS::getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
422   
423       /* Delete dns */
424       foreach($tmp['del'] as $dn => $del){
425         $ldap->cd($dn);
426         $ldap->rmdir_recursive($dn);
427         new log("remove","unknown/".get_class($this),$dn);
428         if (!$ldap->success()){
429           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_DEL, get_class()));
430         }
431       }
432     }
433   }
436   /* Save data to object */
437   function save_object()
438   {
440     if(isset($_POST['network_tpl_posted'])){
442       /* Save all posted vars */
443       plugin::save_object();
445       /* Handle DHCP Posts*/
446       if($this->dhcpEnabled && isset($_POST['network_tpl_posted'])){
447         foreach($this->dhcpAttributes as $attr){
448           if(isset($_POST[$attr])){
449             $this->$attr = $_POST[$attr];
450           }
451         }
452         if(isset($_POST['dhcp_is_Account'])){
453           $this->dhcp_is_Account = TRUE;
454         }else{
455           $this->dhcp_is_Account = FALSE;
456         }
457       }
459       /* Ge all non dns attributes (IP/MAC)*/
460       foreach($this->attributes as $attr){
461         if(isset($_POST[$attr]) && $this->acl_is_writeable($attr)){
462           $this->$attr = $_POST[$attr];
463         }
464       }
466       /* Check if DNS should be enabled / disabled */
467       if($this->DNS_is_account && $this->acl_is_removeable() && !isset($_POST['DNS_is_account'])){
468         $this->DNS_is_account = false;
469       }elseif(!$this->DNS_is_account && $this->acl_is_createable() && isset($_POST['DNS_is_account'])){
470         $this->DNS_is_account = true;
471       }
473       /* Get dns attributes */
474       if(($this->DNSenabled) && (isset($_POST['network_tpl_posted']))){
476         /* Check for posted record changes */
477         if(is_array($this->dnsEntry['RECORDS']) && $this->acl_is_writeable("Records")){
478           foreach($this->dnsEntry['RECORDS'] as $key => $value){
480             /* Check if type has changed */
481             if(isset($_POST['RecordTypeSelectedFor_'.$key])){
482               $this->dnsEntry['RECORDS'][$key]['type'] = $_POST['RecordTypeSelectedFor_'.$key];
483             }
484             /* Check if value has changed */
485             if(isset($_POST['RecordValue_'.$key])){
486               $this->dnsEntry['RECORDS'][$key]['value'] = $_POST['RecordValue_'.$key];
487             }
488           }
489         }
490         /* Get all basic DNS attributes (TTL, Clas ..)*/
491         foreach($this->DNSattributes as $attr){
492           if(isset($_POST[$attr]) && $this->acl_is_writeable($attr)){
493             $this->dnsEntry[$attr] = $_POST[$attr];
494           }
495         }
498       }
499       if($this->hide_dns_check_box){
500         $this->DNS_is_account = true;
501       }
502     }
503   }
506   /* Check supplied data */
507   function check()
508   {
509     /* Call common method to give check the hook */
510     $message= plugin::check();
512     /* Check if mac and ip are already used */
513     if(!empty($this->ipHostNumber) && $this->DNS_is_account && 
514         $this->ipHostNumber != $this->orig_ipHostNumber && 
515         in_array("ip:".$this->ipHostNumber,$this->used_ip_mac)){
516       $message[]= msgPool::duplicated(_("IP address"));
517     }
518     if(!empty($this->macAddress) && $this->dhcp_is_Account && 
519         $this->macAddress != $this->orig_macAddress && 
520         in_array("mac:".$this->macAddress,$this->used_ip_mac)){
521       $message[]= msgPool::duplicated(_("MAC address"));
522     }
524     /* Check if ip must be given
525      */  
526     if(($this->IPisMust)||($this->DNS_is_account)){
527       if (empty($this->ipHostNumber)){
528         $message[]= msgPool::required(_("IP address"));
529       }
531       if (!tests::is_ip($this->ipHostNumber)){
532         $message[]= msgPool::invalid(_("IP address"), "", "", "192.168.1.10");
533       }
534     }
536     /* Check if mac is empty 
537      */
538     if ($this->macAddress == "" ){
539       $message[]= msgPool::required(_("IP address"));
540     }
541     if(!tests::is_mac($this->macAddress)){
542       $message[]= msgPool::invalid(_("MAC address"), "", "", "00:0C:7F:31:33:F1");
543     }
545     /* only perfrom this checks if this is a valid DNS account */
546     if($this->DNS_is_account){
548       $checkArray = array();
549       $onlyOnce   = array();
551       //  $onlyOnce['cNAMERecord'] = 0;
552        $tmp = array_flip($this->Zones);
553        $tmp2 = $tmp[$this->dnsEntry['zoneName']];
554        if(!$this->netmaskIsCoherent($tmp2)){ //this->dnsEntry['zoneName'])){
555          $tmp2 = preg_replace("/^.*\//","",$tmp2);
556          $message[] =sprintf(_("The IP address '%s' is not part of the selected reverse zone '%s'!"),$this->ipHostNumber,$tmp2);
557        }
559       /* Walk through all entries and detect duplicates or mismatches
560        */  
561       foreach($this->dnsEntry['RECORDS'] as $name => $values){
563         /* Count record values, to detect duplicate entries for a specific record
564          */
565         if(!isset($checkArray[$values['type']][$values['value']])){
566           $checkArray[$values['type']][$values['value']] = 0;
567         }else{
568           $message[] = sprintf(_("Record type '%s' is duplicated!"),$values['type']);
569         }
571         /* Check if given entries in $onlyOnce are used more than once
572          */
573         if(isset($onlyOnce[$values['type']])){
574           $onlyOnce[$values['type']] ++;
575           if($onlyOnce[$values['type']] > 1){
576             $message[] = sprintf(_("Uniq record type '%s' is duplicated!"),$values['type']);
577           }
578         }
580         /* Skip txt record ... 
581          */
582         if($values['type'] == "tXTRecord") continue;
584         /* Check if there is an aRecord defined which uses the same IP as used in IPhostAddress 
585          */
586         if(($values['type'] == "aRecord")&&($values['value'] == $this->ipHostNumber)){
587           #TODO: Where's the problem here?
588           $message[]=sprintf(_("The IP address '%s' will be added as 'A Record', this will be done automatically, please remove the record."), 
589                $this->ipHostNumber);
590         }
592         /* only lower-case is allowed in record entries ... 
593          */
594         if($values['value'] != strtolower($values['value'])){
595           #TODO: What's in values['value']? Something for a propper message?
596           $message[] = sprintf(_("Only lowercase records are allowed, please check your '%ss'."),$values['type']);
597         }
598       }
599     }
600     return ($message);
601   }
604   /* Save to LDAP */
605   function save()
606   {
607     $ldap= $this->config->get_ldap_link();
608   
609     $dn = $this->parent->dn;
610  
611     /*******************/ 
612     /* IP-MAC HANDLING */
613     /*******************/ 
615     /* $dn was posted as parameter */
616     $this->dn = $dn;
617     
618     /* Save DNS setting & ip/Mac*/
619     plugin::save();
621     /* Write back to ldap */
622     $ldap->cd($this->dn);
623     $this->cleanup();
624     $ldap->modify ($this->attrs); 
626     /****************/ 
627     /* DHCP HANDLING */
628     /****************/ 
629   
630     /* New entry */
631     if($this->dhcpEnabled){
633       if(count($this->dhcpHostEntry) == 0){
634         $this->dialog = new dhcpHost($this->dhcpParentNode,TRUE);
635         $this->dialog->cn = $this->cn;
636         $this->dialog->dhcpHWAddress = "ethernet ".$this->macAddress;
637         if(!empty($this->ipHostNumber)){
638           $this->dialog->statements['fixed-address'] = $this->ipHostNumber;
639         }
640         $this->dialog->execute();
641         $this->dialog->save_object(); 
642         $this->dhcpHostEntry = $this->dialog->save();
643         if(count($this->dhcpHostEntry['dhcpOption']) == 0){
644           $this->dhcpHostEntry['dhcpOption']= array("host-name ".$this->cn);
645         }
646       }
648       /* Write mac address to dhcp settings */
649       if($this->dhcp_is_Account){
650         if(!isset($this->dhcpHostEntry['dhcpHWAddress'][0]) || 
651             !preg_match("/ethernet ".$this->macAddress."/",$this->dhcpHostEntry['dhcpHWAddress'][0])){
652           $this->dhcpHostEntry['dhcpHWAddress'] = array("ethernet ".$this->macAddress);
653           $this->dhcpHostEntry['MODIFIED'] = TRUE;
654         }
655       }
657       /* Updated IP host number */
658       if($this->dhcp_is_Account){
659         foreach($this->dhcpHostEntry['dhcpStatements'] as $id => $value){
660           if(preg_match("/^fixed-address/",$value)){
661             $this->dhcpHostEntry['dhcpStatements'][$id] = "fixed-address ".$this->ipHostNumber; 
662             $this->dhcpHostEntry['MODIFIED'] = TRUE;
663           }
664         }
665       }
667       /* Unset dhcpStatements if this attribute is empty  */
668       if(isset($this->dhcpHostEntry['dhcpStatements']) && 
669           ($this->dhcpHostEntry['dhcpStatements'] == "" || count($this->dhcpHostEntry['dhcpStatements']) == 0) ){
670         unset($this->dhcpHostEntry['dhcpStatements']);
671       }
672   
673       /* DHCP removed */
674       if($this->initial_dhcp_is_Account && !$this->dhcp_is_Account){
675         $ldap->rmdir_recursive($this->dhcpHostEntry['dn']);
676         if (!$ldap->success()){
677           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dhcpHostEntry['dn'], LDAP_DEL, get_class()));
678         }
680         $tmp = new servdhcp($this->config,$this->dhcpParentNode);
681         $tmp->handle_post_events("remove");
682       }
684       /* DHCP Added */
685       if(!$this->initial_dhcp_is_Account && $this->dhcp_is_Account){
686         $attrs = $this->dhcpHostEntry;
687         unset($attrs['MODIFIED']);
688         unset($attrs['dn']);
689         $ldap->cd("cn=".$this->cn.",".$this->dhcpParentNode);
690         $res = $ldap->add($attrs);
692         $tmp = new servdhcp($this->config,$this->dhcpParentNode);
693         $tmp->handle_post_events("add");
695         if (!$ldap->success()){
696           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=".$this->cn.",".$this->dhcpParentNode, LDAP_ADD, get_class()));
697         }
698       }
700       /* DHCP still activated */
701       if($this->initial_dhcp_is_Account && $this->dhcp_is_Account){
703         /* DHCP node changed */
704         if(($this->initial_dhcpParentNode != $this->dhcpParentNode) || 
705            ($this->cn != $this->OrigCn)){
706           $attrs = $this->dhcpHostEntry;
707           $attrs['cn'] = $this->cn;
708           unset($attrs['dn']);
709           unset($attrs['MODIFIED']);
710           $ldap->cd("cn=".$this->cn.",".$this->dhcpParentNode);
711           $res = $ldap->add($attrs);
713           $tmp = new servdhcp($this->config,$this->dhcpParentNode);
714           $tmp->handle_post_events("modify");
716           if (!$ldap->success()){
717             msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=".$this->cn.",".$this->dhcpParentNode, LDAP_ADD, get_class()));
718           }
719           if($res){
720             $ldap->rmdir_recursive($this->dhcpHostEntry['dn']);
721             if (!$ldap->success()){
722               msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dhcpHostEntry['dn'], LDAP_DEL, get_class()));
723             }
724           }
725         }
726          
727         /* SAME node but modified */ 
728         if(isset($this->dhcpHostEntry['MODIFIED']) && $this->dhcpHostEntry['MODIFIED'] == 1  && 
729             $this->initial_dhcpParentNode == $this->dhcpParentNode){
730           $attrs = $this->dhcpHostEntry;
731           unset($attrs['dn']);
732           unset($attrs['MODIFIED']);
733           $ldap->cd($this->dhcpHostEntry['dn']);
734           $ldap->modify($attrs);
735           
736           $tmp = new servdhcp($this->config,$this->dhcpParentNode);
737           $tmp->handle_post_events("modify");
739           if (!$ldap->success()){
740             msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dhcpHostEntry['dn'], LDAP_MOD, get_class()));
741           }
742         }    
743       }
744     }
745     $this->dialog = FALSE; 
747     /****************/ 
748     /* DNS HANDLING */
749     /****************/ 
751     /* If isn't DNS account but initially was DNS account 
752        remove all DNS entries 
753      */ 
754     if((!$this->DNSenabled) || ((!$this->DNS_is_account)&&(!$this->initially_was_account))){
755       return;
756     }else{
758       /* Add ipHostNumber to aRecords
759        */
760       $backup_dnsEntry = $this->dnsEntry;
761       if(!empty($this->ipHostNumber)){
762         $this->dnsEntry['RECORDS'][] = array("type"=>"aRecord","value"=>$this->ipHostNumber);
763         $ptr = $this->get_pTRRecord();
764         if(!empty($ptr)){
765           $this->dnsEntry['RECORDS'][] = array("type"=>"pTRRecord","value"=>$ptr);
766         } 
767       }
769       /* Create diff and follow instructions 
770        * If Account was disabled, remove account by setting exists to false
771        */
772       if((!$this->DNS_is_account)&&($this->initially_was_account)){  
773         $this->dnsEntry['exists'] = false;
774         $tmp = DNS::getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
775       }else{
776         $this->dnsEntry['exists'] = $this->DNS_is_account;
777         $tmp = DNS::getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
778       }   
780       /* move follwoing entries 
781        */
782       foreach($tmp['move'] as $src => $dst){
783         $this->recursive_move($src,$dst);
784       }
786       /* Delete dns */
787       foreach($tmp['del'] as $dn => $del){
788         $ldap->cd($dn);
789         $ldap->rmdir_recursive($dn);
790         new log("modify","unknown/".get_class($this),$dn,array("*"),$ldap->get_error());
791       }
793       /* Add || Update new DNS entries 
794        */
795       foreach($tmp['add'] as $dn => $attrs){
796         $ldap->cd($dn);
797         $ldap->cat($dn, array('dn'));
798         if(count($ldap->fetch())){
799           $ldap->cd($dn);
800           $ldap->modify ($attrs); 
801         }else{
802           $ldap->cd($dn);
803           $ldap->add($attrs);
804         }
805         new log("modify","unknown/".get_class($this),$dn,array_keys($attrs),$ldap->get_error());
806       }
809       /* Display errors 
810        */
811       if (!$ldap->success()){
812         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, 0, get_class()));
813       }
815       $tmp2 = new servdns($this->config,$this->dn);
816       $tmp2->handle_post_events("modify");
818       $this->dnsEntry =  $backup_dnsEntry;
819     }
820   }
822   /*  Create html table with all used record types
823    */
824   function generateRecordsList()
825   {
826     $changeStateForRecords = "";
827     
828     if(!$this->DNS_is_account) {
829       $str = "<input type='submit' value='"._("Add")."' name='AddNewRecord' id='AddNewRecord' disabled='disabled'>";
830       return(array("str" => $str, "changeStateForRecords"=> ""));
831     }
832  
833     $str = "<table summary='' width='100%'>";
834     foreach($this->dnsEntry['RECORDS'] as $key => $entry){
836         $changeStateForRecords.= "changeState('RecordTypeSelectedFor_".$key."');\n";
837         $changeStateForRecords.= "changeState('RecordValue_".$key."');\n";
838         $changeStateForRecords.= "changeState('RemoveRecord_".$key."');\n";
840         $str.=" <tr>".
841           "   <td>".$this->generateRecordListBox($entry['type'],"RecordTypeSelectedFor_".$key)."</td>".
842           "   <td><input type='text' value='".$entry['value']."' name='RecordValue_".$key."' id='RecordValue_".$key."'></td>".
843           "   <td><input type='submit' name='RemoveRecord_".$key."' value='"._("Delete")."' id='RemoveRecord_".$key."'></td>".
844           "</tr>";
845     }
847     $str.= "  <tr>".
848            "    <td colspan=2 width='50%'></td><td>".
849            "      <input type='submit' value='"._("Add")."' name='AddNewRecord' id='AddNewRecord'>".
850            "    </td>".
851            "  </tr>".
852            "</table>";
853      $ret =  array("str" => $str, "changeStateForRecords" => $changeStateForRecords);
854     return($ret);
855   }
858   /* Create a html select box which allows us to select different types of records 
859    */
860   function generateRecordListBox($selected,$name)
861   {
862     $str = "<select name='".$name."' id='".$name."'>";
863     foreach($this->RecordTypes as $type => $value){
864       $use = "";
865       if($type == $selected){
866         $use = " selected ";
867       }
868       $str.="\n <option value='".$type."' ".$use.">".strtoupper(preg_replace("/record/i","",$type))."</option>";
869     }
870     $str.="</select>";
871     return($str); 
872   }
875   /* Return plugin informations for acl handling  */ 
876   static function plInfo()
877   {
878     $tmp =  array(
879         "plShortName"   => _("DNS"),
880         "plDescription" => _("DNS settings"),
881         "plSelfModify"  => FALSE,
882         "plDepends"     => array(),
883         "plPriority"    => 5,
884         "plSection"     => array("administration"),
885         "plCategory"    => array("workstation","terminal","phone","server","component","printer","winworkstation"),
887         "plProvidedAcls"=> array(
888           "ipHostNumber"  => _("IP address"),
889           "macAddress"    => _("MAC address"))
890         );
892     /* Hide all dns specific code, if dns is not available
893      */
894     $config = session::get('config');
895     foreach($config->data['TABS']['SERVERSERVICE'] as $tab){
896       if(preg_match("/^servdns$/",$tab['CLASS'])){
897         $tmp['plProvidedAcls']["Records"]        = _("DNS records");
898         $tmp['plProvidedAcls']["zoneName"]       = _("Zone name");
899         $tmp['plProvidedAcls']["dNSTTL"]         = _("TTL");
900         break;
901       }
902     }
903     return($tmp);
904   }
906   
907   function get_dhcp_host_entry()
908   {
909     $attrs = array();
910     $dn = $this->get_dhcp_host_entry_dn();
911     if($dn){
912       $ldap = $this->config->get_ldap_link();
913       $ldap->cd($this->config->current['BASE']);
914       $ldap->cat($dn,array("*"));
915       if($ldap->count()){
916         $attrs = $ldap->fetch();
917         foreach($attrs as $key => $value){
918           if(is_numeric($key) || ($key == "count")){
919             unset($attrs[$key]);
920           }
921           if(is_array($value) && isset($value['count'])){
922             unset($attrs[$key]['count']);
923           }
924         }
925       }
926     }
927     return($attrs);
928   }
931   function get_dhcp_host_entry_dn()
932   {
933     $ldap = $this->config->get_ldap_link();
934     $ldap->cd($this->config->current['BASE']);
935     $ldap->search ("(&(objectClass=dhcpHost)(cn=".$this->cn."))",array("cn","dn"));
937     if($ldap->count()){
938       $attr = $ldap->fetch();
939       return($attr['dn']);
940     }else{
941       return("");
942     }
943   }  
946   function get_dhcp_parent_node()
947   {
948     return(preg_replace("/^cn=".normalizePreg($this->cn).",/","",$this->get_dhcp_host_entry_dn()));
949   }
952   function get_dhcp_parent_nodes()
953   {
954     $ldap = $this->config->get_ldap_link();
955     $ldap->cd($this->config->current['BASE']);
956     $ldap->search("(objectClass=dhcpService)",array("dhcpPrimaryDN"));
957     
958     $dhcp_dns = array();
959     while($attr = $ldap->fetch()){
960       $dhcp_dns[$attr['dn']] = $attr['dhcpPrimaryDN'][0];
961     }
962  
963     foreach($dhcp_dns as $key => $pri_dns){
964       $ldap->cat($pri_dns,array("cn"));
965       $tmp = $ldap->fetch();
966       if(isset($tmp['cn'][0])){
967         $dhcp_dns[$key] = $tmp['cn'][0];
968       }else{
969         unset($dhcp_dns[$key]);
970       }
971     }
973     $tmp = $tmp2 = array();
974     foreach($dhcp_dns as $dn => $cn){
975       $ldap->cd($dn);
976       $ldap->search("(|(objectClass=dhcpService)(objectClass=dhcpGroup)".
977                     "(objectClass=dhcpSubnet)(objectClass=dhcpSharedNetwork))",array("cn"));
978       while($attr = $ldap->fetch()){
979         $tmp[$attr['dn']] = $attr['cn'][0];
980       }
981       $tmp2 = array_merge($tmp2,$this->create_tree($tmp,preg_replace("/^[^,]+,/i","",$dn),"(".$cn.")&nbsp;"));
982     }
983     return($tmp2);
984   }
986   
987   /* this function returns the default ptr record entry */
988   function get_pTRRecord()
989   {
990     if(!empty($this->ipHostNumber) && isset($this->dnsEntry['zoneName']) && !empty($this->dnsEntry['zoneName'])){
991       $ldap = $this->config->get_ldap_link();
992       $ldap->cat(DNS::getDNSZoneDN($this->config,$this->dnsEntry['zoneName']));
993       $attrs = $ldap->fetch();
994       $tmp = array_flip($this->Zones);
995       $tmp = preg_replace("/^[^\/]*+\//","",$tmp[$this->dnsEntry['zoneName']]);
996       $tmp = trim(preg_replace("/\.in-addr.arpa$/","",$tmp));
997       $ptr = preg_replace("/^".normalizePreg(DNS::FlipIp($tmp))."\./","",$this->ipHostNumber);
998       return($ptr);
999     }else{
1000       return(FALSE);
1001     }
1002   }
1004   
1005   function generateRandomIP($net = "")
1006   {
1007     $str = $net;
1008     $cnt = 4;
1009     while(substr_count($str,".") < 3 && $cnt > 0){
1010       $str .= ".".rand(0,255);
1011       $str = preg_replace("/\.\.*/",".",$str);
1012       $str = trim($str,". ");
1013       $cnt --;
1014     }
1015     return($str);
1016   }
1018   
1019   function create_tree($arr,$base,$current = "")
1020   {
1021     $ret = array();
1022     foreach($arr as $r => $name){
1023       $base_part = str_replace($base,"",$r);
1024       if(preg_match("/^[a-z]*=".normalizePreg($name)."(|,)$/i",$base_part)){
1025         $ret[$r] = $current.$name;
1026         $tmp = $this->create_tree($arr,$r,$current.".&nbsp;");
1027         foreach($tmp as $sub_key => $sub_name){
1028           $ret[$sub_key] = $sub_name;
1029         }
1030       } 
1031     }
1032     return($ret);
1033   }
1035   function force_dns()
1036   {
1037     if($this->DNSenabled){
1039       /* Only force DNS account, if we have at least on dns Zone */
1040       if(count($this->Zones)){
1041         $this->DNS_is_account  = TRUE;
1042         $this->hide_dns_check_box = TRUE;
1043       }
1044     }
1045   }
1048 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1049 ?>