Code

Updated host network settings ACLs
[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     if($this->acl_is_writeable("ipHostNumber")){
271       foreach($_POST as $name => $value){
272         if(preg_match("/^additionalHostNumbers_add/",$name)){
273           $this->additionalHostNumbers[] = "";
274           break;
275         }
277         /* Delete given entry */
278         if(preg_match("/^additionalHostNumbers_del_/",$name)){
279           $id = preg_replace("/^^additionalHostNumbers_del_([0-9]*)_.*/","\\1",$name);
280           if(isset($this->additionalHostNumbers[$id])){
281             unset($this->additionalHostNumbers[$id]);
282             $this->additionalHostNumbers = array_values($this->additionalHostNumbers);
283           }
284           break;
285         } 
286       }
287     }
288  
289     $smarty->assign("additionalHostNumbers",$this->additionalHostNumbers);
290     $smarty->assign("staticAddress", ""); 
291  
292     /**********
293      * Autonet completion
294      **********/
295  
296     /* Check for autonet button */
297     if (isset($_POST['autonet']) && ($this->acl_is_writeable("ipHostNumber") || $this->acl_is_writeable("macAddress"))){
298       $d= new gosaSupportDaemon(TRUE, 0.5);
299       $res= $d->_send("<xml><header>gosa_network_completition</header>".
300           "<source>GOSA</source><target>GOSA</target><hostname>".$this->cn."</hostname></xml>", TRUE);
301       if (isset($res['XML']['IP']) && $this->acl_is_writeable("ipHostNumber")){
302         $this->ipHostNumber= $res['XML']['IP'];
303       }
304       if (isset($res['XML']['MAC']) && $this->acl_is_writeable("macAddress")){
305         $this->macAddress= $res['XML']['MAC'];
306       }
307     }
309   
310     /**********
311      * DHCP Handling
312      **********/
313  
314     if(isset($_POST['dhcpEditOptions']) && $this->acl_is_readable("dhcpSetup")){
315       if(count($this->dhcpHostEntry) == 0){
316         $this->dialog = new dhcpHost($this->dhcpParentNode,TRUE);
317       }else{
318         $this->dialog = new dhcpHost($this->dhcpHostEntry,TRUE);
319       }
320       $this->dialog->cn   = $this->cn;
321       $this->dialog->read_only     = !$this->acl_is_writeable("dhcpSetup");
322       $this->dialog->dhcpHWAddress = "ethernet ".$this->macAddress; 
323       if(!empty($this->ipHostNumber)){
324         $this->dialog->statements['fixed-address'] = $this->ipHostNumber; 
325       }
326     }
328     if(isset($_POST['cancel_dhcp'])){
329       $this->dialog = FALSE; 
330     }
332     if(isset($_POST['save_dhcp']) && $this->acl_is_writeable("dhcpSetup")){
333       $this->dialog->save_object();
334       $msgs = $this->dialog->check(array());
335       if(count($msgs)){
336         foreach($msgs as $msg){
337           msg_dialog::display(_("Error"), $msg, ERROR_DIALOG);
338         }
339       }else{
340         $this->dhcpHostEntry = $this->dialog->save();
341         $this->dialog = FALSE; 
342       }
343     }
345     if(is_object($this->dialog)){
346       $this->dialog->save_object();
347       return($this->dialog->execute());
348     }
349  
350     $smarty->assign("dhcpEnabled",    $this->dhcpEnabled && $this->acl_is_readable("dhcpSetup"));
351     $smarty->assign("dhcp_is_Account",$this->dhcp_is_Account);
352     $smarty->assign("dhcpParentNode", $this->dhcpParentNode);
353     $smarty->assign("dhcpParentNodes",$this->dhcpParentNodes);
354     $smarty->assign("dhcpParentNodeCnt",count($this->dhcpParentNodes));
356     /**********
357      * DNS Handling
358      **********/
360     /* There is no dns available
361      */
362     $smarty->assign("DNS_is_account",$this->DNS_is_account);
363     $smarty->assign("DNSenabled",$this->DNSenabled && $this->acl_is_readable("dnsSetup"));
365     if($this->DNSenabled == false){
367       /* Is IP address must ? */
368 #      $smarty->assign("DNS_is_account",false);
369       $smarty->assign("IPisMust",(($this->IPisMust)||($this->DNS_is_account)));
371       /* Assign smarty all non DNs attributes */
372       foreach($this->attributes as $attr){
373         $smarty->assign($attr,$this->$attr);
374       }
375       $smarty->assign("staticAddress","<font class=\"must\">*</font>");
377       $display.= $smarty->fetch(get_template_path('network.tpl', TRUE));
378     }else{
379  #     $smarty->assign("DNS_is_account",true);
381       /* Add new empty array to our record list */
382       if(isset($_POST['AddNewRecord']) && $this->acl_is_writeable("dnsSetup")){
383         $this->dnsEntry['RECORDS'][]  =array("type"=>"aRecord","value"=>"");
384       }
386       /* propose_ip */
387       if(isset($_POST['propose_ip']) && $this->acl_is_writeable("ipHostNumber")){
388         foreach($this->Zones as $key => $name){
389           if($name == $this->dnsEntry['zoneName']){
390             $net = DNS::FlipIp(str_replace(".in-addr.arpa","",DNS::getNameFromMix($key)));
391             $this->ipHostNumber = $this->generateRandomIp($net);
392           }
393         }
394       }
396       /* Handle all posts */
397       $only_once =true;
398       if($this->acl_is_writeable("dnsSetup")){
399         foreach($_POST as $name => $value){
401           /* Check if we have to delete a record entry */
402           if((preg_match("/RemoveRecord_/",$name))&&($only_once)) {
404             /* Avoid performing this once again */
405             $only_once = false;
407             /* Extract id for specified entry */
408             $id = preg_replace("/RemoveRecord_/","",$name);
409             $id = preg_replace("/_.*$/","",$id);
411             /* Delete this record, mark edited entries to be able to delete them */
412             if(isset($this->dnsEntry['RECORDS'][$id])){
413               unset($this->dnsEntry['RECORDS'][$id]);
414             }
415           }
416         }
417       }
418       /* Assign smarty all non DNs attributes */
419       foreach($this->attributes as $attr){
420         $smarty->assign($attr,$this->$attr);
421       }
423       /* Assign smarty all DNS attributes */
424       foreach($this->DNSattributes as $attr){
425         $smarty->assign($attr,$this->dnsEntry[$attr]);
426       }
428       /* Assign all needed vars */
429  #     $smarty->assign("DNSAccount",$this->DNS_is_account);
430       $smarty->assign("hide_dns_check_box",$this->hide_dns_check_box);
431   
432       $smarty->assign("Zones",$this->Zones);
433       $smarty->assign("ZoneCnt",count($this->Zones));
434       $smarty->assign("ZoneKeys",($this->Zones));
435       $smarty->assign("IPisMust",(($this->IPisMust)||($this->DNS_is_account)));
437       /* Create zone array */
438       $idZones = array();
439       foreach($this->Zones as $id => $zone){
440         if($this->netmaskIsCoherent($id)) {
441           $idZones[$id] = $zone;
442         }else{
443           $idZones[$id] = $zone."&nbsp;("._("Not matching").")";
444         }
445       }
446       $smarty->assign("Zones",$idZones);
447       $smarty->assign("ZoneKeys", $this->Zones);
449       $tmp = $this->generateRecordsList();
451       $changeStateForRecords = $tmp['changeStateForRecords'];
453       $smarty->assign("records",$tmp['str']);
454       $smarty->assign("changeStateForRecords",$changeStateForRecords);
455       $smarty->assign("staticAddress","<font class=\"must\">*</font>");
457       $display.= $smarty->fetch(get_template_path('network.tpl', TRUE));
458     }
460     return($display);
461   }
464   function remove_from_parent()
465   {
466     if($this->DNS_is_account){
468       $ldap = $this->config->get_ldap_link();
470       $tmp = array();
471       $this->dnsEntry['exists'] = false;
472       $tmp = DNS::getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
473   
474       /* Delete dns */
475       foreach($tmp['del'] as $dn => $del){
476         $ldap->cd($dn);
477         $ldap->rmdir_recursive($dn);
478         new log("remove","unknown/".get_class($this),$dn);
479         if (!$ldap->success()){
480           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_DEL, get_class()));
481         }
482       }
483     }
484   }
487   /* Save data to object */
488   function save_object()
489   {
491     if(isset($_POST['network_tpl_posted'])){
493       /* Save all posted vars */
494       plugin::save_object();
496       /******
497         Additional IP Host Numbers 
498        ******/
500       /* Get posts for all additionally added ipHostNumbers */
501       if($this->acl_is_writeable("ipHostNumber")){
502         foreach($this->additionalHostNumbers as $id => $value){
503           if(isset($_POST['additionalHostNumbers_'.$id])){
504             $this->additionalHostNumbers[$id] = get_post('additionalHostNumbers_'.$id);
505           }
506         } 
507       } 
510       /******
511         DHCP posts
512        ******/
514       if($this->acl_is_writeable("dhcpSetup") && $this->dhcpEnabled && isset($_POST['network_tpl_posted'])){
515         foreach($this->dhcpAttributes as $attr){
516           if(isset($_POST[$attr])){
517             $this->$attr = $_POST[$attr];
518           }
519         }
520         if(isset($_POST['dhcp_is_Account'])){
521           $this->dhcp_is_Account = TRUE;
522         }else{
523           $this->dhcp_is_Account = FALSE;
524         }
525       }
527       /* Ge all non dns attributes (IP/MAC)*/
528       foreach($this->attributes as $attr){
529         if(isset($_POST[$attr]) && $this->acl_is_writeable($attr)){
530           $this->$attr = $_POST[$attr];
531         }
532       }
535       /******
536         DNS posts
537        ******/
539       /* Check if DNS should be enabled / disabled */
540       if($this->DNS_is_account && $this->acl_is_writeable("dnsSetup") && !isset($_POST['DNS_is_account'])){
541         $this->DNS_is_account = false;
542       }elseif(!$this->DNS_is_account && $this->acl_is_writeable("dnsSetup") && isset($_POST['DNS_is_account'])){
543         $this->DNS_is_account = true;
544       }
546       /* Get dns attributes */
547       if(($this->DNSenabled) && (isset($_POST['network_tpl_posted'])) && $this->acl_is_writeable("dnsSetup")){
549         /* Check for posted record changes */
550         if(is_array($this->dnsEntry['RECORDS']) && $this->acl_is_writeable("Records")){
551           foreach($this->dnsEntry['RECORDS'] as $key => $value){
553             /* Check if type has changed */
554             if(isset($_POST['RecordTypeSelectedFor_'.$key])){
555               $this->dnsEntry['RECORDS'][$key]['type'] = $_POST['RecordTypeSelectedFor_'.$key];
556             }
557             /* Check if value has changed */
558             if(isset($_POST['RecordValue_'.$key])){
559               $this->dnsEntry['RECORDS'][$key]['value'] = $_POST['RecordValue_'.$key];
560             }
561           }
562         }
563         /* Get all basic DNS attributes (TTL, Clas ..)*/
564         foreach($this->DNSattributes as $attr){
565           if(isset($_POST[$attr]) && $this->acl_is_writeable($attr)){
566             $this->dnsEntry[$attr] = $_POST[$attr];
567           }
568         }
571       }
572       if($this->hide_dns_check_box){
573         $this->DNS_is_account = true;
574       }
575     }
576   }
579   /* Check supplied data */
580   function check()
581   {
582     /* Call common method to give check the hook */
583     $message= plugin::check();
585     /******
586       check additional IP Host Numbers 
587      ******/
589     foreach($this->additionalHostNumbers as $id => $value){
590       if(!tests::is_ip($value)){
591         $message[]= msgPool::invalid(sprintf(_("IP address #%s"),($id +2)), "", "", "192.168.1.10");
592       }
593     }
596     /* Check if mac and ip are already used */
597     if(!empty($this->ipHostNumber) && $this->DNS_is_account && 
598         $this->ipHostNumber != $this->orig_ipHostNumber && 
599         in_array("ip:".$this->ipHostNumber,$this->used_ip_mac)){
600       $message[]= msgPool::duplicated(_("IP address"));
601     }
602     if(!empty($this->macAddress) && $this->dhcp_is_Account && 
603         $this->macAddress != $this->orig_macAddress && 
604         in_array("mac:".$this->macAddress,$this->used_ip_mac)){
605       $message[]= msgPool::duplicated(_("MAC address"));
606     }
608     /* Check if ip must be given
609      */  
610     if(($this->IPisMust)||($this->DNS_is_account)){
611       if (empty($this->ipHostNumber)){
612         $message[]= msgPool::required(_("IP address"));
613       }elseif (!tests::is_ip($this->ipHostNumber)){
614         $message[]= msgPool::invalid(_("IP address"), "", "", "192.168.1.10");
615       }
616     }
618     /* Check if mac is empty 
619      */
620     if($this->MACisMust || $this->dhcp_is_Account){
621       if ($this->macAddress == "" ){
622         $message[]= msgPool::required(_("MAC address"));
623       }elseif(!tests::is_mac($this->macAddress)){
624         $message[]= msgPool::invalid(_("MAC address"), "", "", "00:0C:7F:31:33:F1");
625       }
626     }
628     /* only perfrom this checks if this is a valid DNS account */
629     if($this->DNS_is_account){
631       $checkArray = array();
632       $onlyOnce   = array();
634       //  $onlyOnce['cNAMERecord'] = 0;
635        $tmp = array_flip($this->Zones);
636        $tmp2 = $tmp[$this->dnsEntry['zoneName']];
637        if(!$this->netmaskIsCoherent($tmp2)){ //this->dnsEntry['zoneName'])){
638          $tmp2 = preg_replace("/^.*\//","",$tmp2);
639          $message[] =sprintf(_("The IP address '%s' is not part of the selected reverse zone '%s'!"),$this->ipHostNumber,$tmp2);
640        }
642       /* Walk through all entries and detect duplicates or mismatches
643        */  
644       foreach($this->dnsEntry['RECORDS'] as $name => $values){
646         /* Count record values, to detect duplicate entries for a specific record
647          */
648         if(!isset($checkArray[$values['type']][$values['value']])){
649           $checkArray[$values['type']][$values['value']] = 0;
650         }else{
651           $message[] = sprintf(_("Record type '%s' is duplicated!"),$values['type']);
652         }
654         /* Check if given entries in $onlyOnce are used more than once
655          */
656         if(isset($onlyOnce[$values['type']])){
657           $onlyOnce[$values['type']] ++;
658           if($onlyOnce[$values['type']] > 1){
659             $message[] = sprintf(_("Uniq record type '%s' is duplicated!"),$values['type']);
660           }
661         }
663         /* Skip txt record ... 
664          */
665         if($values['type'] == "tXTRecord") continue;
667         /* Check if there is an aRecord defined which uses the same IP as used in IPhostAddress 
668          */
669         if(($values['type'] == "aRecord")&&($values['value'] == $this->ipHostNumber)){
670           #TODO: Where's the problem here?
671           $message[]=sprintf(_("The IP address '%s' will be added as 'A Record', this will be done automatically, please remove the record."), 
672                $this->ipHostNumber);
673         }
675         /* only lower-case is allowed in record entries ... 
676          */
677         if($values['value'] != strtolower($values['value'])){
678           #TODO: What's in values['value']? Something for a propper message?
679           $message[] = sprintf(_("Only lowercase records are allowed, please check your '%ss'."),$values['type']);
680         }
681       }
682     }
683     return ($message);
684   }
687   /* Save to LDAP */
688   function save()
689   {
690     $ldap= $this->config->get_ldap_link();
691   
692     $dn = $this->parent->dn;
693  
694     /*******************/ 
695     /* IP-MAC HANDLING */
696     /*******************/ 
698     /* $dn was posted as parameter */
699     $this->dn = $dn;
700     
701     /* Save DNS setting & ip/Mac*/
702     plugin::save();
704     /* Add all additional ipHostNumbers now 
705      */
706     if(!empty($this->ipHostNumber)){
707       $this->attrs['ipHostNumber'] = array($this->ipHostNumber);
708     }
709     foreach($this->additionalHostNumbers as $value){
710       $this->attrs['ipHostNumber'][] = $value;
711     }
713     /* Write back to ldap */
714     $ldap->cd($this->dn);
715     $this->cleanup();
716     $ldap->modify ($this->attrs); 
718     /****************/ 
719     /* DHCP HANDLING */
720     /****************/ 
721   
722     /* New entry */
723     if($this->dhcpEnabled && $this->acl_is_writeable("dhcpSetup")) {
725       if(count($this->dhcpHostEntry) == 0){
726         $this->dialog = new dhcpHost($this->dhcpParentNode,TRUE);
727         $this->dialog->cn = $this->cn;
728         $this->dialog->dhcpHWAddress = "ethernet ".$this->macAddress;
729         if(!empty($this->ipHostNumber)){
730           $this->dialog->statements['fixed-address'] = $this->ipHostNumber;
731         }
732         $this->dialog->execute();
733         $this->dialog->save_object(); 
734         $this->dhcpHostEntry = $this->dialog->save();
735         if(count($this->dhcpHostEntry['dhcpOption']) == 0){
736           $this->dhcpHostEntry['dhcpOption']= array("host-name ".$this->cn);
737         }
738       }
740       /* Write mac address to dhcp settings */
741       if($this->dhcp_is_Account){
742         if(!isset($this->dhcpHostEntry['dhcpHWAddress'][0]) || 
743             !preg_match("/ethernet ".$this->macAddress."/",$this->dhcpHostEntry['dhcpHWAddress'][0])){
744           $this->dhcpHostEntry['dhcpHWAddress'] = array("ethernet ".$this->macAddress);
745           $this->dhcpHostEntry['MODIFIED'] = TRUE;
746         }
747       }
749       /* Updated IP host number */
750       if($this->dhcp_is_Account){
751         foreach($this->dhcpHostEntry['dhcpStatements'] as $id => $value){
752           if(preg_match("/^fixed-address/",$value)){
753             $this->dhcpHostEntry['dhcpStatements'][$id] = "fixed-address ".$this->ipHostNumber; 
754             $this->dhcpHostEntry['MODIFIED'] = TRUE;
755           }
756         }
757       }
759       /* Unset dhcpStatements if this attribute is empty  */
760       if(isset($this->dhcpHostEntry['dhcpStatements']) && 
761           ($this->dhcpHostEntry['dhcpStatements'] == "" || count($this->dhcpHostEntry['dhcpStatements']) == 0) ){
762         unset($this->dhcpHostEntry['dhcpStatements']);
763       }
764   
765       /* DHCP removed */
766       if($this->initial_dhcp_is_Account && !$this->dhcp_is_Account){
767         $ldap->rmdir_recursive($this->dhcpHostEntry['dn']);
768         if (!$ldap->success()){
769           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dhcpHostEntry['dn'], LDAP_DEL, get_class()));
770         }
772         $tmp = new servdhcp($this->config,$this->dhcpParentNode);
773         $tmp->handle_post_events("remove");
774       }
776       /* DHCP Added */
777       if(!$this->initial_dhcp_is_Account && $this->dhcp_is_Account){
778         $attrs = $this->dhcpHostEntry;
779         unset($attrs['MODIFIED']);
780         unset($attrs['dn']);
781         $ldap->cd("cn=".$this->cn.",".$this->dhcpParentNode);
782         $res = $ldap->add($attrs);
784         $tmp = new servdhcp($this->config,$this->dhcpParentNode);
785         $tmp->handle_post_events("add");
787         if (!$ldap->success()){
788           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=".$this->cn.",".$this->dhcpParentNode, LDAP_ADD, get_class()));
789         }
790       }
792       /* DHCP still activated */
793       if($this->initial_dhcp_is_Account && $this->dhcp_is_Account){
795         /* DHCP node changed */
796         if(($this->initial_dhcpParentNode != $this->dhcpParentNode) || 
797            ($this->cn != $this->OrigCn)){
798           $attrs = $this->dhcpHostEntry;
799           $attrs['cn'] = $this->cn;
800           unset($attrs['dn']);
801           unset($attrs['MODIFIED']);
802           $ldap->cd("cn=".$this->cn.",".$this->dhcpParentNode);
803           $res = $ldap->add($attrs);
805           $tmp = new servdhcp($this->config,$this->dhcpParentNode);
806           $tmp->handle_post_events("modify");
808           if (!$ldap->success()){
809             msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=".$this->cn.",".$this->dhcpParentNode, LDAP_ADD, get_class()));
810           }
811           if($res){
812             $ldap->rmdir_recursive($this->dhcpHostEntry['dn']);
813             if (!$ldap->success()){
814               msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dhcpHostEntry['dn'], LDAP_DEL, get_class()));
815             }
816           }
817         }
818          
819         /* SAME node but modified */ 
820         if(isset($this->dhcpHostEntry['MODIFIED']) && $this->dhcpHostEntry['MODIFIED'] == 1  && 
821             $this->initial_dhcpParentNode == $this->dhcpParentNode){
822           $attrs = $this->dhcpHostEntry;
823           unset($attrs['dn']);
824           unset($attrs['MODIFIED']);
825           $ldap->cd($this->dhcpHostEntry['dn']);
826           $ldap->modify($attrs);
827           
828           $tmp = new servdhcp($this->config,$this->dhcpParentNode);
829           $tmp->handle_post_events("modify");
831           if (!$ldap->success()){
832             msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dhcpHostEntry['dn'], LDAP_MOD, get_class()));
833           }
834         }    
835       }
836     }
837     $this->dialog = FALSE; 
839     /****************/ 
840     /* DNS HANDLING */
841     /****************/ 
843     /* If isn't DNS account but initially was DNS account 
844        remove all DNS entries 
845      */ 
846     if((!$this->DNSenabled) || ((!$this->DNS_is_account)&&(!$this->initially_was_account))){
847       return;
848     }elseif($this->acl_is_writeable("dnsSetup")){
850       /* Add ipHostNumber to aRecords
851        */
852       $backup_dnsEntry = $this->dnsEntry;
853       if(!empty($this->ipHostNumber)){
854         $this->dnsEntry['RECORDS'][] = array("type"=>"aRecord","value"=>$this->ipHostNumber);
855         $ptr = $this->get_pTRRecord();
856         if(!empty($ptr)){
857           $this->dnsEntry['RECORDS'][] = array("type"=>"pTRRecord","value"=>$ptr);
858         } 
859       }
861       /* Create diff and follow instructions 
862        * If Account was disabled, remove account by setting exists to false
863        */
864       if((!$this->DNS_is_account)&&($this->initially_was_account)){  
865         $this->dnsEntry['exists'] = false;
866         $tmp = DNS::getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
867       }else{
868         $this->dnsEntry['exists'] = $this->DNS_is_account;
869         $tmp = DNS::getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
870       }   
872       /* move follwoing entries 
873        */
874       foreach($tmp['move'] as $src => $dst){
875         $this->recursive_move($src,$dst);
876       }
878       /* Delete dns */
879       foreach($tmp['del'] as $dn => $del){
880         $ldap->cd($dn);
881         $ldap->rmdir_recursive($dn);
882         new log("modify","unknown/".get_class($this),$dn,array("*"),$ldap->get_error());
883       }
885       /* Add || Update new DNS entries 
886        */
887       foreach($tmp['add'] as $dn => $attrs){
888         $ldap->cd($dn);
889         $ldap->cat($dn, array('dn'));
890         if(count($ldap->fetch())){
891           $ldap->cd($dn);
892           $ldap->modify ($attrs); 
893         }else{
894           $ldap->cd($dn);
895           $ldap->add($attrs);
896         }
897         new log("modify","unknown/".get_class($this),$dn,array_keys($attrs),$ldap->get_error());
898       }
901       /* Display errors 
902        */
903       if (!$ldap->success()){
904         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, 0, get_class()));
905       }
907       $tmp2 = new servdns($this->config,$this->dn);
908       $tmp2->handle_post_events("modify");
910       $this->dnsEntry =  $backup_dnsEntry;
911     }
912   }
914   /*  Create html table with all used record types
915    */
916   function generateRecordsList()
917   {
918     $changeStateForRecords = "";
919     
920     if(!$this->DNS_is_account) {
921       $str = "<input type='submit' value='"._("Add")."' name='AddNewRecord' id='AddNewRecord' disabled='disabled'>";
922       return(array("str" => $str, "changeStateForRecords"=> ""));
923     }
924  
925     $str = "<table summary='' width='100%'>";
926     foreach($this->dnsEntry['RECORDS'] as $key => $entry){
928         $changeStateForRecords.= "changeState('RecordTypeSelectedFor_".$key."');\n";
929         $changeStateForRecords.= "changeState('RecordValue_".$key."');\n";
930         $changeStateForRecords.= "changeState('RemoveRecord_".$key."');\n";
932         $str.=" <tr>".
933           "   <td>".$this->generateRecordListBox($entry['type'],"RecordTypeSelectedFor_".$key)."</td>".
934           "   <td><input type='text' value='".$entry['value']."' name='RecordValue_".$key."' id='RecordValue_".$key."'></td>".
935           "   <td><input type='submit' name='RemoveRecord_".$key."' value='"._("Delete")."' id='RemoveRecord_".$key."'></td>".
936           "</tr>";
937     }
939     $str.= "  <tr>".
940            "    <td colspan=2 width='50%'></td><td>".
941            "      <input type='submit' value='"._("Add")."' name='AddNewRecord' id='AddNewRecord'>".
942            "    </td>".
943            "  </tr>".
944            "</table>";
945      $ret =  array("str" => $str, "changeStateForRecords" => $changeStateForRecords);
946     return($ret);
947   }
950   /* Create a html select box which allows us to select different types of records 
951    */
952   function generateRecordListBox($selected,$name)
953   {
954     $str = "<select name='".$name."' id='".$name."'>";
955     foreach($this->RecordTypes as $type => $value){
956       $use = "";
957       if($type == $selected){
958         $use = " selected ";
959       }
960       $str.="\n <option value='".$type."' ".$use.">".strtoupper(preg_replace("/record/i","",$type))."</option>";
961     }
962     $str.="</select>";
963     return($str); 
964   }
967   /* Return plugin informations for acl handling  */ 
968   static function plInfo()
969   {
970     $tmp =  array(
971         "plShortName"   => _("DNS"),
972         "plDescription" => _("DNS settings"),
973         "plSelfModify"  => FALSE,
974         "plDepends"     => array(),
975         "plPriority"    => 5,
976         "plSection"     => array("administration"),
977         "plCategory"    => array("workstation","terminal","phone","server","component","printer","winworkstation"),
979         "plProvidedAcls"=> array(
980           "ipHostNumber"  => _("IP address"),
981           "macAddress"    => _("MAC address"))
982         );
984     /* Hide all dns/dhcp configurations if not available
985      */
986     if(class_available("servdns")){
987       $tmp['plProvidedAcls']["dnsSetup"]    = _("DNS configuration");
988     }
989     if(class_available("servdhcp")){
990       $tmp['plProvidedAcls']["dhcpSetup"]   = _("DHCP configuration");
991     }
992     return($tmp);
993   }
995   
996   function get_dhcp_host_entry()
997   {
998     $attrs = array();
999     $dn = $this->get_dhcp_host_entry_dn();
1000     if($dn){
1001       $ldap = $this->config->get_ldap_link();
1002       $ldap->cd($this->config->current['BASE']);
1003       $ldap->cat($dn,array("*"));
1004       if($ldap->count()){
1005         $attrs = $ldap->fetch();
1006         foreach($attrs as $key => $value){
1007           if(is_numeric($key) || ($key == "count")){
1008             unset($attrs[$key]);
1009           }
1010           if(is_array($value) && isset($value['count'])){
1011             unset($attrs[$key]['count']);
1012           }
1013         }
1014       }
1015     }
1016     return($attrs);
1017   }
1020   function get_dhcp_host_entry_dn()
1021   {
1022     $ldap = $this->config->get_ldap_link();
1023     $ldap->cd($this->config->current['BASE']);
1024     $ldap->search ("(&(objectClass=dhcpHost)(cn=".$this->cn."))",array("cn","dn"));
1026     if($ldap->count()){
1027       $attr = $ldap->fetch();
1028       return($attr['dn']);
1029     }else{
1030       return("");
1031     }
1032   }  
1035   function get_dhcp_parent_node()
1036   {
1037     return(preg_replace("/^cn=".normalizePreg($this->cn).",/","",$this->get_dhcp_host_entry_dn()));
1038   }
1041   function get_dhcp_parent_nodes()
1042   {
1043     $ldap = $this->config->get_ldap_link();
1044     $ldap->cd($this->config->current['BASE']);
1045     $ldap->search("(objectClass=dhcpService)",array("dhcpPrimaryDN"));
1046     
1047     $dhcp_dns = array();
1048     while($attr = $ldap->fetch()){
1049       $dhcp_dns[$attr['dn']] = $attr['dhcpPrimaryDN'][0];
1050     }
1051  
1052     foreach($dhcp_dns as $key => $pri_dns){
1053       $ldap->cat($pri_dns,array("cn"));
1054       $tmp = $ldap->fetch();
1055       if(isset($tmp['cn'][0])){
1056         $dhcp_dns[$key] = $tmp['cn'][0];
1057       }else{
1058         unset($dhcp_dns[$key]);
1059       }
1060     }
1062     $tmp = $tmp2 = array();
1063     foreach($dhcp_dns as $dn => $cn){
1064       $ldap->cd($dn);
1065       $ldap->search("(|(objectClass=dhcpService)(objectClass=dhcpGroup)".
1066                     "(objectClass=dhcpSubnet)(objectClass=dhcpSharedNetwork))",array("cn"));
1067       while($attr = $ldap->fetch()){
1068         $tmp[$attr['dn']] = $attr['cn'][0];
1069       }
1070       $tmp2 = array_merge($tmp2,$this->create_tree($tmp,preg_replace("/^[^,]+,/i","",$dn),"(".$cn.")&nbsp;"));
1071     }
1072     return($tmp2);
1073   }
1075   
1076   /* this function returns the default ptr record entry */
1077   function get_pTRRecord()
1078   {
1079     if(!empty($this->ipHostNumber) && isset($this->dnsEntry['zoneName']) && !empty($this->dnsEntry['zoneName'])){
1080       $ldap = $this->config->get_ldap_link();
1081       $ldap->cat(DNS::getDNSZoneDN($this->config,$this->dnsEntry['zoneName']));
1082       $attrs = $ldap->fetch();
1083       $tmp = array_flip($this->Zones);
1084       $tmp = preg_replace("/^[^\/]*+\//","",$tmp[$this->dnsEntry['zoneName']]);
1085       $tmp = trim(preg_replace("/\.in-addr.arpa$/","",$tmp));
1086       $ptr = preg_replace("/^".normalizePreg(DNS::FlipIp($tmp))."\./","",$this->ipHostNumber);
1087       return($ptr);
1088     }else{
1089       return(FALSE);
1090     }
1091   }
1093   
1094   function generateRandomIP($net = "")
1095   {
1096     $str = $net;
1097     $cnt = 4;
1098     while(substr_count($str,".") < 3 && $cnt > 0){
1099       $str .= ".".rand(0,255);
1100       $str = preg_replace("/\.\.*/",".",$str);
1101       $str = trim($str,". ");
1102       $cnt --;
1103     }
1104     return($str);
1105   }
1107   
1108   function create_tree($arr,$base,$current = "")
1109   {
1110     $ret = array();
1111     foreach($arr as $r => $name){
1112       $base_part = str_replace($base,"",$r);
1113       if(preg_match("/^[a-z]*=".normalizePreg($name)."(|,)$/i",$base_part)){
1114         $ret[$r] = $current.$name;
1115         $tmp = $this->create_tree($arr,$r,$current.".&nbsp;");
1116         foreach($tmp as $sub_key => $sub_name){
1117           $ret[$sub_key] = $sub_name;
1118         }
1119       } 
1120     }
1121     return($ret);
1122   }
1124   function force_dns()
1125   {
1126     if($this->DNSenabled){
1128       /* Only force DNS account, if we have at least on dns Zone */
1129       if(count($this->Zones)){
1130         $this->DNS_is_account  = TRUE;
1131         $this->hide_dns_check_box = TRUE;
1132       }
1133     }
1134   }
1137 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1138 ?>