Code

Removed a couple of print_red calls
[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       if(count($this->dhcpHostEntry) == 0){
649         $this->dialog = new dhcpHost($this->dhcpParentNode,TRUE);
650         $this->dialog->cn = $this->cn;
651         $this->dialog->dhcpHWAddress = "ethernet ".$this->macAddress;
652         if(!empty($this->ipHostNumber)){
653           $this->dialog->statements['fixed-address'] = $this->ipHostNumber;
654         }
655         $this->dialog->execute();
656         $this->dialog->save_object(); 
657         $this->dhcpHostEntry = $this->dialog->save();
658         if(count($this->dhcpHostEntry['dhcpOption']) == 0){
659           $this->dhcpHostEntry['dhcpOption']= array("host-name ".$this->cn);
660         }
661       }
663       /* Write mac address to dhcp settings */
664       if($this->dhcp_is_Account){
665         if(!isset($this->dhcpHostEntry['dhcpHWAddress'][0]) || 
666             !preg_match("/ethernet ".$this->macAddress."/",$this->dhcpHostEntry['dhcpHWAddress'][0])){
667           $this->dhcpHostEntry['dhcpHWAddress'] = array("ethernet ".$this->macAddress);
668           $this->dhcpHostEntry['MODIFIED'] = TRUE;
669         }
670       }
671   
673       /* Unset dhcpStatements if this attribute is empty  */
674       if(isset($this->dhcpHostEntry['dhcpStatements']) && 
675           ($this->dhcpHostEntry['dhcpStatements'] == "" || count($this->dhcpHostEntry['dhcpStatements']) == 0) ){
676         unset($this->dhcpHostEntry['dhcpStatements']);
677       }
678   
679       /* DHCP removed */
680       if($this->initial_dhcp_is_Account && !$this->dhcp_is_Account){
681         $ldap->rmdir_recursive($this->dhcpHostEntry['dn']);
682         if (!$ldap->success()){
683           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dhcpHostEntry['dn'], LDAP_DEL, get_class()));
684         }
686         $tmp = new servdhcp($this->config,$this->dhcpParentNode);
687         $tmp->handle_post_events("remove");
688       }
690       /* DHCP Added */
691       if(!$this->initial_dhcp_is_Account && $this->dhcp_is_Account){
692         $attrs = $this->dhcpHostEntry;
693         unset($attrs['MODIFIED']);
694         unset($attrs['dn']);
695         $ldap->cd("cn=".$this->cn.",".$this->dhcpParentNode);
696         $res = $ldap->add($attrs);
698         $tmp = new servdhcp($this->config,$this->dhcpParentNode);
699         $tmp->handle_post_events("add");
701         if (!$ldap->success()){
702           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=".$this->cn.",".$this->dhcpParentNode, LDAP_ADD, get_class()));
703         }
704       }
706       /* DHCP still activated */
707       if($this->initial_dhcp_is_Account && $this->dhcp_is_Account){
709         /* DHCP node changed */
710         if(($this->initial_dhcpParentNode != $this->dhcpParentNode) || 
711            ($this->cn != $this->OrigCn)){
712           $attrs = $this->dhcpHostEntry;
713           $attrs['cn'] = $this->cn;
714           unset($attrs['dn']);
715           unset($attrs['MODIFIED']);
716           $ldap->cd("cn=".$this->cn.",".$this->dhcpParentNode);
717           $res = $ldap->add($attrs);
719           $tmp = new servdhcp($this->config,$this->dhcpParentNode);
720           $tmp->handle_post_events("modify");
722           if (!$ldap->success()){
723             msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=".$this->cn.",".$this->dhcpParentNode, LDAP_ADD, get_class()));
724           }
725           if($res){
726             $ldap->rmdir_recursive($this->dhcpHostEntry['dn']);
727             if (!$ldap->success()){
728               msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dhcpHostEntry['dn'], LDAP_DEL, get_class()));
729             }
730           }
731         }
732          
733         /* SAME node but modified */ 
734         if(isset($this->dhcpHostEntry['MODIFIED']) && $this->dhcpHostEntry['MODIFIED'] == 1  && 
735             $this->initial_dhcpParentNode == $this->dhcpParentNode){
736           $attrs = $this->dhcpHostEntry;
737           unset($attrs['dn']);
738           unset($attrs['MODIFIED']);
739           $ldap->cd($this->dhcpHostEntry['dn']);
740           $ldap->modify($attrs);
741           
742           $tmp = new servdhcp($this->config,$this->dhcpParentNode);
743           $tmp->handle_post_events("modify");
745           if (!$ldap->success()){
746             msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dhcpHostEntry['dn'], LDAP_MOD, get_class()));
747           }
748         }    
749       }
750     }
751     $this->dialog = FALSE; 
753     /****************/ 
754     /* DNS HANDLING */
755     /****************/ 
757     /* If isn't DNS account but initially was DNS account 
758        remove all DNS entries 
759      */ 
760     if((!$this->DNSenabled) || ((!$this->DNS_is_account)&&(!$this->initially_was_account))){
761       return;
762     }else{
764       /* Add ipHostNumber to aRecords
765        */
766       $backup_dnsEntry = $this->dnsEntry;
767       if(!empty($this->ipHostNumber)){
768         $this->dnsEntry['RECORDS'][] = array("type"=>"aRecord","value"=>$this->ipHostNumber);
769         $ptr = $this->get_pTRRecord();
770         if(!empty($ptr)){
771           $this->dnsEntry['RECORDS'][] = array("type"=>"pTRRecord","value"=>$ptr);
772         } 
773       }
775       /* Create diff and follow instructions 
776        * If Account was disabled, remove account by setting exists to false
777        */
778       if((!$this->DNS_is_account)&&($this->initially_was_account)){  
779         $this->dnsEntry['exists'] = false;
780         $tmp = DNS::getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
781       }else{
782         $this->dnsEntry['exists'] = $this->DNS_is_account;
783         $tmp = DNS::getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
784       }   
786       /* move follwoing entries 
787        */
788       foreach($tmp['move'] as $src => $dst){
789         $this->recursive_move($src,$dst);
790       }
792       /* Delete dns */
793       foreach($tmp['del'] as $dn => $del){
794         $ldap->cd($dn);
795         $ldap->rmdir_recursive($dn);
796         new log("modify","unknown/".get_class($this),$dn,array("*"),$ldap->get_error());
797       }
799       /* Add || Update new DNS entries 
800        */
801       foreach($tmp['add'] as $dn => $attrs){
802         $ldap->cd($dn);
803         $ldap->cat($dn, array('dn'));
804         if(count($ldap->fetch())){
805           $ldap->cd($dn);
806           $ldap->modify ($attrs); 
807         }else{
808           $ldap->cd($dn);
809           $ldap->add($attrs);
810         }
811         new log("modify","unknown/".get_class($this),$dn,array_keys($attrs),$ldap->get_error());
812       }
815       /* Display errors 
816        */
817       if (!$ldap->success()){
818         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, 0, get_class()));
819       }
821       $tmp2 = new servdns($this->config,$this->dn);
822       $tmp2->handle_post_events("modify");
824       $this->dnsEntry =  $backup_dnsEntry;
825     }
826   }
828   /*  Create html table with all used record types
829    */
830   function generateRecordsList()
831   {
832     $changeStateForRecords = "";
833     
834     if(!$this->DNS_is_account) {
835       $str = "<input type='submit' value='"._("Add")."' name='AddNewRecord' id='AddNewRecord' disabled='disabled'>";
836       return(array("str" => $str, "changeStateForRecords"=> ""));
837     }
838  
839     $str = "<table summary='' width='100%'>";
840     foreach($this->dnsEntry['RECORDS'] as $key => $entry){
842         $changeStateForRecords.= "changeState('RecordTypeSelectedFor_".$key."');\n";
843         $changeStateForRecords.= "changeState('RecordValue_".$key."');\n";
844         $changeStateForRecords.= "changeState('RemoveRecord_".$key."');\n";
846         $str.=" <tr>".
847           "   <td>".$this->generateRecordListBox($entry['type'],"RecordTypeSelectedFor_".$key)."</td>".
848           "   <td><input type='text' value='".$entry['value']."' name='RecordValue_".$key."' id='RecordValue_".$key."'></td>".
849           "   <td><input type='submit' name='RemoveRecord_".$key."' value='"._("Delete")."' id='RemoveRecord_".$key."'></td>".
850           "</tr>";
851     }
853     $str.= "  <tr>".
854            "    <td colspan=2 width='50%'></td><td>".
855            "      <input type='submit' value='"._("Add")."' name='AddNewRecord' id='AddNewRecord'>".
856            "    </td>".
857            "  </tr>".
858            "</table>";
859      $ret =  array("str" => $str, "changeStateForRecords" => $changeStateForRecords);
860     return($ret);
861   }
864   /* Create a html select box which allows us to select different types of records 
865    */
866   function generateRecordListBox($selected,$name)
867   {
868     $str = "<select name='".$name."' id='".$name."'>";
869     foreach($this->RecordTypes as $type => $value){
870       $use = "";
871       if($type == $selected){
872         $use = " selected ";
873       }
874       $str.="\n <option value='".$type."' ".$use.">".strtoupper(preg_replace("/record/i","",$type))."</option>";
875     }
876     $str.="</select>";
877     return($str); 
878   }
881   /* Return plugin informations for acl handling  */ 
882   static function plInfo()
883   {
884     $tmp =  array(
885         "plShortName"   => _("DNS"),
886         "plDescription" => _("DNS settings"),
887         "plSelfModify"  => FALSE,
888         "plDepends"     => array(),
889         "plPriority"    => 5,
890         "plSection"     => array("administration"),
891         "plCategory"    => array("workstation","terminal","phone","server","component","printer","winworkstation"),
893         "plProvidedAcls"=> array(
894           "ipHostNumber"  => _("IP address"),
895           "macAddress"    => _("MAC address"))
896         );
898     /* Hide all dns specific code, if dns is not available
899      */
900     $config = session::get('config');
901     foreach($config->data['TABS']['SERVERSERVICE'] as $tab){
902       if(preg_match("/^servdns$/",$tab['CLASS'])){
903         $tmp['plProvidedAcls']["Records"]        = _("DNS records");
904         $tmp['plProvidedAcls']["zoneName"]       = _("Zone name");
905         $tmp['plProvidedAcls']["dNSTTL"]         = _("TTL");
906         break;
907       }
908     }
909     return($tmp);
910   }
912   
913   function get_dhcp_host_entry()
914   {
915     $attrs = array();
916     $dn = $this->get_dhcp_host_entry_dn();
917     if($dn){
918       $ldap = $this->config->get_ldap_link();
919       $ldap->cd($this->config->current['BASE']);
920       $ldap->cat($dn,array("*"));
921       if($ldap->count()){
922         $attrs = $ldap->fetch();
923         foreach($attrs as $key => $value){
924           if(is_numeric($key) || ($key == "count")){
925             unset($attrs[$key]);
926           }
927           if(is_array($value) && isset($value['count'])){
928             unset($attrs[$key]['count']);
929           }
930         }
931       }
932     }
933     return($attrs);
934   }
937   function get_dhcp_host_entry_dn()
938   {
939     $ldap = $this->config->get_ldap_link();
940     $ldap->cd($this->config->current['BASE']);
941     $ldap->search ("(&(objectClass=dhcpHost)(cn=".$this->cn."))",array("cn","dn"));
943     if($ldap->count()){
944       $attr = $ldap->fetch();
945       return($attr['dn']);
946     }else{
947       return("");
948     }
949   }  
952   function get_dhcp_parent_node()
953   {
954     return(preg_replace("/^cn=".normalizePreg($this->cn).",/","",$this->get_dhcp_host_entry_dn()));
955   }
958   function get_dhcp_parent_nodes()
959   {
960     $ldap = $this->config->get_ldap_link();
961     $ldap->cd($this->config->current['BASE']);
962     $ldap->search("(objectClass=dhcpService)",array("dhcpPrimaryDN"));
963     
964     $dhcp_dns = array();
965     while($attr = $ldap->fetch()){
966       $dhcp_dns[$attr['dn']] = $attr['dhcpPrimaryDN'][0];
967     }
968  
969     foreach($dhcp_dns as $key => $pri_dns){
970       $ldap->cat($pri_dns,array("cn"));
971       $tmp = $ldap->fetch();
972       if(isset($tmp['cn'][0])){
973         $dhcp_dns[$key] = $tmp['cn'][0];
974       }else{
975         unset($dhcp_dns[$key]);
976       }
977     }
979     $tmp = $tmp2 = array();
980     foreach($dhcp_dns as $dn => $cn){
981       $ldap->cd($dn);
982       $ldap->search("(|(objectClass=dhcpService)(objectClass=dhcpGroup)".
983                     "(objectClass=dhcpSubnet)(objectClass=dhcpSharedNetwork))",array("cn"));
984       while($attr = $ldap->fetch()){
985         $tmp[$attr['dn']] = $attr['cn'][0];
986       }
987       $tmp2 = array_merge($tmp2,$this->create_tree($tmp,preg_replace("/^[^,]+,/i","",$dn),"(".$cn.")&nbsp;"));
988     }
989     return($tmp2);
990   }
992   
993   /* this function returns the default ptr record entry */
994   function get_pTRRecord()
995   {
996     if(!empty($this->ipHostNumber) && isset($this->dnsEntry['zoneName']) && !empty($this->dnsEntry['zoneName'])){
997       $ldap = $this->config->get_ldap_link();
998       $ldap->cat(DNS::getDNSZoneDN($this->config,$this->dnsEntry['zoneName']));
999       $attrs = $ldap->fetch();
1000       $tmp = array_flip($this->Zones);
1001       $tmp = preg_replace("/^[^\/]*+\//","",$tmp[$this->dnsEntry['zoneName']]);
1002       $tmp = trim(preg_replace("/\.in-addr.arpa$/","",$tmp));
1003       $ptr = preg_replace("/^".normalizePreg(DNS::FlipIp($tmp))."\./","",$this->ipHostNumber);
1004       return($ptr);
1005     }else{
1006       return(FALSE);
1007     }
1008   }
1010   
1011   function generateRandomIP($net = "")
1012   {
1013     $str = $net;
1014     $cnt = 4;
1015     while(substr_count($str,".") < 3 && $cnt > 0){
1016       $str .= ".".rand(0,255);
1017       $str = preg_replace("/\.\.*/",".",$str);
1018       $str = trim($str,". ");
1019       $cnt --;
1020     }
1021     return($str);
1022   }
1024   
1025   function create_tree($arr,$base,$current = "")
1026   {
1027     $ret = array();
1028     foreach($arr as $r => $name){
1029       $base_part = str_replace($base,"",$r);
1030       if(preg_match("/^[a-z]*=".normalizePreg($name)."(|,)$/i",$base_part)){
1031         $ret[$r] = $current.$name;
1032         $tmp = $this->create_tree($arr,$r,$current.".&nbsp;");
1033         foreach($tmp as $sub_key => $sub_name){
1034           $ret[$sub_key] = $sub_name;
1035         }
1036       } 
1037     }
1038     return($ret);
1039   }
1041   function force_dns()
1042   {
1043     if($this->DNSenabled){
1045       /* Only force DNS account, if we have at least on dns Zone */
1046       if(count($this->Zones)){
1047         $this->DNS_is_account  = TRUE;
1048         $this->hide_dns_check_box = TRUE;
1049       }
1050     }
1051   }
1054 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1055 ?>