Code

Replace {t}Delete{/t} with {msgPool type=delButton}
[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           print_red($msg);
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 #    if($this->dhcpEnabled && $this->dhcp_is_Account && $this->dhcpParentNode != "" && count($this->dhcpHostEntry) == 0){
513 #      $message[] =_("You have not configured your dhcp settings yet.");
514 #    }
515     
516     /* Check if mac and ip are already used */
517     if(!empty($this->ipHostNumber) && $this->DNS_is_account && 
518         $this->ipHostNumber != $this->orig_ipHostNumber && 
519         in_array("ip:".$this->ipHostNumber,$this->used_ip_mac)){
520       $message[]= msgPool::duplicated(_("IP address"));
521     }
522     if(!empty($this->macAddress) && $this->dhcp_is_Account && 
523         $this->macAddress != $this->orig_macAddress && 
524         in_array("mac:".$this->macAddress,$this->used_ip_mac)){
525       $message[]= msgPool::duplicated(_("MAC address"));
526     }
528     /* Check if ip must be given
529      */  
530     if(($this->IPisMust)||($this->DNS_is_account)){
531       if (empty($this->ipHostNumber)){
532         $message[]= msgPool::required(_("IP address"));
533       }
535       if (!tests::is_ip($this->ipHostNumber)){
536         $message[]= msgPool::invalid(_("IP address"), "", "", "192.168.1.10");
537       }
538     }
540     /* Check if mac is empty 
541      */
542     if ($this->macAddress == "" ){
543       $message[]= msgPool::required(_("IP address"));
544     }
545     if(!tests::is_mac($this->macAddress)){
546       $message[]= msgPool::invalid(_("MAC address"), "", "", "00:0C:7F:31:33:F1");
547     }
549     /* only perfrom this checks if this is a valid DNS account */
550     if($this->DNS_is_account){
552       $checkArray = array();
553       $onlyOnce   = array();
555       //  $onlyOnce['cNAMERecord'] = 0;
556        $tmp = array_flip($this->Zones);
557        $tmp2 = $tmp[$this->dnsEntry['zoneName']];
558        if(!$this->netmaskIsCoherent($tmp2)){ //this->dnsEntry['zoneName'])){
559          $tmp2 = preg_replace("/^.*\//","",$tmp2);
560          $message[] =sprintf(_("The IP address '%s' is not part of the selected reverse zone '%s'!"),$this->ipHostNumber,$tmp2);
561        }
563       /* Walk through all entries and detect duplicates or mismatches
564        */  
565       foreach($this->dnsEntry['RECORDS'] as $name => $values){
567         /* Count record values, to detect duplicate entries for a specific record
568          */
569         if(!isset($checkArray[$values['type']][$values['value']])){
570           $checkArray[$values['type']][$values['value']] = 0;
571         }else{
572           $message[] = sprintf(_("Record type '%s' is duplicated!"),$values['type']);
573         }
575         /* Check if given entries in $onlyOnce are used more than once
576          */
577         if(isset($onlyOnce[$values['type']])){
578           $onlyOnce[$values['type']] ++;
579           if($onlyOnce[$values['type']] > 1){
580             $message[] = sprintf(_("Uniq record type '%s' is duplicated!"),$values['type']);
581           }
582         }
584         /* Skip txt record ... 
585          */
586         if($values['type'] == "tXTRecord") continue;
588         /* Check if there is an aRecord defined which uses the same IP as used in IPhostAddress 
589          */
590         if(($values['type'] == "aRecord")&&($values['value'] == $this->ipHostNumber)){
591           #TODO: Where's the problem here?
592           $message[]=sprintf(_("The IP address '%s' will is added as 'A Record', this will be done automatically, please remove the record."), 
593                $this->ipHostNumber);
594         }
596         /* only lower-case is allowed in record entries ... 
597          */
598         if($values['value'] != strtolower($values['value'])){
599           #TODO: What's in values['value']? Something for a propper message?
600           $message[] = sprintf(_("Only lowercase records are allowed, please check your '%ss'."),$values['type']);
601         }
602       }
603     }
604     return ($message);
605   }
608   /* Save to LDAP */
609   function save()
610   {
611     $ldap= $this->config->get_ldap_link();
612   
613     $dn = $this->parent->dn;
614  
615     /*******************/ 
616     /* IP-MAC HANDLING */
617     /*******************/ 
619     /* $dn was posted as parameter */
620     $this->dn = $dn;
621     
622     /* Save DNS setting & ip/Mac*/
623     plugin::save();
625     /* Write back to ldap */
626     $ldap->cd($this->dn);
627     $this->cleanup();
628     $ldap->modify ($this->attrs); 
630     /****************/ 
631     /* DHCP HANDLING */
632     /****************/ 
633   
634     /* New entry */
635     if($this->dhcpEnabled){
637       if(count($this->dhcpHostEntry) == 0){
638         $this->dialog = new dhcpHost($this->dhcpParentNode,TRUE);
639         $this->dialog->cn = $this->cn;
640         $this->dialog->dhcpHWAddress = "ethernet ".$this->macAddress;
641         if(!empty($this->ipHostNumber)){
642           $this->dialog->statements['fixed-address'] = $this->ipHostNumber;
643         }
644         $this->dialog->execute();
645         $this->dialog->save_object(); 
646         $this->dhcpHostEntry = $this->dialog->save();
647         if(count($this->dhcpHostEntry['dhcpOption']) == 0){
648           $this->dhcpHostEntry['dhcpOption']= array("host-name ".$this->cn);
649         }
650       }
652       if(count($this->dhcpHostEntry) == 0){
653         $this->dialog = new dhcpHost($this->dhcpParentNode,TRUE);
654         $this->dialog->cn = $this->cn;
655         $this->dialog->dhcpHWAddress = "ethernet ".$this->macAddress;
656         if(!empty($this->ipHostNumber)){
657           $this->dialog->statements['fixed-address'] = $this->ipHostNumber;
658         }
659         $this->dialog->execute();
660         $this->dialog->save_object(); 
661         $this->dhcpHostEntry = $this->dialog->save();
662         if(count($this->dhcpHostEntry['dhcpOption']) == 0){
663           $this->dhcpHostEntry['dhcpOption']= array("host-name ".$this->cn);
664         }
665       }
667       /* Write mac address to dhcp settings */
668       if($this->dhcp_is_Account){
669         if(!isset($this->dhcpHostEntry['dhcpHWAddress'][0]) || 
670             !preg_match("/ethernet ".$this->macAddress."/",$this->dhcpHostEntry['dhcpHWAddress'][0])){
671           $this->dhcpHostEntry['dhcpHWAddress'] = array("ethernet ".$this->macAddress);
672           $this->dhcpHostEntry['MODIFIED'] = TRUE;
673         }
674       }
675   
677       /* Unset dhcpStatements if this attribute is empty  */
678       if(isset($this->dhcpHostEntry['dhcpStatements']) && 
679           ($this->dhcpHostEntry['dhcpStatements'] == "" || count($this->dhcpHostEntry['dhcpStatements']) == 0) ){
680         unset($this->dhcpHostEntry['dhcpStatements']);
681       }
682   
683       /* DHCP removed */
684       if($this->initial_dhcp_is_Account && !$this->dhcp_is_Account){
685         $ldap->rmdir_recursive($this->dhcpHostEntry['dn']);
686         if (!$ldap->success()){
687           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dhcpHostEntry['dn'], LDAP_DEL, get_class()));
688         }
690         $tmp = new servdhcp($this->config,$this->dhcpParentNode);
691         $tmp->handle_post_events("remove");
692       }
694       /* DHCP Added */
695       if(!$this->initial_dhcp_is_Account && $this->dhcp_is_Account){
696         $attrs = $this->dhcpHostEntry;
697         unset($attrs['MODIFIED']);
698         unset($attrs['dn']);
699         $ldap->cd("cn=".$this->cn.",".$this->dhcpParentNode);
700         $res = $ldap->add($attrs);
702         $tmp = new servdhcp($this->config,$this->dhcpParentNode);
703         $tmp->handle_post_events("add");
705         if (!$ldap->success()){
706           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=".$this->cn.",".$this->dhcpParentNode, LDAP_ADD, get_class()));
707         }
708       }
710       /* DHCP still activated */
711       if($this->initial_dhcp_is_Account && $this->dhcp_is_Account){
713         /* DHCP node changed */
714         if(($this->initial_dhcpParentNode != $this->dhcpParentNode) || 
715            ($this->cn != $this->OrigCn)){
716           $attrs = $this->dhcpHostEntry;
717           $attrs['cn'] = $this->cn;
718           unset($attrs['dn']);
719           unset($attrs['MODIFIED']);
720           $ldap->cd("cn=".$this->cn.",".$this->dhcpParentNode);
721           $res = $ldap->add($attrs);
723           $tmp = new servdhcp($this->config,$this->dhcpParentNode);
724           $tmp->handle_post_events("modify");
726           if (!$ldap->success()){
727             msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=".$this->cn.",".$this->dhcpParentNode, LDAP_ADD, get_class()));
728           }
729           if($res){
730             $ldap->rmdir_recursive($this->dhcpHostEntry['dn']);
731             if (!$ldap->success()){
732               msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dhcpHostEntry['dn'], LDAP_DEL, get_class()));
733             }
734           }
735         }
736          
737         /* SAME node but modified */ 
738         if(isset($this->dhcpHostEntry['MODIFIED']) && $this->dhcpHostEntry['MODIFIED'] == 1  && 
739             $this->initial_dhcpParentNode == $this->dhcpParentNode){
740           $attrs = $this->dhcpHostEntry;
741           unset($attrs['dn']);
742           unset($attrs['MODIFIED']);
743           $ldap->cd($this->dhcpHostEntry['dn']);
744           $ldap->modify($attrs);
745           
746           $tmp = new servdhcp($this->config,$this->dhcpParentNode);
747           $tmp->handle_post_events("modify");
749           if (!$ldap->success()){
750             msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dhcpHostEntry['dn'], LDAP_MOD, get_class()));
751           }
752         }    
753       }
754     }
755     $this->dialog = FALSE; 
757     /****************/ 
758     /* DNS HANDLING */
759     /****************/ 
761     /* If isn't DNS account but initially was DNS account 
762        remove all DNS entries 
763      */ 
764     if((!$this->DNSenabled) || ((!$this->DNS_is_account)&&(!$this->initially_was_account))){
765       return;
766     }else{
768       /* Add ipHostNumber to aRecords
769        */
770       $backup_dnsEntry = $this->dnsEntry;
771       if(!empty($this->ipHostNumber)){
772         $this->dnsEntry['RECORDS'][] = array("type"=>"aRecord","value"=>$this->ipHostNumber);
773         $ptr = $this->get_pTRRecord();
774         if(!empty($ptr)){
775           $this->dnsEntry['RECORDS'][] = array("type"=>"pTRRecord","value"=>$ptr);
776         } 
777       }
779       /* Create diff and follow instructions 
780        * If Account was disabled, remove account by setting exists to false
781        */
782       if((!$this->DNS_is_account)&&($this->initially_was_account)){  
783         $this->dnsEntry['exists'] = false;
784         $tmp = DNS::getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
785       }else{
786         $this->dnsEntry['exists'] = $this->DNS_is_account;
787         $tmp = DNS::getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
788       }   
790       /* move follwoing entries 
791        */
792       foreach($tmp['move'] as $src => $dst){
793         $this->recursive_move($src,$dst);
794       }
796       /* Delete dns */
797       foreach($tmp['del'] as $dn => $del){
798         $ldap->cd($dn);
799         $ldap->rmdir_recursive($dn);
800         new log("modify","unknown/".get_class($this),$dn,array("*"),$ldap->get_error());
801       }
803       /* Add || Update new DNS entries 
804        */
805       foreach($tmp['add'] as $dn => $attrs){
806         $ldap->cd($dn);
807         $ldap->cat($dn, array('dn'));
808         if(count($ldap->fetch())){
809           $ldap->cd($dn);
810           $ldap->modify ($attrs); 
811         }else{
812           $ldap->cd($dn);
813           $ldap->add($attrs);
814         }
815         new log("modify","unknown/".get_class($this),$dn,array_keys($attrs),$ldap->get_error());
816       }
819       /* Display errors 
820        */
821       if (!$ldap->success()){
822         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, 0, get_class()));
823       }
825       $tmp2 = new servdns($this->config,$this->dn);
826       $tmp2->handle_post_events("modify");
828       $this->dnsEntry =  $backup_dnsEntry;
829     }
830   }
832   /*  Create html table with all used record types
833    */
834   function generateRecordsList()
835   {
836     $changeStateForRecords = "";
837     
838     if(!$this->DNS_is_account) {
839       $str = "<input type='submit' value='"._("Add")."' name='AddNewRecord' id='AddNewRecord' disabled='disabled'>";
840       return(array("str" => $str, "changeStateForRecords"=> ""));
841     }
842  
843     $str = "<table summary='' width='100%'>";
844     foreach($this->dnsEntry['RECORDS'] as $key => $entry){
846         $changeStateForRecords.= "changeState('RecordTypeSelectedFor_".$key."');\n";
847         $changeStateForRecords.= "changeState('RecordValue_".$key."');\n";
848         $changeStateForRecords.= "changeState('RemoveRecord_".$key."');\n";
850         $str.=" <tr>".
851           "   <td>".$this->generateRecordListBox($entry['type'],"RecordTypeSelectedFor_".$key)."</td>".
852           "   <td><input type='text' value='".$entry['value']."' name='RecordValue_".$key."' id='RecordValue_".$key."'></td>".
853           "   <td><input type='submit' name='RemoveRecord_".$key."' value='"._("Delete")."' id='RemoveRecord_".$key."'></td>".
854           "</tr>";
855     }
857     $str.= "  <tr>".
858            "    <td colspan=2 width='50%'></td><td>".
859            "      <input type='submit' value='"._("Add")."' name='AddNewRecord' id='AddNewRecord'>".
860            "    </td>".
861            "  </tr>".
862            "</table>";
863      $ret =  array("str" => $str, "changeStateForRecords" => $changeStateForRecords);
864     return($ret);
865   }
868   /* Create a html select box which allows us to select different types of records 
869    */
870   function generateRecordListBox($selected,$name)
871   {
872     $str = "<select name='".$name."' id='".$name."'>";
873     foreach($this->RecordTypes as $type => $value){
874       $use = "";
875       if($type == $selected){
876         $use = " selected ";
877       }
878       $str.="\n <option value='".$type."' ".$use.">".strtoupper(preg_replace("/record/i","",$type))."</option>";
879     }
880     $str.="</select>";
881     return($str); 
882   }
885   /* Return plugin informations for acl handling  */ 
886   static function plInfo()
887   {
888     $tmp =  array(
889         "plShortName"   => _("DNS"),
890         "plDescription" => _("DNS settings"),
891         "plSelfModify"  => FALSE,
892         "plDepends"     => array(),
893         "plPriority"    => 5,
894         "plSection"     => array("administration"),
895         "plCategory"    => array("workstation","terminal","phone","server","component","printer","winworkstation"),
897         "plProvidedAcls"=> array(
898           "ipHostNumber"  => _("IP address"),
899           "macAddress"    => _("MAC address"))
900         );
902     /* Hide all dns specific code, if dns is not available
903      */
904     $config = session::get('config');
905     foreach($config->data['TABS']['SERVERSERVICE'] as $tab){
906       if(preg_match("/^servdns$/",$tab['CLASS'])){
907         $tmp['plProvidedAcls']["Records"]        = _("DNS records");
908         $tmp['plProvidedAcls']["zoneName"]       = _("Zone name");
909         $tmp['plProvidedAcls']["dNSTTL"]         = _("TTL");
910         break;
911       }
912     }
913     return($tmp);
914   }
916   
917   function get_dhcp_host_entry()
918   {
919     $attrs = array();
920     $dn = $this->get_dhcp_host_entry_dn();
921     if($dn){
922       $ldap = $this->config->get_ldap_link();
923       $ldap->cd($this->config->current['BASE']);
924       $ldap->cat($dn,array("*"));
925       if($ldap->count()){
926         $attrs = $ldap->fetch();
927         foreach($attrs as $key => $value){
928           if(is_numeric($key) || ($key == "count")){
929             unset($attrs[$key]);
930           }
931           if(is_array($value) && isset($value['count'])){
932             unset($attrs[$key]['count']);
933           }
934         }
935       }
936     }
937     return($attrs);
938   }
941   function get_dhcp_host_entry_dn()
942   {
943     $ldap = $this->config->get_ldap_link();
944     $ldap->cd($this->config->current['BASE']);
945     $ldap->search ("(&(objectClass=dhcpHost)(cn=".$this->cn."))",array("cn","dn"));
947     if($ldap->count()){
948       $attr = $ldap->fetch();
949       return($attr['dn']);
950     }else{
951       return("");
952     }
953   }  
956   function get_dhcp_parent_node()
957   {
958     return(preg_replace("/^cn=".normalizePreg($this->cn).",/","",$this->get_dhcp_host_entry_dn()));
959   }
962   function get_dhcp_parent_nodes()
963   {
964     $ldap = $this->config->get_ldap_link();
965     $ldap->cd($this->config->current['BASE']);
966     $ldap->search("(objectClass=dhcpService)",array("dhcpPrimaryDN"));
967     
968     $dhcp_dns = array();
969     while($attr = $ldap->fetch()){
970       $dhcp_dns[$attr['dn']] = $attr['dhcpPrimaryDN'][0];
971     }
972  
973     foreach($dhcp_dns as $key => $pri_dns){
974       $ldap->cat($pri_dns,array("cn"));
975       $tmp = $ldap->fetch();
976       if(isset($tmp['cn'][0])){
977         $dhcp_dns[$key] = $tmp['cn'][0];
978       }else{
979         unset($dhcp_dns[$key]);
980       }
981     }
983     $tmp = $tmp2 = array();
984     foreach($dhcp_dns as $dn => $cn){
985       $ldap->cd($dn);
986       $ldap->search("(|(objectClass=dhcpService)(objectClass=dhcpGroup)".
987                     "(objectClass=dhcpSubnet)(objectClass=dhcpSharedNetwork))",array("cn"));
988       while($attr = $ldap->fetch()){
989         $tmp[$attr['dn']] = $attr['cn'][0];
990       }
991       $tmp2 = array_merge($tmp2,$this->create_tree($tmp,preg_replace("/^[^,]+,/i","",$dn),"(".$cn.")&nbsp;"));
992     }
993     return($tmp2);
994   }
996   
997   /* this function returns the default ptr record entry */
998   function get_pTRRecord()
999   {
1000     if(!empty($this->ipHostNumber) && isset($this->dnsEntry['zoneName']) && !empty($this->dnsEntry['zoneName'])){
1001       $ldap = $this->config->get_ldap_link();
1002       $ldap->cat(DNS::getDNSZoneDN($this->config,$this->dnsEntry['zoneName']));
1003       $attrs = $ldap->fetch();
1004       $tmp = array_flip($this->Zones);
1005       $tmp = preg_replace("/^[^\/]*+\//","",$tmp[$this->dnsEntry['zoneName']]);
1006       $tmp = trim(preg_replace("/\.in-addr.arpa$/","",$tmp));
1007       $ptr = preg_replace("/^".normalizePreg(DNS::FlipIp($tmp))."\./","",$this->ipHostNumber);
1008       return($ptr);
1009     }else{
1010       return(FALSE);
1011     }
1012   }
1014   
1015   function generateRandomIP($net = "")
1016   {
1017     $str = $net;
1018     $cnt = 4;
1019     while(substr_count($str,".") < 3 && $cnt > 0){
1020       $str .= ".".rand(0,255);
1021       $str = preg_replace("/\.\.*/",".",$str);
1022       $str = trim($str,". ");
1023       $cnt --;
1024     }
1025     return($str);
1026   }
1028   
1029   function create_tree($arr,$base,$current = "")
1030   {
1031     $ret = array();
1032     foreach($arr as $r => $name){
1033       $base_part = str_replace($base,"",$r);
1034       if(preg_match("/^[a-z]*=".normalizePreg($name)."(|,)$/i",$base_part)){
1035         $ret[$r] = $current.$name;
1036         $tmp = $this->create_tree($arr,$r,$current.".&nbsp;");
1037         foreach($tmp as $sub_key => $sub_name){
1038           $ret[$sub_key] = $sub_name;
1039         }
1040       } 
1041     }
1042     return($ret);
1043   }
1045   function force_dns()
1046   {
1047     if($this->DNSenabled){
1049       /* Only force DNS account, if we have at least on dns Zone */
1050       if(count($this->Zones)){
1051         $this->DNS_is_account  = TRUE;
1052         $this->hide_dns_check_box = TRUE;
1053       }
1054     }
1055   }
1058 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1059 ?>