Code

022d92d2516ff8f817e9b018430418a84f1aea51
[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("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;
68   var $namingAttr               = "cn";
70   /*  Terminal dns 
71    */
72   function termDNS (&$config, $parent,$objectClasses,$IPisMust = false,$namingAttr = "cn")
73   {
74     /* We need to know which objectClasses are used, to store the ip/mac
75      * Because of different type of devices   
76      */ 
77     $this->parent         = $parent;
78     $this->objectclasses  =  $objectClasses;
79     $this->IPisMust       = $IPisMust;
80     $this->namingAttr     = $namingAttr;
82     plugin::plugin ($config, $parent->dn, $this->parent);
83   
84     $this->attrs = &$this->parent->attrs;
86     if(isset($this->attrs[$namingAttr][0])){
87       $this->OrigCn = preg_replace("/\\\$\$/","",$this->attrs[$namingAttr][0]);
88       $this->cn = preg_replace("/\\\$\$/","",$this->attrs[$namingAttr][0]);
89     }
91     /* Create list of additional ipHostNumber.
92      */
93     $this->additionalHostNumbers = array();
94     if(isset($this->attrs['ipHostNumber']) && $this->attrs['ipHostNumber']['count'] > 1){
95       for($i = 1 ; $i < $this->attrs['ipHostNumber']['count']; $i ++){
96         $this->additionalHostNumbers[] = $this->attrs['ipHostNumber'][$i];
97       }
98     }
99  
100     /************
101      * DHCP 
102      ************/
104     /* Hide all dhcp specific code, if dhcp plugin is not present in config */
105     $this->dhcpEnabled = FALSE;
106     if($this->config->search("servdhcp","class",array("tabs"))){
107       $this->dhcpEnabled = TRUE;
108     }
109     
110     if(!class_available("dhcpHost")){
111       $this->dhcpEnabled = FALSE;
112     }
114     if($this->dhcpEnabled){
115       $this->dhcpParentNodes = $this->get_dhcp_parent_nodes();
116       $this->dhcpParentNode  = $this->get_dhcp_parent_node();
117       if($this->dhcpParentNode){
118         $this->dhcp_is_Account = TRUE;
119         $this->initial_dhcp_is_Account = TRUE;
120         $this->dhcpHostEntry  = $this->get_dhcp_host_entry();    
121       }
122       $this->initial_dhcpHostEntry = $this->dhcpHostEntry;
123       $this->initial_dhcpParentNode= $this->dhcpParentNode;
124     }
127     /************
128      * DNS
129      ************/
130  
131     /* Hide all dns specific code, if dns is not available 
132      */
133     $DNSenabled = false;
134     foreach($this->config->data['TABS']['SERVERSERVICE'] as $tab){
135       if(preg_match("/^servdns$/",$tab['CLASS'])){
136         $this->DNSenabled = true;
137       }
138     }
140     if(!class_available("DNS")){
141       $this->DNSenabled = FALSE;
142     }
143   
144     if(!$this->DNSenabled){
145       $this->DNS_is_account = false;
146       return;
147     }
149     if($this->DNSenabled){
151       /* Get Zones  
152        */
153       $this->Zones        = DNS::getAvailableZones($config);
155       /* Get Entry 
156        */
157       $this->dnsEntry     = DNS::getDNSHostEntries($config,$this->OrigCn);
159       $ptr = DNS::FlipIp($this->get_pTRRecord());
161       /* Remove A record which equals $this->ipHostNumber
162        */
163       foreach($this->dnsEntry['RECORDS'] as $key => $rec){
164         if(($rec['type'] == "aRecord") && ($rec['value'] == $this->ipHostNumber)){
165           unset($this->dnsEntry['RECORDS'][$key]);
166         }
167         if(($rec['type'] == "pTRRecord") && ($rec['value'] == $ptr)){
168           unset($this->dnsEntry['RECORDS'][$key]);
169         }
170       }
172       /* Get Record types 
173        */
174       $this->RecordTypes  = DNS::getDnsRecordTypes();
176       /* If there is at least one entry in this -> types, we have DNS enabled 
177        */
178       if($this->dnsEntry['exists']){
179         $this->DNS_is_account = true;
180       }else{
181         $this->DNS_is_account = false;
182       }
183     }
185     /* Create a list of used mac and ip addresses.
187        ! We use this optically huge amount of code to fetch all 
188        Mac and IP addresses, because a simple search for mac and IP
189        over the whole ldap server was 10 to 20 times slower.
190      */
191     $deps  = array();
192     $ou = preg_replace("/,.*$/","",get_ou("systemRDN"));
193     $a_ous = array(get_ou("serverRDN"),
194                   get_ou("terminalRDN"),
195                   get_ou("workstationRDN"),
196                   get_ou("printerRDN"),
197                   get_ou("phoneRDN"),
198                   get_ou("componentRDN"));
199   
200     $ldap = $this->config->get_ldap_link();
201     $ldap->cd($this->config->current['BASE']);
202     $ldap->search("(&(objectClass=organizationalUnit)(".$ou."))",array("dn"));
203     while($attrs = $ldap->fetch()){
204       foreach($a_ous as $allowed){
205         $deps[] = $allowed.$attrs['dn'];
206       }
207     }
209     foreach($deps as $dep){
210       $ldap->cd($dep);
211       $ldap->search("(|(macAddress=*)(ipHostNumber=*))",array("macAddress","ipHostNumber"));
212       while($attrs = $ldap->fetch()){
213         if(isset($attrs['ipHostNumber'][0])){
214           $this->used_ip_mac["ip:".$attrs['ipHostNumber'][0]] = "ip:".$attrs['ipHostNumber'][0];
215         }
216         if(isset($attrs['macAddress'][0])){
217           $this->used_ip_mac["mac:".$attrs['macAddress'][0]] = "mac:".$attrs['macAddress'][0];
218         }
219       } 
220     }
222     /* Save initial ip and mac values, to be able 
223         check if the used values are already in use */ 
224     $this->orig_ipHostNumber   = $this->ipHostNumber;  
225     $this->orig_macAddress     = $this->macAddress;
226  
227     /* Store initally account settings 
228      */
229     $this->initially_was_account = $this->DNS_is_account;
231     if($this->DNS_is_account){
232       new log("view","unknown/".get_class($this),$this->dn);
233     }
234   }
237   function netmaskIsCoherent($idZone) 
238   {
239     $netmask = DNS::FlipIp(str_replace(".in-addr.arpa.","",DNS::getNameFromMix($idZone)));
240     if(!strstr($this->ipHostNumber, $netmask)){
241       return false;
242     }else{
243       return true;
244     }
245   }
248   function getVarsForSaving($attrs) 
249   {
250     foreach($this->attributes as $attr){
251       if(!empty($this->$attr)){
252         $attrs[$attr] = $this->$attr;
253       }
254     }
255     return($attrs); 
256   }
258   function execute()
259   {
260           /* Call parent execute */
261     $smarty= get_smarty();
262     $smarty->assign("autonetACL",$this->acl_is_writeable("macAddress") && $this->acl_is_writeable("ipHostNumber")?"rw":"");
264     $tmp = $this->plInfo();
265     foreach($tmp['plProvidedAcls'] as $name => $translation){
266       $smarty->assign($name."ACL",$this->getacl($name));
267     }
269     $display= "";
271     /**********
272      * Additional ipHostNumber handling 
273      **********/
274       
275     /* Add a new one */
276     if($this->acl_is_writeable("ipHostNumber")){
277       foreach($_POST as $name => $value){
278         if(preg_match("/^additionalHostNumbers_add/",$name)){
279           $this->additionalHostNumbers[] = "";
280           break;
281         }
283         /* Delete given entry */
284         if(preg_match("/^additionalHostNumbers_del_/",$name)){
285           $id = preg_replace("/^^additionalHostNumbers_del_([0-9]*)_.*/","\\1",$name);
286           if(isset($this->additionalHostNumbers[$id])){
287             unset($this->additionalHostNumbers[$id]);
288             $this->additionalHostNumbers = array_values($this->additionalHostNumbers);
289           }
290           break;
291         } 
292       }
293     }
294  
295     $smarty->assign("additionalHostNumbers",$this->additionalHostNumbers);
296     $smarty->assign("staticAddress", ""); 
297  
298     /**********
299      * Autonet completion
300      **********/
301  
302     /* Check for autonet button */
303     if (isset($_POST['autonet']) && ($this->acl_is_writeable("ipHostNumber") || $this->acl_is_writeable("macAddress"))){
304         if(class_available("gosaSupportDaemon")){
305             $d= new gosaSupportDaemon(TRUE, 0.5);
306             $res= $d->_send("<xml><header>gosa_network_completition</header>".
307                     "<source>GOSA</source><target>GOSA</target><hostname>".$this->cn."</hostname></xml>", TRUE);
308             if (isset($res['XML']['IP']) && $this->acl_is_writeable("ipHostNumber")){
309                 $this->ipHostNumber= $res['XML']['IP'];
310             }
311             if (isset($res['XML']['MAC']) && $this->acl_is_writeable("macAddress")){
312                 $this->macAddress= $res['XML']['MAC'];
313             }
314         }
315     }
317   
318     /**********
319      * DHCP Handling
320      **********/
321  
322     if(isset($_POST['dhcpEditOptions']) && $this->acl_is_readable("dhcpSetup")){
323       if(count($this->dhcpHostEntry) == 0){
324         $this->dialog = new dhcpHost($this->parent,$this->dhcpParentNode,TRUE);
325       }else{
326         $this->dialog = new dhcpHost($this->parent,$this->dhcpHostEntry,TRUE);
327       }
328       $this->dialog->cn   = $this->cn;
329       $this->dialog->read_only     = !$this->acl_is_writeable("dhcpSetup");
330       $this->dialog->dhcpHWAddress = "ethernet ".$this->macAddress; 
331       if(!empty($this->ipHostNumber)){
332         $this->dialog->statements->set('fixed-address', $this->ipHostNumber); 
333       }
334     }
336     if(isset($_POST['cancel_dhcp'])){
337       $this->dialog = FALSE; 
338     }
340     if(isset($_POST['save_dhcp']) && $this->acl_is_writeable("dhcpSetup") && is_object($this->dialog)){
341       $this->dialog->save_object();
342       $msgs = $this->dialog->check(array());
343       if(count($msgs)){
344         foreach($msgs as $msg){
345           msg_dialog::display(_("Error"), $msg, ERROR_DIALOG);
346         }
347       }else{
348         $this->dhcpHostEntry = $this->dialog->save();
349         $this->dialog = FALSE; 
350       }
351     }
353     if(is_object($this->dialog)){
354       $this->dialog->save_object();
355       return($this->dialog->execute());
356     }
357  
358     $smarty->assign("dhcpEnabled",    $this->dhcpEnabled && $this->acl_is_readable("dhcpSetup"));
359     $smarty->assign("dhcp_is_Account",$this->dhcp_is_Account);
360     $smarty->assign("dhcpParentNode", $this->dhcpParentNode);
361     $smarty->assign("dhcpParentNodes",$this->dhcpParentNodes);
362     $smarty->assign("dhcpParentNodeCnt",count($this->dhcpParentNodes));
364     /**********
365      * DNS Handling
366      **********/
368     /* There is no dns available
369      */
370     $smarty->assign("DNS_is_account",$this->DNS_is_account);
371     $smarty->assign("DNSenabled",$this->DNSenabled && $this->acl_is_readable("dnsSetup"));
373     if($this->DNSenabled == false){
375       /* Is IP address must ? */
376 #      $smarty->assign("DNS_is_account",false);
377       $smarty->assign("IPisMust",(($this->IPisMust)||($this->DNS_is_account)));
379       /* Assign smarty all non DNs attributes */
380       foreach($this->attributes as $attr){
381         $smarty->assign($attr,$this->$attr);
382       }
383       $smarty->assign("staticAddress","<font class=\"must\">*</font>");
385       $display.= $smarty->fetch(get_template_path('network.tpl', TRUE));
386     }else{
387  #     $smarty->assign("DNS_is_account",true);
389       /* Add new empty array to our record list */
390       if(isset($_POST['AddNewRecord']) && $this->acl_is_writeable("dnsSetup")){
391         $this->dnsEntry['RECORDS'][]  =array("type"=>"aRecord","value"=>"");
392       }
394       /* propose_ip */
395       if(isset($_POST['propose_ip']) && $this->acl_is_writeable("ipHostNumber")){
396         foreach($this->Zones as $key => $name){
397           if($name == $this->dnsEntry['zoneName']){
398             $net = DNS::FlipIp(str_replace(".in-addr.arpa.","",DNS::getNameFromMix($key)));
399             $this->ipHostNumber = $this->generateRandomIP($net);
400           }
401         }
402       }
404       /* Handle all posts */
405       $only_once =true;
406       if($this->acl_is_writeable("dnsSetup")){
407         foreach($_POST as $name => $value){
409           /* Check if we have to delete a record entry */
410           if((preg_match("/RemoveRecord_/",$name))&&($only_once)) {
412             /* Avoid performing this once again */
413             $only_once = false;
415             /* Extract id for specified entry */
416             $id = preg_replace("/RemoveRecord_/","",$name);
417             $id = preg_replace("/_.*$/","",$id);
419             /* Delete this record, mark edited entries to be able to delete them */
420             if(isset($this->dnsEntry['RECORDS'][$id])){
421               unset($this->dnsEntry['RECORDS'][$id]);
422             }
423           }
424         }
425       }
426       /* Assign smarty all non DNs attributes */
427       foreach($this->attributes as $attr){
428         $smarty->assign($attr,$this->$attr);
429       }
431       /* Assign smarty all DNS attributes */
432       foreach($this->DNSattributes as $attr){
433         $smarty->assign($attr,htmlentities($this->dnsEntry[$attr]));
434       }
436       /* Assign all needed vars */
437  #     $smarty->assign("DNSAccount",$this->DNS_is_account);
438       $smarty->assign("hide_dns_check_box",$this->hide_dns_check_box);
439   
440       $smarty->assign("Zones",$this->Zones);
441       $smarty->assign("ZoneCnt",count($this->Zones));
442       $smarty->assign("ZoneKeys",($this->Zones));
443       $smarty->assign("IPisMust",(($this->IPisMust)||($this->DNS_is_account)));
445       /* Create zone array */
446       $idZones = array();
447       foreach($this->Zones as $id => $zone){
448         if($this->netmaskIsCoherent($id)) {
449           $idZones[$id] = $zone;
450         }else{
451           $idZones[$id] = $zone."&nbsp;("._("Not matching").")";
452         }
453       }
454       $smarty->assign("Zones",$idZones);
455       $smarty->assign("ZoneKeys", $this->Zones);
457       $tmp = $this->generateRecordsList();
459       $changeStateForRecords = $tmp['changeStateForRecords'];
461       $smarty->assign("records",$tmp['str']);
462       $smarty->assign("changeStateForRecords",$changeStateForRecords);
463       $smarty->assign("staticAddress","<font class=\"must\">*</font>");
465       $smarty->assign("autonetACL",$this->acl_is_writeable("macAddress") && $this->acl_is_writeable("ipHostNumber")?"rw":"");
467       $display.= $smarty->fetch(get_template_path('network.tpl', TRUE));
468     }
470     return($display);
471   }
474   function remove_from_parent()
475   {
476     if($this->DNS_is_account){
478       $ldap = $this->config->get_ldap_link();
480       $tmp = array();
481       $this->dnsEntry['exists'] = false;
482       $tmp = DNS::getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
483   
484       /* Delete dns */
485       foreach($tmp['del'] as $dn => $del){
486         $ldap->cd($dn);
487         $ldap->rmdir_recursive($dn);
488         new log("remove","unknown/".get_class($this),$dn);
489         if (!$ldap->success()){
490           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_DEL, get_class()));
491         }
492       }
493     }
494   }
497   /* Save data to object */
498   function save_object()
499   {
501     if(isset($_POST['network_tpl_posted'])){
503       /* Save all posted vars */
504       plugin::save_object();
506       /******
507         Additional IP Host Numbers 
508        ******/
510       /* Get posts for all additionally added ipHostNumbers */
511       if($this->acl_is_writeable("ipHostNumber")){
512         foreach($this->additionalHostNumbers as $id => $value){
513           if(isset($_POST['additionalHostNumbers_'.$id])){
514             $this->additionalHostNumbers[$id] = get_post('additionalHostNumbers_'.$id);
515           }
516         } 
517       } 
520       /******
521         DHCP posts
522        ******/
524       if($this->acl_is_writeable("dhcpSetup") && $this->dhcpEnabled && isset($_POST['network_tpl_posted'])){
525         foreach($this->dhcpAttributes as $attr){
526           if(isset($_POST[$attr])){
527             $this->$attr = $_POST[$attr];
528           }
529         }
530         if(isset($_POST['dhcp_is_Account'])){
531           $this->dhcp_is_Account = TRUE;
532         }else{
533           $this->dhcp_is_Account = FALSE;
534         }
535       }
537       /* Ge all non dns attributes (IP/MAC)*/
538       foreach($this->attributes as $attr){
539         if(isset($_POST[$attr]) && $this->acl_is_writeable($attr)){
540           $this->$attr = $_POST[$attr];
541         }
542       }
545       /******
546         DNS posts
547        ******/
549       /* Check if DNS should be enabled / disabled 
550        *  -skip this, if the dns account is enforced.
551        */
552       if(!$this->hide_dns_check_box){
553         if($this->DNS_is_account && $this->acl_is_writeable("dnsSetup") && !isset($_POST['DNS_is_account'])){
554           $this->DNS_is_account = false;
555         }elseif(!$this->DNS_is_account && $this->acl_is_writeable("dnsSetup") && isset($_POST['DNS_is_account'])){
556           $this->DNS_is_account = true;
557         }
558       }
560       /* Get dns attributes */
561       if(($this->DNSenabled) && (isset($_POST['network_tpl_posted'])) && $this->acl_is_writeable("dnsSetup")){
563         /* Check for posted record changes */
564         if(is_array($this->dnsEntry['RECORDS'])){
565           foreach($this->dnsEntry['RECORDS'] as $key => $value){
567             /* Check if type has changed */
568             if(isset($_POST['RecordTypeSelectedFor_'.$key])){
569               $this->dnsEntry['RECORDS'][$key]['type'] = $_POST['RecordTypeSelectedFor_'.$key];
570             }
571             /* Check if value has changed */
572             if(isset($_POST['RecordValue_'.$key])){
573               $this->dnsEntry['RECORDS'][$key]['value'] = get_post('RecordValue_'.$key);
574             }
575           }
576         }
578         /* Get all basic DNS attributes (TTL, Clas ..)*/
579         foreach($this->DNSattributes as $attr){
580           if(isset($_POST[$attr])){
581             $this->dnsEntry[$attr] = get_post($attr);
582           }
583         }
584       }
585       if($this->hide_dns_check_box){
586         $this->DNS_is_account = true;
587       }
588     }
589   }
592   /* Check supplied data */
593   function check()
594   {
595     /* Call common method to give check the hook */
596     $message= plugin::check();
598     /******
599       check additional IP Host Numbers 
600      ******/
602     foreach($this->additionalHostNumbers as $id => $value){
603       if(!tests::is_ip($value)){
604         $message[]= msgPool::invalid(sprintf(_("IP address %s"),($id +2)), "", "", "192.168.1.10");
605       }
606     }
609     /* Check if mac and ip are already used */
610     if(!empty($this->ipHostNumber) && $this->DNS_is_account && 
611         $this->ipHostNumber != $this->orig_ipHostNumber && 
612         in_array("ip:".$this->ipHostNumber,$this->used_ip_mac)){
613       $message[]= msgPool::duplicated(_("IP address"));
614     }
615     if(!empty($this->macAddress) && $this->dhcp_is_Account && 
616         $this->macAddress != $this->orig_macAddress && 
617         in_array("mac:".$this->macAddress,$this->used_ip_mac)){
618       $message[]= msgPool::duplicated(_("MAC address"));
619     }
621     /* Check if ip must be given
622      */  
623     if(($this->IPisMust)||($this->DNS_is_account)){
624       if (empty($this->ipHostNumber)){
625         $message[]= msgPool::required(_("IP address"));
626       }elseif (!tests::is_ip($this->ipHostNumber)){
627         $message[]= msgPool::invalid(_("IP address"), "", "", "192.168.1.10");
628       }
629     }
631     /* Check if mac is empty 
632      */
633     if($this->MACisMust || $this->dhcp_is_Account){
634       if ($this->macAddress == "" ){
635         $message[]= msgPool::required(_("MAC address"));
636       }elseif(!tests::is_mac($this->macAddress)){
637         $message[]= msgPool::invalid(_("MAC address"), "", "", "00:0C:7F:31:33:F1");
638       }
639     }
641     /* only perfrom this checks if this is a valid DNS account */
642     if($this->DNS_is_account){
644       $checkArray = array();
645       $onlyOnce   = array();
647       //  $onlyOnce['cNAMERecord'] = 0;
648        $tmp = array_flip($this->Zones);
649        $tmp2 = $tmp[$this->dnsEntry['zoneName']];
650        if(!$this->netmaskIsCoherent($tmp2)){ //this->dnsEntry['zoneName'])){
651          $tmp2 = preg_replace("/^.*\//","",$tmp2);
652          $message[] =sprintf(_("The IP address '%s' is not part of the selected reverse zone '%s'!"),$this->ipHostNumber,$tmp2);
653        }
655       /* Walk through all entries and detect duplicates or mismatches
656        */  
657       foreach($this->dnsEntry['RECORDS'] as $name => $values){
659         /* Count record values, to detect duplicate entries for a specific record
660          */
661         if(!isset($checkArray[$values['type']][$values['value']])){
662           $checkArray[$values['type']][$values['value']] = 0;
663         }else{
664           $message[] = sprintf(_("Record type '%s' is duplicated!"),$values['type']);
665         }
667         /* Check if given entries in $onlyOnce are used more than once
668          */
669         if(isset($onlyOnce[$values['type']])){
670           $onlyOnce[$values['type']] ++;
671           if($onlyOnce[$values['type']] > 1){
672             $message[] = sprintf(_("Uniq record type '%s' is duplicated!"),$values['type']);
673           }
674         }
676         /* Skip txt record ... 
677          */
678         if($values['type'] == "tXTRecord") continue;
680         /* Check if there is an aRecord defined which uses the same IP as used in IPhostAddress 
681          */
682         if(($values['type'] == "aRecord")&&($values['value'] == $this->ipHostNumber)){
683           #TODO: Where's the problem here?
684           $message[]=sprintf(_("The IP address '%s' will be added as 'A Record', this will be done automatically, please remove the record."), 
685                $this->ipHostNumber);
686         }
688         /* only lower-case is allowed in record entries ... 
689          */
690         if($values['value'] != strtolower($values['value'])){
691           #TODO: What's in values['value']? Something for a propper message?
692           $message[] = sprintf(_("Only lowercase records are allowed, please check your '%ss'."),$values['type']);
693         }
694       }
695     }
696     return ($message);
697   }
700   /* Save to LDAP */
701   function save()
702   {
703     $ldap= $this->config->get_ldap_link();
704   
705     $dn = $this->parent->dn;
706  
707     /*******************/ 
708     /* IP-MAC HANDLING */
709     /*******************/ 
711     /* $dn was posted as parameter */
712     $this->dn = $dn;
713     
714     /* Save DNS setting & ip/Mac*/
715     plugin::save();
717     /* Add all additional ipHostNumbers now 
718      */
719     if(!empty($this->ipHostNumber)){
720       $this->attrs['ipHostNumber'] = array($this->ipHostNumber);
721     }
722     foreach($this->additionalHostNumbers as $value){
723       $this->attrs['ipHostNumber'][] = $value;
724     }
726     /* Do not add the objectClass ipHost if no ip address is given */
727     if(!isset($this->attrs['ipHostNumber'])){
728       $this->attrs['objectClass'] = array_remove_entries(array("ipHost"),$this->attrs['objectClass']);
729     }
731     /* Write back to ldap */
732     $ldap->cd($this->dn);
733     $this->cleanup();
734     $ldap->modify ($this->attrs); 
736     /****************/ 
737     /* DHCP HANDLING */
738     /****************/ 
739   
740     /* New entry */
741     if($this->dhcpEnabled && $this->acl_is_writeable("dhcpSetup")) {
743       if(count($this->dhcpHostEntry) == 0){
744         $this->dialog = new dhcpHost($this->parent,$this->dhcpParentNode,TRUE);
745         $this->dialog->cn = $this->cn;
746         $this->dialog->dhcpHWAddress = "ethernet ".$this->macAddress;
747         if(!empty($this->ipHostNumber)){
748           $this->dialog->statements->set('fixed-address', $this->ipHostNumber);
749         }
750         $this->dialog->execute();
751         $this->dialog->save_object(); 
752         $this->dhcpHostEntry = $this->dialog->save();
753         if(count($this->dhcpHostEntry['dhcpOption']) == 0){
754           $this->dhcpHostEntry['dhcpOption']= array("host-name ".$this->cn);
755         }
756       }else{
758         // Updated Host-Name entry 
759         foreach($this->dhcpHostEntry['dhcpOption'] as $key => $entry){
760           if(preg_match("/^host-name/", $entry)){
761             $this->dhcpHostEntry['dhcpOption'][$key] = "host-name ".$this->cn;
762             break;
763           }
764         }
765       }
767       /* Write mac address to dhcp settings */
768       if($this->dhcp_is_Account){
769         if(!isset($this->dhcpHostEntry['dhcpHWAddress'][0]) || 
770             !preg_match("/ethernet ".$this->macAddress."/",$this->dhcpHostEntry['dhcpHWAddress'][0])){
771           $this->dhcpHostEntry['dhcpHWAddress'] = array("ethernet ".$this->macAddress);
772           $this->dhcpHostEntry['MODIFIED'] = TRUE;
773         }
774       }
776       /* Updated IP host number */
777       if($this->dhcp_is_Account && $this->dhcpHostEntry['dhcpStatements']){
778         foreach($this->dhcpHostEntry['dhcpStatements'] as $id => $value){
779           if(preg_match("/^fixed-address/",$value)){
780             $this->dhcpHostEntry['dhcpStatements'][$id] = "fixed-address ".$this->ipHostNumber; 
781             $this->dhcpHostEntry['MODIFIED'] = TRUE;
782           }
783         }
784       }
786       /* Unset dhcpStatements if this attribute is empty  */
787       if(isset($this->dhcpHostEntry['dhcpStatements']) && 
788           ($this->dhcpHostEntry['dhcpStatements'] == "" || count($this->dhcpHostEntry['dhcpStatements']) == 0) ){
789         unset($this->dhcpHostEntry['dhcpStatements']);
790       }
791   
792       /* DHCP removed */
793       if($this->initial_dhcp_is_Account && !$this->dhcp_is_Account){
794         $ldap->rmdir_recursive($this->dhcpHostEntry['dn']);
795         if (!$ldap->success()){
796           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dhcpHostEntry['dn'], LDAP_DEL, get_class()));
797         }
799         $tmp = new servdhcp($this->config,$this->dhcpParentNode);
800         $tmp->handle_post_events("remove");
801       }
803       /* DHCP Added */
804       if(!$this->initial_dhcp_is_Account && $this->dhcp_is_Account){
805         $attrs = $this->dhcpHostEntry;
806         unset($attrs['MODIFIED']);
807         unset($attrs['dn']);
808         $ldap->cd("cn=".$this->cn.",".$this->dhcpParentNode);
809         $res = $ldap->add($attrs);
811         $tmp = new servdhcp($this->config,$this->dhcpParentNode);
812         $tmp->handle_post_events("add");
814         if (!$ldap->success()){
815           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=".$this->cn.",".$this->dhcpParentNode, LDAP_ADD, get_class()));
816         }
817       }
819       /* DHCP still activated */
820       if($this->initial_dhcp_is_Account && $this->dhcp_is_Account){
822         /* DHCP node changed */
823         if(($this->initial_dhcpParentNode != $this->dhcpParentNode) || 
824            ($this->cn != $this->OrigCn)){
825           $attrs = $this->dhcpHostEntry;
826           $attrs[$this->namingAttr] = $this->cn;
827           unset($attrs['dn']);
828           unset($attrs['MODIFIED']);
829           $ldap->cd("cn=".$this->cn.",".$this->dhcpParentNode);
830           $res = $ldap->add($attrs);
832           $tmp = new servdhcp($this->config,$this->dhcpParentNode);
833           $tmp->handle_post_events("modify");
835           if (!$ldap->success()){
836             msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=".$this->cn.",".$this->dhcpParentNode, LDAP_ADD, get_class()));
837           }
838           if($res){
839             $ldap->rmdir_recursive($this->dhcpHostEntry['dn']);
840             if (!$ldap->success()){
841               msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dhcpHostEntry['dn'], LDAP_DEL, get_class()));
842             }
843           }
844         }
845          
846         /* SAME node but modified */ 
847         if(isset($this->dhcpHostEntry['MODIFIED']) && $this->dhcpHostEntry['MODIFIED'] == 1  && 
848             $this->initial_dhcpParentNode == $this->dhcpParentNode){
849           $attrs = $this->dhcpHostEntry;
850           unset($attrs['dn']);
851           unset($attrs['MODIFIED']);
852           $ldap->cd($this->dhcpHostEntry['dn']);
853           $ldap->modify($attrs);
854           
855           $tmp = new servdhcp($this->config,$this->dhcpParentNode);
856           $tmp->handle_post_events("modify");
858           if (!$ldap->success()){
859             msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dhcpHostEntry['dn'], LDAP_MOD, get_class()));
860           }
861         }    
862       }
863     }
864     $this->dialog = FALSE; 
866     /****************/ 
867     /* DNS HANDLING */
868     /****************/ 
870     /* If isn't DNS account but initially was DNS account 
871        remove all DNS entries 
872      */ 
873     if((!$this->DNSenabled) || ((!$this->DNS_is_account)&&(!$this->initially_was_account))){
874       return;
875     }elseif($this->acl_is_writeable("dnsSetup")){
877       /* Add ipHostNumber to aRecords
878        */
879       $backup_dnsEntry = $this->dnsEntry;
880       if(!empty($this->ipHostNumber)){
881         $this->dnsEntry['RECORDS'][] = array("type"=>"aRecord","value"=>$this->ipHostNumber);
882         $ptr = $this->get_pTRRecord();
883         if(!empty($ptr)){
884           $this->dnsEntry['RECORDS'][] = array("type"=>"pTRRecord","value"=>$ptr);
885         } 
886       }
888       /* Create diff and follow instructions 
889        * If Account was disabled, remove account by setting exists to false
890        */
891       if((!$this->DNS_is_account)&&($this->initially_was_account)){  
892         $this->dnsEntry['exists'] = false;
893         $tmp = DNS::getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
894       }else{
895         $this->dnsEntry['exists'] = $this->DNS_is_account;
896         $tmp = DNS::getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
897       }   
898     
899       /* Update SOA record if needed
900        */
901       $this->updateSOARecord();
903       /* move follwoing entries 
904        */
905       foreach($tmp['move'] as $src => $dst){
906         $this->recursive_move($src,$dst);
907       }
909       /* Delete dns */
910       foreach($tmp['del'] as $dn => $del){
911         $ldap->cd($dn);
912         $ldap->rmdir_recursive($dn);
913         new log("modify","unknown/".get_class($this),$dn,array("*"),$ldap->get_error());
914       }
916       /* Add || Update new DNS entries 
917        */
918       foreach($tmp['add'] as $dn => $attrs){
919         $ldap->cd($dn);
920         $ldap->cat($dn, array('dn'));
921         if(count($ldap->fetch())){
922           $ldap->cd($dn);
923           $ldap->modify ($attrs); 
924         }else{
925           $ldap->cd($dn);
926           $ldap->add($attrs);
927         }
928         new log("modify","unknown/".get_class($this),$dn,array_keys($attrs),$ldap->get_error());
929       }
932       /* Display errors 
933        */
934       if (!$ldap->success()){
935         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, 0, get_class()));
936       }
938       $tmp2 = new servdns($this->config,$this->dn);
939       $tmp2->handle_post_events("modify");
941       $this->dnsEntry =  $backup_dnsEntry;
942     }
943   }
945   /*  Create html table with all used record types
946    */
947   function generateRecordsList()
948   {
949     $changeStateForRecords = "";
950     $str = "<table summary='' width='100%'>";
951     foreach($this->dnsEntry['RECORDS'] as $key => $entry){
953         $changeStateForRecords.= "changeState('RecordTypeSelectedFor_".$key."');\n";
954         $changeStateForRecords.= "changeState('RecordValue_".$key."');\n";
955         $changeStateForRecords.= "changeState('RemoveRecord_".$key."');\n";
957         $str.=" <tr>".
958           "   <td>".$this->generateRecordListBox($entry['type'],"RecordTypeSelectedFor_".$key)."</td>".
959           "   <td><input type='text' value=\"".htmlentities($entry['value'])."\" name='RecordValue_".$key."' id='RecordValue_".$key."'></td>".
960           "   <td><input type='submit' name='RemoveRecord_".$key."' value='"._("Delete")."' id='RemoveRecord_".$key."'></td>".
961           "</tr>";
962     }
964     $str.= "  <tr>".
965            "    <td colspan=2 width='50%'></td><td>".
966            "      <input type='submit' value='"._("Add")."' name='AddNewRecord' id='AddNewRecord'>".
967            "    </td>".
968            "  </tr>".
969            "</table>";
970      $ret =  array("str" => $str, "changeStateForRecords" => $changeStateForRecords);
971   
972     return($ret);
973   }
976   /* Create a html select box which allows us to select different types of records 
977    */
978   function generateRecordListBox($selected,$name)
979   {
980     $str = "<select name='".$name."' id='".$name."'>";
981     foreach($this->RecordTypes as $type => $value){
982       $use = "";
983       if($type == $selected){
984         $use = " selected ";
985       }
986       $str.="\n <option value='".$type."' ".$use.">".strtoupper(preg_replace("/record/i","",$type))."</option>";
987     }
988     $str.="</select>";
989     return($str); 
990   }
993   /* Return plugin informations for acl handling  */ 
994   static function plInfo()
995   {
996     $tmp =  array(
997         "plShortName"   => _("DNS"),
998         "plDescription" => _("DNS settings"),
999         "plSelfModify"  => FALSE,
1000         "plDepends"     => array(),
1001         "plPriority"    => 5,
1002         "plSection"     => array("administration"),
1003         "plCategory"    => array("workstation","terminal","phone","server","component","printer","winworkstation"),
1005         "plProvidedAcls"=> array(
1006           "ipHostNumber"  => _("IP address"),
1007           "macAddress"    => _("MAC address"))
1008         );
1010     /* Hide all dns/dhcp configurations if not available
1011      */
1012     if(class_available("servdns")){
1013       $tmp['plProvidedAcls']["dnsSetup"]    = _("DNS configuration");
1014     }
1015     if(class_available("servdhcp")){
1016       $tmp['plProvidedAcls']["dhcpSetup"]   = _("DHCP configuration");
1017     }
1018     return($tmp);
1019   }
1021   
1022   function get_dhcp_host_entry()
1023   {
1024     $attrs = array();
1025     $dn = $this->get_dhcp_host_entry_dn();
1026     if($dn){
1027       $ldap = $this->config->get_ldap_link();
1028       $ldap->cd($this->config->current['BASE']);
1029       $ldap->cat($dn,array("*"));
1030       if($ldap->count()){
1031         $attrs = $ldap->fetch();
1032         foreach($attrs as $key => $value){
1033           if(is_numeric($key) || ($key == "count")){
1034             unset($attrs[$key]);
1035           }
1036           if(is_array($value) && isset($value['count'])){
1037             unset($attrs[$key]['count']);
1038           }
1039         }
1040       }
1041     }
1042     return($attrs);
1043   }
1046   function get_dhcp_host_entry_dn()
1047   {
1048     $ldap = $this->config->get_ldap_link();
1049     $ldap->cd($this->config->current['BASE']);
1050     $ldap->search ("(&(objectClass=dhcpHost)(cn=".$this->cn."))",array("uid","cn","dn"));
1052     if($ldap->count()){
1053       $attr = $ldap->fetch();
1054       return($attr['dn']);
1055     }else{
1056       return("");
1057     }
1058   }  
1061   function get_dhcp_parent_node()
1062   {
1063     return(preg_replace("/^cn=".preg_quote($this->cn, '/').",/","",$this->get_dhcp_host_entry_dn()));
1064   }
1067   function get_dhcp_parent_nodes()
1068   {
1069     $ldap = $this->config->get_ldap_link();
1070     $ldap->cd($this->config->current['BASE']);
1071     $ldap->search("(objectClass=dhcpService)",array("dhcpPrimaryDN"));
1072     
1073     $dhcp_dns = array();
1074     while($attr = $ldap->fetch()){
1075       $dhcp_dns[$attr['dn']] = $attr['dhcpPrimaryDN'][0];
1076     }
1077  
1078     foreach($dhcp_dns as $key => $pri_dns){
1079       $ldap->cat($pri_dns,array("cn"));
1080       $tmp = $ldap->fetch();
1081       if(isset($tmp['cn'][0])){
1082         $dhcp_dns[$key] = $tmp['cn'][0];
1083       }else{
1084         unset($dhcp_dns[$key]);
1085       }
1086     }
1088     $tmp = $tmp2 = array();
1089     foreach($dhcp_dns as $dn => $cn){
1090       $ldap->cd($dn);
1091       $ldap->search("(|(objectClass=dhcpService)(objectClass=dhcpGroup)".
1092                     "(objectClass=dhcpSubnet)(objectClass=dhcpSharedNetwork))",array("cn"));
1093       while($attr = $ldap->fetch()){
1094         $tmp[$attr['dn']] = $attr['cn'][0];
1095       }
1096       $tmp2 = array_merge($tmp2,$this->create_tree($tmp,preg_replace("/^[^,]+,/i","",$dn),"(".$cn.")&nbsp;"));
1097     }
1098     return($tmp2);
1099   }
1101   
1102   /* this function returns the default ptr record entry */
1103   function get_pTRRecord()
1104   {
1105     if(!empty($this->ipHostNumber) && isset($this->dnsEntry['zoneName']) && !empty($this->dnsEntry['zoneName'])){
1106       $ldap = $this->config->get_ldap_link();
1107       $ldap->cat(DNS::getDNSZoneDN($this->config,$this->dnsEntry['zoneName']));
1108       $attrs = $ldap->fetch();
1109       $tmp = array_flip($this->Zones);
1110       $tmp = preg_replace("/^[^\/]*+\//","",$tmp[$this->dnsEntry['zoneName']]);
1111       $tmp = trim(preg_replace("/\.in-addr.arpa\.$/","",$tmp));
1112       $ptr = preg_replace("/^".preg_quote(DNS::FlipIp($tmp), '/')."\./","",$this->ipHostNumber);
1113       return($ptr);
1114     }else{
1115       return(FALSE);
1116     }
1117   }
1119   
1120   function generateRandomIP($net = "")
1121   {
1122     $str = $net;
1123     $cnt = 4;
1125     // first gather all IPs 
1126     $ldap = $this->config->get_ldap_link();
1127     $ocs = 
1128       "(objectClass=goFonHardware)".
1129       "(objectClass=goServer)".
1130       "(objectClass=GOhard)".
1131       "(objectClass=gotoTerminal)".
1132       "(objectClass=gotoWorkstation)".
1133       "(objectClass=gotoPrinter)".
1134       "(objectClass=ipHost)";
1135     $list = array();
1136     $ldap->search("(&(|{$ocs})(ipHostNumber=*))",array("ipHostNumber"));
1137     while($attrs = $ldap->fetch()){
1138       if (preg_match("/^$net\./", $attrs['ipHostNumber'][0])) {
1139         $list[] = $attrs['ipHostNumber'][0];
1140       }
1141     }
1143     // Set starting ip.
1144     $ip_data = preg_split("/\./",$net);
1145     for($i=0;$i<4;$i++){
1146       if(!isset($ip_data[$i])) $ip_data[$i] = 0;
1147     }
1149     // Search the next free and valid ip.
1150     while(in_array(implode(".",$ip_data),$list) || $ip_data[3] <= 1){
1151       $ip_data[3] ++ ;
1152       if($ip_data[3] > 255){
1153         $ip_data[3] = 1 ;
1154         $ip_data[2] ++ ;
1155       }
1156       if($ip_data[2] > 255){
1157         $ip_data[2] = 1 ;
1158         $ip_data[1] ++ ;
1159       }
1160       if($ip_data[1] > 255){
1161         $ip_data[1] = 1 ;
1162         $ip_data[0] ++ ;
1163       }
1164       if($ip_data[0] > 255) break;
1165     }
1167     return(implode(".",$ip_data));
1168   }
1170   
1171   function create_tree($arr,$base,$current = "")
1172   {
1173     $ret = array();
1174     foreach($arr as $r => $name){
1175       $base_part = str_replace($base,"",$r);
1176       if(preg_match("/^[a-z]*=".preg_quote($name, '/')."(|,)$/i",$base_part)){
1177         $ret[$r] = $current.$name;
1178         $tmp = $this->create_tree($arr,$r,$current.".&nbsp;");
1179         foreach($tmp as $sub_key => $sub_name){
1180           $ret[$sub_key] = $sub_name;
1181         }
1182       } 
1183     }
1184     return($ret);
1185   }
1187   function force_dns()
1188   {
1189     if($this->DNSenabled){
1191       /* Only force DNS account, if we have at least on dns Zone */
1192       if(count($this->Zones)){
1193         $this->DNS_is_account  = TRUE;
1194         $this->hide_dns_check_box = TRUE;
1195       }
1196     }
1197   }
1199   function updateSOARecord()
1200   {
1201     $oldEntries = DNS::getDNSHostEntries($this->config,$this->OrigCn);
1202     $newEntries = $this->dnsEntry;
1203     if(array_differs($newEntries['RECORDS'],$oldEntries['RECORDS'])){
1204       DNS::touchDNSZone($this->config,$this->dnsEntry['zoneName']);
1205     }
1206   }
1209 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1210 ?>