Code

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