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