Code

Updated system Management
[gosa.git] / gosa-plugins / systems / admin / systems / class_termDNS.inc
1 <?php
2 /*
3  * This code is part of GOsa (http://www.gosa-project.org)
4  * Copyright (C) 2003-2008 GONICUS GmbH
5  *
6  * ID: $$Id$$
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
23 class termDNS extends plugin
24 {
25   /* attribute list for save action */
26   var $ignore_account = true;
28   /* Basic informations 
29    */
30   var $attributes     = array("ipHostNumber","macAddress");
31   var $objectclasses  = array("whatever");
33   var $ipHostNumber          = "";    // IP address 
34   var $additionalHostNumbers = array();
35   var $macAddress            = "";    // Mac address 
37   var $orig_ipHostNumber   = "";    // IP address 
38   var $orig_macAddress     = "";    // Mac address 
40   var $cn             = "";    // CN of currently edited device 
41   var $OrigCn         = "";    // Initial cn
42   var $IPisMust       = false;
43   var $MACisMust      = false;
44   var $dialog         = false;
46   /* DCHP Attributes 
47    */
48   var $dhcpAttributes           = array("dhcpParentNode");
49   var $dhcpEnabled              = FALSE;
50   var $dhcp_is_Account          = FALSE;
51   var $dhcpParentNodes          = array();
52   var $dhcpParentNode           = "";
53   var $dhcpHostEntry            = array();
54   var $initial_dhcpParentNode   = "";
55   var $initial_dhcpHostEntry    = array();
56   var $initial_dhcp_is_Account  = FALSE;
58   var $used_ip_mac              = array();  
60   /* DNS attributes  
61    */
62   var $DNSattributes            = array("dNSClass","zoneName","dNSTTL");
63   var $DNS_is_account           = false;
64   var $initially_was_account = false;
65   var $dnsEntry                 = array();
66   var $DNSenabled               = false;
67   var $hide_dns_check_box       = FALSE;
69   /*  Terminal dns 
70    */
71   function termDNS (&$config, $parent,$objectClasses,$IPisMust = false)
72   {
73     /* We need to know which objectClasses are used, to store the ip/mac
74      * Because of different type of devices   
75      */ 
76     $this->parent         = $parent;
77     $this->objectclasses  =  $objectClasses;
78     $this->IPisMust       = $IPisMust;
80     plugin::plugin ($config, $parent->dn);
82     if(isset($this->attrs['cn'][0])){
83       $this->OrigCn = preg_replace("/\\\$\$/","",$this->attrs['cn'][0]);
84       $this->cn = preg_replace("/\\\$\$/","",$this->attrs['cn'][0]);
85     }
88     $this->additionalHostNumbers = array();
89     if(isset($this->attrs['ipHostNumber']) && $this->attrs['ipHostNumber']['count'] > 1){
90       for($i = 1 ; $i < $this->attrs['ipHostNumber']['count']; $i ++){
91         $this->additionalHostNumbers[] = $this->attrs['ipHostNumber'][$i];
92       }
93     }
94  
95     /************
96      * DHCP 
97      ************/
99     /* Hide all dhcp specific code, if dhcp plugin is not present in config */
100     $dhcpEnabled = FALSE;
101     if($this->config->search("servdhcp","class",array("tabs"))){
102       $this->dhcpEnabled = TRUE;
103     }
104     if($this->dhcpEnabled){
105       $this->dhcpParentNodes = $this->get_dhcp_parent_nodes();
106       $this->dhcpParentNode  = $this->get_dhcp_parent_node();
107       if($this->dhcpParentNode){
108         $this->dhcp_is_Account = TRUE;
109         $this->initial_dhcp_is_Account = TRUE;
110         $this->dhcpHostEntry  = $this->get_dhcp_host_entry();    
111       }
112       $this->initial_dhcpHostEntry = $this->dhcpHostEntry;
113       $this->initial_dhcpParentNode= $this->dhcpParentNode;
114     }
117     /************
118      * DNS
119      ************/
120  
121     /* Hide all dns specific code, if dns is not available 
122      */
123     $DNSenabled = false;
124     foreach($this->config->data['TABS']['SERVERSERVICE'] as $tab){
125       if(preg_match("/^servdns$/",$tab['CLASS'])){
126         $this->DNSenabled = true;
127       }
128     }
129     if(!$this->DNSenabled){
130       $this->DNS_is_account = false;
131       return;
132     }
134     if($this->DNSenabled){
136       /* Get Zones  
137        */
138       $this->Zones        = DNS::getAvailableZones($config);
140       /* Get Entry 
141        */
142       $this->dnsEntry     = DNS::getDNSHostEntries($config,$this->OrigCn);
144       /* Remove A record which equals $this->ipHostNumber
145        */
146       $ptr = $this->get_pTRRecord();
147       foreach($this->dnsEntry['RECORDS'] as $key => $rec){
148         if(($rec['type'] == "aRecord") && ($rec['value'] == $this->ipHostNumber)){
149           unset($this->dnsEntry['RECORDS'][$key]);
150         }
151         if(($rec['type'] == "pTRRecord") && ($rec['value'] == $ptr)){
152           unset($this->dnsEntry['RECORDS'][$key]);
153         }
154       }
156       /* Get Record types 
157        */
158       $this->RecordTypes  = DNS::getDnsRecordTypes();
160       /* If there is at least one entry in this -> types, we have DNS enabled 
161        */
162       if($this->dnsEntry['exists']){
163         $this->DNS_is_account = true;
164       }else{
165         $this->DNS_is_account = false;
166       }
167     }
169     /* Create a list of used mac and ip addresses.
171        ! We use this optically huge amount of code to fetch all 
172        Mac and IP addresses, because a simple search for mac and IP
173        over the whole ldap server was 10 to 20 times slower.
174      */
175     $deps  = array();
176     $ou = preg_replace("/,.*$/","",get_ou("systemsou"));
177     $a_ous = array(get_ou("serverou"),
178                   get_ou("terminalou"),
179                   get_ou("workstationou"),
180                   get_ou("printerou"),
181                   get_ou("phoneou"),
182                   get_ou("componentou"));
183   
184     $ldap = $this->config->get_ldap_link();
185     $ldap->cd($this->config->current['BASE']);
186     $ldap->search("(&(objectClass=organizationalUnit)(".$ou."))",array("dn"));
187     while($attrs = $ldap->fetch()){
188       foreach($a_ous as $allowed){
189         $deps[] = $allowed.$attrs['dn'];
190       }
191     }
193     foreach($deps as $dep){
194       $ldap->cd($dep);
195       $ldap->search("(|(macAddress=*)(ipHostNumber=*))",array("macAddress","ipHostNumber"));
196       while($attrs = $ldap->fetch()){
197         if(isset($attrs['ipHostNumber'][0])){
198           $this->used_ip_mac["ip:".$attrs['ipHostNumber'][0]] = "ip:".$attrs['ipHostNumber'][0];
199         }
200         if(isset($attrs['macAddress'][0])){
201           $this->used_ip_mac["mac:".$attrs['macAddress'][0]] = "mac:".$attrs['macAddress'][0];
202         }
203       } 
204     }
206     /* Save initial ip and mac values, to be able 
207         check if the used values are already in use */ 
208     $this->orig_ipHostNumber   = $this->ipHostNumber;  
209     $this->orig_macAddress     = $this->macAddress;
210  
211     /* Store initally account settings 
212      */
213     $this->initially_was_account = $this->DNS_is_account;
215     if($this->DNS_is_account){
216       new log("view","unknown/".get_class($this),$this->dn);
217     }
218   }
221   function netmaskIsCoherent($idZone) 
222   {
223     $netmask = DNS::FlipIp(str_replace(".in-addr.arpa","",DNS::getNameFromMix($idZone)));
224     if(!strstr($this->ipHostNumber, $netmask)){
225       return false;
226     }else{
227       return true;
228     }
229   }
232   function getVarsForSaving($attrs) 
233   {
234     foreach($this->attributes as $attr){
235       if(!empty($this->$attr)){
236         $attrs[$attr] = $this->$attr;
237       }
238     }
239     return($attrs); 
240   }
242   function execute()
243   {
244           /* Call parent execute */
245     $smarty= get_smarty();
247     $tmp = $this->plInfo();
248     foreach($tmp['plProvidedAcls'] as $name => $translation){
249       $smarty->assign($name."ACL",$this->getacl($name));
250     }
252     $display= "";
254     $smarty->assign("additionalHostNumbers",$this->additionalHostNumbers);
255     $smarty->assign("staticAddress", ""); 
256  
257     /* Check for autonet button */
258     if (isset($_POST['autonet'])){
259         $d= new gosaSupportDaemon(TRUE, 0.5);
260         $res= $d->_send("<xml><header>gosa_network_completition</header><source>GOSA</source><target>GOSA</target><hostname>".$this->cn."</hostname></xml>", TRUE);
261         if (isset($res['XML']['IP'])){
262                 $this->ipHostNumber= $res['XML']['IP'];
263         }
264         if (isset($res['XML']['MAC'])){
265                 $this->macAddress= $res['XML']['MAC'];
266         }
267     }
268     
269   
270     /**********
271      * DHCP Handling
272      **********/
273  
274     if(isset($_POST['dhcpEditOptions'])){
276       if(count($this->dhcpHostEntry) == 0){
277         $this->dialog = new dhcpHost($this->dhcpParentNode,TRUE);
278       }else{
279         $this->dialog = new dhcpHost($this->dhcpHostEntry,TRUE);
280       }
281       $this->dialog->cn = $this->cn; 
282       $this->dialog->dhcpHWAddress = "ethernet ".$this->macAddress; 
283       if(!empty($this->ipHostNumber)){
284         $this->dialog->statements['fixed-address'] = $this->ipHostNumber; 
285       }
286     }
288     if(isset($_POST['cancel_dhcp'])){
289       $this->dialog = FALSE; 
290     }
292     if(isset($_POST['save_dhcp'])){
293       $this->dialog->save_object();
294       
295       $msgs = $this->dialog->check(array());
296       if(count($msgs)){
297         foreach($msgs as $msg){
298           msg_dialog::display(_("Error"), $msg, ERROR_DIALOG);
299         }
300       }else{
301         $this->dhcpHostEntry = $this->dialog->save();
302         $this->dialog = FALSE; 
303       }
304     }
306     if(is_object($this->dialog)){
307       $this->dialog->save_object();
308       return($this->dialog->execute());
309     }
310  
311     $smarty->assign("dhcpEnabled",    $this->dhcpEnabled);
312     $smarty->assign("dhcp_is_Account",$this->dhcp_is_Account);
313     $smarty->assign("dhcpParentNode", $this->dhcpParentNode);
314     $smarty->assign("dhcpParentNodes",$this->dhcpParentNodes);
315     $smarty->assign("dhcpParentNodeCnt",count($this->dhcpParentNodes));
318     /**********
319      * DNS Handling
320      **********/
322     /* There is no dns available
323      */
324     $smarty->assign("DNS_is_account",$this->DNS_is_account);
325     $smarty->assign("DNSenabled",$this->DNSenabled);
326     if($this->DNSenabled == false){
328       /* Is IP address must ? */
329 #      $smarty->assign("DNS_is_account",false);
330       $smarty->assign("IPisMust",(($this->IPisMust)||($this->DNS_is_account)));
332       /* Assign smarty all non DNs attributes */
333       foreach($this->attributes as $attr){
334         $smarty->assign($attr,$this->$attr);
335       }
336       $smarty->assign("staticAddress","<font class=\"must\">*</font>");
338       $display.= $smarty->fetch(get_template_path('network.tpl', TRUE));
339     }else{
340  #     $smarty->assign("DNS_is_account",true);
342       /* Add new empty array to our record list */
343       if(isset($_POST['AddNewRecord'])){
344         $this->dnsEntry['RECORDS'][]  =array("type"=>"aRecord","value"=>"");
345       }
347       /* propose_ip */
348       if(isset($_POST['propose_ip'])){
349         foreach($this->Zones as $key => $name){
350           if($name == $this->dnsEntry['zoneName']){
351             $net = DNS::FlipIp(str_replace(".in-addr.arpa","",DNS::getNameFromMix($key)));
352             $this->ipHostNumber = $this->generateRandomIp($net);
353           }
354         }
355       }
357       /* Handle all posts */
358       $only_once =true;
359       foreach($_POST as $name => $value){
361         /* Check if we have to delete a record entry */
362         if((preg_match("/RemoveRecord_/",$name))&&($only_once)) {
364           /* Avoid performing this once again */
365           $only_once = false;
367           /* Extract id for specified entry */
368           $id = preg_replace("/RemoveRecord_/","",$name);
369           $id = preg_replace("/_.*$/","",$id);
371           /* Delete this record, mark edited entries to be able to delete them */
372           if(isset($this->dnsEntry['RECORDS'][$id])){
373             unset($this->dnsEntry['RECORDS'][$id]);
374           }
375         }
376       }
377       /* Assign smarty all non DNs attributes */
378       foreach($this->attributes as $attr){
379         $smarty->assign($attr,$this->$attr);
380       }
382       /* Assign smarty all DNS attributes */
383       foreach($this->DNSattributes as $attr){
384         $smarty->assign($attr,$this->dnsEntry[$attr]);
385       }
387       /* Assign all needed vars */
388  #     $smarty->assign("DNSAccount",$this->DNS_is_account);
389       $smarty->assign("hide_dns_check_box",$this->hide_dns_check_box);
390   
391       $smarty->assign("Zones",$this->Zones);
392       $smarty->assign("ZoneCnt",count($this->Zones));
393       $smarty->assign("ZoneKeys",($this->Zones));
394       $smarty->assign("IPisMust",(($this->IPisMust)||($this->DNS_is_account)));
396       /* Create zone array */
397       $idZones = array();
398       foreach($this->Zones as $id => $zone){
399         if($this->netmaskIsCoherent($id)) {
400           $idZones[$id] = $zone;
401         }else{
402           $idZones[$id] = $zone."&nbsp;("._("Not matching").")";
403         }
404       }
405       $smarty->assign("Zones",$idZones);
406       $smarty->assign("ZoneKeys", $this->Zones);
408       $tmp = $this->generateRecordsList();
410       $changeStateForRecords = $tmp['changeStateForRecords'];
412       $smarty->assign("records",$tmp['str']);
413       $smarty->assign("changeStateForRecords",$changeStateForRecords);
414       $smarty->assign("staticAddress","<font class=\"must\">*</font>");
416       $display.= $smarty->fetch(get_template_path('network.tpl', TRUE));
417     }
419     return($display);
420   }
423   function remove_from_parent()
424   {
425     if($this->initially_was_account){
427       $ldap = $this->config->get_ldap_link();
429       $tmp = array();
430       $this->dnsEntry['exists'] = false;
431       $tmp = DNS::getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
432   
433       /* Delete dns */
434       foreach($tmp['del'] as $dn => $del){
435         $ldap->cd($dn);
436         $ldap->rmdir_recursive($dn);
437         new log("remove","unknown/".get_class($this),$dn);
438         if (!$ldap->success()){
439           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_DEL, get_class()));
440         }
441       }
442     }
443   }
446   /* Save data to object */
447   function save_object()
448   {
450     if(isset($_POST['network_tpl_posted'])){
452       /* Save all posted vars */
453       plugin::save_object();
455       /* Handle DHCP Posts*/
456       if($this->dhcpEnabled && isset($_POST['network_tpl_posted'])){
457         foreach($this->dhcpAttributes as $attr){
458           if(isset($_POST[$attr])){
459             $this->$attr = $_POST[$attr];
460           }
461         }
462         if(isset($_POST['dhcp_is_Account'])){
463           $this->dhcp_is_Account = TRUE;
464         }else{
465           $this->dhcp_is_Account = FALSE;
466         }
467       }
469       /* Ge all non dns attributes (IP/MAC)*/
470       foreach($this->attributes as $attr){
471         if(isset($_POST[$attr]) && $this->acl_is_writeable($attr)){
472           $this->$attr = $_POST[$attr];
473         }
474       }
476       /* Check if DNS should be enabled / disabled */
477       if($this->DNS_is_account && $this->acl_is_removeable() && !isset($_POST['DNS_is_account'])){
478         $this->DNS_is_account = false;
479       }elseif(!$this->DNS_is_account && $this->acl_is_createable() && isset($_POST['DNS_is_account'])){
480         $this->DNS_is_account = true;
481       }
483       /* Get dns attributes */
484       if(($this->DNSenabled) && (isset($_POST['network_tpl_posted']))){
486         /* Check for posted record changes */
487         if(is_array($this->dnsEntry['RECORDS']) && $this->acl_is_writeable("Records")){
488           foreach($this->dnsEntry['RECORDS'] as $key => $value){
490             /* Check if type has changed */
491             if(isset($_POST['RecordTypeSelectedFor_'.$key])){
492               $this->dnsEntry['RECORDS'][$key]['type'] = $_POST['RecordTypeSelectedFor_'.$key];
493             }
494             /* Check if value has changed */
495             if(isset($_POST['RecordValue_'.$key])){
496               $this->dnsEntry['RECORDS'][$key]['value'] = $_POST['RecordValue_'.$key];
497             }
498           }
499         }
500         /* Get all basic DNS attributes (TTL, Clas ..)*/
501         foreach($this->DNSattributes as $attr){
502           if(isset($_POST[$attr]) && $this->acl_is_writeable($attr)){
503             $this->dnsEntry[$attr] = $_POST[$attr];
504           }
505         }
508       }
509       if($this->hide_dns_check_box){
510         $this->DNS_is_account = true;
511       }
512     }
513   }
516   /* Check supplied data */
517   function check()
518   {
519     /* Call common method to give check the hook */
520     $message= plugin::check();
522     /* Check if mac and ip are already used */
523     if(!empty($this->ipHostNumber) && $this->DNS_is_account && 
524         $this->ipHostNumber != $this->orig_ipHostNumber && 
525         in_array("ip:".$this->ipHostNumber,$this->used_ip_mac)){
526       $message[]= msgPool::duplicated(_("IP address"));
527     }
528     if(!empty($this->macAddress) && $this->dhcp_is_Account && 
529         $this->macAddress != $this->orig_macAddress && 
530         in_array("mac:".$this->macAddress,$this->used_ip_mac)){
531       $message[]= msgPool::duplicated(_("MAC address"));
532     }
534     /* Check if ip must be given
535      */  
536     if(($this->IPisMust)||($this->DNS_is_account)){
537       if (empty($this->ipHostNumber)){
538         $message[]= msgPool::required(_("IP address"));
539       }
541       if (!tests::is_ip($this->ipHostNumber)){
542         $message[]= msgPool::invalid(_("IP address"), "", "", "192.168.1.10");
543       }
544     }
546     /* Check if mac is empty 
547      */
548     if ($this->macAddress == "" ){
549       $message[]= msgPool::required(_("IP address"));
550     }
551     if(!tests::is_mac($this->macAddress)){
552       $message[]= msgPool::invalid(_("MAC address"), "", "", "00:0C:7F:31:33:F1");
553     }
555     /* only perfrom this checks if this is a valid DNS account */
556     if($this->DNS_is_account){
558       $checkArray = array();
559       $onlyOnce   = array();
561       //  $onlyOnce['cNAMERecord'] = 0;
562        $tmp = array_flip($this->Zones);
563        $tmp2 = $tmp[$this->dnsEntry['zoneName']];
564        if(!$this->netmaskIsCoherent($tmp2)){ //this->dnsEntry['zoneName'])){
565          $tmp2 = preg_replace("/^.*\//","",$tmp2);
566          $message[] =sprintf(_("The IP address '%s' is not part of the selected reverse zone '%s'!"),$this->ipHostNumber,$tmp2);
567        }
569       /* Walk through all entries and detect duplicates or mismatches
570        */  
571       foreach($this->dnsEntry['RECORDS'] as $name => $values){
573         /* Count record values, to detect duplicate entries for a specific record
574          */
575         if(!isset($checkArray[$values['type']][$values['value']])){
576           $checkArray[$values['type']][$values['value']] = 0;
577         }else{
578           $message[] = sprintf(_("Record type '%s' is duplicated!"),$values['type']);
579         }
581         /* Check if given entries in $onlyOnce are used more than once
582          */
583         if(isset($onlyOnce[$values['type']])){
584           $onlyOnce[$values['type']] ++;
585           if($onlyOnce[$values['type']] > 1){
586             $message[] = sprintf(_("Uniq record type '%s' is duplicated!"),$values['type']);
587           }
588         }
590         /* Skip txt record ... 
591          */
592         if($values['type'] == "tXTRecord") continue;
594         /* Check if there is an aRecord defined which uses the same IP as used in IPhostAddress 
595          */
596         if(($values['type'] == "aRecord")&&($values['value'] == $this->ipHostNumber)){
597           #TODO: Where's the problem here?
598           $message[]=sprintf(_("The IP address '%s' will be added as 'A Record', this will be done automatically, please remove the record."), 
599                $this->ipHostNumber);
600         }
602         /* only lower-case is allowed in record entries ... 
603          */
604         if($values['value'] != strtolower($values['value'])){
605           #TODO: What's in values['value']? Something for a propper message?
606           $message[] = sprintf(_("Only lowercase records are allowed, please check your '%ss'."),$values['type']);
607         }
608       }
609     }
610     return ($message);
611   }
614   /* Save to LDAP */
615   function save()
616   {
617     $ldap= $this->config->get_ldap_link();
618   
619     $dn = $this->parent->dn;
620  
621     /*******************/ 
622     /* IP-MAC HANDLING */
623     /*******************/ 
625     /* $dn was posted as parameter */
626     $this->dn = $dn;
627     
628     /* Save DNS setting & ip/Mac*/
629     plugin::save();
631     /* Write back to ldap */
632     $ldap->cd($this->dn);
633     $this->cleanup();
634     $ldap->modify ($this->attrs); 
636     /****************/ 
637     /* DHCP HANDLING */
638     /****************/ 
639   
640     /* New entry */
641     if($this->dhcpEnabled){
643       if(count($this->dhcpHostEntry) == 0){
644         $this->dialog = new dhcpHost($this->dhcpParentNode,TRUE);
645         $this->dialog->cn = $this->cn;
646         $this->dialog->dhcpHWAddress = "ethernet ".$this->macAddress;
647         if(!empty($this->ipHostNumber)){
648           $this->dialog->statements['fixed-address'] = $this->ipHostNumber;
649         }
650         $this->dialog->execute();
651         $this->dialog->save_object(); 
652         $this->dhcpHostEntry = $this->dialog->save();
653         if(count($this->dhcpHostEntry['dhcpOption']) == 0){
654           $this->dhcpHostEntry['dhcpOption']= array("host-name ".$this->cn);
655         }
656       }
658       /* Write mac address to dhcp settings */
659       if($this->dhcp_is_Account){
660         if(!isset($this->dhcpHostEntry['dhcpHWAddress'][0]) || 
661             !preg_match("/ethernet ".$this->macAddress."/",$this->dhcpHostEntry['dhcpHWAddress'][0])){
662           $this->dhcpHostEntry['dhcpHWAddress'] = array("ethernet ".$this->macAddress);
663           $this->dhcpHostEntry['MODIFIED'] = TRUE;
664         }
665       }
667       /* Updated IP host number */
668       if($this->dhcp_is_Account){
669         foreach($this->dhcpHostEntry['dhcpStatements'] as $id => $value){
670           if(preg_match("/^fixed-address/",$value)){
671             $this->dhcpHostEntry['dhcpStatements'][$id] = "fixed-address ".$this->ipHostNumber; 
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 ?>